Qt参考文档

初步了解 | 进一步了解 | 最新动态
  • 关于Qt
  • Qt的版本
  • 常见问题解答
  • Window系统特性注释
  • 如何购买Qt
  • 安装
  • 如何学习Qt
  • 教程一， 教程二
  • 实例
  • 循序渐进实例
  • 白皮书
  • Qt 3.0的关键特征
  • 修改历史
  • 从Qt 2.x移植到Qt 3.x
  • 简体中文汉化日志
  • Qt季刊
API参考 | 模块 | 概述
  • 所有的类
  • 主要的类
  • 分组的类
  • 注释的类
  • 继承关系
  • 类表(图像)
  • 所有的函数(很长)
  • 头文件索引

  • PDF格式文档
  • man帮助格式文档
  • 关于模块
  • 画布
  • 图标视图
  • 网络
  • OpenGL
  • SQL
  • 表格
  • 工作区
  • XML
  • 概述与HOWTO
  • Qt对象模型
  • 信号与槽
  • 窗口几何结构
  • 事件和事件过滤器
  • 国际化(i18n)
  • 调试技术
  • Qt中的线程支持
  • Qt插件
  • 窗口部件快照

Trolltech | 工具 | 附录
  • 关于Trolltech公司
  • 如何报告bug
  • 邮件列表信息
  • 所有的工具
  • Qt设计器
  • Qt语言学家
  • Qt助手
  • qmake
  • 标准快捷键
  • Q公共许可证
  • GNU通用公共许可证
  • Qt中使用的其它许可证
  • 鸣谢

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


关于Qt

Qt是一个多平台的C++图形用户界面应用程序框架。它提供给应用程序开发者建立 艺术级的图形用户界面所需的所用功能。Qt是完全面向对象的很容易扩展，并且 允许真正地组件编程。

自从1996年早些时候，Qt进入商业领域，它已经成为全世界范围内数千种成功的应用 程序的基础。Qt也是流行的Linux桌面环境KDE 的基础，KDE是所有主要的Linux发行版的一个标准组件。

Qt支持下述平台：

  • MS/Windows - 95、98、NT 4.0、ME、和2000
  • Unix/X11 - Linux、Sun Solaris、HP-UX、Compaq Tru64 UNIX、IBM AIX、SGI IRIX和其它很多X11平台
  • Macintosh - Mac OS X
  • Embedded - 有帧缓冲(framebuffer)支持的Linux平台。

Qt是Trolltech公司的一个产品。

Qt被按不同的版本发行：

Qt企业版和Qt专业版 提供给商业软件开发。它们提供传统商业软件发行版并且提供免费升级和技术支持服务。 如果要获得最新报价，请浏览Trolltech公司网站的价格和可行性页面，或者与sales@trolltech.com联系。 企业版比专业版多一些扩展模块。

Qt自由版是Qt仅仅为了开发自由和开放源码软件 提供的Unix/X11版本。在Q公共许可证和GNU通用公共许可证 下，它是免费的。最新的版本可以在这里下载。

Qt/嵌入式自由版是Qt为了开发自由软件提供的嵌入式版本。 在GNU通用公共许可证下，它是免费的。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt的版本

Qt专业版和企业版是Qt的商业版本。

Qt自由版是Qt的非商业版本。它可以免费下载。

只有你购买了专业版或企业版，你才能够编写商业的，私人的或收费的软件。 如果你购买了这些商业版本，你也可以获得技术支持和升级服务。Qt为微软 公司的Windows操作系统只提供了专业版和企业版。

专业版/企业版比较表 | 专业版 | 企业版
Qt的基本模块（工具、核心、窗口部件、对话框） 与平台无关的Qt图形用户界面工具包和应用类 | X | X
Qt设计器 可视化的Qt图形用户界面的生成器 | X | X
图标视图模块 几套图形用户交互操作的可视化效果。 | X | X
工作区模块 多文档界面（MDI）支持 | X | X
OpenGL 三维图形模块 在Qt中集成了OpenGL |  | X
网络模块 一些套接字，TCP、FTP和异步DNS查询并且与平台无关的类。 |  | X
画布模块 为可视化效果，图表和其它而优化的二维图形领域。 |  | X
表格模块 灵活的可编辑的表格/电子表格 |  | X
XML模块 通过SAX接口和DOM Level 1很好且已经成形的XML解析器。 |  | X
SQL模块 SQL数据库访问类。 |  | X

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


FAQs

This document describes how to use more than one Qt version on one machine and how to use Qt on X11 without a window manager. In addition it explains the most common source of link errors with Qt.
这个文档描述了如何在一台机器上使用超过一个版本的Qt和如何在X11中使用没有窗口管理器的Qt。 另外，还有使用Qt时的一些最常见的Source链接错误。

Other frequently asked questions can be found in the
其他的常见问题(FAQs)能够在 FAQ index 和 Technical FAQ中发现.

  • Link error, complaining about a lack of \c vtbl, \c _vtbl, \c __vtbl or similar
  • 链接错误，\c vtbl, \c _vtbl, \c __vtbl或者相似问题缺乏的报告。
  • Using different versions of Qt on the same machine
  • 在同一台计算机上使用不同版本的Qt
    • Developers building for a single version of Qt on Unix - Qt binary packages
    • 在Unix上，开发人员为单一的Qt版本构建环境(Building) - Qt二进制包(binary packages)
    • Developers building for two versions of Qt on Unix - Qt sources
    • 在Unix上，开发人员为两个Qt版本构建环境(Building) - Qt源代码(sources)
  • Using Qt on X11 without a window manager
  • 在X11中使用没有窗口管理器的Qt

Link error, complaining about a lack of vtbl, _vtbl, __vtbl or similar

链接错误, vtbl, _vtbl, __vtbl或者相似问题缺乏的报告

This indicates that you've included the Q_OBJECT macro in a class declaration and probably also run the moc, but forgot to link the moc-generated object code into your executable. See Using the Meta Object Compiler for details on how to use moc.

Using different versions of Qt on the same machine

Qt programs need the following components of a Qt distribution:

Header files - Compile time

Programmers need to include the Qt header files. The Qt header files are usually located in the include subdirectory of Qt distributions. Care must be taken to include the header files of the relevant release of Qt. Those with a command-line compiler will typically use options such as /I%QTDIR%\include the relevant release of Qt.

Meta Object Compiler and other tools - Compile time

Programmers need to run moc and other tools such as uic. These tools are usually located in the bin subdirectory of Qt distributions. Either run "$QTDIR"/bin/moc and "$QTDIR"/bin/uic or add "$QTDIR"/bin to your PATH and run moc and uic. If you use qmake the appropriate lines will be added to your Makefiles so that uic and moc will be executed as required.

Static or shared libraries - Link time

Programmers need to link with the Qt static or shared libraries. The Qt libraries are usually located in the lib subdirectory of Qt distributions. Care must be taken to link with the libraries of the relevant release of Qt. Those with a command-line compiler will typically use options such as /L%QTDIR%\lib\qt.lib or -L"$QTDIR"/lib -lqt provided QTDIR specifies the relevant release of Qt.

Shared libraries - Run time

Users of programs linked with shared Qt libraries need these same shared libraries to run these programs. The Qt libraries are usually located in the lib subdirectory of Qt distributions. Shared libraries are made available to programs in places such as C:\windows\system on Windows platforms, directories listed in file /etc/ld.so.conf on Linux, standard lib directories on Unix, or directories listed in environment variables LD_LIBRARY_PATH, SHLIB_PATH, or LIBPATH on various Unix flavours. Make the relevant Qt libraries available using one of these mechanisms.

Qt distributions consist of different files needed at compile time, link time, or run time. Trolltech distributes Qt in the form of a source package that contain all these files once they have been built.

Other vendors distribute Qt in the form of binary packages. Binary packages usually consist of two parts:

  • shared libraries in the run time package, usually called qt3.

  • header files, static libraries, the moc and other tools in the developers' kit, usually called qt3-dev.

Depending on how you are using Qt, you need to make specific parts of the Qt distribution available to your programs. Typical situations are described below.

Developers building for a single version of Qt on Unix - Qt binary packages

You build programs with a single version of Qt, but you still need to run programs linked with another version of Qt. You are typically a Linux developer who builds programs for Qt 3.x on a KDE desktop based on Qt 2.x. Qt packages are usually split into a shared library package with a name like qt and a developer package with a name like qt-dev. You will need the appropriate packages:

  • To build programs you will need the header files, the libraries, the moc and other tools from Qt 3.x. They are included in the developer package of Qt 3.x (qt3-dev or similar).

  • To run programs you will need the shared libraries of Qt 3.x and Qt 2.x. They are included in the regular packages of Qt 3.x (qt3 or similar) and Qt 2.x (qt2 or similar).

Just install the packages, qt2, qt3, and qt3-dev. You may need to set the environment variable QTDIR to point to Qt 3.x.

Developers building for two versions of Qt on Unix - Qt sources

You build and run programs for Qt 2.x and Qt 3.x. You will need:

  • the header files, the libraries, the moc and other tools from Qt 3.x and Qt 2.x to build programs,

  • the shared libraries of Qt 3.x and Qt 2.x to run programs.

Get the source distributions of both Qt 2.x and Qt 3.x.

  1. Install and build Qt 2.x and Qt 3.x, usually in /opt or /usr/local. In the case of /opt:

    $ cd /opt
$ gunzip -c \c qt-x11-2.3.1.tar.gz | tar xf -
$ cd qt-2.3.1
$ setenv QTDIR /opt/qt-2.3.1
$ configure [options]
$ make

$ cd /opt
$ gunzip -c qt-x11-free-3.0.0.tar.gz | tar xf -
$ cd qt-3.0.0
$ setenv QTDIR /opt/qt-3.0.0
$ configure [options]
$ make

  2. Make shared libraries available to programs at run time. Either add both /opt/qt-2.3.1/lib and /opt/qt-3.0.0/lib to your environment variable LD_LIBRARY_PATH or file /etc/ld.so.conf or whataver mechanism you're using, or make links to the libraries in a standard directory like /usr/local/lib:

    cd /usr/local/lib
ln -s /opt/qt-2.3.1/lib/libqt.so.2 .
ln -s /opt/qt-2.3.1/lib/libqt-mt.so.2 .
ln -s /opt/qt-2.3.1/lib/libqutil.so.1 .
ln -s /opt/qt-3.0.0/lib/libqt.so.3 .
ln -s /opt/qt-3.0.0/lib/libqui.so.1 .

To develop with Qt 2.x use:

setenv QTDIR /opt/qt-2.3.1
setenv PATH ${QTDIR}/bin:${PATH}

To develop with Qt 3.x use:

setenv QTDIR /opt/qt-3.0.0
setenv PATH ${QTDIR}/bin:${PATH}

Setting QTDIR ensures that the proper resources are used, such as the documentation appropriate to the version of Qt you're using. Also your Makfiles may refer to "$QTDIR"/include and "$QTDIR"/lib to include the proper header files and link with the proper libraries. Setting the PATH ensures that the proper version of moc and other tools is being used.

Using Qt on X11 without a window manager

When using Qt without a window manager on Unix/X11, you will most likely experience focus problems. Without a window manager, there is no focus handling on X11, and no concept of an active window either. If you want your application to work in such an environment, you have to explicitly mark a window as active after showing it:

 yourWindow->show();
 yourWindow->setActiveWindow();

Note that setActiveWindow() won't work if the widget does not become physically visible during this event cycle. However, without a window manager running, this is guaranteed to happen. For the curious reader: setActiveWindow() emulates a window manager by explicitly setting the X Input Focus to a widget's top level window.

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


Window System-specific Notes

Qt is a multiplatform GUI toolkit, so almost the entire API is the same on all platforms and window systems. If you wish to use platform-specific features, and still maintain a platform-independent source tree, you should protect the platform-specific code using the appropriate #ifdef statements (see below).

For information about which platforms are supported by Qt, see the Platform Notes.

Qt/X11

When compiling for this platform, the macro Q_WS_X11 is defined.

Not documented here. Please contact Trolltech Technical Support if you have queries.

Qt/Windows

When compiling for this platform, the macro Q_WS_WIN is defined.

Not documented here. Please contact Trolltech Technical Support if you have queries.

Qt/MacOSX

When compiling for this platform, the macro Q_WS_MACX is defined.

Not documented here. Please contact Trolltech Technical Support if you have queries.

Qt/Embedded

When compiling for this platform, the macro Q_WS_QWS is defined (the window system is literally the Qt Window System).

  • Installation
  • Qt/Embedded performance tuning
  • Running Qt/Embedded applications
  • Porting your applications to Qt/Embedded
  • Font formats and definitions
  • Character input (keyboard, pen, ...)
  • Pointer handling (mouse, pen, ...)
  • Reduce memory use with the feature definition file
  • A case study embedding on Cassiopeia


如何购买Qt

你可以通过把定购表单打印出来并传真到+47 21 60 48 01来定购Qt企业版和Qt专业版。对于价格，请查看定价和实用性页面。

我们接受如下支付方式：

  • 信用卡（VISA、American Express、Mastercard、JCB）
  • 支票（美国的或者国际的）
  • SWIFT 国际银行转帐（细节请看定购表单）

（因为被信用卡公司的强加限制，我们不能通过网页或者e-mail方式接受信用卡订单，我们必须收到签字的订单表格。）

支票和定购表单也可以使用平信方式邮寄到：

Trolltech AS
Waldemar Thranes gate 98
N-0175 Oslo
NORWAY

有关定购和价格的问题，请通过sales@trolltech.com或者电话+47 21 60 48 00联系我们。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


安装

安装的过程对于不同的Qt平台是不同的：

  • Qt/X11
  • Qt/Windows
  • Qt/Embedded

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


安装Qt/X11

你可能需要root帐号，这取决于你要安装Qt的路径的权限。

  1. 如果你还没有解开压缩包的话，请解开：

        cd /usr/local
    gunzip qt-x11-version.tar.gz    # 对这个包进行解压速
    tar xf qt-x11-version.tar       # 对这个包进行解包

    这样就会创建一个包含主要的包中文件的/usr/local/qt-version目录。

    把qt-version重新命名为qt（或者建立一个链接）：

        mv qt-version qt

    这里假设Qt要被安装到/usr/local/qt路径下。

  2. 在你的主目录下的.profile文件（或者.login文件，取决于你的shell）中设置一些环境变量。如果它们并不存在的话，就创建它们。

    • QTDIR -- 你安装Qt的路径
    • PATH -- 用来定位moc程序和其它Qt工具
    • MANPATH -- 访问Qt man格式帮助文档的路径
    • LD_LIBRARY_PATH -- 共享Qt库的路径

    就像下面这样做：

    在.profile文件（如果你的shell是bash、ksh、zsh或者sh）中，添加下面这些行：

        QTDIR=/usr/local/qt
    PATH=$QTDIR/bin:$PATH
    MANPATH=$QTDIR/man:$MANPATH
    LD_LIBRARY_PATH=$QTDIR/lib:$LD_LIBRARY_PATH

    export QTDIR PATH MANPATH LD_LIBRARY_PATH

    在.login文件（如果你的shell是csh或者tcsh的情况下），添加下面这些行：

        setenv QTDIR /usr/local/qt
    setenv PATH $QTDIR/bin:$PATH
    setenv MANPATH $QTDIR/man:$MANPATH
    setenv LD_LIBRARY_PATH $QTDIR/lib:$LD_LIBRARY_PATH

    做完这些之后，你需要重新登录，或者在继续工作之前重新指定你的配置文件，这样至少$QTDIR被设置了。否则的话安装程序就会给出一个错误信息并且不再进行下去了。

  3. 安装你的许可证文件。对于自由版本，你不需要一个许可证文件。对于专业版和企业版，你就需要安装一个和你的发行版一致的许可证文件。

  4. 编译Qt库，并且连编实例程序、教程和工具（比如Qt设计器），就像下面这样。

    输入：

        ./configure

    这样的话就为你的机器配置Qt库。注意在默认条件下GIF文件支持选项是关闭的。运行./configure -help就会得到配置选项的一个列表。阅读PLATFORMS文件能够得到被支持的平台的列表。

    生成库和编译所有的例程和教程：

        make
    如果你有问题，请看http://www.trolltech.com/platforms/。

  5. 在很少的情况下，如果你使用了共享库，在这个地方你也许需要运行/sbin/ldconfig或者其它相似的东西。

    如果你在运行实例程序的时候遇到问题，比如消息如下

        can't load library 'libqt.so.2'
    你也许需要在配置文件中给定一个qt库的定位，并且以root的身份在你的系统中运行/sbin/ldconfig。并且你不要忘记了在上面的第二步中提到的设置一个LD_LIBRARY_PATH环境变量。

  6. 在线的HTML文档被安装到了/usr/local/qt/doc/html/，主页面是/usr/local/qt/doc/html/index.html。man帮助文档被安装到了/usr/local/qt/doc/man/。

你已经做完了。Qt已经安装完毕。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


安装Qt/Windows

Qt/Windows发行版是一个包含内置安装程序的自解压包。只要跟着安装向导进行就可以了。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


安装Qt/Embedded

Installing Qt/Embedded

This installation procedure is written for Linux. It may need to be modified for other platforms.
这个安装过程是为Linux写的，如果是其他平台这个过程需要修改。

    Unpack the archive if you have not done so already
  1. 假如你没有准备好的话，解包档案文件。

        cd <anywhere>;
    gunzip qt-embedded-VERSION-commercial.tar.gz    # uncompress the archive
    tar xf qt-embedded-VERSION-commercial.tar       # unpack it
    Replace VERSION with the Qt/Embedded version number throughout.
     使用Qt/Embedded的完整版本号替换上面的"VERSION"。
    This document assumes that the archive is installed as ~/qt-VERSION.
    这个文档默认Qt被安装在~/qt-VERSION.
    Compile the Qt/Embedded library and examples.
  2. 编译Qt/Embedded库和例程

        cd ~/qt-VERSION
    export QTDIR=~/qt-VERSION
    ./configure
    make
    The configuration system is designed to allow platform-specific options to be added, but in general all Linux system which have framebuffer support can use the "linux-generic-g++" platform. The configuration system also supports cross-compilers: to build on Linux/x86 for the Linux/MIPSEL target, you would use:

    这个配置系统(configuration system)是被设计为允许添加平台指定的选项的， 但是在普通的有架构缓存(framebuffer)支持的Linux系统能使用"linux-generic-g++"平台。 这个配置系统(configuration system)也支持交叉编译器为Linux/x86上的Linux/MIPSEL目标构建，你需要使用下面的命令：

        ./configure -platform linux-x86-g++ -xplatform linux-mips-g++
    Only a small number of configurations are predefined, all much the same. Configurations files are found in configs/.

    配置中仅有一小部分被预定义了，绝大部分相同，配置文件可以在configs/中被发现。

    Enable framebuffer support.

  3. 使架构缓存(framebuffer)支持有效

    You may need to recompile your kernel to enable the framebuffer. This document does not describe how to do this; the HOWTO-Framebuffer page contains a short description. (You should see a penguin logo at boot time when the frame buffer is enabled.)
    为了使架构缓存(framebuffer)支持有效你需要重新编译核(Kernel)。 这个文档没有描述如何做，在HOWTO-Framebuffer page中有一个简短记述。 (如果架构缓存(framebuffer)是有效的，在系统启动时你应该能够看到企鹅标志)。

      For Matrox G100/G200/G400 use the matrox frame buffer driver.
      For NVidia TNT cards use the nvidia frame buffer driver.
      For Mach64 and most other cards, use the vesafb driver.
    • Matrox G100/G200/G400使用的是matrox frame buffer驱动
    • NVidia TNT卡使用的是nvidia frame buffer驱动
    • Mach64和其他大多数卡使用的是vesafb驱动

    Note that some cards are only supported in VGA16 mode, this will not work with the current version of Qt/Embedded, since VGA/16 is not yet supported. You may need to upgrade your kernel, or even switch to an experimental kernel.

    注意有一些卡仅在VGA16模式的情况下才被支持，自从VGA/16不再被支持，当前版本的Qt/Embedded有可能将不能够工作， 你需要更新核或者转化到经过验证的核(experimental kernel)。

    The frame buffer must also be enabled with a boot parameter. See /usr/src/linux/Documentation/fb for details.
    架构缓存必须在启动时被设置成有效，更详细的内容请看/usr/src/linux/Documentation/fb

    The fbset program, which should be included in Linux distributions, may be used to switch video modes without rebooting the system. The video mode active when the server is started will be used. (8-bit modes are still experimental.) Note: fbset does not work with the vesafb driver.

  4. Change permissions.
    改变权限

    To run Qt/Embedded, you need write access to the framebuffer device /dev/fb0.
    You also need read access to the mouse device. (Note that /dev/mouse is normally a symbolic link; the actual mouse device must be readable.)
    为了运行Qt/Embedded,你需要架构缓存/dev/fb0的写权限，你也需要鼠标驱动/dev/fb0的读取访问权限 (注意/dev/mouse是一个普通的链接符号，实际的鼠标驱动必须是可读的)。

  5. How to run the demonstration program.
    如何运行例子程序

    Log into a virtual console and do:
    登陆到虚拟控制台然后执行如下命令：

        cd ~/qt-VERSION/
    ./start-demo

  6. Miscellaneous troubleshooting and known bugs.
    各种问题和已知的Bug

    To kill gpm, run the following command as root:
    杀死gpm，使用root用户运行如下名令:

        gpm -k

    In some cases, if the server does not work, it will work when run as root.
    因为某些原因，假如服务没有运行，用root用户登陆使它运行。

    Some example programs may not compile with GCC 2.95.
    一些例程不能使用GCC 2.95进行编译。

    Show processes using the framebuffer:
    显示架构缓存(framebuffer)的进程(processes):

        fuser -v /dev/fb0

    Kill such processes:
    杀死这样的进程

        fuser -vk /dev/fb0
    or harsher:
    或者更严格:
        fuser -k -KILL /dev/fb0

    Show existing semaphores:
    显示已经存在的信号:

        ipcs

    Remove semaphores:
    删除信号:

        ipcrm

    The communication between client and server is done through the named pipe /tmp/.QtEmbedded; sometimes it may need to be deleted (eg. if you run Qt/Embedded as root then later as an unprivileged user).
    客户端和服务器进行沟通是通过名字管道(named pipe)/tmp/.QtEmbedded进行的;有些时候，它是需要被删除的 例如：假如你首先以root权限运行Qt/Embedded，而以后是用没有特权的帐户运行它。

  7. Customization.
    客户化

    The Qt/Embedded library can be reduced in size by removing unnecessary features.
    可以通过删除一些不必要的特征来减少Qt/Embedded库的大小。


如何学习Qt

我们假设你已经熟悉C++了！

请先阅读一下Qt白皮书。它包含一个关于Qt软件的概述，并且提供了一些用来示范使用Qt进行编程的代码的片断。它会给你一个“大的图画”。

如果你想要完全的在C++中进行编程，不使用任何设计工具的帮助下在代码中设计你的界面，请阅读教程。教程1就是被设计成把你带入Qt编程的一个教程，它更强调的是编写代码而不是一个特征的漫游。教程2是一个更加真实的例子，示范了如何编写菜单、工具条、文件的载入和保存、对话框等地那个。

如果你想使用一个设计工具来设计你的用户界面，那么你至少要先阅读Qt设计器手册的前几章。在这之后，学习一下上面提到的纯粹的C++教程（教程1和教程2）还是很值得的。

到现在为止，如果你已经完成了一些小的可以工作的应用程序并且对Qt编程有了一个主要的了解。你可以直接开始你自己的项目了，但我们建议你阅读一些关键的概述来加深你对Qt的理解：对象模型和信号和槽。

在这里我们建议你看一下概述并且阅读一些和你的项目相关的文章。你也许会发现浏览和你项目做相同事情的实例的源代码是非常有用的。你也可以阅读Qt的源代码，因为它们也被提供。

如果你运行demo这个应用程序（在$QTDIR/examples/demo），你就会看到很多运转中的Qt窗口部件

Qt提供了广泛的文档，完全前后参考的超文本，所以你可以很容易地按你喜欢的方式进行点击。在文档中，你最经常使用的部分可能就是API参考。每一个链接都提供了一个不同的方式来导航API参考，全都试试，看哪一个更适合你。

你现在应该已经准备好你的伟大工程：祝你好运，玩得开心！

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 共十四步

这个教程介绍了使用Qt工具包进行图形用户界面编程。它没有包括所有的东西：强调的是教授一种图形用户界面编程的编程思想，并且介绍Qt的特征也是必需的。一些通常情况下使用的特征在这个教程里没有用到。

第一章开始讲述一个十行的Hello World程序并且后来的每一章都介绍了一个或几个更多的概念。一直到第十四章，程序已经从第一章的十行变成了六百五十行的游戏。

如果你对Qt完全不熟悉，如果你还没有读过如何学习Qt的话，请读一下。

教程章节：

  1. Hello, World!
  2. 调用退出
  3. 家庭价值
  4. 使用窗口部件
  5. 组装积木
  6. 组装丰富的积木！
  7. 一个事物领导另一个
  8. 准备战斗
  9. 你可以使用加农炮了
  10. 像丝一样滑
  11. 给它一个炮弹
  12. 悬在空中的砖
  13. 游戏结束
  14. 面对墙壁

这个小游戏看起来不像一个现代的图形用户界面应用程序。它只使用了有用的少数图形用户界面技术，但是如果你通过它工作之后，我们建议你阅读一下教程二。第二个教程更加正式一些，并且覆盖了包括菜单条、工具条、文件的载入和保存、对话框等典型应用程序的特征。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第一章：Hello, World!

Screenshot of tutorial one

第一个程序是一个简单的Hello World例子。它只包含你建立和运行Qt应用程序所需要的最少的代码。上面的图片是这个程序的快照。

/****************************************************************
**
** Qt教程一 - 2
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>

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

    QPushButton hello( "Hello world!", 0 );
    hello.resize( 100, 30 );

    a.setMainWidget( &hello );
    hello.show();
    return a.exec();
}

一行一行地解说

    #include <qapplication.h>

这一行包含了QApplication类的定义。在每一个使用Qt的应用程序中都必须使用一个QApplication对象。QApplication管理了各种各样的应用程序的广泛资源，比如默认的字体和光标。

    #include <qpushbutton.h>

这一行包含了QPushButton类的定义。参考文档的文件的最上部分提到了使用哪个类就必须包含哪个头文件的说明。

QPushButton是一个经典的图形用户界面按钮，用户可以按下去，也可以放开。它管理自己的观感，就像其它每一个QWidget。一个窗口部件就是一个可以处理用户输入和绘制图形的用户界面对象。程序员可以改变它的全部观感和它的许多主要的属性（比如颜色），还有这个窗口部件的内容。一个QPushButton可以显示一段文本或者一个QPixmap。

    int main( int argc, char **argv )
    {

main()函数是程序的入口。几乎在使用Qt的所有情况下，main()只需要在把控制转交给Qt库之前执行一些初始化，然后Qt库通过事件来向程序告知用户的行为。

argc是命令行变量的数量，argv是命令行变量的数组。这是一个C/C++特征。它不是Qt专有的，无论如何Qt需要处理这些变量（请看下面）。

        QApplication a( argc, argv );

a是这个程序的QApplication。它在这里被创建并且处理这些命令行变量（比如在X窗口下的-display）。请注意，所有被Qt识别的命令行参数都会从argv中被移除（并且argc也因此而减少）。关于细节请看QApplication::argv()文档。

注意：在任何Qt的窗口系统部件被使用之前创建QApplication对象是必须的。

        QPushButton hello( "Hello world!", 0 );

这里，在QApplication之后，接着的是第一个窗口系统代码：一个按钮被创建了。

这个按钮被设置成显示“Hello world!”并且它自己构成了一个窗口（因为在构造函数指定0为它的父窗口，在这个父窗口中按钮被定位）。

        hello.resize( 100, 30 );

这个按酒被设置成100像素宽，30像素高（加上窗口系统边框）。在这种情况下，我们不用考虑按钮的位置，并且我们接受默认值。

        a.setMainWidget( &hello );

这个按钮被选为这个应用程序的主窗口部件。如果用户关闭了主窗口部件，应用程序就退出了。

你不用必须设置一个主窗口部件，但绝大多数程序都有一个。

        hello.show();

当你创建一个窗口部件的时候，它是不可见的。你必须调用show()来使它变为可见的。

        return a.exec();

这里就是main()把控制转交给Qt，并且当应用程序退出的时候exec()就会返回。

在exec()中，Qt接受并处理用户和系统的事件并且把它们传递给适当的窗口部件。

    }

你现在可以试着编译和运行这个程序了。

编译

编译一个C++应用程序，你需要创建一个makefile。创建一个Qt的makefile的最容易的方法是使用Qt提供的连编工具qmake。如果你已经把main.cpp保存到它自己的目录了，你所要做的就是这些：

qmake -project
qmake

第一个命令调用qmake来生成一个.pro（项目）文件。第二个命令根据这个项目文件来生成一个（系统相关的）makefile。你现在可以输入make（或者nmake，如果你使用Visual Studio），然后运行你的第一个Qt应用程序！

行为

当你运行它的时候，你就会看到一个被单一按钮充满的小窗口，在它上面你可以读到著名的词：Hellow World!

练习

试着改变窗口的大小。按下按钮。如果你在X窗口下运行，使用-geometry选项（比如，-geometry 100x200+10+20）来运行这个程序。

现在你可以进行第二章了。

[下一章] [教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第二章：调用退出

Screenshot of tutorial two

你已经在第一章中创建了一个窗口，我们现在使这个应用程序在用户让它退出的时候退出。

我们也会使用一个比默认字体更好的一个字体。

/****************************************************************
**
** Qt教程一 - 2
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qfont.h>

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

    QPushButton quit( "Quit", 0 );
    quit.resize( 75, 30 );
    quit.setFont( QFont( "Times", 18, QFont::Bold ) );

    QObject::connect( &quit, SIGNAL(clicked()), &a, SLOT(quit()) );

    a.setMainWidget( &quit );
    quit.show();
    return a.exec();
}

一行一行地解说

    #include <qfont.h>

因为这个程序使用了QFont，所以它需要包含qfont.h。Qt的字体提取和X中提供的可怕的字体提取大为不同，字体的载入和使用都已经被高度优化了。

        QPushButton quit( "Quit", 0 );

这时，按钮显示“Quit”，确切的说这就是当用户点击这个按钮时程序所要做的。这不是一个巧合。因为这个按钮是一个顶层窗口，我们还是把0作为它的父对象。

        quit.resize( 75, 30 );

我们给这个按钮选择了另外一个大小，因为这个文本比“Hello world!”小一些。我们也可以使用QFontMetrics来设置正确的大小。

        quit.setFont( QFont( "Times", 18, QFont::Bold ) );

这里我们给这个按钮选择了一个新字体，Times字体中的18点加粗字体。注意在这里我们调用了这个字体。

你也可以改变整个应用程序的默认字体（使用QApplication::setFont()）。

        QObject::connect( &quit, SIGNAL(clicked()), &a, SLOT(quit()) );

connect也许是Qt中最重要的特征了。注意connect()是QObject中的一个静态函数。不要把这个函数和socket库中的connect()搞混了。

这一行在两个Qt对象（直接或间接继承QObject对象的对象）中建立了一种单向的连接。每一个Qt对象都有signals（发送消息）和slots（接收消息）。所有窗口部件都是Qt对象。它们继承QWidget，而QWidget继承QObject。

这里quit的clicked()信号和a的quit()槽连接起来了，所以当这个按钮被按下的时候，这个程序就退出了。

信号和槽文档详细描述了这一主题。

行为

当你运行这个程序的时候，你会看到这个窗口比第一章中的那个小一些，并且被一个更小的按钮充满。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

试着改变窗口的大小。按下按钮。注意！connect()看起来会有一些不同。

是不是在QPushButton中还有其它的你可以连接到quit的信号？提示：QPushButton继承了QButton的绝大多数行为。

现在你可以进行第三章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第三章：家庭价值

Screenshot of tutorial three

这个例子演示了如何创建一个父窗口部件和子窗口部件。

我们将会保持这个程序的简单性，并且只使用一个单一的父窗口部件和一个独立的子窗口部件。

/****************************************************************
**
** Qt教程一 - 3
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qfont.h>
#include <qvbox.h>

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

    QVBox box;
    box.resize( 200, 120 );

    QPushButton quit( "Quit", &box );
    quit.setFont( QFont( "Times", 18, QFont::Bold ) );

    QObject::connect( &quit, SIGNAL(clicked()), &a, SLOT(quit()) );

    a.setMainWidget( &box );
    box.show();

    return a.exec();
}

一行一行地解说

    #include <qvbox.h>

我们添加了一个头文件qvbox.h用来获得我们要使用的布局类。

        QVBox box;

这里我们简单地创建了一个垂直的盒子容器。QVBox把它的子窗口部件排成一个垂直的行，一个在其它的上面，根据每一个子窗口部件的QWidget::sizePolicy()来安排空间。

        box.resize( 200, 120 );

我们它的高设置为120像素，宽为200像素。

        QPushButton quit( "Quit", &box );

子窗口部件产生了。

QPushButton通过一个文本（“text”）和一个父窗口部件（box）生成的。子窗口部件总是放在它的父窗口部件的最顶端。当它被显示的时候，它被父窗口部件的边界挡住了一部分。

父窗口部件，QVBox，自动地把这个子窗口部件添加到它的盒子中央。因为没有其它的东西被添加了，这个按钮就获得了父窗口部件的所有空间。

        box.show();

当父窗口部件被显示的时候，它会调用所有子窗口部件的显示函数（除非在这些子窗口部件中你已经明确地使用QWidget::hide()）。

行为

这个按钮不再充满整个窗口部件。相反，它获得了一个“自然的”大小。这是因为现在的这个新的顶层窗口，使用了按钮的大小提示和大小变化策略来设置这个按钮的大小和位置。（请看QWidget::sizeHint()和QWidget::setSizePolicy()来获得关于这几个函数的更详细的信息。）

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

试着改变窗口的大小。按钮是如何变化的？按钮的大小变化策略是什么？如果你运行这个程序的时候使用了一个大一些的字体，按钮的高度发生了什么变化？如果你试图让这个窗口真的变小，发生了什么？

现在你可以进行第四章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第四章：使用窗口部件

Screenshot of tutorial four

这个例子显示了如何创建一个你自己的窗口部件，描述如何控制一个窗口部件的最小大小和最大大小，并且介绍了窗口部件的名称。

/****************************************************************
**
** Qt教程一 - 4
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qfont.h>

class MyWidget : public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    setMinimumSize( 200, 120 );
    setMaximumSize( 200, 120 );

    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setGeometry( 62, 40, 75, 30 );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
}

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

    MyWidget w;
    w.setGeometry( 100, 100, 200, 120 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}

一行一行地解说

    class MyWidget : public QWidget
    {
    public:
        MyWidget( QWidget *parent=0, const char *name=0 );
    };

这里我们创建了一个新类。因为这个类继承了QWidget，所以新类是一个窗口部件，并且可以最为一个顶层窗口或者子窗口部件（像第三章里面的按钮）。

这个类只有一个成员函数，构造函数（加上从QWidget继承来的成员函数）。这个构造函数是一个标准的Qt窗口部件构造函数，当你创建窗口部件时，你应该总是包含一个相似的构造函数。

第一个参数是它的父窗口部件。为了生成一个顶层窗口，你指定一个空指针作为父窗口部件。就像你看到的那样，这个窗口部件默认地被认做是一个顶层窗口。

第二个参数是这个窗口部件的名称。这个不是显示在窗口标题栏或者按钮上的文本。这只是分配给窗口部件的一个名称，以后可以用来查找这个窗口部件，并且这里还有一个方便的调试功能可以完整地列出窗口部件层次。

    MyWidget::MyWidget( QWidget *parent, const char *name )
            : QWidget( parent, name )

构造函数的实现从这里开始。像大多数窗口部件一样，它把parent和name传递给了QWidget的构造函数。

    {
        setMinimumSize( 200, 120 );
        setMaximumSize( 200, 120 );

因为这个窗口部件不知道如何处理重新定义大小，我们把它的最小大小和最大大小设置为相等的值，这样我们就确定了它的大小。在下一章，我们将演示窗口部件如何响应用户的重新定义大小事件。

        QPushButton *quit = new QPushButton( "Quit", this, "quit" );
        quit->setGeometry( 62, 40, 75, 30 );
        quit->setFont( QFont( "Times", 18, QFont::Bold ) );

这里我们创建并设置了这个窗口部件的一个名称为“quit”的子窗口部件（新窗口部件的父窗口部件是this）。这个窗口部件名称和按钮文本没有关系，只是在这一情况下碰巧相似。

注意quit是这个构造函数中的局部变量。MyWidget不能跟踪它，但Qt可以，当MyWidget被删除的时候，默认地它也会被删除。这就是为什么MyWidget不需要一个析构函数的原因。（另外一方面，如果你选择删除一个子窗口部件，也没什么坏处，这个子窗口部件会自动告诉Qt它即将死亡。）

setGeometry()调用和上一章的move()和resize()是一样的。

        connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
    }

因为MyWidget类不知道这个应用程序对象，它不得不连接到Qt的指针，qApp。

一个窗口部件就是一个软件组件并且它应该尽量少地知道关于它的环境，因为它应该尽可能的通用和可重用。

知道了应用程序的名称将会打破上述原则，所以在一个组件，比如MyWidget，需要和应用程序对象对话的这种情况下，Qt提供了一个别名，qApp。

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

        MyWidget w;
        w.setGeometry( 100, 100, 200, 120 );
        a.setMainWidget( &w );
        w.show();
        return a.exec();
    }

这里我们举例说明了我们的新子窗口部件，把它设置为主窗口部件，并且执行这个应用程序。

行为

这个程序和上一章的在行为上非常相似。不同点是我们实现的方式。无论如何它的行为还是有一些小差别。试试改变它的大小，你会看到什么？

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

试着在main()中创建另一个MyWidget对象。发生了什么？

试着添加更多的按钮或者把除了QPushButton之外的东西放到窗口部件中。

现在你可以进行第五章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第五章：组装积木

Screenshot of tutorial five

这个例子显示了创建几个窗口部件并用信号和槽把它们连接起来，和如何处理重新定义大小事件。

/****************************************************************
**
** Qt教程一 - 5
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qslider.h>
#include <qlcdnumber.h>
#include <qfont.h>

#include <qvbox.h>

class MyWidget : public QVBox
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd" );

    QSlider * slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );

    connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)) );
}

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

    MyWidget w;
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}

一行一行地解说

    #include <qapplication.h>
    #include <qpushbutton.h>
    #include <qslider.h>
    #include <qlcdnumber.h>
    #include <qfont.h>

    #include <qvbox.h>

这里显示的是三个新的被包含的头文件。qslider.h和qlcdnumber.h在这里是因为我们使用了两个新的窗口部件，QSlider和QLCDNumber。qvbox.h在这里是因为我们使用了Qt的自动布局支持。

    class MyWidget : public QVBox
    {
    public:
        MyWidget( QWidget *parent=0, const char *name=0 );
    };

    MyWidget::MyWidget( QWidget *parent, const char *name )
            : QVBox( parent, name )
    {

MyWidget现在继承了QVBox，而不是QWidget。我们通过这种方式来使用QVBox的布局（它可以把它的子窗口部件垂直地放在自己里面）。重新定义大小自动地被QVBox处理，因此现在也就被MyWidget处理了。

        QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd" );

lcd是一个QLCDNumber，一个可以按像LCD的方式显示数字的窗口部件。这个实例被设置为显示两个数字，并且是this的子窗口部件。它被命名为“lcd”。

        QSlider * slider = new QSlider( Horizontal, this, "slider" );
        slider->setRange( 0, 99 );
        slider->setValue( 0 );

QSlider是一个经典的滑块，用户可以通过在拖动一个东西在一定范围内调节一个整数数值的方式来使用这个窗口部件。这里我们创建了一个水平的滑块，设置它的范围是0~99（包括0和99，参见QSlider::setRange()文档）并且它的初始值是0。

        connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)) );

这里我们是用了信号/槽机制把滑块的valueChanged()信号和LCD数字的display()槽连接起来了。

无论什么时候滑块的值发生了变化，它都会通过发射valueChanged()信号来广播这个新的值。因为这个信号已经和LCD数字的display()槽连接起来了，当信号被广播的时候，这个槽就被调用了。这两个对象中的任何一个都不知道对方。这就是组件编程的本质。

槽是和普通C++成员函数的方式不同，但有着普通C++成员函数的方位规则。

行为

LCD数字反应了你对滑块做的一切，并且这个窗口部件很好地处理了重新定义大小事件。注意当窗口被重新定义大小（因为它可以）的时候，LDC数字窗口部件也改变了大小，但是其它的还是和原来一样（因为如果它们变化了，看起来好像很傻）。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

试着改变LCD数字，添加更多的数字或者改变模式。你甚至可以添加四个按钮来设置基数。

你也可以改变滑块的范围。

也许使用QSpinBox比滑块更好？

试着当LCD数字溢出的时候使这个应用程序退出。

现在你可以进行第六章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第六章：组装丰富的积木！

Screenshot of tutorial six

这个例子显示了如何把两个窗口部件封装成一个新的组件和使用许多窗口部件是多么的容易。首先，我们使用一个自定义的窗口部件作为一个子窗口部件。

/****************************************************************
**
** Qt教程一 - 6
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qslider.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qvbox.h>
#include <qgrid.h>

class LCDRange : public QVBox
{
public:
    LCDRange( QWidget *parent=0, const char *name=0 );
};

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    QSlider * slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)) );
}

class MyWidget : public QVBox
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    QGrid *grid = new QGrid( 4, this );

    for( int r = 0 ; r < 4 ; r++ )
        for( int c = 0 ; c < 4 ; c++ )
            (void)new LCDRange( grid );
}

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

    MyWidget w;
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}

一行一行地解说

    class LCDRange : public QVBox
    {
    public:
        LCDRange( QWidget *parent=0, const char *name=0 );
    };

LCDRange窗口部件是一个没有任何API的窗口部件。它只有一个构造函数。这种窗口部件不是很有用，所以我们一会儿会加入一些API。

    LCDRange::LCDRange( QWidget *parent, const char *name )
            : QVBox( parent, name )
    {
        QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
        QSlider * slider = new QSlider( Horizontal, this, "slider" );
        slider->setRange( 0, 99 );
        slider->setValue( 0 );
        connect( slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)) );
    }

这里直接利用了第五章里面的MyWidget的构造函数。唯一的不同是按钮被省略了并且这个类被重新命名了。

    class MyWidget : public QVBox
    {
    public:
        MyWidget( QWidget *parent=0, const char *name=0 );
    };

MyWidget也是除了一个构造函数之外没有包含任何API。

    MyWidget::MyWidget( QWidget *parent, const char *name )
            : QVBox( parent, name )
    {
        QPushButton *quit = new QPushButton( "Quit", this, "quit" );
        quit->setFont( QFont( "Times", 18, QFont::Bold ) );

        connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

这个按钮被放在LCDRange中，这样我们就有了一个“Quit”按钮和许多LCDRange对象。

        QGrid *grid = new QGrid( 4, this );

我们创建了一个四列的QGrid对象。这个QGrid窗口部件可以自动地把自己地子窗口部件排列到行列中，你可以指定行和列的数量，并且QGrid可以发现它的新子窗口部件并且把它们安放到网格中。

        for( int r = 0 ; r < 4 ; r++ )
            for( int c = 0 ; c < 4 ; c++ )
                (void)new LCDRange( grid );

四行，四列。

我们创建了一个4*4个LCDRanges，所有这些都是这个grid对象的子窗口部件。这个QGrid窗口部件会安排它们。

    }

这就是全部了。

行为

这个程序显示了在同一时间使用许多窗口部件是多么的容易。其中的滑块和LCD数字的行为在前一章已经提到过了。还有就是，就是实现的不同。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

在开始的时候使用不同的或者随机的值初始化每个滑块。

源代码中的“4”出现了3次。如果你改变QGrid构造函数中调用的那个，会发生什么？改变另外两个又会发生什么呢？为什么呢？

现在你可以进行第七章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第七章：一个事物领导另一个

Screenshot of tutorial seven

这个例子显示了如何使用信号和槽来创建自定义窗口部件，和如何使用更加复杂的方式把它们连接起来。首先，源文件被我们分成几部分并放在放在t7目录下。

  • t7/lcdrange.h包含LCDRange类定义。
  • t7/lcdrange.cpp包含LCDRange类实现。
  • t7/main.cpp包含MyWidget和main。

一行一行地解说

t7/lcdrange.h

这个文件主要利用了第六章的main.cpp，在这里只是说明一下改变了哪些。

    #ifndef LCDRANGE_H
    #define LCDRANGE_H

这里是一个经典的C语句，为了避免出现一个头文件被包含不止一次的情况。如果你没有使用过它，这是开发中的一个很好的习惯。#ifndef需要把这个头文件的全部都包含进去。

    #include <qvbox.h>

qvbox.h被包含了。LCDRange继承了QVBox，所以父类的头文件必须被包含。我们在前几章里面偷了一点懒，我们通过包含其它一些头文件，比如qpushbutton.h，这样就可以间接地包含qwidget.h。

    class QSlider;

这里是另外一个小伎俩，但是没有前一个用的多。因为我们在类的界面中不需要QSlider，仅仅是在实现中，我们在头文件中使用一个前置的类声明，并且在.cpp文件中包含一个QSlider的头文件。

这会使编译一个大的项目变得更快，因为当一个头文件改变的时候，很少的文件需要重新编译。它通常可以给大型编译加速两倍或两倍以上。

    class LCDRange : public QVBox
    {
        Q_OBJECT
    public:
        LCDRange( QWidget *parent=0, const char *name=0 );

meta object file. 注意Q_OBJECT。这个宏必须被包含到所有使用信号和/或槽的类。如果你很好奇，它定义了在元对象文件中实现的一些函数。

        int value() const;
    public slots:
        void setValue( int );

    signals:
        void valueChanged( int );

这三个成员函数构成了这个窗口部件和程序中其它组件的接口。直到现在，LCDRange根本没有一个真正的接口。

value()是一个可以访问LCDRange的值的公共函数。setValue()是我们第一个自定义槽，并且valueChanged()是我们第一个自定义信号。

槽必须按通常的方式实现（记住槽也是一个C++成员函数）。信号可以在元对象文件中自动实现。信号也遵守C++函数的保护法则（比如，一个类只能发射它自己定义的或者继承来的信号）。

当LCDRange的值发生变化时，valueChanged()信号就会被使用——你从这个名字中就可以猜到。这将不会是你将会看到的命名为somethingChanged()的最后一个信号。

t7/lcdrange.cpp

这个文件主要利用了t6/main.cpp，在这里只是说明一下改变了哪些。

        connect( slider, SIGNAL(valueChanged(int)),
                 lcd, SLOT(display(int)) );
        connect( slider, SIGNAL(valueChanged(int)),
                 SIGNAL(valueChanged(int)) );

这个代码来自LCDRange的构造函数。

第一个connect和你在上一章中看到的一样。第二个是新的，它把滑块的valueChanged()信号和这个对象的valueChanged信号连接起来了。带有三个参数的connect()函数连接到this对象的信号或槽。

是的，这是正确的。信号可以被连接到其它的信号。当第一个信号被发射时，第二个信号也被发射。

让我们来看看当用户操作这个滑块的时候都发生了些什么。滑块看到自己的值发生了改变，并发射了valueChanged()信号。这个信号被连接到QLCDNumber的display()槽和LCDRange的valueChanged()信号。

所以，当这个信号被发射的时候，LCDRange发射它自己的valueChanged()信号。另外，QLCDNumber::display()被调用并显示新的数字。

注意你并没有保证执行的任何顺序——LCDRange::valueChanged()也许在QLCDNumber::display()之前或者之后发射，这是完全任意的。

    int LCDRange::value() const
    {
        return slider->value();
    }

value()的实现是直接了当的，它简单地返回滑块的值。

    void LCDRange::setValue( int value )
    {
        slider->setValue( value );
    }

setValue()的实现是相当直接了当的。注意因为滑块和LCD数字是连接的，设置滑块的值就会自动的改变LCD数字的值。另外，如果滑块的值超过了合法范围，它会自动调节。

t7/main.cpp

        LCDRange *previous = 0;
        for( int r = 0 ; r < 4 ; r++ ) {
            for( int c = 0 ; c < 4 ; c++ ) {
                LCDRange* lr = new LCDRange( grid );
                if ( previous )
                    connect( lr, SIGNAL(valueChanged(int)),
                             previous, SLOT(setValue(int)) );
                previous = lr;
            }
        }

main.cpp中所有的部分都是上一章复制的，除了MyWidget的构造函数。当我们创建16个RCDRange对象时，我们现在使用信号/槽机制连接它们。每一个的valueChanged()信号都和前一个的setValue()槽连接起来了。因为当LCDRange的值发生改变的时候，发射一个valueChanged()信号（惊奇！），我们在这里创建了一个信号和槽的“链”。

编译

为一个多文件的应用程序创建一个makefile和为一个单文件的应用程序创建一个makefile是没有什么不同的。如果你已经把这个例子中的所有文件都保存到它们自己的目录中，你所要做的就是这些：

qmake -project
qmake

第一个命令调用qmake来生成一个.pro（项目）文件。第二个命令根据这个项目文件来生成一个（系统相关的）makefile。你现在可以输入make（或者nmake，如果你使用Visual Studio）。

行为

在开始的时候，这个程序看起来和上一章里的一样。试着操作滑块到右下角……

练习

seven LCDs back to 50. 使用右下角的滑块并设置所有的LCD到50。然后设置通过点击这个滑块的左侧把它设置为40。现在，你可以通过把最后一个调到左边来把前七个LCD设置回50。

点击右下角滑块的滑块的左边。发生了什么？为什么只是正确的行为？

现在你可以进行第八章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第九章：你可以使用加农炮了

Screenshot of tutorial nine

在这个例子中我们开始画一个蓝色可爱的小加农炮.只cannon.cpp和上一章不同。

  • t9/lcdrange.h包含LCDRange类定义。
  • t9/lcdrange.cpp包含LCDRange类实现。
  • t9/cannon.h包含CannonField类定义。
  • t9/cannon.cpp包含CannonField类实现。
  • t9/main.cpp包含MyWidget和main。

一行一行地解说

t9/cannon.cpp

    void CannonField::paintEvent( QPaintEvent * )
    {
        QPainter p( this );

我们现在开始认真地使用QPainter。我们创建一个绘画工具来操作这个窗口部件。

        p.setBrush( blue );

当一个QPainter填满一个矩形、圆或者其它无论什么，它会用它的画刷填满这个图形。这里我们把画刷设置为蓝色。（我们也可以使用一个调色板。）

        p.setPen( NoPen );

并且QPainter使用画笔来画边界。这里我们设置为NoPen，就是说我们在边界上什么都不画，蓝色画刷会在我们画的东西的边界内画满全部。

        p.translate( 0, rect().bottom() );

QPainter::translate()函数转化QPainter的坐标系统，比如，它通过偏移谅来移动。这里我们设置窗口部件的左下角为(0,0)。x和y的方向没有改变，比如，窗口部件中的所有y坐标现在都是负数（请看坐标系统获得有关Qt的坐标系统更多的信息。）

        p.drawPie( QRect(-35, -35, 70, 70), 0, 90*16 );

drawPie()函数使用一个开始角度和弧长在一个指定的矩形内画一个饼型图。角度的度量用的是一度的十六分之一。零度在三点的位置。画的方向是顺时针的。这里我们在窗口部件的左下角画一个四分之一圆。这个饼图被蓝色充满，并且没有边框。

        p.rotate( -ang );

QPainter::rotate()函数绕QPainter坐标系统的初始位置旋转它。旋转的参数是一个按度数给定的浮点数（不是一个像上面那样给的十六分之一的度数）并且是顺时针的。这里我们顺时针旋转ang度数。

        p.drawRect( QRect(33, -4, 15, 8) );

QPainter::drawRect()函数画一个指定的矩形。这里我们画的是加农炮的炮筒。

很难想象当坐标系统被转换之后（转化、旋转、缩放或者修剪）的绘画结果。

在这种情况下，坐标系统先被转化后被旋转。如果矩形QRect(33, -4, 15, 8)被画到这个转化后的坐标系统中，它看起来会是这样：

The cannon translated but not rotated

注意矩形被CannonField窗口部件的边界省略了一部分。当我们选装坐标系统，以60度为例，矩形会以(0,0)为圆心被旋转，也就是左下角，因为我们已经转化了坐标系统。结果会是这样：

The cannon translated and rotated

我们做完了，除了我们还没有解释为什么Windows在这个时候没有发抖。

    int main( int argc, char **argv )
    {
        QApplication::setColorSpec( QApplication::CustomColor );
        QApplication a( argc, argv );

我们告诉Qt我们在这个程序中想使用一个不同的颜色分配策略。这里没有单一正确的颜色分配策略。因为这个程序使用了不常用的黄色，但不是很多颜色，CustomColor最好。这里有几个其它的分配策略，你可以在QApplication::setColorSpec()文档中读到它们。

通常情况下你可以忽略这一点，因为默认的是好的。偶尔一些使用常用颜色的应用程序看起来比较糟糕，因而改变分配策略通常会有所帮助。

行为

当滑块被操作的时候，所画的加农炮的角度会因此而变化。

Quit中的字母Q现在有下划线，并且Alt+Q会实现你所要的。如果你不知道这些，你一定是没有做第八章中的练习。

你也要注意加农炮的闪烁让人很烦，特别是在一个比较慢的机器上。我们将会在下一章修正这一点。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

设置一个不同的画笔代替NoPen。设置一个调色板的画刷。

试着用“Q&uit”或者“Qu&it”作为按钮的文本来提到“&Quit”。发生了什么？

现在你可以进行第十章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第十章：像丝一样滑

Screenshot of tutorial ten

在这个例子中，我们介绍画一个pixmap来除去闪烁。我们也会加入一个力量控制。

  • t10/lcdrange.h包含LCDRange类定义。
  • t10/lcdrange.cpp包含LCDRange类实现。
  • t10/cannon.h包含CannonField类定义。
  • t10/cannon.cpp包含CannonField类实现。
  • t10/main.cpp包含MyWidget和main。

一行一行地解说

t10/cannon.h

CannonField现在除了角度又多了一个力量值。

        int   angle() const { return ang; }
        int   force() const { return f; }

    public slots:
        void  setAngle( int degrees );
        void  setForce( int newton );

    signals:
        void  angleChanged( int );
        void  forceChanged( int );

力量的接口的实现和角度一样。

    private:
        QRect cannonRect() const;

我们把加农炮封装的矩形的定义放到了一个单独的函数中。

        int ang;
        int f;
    };

力量被存储到一个整数f中。

t10/cannon.cpp

    #include <qpixmap.h>

我们包含了QPixmap类定义。

    CannonField::CannonField( QWidget *parent, const char *name )
            : QWidget( parent, name )
    {
        ang = 45;
        f = 0;
        setPalette( QPalette( QColor( 250, 250, 200) ) );
    }

力量（f）被初始化为0。

    void CannonField::setAngle( int degrees )
    {
        if ( degrees < 5 )
            degrees = 5;
        if ( degrees > 70 )
            degrees = 70;
        if ( ang == degrees )
            return;
        ang = degrees;
        repaint( cannonRect(), FALSE );
        emit angleChanged( ang );
    }

我们在setAngle()函数中做了一个小的改变。它只重画窗口部件中含有加农炮的一小部分。FALSE参数说明在一个绘画事件发送到窗口部件之前指定的矩形将不会被擦去。这将会使绘画过程加速和平滑。

    void CannonField::setForce( int newton )
    {
        if ( newton < 0 )
            newton = 0;
        if ( f == newton )
            return;
        f = newton;
        emit forceChanged( f );
    }

setForce()的实现和setAngle()很相似。唯一的不同是因为我们不显示力量值，我们不需要重画窗口部件。

    void CannonField::paintEvent( QPaintEvent *e )
    {
        if ( !e->rect().intersects( cannonRect() ) )
            return;

我们现在用只重画需要刷新得部分来优化绘画事件。首先我们检查是否不得不完全重画任何事，我们返回是否不需要。

        QRect cr = cannonRect();
        QPixmap pix( cr.size() );

然后，我们创建一个临时的pixmap，我们用来不闪烁地画。所有的绘画操作都在这个pixmap中完成，并且之后只用一步操作来把这个pixmap画到屏幕上。

这是不闪烁绘画的本质：一次准确地在每一个像素上画。更少，你会得到绘画错误。更多，你会得到闪烁。在这个例子中这个并不重要——当代码被写时，仍然是很慢的机器导致闪烁，但以后不会再闪烁了。我们由于教育目的保留了这些代码。

        pix.fill( this, cr.topLeft() );

我们用这个pixmap来充满这个窗口部件的背景。

        QPainter p( &pix );
        p.setBrush( blue );
        p.setPen( NoPen );
        p.translate( 0, pix.height() - 1 );
        p.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
        p.rotate( -ang );
        p.drawRect( QRect(33, -4, 15, 8) );
        p.end();

我们就像第九章中一样画，但是现在我们是在pixmap上画。

在这一点上，我们有一个绘画工具变量和一个pixmap看起来相当正确，但是我们还没有在屏幕上画呢。

        p.begin( this );
        p.drawPixmap( cr.topLeft(), pix );

所以我们在CannonField上面打开绘图工具并在这之后画这个pixmap。

这就是全部了。在顶部和底部各有一对线，并且这个代码是100%不闪烁的。

    QRect CannonField::cannonRect() const
    {
        QRect r( 0, 0, 50, 50 );
        r.moveBottomLeft( rect().bottomLeft() );
        return r;
    }

这个函数返回一个在窗口部件坐标中封装加农炮的矩形。首先我们创建一个50*50大小的矩形，然后移动它，使它的左下角和窗口部件自己的左下角相等。

QWidget::rect()函数在窗口部件自己的坐标（左上角是0,0）中返回窗口部件封装的矩形。

t10/main.cpp

    MyWidget::MyWidget( QWidget *parent, const char *name )
            : QWidget( parent, name )
    {

构造函数也是一样，但是已经加入了一些东西。

        LCDRange *force  = new LCDRange( this, "force" );
        force->setRange( 10, 50 );

我们加入了第二个LCDRange，用来设置力量。

        connect( force, SIGNAL(valueChanged(int)),
                 cannonField, SLOT(setForce(int)) );
        connect( cannonField, SIGNAL(forceChanged(int)),
                 force, SLOT(setValue(int)) );

我们把force窗口部件和cannonField窗口部件连接起来，就和我们对angle窗口部件做的一样。

        QVBoxLayout *leftBox = new QVBoxLayout;
        grid->addLayout( leftBox, 1, 0 );
        leftBox->addWidget( angle );
        leftBox->addWidget( force );

在第九章，我们把angle放到了布局的左下单元。现在我们想在这个单元中放入两个窗口部件，所一个我们用了一个垂直的盒子，把这个垂直的盒子放到这个网格单元中，并且把angle和force放到这个垂直的盒子中。

        force->setValue( 25 );

我们初始化力量的值为25。

行为

闪烁已经走了，并且我们还有一个力量控制。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

让加农炮的炮筒的大小依赖于力量。

把加农炮放到右下角。

试着加入一个更好的键盘接口。例如，用+和-来增加或者减少力量，用enter来发射。提示：QAccel和在LCDRange中新建addStep()和subtractStep()，就像QSlider::addStep()。如果你被左面和右面键所苦恼（我就是！），试着都改变！

现在你可以进行第十一章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第十一章：给它一个炮弹

Screenshot of tutorial eleven

在这个例子里我们介绍了一个定时器来实现动画的射击。

  • t11/lcdrange.h包含LCDRange类定义。
  • t11/lcdrange.cpp包含LCDRange类实现。
  • t11/cannon.h包含CannonField类定义。
  • t11/cannon.cpp包含CannonField类实现。
  • t11/main.cpp包含MyWidget和main。

一行一行地解说

t11/cannon.h

CannonField现在就有了射击能力。

        void  shoot();

当炮弹不在空中中，调用这个槽就会使加农炮射击。

    private slots:
        void  moveShot();

当炮弹正在空中时，这个私有槽使用一个定时器来移动射击。

    private:
        void  paintShot( QPainter * );

这个函数来画射击。

        QRect shotRect() const;

当炮弹正在空中的时候，这个私有函数返回封装它所占用空间的矩形，否则它就返回一个没有定义的矩形。

        int timerCount;
        QTimer * autoShootTimer;
        float shoot_ang;
        float shoot_f;
    };

这些私有变量包含了描述射击的信息。timerCount保留了射击进行后的时间。shoot_ang是加农炮射击时的角度，shoot_f是射击时加农炮的力量。

t11/cannon.cpp

    #include <math.h>

我们包含了数学库，因为我们需要使用sin()和cos()函数。

    CannonField::CannonField( QWidget *parent, const char *name )
            : QWidget( parent, name )
    {
        ang = 45;
        f = 0;
        timerCount = 0;
        autoShootTimer = new QTimer( this, "movement handler" );
        connect( autoShootTimer, SIGNAL(timeout()),
                 this, SLOT(moveShot()) );
        shoot_ang = 0;
        shoot_f = 0;
        setPalette( QPalette( QColor( 250, 250, 200) ) );
    }

我们初始化我们新的私有变量并且把QTimer::timeout()信号和我们的moveShot()槽相连。我们会在定时器超时的时候移动射击。

    void CannonField::shoot()
    {
        if ( autoShootTimer->isActive() )
            return;
        timerCount = 0;
        shoot_ang = ang;
        shoot_f = f;
        autoShootTimer->start( 50 );
    }

只要炮弹不在空中，这个函数就会进行一次射击。timerCount被重新设置为零。shoot_ang和shoot_f设置为当前加农炮的角度和力量。最后，我们开始这个定时器。

    void CannonField::moveShot()
    {
        QRegion r( shotRect() );
        timerCount++;

        QRect shotR = shotRect();

        if ( shotR.x() > width() || shotR.y() > height() )
            autoShootTimer->stop();
        else
            r = r.unite( QRegion( shotR ) );
        repaint( r );
    }

moveShot()是一个移动射击的槽，当QTimer开始的时候，每50毫秒被调用一次。

它的任务就是计算新的位置，重新画屏幕并把炮弹放到新的位置，并且如果需要的话，停止定时器。

首先我们使用QRegion来保留旧的shotRect()。QRegion可以保留任何种类的区域，并且我们可以用它来简化绘画过程。shotRect()返回现在炮弹所在的矩形——稍后我们会详细介绍。

然后我们增加timerCount，用它来实现炮弹在它的轨迹中移动的每一步。

下一步我们算出新的炮弹的矩形。

如果炮弹已经移动到窗口部件的右面或者下面的边界，我们停止定时器或者添加新的shotRect()到QRegion。

最后，我们重新绘制QRegion。这将会发送一个单一的绘画事件，但仅仅有一个到两个举行需要刷新。

    void CannonField::paintEvent( QPaintEvent *e )
    {
        QRect updateR = e->rect();
        QPainter p( this );

        if ( updateR.intersects( cannonRect() ) )
            paintCannon( &p );
        if ( autoShootTimer->isActive() &&
             updateR.intersects( shotRect() ) )
            paintShot( &p );
    }

绘画事件函数在前一章中已经被分成两部分了。现在我们得到的新的矩形区域需要绘画，检查加农炮和/或炮弹是否相交，并且如果需要的话，调用paintCannon()和/或paintShot()。

    void CannonField::paintShot( QPainter *p )
    {
        p->setBrush( black );
        p->setPen( NoPen );
        p->drawRect( shotRect() );
    }

这个私有函数画一个黑色填充的矩形作为炮弹。

我们把paintCannon()的实现放到一边，它和前一章中的paintEvent()一样。

    QRect CannonField::shotRect() const
    {
        const double gravity = 4;

        double time      = timerCount / 4.0;
        double velocity  = shoot_f;
        double radians   = shoot_ang*3.14159265/180;

        double velx      = velocity*cos( radians );
        double vely      = velocity*sin( radians );
        double x0        = ( barrelRect.right()  + 5 )*cos(radians);
        double y0        = ( barrelRect.right()  + 5 )*sin(radians);
        double x         = x0 + velx*time;
        double y         = y0 + vely*time - 0.5*gravity*time*time;

        QRect r = QRect( 0, 0, 6, 6 );
        r.moveCenter( QPoint( qRound(x), height() - 1 - qRound(y) ) );
        return r;
    }

这个私有函数计算炮弹的中心点并且返回封装炮弹的矩形。它除了使用自动增加所过去的时间的timerCount之外，还使用初始时的加农炮的力量和角度。

运算公式使用的是有重力的环境下光滑运动的经典牛顿公式。简单地说，我们已经选择忽略爱因斯坦理论的结果。

我们在一个y坐标向上增加的坐标系统中计算中心点。在我们计算出中心点之后，我们构造一个6*6大小的QRect，并把它的中心移动到我们上面所计算出的中心点。同样的操作我们把这个点移动到窗口部件的坐标系统（请看坐标系统）。

qRound()函数是一个在qglobal.h中定义的内嵌函数（被其它所有Qt头文件包含）。qRound()把一个双精度实数变为最接近的整数。

t11/main.cpp

    class MyWidget: public QWidget
    {
    public:
        MyWidget( QWidget *parent=0, const char *name=0 );
    };

唯一的增加是Shoot按钮。

        QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
        shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

在构造函数中我们创建和设置Shoot按钮就像我们对Quit按钮所做的那样。注意构造函数的第一个参数是按钮的文本，并且第三个是窗口部件的名称。

        connect( shoot, SIGNAL(clicked()), cannonField, SLOT(shoot()) );

把Shoot按钮的clicked()信号和CannonField的shoot()槽连接起来。

行为

The cannon can shoot, but there's nothing to shoot at.

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

用一个填充的圆来表示炮弹。提示：QPainter::drawEllipse()会对你有所帮助。

当炮弹在空中的时候，改变加农炮的颜色。

现在你可以进行第十二章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第十三章：游戏结束

Screenshot of tutorial thirteen

在这个例子中我们开始研究一个带有记分的真正可玩的游戏。我们给MyWidget一个新的名字（GameBoard）并添加一些槽。

我们把定义放在gamebrd.h并把实现放在gamebrd.cpp。

CannonField现在有了一个游戏结束状态。

在LCDRange中的布局问题已经修好了。

  • t13/lcdrange.h包含LCDRange类定义。
  • t13/lcdrange.cpp包含LCDRange类实现。
  • t13/cannon.h包含CannonField类定义。
  • t13/cannon.cpp包含CannonField类实现。
  • t13/gamebrd.h包含GameBoard类定义。
  • t13/gamebrd.cpp包含GameBoard类实现。
  • t13/main.cpp包含MyWidget和main。

一行一行地解说

t13/lcdrange.h

    #include <qwidget.h>

    class QSlider;
    class QLabel;

    class LCDRange : public QWidget

我们继承了QWidget而不是QVBox。QVBox是非常容易使用的，但是它也显示了它的局域性，所以我们选择使用更加强大和稍微有一些难的QVBoxLayout。（和你记忆中的一样，QVBoxLayout不是一个窗口部件，它管理窗口部件。）

t13/lcdrange.cpp

    #include <qlayout.h>

我们现在需要包含qlayout.h来获得其它布局管理API。

    LCDRange::LCDRange( QWidget *parent, const char *name )
            : QWidget( parent, name )

我们使用一种平常的方式继承QWidget。

另外一个构造函数作了同样的改动。init()没有变化，除了我们在最后加了几行：

        QVBoxLayout * l = new QVBoxLayout( this );

我们使用所有默认值创建一个QVBoxLayout，管理这个窗口部件的子窗口部件。

        l->addWidget( lcd, 1 );

At the top we add the QLCDNumber with a non-zero stretch.

        l->addWidget( slider );
        l->addWidget( label );

然后我们添加另外两个，它们都使用默认的零伸展因数。

这个伸展控制是QVBoxLayout（和QHBoxLayout，和QGridLayout）所提供的，而像QVBox这样的类却不提供。在这种情况下我们让QLCDNumber可以伸展，而其它的不可以。

t13/cannon.h

CannonField现在有一个游戏结束状态和一些新的函数。

        bool  gameOver() const { return gameEnded; }

如果游戏结束了，这个函数返回TRUE，或者如果游戏还在继续，返回FALSE。

        void  setGameOver();
        void  restartGame();

这里是两个新槽：setGameOver()和restartGame()。

        void  canShoot( bool );

这个新的信号表明CannonField使shoot()槽生效的状态。我们将在下面使用它用来使Shoot按钮生效或失效。

        bool gameEnded;

这个私有变量包含游戏的状态。TRUE说明游戏结束，FALSE说明游戏还将继续。

t13/cannon.cpp

        gameEnded = FALSE;

这一行已经被加入到构造函数中。最开始的时候，游戏没有结束（对于玩家是很幸运的 :-）。

    void CannonField::shoot()
    {
        if ( isShooting() )
            return;
        timerCount = 0;
        shoot_ang = ang;
        shoot_f = f;
        autoShootTimer->start( 50 );
        emit canShoot( FALSE );
    }

我们添加一个新的isShooting()函数，所以shoot()使用它替代直接的测试。同样，shoot告诉世界CannonField现在不可以射击。

    void CannonField::setGameOver()
    {
        if ( gameEnded )
            return;
        if ( isShooting() )
            autoShootTimer->stop();
        gameEnded = TRUE;
        repaint();
    }

这个槽终止游戏。它必须被CannonField外面的调用，因为这个窗口部件不知道什么时候终止游戏。这是组件编程中一条重要设计原则。我们选择使组件可以尽可能灵活以适应不同的规则（比如，在一个首先射中十次的人胜利的多人游戏版本可能使用不变的CannonField）。

如果游戏已经被终止，我们立即返回。如果游戏会继续到我们的设计完成，设置游戏结束标志，并且重新绘制整个窗口部件。

    void CannonField::restartGame()
    {
        if ( isShooting() )
            autoShootTimer->stop();
        gameEnded = FALSE;
        repaint();
        emit canShoot( TRUE );
    }

这个槽开始一个新游戏。如果炮弹还在空中，我们停止设计。然后我们重置gameEnded变量并重新绘制窗口部件。

就像hit()或miss()一样，moveShot()同时也发射新的canShoot(TRUE)信号。

CannonField::paintEvent()的修改：

    void CannonField::paintEvent( QPaintEvent *e )
    {
        QRect updateR = e->rect();
        QPainter p( this );

        if ( gameEnded ) {
            p.setPen( black );
            p.setFont( QFont( "Courier", 48, QFont::Bold ) );
            p.drawText( rect(), AlignCenter, "Game Over" );
        }

绘画事件已经通过如果游戏结束，比如gameEnded是TRUE，就显示文本“Game Over”而被增强了。我们在这里不怕麻烦来检查更新矩形，是因为在游戏结束的时候速度不是关键性的。

为了画文本，我们先设置了黑色的画笔，当画文本的时候，画笔颜色会被用到。接下来我们选择Courier字体中的48号加粗字体。最后我们在窗口部件的矩形中央绘制文本。不幸的是，在一些系统中（特别是使用Unicode的X服务器）它会用一小段时间来载入如此大的字体。因为Qt缓存字体，我们只有第一次使用这个字体的时候才会注意到这一点。

        if ( updateR.intersects( cannonRect() ) )
            paintCannon( &p );
        if ( isShooting() && updateR.intersects( shotRect() ) )
            paintShot( &p );
        if ( !gameEnded && updateR.intersects( targetRect() ) )
            paintTarget( &p );
    }

我们只有在设计的时候画炮弹，在玩游戏的时候画目标（这也就是说，当游戏没有结束的时候）。

t13/gamebrd.h

这个文件是新的。它包含最后被用来作为MyWidget的GameBoard类的定义。

    class QPushButton;
    class LCDRange;
    class QLCDNumber;
    class CannonField;

    #include "lcdrange.h"
    #include "cannon.h"

    class GameBoard : public QWidget
    {
        Q_OBJECT
    public:
        GameBoard( QWidget *parent=0, const char *name=0 );

    protected slots:
        void  fire();
        void  hit();
        void  missed();
        void  newGame();

    private:
        QLCDNumber  *hits;
        QLCDNumber  *shotsLeft;
        CannonField *cannonField;
    };

我们现在已经添加了四个槽。这些槽都是被保护的，只在内部使用。我们也已经加入了两个QLCDNumbers（hits和shotsLeft）用来显示游戏的状态。

t13/gamebrd.cpp

这个文件是新的。它包含最后被用来作为MyWidget的GameBoard类的实现，

我们已经在GameBoard的构造函数中做了一些修改。

        cannonField = new CannonField( this, "cannonField" );

cannonField现在是一个成员变量，所以我们在使用它的时候要小心地改变它的构造函数。（Trolltech的好程序员从来不会忘记这点，但是我就忘了。告诫程序员－如果“programmor”是拉丁语，至少。无论如何，返回代码。）

        connect( cannonField, SIGNAL(hit()),
                 this, SLOT(hit()) );
        connect( cannonField, SIGNAL(missed()),
                 this, SLOT(missed()) );

这次当炮弹射中或者射失目标的时候，我们想做些事情。所以我们把CannonField的hit()和missed()信号连接到这个类的两个被保护的同名槽。

        connect( shoot, SIGNAL(clicked()), SLOT(fire()) );

以前我们直接把Shoot按钮的clicked()信号连接到CannonField的shoot()槽。这次我们想跟踪射击的次数，所以我们把它改为连接到这个类里面一个被保护的槽。

注意当你用独立的组件工作的时候，改变程序的行为是多么的容易。

        connect( cannonField, SIGNAL(canShoot(bool)),
                 shoot, SLOT(setEnabled(bool)) );

我们也使用cannonField的canShoot()信号来适当地使Shoot按钮生效和失效。

        QPushButton *restart
            = new QPushButton( "&New Game", this, "newgame" );
        restart->setFont( QFont( "Times", 18, QFont::Bold ) );

        connect( restart, SIGNAL(clicked()), this, SLOT(newGame()) );

我们创建、设置并且连接这个New Game按钮就像我们对其它按钮所做的一样。点击这个按钮就会激活这个窗口部件的newGame()槽。

        hits = new QLCDNumber( 2, this, "hits" );
        shotsLeft = new QLCDNumber( 2, this, "shotsleft" );
        QLabel *hitsL = new QLabel( "HITS", this, "hitsLabel" );
        QLabel *shotsLeftL
            = new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

我们创建了四个新的窗口部件。注意我们不怕麻烦的把QLabel窗口部件的指针保留到GameBoard类中是因为我们不想再对它们做什么了。当GameBoard窗口部件被销毁的时候，Qt将会删除它们，并且布局类会适当地重新定义它们的大小。

        QHBoxLayout *topBox = new QHBoxLayout;
        grid->addLayout( topBox, 0, 1 );
        topBox->addWidget( shoot );
        topBox->addWidget( hits );
        topBox->addWidget( hitsL );
        topBox->addWidget( shotsLeft );
        topBox->addWidget( shotsLeftL );
        topBox->addStretch( 1 );
        topBox->addWidget( restart );

右上单元格的窗口部件的数量正在变大。从前它是空的，现在它是完全充足的，我们把它们放到布局中来更好的看到它们。

注意我们让所有的窗口部件获得它们更喜欢的大小，改为在New Game按钮的左边加入了一个可以自由伸展的东西。

        newGame();
    }

我们已经做完了所有关于GameBoard的构造，所以我们使用newGame()来开始。（newGame()是一个槽，但是就像我们所说的，槽也可以像普通的函数一样使用。）

    void GameBoard::fire()
    {
        if ( cannonField->gameOver() || cannonField->isShooting() )
            return;
        shotsLeft->display( shotsLeft->intValue() - 1 );
        cannonField->shoot();
    }

这个函数进行射击。如果游戏结束了或者还有一个炮弹在空中，我们立即返回。我们减少炮弹的数量并告诉加农炮进行射击。

    void GameBoard::hit()
    {
        hits->display( hits->intValue() + 1 );
        if ( shotsLeft->intValue() == 0 )
            cannonField->setGameOver();
        else
            cannonField->newTarget();
    }

当炮弹击中目标的时候这个槽被激活。我们增加射中的数量。如果没有炮弹了，游戏就结束了。否则，我们会让CannonField生成新的目标。

    void GameBoard::missed()
    {
        if ( shotsLeft->intValue() == 0 )
            cannonField->setGameOver();
    }

当炮弹射失目标的时候这个槽被激活，如果没有炮弹了，游戏就结束了。

    void GameBoard::newGame()
    {
        shotsLeft->display( 15 );
        hits->display( 0 );
        cannonField->restartGame();
        cannonField->newTarget();
    }

当用户点击Restart按钮的时候这个槽被激活。它也会被构造函数调用。首先它把炮弹的数量设置为15。注意这里是我们在程序中唯一设置炮弹数量的地方。把它改变为你所想要的游戏规则。接下来我们重置射中的数量，重新开始游戏，并且生成一个新的目标。

t13/main.cpp

这个文件仅仅被删掉了一部分。MyWidget没了，并且唯一剩下的是main()函数，除了名称的改变其它都没有改变。

行为

射中的和剩余炮弹的数量被显示并且程序继续跟踪它们。游戏可以结束了，并且还有一个按钮可以开始一个新游戏。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

添加一个随机的风的因素并把它显示给用户看。

当炮弹击中目标的时候做一些飞溅的效果。

实现多个目标。

现在你可以进行第十四章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第十四章：面对墙壁

Screenshot of tutorial fourteen

这是最后的例子：一个完整的游戏。

我们添加键盘快捷键并引入鼠标事件到CannonField。我们在CannonField周围放一个框架并添加一个障碍物（墙）使这个游戏更富有挑战性。

  • t14/lcdrange.h包含LCDRange类定义。
  • t14/lcdrange.cpp包含LCDRange类实现。
  • t14/cannon.h包含CannonField类定义。
  • t14/cannon.cpp包含CannonField类实现。
  • t14/gamebrd.h包含GameBoard类定义。
  • t14/gamebrd.cpp包含GameBoard类实现。
  • t14/main.cpp包含MyWidget和main。

一行一行地解说

t14/cannon.h

CannonField现在可以接收鼠标事件，使得用户可以通过点击和拖拽炮筒来瞄准。CannonField也有一个障碍物的墙。

    protected:
        void  paintEvent( QPaintEvent * );
        void  mousePressEvent( QMouseEvent * );
        void  mouseMoveEvent( QMouseEvent * );
        void  mouseReleaseEvent( QMouseEvent * );

除了常见的事件处理器，CannonField实现了三个鼠标事件处理器。名称说明了一切。

        void  paintBarrier( QPainter * );

这个私有函数绘制了障碍物墙。

        QRect barrierRect() const;

这个私有寒暑返回封装障碍物的矩形。

        bool  barrelHit( const QPoint & ) const;

这个私有函数检查是否一个点在加农炮炮筒的内部。

        bool barrelPressed;

当用户在炮筒上点击鼠标并且没有放开的话，这个私有变量为TRUE。

t14/cannon.cpp

        barrelPressed = FALSE;

这一行被添加到构造函数中。最开始的时候，鼠标没有在炮筒上点击。

        } else if ( shotR.x() > width() || shotR.y() > height() ||
                    shotR.intersects(barrierRect()) ) {

现在我们有了一个障碍物，这样就有了三种射失的方法。我们来测试一下第三种。

    void CannonField::mousePressEvent( QMouseEvent *e )
    {
        if ( e->button() != LeftButton )
            return;
        if ( barrelHit( e->pos() ) )
            barrelPressed = TRUE;
    }

这是一个Qt事件处理器。当鼠标指针在窗口部件上，用户按下鼠标的按键时，它被调用。

如果事件不是由鼠标左键产生的，我们立即返回。否则，我们检查鼠标指针是否在加农炮的炮筒内。如果是的，我们设置barrelPressed为TRUE。

注意pos()函数返回的是窗口部件坐标系统中的点。

    void CannonField::mouseMoveEvent( QMouseEvent *e )
    {
        if ( !barrelPressed )
            return;
        QPoint pnt = e->pos();
        if ( pnt.x() <= 0 )
            pnt.setX( 1 );
        if ( pnt.y() >= height() )
            pnt.setY( height() - 1 );
        double rad = atan(((double)rect().bottom()-pnt.y())/pnt.x());
        setAngle( qRound ( rad*180/3.14159265 ) );
    }

这是另外一个Qt事件处理器。当用户已经在窗口部件中按下了鼠标按键并且移动/拖拽鼠标时，它被调用。（你可以让Qt在没有鼠标按键被按下的时候发送鼠标移动事件。请看QWidget::setMouseTracking()。）

这个处理器根据鼠标指针的位置重新配置加农炮的炮筒。

首先，如果炮筒没有被按下，我们返回。接下来，我们获得鼠标指针的位置。如果鼠标指针到了窗口部件的左面或者下面，我们调整鼠标指针使它返回到窗口部件中。

然后我们计算在鼠标指针和窗口部件的左下角所构成的虚构的线和窗口部件下边界的角度。最后，我们把加农炮的角度设置为我们新算出来的角度。

记住要用setAngle()来重新绘制加农炮。

    void CannonField::mouseReleaseEvent( QMouseEvent *e )
    {
        if ( e->button() == LeftButton )
            barrelPressed = FALSE;
    }

只要用户释放鼠标按钮并且它是在窗口部件中按下的时候，这个Qt事件处理器就会被调用。

如果鼠标左键被释放，我们就会确认炮筒不再被按下了。

绘画事件包含了下述额外的两行：

        if ( updateR.intersects( barrierRect() ) )
            paintBarrier( &p );

paintBarrier()做的和paintShot()、paintTarget()和paintCannon()是同样的事情。

    void CannonField::paintBarrier( QPainter *p )
    {
        p->setBrush( yellow );
        p->setPen( black );
        p->drawRect( barrierRect() );
    }

这个私有函数用一个黑色边界黄色填充的矩形作为障碍物。

    QRect CannonField::barrierRect() const
    {
        return QRect( 145, height() - 100, 15, 100 );
    }

这个私有函数返回障碍物的矩形。我们把障碍物的下边界和窗口部件的下边界放在了一起。

    bool CannonField::barrelHit( const QPoint &p ) const
    {
        QWMatrix mtx;
        mtx.translate( 0, height() - 1 );
        mtx.rotate( -ang );
        mtx = mtx.invert();
        return barrelRect.contains( mtx.map(p) );
    }

如果点在炮筒内，这个函数返回TRUE；否则它就返回FALSE。

这里我们使用QWMatrix类。它是在头文件qwmatrix.h中定义的，这个头文件被qpainter.h包含。

QWMatrix定义了一个坐标系统映射。它可以执行和QPainter中一样的转换。

这里我们实现同样的转换的步骤就和我们在paintCannon()函数中绘制炮筒的时候所作的一样。首先我们转换坐标系统，然后我们旋转它。

现在我们需要检查点p（在窗口部件坐标系统中）是否在炮筒内。为了做到这一点，我们倒置这个转换矩阵。倒置的矩阵就执行了我们在绘制炮筒时使用的倒置的转换。我们通过使用倒置矩阵来映射点p，并且如果它在初始的炮筒矩形内就返回TRUE。

t14/gamebrd.cpp

    #include <qaccel.h>

我们包含QAccel的类定义。

        QVBox *box = new QVBox( this, "cannonFrame" );
        box->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
        cannonField = new CannonField( box, "cannonField" );

我们创建并设置一个QVBox，设置它的框架风格，并在之后创建CannonField作为这个盒子的子对象。因为没有其它的东西在这个盒子里了，效果就是QVBox会在CannonField周围生成了一个框架。

        QAccel *accel = new QAccel( this );
        accel->connectItem( accel->insertItem( Key_Enter ),
                            this, SLOT(fire()) );
        accel->connectItem( accel->insertItem( Key_Return ),
                            this, SLOT(fire()) );

现在我们创建并设置一个加速键。加速键就是在应用程序中截取键盘事件并且如果特定的键被按下的时候调用相应的槽。这种机制也被称为快捷键。注意快捷键是窗口部件的子对象并且当窗口部件被销毁的时候销毁。QAccel 不是窗口部件，并且在它的父对象中没有任何可见的效果。

我们定义两个快捷键。我们希望在Enter键被按下的时候调用fire()槽，在Ctrl+Q键被按下的时候，应用程序退出。因为Enter有时又被称为Return，并且有时键盘中两个键都有，所以我们让这两个键都调用fire()。

        accel->connectItem( accel->insertItem( CTRL+Key_Q ),
                            qApp, SLOT(quit()) );

并且之后我们设置Ctrl+Q和Alt+Q做同样的事情。一些人通常使用Ctrl+Q更多一些（并且无论如何它显示了如果做到它）。

CTRL、Key_Enter、Key_Return和Key_Q都是Qt提供的常量。它们实际上就是Qt::Key_Enter等等，但是实际上所有的类都继承了Qt这个命名空间类。

        QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
        grid->addWidget( quit, 0, 0 );
        grid->addWidget( box, 1, 1 );
        grid->setColStretch( 1, 10 );

我们放置box（QVBox），不是CannonField，在右下的单元格中。

行为

现在当你按下Enter的时候，加农炮就会发射。你也可以用鼠标来确定加农炮的角度。障碍物会使你在玩游戏的时候获得更多一点的挑战。我们还会在CannnonField周围看到一个好看的框架。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

写一个空间入侵者的游戏。

（这个练习首先被Igor Rafienko作出来了。你可以下载他的游戏。）

新的练习是：写一个突围游戏。

最后的劝告：现在向前进，创造编程艺术的杰作！

 [上一章]
[第一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程二

这个教程会提供一个比第一个教程更加“真实世界”的Qt编程实例。它介绍了Qt编程的许多方面，介绍了创建菜单（包括最近使用文件列表）、工具条和对话框、载入和保存用户设置，等等。

如果你对Qt很陌生，如果你还没有阅读过如何学习Qt，请阅读一下。

  • 介绍
  • “大图片”
  • 数据元素
  • 主体很容易
  • 实现图形用户界面
  • 画布控制
  • 文件处理
  • 获得数据
  • 设置选项
  • 项目文件
  • 完成

介绍 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


介绍

在这个教程中，我们将会开发一个叫做chart的单一应用程序，它根据用户输入的数据来显示简单的饼形和条形图表。

这个教程提供了一个应用程序开发的概述，包含了一些代码片断和与之相配的解释。应用程序完整的源程序在examples/chart。

The chart application

« 目录 | “大图片” »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


“大图片”

The chart application's dialogs

chart程序允许用户创建、保存、载入和直观化简单的数据组。每一个用户给出的数据元素都可以被给定颜色和饼形块或条形的样式、一些标签文本和文本的位置和颜色。Element类用来代表数据元素。

程序包含一个调入图表视窗的简单的main.cpp。这个图表视窗有一个提供访问程序功能的菜单条和工具条。程序还提供了两个对话框，一个设置选项，另一个用来创建和编辑数据组。这两个对话框都是由图表视窗的菜单选项或者工具条按钮调用的。

图表视窗的主窗口部件是QCanvasView，它显示一个我们用来画饼形图或条形图的QCanvas。我们继承QCanvasView来获得一些特定的行为。同样我们因为需要比标准类提供的稍多一些，所以我们继承了QCanvasText类（用来在画布上放置文本条目）。

项目文件，chart.pro，用来创建可以用来连编应用程序的Makefile。

« 介绍 | 目录 | 数据元素 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


数据元素

我们将使用一个叫Element的类来存储和访问数据元素。

（由element.h展开。）

    private:

        double m_value;
        QColor m_valueColor;
        int m_valuePattern;
        QString m_label;
        QColor m_labelColor;
        double m_propoints[2 * MAX_PROPOINTS];

每一个元素都有一个值。每一个值都会被使用一种特定的颜色和填充样式来图形化地显示。值也许会有一个和它们关联的标签，标签会被使用标签的颜色来画，并且对于每一种类型的图表都有一个存储在m_propoints数组中的一个（相对）位置。

    #include <qcolor.h>
    #include <qnamespace.h>
    #include <qstring.h>
    #include <qvaluevector.h>

尽管Element是一个纯粹的内部数据类，它包含了四个Qt类。Qt经常被认为是一个纯粹的图形用户界面工具包，但它也提供了一些用来支持应用程序编程的绝大多数方面的非图形用户界面类。我们使用qcolor.h可以使我们在Element类中控制绘图颜色和文本颜色。qnamespace.h的用处稍微有些模糊。绝大多数Qt类都继承于含有各种各样的枚举的Qt这个超级类。Element类不继承于Qt，所以我们需要包含qnamespace.h来访问这些Qt枚举名称。另一个替代的方案就是使Element成为Qt的一个子类。我们包含qstring.h用来使用Qt的Unicode字符串。为了方便，我们类型定义一个Element的矢量容器，这就是我们为什么把qvaluevector.h头文件放到这里的原因。

    typedef QValueVector<Element> ElementVector;

Qt提供了大量的容器，一些是基于值的，比如QValueVector，其它一些基于指针。（请看集合类。）这里我们只是类型定义了一个容器类型，我们将在ElementVector中保存每一个元素数据组。

    const double EPSILON = 0.0000001; // 必须 > INVALID。

元素也许只能是正的值。因为我们使用双精度实数来存储值，我们不能很容易地拿它们和零作比较。所以我们指定一个值，EPSILON，它和零非常接近，并且任何比EPSILON大的值可以被认为是正的和有效的。

    class Element
    {
    public:
        enum { INVALID = -1 };
        enum { NO_PROPORTION = -1 };
        enum { MAX_PROPOINTS = 3 }; // 每个图表类型一个比例值

我们给Element定义了三个公有的枚举变量。INVALID被isValid()函数使用。它是有用的，因为我们将用使用一个固定大小的Element矢量，并且可以通过给定INVALID值来标明未使用的Element。NO_PROPORTION枚举变量用来表明用户还没有定位元素的标签，任何正的比例值都被用来作为与画布大小成比例的文本元素的位置。

如果我们存储每一个标签的实际x和y的位置，当用户每次重新定义主窗口大小（同样也对画布）的时候，文本会保留它的初始（现在是错的）位置。所以我们不存储绝对(x,y)位置，我们存储比例位置，比如x/width和y/height。然后当我们画文本的时候，我们分别用当前的宽度和高度来乘这些位置，这样不管大小如何变化，文本都会被正确定位。比如，如果标签的x位置为300，画布有400像素宽，x的比例值为300/400 = 0.75。

MAX_PROPOINTS枚举变量是有些疑问的。我们对于每一个图表类型的文本标签都要存储x和y的比例。并且我们已经选择把这些比例存储到一个固定大小的数组中。因为我们必须指定所需要的比例对的最大数字。如果我们改变图表类型的数字，这个值就必须被改变，这也就是说Element类和由ChartForm所提供的图表类型的数字是紧密联系的。在一个更大的应用程序中，我们也许使用一个矢量来存储这些点并且根据所能提供的图表类型的数量来动态改变它的大小。

        Element( double value = INVALID, QColor valueColor = Qt::gray,
                 int valuePattern = Qt::SolidPattern,
                 const QString& label = QString::null,
                 QColor labelColor = Qt::black ) {
            init( value, valueColor, valuePattern, label, labelColor );
            for ( int i = 0; i < MAX_PROPOINTS * 2; ++i )
                m_propoints[i] = NO_PROPORTION;
        }

构造函数为Element类的所有成员变量提供了默认值。新的元素总是有没有位置的标签文本。我们是用init()函数是因为我们也提供了一个set()函数，除了比例位置它做的和构造函数一样。

        bool isValid() const { return m_value > EPSILON; }

因为我们正在把Element存储到一个固定大小的矢量中，所以我们需要检测一个特定元素是否有效（比如应该被用来计算和显示）。通过isValid()函数很容易到达这一目的。

（由element.cpp展开。）

    double Element::proX( int index ) const
    {
        Q_ASSERT(index >= 0 && index < MAX_PROPOINTS);
        return m_propoints[2 * index];
    }

这里对Element的所有成员都提供了读取函数和设置函数。proX()和proY()读取函数和setProX()和setProY()设置函数用来读取和设置一个用来确定比例位置所适用的图表的类型索引。这也就是说用户可以为用于竖直条图表、水平条图表和饼形图表的相同数据组设定不同的标签位置。注意我们也使用Q_ASSERT宏来提供对图表类型索引的预先情况测试，（请看调试）。

读写数据元素

（由element.h展开。）

    Q_EXPORT QTextStream &operator<<( QTextStream&, const Element& );
    Q_EXPORT QTextStream &operator>>( QTextStream&, Element& );

为了使我们的Element类更加独立，我们提供了<<和>>的操作符重载，这样Element就可以被文本流读写。我们也可以很容易地使用二进制流，但是使用文本可以让用户使用文本编辑器来维护他们的数据，可以更容易的使用脚本语言来产生和过滤。

（由element.cpp展开。）

    #include "element.h"

    #include <qstringlist.h>
    #include <qtextstream.h>

我们对于操作符的实现需要包含qtextstream.h和qstringlist.h。

    const char FIELD_SEP = ':';
    const char PROPOINT_SEP = ';';
    const char XY_SEP = ',';

我们用来存储数据的格式是用冒号来分隔字段，用换行来分隔记录。比例点用分号间隔，它们的x和y使用逗号分隔。字段的顺序是值、值的颜色、值的样式、标签颜色、标签点、标签文本。比如：

20:#ff0000:14:#000000:0.767033,0.412946;0,0.75;0,0:Red :with colons:!
70:#00ffff:2:#ffff00:0.450549,0.198661;0.198516,0.125954;0,0.198473:Cyan
35:#0000ff:8:#555500:0.10989,0.299107;0.397032,0.562977;0,0.396947:Blue
55:#ffff00:1:#000080:0.0989011,0.625;0.595547,0.312977;0,0.59542:Yellow
80:#ff00ff:1:#000000:0.518681,0.694196;0.794063,0;0,0.793893:Magenta or Violet

我们阅读Element数据的方式中对于文本标签中的空白符和字段间隔符都没有问题。

    QTextStream &operator<<( QTextStream &s, const Element &element )
    {
        s << element.value() << FIELD_SEP
          << element.valueColor().name() << FIELD_SEP
          << element.valuePattern() << FIELD_SEP
          << element.labelColor().name() << FIELD_SEP;

        for ( int i = 0; i < Element::MAX_PROPOINTS; ++i ) {
            s << element.proX( i ) << XY_SEP << element.proY( i );
            s << ( i == Element::MAX_PROPOINTS - 1 ? FIELD_SEP : PROPOINT_SEP );
        }

        s << element.label() << '\n';

        return s;
    }

写元素就是一直向前。每一个成员后面都被写一个字段间隔符。点被写成由逗号间隔的（XY_SEP）x和y的组合，每一对由PROPOINT_SEP分隔符分隔。最后一个字段是标签和接着的换行符。

    QTextStream &operator>>( QTextStream &s, Element &element )
    {
        QString data = s.readLine();
        element.setValue( Element::INVALID );

        int errors = 0;
        bool ok;

        QStringList fields = QStringList::split( FIELD_SEP, data );
        if ( fields.count() >= 4 ) {
            double value = fields[0].toDouble( &ok );
            if ( !ok )
                errors++;
            QColor valueColor = QColor( fields[1] );
            if ( !valueColor.isValid() )
                errors++;
            int valuePattern = fields[2].toInt( &ok );
            if ( !ok )
                errors++;
            QColor labelColor = QColor( fields[3] );
            if ( !labelColor.isValid() )
                errors++;
            QStringList propoints = QStringList::split( PROPOINT_SEP, fields[4] );
            QString label = data.section( FIELD_SEP, 5 );

            if ( !errors ) {
                element.set( value, valueColor, valuePattern, label, labelColor );
                int i = 0;
                for ( QStringList::iterator point = propoints.begin();
                    i < Element::MAX_PROPOINTS && point != propoints.end();
                    ++i, ++point ) {
                    errors = 0;
                    QStringList xy = QStringList::split( XY_SEP, *point );
                    double x = xy[0].toDouble( &ok );
                    if ( !ok || x <= 0.0 || x >= 1.0 )
                        errors++;
                    double y = xy[1].toDouble( &ok );
                    if ( !ok || y <= 0.0 || y >= 1.0 )
                        errors++;
                    if ( errors )
                        x = y = Element::NO_PROPORTION;
                    element.setProX( i, x );
                    element.setProY( i, y );
                }
            }
        }

        return s;
    }

为了读取一个元素我们读取一条记录（比如一行）。我们使用QStringList::split()来把数据分成字段。因为标签中有可能包含FIELD_SEP字符，所以我们使用QString::section()来获得从最后一个字段到这一行结尾的所有文本。如果获得了足够的字段和值，颜色和样式数据是有效的，我们使用Element::set()来把这些数据写到元素中，否则我们就会设置这个元素为INVALID。然后我们对点也是这样。如果x和y比例是有效的并且在范围内，我们将会为元素设置它们。如果一个或两个比例是无效的，它们将认为值为零，这样是不合适的，所以我们将会改变无效的（和超出范围的）比例点的值为NO_PROPORTION。

我们的Element类现在足够用来存储、维护和读写元素数据了。我们也创建了一个元素矢量类型定义来存储一个元素的集合。

我们现在已经准备好通过我们的用户来生成、编辑和可视化他们的数据组来生成main.cpp和用户界面。

如果要获得更多的有关Qt的数据流工具请看QDataStream操作符格式，和任何一个被提及的和你所要存储的东西相似的Qt类的源代码。

« “大图片” | 目录 | 主体很容易 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


主体很容易

（main.cpp。）

    #include <qapplication.h>
    #include "chartform.h"

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

        QString filename;
        if ( app.argc() > 1 ) {
            filename = app.argv()[1];
            if ( !filename.endsWith( ".cht" ) )
                filename = QString::null;
        }

        ChartForm *cf = new ChartForm( filename );
        app.setMainWidget( cf );
        cf->show();
        app.connect( &app, SIGNAL(lastWindowClosed()), cf, SLOT(fileQuit()) );

        return app.exec();
    }

我们把main()函数保持得很简单，很小。我们创建一个QApplication对象并且传递给它命令行参数。我们也允许用户通过chart mychart.cht来调用程序，所以如果他们已经添加了一个文件名，我们就把它传递给构造函数。图表窗口中的大多数行为我们将在下一步进行评论。

« 数据元素 | 目录 | 实现图形用户界面 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


实现图形用户界面

The chart application

chart程序提供了通过排列在中央窗口部件周围的菜单和工具条来访问选项，和一个通常的文档在中央的风格的CanvasView。

（由chartform.h展开。）

    class ChartForm: public QMainWindow
    {
        Q_OBJECT
    public:
        enum { MAX_ELEMENTS = 100 };
        enum { MAX_RECENTFILES = 9 }; // 必须不超过9
        enum ChartType { PIE, VERTICAL_BAR, HORIZONTAL_BAR };
        enum AddValuesType { NO, YES, AS_PERCENTAGE };

        ChartForm( const QString& filename );
        ~ChartForm();

        int chartType() { return m_chartType; }
        void setChanged( bool changed = true ) { m_changed = changed; }
        void drawElements();

        QPopupMenu *optionsMenu; // 为什么是公有的？请看canvasview.cpp。

    private slots:
        void fileNew();
        void fileOpen();
        void fileOpenRecent( int index );
        void fileSave();
        void fileSaveAs();
        void fileSaveAsPixmap();
        void filePrint();
        void fileQuit();
        void optionsSetData();
        void updateChartType( QAction *action );
        void optionsSetFont();
        void optionsSetOptions();
        void helpHelp();
        void helpAbout();
        void helpAboutQt();
        void saveOptions();

    private:
        void init();
        void load( const QString& filename );
        bool okToClear();
        void drawPieChart( const double scales[], double total, int count );
        void drawVerticalBarChart( const double scales[], double total, int count );
        void drawHorizontalBarChart( const double scales[], double total, int count );

        QString valueLabel( const QString& label, double value, double total );
        void updateRecentFiles( const QString& filename );
        void updateRecentFilesMenu();
        void setChartType( ChartType chartType );

        QPopupMenu *fileMenu;
        QAction *optionsPieChartAction;
        QAction *optionsHorizontalBarChartAction;
        QAction *optionsVerticalBarChartAction;
        QString m_filename;
        QStringList m_recentFiles;
        QCanvas *m_canvas;
        CanvasView *m_canvasView;
        bool m_changed;
        ElementVector m_elements;
        QPrinter *m_printer;
        ChartType m_chartType;
        AddValuesType m_addValues;
        int m_decimalPlaces;
        QFont m_font;
    };

我们创建了一个QMainWindow的子类ChartForm。我们的子类使用了Q_OBJECT宏来支持Qt的信号和槽机制。

公有接口是很少的，被显示的图表类型能够被追溯，图表可以被标记为“changed”（这样用户在退出的时候会被提示保存），并且图表可以要求拖拽自己（drawElements()）。我们已经把选项菜单设为公有，因为我们也会把这个菜单作为画布视图的关联菜单。

QCanvas类用来绘制二维矢量图。QCanvasView类用来在一个应用程序的图形用户界面中实现一个画布的视图。我们所有的绘制操作都发生在画布上，但是事件（比如鼠标点击）却发生在画布视图中。

每一个动作都被一个私有槽实现，比如fileNew()、optionsSetData()等等。我们也需要相当多的私有函数和数据成员，当我们执行这些实现的时候，我们来看看这些。

为了方便和编译速度的原因，图表视窗的实现被分为三个文件，chartform.cpp实现图形用户界面，chartform_canvas.cpp实现画布处理和chartform_files.cpp实现文件处理。我们会依次评论每一个。

图表视窗图形用户界面

（由chartform.cpp展开。）

    #include "images/file_new.xpm"
    #include "images/file_open.xpm"

    #include "images/options_piechart.xpm"

chart中使用的所有图像是我们已经创建好并放在images子目录中的.xpm文件。

构造函数

    ChartForm::ChartForm( const QString& filename )
        : QMainWindow( 0, 0, WDestructiveClose )
...
        QAction *fileNewAction;
        QAction *fileOpenAction;
        QAction *fileSaveAction;

对于每一个用户动作我们声明了一个QAction指针。一些动作在头文件中已经声明，因为它们需要在构造函数外被参考。

大部分用户动作适用于菜单条目和工具条按钮。Qt允许用户创建一个单一的QAction而被添加到菜单和工具条中。这种方法保证了菜单条目和工具条按钮处于同步状态并且可以节省代码。

        fileNewAction = new QAction(
                "New Chart", QPixmap( file_new ),
                "&New", CTRL+Key_N, this, "new" );
        connect( fileNewAction, SIGNAL( activated() ), this, SLOT( fileNew() ) );

当我们构造一个动作时，我们给它一个名字、一个可选的图标、一个菜单文本和一个加速快捷键（或者0如果不需要加速键）。我们也可以使它成为视窗的子对象（通过this）。当用户点击一个工具条按钮或者点击一个菜单选项时，activated()信号会被发射。我们把这个信号和这个动作的槽连接起来，就是上面的程序代码中提到的fileNew()。

图表类型是互斥的：我们可以用一个饼图或一个竖直条形图或一个水平条形图。这也就是说如果用户选择了饼图菜单选项，饼图工具条按钮也必须被自动地选中，并且其它图表菜单选项和工具条按钮必须被自动地取消选择。这种行为是通过创建一个QActionGroup来实现的并且把这些图表类型动作放到这个组中。

        QActionGroup *chartGroup = new QActionGroup( this ); // Connected later
        chartGroup->setExclusive( true );

动作组成为了视窗（this）的子对象并且exlusive行为通过setExclusive()调用实现的。

        optionsPieChartAction = new QAction(
                "Pie Chart", QPixmap( options_piechart ),
                "&Pie Chart", CTRL+Key_I, chartGroup, "pie chart" );
        optionsPieChartAction->setToggleAction( true );

组中的每一个动作都以和其它动作一样的方式创建，除了动作的父对象是组而不是视窗。因为我们的图表类型动作由开/关状态，我们为它们中的每一个调用setToggleAction(TRUE)。注意我们没有连接动作，相反，稍后我们会我们会把这个组连接到一个可以使画布重画的槽。

为什么我们不马上连接这个组呢？稍后在构造函数中我们将会读取用户选项，图表类型之一。我们将会直接设置图表类型。但那时我们还没有创建画布或者有任何数据，所以我们想做的一切就是切换画布类型工具条按钮，而不是真正地画（这时还不存在的）画布。在我们设置好画布类型之后，我们将会连接这个组。

一旦我们已经创建完所有的用户动作，我们就可以创建工具条和菜单选项来允许用户调用它们。

        QToolBar* fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );
        fileNewAction->addTo( fileTools );
        fileOpenAction->addTo( fileTools );
        fileSaveAction->addTo( fileTools );
...
        fileMenu = new QPopupMenu( this );
        menuBar()->insertItem( "&File", fileMenu );
        fileNewAction->addTo( fileMenu );
        fileOpenAction->addTo( fileMenu );
        fileSaveAction->addTo( fileMenu );

工具条动作和菜单选项可以很容易地由QAction生成。

作为一个对我们的用户提供的方便，我们将会重新载入上次窗口的位置和大小并列出最近使用的文件。这是通过在程序退出的时候写出这些设置，在我们构造视窗的时候再把它们都回来实现的。

        QSettings settings;
        settings.insertSearchPath( QSettings::Windows, WINDOWS_REGISTRY );
        int windowWidth = settings.readNumEntry( APP_KEY + "WindowWidth", 460 );
        int windowHeight = settings.readNumEntry( APP_KEY + "WindowHeight", 530 );
        int windowX = settings.readNumEntry( APP_KEY + "WindowX", 0 );
        int windowY = settings.readNumEntry( APP_KEY + "WindowY", 0 );
        setChartType( ChartType(
                settings.readNumEntry( APP_KEY + "ChartType", int(PIE) ) ) );

        m_font = QFont( "Helvetica", 18, QFont::Bold );
        m_font.fromString(
                settings.readEntry( APP_KEY + "Font", m_font.toString() ) );
        for ( int i = 0; i < MAX_RECENTFILES; ++i ) {
            QString filename = settings.readEntry( APP_KEY + "File" +
                                                   QString::number( i + 1 ) );
            if ( !filename.isEmpty() )
                m_recentFiles.push_back( filename );
        }
        if ( m_recentFiles.count() )
            updateRecentFilesMenu();

QSettings类通过和平台无关的方式来处理用户设置。我们很简单地读写设置，把处理平台依赖性的问题留给QSettings来处理。insertSearchPath()调用没有做任何事，除非在Windows下被#ifdef过。

我们使用readNumEntry()调用来得到图表视窗上次的大小和位置，并且为它的第一次运行提供了默认值。图表类型是以一个整数重新获得并把它扔给CharType枚举值。我们创建默认标签字体，然后读取“Font”设置，如果需要的话我们使用刚才生成的默认字体。

尽管QSettings可以处理字符串列表，但是我们已经选择把最近使用的每一个文件作为单一的条目来存储，这样就可以更容易地处理和编辑这些设置。我们试着去读每一个可能的文件条目（从“File1”到“File9”），并把每一个非空条目添加到最近使用的文件的列表中。如果有一个或多个最近使用的文件，我们通过调用updateRecentFilesMenu()来更新File菜单，（我们将会在稍后再评论这个）。

        connect( chartGroup, SIGNAL( selected(QAction*) ),
                 this, SLOT( updateChartType(QAction*) ) );

现在我们已经设置图表类型（当我们把它作为一个用户设置读入的时候），把图表组和我们的updateChartType()槽连接起来是安全的。

        resize( windowWidth, windowHeight );
        move( windowX, windowY );

并且现在我们已经知道窗口大小和位置，我们就可以根据这些重新定义大小并移动图表视窗窗口。

        m_canvas = new QCanvas( this );
        m_canvas->resize( width(), height() );
        m_canvasView = new CanvasView( m_canvas, &m_elements, this );
        setCentralWidget( m_canvasView );
        m_canvasView->show();

我们创建一个新的QCanvas并且设置它的大小为图表视窗窗口的客户区域。我们也创建一个CanvasView（我们自己的QCanvasView的子类）来显示QCanvas。我们把这个画布视图作为图表视窗的主窗口部件并显示它。

        if ( !filename.isEmpty() )
            load( filename );
        else {
            init();
            m_elements[0].set( 20, red,    14, "Red" );
            m_elements[1].set( 70, cyan,    2, "Cyan",   darkGreen );
            m_elements[2].set( 35, blue,   11, "Blue" );
            m_elements[3].set( 55, yellow,  1, "Yellow", darkBlue );
            m_elements[4].set( 80, magenta, 1, "Magenta" );
            drawElements();
        }

如果我们有一个文件要载入，我们就载入它，否则我们就初始化我们的元素矢量并画一个示例图表。

        statusBar()->message( "Ready", 2000 );

我们在构造函数中调用statusBar()是非常重要的，因为这个调用保证了我们能够在这个主窗口中创建一个状态条。

init()

    void ChartForm::init()
    {
        setCaption( "Chart" );
        m_filename = QString::null;
        m_changed = false;

        m_elements[0]  = Element( Element::INVALID, red );
        m_elements[1]  = Element( Element::INVALID, cyan );
        m_elements[2]  = Element( Element::INVALID, blue );
...

我们使用了init()函数是因为我们想在视窗被构造的时候和无论用户载入一个存在的数据组或者创建一个新的数据组的时候初始化画布和元素（在m_elements ElementVector中）。

我们重新设置标题并设置当前文件名称为QString::null。我们也用无效的元素来组装元素矢量。这不是必需的，但是给每一个元素一个不同的颜色对于用户来讲是更方便的，因为当他们输入值的时候每一个都会已经有了一个确定的颜色（当然他们可以修改）。

文件处理动作

okToClear()

    bool ChartForm::okToClear()
    {
        if ( m_changed ) {
            QString msg;
            if ( m_filename.isEmpty() )
                msg = "Unnamed chart ";
            else
                msg = QString( "Chart '%1'\n" ).arg( m_filename );
            msg += "has been changed.";
            switch( QMessageBox::information( this, "Chart -- Unsaved Changes",
                                              msg, "&Save", "Cancel", "&Abandon",
                                              0, 1 ) ) {
                case 0:
                    fileSave();
                    break;
                case 1:
                default:
                    return false;
                    break;
                case 2:
                    break;
            }
        }

        return true;
    }

okToClear()函数用来提示用户在有没保存的数据的时候保存它们。它也被其它几个函数使用。

fileNew()

    void ChartForm::fileNew()
    {
        if ( okToClear() ) {
            init();
            drawElements();
        }
    }

当用户调用fileNew()动作时，我们调用okToClear()来给他们一个保存任何为保存的数据的机会。无论他们保存或者放弃或者没有任何为保存的数据，我们都重新初始化元素矢量并绘制默认图表。

我们是不是也应该调用optionsSetData()来弹出一个对话框，让用户通过它来创建和编辑值、颜色等等呢？你可以运行一下现在的应用程序，然后试着把optionsSetData()的调用添加进去后再运行并观察它们来决定你更喜欢哪一个。

fileOpen()

    void ChartForm::fileOpen()
    {
        if ( !okToClear() )
            return;

        QString filename = QFileDialog::getOpenFileName(
                                QString::null, "Charts (*.cht)", this,
                                "file open", "Chart -- File Open" );
        if ( !filename.isEmpty() )
            load( filename );
        else
            statusBar()->message( "File Open abandoned", 2000 );
    }

我们检查它是否是okToClear()。如果是的话，我们使用静态的QFileDialog::getOpenFileName()函数来获得用户想要载入的文件的名称。如果我们得到一个文件名，我们就调用load()。

fileSaveAs()

    void ChartForm::fileSaveAs()
    {
        QString filename = QFileDialog::getSaveFileName(
                                QString::null, "Charts (*.cht)", this,
                                "file save as", "Chart -- File Save As" );
        if ( !filename.isEmpty() ) {
            int answer = 0;
            if ( QFile::exists( filename ) )
                answer = QMessageBox::warning(
                                this, "Chart -- Overwrite File",
                                QString( "Overwrite\n\'%1\'?" ).
                                    arg( filename ),
                                "&Yes", "&No", QString::null, 1, 1 );
            if ( answer == 0 ) {
                m_filename = filename;
                updateRecentFiles( filename );
                fileSave();
                return;
            }
        }
        statusBar()->message( "Saving abandoned", 2000 );
    }

这个函数调用了静态的QFileDialog::getSaveFileName()来得到一个要保存数据的文件的明处那个。如果文件存在，我们使用使用一个QMessageBox::warning()来提醒用户并给他们一个放弃保存的选择。如果文件被保存了我们就更新最近打开的文件列表并调用fileSave()（在文件处理中）来执行存储。

管理最近打开文件的列表

        QStringList m_recentFiles;

我们用一个字符串列表来处理这个最近打开文件的列表。

    void ChartForm::updateRecentFilesMenu()
    {
        for ( int i = 0; i < MAX_RECENTFILES; ++i ) {
            if ( fileMenu->findItem( i ) )
                fileMenu->removeItem( i );
            if ( i < int(m_recentFiles.count()) )
                fileMenu->insertItem( QString( "&%1 %2" ).
                                        arg( i + 1 ).arg( m_recentFiles[i] ),
                                      this, SLOT( fileOpenRecent(int) ),
                                      0, i );
        }
    }

无论用户打开一个存在的文件或者保存一个新文件的时候，这个函数会被调用（通常是通过updateRecentFiles()）。对于这个字符串列表中的每一个文件我们都插入一个新的菜单条目。我们在每一个文件名的前面都加上一个从1到9带下划线的数字，这样就可以支持键盘操作（比如，Alt+F，2就可以打开列表中的第二个文件）。我们给每一个菜单条目一个和它们在字符串列表中的索引位置相同的数值作为id，并且把每一个菜单条目都和fileOpenRecent()槽相连。老的文件菜单条目会在每一个最新的文件菜单条目id来到的同时被删除。它会工作是因为其它文件菜单条目都有一个由Qt生成的id（它们都是<0的），然而我们所创建的菜单条目的id都是>=0的。

    void ChartForm::updateRecentFiles( const QString& filename )
    {
        if ( m_recentFiles.find( filename ) != m_recentFiles.end() )
            return;

        m_recentFiles.push_back( filename );
        if ( m_recentFiles.count() > MAX_RECENTFILES )
            m_recentFiles.pop_front();

        updateRecentFilesMenu();
    }

当用户打开一个存在的文件或者保存一个新文件的时候，它会被调用。如果文件已经存在于列表中，它就会很简单地返回。否则这个文件会被添加到列表的末尾并且如果列表太大（>9个文件）的话，第一个（最老的）就会被移去。然后updateRecentFilesMenu()被调用来在File菜单中重新创建最近使用的文件列表。

    void ChartForm::fileOpenRecent( int index )
    {
        if ( !okToClear() )
            return;

        load( m_recentFiles[index] );
    }

当用户选择了一个最近打开的文件时，fileOpenRecent()槽会伴随一个用户选择的文件的菜单id而被调用。因为我们使文件菜单的id和文件在m_recentFiles列表中的索引位置相等，我们就可以很简单的通过文件的菜单条目id来载入了。

退出

    void ChartForm::fileQuit()
    {
        if ( okToClear() ) {
            saveOptions();
            qApp->exit( 0 );
        }
    }

当用户退出时，我们给他们保存任何未保存数据的机会（okToClear()），然后在结束之前保存它们的选项，比如窗口的大小和位置、图表类型等等。

    void ChartForm::saveOptions()
    {
        QSettings settings;
        settings.insertSearchPath( QSettings::Windows, WINDOWS_REGISTRY );
        settings.writeEntry( APP_KEY + "WindowWidth", width() );
        settings.writeEntry( APP_KEY + "WindowHeight", height() );
        settings.writeEntry( APP_KEY + "WindowX", x() );
        settings.writeEntry( APP_KEY + "WindowY", y() );
        settings.writeEntry( APP_KEY + "ChartType", int(m_chartType) );
        settings.writeEntry( APP_KEY + "AddValues", int(m_addValues) );
        settings.writeEntry( APP_KEY + "Decimals", m_decimalPlaces );
        settings.writeEntry( APP_KEY + "Font", m_font.toString() );
        for ( int i = 0; i < int(m_recentFiles.count()); ++i )
            settings.writeEntry( APP_KEY + "File" + QString::number( i + 1 ),
                                 m_recentFiles[i] );
    }

直接使用QSettings来保存用户选项。

自定义对话框

我们想让用户可以手工地设置一些选项并且创建和编辑值、值颜色等等。

    void ChartForm::optionsSetOptions()
    {
        OptionsForm *optionsForm = new OptionsForm( this );
        optionsForm->chartTypeComboBox->setCurrentItem( m_chartType );
        optionsForm->setFont( m_font );

        if ( optionsForm->exec() ) {
            setChartType( ChartType(
                    optionsForm->chartTypeComboBox->currentItem()) );
            m_font = optionsForm->font();

            drawElements();
        }
        delete optionsForm;
    }

设置选项的视窗是由我们自定义的OptionsForm提供的，在设置选项中。这个选项视窗是一个标准的“哑的”对话框：我们创建一个实例，把所有的图形用户界面元素都和所有相关的设置都组装起来，并且如果用户点击了“OK”（exec()返回一个真值）我们就会从图形用户界面元素中读取设置。

    void ChartForm::optionsSetData()
    {
        SetDataForm *setDataForm = new SetDataForm( &m_elements, m_decimalPlaces, this );
        if ( setDataForm->exec() ) {
            m_changed = true;
            drawElements();
        }
        delete setDataForm;
    }

创建和编辑图表数据的视窗由我们自定义的SetDataForm提供，在获得数据中。这个视窗是一个“聪明的”对话框。我们传入我们想要使用的数据结构，并且对话框可以自己处理数据机构的表达。如果用户点击“OK”，对话框会更新数据结构并且exec()会返回一个真值。如果用户改变了数据时我们在optionsSetData()中所要做的时把图表标记为changed并调用drawElements()来使用新的和更新过的数据来重新绘制图表。

« 主体很容易 | 目录 | 画布控制 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


画布控制

我们在画布上画饼形区域（或者条形图表条），和所有的标签。画布是通过画布视图来呈现给用户的。drawElements()函数被调用从而在需要的时候重新绘制画布。

（由chartform_canvas.cpp展开。）

drawElements()

    void ChartForm::drawElements()
    {
        QCanvasItemList list = m_canvas->allItems();
        for ( QCanvasItemList::iterator it = list.begin(); it != list.end(); ++it )
            delete *it;

我们在drawElements()中所作的第一件事是删除所有已经存在的画布条目。

            // 360 * 16为一个饼形，Qt中使用的是16倍的度数（就是它的一个圆周为360x16）
        int scaleFactor = m_chartType == PIE ? 5760 :
                            m_chartType == VERTICAL_BAR ? m_canvas->height() :
                                m_canvas->width();

接下来我们根据要绘制的图表的种类来计算比例因子。

        double biggest = 0.0;
        int count = 0;
        double total = 0.0;
        static double scales[MAX_ELEMENTS];

        for ( int i = 0; i < MAX_ELEMENTS; ++i ) {
            if ( m_elements[i].isValid() ) {
                double value = m_elements[i].value();
                count++;
                total += value;
                if ( value > biggest )
                    biggest = value;
                scales[i] = m_elements[i].value() * scaleFactor;
            }
        }

        if ( count ) {
                // 第二个循环是因为总量和最大的
            for ( int i = 0; i < MAX_ELEMENTS; ++i )
                if ( m_elements[i].isValid() )
                    if ( m_chartType == PIE )
                        scales[i] = (m_elements[i].value() * scaleFactor) / total;
                    else
                        scales[i] = (m_elements[i].value() * scaleFactor) / biggest;

我们需要知道这里有多少值、最大的值和值的总和，这样我们就可以正确地按比例创建饼形区域或条形了。我们把比例值存放在scales数组中。

            switch ( m_chartType ) {
                case PIE:
                    drawPieChart( scales, total, count );
                    break;
                case VERTICAL_BAR:
                    drawVerticalBarChart( scales, total, count );
                    break;
                case HORIZONTAL_BAR:
                    drawHorizontalBarChart( scales, total, count );
                    break;
            }
        }

既然我们已经知道了必需的信息，那我们就调用相关绘制函数，传递比例值、总量和计数。

        m_canvas->update();

最终我们使用update()更新画布来使所有的变化可视。

drawHorizontalBarChart()

我们来回顾一下刚才的这个绘制函数，看到了画布条目如何被生成并放置到画布上，因为这个教程是关于Qt的，而不是关于绘制图表的好的（或者坏的）算法。

    void ChartForm::drawHorizontalBarChart(
            const double scales[], double total, int count )
    {

画水平条形图我们需要一个比例值的数组、总量（这样我们就可以在需要的时候计算并且画出百分比）和这一组值的计数。

        double width = m_canvas->width();
        double height = m_canvas->height();
        int proheight = int(height / count);
        int y = 0;

我们重新得到画布的宽度和高度并且计算比例高度（proheight）。我们把初始的y位置设为0。

        QPen pen;
        pen.setStyle( NoPen );

我们创建一个用来绘制每一个条形（矩形）的画笔，我们把它设置为NoPen，这样就不会画出边框。

        for ( int i = 0; i < MAX_ELEMENTS; ++i ) {
            if ( m_elements[i].isValid() ) {
                int extent = int(scales[i]);

我们在元素矢量中迭代每一个元素，忽略无效的元素。每个条的宽度（它的长度）很简单地就是它的比例值。

                QCanvasRectangle *rect = new QCanvasRectangle(
                                                0, y, extent, proheight, m_canvas );
                rect->setBrush( QBrush( m_elements[i].valueColor(),
                                        BrushStyle(m_elements[i].valuePattern()) ) );
                rect->setPen( pen );
                rect->setZ( 0 );
                rect->show();

我们为每个条形创建一个新的QCanvasRectangle，它的x位置为0（因为这是一个水平条形图，每个条形都从左边开始），y值从0开始，随着每一个要画的条形的高度增长，一直到我们要画的条形和画布的高度。然后我们设置条形的画刷为用户为元素指定的颜色和样式，设置画笔为我们先前生成的画笔（比如，设置为NoPen）并且我们把条形的Z轴顺序设置为0。最后我们调用show()在画布上绘制条形。

                QString label = m_elements[i].label();
                if ( !label.isEmpty() || m_addValues != NO ) {
                    double proX = m_elements[i].proX( HORIZONTAL_BAR );
                    double proY = m_elements[i].proY( HORIZONTAL_BAR );
                    if ( proX < 0 || proY < 0 ) {
                        proX = 0;
                        proY = y / height;
                    }

如果用户已经为元素指定了标签或者要求把值（或者百分比）显示出来，我们也要画一个画布文本条目。我们创建我们自己的CanvasText类（请看后面），因为我们想存储每一个画布文本条目中对应元素的索引（在元素矢量中）。我们从元素中得出x和y的比例值。如果其中之一< 0，那么他们还没有被用户定位，所以你必须计算它们的位置。我们标签的x值为0（左）并且y值为条形图的顶部（这样标签的左上角就会在x,y位置）。

                    label = valueLabel( label, m_elements[i].value(), total );

然后我们调用一个助手函数valueLabel()，它可以返回一个包含标签文本的字符串。（如果用户已经设置相应的选项，valueLabel()函数添加值或者百分比到这个文本的标签。）

                    CanvasText *text = new CanvasText( i, label, m_font, m_canvas );
                    text->setColor( m_elements[i].labelColor() );
                    text->setX( proX * width );
                    text->setY( proY * height );
                    text->setZ( 1 );
                    text->show();
                    m_elements[i].setProX( HORIZONTAL_BAR, proX );
                    m_elements[i].setProY( HORIZONTAL_BAR, proY );

然后我们创建一个CanvasText条目，传递给它在元素矢量中这个元素的索引和所要使用的标签、字体和画布。我们设置文本条目的颜色为用户指定的颜色并且设置条目的x和y位置和画布的宽高成比例。我们设置Z轴顺序为1，这样文本条目总是在条形（Z轴顺序为0）的上面（前面）。我们调用show()函数在画布上绘制文本条目，并且设置元素的相对x和y位置。

                }
                y += proheight;

在绘制完条形和可能存在的标签之后，我们给y增加一定比例的高度用来准备绘制下一个元素。

            }
        }
    }

QCanvasText的子类

（由canvastext.h展开。）

    class CanvasText : public QCanvasText
    {
    public:
        enum { CANVAS_TEXT = 1100 };

        CanvasText( int index, QCanvas *canvas )
            : QCanvasText( canvas ), m_index( index ) {}
        CanvasText( int index, const QString& text, QCanvas *canvas )
            : QCanvasText( text, canvas ), m_index( index ) {}
        CanvasText( int index, const QString& text, QFont font, QCanvas *canvas )
            : QCanvasText( text, font, canvas ), m_index( index ) {}

        int index() const { return m_index; }
        void setIndex( int index ) { m_index = index; }

        int rtti() const { return CANVAS_TEXT; }

    private:
        int m_index;
    };

我们的CanvasText子类是QCanvasText的一个非常简单的特化。我们所做的一切只是添加一个私有成员m_index，它用来保存和这个文本相关的元素的元素矢量索引，并且提供为这个值提供一个读和写函数。

QCanvasView的子类

（由canvasview.h展开。）

    class CanvasView : public QCanvasView
    {
        Q_OBJECT
    public:
        CanvasView( QCanvas *canvas, ElementVector *elements,
                    QWidget* parent = 0, const char* name = "canvas view",
                    WFlags f = 0 )
            : QCanvasView( canvas, parent, name, f ),
              m_elements( elements ) {}

    protected:
        void viewportResizeEvent( QResizeEvent *e );
        void contentsMousePressEvent( QMouseEvent *e );
        void contentsMouseMoveEvent( QMouseEvent *e );
        void contentsContextMenuEvent( QContextMenuEvent *e );

    private:
        QCanvasItem *m_movingItem;
        QPoint m_pos;
        ElementVector *m_elements;
    };

我们需要继承QCanvasView，这样我们就能处理：

  1. 上下文菜单请求。
  2. 视窗重定义大小。
  3. 用户拖拽标签到任意位置。

为了支持这些，我们存储一个到正在被移动的画布条目的指针和它的最终位置。我们也存储一个到元素矢量的指针。

上下文菜单请求

（由canvasview.cpp展开。）

    void CanvasView::contentsContextMenuEvent( QContextMenuEvent * )
    {
        ((ChartForm*)parent())->optionsMenu->exec( QCursor::pos() );
    }

当用户调用一个上下文菜单（比如在绝大多数平台通过右键点击），我们把画布视图的父对象（是一个ChartForm）转化为正确的类型，然后用exec()在光标位置执行选项菜单。

视窗重定义大小

    void CanvasView::viewportResizeEvent( QResizeEvent *e )
    {
        canvas()->resize( e->size().width(), e->size().height() );
        ((ChartForm*)parent())->drawElements();
    }

为了改变大小我们简单地改变花布的大小，画布视图就会呈现在视窗客户端区域的宽高中，然后调用drawElements()函数来重新绘制图表。因为drawElements()画的每一件都和画布的宽高有关，所以图表就会被正确地绘制。

拖拽标签到任意位置

当用户想把标签拖拽到他们点击的位置时，就应该拖拽它并在新的位置释放它。

    void CanvasView::contentsMousePressEvent( QMouseEvent *e )
    {
        QCanvasItemList list = canvas()->collisions( e->pos() );
        for ( QCanvasItemList::iterator it = list.begin(); it != list.end(); ++it )
            if ( (*it)->rtti() == CanvasText::CANVAS_TEXT ) {
                m_movingItem = *it;
                m_pos = e->pos();
                return;
            }
        m_movingItem = 0;
    }

当用户点击鼠标时，我们创建一个鼠标点击“碰撞”（如果有的话）的画布条目的列表。然后我们迭代这个列表并且如果我们发现一个CanvasText条目，我们就把它设置为移动的条目并且记录下它的位置。否则我们设置为不移动条目。

    void CanvasView::contentsMouseMoveEvent( QMouseEvent *e )
    {
        if ( m_movingItem ) {
            QPoint offset = e->pos() - m_pos;
            m_movingItem->moveBy( offset.x(), offset.y() );
            m_pos = e->pos();
            ChartForm *form = (ChartForm*)parent();
            form->setChanged( true );
            int chartType = form->chartType();
            CanvasText *item = (CanvasText*)m_movingItem;
            int i = item->index();
            (*m_elements)[i].setProX( chartType, item->x() / canvas()->width() );
            (*m_elements)[i].setProY( chartType, item->y() / canvas()->height() );
            canvas()->update();
        }
    }

当用户拖拽鼠标的时候，移动事件就产生了。如果那里是一个可移动条目，我们从鼠标最后的位置和可移动条目原来的位置计算出位移。我们将新的位置记录为最后的位置。因为图表现在改变了，所以我们调用setChanged()，这样当用户试图退出或者读入已存在的图表时或者创建新的图表，就会被提示是否保存。我们也分别地更新当前图表类型的元素的x和y的比例位置为当前x和y与宽和高的比例。我们知道要更新哪个元件因为当我们创建每个画布文本条目的时候，我们传给它一个这个元素所对应的位置索引。我们继承了QCanvasText，这样我们就可以设置和读取这个索引值。最后我们调用update()来重绘画布。

QCanvas没有任何视觉效果。为了看到画布的内容，你必须创建一个QCanvasView来呈现画布。如果条目被show()显示，它们就会出现在画布视图中，然后，只有当QCanvas::update()被调用的时候。默认情况下QCanva的背景是白色，并且会在画布上绘制默认的形状，比如QCanvasRectangle、QCanvasEllipse等等，因为它们被白色填充，所以非常推荐使用一个非白色的画刷颜色！

« 实现图形用户界面 | 目录 | 文件处理 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


文件处理

（从chartform_files.cpp展开。）

读图表数据

    void ChartForm::load( const QString& filename )
    {
        QFile file( filename );
        if ( !file.open( IO_ReadOnly ) ) {
            statusBar()->message( QString( "Failed to load \'%1\'" ).
                                    arg( filename ), 2000 );
            return;
        }

        init(); // 确保我们拥有颜色
        m_filename = filename;
        QTextStream ts( &file );
        Element element;
        int errors = 0;
        int i = 0;
        while ( !ts.eof() ) {
            ts >> element;
            if ( element.isValid() )
                m_elements[i++] = element;

        file.close();

        setCaption( QString( "Chart -- %1" ).arg( filename ) );
        updateRecentFiles( filename );

        drawElements();
        m_changed = false;
    }

载入数据组非常容易。我们打开文件并且创建一个文本流。当有数据要读的时候，我们把一个元素读入到element并且如果它是有效的，我们就把它插入到m_elements矢量。所有的细节都由Element类来处理。然后我们关闭文件并且更新标题和最近打开的文件列表。最后我们绘制图表并标明它没有被改变。

写图表数据

    void ChartForm::fileSave()
    {

        QFile file( m_filename );
        if ( !file.open( IO_WriteOnly ) ) {
            statusBar()->message( QString( "Failed to save \'%1\'" ).
                                    arg( m_filename ), 2000 );
            return;
        }
        QTextStream ts( &file );
        for ( int i = 0; i < MAX_ELEMENTS; ++i )
            if ( m_elements[i].isValid() )
                ts << m_elements[i];

        file.close();

        setCaption( QString( "Chart -- %1" ).arg( m_filename ) );
        statusBar()->message( QString( "Saved \'%1\'" ).arg( m_filename ), 2000 );
        m_changed = false;
    }

保存数据一样地容易。我们打开文件并且创建一个文本流。然后我们把每一个有效元素写到文本留中。所有的细节都由Element类来处理。

« 画布控制 | 目录 | 获得数据 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


获得数据

The set data dialog

设置数据对话框允许用户添加和编辑值，并且可以选择用来显示值的颜色和样式。用户可以可以输入标签文本并为每一个标签选择一个标签颜色。

（由setdataform.h展开。）

    class SetDataForm: public QDialog
    {
        Q_OBJECT
    public:
        SetDataForm( ElementVector *elements, int decimalPlaces,
                     QWidget *parent = 0, const char *name = "set data form",
                     bool modal = TRUE, WFlags f = 0 );
        ~SetDataForm() {}

    public slots:
        void setColor();
        void setColor( int row, int col );
        void currentChanged( int row, int col );
        void valueChanged( int row, int col );

    protected slots:
        void accept();

    private:
        QTable *table;
        QPushButton *colorPushButton;
        QPushButton *okPushButton;
        QPushButton *cancelPushButton;

    protected:
        QVBoxLayout *tableButtonBox;
        QHBoxLayout *buttonBox;

    private:
        ElementVector *m_elements;
        int m_decimalPlaces;
    };

头文件很简单。构造函数中用一个指针指向元素矢量，这样这个“聪明的”对话框就可以直接显示并且编辑数据。我们将会解释我们在实现中所看到的槽的。

（由setdataform.cpp展开。）

    #include "images/pattern01.xpm"
    #include "images/pattern02.xpm"

我们创建了一个小的.XPM图片用来显示Qt支持的每一种画刷样式。我们将会在样式组合框中使用这些的。

构造函数

    SetDataForm::SetDataForm( ElementVector *elements, int decimalPlaces,
                              QWidget* parent,  const char* name,
                              bool modal, WFlags f )
        : QDialog( parent, name, modal, f )

    {
        m_elements = elements;
        m_decimalPlaces = decimalPlaces;

我们传递了绝大部分参数到QDialog超类中。我们把元素矢量指针和所要显示的小数点位数赋给成员变量，这样它们就可以被所有的SetDataForm的成员函数访问了。

        setCaption( "Chart -- Set Data" );
        resize( 540, 440 );

我们为对话框设置一个标题并且重定义它的大小。

        tableButtonBox = new QVBoxLayout( this, 11, 6, "table button box layout" );

这个视窗的布局相当简单。按钮被组织在一个水平的布局中并且表和这个按钮布局通过使用tableButtonBox布局被竖直地组织在一起。

        table = new QTable( this, "data table" );
        table->setNumCols( 5 );
        table->setNumRows( ChartForm::MAX_ELEMENTS );
        table->setColumnReadOnly( 1, true );
        table->setColumnReadOnly( 2, true );
        table->setColumnReadOnly( 4, true );
        table->setColumnWidth( 0, 80 );
        table->setColumnWidth( 1, 60 ); // Columns 1 and 4 must be equal
        table->setColumnWidth( 2, 60 );
        table->setColumnWidth( 3, 200 );
        table->setColumnWidth( 4, 60 );
        QHeader *th = table->horizontalHeader();
        th->setLabel( 0, "Value" );
        th->setLabel( 1, "Color" );
        th->setLabel( 2, "Pattern" );
        th->setLabel( 3, "Label" );
        th->setLabel( 4, "Color" );
        tableButtonBox->addWidget( table );

我们创建一个有五列的新的QTable，并且它的行数和元素矢量中的元素个数相同。我们让颜色和样式列只读：这是为了防止用户在这些地方输入。我们将通过让用户在颜色上点击或者定位到颜色上并且点击Color按钮时可以修改颜色。样式被放在一个组合框中，很简单地通过用户选择一个不同地样式就可以改变它。接下来我们设置合适地初始宽度，为每一列插入标签并且最后把这个表添加到tableButtonBox布局中。

        buttonBox = new QHBoxLayout( 0, 0, 6, "button box layout" );

我们创建一个水平盒子布局用来保存按钮。

        colorPushButton = new QPushButton( this, "color button" );
        colorPushButton->setText( "&Color..." );
        colorPushButton->setEnabled( false );
        buttonBox->addWidget( colorPushButton );

我们创建一个color按钮并把它添加到buttonBox布局中。我们让这个按钮失效，只有当焦点在一个颜色单元格时，我们才会让它有效。

        QSpacerItem *spacer = new QSpacerItem( 0, 0, QSizePolicy::Expanding,
                                                     QSizePolicy::Minimum );
        buttonBox->addItem( spacer );

因为我们想把color按钮和OK以及Cancel按钮分开，接下来我们创建一个间隔并把它添加到buttonBox布局中。

        okPushButton = new QPushButton( this, "ok button" );
        okPushButton->setText( "OK" );
        okPushButton->setDefault( TRUE );
        buttonBox->addWidget( okPushButton );

        cancelPushButton = new QPushButton( this, "cancel button" );
        cancelPushButton->setText( "Cancel" );
        cancelPushButton->setAccel( Key_Escape );
        buttonBox->addWidget( cancelPushButton );

OK和Cancel按钮被创建了并被添加到buttonBox。我们让OK按钮为这个对话框的默认按钮，并且我们为Cancel按钮提供了一个Esc加速键。

        tableButtonBox->addLayout( buttonBox );

我们把buttonBox布局添加到tableButtonBox中，并且这个布局也是完整的。

        connect( table, SIGNAL( clicked(int,int,int,const QPoint&) ),
                 this, SLOT( setColor(int,int) ) );
        connect( table, SIGNAL( currentChanged(int,int) ),
                 this, SLOT( currentChanged(int,int) ) );
        connect( table, SIGNAL( valueChanged(int,int) ),
                 this, SLOT( valueChanged(int,int) ) );
        connect( colorPushButton, SIGNAL( clicked() ), this, SLOT( setColor() ) );
        connect( okPushButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
        connect( cancelPushButton, SIGNAL( clicked() ), this, SLOT( reject() ) );

现在我们来演习一下这个视窗。

  • 如果用户点击了一个单元格，我们调用setColor()槽，它会检查这个单元格是否保存一个颜色，如果是的，将会调用颜色对话框。
  • 我们把QTable的currentChanged()信号和我们的currentChanged()槽连接起来了，举例来说，这将被用在根据用户现在所在的列来决定使color按钮有效/失效。
  • 我们把表格的valueChanged()和我们的valueChanged()槽连接起来了，我们将会用这个来显示带有正确的小数位数的值。
  • 如果用户点击Color按钮，我们就调用setColor()槽。
  • OK按钮被连接到accept()槽，我们将会在这个槽里面更新元素矢量。
  • Cancel按钮被连接到QDialog的reject()槽，并且这部分中不再需要更多的代码和动作。

        QPixmap patterns[MAX_PATTERNS];
        patterns[0]  = QPixmap( pattern01 );
        patterns[1]  = QPixmap( pattern02 );

我们为每一个画刷样式创建了一个图片并且把它们存储在patterns数组中。

        QRect rect = table->cellRect( 0, 1 );
        QPixmap pix( rect.width(), rect.height() );

我们每一个颜色单元格所占用的矩形并创建一个这样大小的空白图片。

        for ( int i = 0; i < ChartForm::MAX_ELEMENTS; ++i ) {
            Element element = (*m_elements)[i];

            if ( element.isValid() )
                table->setText(
                    i, 0,
                    QString( "%1" ).arg( element.value(), 0, 'f',
                                         m_decimalPlaces ) );

            QColor color = element.valueColor();
            pix.fill( color );
            table->setPixmap( i, 1, pix );
            table->setText( i, 1, color.name() );

            QComboBox *combobox = new QComboBox;
            for ( int j = 0; j < MAX_PATTERNS; ++j )
                combobox->insertItem( patterns[j] );
            combobox->setCurrentItem( element.valuePattern() - 1 );
            table->setCellWidget( i, 2, combobox );

            table->setText( i, 3, element.label() );

            color = element.labelColor();
            pix.fill( color );
            table->setPixmap( i, 4, pix );
            table->setText( i, 4, color.name() );

对于元素矢量中的每一个元素，我们必须填充表格。

如果元素是有效的，我们把它的值写在第一列（0列，Value），根据指定的小数点位数进行格式化。

我们读元素的值颜色并用这种颜色填充空白图片，然后我们让颜色单元格显示这个图片。我们需要能够在以后读到这个颜色（比如用户改变了颜色）。一个方法就是测试图片中的一个像素，另一个就是继承QTableItem（和我们继承CanvasText类似）并且在里面存储这个颜色。但是我们用了一个简单的方法：我们设置这个单元格的文本为这个颜色的名字。

接下来我们用样式来填充样式组合框。我们将通过使用被选择的样式在组合框中的位置来决定用户选择了哪一个样式。QTable可以利用QComboTableItem条目，但是只支持文本，所以我们使用setCellWidget()来代替把QComboBox的插入到表中。

接下来我们插入元素的标签。最后我们用我们设置值颜色的方法来设置标签颜色。

槽

    void SetDataForm::currentChanged( int row, int col )
    {
        colorPushButton->setEnabled( col == 1 || col == 4 );
        if ( col == 2 )
            ((QComboBox*)table->cellWidget( row, col ))->popup();
    }

当用户进行定位时，表的currentChanged()信号被发射。如果用户进入1或4列时（值颜色或标签颜色），我们让colorPushButton生效，否则让它失效。

为了给键盘用户提供方便，如果用户定位到样式组合框中时，我们弹出它。

    void SetDataForm::valueChanged( int row, int col )
    {
        if ( col == 0 ) {
            bool ok;
            double d = table->text( row, col ).toDouble( &ok );
            if ( ok && d > EPSILON )
                table->setText(
                    row, col, QString( "%1" ).arg(
                                d, 0, 'f', m_decimalPlaces ) );
            else
                table->setText( row, col, table->text( row, col ) + "?" );
        }
    }

如果用户改变值，我们必须使用正确的小数位数对它进行格式化，或者指出它是无效的。

    void SetDataForm::setColor()
    {
        setColor( table->currentRow(), table->currentColumn() );
        table->setFocus();
    }

如果用户按下Color按钮，我们调用另一个setColor()函数并把焦点返回到表中。

    void SetDataForm::setColor( int row, int col )
    {
        if ( !( col == 1 || col == 4 ) )
            return;

        QColor color = QColorDialog::getColor(
                            QColor( table->text( row, col ) ),
                            this, "color dialog" );
        if ( color.isValid() ) {
            QPixmap pix = table->pixmap( row, col );
            pix.fill( color );
            table->setPixmap( row, col, pix );
            table->setText( row, col, color.name() );
        }
    }

如果当焦点在一个颜色单元格中时这个函数被调用，我们调用静态的QColorDialog::getColor()对话框来获得用户所选择的颜色。如果他们选择了一个颜色，我们就用这种颜色来填充颜色单元格的图片，并且设置单元格的文本为新的颜色的名称。

    void SetDataForm::accept()
    {
        bool ok;
        for ( int i = 0; i < ChartForm::MAX_ELEMENTS; ++i ) {
            Element &element = (*m_elements)[i];
            double d = table->text( i, 0 ).toDouble( &ok );
            if ( ok )
                element.setValue( d );
            else
                element.setValue( Element::INVALID );
            element.setValueColor( QColor( table->text( i, 1 ) ) );
            element.setValuePattern(
                    ((QComboBox*)table->cellWidget( i, 2 ))->currentItem() + 1 );
            element.setLabel( table->text( i, 3 ) );
            element.setLabelColor( QColor( table->text( i, 4 ) ) );
        }

        QDialog::accept();
    }

如果用户点击OK，我们必须更新元素矢量。我们对矢量进行迭代并把每一个元素的值设置为用户输入的值，否则如果值是无效的就设置为INVALID。我们通过颜色的名称作为参数临时构造一个QColor来设置值颜色和标签颜色。样式被设置为样式组合框的当前条目与1的偏移量（因为我们的样式数字是从1开始的，但是组合框的条目是从0开始索引的）。

最后我们调用QDialog::accept()。

« 文件处理 | 目录 | 设置选项 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


设置选项

The options dialog

我们提供了一个选项对话框，这样用户就可以在一个地方对所有的数据组设置选项。

（由optionsform.h展开。）

    class OptionsForm : public QDialog
    {
        Q_OBJECT
    public:
        OptionsForm( QWidget* parent = 0, const char* name = "options form",
                     bool modal = FALSE, WFlags f = 0 );
        ~OptionsForm() {}

        QFont font() const { return m_font; }
        void setFont( QFont font );

        QLabel *chartTypeTextLabel;
        QComboBox *chartTypeComboBox;
        QPushButton *fontPushButton;
        QLabel *fontTextLabel;
        QFrame *addValuesFrame;
        QButtonGroup *addValuesButtonGroup;
        QRadioButton *noRadioButton;
        QRadioButton *yesRadioButton;
        QRadioButton *asPercentageRadioButton;
        QLabel *decimalPlacesTextLabel;
        QSpinBox *decimalPlacesSpinBox;
        QPushButton *okPushButton;
        QPushButton *cancelPushButton;

    protected slots:
        void chooseFont();

    protected:
        QVBoxLayout *optionsFormLayout;
        QHBoxLayout *chartTypeLayout;
        QHBoxLayout *fontLayout;
        QVBoxLayout *addValuesFrameLayout;
        QVBoxLayout *addValuesButtonGroupLayout;
        QHBoxLayout *decimalPlacesLayout;
        QHBoxLayout *buttonsLayout;

    private:
        QFont m_font;
    };

这个对话框的布局比设置数据视窗要更复杂一些，但是我们只需要一个单一的槽。不像“聪明的”设置数据视窗那样，这是一个“哑的”对话框，它只向窗口部件的调用者提供了读和写。调用者有责任基于用户所作的改变更新事物。

（由optionsform.cpp展开。）

    #include "images/options_horizontalbarchart.xpm"
    #include "images/options_piechart.xpm"
    #include "images/options_verticalbarchart.xpm"

我们包含了一些在图表类型组合框中要使用的图片。

构造函数

    OptionsForm::OptionsForm( QWidget* parent, const char* name,
                              bool modal, WFlags f )
        : QDialog( parent, name, modal, f )
    {
        setCaption( "Chart -- Options" );
        resize( 320, 290 );

我们把所有的参数传递给QDialog构造函数，设置一个题目并且设置一个初始大小。

视窗的布局将是一个包含图表类型标签和组合框的水平盒子布局，并且对于字体按钮和字体标签、小数点位置标签和微调框也是相似的。按钮也会被放在一个水平布局中，但是还会有一个间隔来把它们移到右边。显示值的单选按钮将会竖直地排列在一个框架中。所有地这些都被放在一个竖直盒子布局中。

        optionsFormLayout = new QVBoxLayout( this, 11, 6 );

所有的窗口部件都被放在视窗的竖直盒子布局中。

        chartTypeLayout = new QHBoxLayout( 0, 0, 6 );

图表类型标签和组合框将被并排放置。

        chartTypeTextLabel = new QLabel( "&Chart Type", this );
        chartTypeLayout->addWidget( chartTypeTextLabel );

        chartTypeComboBox = new QComboBox( false, this );
        chartTypeComboBox->insertItem( QPixmap( options_piechart ), "Pie Chart" );
        chartTypeComboBox->insertItem( QPixmap( options_verticalbarchart ),
                                       "Vertical Bar Chart" );
        chartTypeComboBox->insertItem( QPixmap( options_horizontalbarchart ),
                                       "Horizontal Bar Chart" );
        chartTypeLayout->addWidget( chartTypeComboBox );
        optionsFormLayout->addLayout( chartTypeLayout );

我们创建图表类型标签（带有一个加速键，稍后我们会把它和图表类型组合框联系起来）。我们也创建一个图表类型组合框，用图片和文本来填充它。我们把它们两个添加到水平布局中，并把水平布局添加到视窗的竖直布局中。

        fontLayout = new QHBoxLayout( 0, 0, 6 );

        fontPushButton = new QPushButton( "&Font...", this );
        fontLayout->addWidget( fontPushButton );
        QSpacerItem* spacer = new QSpacerItem( 0, 0,
                                               QSizePolicy::Expanding,
                                               QSizePolicy::Minimum );
        fontLayout->addItem( spacer );

        fontTextLabel = new QLabel( this ); // 必须由调用者通过setFont()来设置
        fontLayout->addWidget( fontTextLabel );
        optionsFormLayout->addLayout( fontLayout );

我们创建一个水平盒子布局用来保存字体按钮和字体标签。字体按钮是被直接加入的。我们添加了一个间隔用来增加效果。字体文本标签被初始化为空（因为我们不知道用户正在使用什么字体）。

        addValuesFrame = new QFrame( this );
        addValuesFrame->setFrameShape( QFrame::StyledPanel );
        addValuesFrame->setFrameShadow( QFrame::Sunken );
        addValuesFrameLayout = new QVBoxLayout( addValuesFrame, 11, 6 );

        addValuesButtonGroup = new QButtonGroup( "Show Values", addValuesFrame );
        addValuesButtonGroup->setColumnLayout(0, Qt::Vertical );
        addValuesButtonGroup->layout()->setSpacing( 6 );
        addValuesButtonGroup->layout()->setMargin( 11 );
        addValuesButtonGroupLayout = new QVBoxLayout(
                                            addValuesButtonGroup->layout() );
        addValuesButtonGroupLayout->setAlignment( Qt::AlignTop );

        noRadioButton = new QRadioButton( "&No", addValuesButtonGroup );
        noRadioButton->setChecked( true );
        addValuesButtonGroupLayout->addWidget( noRadioButton );

        yesRadioButton = new QRadioButton( "&Yes", addValuesButtonGroup );
        addValuesButtonGroupLayout->addWidget( yesRadioButton );

        asPercentageRadioButton = new QRadioButton( "As &Percentage",
                                                    addValuesButtonGroup );
        addValuesButtonGroupLayout->addWidget( asPercentageRadioButton );
        addValuesFrameLayout->addWidget( addValuesButtonGroup );

用户也许选择显示它们自己的标签或者在每一个标签的末尾加上值，或者加上百分比。

我们创建一个框架来存放单选按钮并且为它们创建了一个布局。我们创建了一个按钮组（这样Qt就可以自动地处理专有的单选按钮行为了）。接下来我们创建单选按钮，并把“No”作为默认值。

小数位标签和微调框被放在另一个水平布局中，并且按钮和设置数据视窗中的按钮的排布方式非常相似。

        connect( fontPushButton, SIGNAL( clicked() ), this, SLOT( chooseFont() ) );
        connect( okPushButton, SIGNAL( clicked() ), this, SLOT( accept() ) );
        connect( cancelPushButton, SIGNAL( clicked() ), this, SLOT( reject() ) );

我们只需要三个连接：

  1. 当用户点击字体按钮时，我们执行我们自己的chooseFont()槽。
  2. 如果用户点击OK，我们调用QDialog::accept()，它会让调用者来从对话框的窗口部件中读取数据并且执行任何必要的动作。
  3. 如果用户点击Cancel，我们调用QDialog::reject()。

        chartTypeTextLabel->setBuddy( chartTypeComboBox );
        decimalPlacesTextLabel->setBuddy( decimalPlacesSpinBox );

我们使用setBuddy()函数来连接窗口部件和标签的加速键。

槽

    void OptionsForm::chooseFont()
    {
        bool ok;
        QFont font = QFontDialog::getFont( &ok, m_font, this );
        if ( ok )
            setFont( font );
    }

当用户点击Font按钮时，这个槽被调用。它简单地调用静态的QFontDialog::getFont()来获得用户选择的字体。如果他们选择了一个字体，我们调用我们的setFont()槽在字体标签中提供一个字体的文本描述。

    void OptionsForm::setFont( QFont font )
    {
        QString label = font.family() + " " +
                        QString::number( font.pointSize() ) + "pt";
        if ( font.bold() )
            label += " Bold";
        if ( font.italic() )
            label += " Italic";
        fontTextLabel->setText( label );
        m_font = font;
    }

这个函数在字体标签中显示一个被选字体的文本描述，并且在m_font成员中保存一个字体的拷贝。我们需要这个字体为成员，这样我们就会为chooseFont()提供一个默认字体。

« Taking Data | 目录 | 项目文件 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


项目文件

（chart.pro。）

    TEMPLATE = app
    CONFIG  += warn_on

    HEADERS +=  element.h \
                canvastext.h \
                canvasview.h \
                chartform.h \
                optionsform.h \
                setdataform.h
    SOURCES +=  element.cpp \
                canvasview.cpp \
                chartform.cpp \
                chartform_canvas.cpp \
                chartform_files.cpp \
                optionsform.cpp \
                setdataform.cpp \
                main.cpp

通过使用项目文件，我们能够把我们自己从为我们所要使用的平台创建Makefile中脱离出来。为了生成一个Makefile我们所要做的一切就是运行qmake，比如：

qmake -o Makefile chart.pro

« 设置选项 | 目录 | 完成 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


完成

chart应用程序显示了用Qt创建应用程序和对话框是多么的直接。创建菜单和工具条是很容易的并且Qt的信号和槽机制相当地简化了图形用户界面事件处理。

手工创建布局可能会花费一些时间来掌握，但是有一种容易的选择：Qt设计器。Qt设计器包括了简单但强大的布局工具和一个代码编辑器。它可以自动地生成main.cpp和.pro项目文件。

chart应用程序对于进一步开发和实验是成熟的。你也许可以考虑实现下面的一些思路：

  • 使用QValidator子类来保证只有有效的双精实数被输入到值中。
  • 添加更多的图表类型，比如线图、区域图和高低图。
  • 允许用户设置上下左右边白。
  • 允许用户指定一个可以像标签一样拖拽的标题。
  • 提供一个绘制和标签选项的中心线。
  • 提供一个选项用键（或者图例）来替换标签。
  • 为所有的图表类型添加一个三维的查看选项。

« 项目文件 | 目录 »

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Examples

Qt ships with lots of small and some medium-sized example programs that teach you how to implement various tasks with Qt. Most of them will show how to use a certain class or module, others aim at programming techniques and Qt basics, and some of them simply want to show you what's possible.

Note that most of the examples assume that you have some experience with C++ and Qt and therefore are not commented extensively. If you are interested in a line-by-line coverage please refer to the step-by-step examples.

Qt Base Classes: Assorted Examples

  • QAction and QActionGroup
  • QFont, QFontMetrics, QFontInfo and QFontDatabase
  • QProcess

Qt Modules: Assorted Examples

  • XML examples
  • Network examples
  • OpenGL examples
  • Table examples
  • SQL examples

Qt Extensions: Assorted Examples

  • Qt-based plugins for web browsers
  • Xt/Motif support extension

Miscellaneous Examples

Analog Clock
Simple Addressbook
Biff (UNIX only)
Buttons and Groupboxes
Canvas Example
Listviews with Checkable Items
Cursors
Customized Layoutmanager
Digital Clock
Qt Demo
Painting on the Desktop
A Directory Browser
Drag and Drop
Draw Demo
Connect the Points
Simple Filemanager
A Rectangle Draw "Benchmark"
Hello, World
Simple HTML Help Browser
Internationalization
Iconview
Layout Managers
Conway's Game of Life
Line Edits
Listbox Example
Listboxes and Comboboxes
Listviews
A MDI Application
Using menus
Movies or the Story of the Animated GIF file
Picture
Popup Widgets
Progress Bar and Dialog Example
Progress Bar
QDir
Font Displayer
QMag
A Tiny QTL Example
Simple HTML Browser
Range controls
Richtext
Rot13
Simple Painting Application
Scrollview
Show Image
A Complete Application Window
Drag and Drop (Simple)
Sound Example
Splitter
Tabdialog
Tablet Example
Tetrix
Text Edit Example
Themes (Styles)
Tic Tac Toe
Advanced use of tool tips
Widgets Example
Wizard
Transformed Graphics Demo

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


Step-by-step Examples

Step-by-step examples provide a careful explanation of example code.

The covered example programs usually show how to use certain classes or deal with programming techniques and Qt basics.

These examples are especially aimed at Qt novices and less experienced programmers and try to make learning Qt as painless as possible.

Walkthrough: A Tiny Editor Illustrating QActionGroup
A Complete Canvas Application
Walkthrough: A Simple Application with Actions
Walkthrough: A Simple Application
Walkthrough: A simple QFont demonstration
Walkthrough: Using SAX2 features with the Qt XML classes
Walkthrough: How to use the Qt SAX2 classes


Qt的类

如果想看一个更紧凑的列表，请参考Qt的主要类.

A | QAccel |  | QDockWindow |  | QImageFormatPlugin |  | QProgressDialog |  | QTableSelection
 | QAccessible |  | QDomAttr |  | QImageFormatType |  | QPtrCollection |  | QTabletEvent
 | QAccessibleInterface |  | QDomCDATASection |  | QImageIO |  | QPtrDict |  | QTabWidget
 | QAccessibleObject |  | QDomCharacterData |  | QIMEvent |  | QPtrDictIterator |  | QTextBrowser
 | QAction |  | QDomComment |  | QInputDialog |  | QPtrList |  | QTextCodec
 | QActionGroup |  | QDomDocument |  | QIntCache |  | QPtrListIterator |  | QTextCodecPlugin
 | QApplication |  | QDomDocumentFragment |  | QIntCacheIterator |  | QPtrQueue |  | QTextDecoder
 | QAsciiCache |  | QDomDocumentType |  | QIntDict |  | QPtrStack |  | QTextDrag
 | QAsciiCacheIterator |  | QDomElement |  | QIntDictIterator |  | QPtrVector |  | QTextEdit
 | QAsciiDict |  | QDomEntity |  | QIntValidator |  | QPushButton |  | QTextEncoder
 | QAsciiDictIterator |  | QDomEntityReference |  | QIODevice | R | QRadioButton |  | QTextIStream
B | QBitArray |  | QDomImplementation | J | QJisCodec |  | QRangeControl |  | QTextOStream
 | QBitmap |  | QDomNamedNodeMap | K | QKeyEvent |  | QRect |  | QTextStream
 | QBitVal |  | QDomNode |  | QKeySequence |  | QRegExp |  | QThread
 | QBoxLayout |  | QDomNodeList | L | QLabel |  | QRegExpValidator |  | QTime
 | QBrush |  | QDomNotation |  | QLayout |  | QRegion |  | QTimeEdit
 | QBuffer |  | QDomProcessingInstruction |  | QLayoutItem |  | QResizeEvent |  | QTimer
 | QButton |  | QDomText |  | QLayoutIterator | S | QScreen |  | QTimerEvent
 | QButtonGroup |  | QDoubleValidator |  | QLCDNumber |  | QScrollBar |  | QToolBar
 | QByteArray |  | QDragEnterEvent |  | QLibrary |  | QScrollView |  | QToolButton
C | QCache |  | QDragLeaveEvent |  | QLineEdit |  | QSemaphore |  | QToolTip
 | QCacheIterator |  | QDragMoveEvent |  | QListBox |  | QServerSocket |  | QToolTipGroup
 | QCanvas |  | QDragObject |  | QListBoxItem |  | QSessionManager |  | QTranslator
 | QCanvasEllipse |  | QDropEvent |  | QListBoxPixmap |  | QSettings |  | QTranslatorMessage
 | QCanvasItem | E | QEditorFactory |  | QListBoxText |  | QSGIStyle |  | QTsciiCodec
 | QCanvasItemList |  | QErrorMessage |  | QListView |  | QShowEvent | U | QUriDrag
 | QCanvasLine |  | QEucJpCodec |  | QListViewItem |  | QSignal |  | QUrl
 | QCanvasPixmap |  | QEucKrCodec |  | QListViewItemIterator |  | QSignalMapper |  | QUrlInfo
 | QCanvasPixmapArray |  | QEvent |  | QLocalFs |  | QSimpleRichText |  | QUrlOperator
 | QCanvasPolygon | F | QFile |  | QLock |  | QSize | V | QValidator
 | QCanvasPolygonalItem |  | QFileDialog | M | QMainWindow |  | QSizeGrip |  | QValueList
 | QCanvasRectangle |  | QFileIconProvider |  | QMap |  | QSizePolicy |  | QValueListConstIterator
 | QCanvasSpline |  | QFileInfo |  | QMapConstIterator |  | QSjisCodec |  | QValueListIterator
 | QCanvasSprite |  | QFilePreview |  | QMapIterator |  | QSlider |  | QValueStack
 | QCanvasText |  | QFocusData |  | QMemArray |  | QSocket |  | QValueVector
 | QCanvasView |  | QFocusEvent |  | QMenuBar |  | QSocketDevice |  | QVariant
 | QCDEStyle |  | QFont |  | QMenuData |  | QSocketNotifier |  | QVBox
 | QChar |  | QFontDatabase |  | QMessageBox |  | QSound |  | QVBoxLayout
 | QCharRef |  | QFontDialog |  | QMetaObject |  | QSpacerItem |  | QVButtonGroup
 | QCheckBox |  | QFontInfo |  | QMetaProperty |  | QSpinBox |  | QVGroupBox
 | QCheckListItem |  | QFontManager |  | QMimeSource |  | QSplitter | W | QWaitCondition
 | QCheckTableItem |  | QFontMetrics |  | QMimeSourceFactory |  | QSql |  | QWhatsThis
 | QChildEvent |  | QFrame |  | QMotifPlusStyle |  | QSqlCursor |  | QWheelEvent
 | QClipboard |  | QFtp |  | QMotifStyle |  | QSqlDatabase |  | QWidget
 | QCloseEvent | G | QGb18030Codec |  | QMouseEvent |  | QSqlDriver |  | QWidgetFactory
 | QColor |  | QGbkCodec |  | QMoveEvent |  | QSqlDriverPlugin |  | QWidgetItem
 | QColorDialog |  | QGL |  | QMovie |  | QSqlEditorFactory |  | QWidgetPlugin
 | QColorDrag |  | QGLayoutIterator |  | QMutex |  | QSqlError |  | QWidgetStack
 | QColorGroup |  | QGLColormap | N | QNetworkOperation |  | QSqlField |  | QWindowsMime
 | QComboBox |  | QGLContext |  | QNetworkProtocol |  | QSqlFieldInfo |  | QWindowsStyle
 | QComboTableItem |  | QGLFormat |  | QNPInstance * |  | QSqlForm |  | QWizard
 | QCommonStyle |  | QGLWidget |  | QNPlugin * |  | QSqlIndex |  | QWMatrix
 | QConstString |  | QGrid |  | QNPStream * |  | QSqlPropertyMap |  | QWorkspace
 | QContextMenuEvent |  | QGridLayout |  | QNPWidget * |  | QSqlQuery |  | QWSDecoration
 | QCopChannel |  | QGridView | O | QObject |  | QSqlRecord |  | QWSKeyboardHandler
 | QCString |  | QGroupBox |  | QObjectCleanupHandler |  | QSqlRecordInfo |  | QWSMouseHandler
 | QCursor |  | QGuardedPtr |  | QObjectList |  | QSqlResult |  | QWSServer
 | QCustomEvent | H | QHBox |  | QObjectListIt |  | QStatusBar |  | QWSWindow
 | QCustomMenuItem |  | QHBoxLayout | P | QPaintDevice |  | QStoredDrag | X | QXmlAttributes
D | QDataBrowser |  | QHButtonGroup |  | QPaintDeviceMetrics |  | QStrIList |  | QXmlContentHandler
 | QDataStream |  | QHeader |  | QPainter |  | QString |  | QXmlDeclHandler
 | QDataTable |  | QHebrewCodec |  | QPaintEvent |  | QStringList |  | QXmlDefaultHandler
 | QDataView |  | QHGroupBox |  | QPair |  | QStrList |  | QXmlDTDHandler
 | QDate |  | QHideEvent |  | QPalette |  | QStrListIterator |  | QXmlEntityResolver
 | QDateEdit |  | QHostAddress |  | QPen |  | QStyle |  | QXmlErrorHandler
 | QDateTime |  | QHttp |  | QPicture |  | QStyleFactory |  | QXmlInputSource
 | QDateTimeEdit | I | QIconDrag |  | QPixmap |  | QStyleOption |  | QXmlLexicalHandler
 | QDesktopWidget |  | QIconDragItem |  | QPixmapCache |  | QStylePlugin |  | QXmlLocator
 | QDial |  | QIconSet |  | QPlatinumStyle |  | QStyleSheet |  | QXmlNamespaceSupport
 | QDialog |  | QIconView |  | QPNGImagePacker |  | QStyleSheetItem |  | QXmlParseException
 | QDict |  | QIconViewItem |  | QPoint | T | Qt |  | QXmlReader
 | QDictIterator |  | QImage |  | QPointArray |  | QTab |  | QXmlSimpleReader
 | QDir |  | QImageConsumer |  | QPopupMenu |  | QTabBar |  | QXtApplication *
 | QDirectPainter |  | QImageDecoder |  | QPrinter |  | QTabDialog |  | QXtWidget *
 | QDns |  | QImageDrag |  | QProcess |  | QTable |  |
 | QDockArea |  | QImageFormat |  | QProgressBar |  | QTableItem |  |

* NSPlugin和Xt/Motif的扩展类。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt的主要类

这些是最常用的Qt类。如果想看一个完整的列表（包括XML、网络和容器类），请参考Qt的类。

A | QAction |  | QFileDialog |  | QMessageBox |  | QSlider |  | QToolBar
 | QApplication |  | QFont |  | QMovie |  | QSound |  | QToolButton
B | QButtonGroup |  | QFontDialog | N | QNetworkProtocol |  | QSpinBox |  | QToolTip
C | QCanvas | G | QGLWidget | O | QObject |  | QSplitter |  | QTranslator
 | QCheckBox |  | QGridLayout | P | QPainter |  | QSql | U | QUrl
 | QClipboard |  | QGroupBox |  | QPalette |  | QSqlDatabase |  | QUrlOperator
 | QColorDialog |  | QGuardedPtr |  | QPen |  | QSqlDriverPlugin | V | QValidator
 | QComboBox | H | QHBoxLayout |  | QPixmap |  | QSqlForm |  | QValueList
D | QDataBrowser | I | QIconSet |  | QPoint |  | QSqlQuery |  | QValueStack
 | QDataTable |  | QIconView |  | QPopupMenu |  | QStatusBar |  | QValueVector
 | QDataView |  | QImage |  | QPrinter |  | QString |  | QVariant
 | QDate |  | QInputDialog |  | QProcess |  | QStringList |  | QVBoxLayout
 | QDateEdit | L | QLabel |  | QProgressBar | T | QTabDialog | W | QWhatsThis
 | QDateTime |  | QLCDNumber |  | QProgressDialog |  | QTable |  | QWidget
 | QDateTimeEdit |  | QLibrary |  | QPushButton |  | QTabWidget |  | QWidgetStack
 | QDial |  | QLineEdit | R | QRadioButton |  | QTextBrowser |  | QWizard
 | QDialog |  | QListBox |  | QRect |  | QTextEdit |  | QWorkspace
 | QDict |  | QListView |  | QRegExp |  | QTextStream | X | QXmlSimpleReader
 | QDir | M | QMainWindow | S | QScrollView |  | QTime |  |
 | QDockWindow |  | QMap |  | QSettings |  | QTimeEdit |  |
F | QFile |  | QMenuBar |  | QSimpleRichText |  | QTimer |  |

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


分组的类

本页提供了一种通过把相关的类放在一起，分组进行浏览Qt类的方式。一些类可能出现在不止一个组中。

组 | 描述
抽象窗口部件 | 抽象窗口部件类是通过子类来使用的。
高级窗口部件 | 高级的GUI窗口部件，比如列表视图和进程条。
基本窗口部件 | 基本的GUI窗口部件，比如按钮,组合框和滚动条。
数据库 | 与数据库相关的类，比如与SQL数据库相关的类。
日期与时间 | 处理日期与时间的类。
拖放 | 处理拖放和MIME类型的编码解码类。
环境 | 提供多样全面的服务（比如事件处理,系统设置访问和国际化等服务）的类。
事件 | 用来生成和处理事件的类。
非GUI的类 | 集合类，比如列表、队列、堆栈和字符串，它们不需要QApplication类就可以和其它类一起使用。
图形和打印 | 提供绘制(和打印)图元，包括OpenGL。（也可以参见图形处理和多媒体）
帮助系统 | 用来给应用程序提供在线帮助的类。
图像处理 | 数字图像编码、解码和操作。（也可以参见图形和打印和多媒体）
布局管理 | 用来处理自动调整窗口部件的大小和位置，能够构成复杂对话框的类。
隐含地和明示地共享类 | 为了快速复制而使用引用计数的类。
输入/输出和网络 | 提供文件输入输出，目录和网络的操作的类。
主窗口和相关类 | 一切你所需要的典型现代主程序窗口，包括目录、工具条、工作区等等。
杂项 | 不同的其他有用的类。
多媒体 | 提供图片、声音、动画等等支持的类。（也可以参见图形和打印和 图像处理）
对象模型 | 在Qt应用程序框架底层的对象模型。
组织者 | 用户接口组织者，比如分隔器、TAB条、按钮组等等。
插件类 | 插件相关类。
标准对话框 | 用于文件、字体、颜色选择和更多的已经做好的对话框。
模板类 | Qt的模板库容器类。
文本相关类 | 文本处理的类。（也可以参见XML类。）
线程类 | 提供线程支持的类。
窗口部件外观 | 可以定制风格、字体、颜色等等外观的类。
XML类 | 通过DOM和SAX来支持XML的类。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Annotated Class Index

Here are the classes in Qt, with brief descriptions:

QAccel | Handles keyboard accelerator and shortcut keys
QAccessible | Enums and static functions relating to accessibility
QAccessibleInterface | Defines an interface that exposes information about accessible objects
QAccessibleObject | Implements parts of the QAccessibleInterface for QObjects
QAction | Abstract user interface action that can appear both in menus and tool bars
QActionGroup | Groups actions together
QApplication | Manages the GUI application's control flow and main settings
QAsciiCache | Template class that provides a cache based on char* keys
QAsciiCacheIterator | Iterator for QAsciiCache collections
QAsciiDict | Template class that provides a dictionary based on char* keys
QAsciiDictIterator | Iterator for QAsciiDict collections
QBitArray | Array of bits
QBitVal | Internal class, used with QBitArray
QBitmap | Monochrome (1-bit depth) pixmaps
QBoxLayout | Lines up child widgets horizontally or vertically
QBrush | Defines the fill pattern of shapes drawn by a QPainter
QBuffer | I/O device that operates on a QByteArray
QButton | The abstract base class of button widgets, providing functionality common to buttons
QButtonGroup | Organizes QButton widgets in a group
QByteArray | Array of bytes
QCDEStyle | CDE look and feel
QCString | Abstraction of the classic C zero-terminated char array (char *)
QCache | Template class that provides a cache based on QString keys
QCacheIterator | Iterator for QCache collections
QCanvas | 2D area that can contain QCanvasItem objects
QCanvasEllipse | Ellipse or ellipse segment on a QCanvas
QCanvasItem | Abstract graphic object on a QCanvas
QCanvasItemList | List of QCanvasItems
QCanvasLine | Line on a QCanvas
QCanvasPixmap | Pixmaps for QCanvasSprites
QCanvasPixmapArray | Array of QCanvasPixmaps
QCanvasPolygon | Polygon on a QCanvas
QCanvasPolygonalItem | Polygonal canvas item on a QCanvas
QCanvasRectangle | Rectangle on a QCanvas
QCanvasSpline | Multi-bezier splines on a QCanvas
QCanvasSprite | Animated canvas item on a QCanvas
QCanvasText | Text object on a QCanvas
QCanvasView | On-screen view of a QCanvas
QChar | Lightweight Unicode character
QCharRef | Helper class for QString
QCheckBox | Checkbox with a text label
QCheckListItem | Checkable list view items
QCheckTableItem | Checkboxes in QTables
QChildEvent | Event parameters for child object events
QClipboard | Access to the window system clipboard
QCloseEvent | Parameters that describe a close event
QColor | Colors based on RGB or HSV values
QColorDialog | Dialog widget for specifying colors
QColorDrag | Drag and drop object for transferring colors
QColorGroup | Group of widget colors
QComboBox | Combined button and popup list
QComboTableItem | Means of using comboboxes in QTables
QCommonStyle | Encapsulates the common Look and Feel of a GUI
QConstString | String objects using constant Unicode data
QContextMenuEvent | Parameters that describe a context menu event
QCopChannel | Communication capabilities between several clients
QCursor | Mouse cursor with an arbitrary shape
QCustomEvent | Support for custom events
QCustomMenuItem | Abstract base class for custom menu items in popup menus
QDataBrowser | Data manipulation and navigation for data entry forms
QDataStream | Serialization of binary data to a QIODevice
QDataTable | Flexible SQL table widget that supports browsing and editing
QDataView | Read-only SQL forms
QDate | Date functions
QDateEdit | Date editor
QDateTime | Date and time functions
QDateTimeEdit | Combines a QDateEdit and QTimeEdit widget into a single widget for editing datetimes
QDesktopWidget | Access to screen information on multi-head systems
QDial | Rounded range control (like a speedometer or potentiometer)
QDialog | The base class of dialog windows
QDict | Template class that provides a dictionary based on QString keys
QDictIterator | Iterator for QDict collections
QDir | Access to directory structures and their contents in a platform-independent way
QDirectPainter | Direct access to the video hardware
QDns | Asynchronous DNS lookups
QDockArea | Manages and lays out QDockWindows
QDockWindow | Widget which can be docked inside a QDockArea or floated as a top level window on the desktop
QDomAttr | Represents one attribute of a QDomElement
QDomCDATASection | Represents an XML CDATA section
QDomCharacterData | Represents a generic string in the DOM
QDomComment | Represents an XML comment
QDomDocument | Represents an XML document
QDomDocumentFragment | Tree of QDomNodes which is not usually a complete QDomDocument
QDomDocumentType | The representation of the DTD in the document tree
QDomElement | Represents one element in the DOM tree
QDomEntity | Represents an XML entity
QDomEntityReference | Represents an XML entity reference
QDomImplementation | Information about the features of the DOM implementation
QDomNamedNodeMap | Collection of nodes that can be accessed by name
QDomNode | The base class for all the nodes in a DOM tree
QDomNodeList | List of QDomNode objects
QDomNotation | Represents an XML notation
QDomProcessingInstruction | Represents an XML processing instruction
QDomText | Represents text data in the parsed XML document
QDoubleValidator | Range checking of floating-point numbers
QDragEnterEvent | Event which is sent to the widget when a drag and drop first drags onto the widget
QDragLeaveEvent | Event which is sent to the widget when a drag and drop leaves the widget
QDragMoveEvent | Event which is sent while a drag and drop is in progress
QDragObject | Encapsulates MIME-based data transfer
QDropEvent | Event which is sent when a drag and drop is completed
QEditorFactory | Used to create editor widgets for QVariant data types
QErrorMessage | Error message display dialog
QEucJpCodec | Conversion to and from EUC-JP character sets
QEucKrCodec | Conversion to and from EUC-KR character sets
QEvent | The base class of all event classes. Event objects contain event parameters
QFile | I/O device that operates on files
QFileDialog | Dialogs that allow users to select files or directories
QFileIconProvider | Icons for QFileDialog to use
QFileInfo | System-independent file information
QFilePreview | File previewing in QFileDialog
QFocusData | Maintains the list of widgets in the focus chain
QFocusEvent | Event parameters for widget focus events
QFont | Font used for drawing text
QFontDatabase | Information about the fonts available in the underlying window system
QFontDialog | Dialog widget for selecting a font
QFontInfo | General information about fonts
QFontManager | Implements font management in Qt/Embedded
QFontMetrics | Font metrics information
QFrame | The base class of widgets that can have a frame
QFtp | Implementation of the FTP protocol
QGL | Namespace for miscellaneous identifiers in the Qt OpenGL module
QGLColormap | Used for installing custom colormaps into QGLWidgets
QGLContext | Encapsulates an OpenGL rendering context
QGLFormat | The display format of an OpenGL rendering context
QGLWidget | Widget for rendering OpenGL graphics
QGLayoutIterator | Abstract base class of internal layout iterators
QGb18030Codec | Conversion to and from the Chinese GB18030/GBK/GB2312 encoding
QGbkCodec | Conversion to and from the Chinese GBK encoding
QGrid | Simple geometry management of its children
QGridLayout | Lays out widgets in a grid
QGridView | Abstract base for fixed-size grids
QGroupBox | Group box frame with a title
QGuardedPtr | Template class that provides guarded pointers to QObjects
QHBox | Horizontal geometry management for its child widgets
QHBoxLayout | Lines up widgets horizontally
QHButtonGroup | Organizes QButton widgets in a group with one horizontal row
QHGroupBox | Organizes widgets in a group with one horizontal row
QHeader | Header row or column, e.g. for tables and listviews
QHebrewCodec | Conversion to and from visually ordered Hebrew
QHideEvent | Event which is sent after a widget is hidden
QHostAddress | IP address
QHttp | Implementation of the HTTP protocol
QIMEvent | Parameters for input method events
QIODevice | The base class of I/O devices
QIconDrag | Supports drag and drop operations within a QIconView
QIconDragItem | Encapsulates a drag item
QIconSet | Set of icons with different styles and sizes
QIconView | Area with movable labelled icons
QIconViewItem | Single item in a QIconView
QImage | Hardware-independent pixmap representation with direct access to the pixel data
QImageConsumer | Abstraction used by QImageDecoder
QImageDecoder | Incremental image decoder for all supported image formats
QImageDrag | Drag and drop object for transferring images
QImageFormat | Incremental image decoder for a specific image format
QImageFormatPlugin | Abstract base for custom image format plugins
QImageFormatType | Factory that makes QImageFormat objects
QImageIO | Parameters for loading and saving images
QInputDialog | Simple convenience dialog to get a single value from the user
QIntCache | Template class that provides a cache based on long keys
QIntCacheIterator | Iterator for QIntCache collections
QIntDict | Template class that provides a dictionary based on long keys
QIntDictIterator | Iterator for QIntDict collections
QIntValidator | Validator which ensures that a string contains a valid integer within a specified range
QJisCodec | Conversion to and from JIS character sets
QKeyEvent | Describes a key event
QKeySequence | Encapsulates a key sequence as used by accelerators
QLCDNumber | Displays a number with LCD-like digits
QLabel | Text or image display
QLayout | The base class of geometry managers
QLayoutItem | Abstract item that a QLayout manipulates
QLayoutIterator | Iterators over QLayoutItem
QLibrary | Wrapper for handling shared libraries
QLineEdit | One-line text editor
QListBox | List of selectable, read-only items
QListBoxItem | The base class of all list box items
QListBoxPixmap | List box items with a pixmap and optional text
QListBoxText | List box items that display text
QListView | Implements a list/tree view
QListViewItem | Implements a list view item
QListViewItemIterator | Iterator for collections of QListViewItems
QLocalFs | Implementation of a QNetworkProtocol that works on the local file system
QLock | Wrapper for a System V shared semaphore
QMainWindow | Main application window, with a menu bar, dock windows (e.g. for toolbars), and a status bar
QMap | Value-based template class that provides a dictionary
QMapConstIterator | Iterator for QMap
QMapIterator | Iterator for QMap
QMemArray | Template class that provides arrays of simple types
QMenuBar | Horizontal menu bar
QMenuData | Base class for QMenuBar and QPopupMenu
QMessageBox | Modal dialog with a short message, an icon, and some buttons
QMetaObject | Meta information about Qt objects
QMetaProperty | Stores meta data about a property
QMimeSource | Abstraction of objects which provide formatted data of a certain MIME type
QMimeSourceFactory | Extensible provider of mime-typed data
QMotifPlusStyle | More sophisticated Motif-ish look and feel
QMotifStyle | Motif look and feel
QMouseEvent | Parameters that describe a mouse event
QMoveEvent | Event parameters for move events
QMovie | Incremental loading of animations or images, signalling as it progresses
QMutex | Access serialization between threads
QNPInstance | QObject that is a Web-browser plugin
QNPStream | Stream of data provided to a QNPInstance by the browser
QNPWidget | QWidget that is a Web-browser plugin window
QNPlugin | The plugin central factory
QNetworkOperation | Common operations for network protocols
QNetworkProtocol | Common API for network protocols
QObject | The base class of all Qt objects
QObjectCleanupHandler | Watches the lifetime of multiple QObjects
QObjectList | QPtrList of QObjects
QObjectListIt | Iterator for QObjectLists
QPNGImagePacker | Creates well-compressed PNG animations
QPaintDevice | The base class of objects that can be painted
QPaintDeviceMetrics | Information about a paint device
QPaintEvent | Event parameters for paint events
QPainter | Does low-level painting e.g. on widgets
QPair | Value-based template class that provides a pair of elements
QPalette | Color groups for each widget state
QPen | Defines how a QPainter should draw lines and outlines of shapes
QPicture | Paint device that records and replays QPainter commands
QPixmap | Off-screen, pixel-based paint device
QPixmapCache | Application-global cache for pixmaps
QPlatinumStyle | Mac/Platinum look and feel
QPoint | Defines a point in the plane
QPointArray | Array of points
QPopupMenu | Popup menu widget
QPrinter | Paint device that paints on a printer
QProcess | Used to start external programs and to communicate with them
QProgressBar | Horizontal progress bar
QProgressDialog | Feedback on the progress of a slow operation
QPtrCollection | The base class of most pointer-based Qt collections
QPtrDict | Template class that provides a dictionary based on void* keys
QPtrDictIterator | Iterator for QPtrDict collections
QPtrList | Template class that provides doubly-linked lists
QPtrListIterator | Iterator for QPtrList collections
QPtrQueue | Template class that provides a queue
QPtrStack | Template class that provides a stack
QPtrVector | Template collection class that provides a vector (array)
QPushButton | Command button
QRadioButton | Radio button with a text or pixmap label
QRangeControl | Integer value within a range
QRect | Defines a rectangle in the plane
QRegExp | Pattern matching using regular expressions
QRegExpValidator | Used to check a string against a regular expression
QRegion | Clip region for a painter
QResizeEvent | Event parameters for resize events
QSGIStyle | SGI/Irix look and feel
QScreen | And its descendants manage the framebuffer and palette
QScrollBar | Vertical or horizontal scroll bar
QScrollView | Scrolling area with on-demand scroll bars
QSemaphore | Robust integer semaphore
QServerSocket | TCP-based server
QSessionManager | Access to the session manager
QSettings | Persistent platform-independent application settings
QShowEvent | Event which is sent when a widget is shown
QSignal | Can be used to send signals for classes that don't inherit QObject
QSignalMapper | Bundles signals from identifiable senders
QSimpleRichText | Small displayable piece of rich text
QSize | Defines the size of a two-dimensional object
QSizeGrip | Corner-grip for resizing a top-level window
QSizePolicy | Layout attribute describing horizontal and vertical resizing policy
QSjisCodec | Conversion to and from Shift-JIS
QSlider | Vertical or horizontal slider
QSocket | Buffered TCP connection
QSocketDevice | Platform-independent low-level socket API
QSocketNotifier | Support for socket callbacks
QSound | Access to the platform audio facilities
QSpacerItem | Blank space in a layout
QSpinBox | Spin box widget (spin button)
QSplitter | Implements a splitter widget
QSql | Namespace for Qt SQL identifiers that need to be global-like
QSqlCursor | Browsing and editing of SQL tables and views
QSqlDatabase | Used to create SQL database connections and provide transaction handling
QSqlDriver | Abstract base class for accessing SQL databases
QSqlDriverPlugin | Abstract base for custom QSqlDriver plugins
QSqlEditorFactory | Used to create the editors used by QDataTable and QSqlForm
QSqlError | SQL database error information
QSqlField | Manipulates the fields in SQL database tables and views
QSqlFieldInfo | Stores meta data associated with a SQL field
QSqlForm | Creates and manages data entry forms tied to SQL databases
QSqlIndex | Functions to manipulate and describe QSqlCursor and QSqlDatabase indexes
QSqlPropertyMap | Used to map widgets to SQL fields
QSqlQuery | Means of executing and manipulating SQL statements
QSqlRecord | Encapsulates a database record, i.e. a set of database fields
QSqlRecordInfo | Encapsulates a set of database field meta data
QSqlResult | Abstract interface for accessing data from SQL databases
QStatusBar | Horizontal bar suitable for presenting status information
QStoredDrag | Simple stored-value drag object for arbitrary MIME data
QStrIList | Doubly-linked list of char* with case-insensitive comparison
QStrList | Doubly-linked list of char*
QStrListIterator | Iterator for the QStrList and QStrIList classes
QString | Abstraction of Unicode text and the classic C null-terminated char array
QStringList | List of strings
QStyle | The look and feel of a GUI
QStyleFactory | Creates QStyle objects
QStyleOption | Optional parameters for QStyle functions
QStylePlugin | Abstract base for custom QStyle plugins
QStyleSheet | Collection of styles for rich text rendering and a generator of tags
QStyleSheetItem | Encapsulation of a set of text styles
QTab | The structures in a QTabBar
QTabBar | Tab bar, e.g. for use in tabbed dialogs
QTabDialog | Stack of tabbed widgets
QTabWidget | Stack of tabbed widgets
QTable | Flexible editable table widget
QTableItem | The cell content for QTable cells
QTableSelection | Access to a selected area in a QTable
QTabletEvent | Parameters that describe a Tablet event
QTextBrowser | Rich text browser with hypertext navigation
QTextCodec | Conversion between text encodings
QTextCodecPlugin | Abstract base for custom QTextCodec plugins
QTextDecoder | State-based decoder
QTextDrag | Drag and drop object for transferring plain and Unicode text
QTextEdit | Powerful single-page rich text editor
QTextEncoder | State-based encoder
QTextIStream | Convenience class for input streams
QTextOStream | Convenience class for output streams
QTextStream | Basic functions for reading and writing text using a QIODevice
QThread | Platform-independent threads
QTime | Clock time functions
QTimeEdit | Time editor
QTimer | Timer signals and single-shot timers
QTimerEvent | Parameters that describe a timer event
QToolBar | Movable panel containing widgets such as tool buttons
QToolButton | Quick-access button to commands or options, usually used inside a QToolBar
QToolTip | Tool tips (balloon help) for any widget or rectangular part of a widget
QToolTipGroup | Collects tool tips into related groups
QTranslator | Internationalization support for text output
QTranslatorMessage | Translator message and its properties
QTsciiCodec | Conversion to and from the Tamil TSCII encoding
QUriDrag | Drag object for a list of URI references
QUrl | URL parser and simplifies working with URLs
QUrlInfo | Stores information about URLs
QUrlOperator | Common operations on URLs
QVBox | Vertical geometry management of its child widgets
QVBoxLayout | Lines up widgets vertically
QVButtonGroup | Organizes QButton widgets in a vertical column
QVGroupBox | Organizes a group of widgets in a vertical column
QValidator | Validation of input text
QValueList | Value-based template class that provides doubly linked lists
QValueListConstIterator | Const iterator for QValueList
QValueListIterator | Iterator for QValueList
QValueStack | Value-based template class that provides a stack
QValueVector | Value-based template class that provides a dynamic array
QVariant | Acts like a union for the most common Qt data types
QWMatrix | 2D transformations of a coordinate system
QWSDecoration | Allows the appearance of the Qt/Embedded Window Manager to be customized
QWSKeyboardHandler | Implements the keyboard driver/handler for Qt/Embedded
QWSMouseHandler | Mouse driver/handler for Qt/Embedded
QWSServer | Server-specific functionality in Qt/Embedded
QWSWindow | Server-specific functionality in Qt/Embedded
QWaitCondition | Allows waiting/waking for conditions between threads
QWhatsThis | Simple description of any widget, i.e. answering the question "What's this?"
QWheelEvent | Parameters that describe a wheel event
QWidget | The base class of all user interface objects
QWidgetFactory | For the dynamic creation of widgets from Qt Designer .ui files
QWidgetItem | Layout item that represents a widget
QWidgetPlugin | Abstract base for custom QWidget plugins
QWidgetStack | Stack of widgets of which only the top widget is user-visible
QWindowsMime | Maps open-standard MIME to Window Clipboard formats
QWindowsStyle | Microsoft Windows-like look and feel
QWizard | Framework for wizard dialogs
QWorkspace | Workspace window that can contain decorated windows, e.g. for MDI
QXmlAttributes | XML attributes
QXmlContentHandler | Interface to report the logical content of XML data
QXmlDTDHandler | Interface to report DTD content of XML data
QXmlDeclHandler | Interface to report declaration content of XML data
QXmlDefaultHandler | Default implementation of all XML handler classes
QXmlEntityResolver | Interface to resolve external entities contained in XML data
QXmlErrorHandler | Interface to report errors in XML data
QXmlInputSource | The input data for the QXmlReader subclasses
QXmlLexicalHandler | Interface to report the lexical content of XML data
QXmlLocator | The XML handler classes with information about the parsing position within a file
QXmlNamespaceSupport | Helper class for XML readers which want to include namespace support
QXmlParseException | Used to report errors with the QXmlErrorHandler interface
QXmlReader | Interface for XML readers (i.e. parsers)
QXmlSimpleReader | Implementation of a simple XML reader (parser)
QXtApplication | Facilitates the mixing of Xt/Motif and Qt widgets
QXtWidget | Allows mixing of Xt/Motif and Qt widgets
Qt | Namespace for miscellaneous identifiers that need to be global-like


Class Inheritance Hierarchy

This list shows the C++ class inheritance relations between the classes in the Qt API.

The list is sorted roughly, but not completely, alphabetically.

  • QAccessible
    • QAccessibleInterface
  • QAsciiCache
  • QAsciiCacheIterator
  • QAsciiDictIterator
  • QAsyncIO
    • QDataSink
    • QDataSource
      • QIODeviceSource
  • QBitVal
  • QCacheIterator
  • QCanvasPixmapArray
  • QChar
  • QCharRef
  • QColor
  • QColorGroup
  • QConstString
  • QDataStream
  • QDate
  • QDateEdit
  • QDateTime
  • QDictIterator
  • QDir
  • QDomImplementation
  • QDomNamedNodeMap
  • QDomNode
    • QDomAttr
    • QDomCharacterData
      • QDomComment
      • QDomText
        • QDomCDATASection
    • QDomDocument
    • QDomDocumentFragment
    • QDomDocumentType
    • QDomElement
    • QDomEntity
    • QDomEntityReference
    • QDomNotation
    • QDomProcessingInstruction
  • QDomNodeList
  • QDropSite
  • QFileInfo
  • QFilePreview
  • QFocusData
  • QFont
  • QFontDatabase
  • QFontInfo
  • QFontManager
  • QFontMetrics
  • QGL
    • QGLContext
    • QGLFormat
  • QGLayoutIterator
  • QGLColormap
  • QGuardedPtr
  • QHostAddress
  • QIconDragItem
  • QIconSet
  • QImage
  • QImageConsumer
  • QImageDecoder
  • QImageFormat
  • QImageFormatPlugin
  • QImageFormatType
  • QImageIO
  • QIntCache
  • QIntCacheIterator
  • QIntDictIterator
  • QIODevice
    • QBuffer
    • QFile
    • QSocketDevice
  • QLayoutItem
    • QSpacerItem
    • QWidgetItem
  • QLayoutIterator
  • QLibrary
  • QListBoxItem
    • QListBoxPixmap
    • QListBoxText
  • QListViewItemIterator
  • QLock
  • QMap
  • QMapConstIterator
  • QMapIterator
  • QMemArray
    • QByteArray
      • QBitArray
      • QCString
    • QPointArray
  • QMenuData
  • QMetaObject
  • QMetaProperty
  • QMimeSource
  • QMimeSourceFactory
  • QMovie
  • QMutex
  • QNPlugin
  • QNPStream
  • QPaintDevice
    • QPicture
    • QPixmap
      • QBitmap
      • QCanvasPixmap
    • QPrinter
  • QPaintDeviceMetrics
  • QPair
  • QPalette
  • QPixmapCache
  • QPNGImagePacker
  • QPoint
  • QPtrCollection
    • QAsciiDict
    • QCache
    • QDict
    • QIntDict
    • QPtrDict
    • QPtrList
      • QObjectList
      • QSortedList
      • QStrList
        • QStrIList
    • QPtrVector
  • QPtrDictIterator
  • QPtrListIterator
    • QObjectListIt
    • QStrListIterator
  • QPtrQueue
  • QPtrStack
  • QRangeControl
  • QRect
  • QRegExp
  • QRegion
  • QScreen
  • QSemaphore
  • QSettings
  • QSimpleRichText
  • QSize
  • QSizePolicy
  • QSql
  • QSqlDriverPlugin
  • QSqlError
  • QSqlField
  • QSqlFieldInfo
  • QSqlPropertyMap
  • QSqlQuery
  • QSqlRecord
    • QSqlCursor
    • QSqlIndex
  • QSqlRecordInfo
  • QSqlResult
  • QString
  • QStyleFactory
  • QStyleOption
  • QStylePlugin
  • Qt
    • QBrush
    • QCanvasItem
      • QCanvasPolygonalItem
        • QCanvasEllipse
        • QCanvasLine
        • QCanvasPolygon
          • QCanvasSpline
        • QCanvasRectangle
      • QCanvasSprite
      • QCanvasText
    • QCursor
    • QCustomMenuItem
    • QEvent
      • QChildEvent
      • QCloseEvent
      • QContextMenuEvent
      • QCustomEvent
      • QDragLeaveEvent
      • QDropEvent
        • QDragMoveEvent
          • QDragEnterEvent
      • QFocusEvent
      • QHideEvent
      • QIMEvent
      • QKeyEvent
      • QMouseEvent
      • QMoveEvent
      • QPaintEvent
      • QResizeEvent
      • QShowEvent
      • QTabletEvent
      • QTimerEvent
      • QWheelEvent
    • QIconViewItem
    • QKeySequence
    • QListViewItem
      • QCheckListItem
    • QObject
      • QAccel
      • QAccessibleObject
      • QAction
        • QActionGroup
      • QApplication
        • QXtApplication
      • QCanvas
      • QClipboard
      • QCopChannel
      • QDataPump
      • QDns
      • QDragObject
        • QIconDrag
        • QImageDrag
        • QStoredDrag
          • QColorDrag
          • QUriDrag
        • QTextDrag
      • QEditorFactory
        • QSqlEditorFactory
      • QFileIconProvider
      • QLayout
        • QBoxLayout
          • QHBoxLayout
          • QVBoxLayout
        • QGridLayout
      • QNetworkOperation
      • QNetworkProtocol
        • QFtp
        • QHttp
        • QLocalFs
      • QNPInstance
      • QObjectCleanupHandler
      • QProcess
      • QServerSocket
      • QSessionManager
      • QSignal
      • QSignalMapper
      • QSocket
      • QSocketNotifier
      • QSound
      • QSqlDatabase
      • QSqlDriver
      • QSqlForm
      • QStyle
        • QCommonStyle
          • QMotifStyle
            • QCDEStyle
            • QMotifPlusStyle
            • QSGIStyle
          • QWindowsStyle
            • QPlatinumStyle
      • QStyleSheet
      • QTimer
      • QToolTipGroup
      • QTranslator
      • QUrlOperator
      • QValidator
        • QDoubleValidator
        • QIntValidator
        • QRegExpValidator
      • QWidget
        • QButton
          • QCheckBox
          • QPushButton
          • QRadioButton
          • QToolButton
        • QComboBox
        • QDataBrowser
        • QDataView
        • QDateTimeEdit
        • QDesktopWidget
        • QDial
        • QDialog
          • QColorDialog
          • QErrorMessage
          • QFileDialog
          • QFontDialog
          • QInputDialog
          • QMessageBox
          • QProgressDialog
          • QTabDialog
          • QWizard
        • QDockArea
        • QFrame
          • QDockWindow
            • QToolBar
          • QGrid
          • QGroupBox
            • QButtonGroup
              • QHButtonGroup
              • QVButtonGroup
            • QHGroupBox
            • QVGroupBox
          • QHBox
            • QVBox
          • QLabel
          • QLCDNumber
          • QLineEdit
          • QMenuBar
          • QPopupMenu
          • QProgressBar
          • QScrollView
            • QCanvasView
            • QGridView
            • QIconView
            • QListBox
            • QListView
            • QTable
              • QDataTable
            • QTextEdit
              • QMultiLineEdit
              • QTextBrowser
              • QTextView
          • QSplitter
          • QtTableView
            • QtMultiLineEdit
          • QWidgetStack
        • QGLWidget
        • QHeader
        • QMainWindow
        • QNPWidget
        • QScrollBar
        • QSizeGrip
        • QSlider
        • QSpinBox
        • QStatusBar
        • QTabBar
        • QTabWidget
        • QWorkspace
        • QXtWidget
      • QWSKeyboardHandler
      • QWSMouseHandler
    • QPainter
      • QDirectPainter
    • QPen
    • QStyleSheetItem
    • QTab
    • QTableItem
      • QCheckTableItem
      • QComboTableItem
    • QThread
    • QToolTip
    • QWhatsThis
  • QTableSelection
  • QTextCodec
    • QEucJpCodec
    • QEucKrCodec
    • QGb18030Codec
      • QGbkCodec
    • QHebrewCodec
    • QJisCodec
    • QSjisCodec
    • QTsciiCodec
  • QTextCodecPlugin
  • QTextDecoder
  • QTextEncoder
  • QTextStream
    • QTextIStream
    • QTextOStream
  • QTime
  • QTimeEdit
  • QTranslatorMessage
  • QUrl
  • QUrlInfo
  • QValueList
    • QCanvasItemList
    • QStringList
    • QValueStack
  • QValueListConstIterator
  • QValueListIterator
  • QValueVector
  • QVariant
  • QWaitCondition
  • QWidgetFactory
  • QWidgetPlugin
  • QWindowsMime
  • QWMatrix
  • QWSDecoration
  • QWSServer
  • QWSWindow
  • QXmlAttributes
  • QXmlContentHandler
    • QXmlDefaultHandler
  • QXmlDeclHandler
  • QXmlDTDHandler
  • QXmlEntityResolver
  • QXmlErrorHandler
  • QXmlInputSource
  • QXmlLexicalHandler
  • QXmlLocator
  • QXmlNamespaceSupport
  • QXmlParseException
  • QXmlReader
    • QXmlSimpleReader


Qt Class Chart

The gzipped postscript A3 size master copy of the class chart is available for download from ftp://ftp.trolltech.com/qt/pdf/3.0/qt30-class-chart.pdf (104K).* The PDF file will always be the same or more recent than the one shown here.

* The PDF file is not supported; we do not guarantee it will print correctly (although several people have reported that it does). It is not available in any other format or size.


Member Function Index

Here is a list of all of the documented member functions in the Qt API with links to the class documentation for each function.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  • DTDHandler: QXmlReader
  • Q_ASSERT: QApplication
  • Q_CHECK_PTR: QApplication
  • abort: QPrinter
  • aborted: QPrinter
  • about: QMessageBox
  • aboutQt: QMessageBox
  • aboutToHide: QPopupMenu
  • aboutToQuit: QApplication
  • aboutToShow: QPopupMenu QTabDialog QWidgetStack
  • absFilePath: QDir QFileInfo
  • absPath: QDir
  • accel: QAction QButton QCheckBox QMenuData QPopupMenu QPushButton QRadioButton
  • accept: QCloseEvent QContextMenuEvent QDialog QDragMoveEvent QDropEvent QIMEvent QKeyEvent QMouseEvent QSocketDevice QTabletEvent QWheelEvent
  • acceptAction: QDropEvent
  • acceptDrop: QIconViewItem QListViewItem
  • acceptDrops: QWidget
  • accum: QGLFormat
  • action: QDropEvent
  • activate: QCheckListItem QLayout QListViewItem QSignal
  • activateItemAt: QMenuData
  • activateNextCell: QTable
  • activated: QAccel QAction QComboBox QMenuBar QPopupMenu QSocketNotifier
  • activatedPos: QListViewItem
  • active: QPalette
  • activeModalWidget: QApplication
  • activePopupWidget: QApplication
  • activeWindow: QApplication QWorkspace
  • actual: QNPlugin
  • add: QActionGroup QGridLayout QLayout QObjectCleanupHandler QToolTip QWhatsThis
  • addArgument: QProcess
  • addChild: QScrollView
  • addChildLayout: QLayout
  • addColSpacing: QGridLayout
  • addColumn: QDataTable QListView
  • addCoords: QRect
  • addDatabase: QSqlDatabase
  • addDays: QDate QDateTime
  • addDockWindow: QMainWindow
  • addFactory: QMimeSourceFactory
  • addFilePath: QMimeSourceFactory
  • addFilter: QFileDialog
  • addItem: QBoxLayout QGridLayout QLayout
  • addLabel: QHeader
  • addLayout: QBoxLayout QGridLayout
  • addLeftWidget: QFileDialog
  • addLibraryPath: QApplication
  • addLine: QDial QRangeControl
  • addMSecs: QTime
  • addMonths: QDate QDateTime
  • addMultiCell: QGridLayout
  • addMultiCellLayout: QGridLayout
  • addMultiCellWidget: QGridLayout
  • addOperation: QNetworkProtocol
  • addPage: QDial QRangeControl QWizard
  • addPath: QUrl
  • addRightWidget: QFileDialog
  • addRowSpacing: QGridLayout
  • addSecs: QDateTime QTime
  • addSelection: QTable
  • addSeparator: QActionGroup QToolBar
  • addSpace: QGroupBox
  • addSpacing: QBoxLayout
  • addStep: QSlider
  • addStretch: QBoxLayout
  • addStrut: QBoxLayout
  • addTab: QTabBar QTabDialog QTabWidget
  • addTo: QAction QActionGroup
  • addToolButton: QFileDialog
  • addWidget: QBoxLayout QGridLayout QStatusBar QWidgetStack
  • addWidgetFactory: QWidgetFactory
  • addWidgets: QFileDialog
  • addYears: QDate QDateTime
  • addedTo: QAction QActionGroup
  • address: QServerSocket QSocket QSocketDevice
  • addressReusable: QSocketDevice
  • addresses: QDns
  • adjustColumn: QDataTable QTable
  • adjustHeaderSize: QHeader
  • adjustItems: QIconView
  • adjustPos: QSplitter
  • adjustRow: QTable
  • adjustSize: QMessageBox QSimpleRichText QWidget
  • advance: QCanvas QCanvasItem QCanvasSprite
  • afterSeek: QSqlQuery
  • alignment: QGroupBox QLabel QLayoutItem QLineEdit QMultiLineEdit QStyleSheetItem QTableItem QTextEdit QtMultiLineEdit
  • alignmentRect: QLayout
  • all: QWindowsMime
  • allColumnsShowFocus: QListView
  • allGray: QImage
  • allItems: QCanvas
  • allWidgets: QApplication
  • alloc: QColor QScreen
  • allocation: QWSWindow
  • allowedInContext: QStyleSheetItem
  • allowsErrorInteraction: QSessionManager
  • allowsInteraction: QSessionManager
  • alpha: QGLFormat
  • anchorAt: QSimpleRichText QTextEdit
  • anchorCol: QTableSelection
  • anchorRow: QTableSelection
  • angleLength: QCanvasEllipse
  • angleStart: QCanvasEllipse
  • animateClick: QButton
  • animated: QCanvasItem
  • answerRect: QDragMoveEvent
  • append: QCString QIconDrag QPtrList QSqlCursor QSqlIndex QSqlRecord QString QTextEdit QValueList QXmlAttributes QtMultiLineEdit
  • appendChild: QDomNode
  • appendData: QDomCharacterData
  • applyButtonPressed: QTabDialog
  • appropriate: QMainWindow QWizard
  • area: QDockWindow
  • areaPoints: QCanvasPolygon QCanvasPolygonalItem
  • areaPointsAdvanced: QCanvasPolygonalItem
  • arg: QNPInstance QNetworkOperation QString
  • argc: QApplication QNPInstance
  • argn: QNPInstance
  • arguments: QProcess
  • argv: QApplication QNPInstance
  • arrangeItemsInGrid: QIconView
  • arrangement: QIconView
  • arrowType: QStyleOption
  • asBitArray: QVariant
  • asBitmap: QVariant
  • asBool: QVariant
  • asBrush: QVariant
  • asByteArray: QVariant
  • asCString: QVariant
  • asColor: QVariant
  • asColorGroup: QVariant
  • asCursor: QVariant
  • asDate: QVariant
  • asDateTime: QVariant
  • asDouble: QVariant
  • asFont: QVariant
  • asIconSet: QVariant
  • asImage: QVariant
  • asInt: QVariant
  • asKeySequence: QVariant
  • asList: QVariant
  • asMap: QVariant
  • asPalette: QVariant
  • asPixmap: QVariant
  • asPoint: QVariant
  • asPointArray: QVariant
  • asRect: QVariant
  • asRegion: QVariant
  • asSize: QVariant
  • asSizePolicy: QVariant
  • asString: QVariant
  • asStringList: QVariant
  • asTime: QVariant
  • asUInt: QVariant
  • ascent: QFontMetrics
  • ascii: QKeyEvent
  • assign: QMemArray
  • at: QBitArray QFile QIODevice QMemArray QPtrList QPtrVector QSocket QSqlQuery QSqlResult QString QValueList QValueVector
  • atBeginning: QMultiLineEdit QtMultiLineEdit
  • atEnd: QDataStream QFile QIODevice QMultiLineEdit QSocket QTextStream QtMultiLineEdit
  • atFirst: QAsciiCacheIterator QCacheIterator QIntCacheIterator QPtrListIterator
  • atLast: QAsciiCacheIterator QCacheIterator QIntCacheIterator QPtrListIterator
  • attribute: QDomElement
  • attributeDecl: QXmlDeclHandler
  • attributeNS: QDomElement
  • attributeNode: QDomElement
  • attributeNodeNS: QDomElement
  • attributes: QDomElement QDomNode
  • autoAdd: QLayout
  • autoAdvance: QDateEdit QDateTimeEdit QTimeEdit
  • autoArrange: QIconView
  • autoBottomScrollBar: QListBox
  • autoBufferSwap: QGLWidget
  • autoClose: QProgressDialog
  • autoCompletion: QComboBox
  • autoDefault: QPushButton
  • autoDelete: QAsciiDict QCache QDataTable QDict QIntDict QNetworkProtocol QPtrCollection QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector
  • autoEdit: QDataBrowser QDataTable
  • autoMask: QWidget
  • autoRaise: QToolButton
  • autoRepeat: QButton QCheckBox QPushButton QRadioButton
  • autoReset: QProgressDialog
  • autoScrollBar: QListBox
  • autoUnload: QLibrary
  • autoUpdate: QtMultiLineEdit QtTableView
  • available: QSemaphore QSound
  • back: QValueList QValueVector QWizard
  • backButton: QWizard
  • background: QColorGroup
  • backgroundBrush: QWidget
  • backgroundColor: QCanvas QMovie QPainter
  • backgroundMode: QPainter QWidget
  • backgroundOrigin: QWidget
  • backgroundPixmap: QCanvas
  • backspace: QLineEdit QMultiLineEdit QtMultiLineEdit
  • backward: QTextBrowser
  • backwardAvailable: QTextBrowser
  • base: QColorGroup QScreen
  • baseName: QFileInfo
  • baseSize: QWidget
  • beep: QApplication
  • beforeDelete: QDataBrowser QDataTable
  • beforeInsert: QDataBrowser QDataTable
  • beforeSeek: QSqlQuery
  • beforeUpdate: QDataBrowser QDataTable
  • begin: QMap QMemArray QPainter QValueList QValueVector
  • beginEdit: QTable
  • beginInsert: QDataTable
  • beginTransaction: QSqlDriver
  • beginUpdate: QDataTable
  • bind: QSocketDevice
  • bitBlt: QPaintDevice
  • bitOrder: QImage
  • bitmap: QCursor
  • bits: QImage
  • blank: QScreen
  • blockSignals: QObject
  • blocking: QSocketDevice
  • blue: QColor
  • bold: QFont QFontDatabase QFontInfo QTextEdit
  • bottom: QDoubleValidator QIntValidator QRect
  • bottomDock: QMainWindow
  • bottomEdge: QCanvasSprite
  • bottomLeft: QRect
  • bottomMargin: QScrollView
  • bottomRight: QRect
  • bottomRow: QTableSelection
  • bottomScrollBar: QListBox
  • bound: QRangeControl
  • boundary: QDataBrowser
  • boundaryChecking: QDataBrowser
  • boundedTo: QSize
  • boundingRect: QCanvasItem QCanvasPolygonalItem QCanvasSprite QCanvasText QFontMetrics QPainter QPicture QPointArray QRegion
  • boundingRectAdvanced: QCanvasItem
  • boxLayout: QDockWindow
  • brightText: QColorGroup
  • brush: QCanvasPolygonalItem QColorGroup QPainter QPalette
  • brushOrigin: QPainter
  • bsearch: QMemArray QPtrVector
  • buddy: QLabel
  • buffer: QBuffer
  • button: QColorGroup QMouseEvent
  • buttonSymbols: QSpinBox
  • buttonText: QColorGroup QMessageBox
  • byteOrder: QDataStream
  • bytesAvailable: QSocket QSocketDevice
  • bytesPerLine: QImage
  • bytesToWrite: QSocket
  • bytesWritten: QSocket
  • cache: QScreen
  • cacheLimit: QPixmapCache
  • caching: QFileInfo
  • calcRect: QIconViewItem
  • calculateField: QSqlCursor
  • calibrate: QWSMouseHandler
  • canCast: QVariant
  • canConvert: QWindowsMime
  • canDecode: QColorDrag QIconDrag QImageDrag QTextDrag QUriDrag
  • canDelete: QSqlCursor
  • canEncode: QTextCodec
  • canInsert: QSqlCursor
  • canReadLine: QSocket
  • canReadLineStderr: QProcess
  • canReadLineStdout: QProcess
  • canUpdate: QSqlCursor
  • cancel: QProgressDialog QSessionManager
  • cancelButton: QWizard
  • cancelButtonPressed: QTabDialog
  • cancelRename: QListViewItem
  • cancelled: QProgressDialog
  • canonicalName: QDns
  • canonicalPath: QDir
  • canvas: QCanvasItem QCanvasView
  • cap: QRegExp
  • capStyle: QPen
  • capacity: QValueVector
  • caption: QWSWindow QWidget
  • capturedTexts: QRegExp
  • cascade: QWorkspace
  • caseSensitive: QRegExp
  • cast: QVariant
  • category: QChar
  • cd: QDir
  • cdUp: QDir QUrl
  • cell: QChar
  • cellGeometry: QGridLayout QGridView QTable
  • cellHeight: QGridView QtTableView
  • cellRect: QGridView QTable
  • cellUpdateRect: QtTableView
  • cellWidget: QTable
  • cellWidth: QGridView QtTableView
  • center: QRect QScrollView
  • centerCurrentItem: QListBox
  • centerIndicator: QProgressBar
  • centralWidget: QMainWindow
  • cf: QWindowsMime
  • cfFor: QWindowsMime
  • cfToMime: QWindowsMime
  • changeInterval: QTimer
  • changeItem: QComboBox QListBox QMenuData QPopupMenu
  • changeSize: QSpacerItem
  • changeTab: QTabDialog QTabWidget
  • changed: QImageConsumer
  • channel: QCopChannel
  • charAt: QTextEdit
  • charWidth: QFontMetrics
  • characterAt: QLineEdit
  • characters: QXmlContentHandler
  • checkConnectArgs: QObject
  • checkConnection: QNetworkProtocol
  • checkOverflow: QLCDNumber
  • child: QChildEvent QObject
  • childAt: QWidget
  • childCount: QAccessibleInterface QListView QListViewItem
  • childEvent: QMainWindow QObject QSplitter
  • childNodes: QDomNode
  • childX: QScrollView
  • childY: QScrollView
  • children: QObject
  • childrenRect: QWidget
  • childrenRegion: QWidget
  • chooseContext: QGLContext
  • chooseMacVisual: QGLContext
  • choosePixelFormat: QGLContext
  • chunkSize: QCanvas
  • chunks: QCanvasRectangle
  • classInfo: QMetaObject
  • className: QMetaObject QObject
  • cleanDirPath: QDir
  • cleanText: QSpinBox
  • cleanup: QColor QCursor QFontManager
  • clear: QAccel QAsciiCache QAsciiDict QCache QClipboard QComboBox QDict QDomNode QIconView QIntCache QIntDict QLabel QLineEdit QListBox QListView QMap QMenuBar QMenuData QObjectCleanupHandler QPixmapCache QPopupMenu QPtrCollection QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector QSqlCursor QSqlField QSqlForm QSqlRecord QStatusBar QTextEdit QToolBar QToolTip QTranslator QValueList QValueVector QVariant QXmlAttributes QtMultiLineEdit
  • clearArguments: QProcess
  • clearBit: QBitArray
  • clearCalibration: QWSMouseHandler
  • clearCell: QTable
  • clearCellWidget: QTable
  • clearEdit: QComboBox
  • clearEntries: QUrlOperator
  • clearFocus: QWidget
  • clearGenerated: QIconSet
  • clearMask: QWidget
  • clearOperationQueue: QNetworkProtocol
  • clearParagraphBackground: QTextEdit
  • clearSelection: QAccessibleInterface QIconView QListBox QListView QTable
  • clearTableFlags: QtTableView
  • clearValidator: QComboBox QLineEdit
  • clearValues: QDataBrowser QDataView QSqlForm QSqlRecord
  • clearWFlags: QWidget
  • clicked: QButton QButtonGroup QCheckBox QHeader QIconView QListBox QListView QPushButton QRadioButton QTable QWhatsThis
  • client: QWSWindow
  • clientWindows: QWSServer
  • clipRegion: QPainter
  • clipboard: QApplication
  • clipper: QScrollView
  • cloneNode: QDomNode
  • close: QFile QIODevice QSocket QSqlDatabase QSqlDriver QWSDecoration QWidget
  • closeAllWindows: QApplication
  • closeEvent: QWidget
  • closeKeyboard: QWSServer
  • closeMode: QDockWindow
  • closeMouse: QWSServer
  • closeStdin: QProcess
  • closed: QCanvasSpline
  • closingDown: QApplication
  • clut: QScreen
  • cmd: QPaintDevice
  • codecForContent: QTextCodec
  • codecForIndex: QTextCodec
  • codecForLocale: QTextCodec
  • codecForMib: QTextCodec
  • codecForName: QTextCodec
  • col: QTableItem
  • colIsVisible: QtTableView
  • colSpan: QTableItem
  • colStretch: QGridLayout
  • colXPos: QtTableView
  • collapsed: QListView
  • collidesWith: QCanvasItem
  • collisions: QCanvas QCanvasItem
  • color: QBrush QCanvasText QColorGroup QImage QPalette QPen QStyleOption QStyleSheetItem QTextEdit
  • colorGroup: QWidget
  • colorMode: QPrinter
  • colorSpec: QApplication
  • colorTable: QImage
  • colormap: QGLWidget
  • columnAlignment: QListView
  • columnAt: QGridView QTable
  • columnClicked: QTable
  • columnIndexChanged: QTable
  • columnMode: QListBox
  • columnMovingEnabled: QTable
  • columnNumber: QXmlLocator QXmlParseException
  • columnPos: QTable
  • columnText: QListView
  • columnWidth: QListView QTable
  • columnWidthChanged: QTable
  • columnWidthMode: QListView
  • columns: QGroupBox QListView QPopupMenu
  • combiningClass: QChar
  • comment: QTranslatorMessage QXmlLexicalHandler
  • commit: QSqlDatabase
  • commitData: QApplication
  • commitTransaction: QSqlDriver
  • commonPrefix: QTranslatorMessage
  • communication: QProcess
  • compare: QIconViewItem QListViewItem QString
  • compareItems: QPtrList QPtrVector
  • complete: QNPStream
  • compose: QString
  • confirmCancel: QDataBrowser QDataTable
  • confirmCancels: QDataBrowser QDataTable
  • confirmDelete: QDataBrowser QDataTable
  • confirmEdit: QDataBrowser QDataTable
  • confirmEdits: QDataBrowser QDataTable
  • confirmInsert: QDataBrowser QDataTable
  • confirmUpdate: QDataBrowser QDataTable
  • connect: QAsyncIO QObject QScreen QSignal QSocketDevice
  • connectItem: QAccel QMenuData QPopupMenu
  • connectNotify: QObject
  • connectResize: QMovie
  • connectStatus: QMovie
  • connectToHost: QSocket
  • connectUpdate: QMovie
  • connected: QSocket
  • connectionClosed: QSocket
  • connectionStateChanged: QNetworkProtocol QUrlOperator
  • constPolish: QWidget
  • constref: QString
  • consume: QContextMenuEvent
  • contains: QCString QDomNamedNodeMap QIconViewItem QMap QMemArray QPtrList QPtrVector QRect QRegion QSqlDatabase QSqlRecord QSqlRecordInfo QString QTranslator QValueList
  • containsRef: QPtrList QPtrVector
  • contentHandler: QXmlReader
  • contentsContextMenuEvent: QScrollView
  • contentsDragEnterEvent: QScrollView QTable
  • contentsDragLeaveEvent: QScrollView QTable
  • contentsDragMoveEvent: QScrollView QTable
  • contentsDropEvent: QScrollView QTable
  • contentsHeight: QScrollView
  • contentsMouseDoubleClickEvent: QListView QScrollView
  • contentsMouseMoveEvent: QListView QScrollView
  • contentsMousePressEvent: QListView QScrollView
  • contentsMouseReleaseEvent: QListView QScrollView
  • contentsMoving: QScrollView
  • contentsRect: QFrame
  • contentsToViewport: QScrollView
  • contentsWheelEvent: QScrollView
  • contentsWidth: QScrollView
  • contentsX: QScrollView
  • contentsY: QScrollView
  • context: QGLWidget QSimpleRichText QTextEdit QTranslatorMessage
  • contextMenuEvent: QWidget
  • contextMenuRequested: QIconView QListBox QListView QTable
  • contexts: QStyleSheetItem
  • controlAt: QAccessibleInterface
  • controlPoints: QCanvasSpline
  • convertBitOrder: QImage
  • convertDepth: QImage
  • convertDepthWithPalette: QImage
  • convertFromImage: QPixmap
  • convertFromMime: QWindowsMime
  • convertFromPlainText: QStyleSheet
  • convertSeparators: QDir
  • convertToAbs: QDir QFileInfo
  • convertToGLFormat: QGLWidget
  • convertToImage: QPixmap
  • convertToMime: QWindowsMime
  • convertor: QWindowsMime
  • convertorName: QWindowsMime
  • coords: QRect
  • copy: QBitArray QCString QImage QLineEdit QMemArray QPalette QPicture QPointArray QTextEdit QUrlOperator QtMultiLineEdit
  • copyAvailable: QTextEdit QtMultiLineEdit
  • cornerWidget: QScrollView
  • count: QAccel QAsciiCache QAsciiCacheIterator QAsciiDict QAsciiDictIterator QButtonGroup QCache QCacheIterator QCanvasPixmapArray QComboBox QComboTableItem QDict QDictIterator QDir QDockArea QDomNamedNodeMap QDomNodeList QFocusData QHeader QIconView QIntCache QIntCacheIterator QIntDict QIntDictIterator QKeyEvent QListBox QMap QMemArray QMenuData QPtrCollection QPtrDict QPtrDictIterator QPtrList QPtrListIterator QPtrQueue QPtrStack QPtrVector QSqlForm QSqlRecord QTabBar QTabWidget QValueList QXmlAttributes
  • countCf: QWindowsMime
  • create: QGLContext QImage QNPlugin QSqlDriverPlugin QStyleFactory QStylePlugin QWidget QWidgetFactory QWidgetPlugin
  • createAlphaMask: QImage
  • createAttribute: QDomDocument
  • createAttributeNS: QDomDocument
  • createCDATASection: QDomDocument
  • createComment: QDomDocument
  • createDockWindowMenu: QMainWindow
  • createDocument: QDomImplementation
  • createDocumentFragment: QDomDocument
  • createDocumentType: QDomImplementation
  • createEditor: QEditorFactory QSqlEditorFactory QTable QTableItem
  • createElement: QDomDocument
  • createElementNS: QDomDocument
  • createEntityReference: QDomDocument
  • createForMib: QTextCodecPlugin
  • createForName: QTextCodecPlugin
  • createGfx: QScreen
  • createHeuristicMask: QImage QPixmap
  • createPopupMenu: QLineEdit QTextEdit
  • createProcessingInstruction: QDomDocument
  • createQuery: QSqlDriver
  • createTextNode: QDomDocument
  • createWidget: QWidgetFactory
  • created: QFileInfo
  • createdDirectory: QNetworkProtocol QUrlOperator
  • creator: QPrinter
  • critical: QMessageBox
  • cubicBezier: QPointArray
  • currEditCol: QTable
  • currEditRow: QTable
  • current: QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QDir QGLayoutIterator QIntCacheIterator QIntDictIterator QLayoutIterator QListViewItemIterator QPtrDictIterator QPtrList QPtrListIterator QPtrQueue QPtrStack
  • currentAlignmentChanged: QTextEdit
  • currentAllocContext: QColor
  • currentChanged: QDataBrowser QDataTable QIconView QListBox QListView QTabDialog QTabWidget QTable
  • currentColorChanged: QTextEdit
  • currentColumn: QTable
  • currentContext: QGLContext
  • currentDate: QDate
  • currentDateTime: QDateTime
  • currentDirPath: QDir
  • currentEdited: QDataBrowser
  • currentFontChanged: QTextEdit
  • currentItem: QComboBox QComboTableItem QIconView QListBox QListView
  • currentKey: QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QIntCacheIterator QIntDictIterator QPtrDictIterator
  • currentNode: QPtrList
  • currentPage: QTabDialog QTabWidget QWizard
  • currentPageIndex: QTabWidget
  • currentRecord: QDataTable
  • currentRow: QTable
  • currentSelection: QTable
  • currentTab: QTabBar
  • currentText: QComboBox QComboTableItem QListBox
  • currentThread: QThread
  • currentTime: QTime
  • currentValueText: QSpinBox
  • currentVerticalAlignmentChanged: QTextEdit
  • cursor: QWidget
  • cursorBackward: QLineEdit
  • cursorChanged: QDataBrowser QDataTable
  • cursorDown: QMultiLineEdit QtMultiLineEdit
  • cursorFlashTime: QApplication
  • cursorForward: QLineEdit
  • cursorLeft: QMultiLineEdit QtMultiLineEdit
  • cursorName: QSqlIndex
  • cursorPoint: QMultiLineEdit QtMultiLineEdit
  • cursorPos: QIMEvent
  • cursorPosition: QLineEdit
  • cursorPositionChanged: QTextEdit
  • cursorRight: QMultiLineEdit QtMultiLineEdit
  • cursorUp: QMultiLineEdit QtMultiLineEdit
  • cursorWordBackward: QLineEdit QMultiLineEdit QtMultiLineEdit
  • cursorWordForward: QLineEdit QMultiLineEdit QtMultiLineEdit
  • customColor: QColorDialog
  • customCount: QColorDialog
  • customEvent: QObject
  • customWhatsThis: QWidget
  • customize: QMainWindow
  • cut: QLineEdit QTextEdit QtMultiLineEdit
  • dark: QColor QColorGroup
  • data: QClipboard QCustomEvent QDomCharacterData QDomProcessingInstruction QIconDragItem QMapConstIterator QMapIterator QMemArray QMimeSourceFactory QNetworkProtocol QPicture QPtrVector QSqlResult QUrlOperator QXmlInputSource
  • dataBytesWritten: QFtp
  • dataChanged: QClipboard
  • dataClosed: QFtp
  • dataConnected: QFtp
  • dataReadyRead: QFtp
  • dataTransferProgress: QNetworkProtocol QUrlOperator
  • database: QSqlDatabase
  • databaseName: QSqlDatabase
  • databaseText: QSqlError
  • date: QDateEdit QDateTime
  • dateEdit: QDateTimeEdit
  • dateFormat: QDataTable
  • dateTime: QDateTimeEdit
  • day: QDate
  • dayOfWeek: QDate
  • dayOfYear: QDate
  • daysInMonth: QDate
  • daysInYear: QDate
  • daysTo: QDate QDateTime
  • deciPointSize: QFont
  • decimals: QDoubleValidator
  • declHandler: QXmlReader
  • decode: QColorDrag QImageDecoder QImageDrag QImageFormat QTextDrag QUriDrag QUrl
  • decodeLocalFiles: QUriDrag
  • decodeName: QFile
  • decodeToUnicodeUris: QUriDrag
  • decoderFor: QImageFormatType
  • decomposition: QChar
  • decompositionTag: QChar
  • defaultButtonPressed: QTabDialog
  • defaultCodec: QApplication
  • defaultDepth: QPixmap
  • defaultFactory: QEditorFactory QMimeSourceFactory QSqlEditorFactory
  • defaultFamily: QFont
  • defaultFormat: QGLFormat
  • defaultMap: QSqlPropertyMap
  • defaultOptimization: QPixmap
  • defaultOverlayFormat: QGLFormat
  • defaultRenameAction: QListView
  • defaultSheet: QStyleSheet
  • defaultTabStop: QtMultiLineEdit
  • defaultValue: QSqlFieldInfo
  • defineIOHandler: QImageIO
  • definesFontItalic: QStyleSheetItem
  • definesFontStrikeOut: QStyleSheetItem
  • definesFontUnderline: QStyleSheetItem
  • del: QDataBrowser QLineEdit QSqlCursor QTextEdit QtMultiLineEdit
  • delay: QToolTipGroup
  • delayedCloseFinished: QSocket
  • deleteAllCodecs: QTextCodec
  • deleteAllItems: QLayout
  • deleteCurrent: QDataBrowser QDataTable QLayoutIterator
  • deleteData: QDomCharacterData
  • deleteItem: QPtrCollection
  • deleteLater: QObject
  • deleteNetworkProtocol: QUrlOperator
  • delta: QWheelEvent
  • depth: QDirectPainter QGLFormat QImage QListViewItem QPaintDeviceMetrics QPixmap QScreen
  • dequeue: QPtrQueue
  • descent: QFontMetrics
  • description: QImageIO
  • deselect: QLineEdit QtMultiLineEdit
  • designable: QMetaProperty
  • desktop: QApplication
  • desktopSettingsAware: QApplication
  • destroy: QWidget
  • destroyAllocContext: QColor
  • destroyed: QObject
  • detach: QBitArray QGLColormap QIconSet QImage QMap QMemArray QPicture QPixmap QValueVector
  • device: QDataStream QGLContext QPainter QTabletEvent QTextStream
  • deviceHeight: QScreen
  • deviceIsPixmap: QGLContext
  • deviceWidth: QScreen
  • dialMoved: QDial
  • dialPressed: QDial
  • dialReleased: QDial
  • digitValue: QChar
  • dimensionChange: QGridView
  • dir: QFileDialog QFileInfo
  • dirEntered: QFileDialog
  • dirName: QDir
  • dirPath: QFileDialog QFileInfo QUrl
  • directRendering: QGLFormat
  • directSetValue: QRangeControl
  • direction: QBoxLayout QChar
  • dirty: QFont
  • disabled: QPalette
  • discardCommand: QSessionManager
  • disconnect: QObject QScreen QSignal
  • disconnectItem: QAccel QMenuData QPopupMenu
  • disconnectNotify: QObject
  • disconnectResize: QMovie
  • disconnectStatus: QMovie
  • disconnectUpdate: QMovie
  • display: QLCDNumber QWhatsThis
  • displayMode: QStyleSheetItem
  • displayText: QLineEdit
  • doAutoScroll: QIconView QListView
  • doDefaultAction: QAccessibleInterface
  • doKeyboardAction: QTextEdit
  • doLayout: QListBox
  • docName: QPrinter
  • dock: QDockWindow
  • dockWindowList: QDockArea
  • dockWindowPositionChanged: QMainWindow
  • dockWindows: QMainWindow
  • dockWindowsMovable: QMainWindow
  • doctype: QDomDocument
  • documentElement: QDomDocument
  • documentTitle: QTextEdit
  • done: QDialog
  • doneCurrent: QGLContext
  • dotsPerMeterX: QImage
  • dotsPerMeterY: QImage
  • doubleBuffer: QGLFormat QGLWidget
  • doubleClickInterval: QApplication
  • doubleClicked: QIconView QListBox QListView QTable
  • downRect: QSpinBox
  • drag: QDragObject
  • dragAutoScroll: QScrollView
  • dragCopy: QDragObject
  • dragEnabled: QIconViewItem QLineEdit QListViewItem QTable
  • dragEnterEvent: QWidget
  • dragEntered: QIconViewItem QListViewItem
  • dragLeaveEvent: QWidget
  • dragLeft: QIconViewItem QListViewItem
  • dragLink: QDragObject
  • dragMove: QDragObject
  • dragMoveEvent: QWidget
  • dragObject: QIconView QListView QTable
  • draggingSlider: QScrollBar
  • draw: QCanvasItem QCanvasPolygonalItem QCanvasSprite QCanvasText QSimpleRichText
  • drawArc: QPainter
  • drawArea: QCanvas
  • drawBackground: QCanvas QIconView
  • drawButton: QButton
  • drawButtonLabel: QButton
  • drawChord: QPainter
  • drawComplexControl: QStyle
  • drawComplexControlMask: QStyle
  • drawContents: QCanvasView QFrame QLCDNumber QLabel QMenuBar QPopupMenu QScrollView QTable
  • drawContentsOffset: QListView QScrollView
  • drawControl: QStyle
  • drawControlMask: QStyle
  • drawConvexPolygon: QPainter
  • drawCubicBezier: QPainter
  • drawEllipse: QPainter
  • drawForeground: QCanvas
  • drawFrame: QFrame
  • drawImage: QPainter
  • drawItem: QPopupMenu QStyle
  • drawLine: QPainter
  • drawLineSegments: QPainter
  • drawPicture: QPainter
  • drawPie: QPainter
  • drawPixmap: QPainter
  • drawPoint: QPainter
  • drawPoints: QPainter
  • drawPolygon: QPainter
  • drawPolyline: QPainter
  • drawPrimitive: QStyle
  • drawRect: QPainter
  • drawRiffles: QPlatinumStyle
  • drawRoundRect: QPainter
  • drawRubber: QIconView
  • drawShape: QCanvasEllipse QCanvasPolygon QCanvasPolygonalItem QCanvasRectangle
  • drawText: QPainter QWidget
  • drawTiledPixmap: QPainter
  • drawWinFocusRect: QPainter
  • driver: QSqlDatabase QSqlQuery QSqlResult
  • driverName: QSqlDatabase
  • driverText: QSqlError
  • drivers: QSqlDatabase
  • drives: QDir
  • dropEnabled: QIconViewItem QListViewItem
  • dropEvent: QWidget
  • dropped: QIconView QIconViewItem QListView QListViewItem QTable
  • dumpObjectInfo: QObject
  • dumpObjectTree: QObject
  • duplicate: QMemArray
  • duplicatesEnabled: QComboBox
  • dx: QWMatrix
  • dy: QWMatrix
  • echoMode: QLineEdit QtMultiLineEdit
  • editBuffer: QSqlCursor
  • editCell: QTable
  • editMode: QTable
  • editType: QTableItem
  • editable: QComboBox
  • edited: QLineEdit QMultiLineEdit QtMultiLineEdit
  • editor: QSpinBox
  • elapsed: QTime
  • elementById: QDomDocument
  • elementsByTagName: QDomDocument QDomElement
  • elementsByTagNameNS: QDomDocument QDomElement
  • emitSelectionChanged: QIconView
  • empty: QMap QValueList QValueVector
  • enableClipper: QScrollView
  • enablePainting: QWSServer
  • enableRewind: QDataSource QIODeviceSource
  • enabled: QToolTipGroup
  • enabledChange: QWidget
  • encode: QUrl
  • encodeName: QFile
  • encodedData: QDropEvent QIconDrag QMimeSource QStoredDrag
  • encodedPathAndQuery: QUrl
  • end: QImageConsumer QLineEdit QMap QMemArray QMultiLineEdit QNPStream QPainter QValueList QValueVector QtMultiLineEdit
  • endCDATA: QXmlLexicalHandler
  • endDTD: QXmlLexicalHandler
  • endDocument: QXmlContentHandler
  • endEdit: QTable
  • endElement: QXmlContentHandler
  • endEntity: QXmlLexicalHandler
  • endPoint: QCanvasLine
  • endPrefixMapping: QXmlContentHandler
  • endsWith: QString
  • enforceSortOrder: QListViewItem
  • enqueue: QPtrQueue
  • ensureCellVisible: QGridView QTable
  • ensureCurrentVisible: QListBox
  • ensureCursorVisible: QTextEdit
  • ensureItemVisible: QIconView QListView
  • ensureVisible: QScrollView
  • enterAllocContext: QColor
  • enterEvent: QWidget
  • enterInstance: QNPWidget
  • enterWhatsThisMode: QWhatsThis
  • enter_loop: QApplication
  • entities: QDomDocumentType
  • entityResolver: QXmlReader
  • entryColor: QGLColormap
  • entryInfoList: QDir
  • entryList: QDir QSettings
  • entryRgb: QGLColormap
  • enumKeys: QMetaProperty
  • eof: QDataSink
  • eor: QRegion
  • equal: QUrlInfo
  • erase: QMap QValueList QValueVector QWidget
  • eraseColor: QWidget
  • erasePixmap: QWidget
  • eraseRect: QPainter
  • erased: QPaintEvent
  • error: QSocket QSocketDevice QStyleSheet QXmlErrorHandler
  • errorCode: QNetworkOperation
  • errorHandler: QXmlReader
  • errorString: QXmlContentHandler QXmlDTDHandler QXmlDeclHandler QXmlEntityResolver QXmlErrorHandler QXmlLexicalHandler
  • escape: QStyleSheet
  • event: QObject QWidget
  • eventFilter: QAccel QListView QObject QScrollView QSpinBox
  • exactMatch: QFont QFontInfo QRegExp
  • exec: QApplication QDialog QPopupMenu QSqlDatabase QSqlQuery
  • exists: QDir QFile QFileInfo
  • exit: QApplication QThread
  • exitStatus: QProcess
  • exit_loop: QApplication
  • expand: QGridLayout
  • expandTo: QTableSelection
  • expanded: QListView
  • expandedTo: QSize
  • expanding: QBoxLayout QGridLayout QLayout QLayoutItem QSizePolicy QSpacerItem QWidgetItem
  • extension: QDialog QFileInfo
  • externalEntityDecl: QXmlDeclHandler
  • falseText: QDataTable
  • families: QFontDatabase
  • family: QFont QFontInfo QTextEdit
  • fatalError: QXmlErrorHandler
  • feature: QXmlReader
  • fetch: QSqlResult
  • fetchData: QXmlInputSource
  • fetchFirst: QSqlResult
  • fetchLast: QSqlResult
  • fetchNext: QSqlResult
  • fetchPrev: QSqlResult
  • field: QSqlRecord
  • fieldAlignment: QDataTable
  • fieldName: QSqlRecord
  • fieldToWidget: QSqlForm
  • fileHighlighted: QFileDialog
  • fileName: QFileInfo QImageIO QSound QUrl
  • filePath: QDir QFileInfo QMimeSourceFactory
  • fileSelected: QFileDialog
  • filesSelected: QFileDialog
  • fill: QBitArray QCString QImage QMemArray QPixmap QPtrVector QString QTextStream
  • fillRect: QPainter
  • filter: QDataBrowser QDataTable QDir QSqlCursor
  • filterSelected: QFileDialog
  • find: QAsciiCache QAsciiDict QButtonGroup QCString QCache QDataTable QDict QGLColormap QIntCache QIntDict QMap QMemArray QPixmapCache QPtrDict QPtrList QPtrVector QSqlRecordInfo QString QTextEdit QValueList QWidget
  • findCol: QtTableView
  • findFirstVisibleItem: QIconView
  • findIndex: QValueList
  • findItem: QIconView QListBox QListView QMenuData
  • findKey: QAccel
  • findLastVisibleItem: QIconView
  • findMessage: QTranslator
  • findNearest: QGLColormap
  • findNext: QPtrList
  • findNextRef: QPtrList
  • findProperty: QMetaObject
  • findRef: QPtrList QPtrVector
  • findRev: QCString QString
  • findRow: QtTableView
  • findWidget: QBoxLayout QGridLayout
  • finishButton: QWizard
  • finished: QMovie QNetworkProtocol QThread QUrlOperator
  • first: QDataBrowser QPtrList QSqlQuery QValueList
  • firstChild: QDomNode QListView QListViewItem
  • firstItem: QIconView QListBox
  • firstRecordAvailable: QDataBrowser
  • fix: QDateEdit
  • fixedExtent: QDockWindow
  • fixedPitch: QFont QFontInfo
  • fixup: QValidator
  • flags: QIODevice QTextStream
  • flush: QApplication QFile QIODevice QPainter QSocket
  • flushX: QApplication
  • focusData: QWidget
  • focusInEvent: QWidget QtMultiLineEdit
  • focusNextPrevChild: QTextEdit QWidget
  • focusOutEvent: QWidget
  • focusPolicy: QWidget
  • focusProxy: QWidget
  • focusStyle: QTable
  • focusWidget: QApplication QFocusData QWidget
  • font: QApplication QCanvasText QFontDatabase QPainter QTextEdit QToolTip QWidget
  • fontChange: QWidget
  • fontFamily: QStyleSheetItem
  • fontInfo: QPainter QWidget
  • fontItalic: QStyleSheetItem
  • fontMetrics: QApplication QPainter QWidget
  • fontSize: QStyleSheetItem
  • fontStrikeOut: QStyleSheetItem
  • fontUnderline: QStyleSheetItem
  • fontWeight: QStyleSheetItem
  • forceShow: QProgressDialog
  • foreground: QColorGroup
  • foregroundColor: QWidget
  • form: QDataBrowser QDataView
  • format: QDropEvent QGLContext QGLWidget QImageDecoder QImageIO QMimeSource
  • formatName: QImageDecoder QImageFormatType
  • formatValue: QSqlDriver
  • forward: QTextBrowser
  • forwardAvailable: QTextBrowser
  • frame: QCanvasSprite QLineEdit
  • frameBuffer: QDirectPainter
  • frameChanged: QFrame
  • frameCount: QCanvasSprite
  • frameDone: QImageConsumer
  • frameGeometry: QWidget
  • frameImage: QMovie
  • frameNumber: QMovie
  • framePixmap: QMovie
  • frameRect: QFrame
  • frameShadow: QFrame QStyleOption
  • frameShape: QFrame QStyleOption
  • frameSize: QWidget
  • frameStyle: QFrame
  • frameWidth: QFrame
  • free: QNetworkOperation
  • fromLast: QValueList
  • fromLatin1: QString
  • fromLocal8Bit: QString
  • fromPage: QPrinter
  • fromRawData: QXmlInputSource
  • fromStrList: QStringList
  • fromString: QDate QDateTime QFont QTime
  • fromStringList: QSqlIndex
  • fromUnicode: QHebrewCodec QTextCodec QTextEncoder
  • fromUtf8: QString
  • front: QValueList QValueVector
  • fullPage: QPrinter
  • fullSpan: QCustomMenuItem
  • gamma: QImageIO
  • geometry: QLayoutItem QWidget
  • get: QFontManager QUrlOperator
  • getCalibration: QWSMouseHandler
  • getColor: QColorDialog
  • getCursorPosition: QTextEdit QtMultiLineEdit
  • getDouble: QInputDialog
  • getExistingDirectory: QFileDialog
  • getFirst: QPtrList
  • getFont: QFontDialog
  • getInteger: QInputDialog
  • getItem: QInputDialog
  • getJavaClass: QNPlugin
  • getJavaEnv: QNPlugin
  • getJavaPeer: QNPInstance
  • getLast: QPtrList
  • getLocation: QMainWindow
  • getMIMEDescription: QNPlugin
  • getMarkedRegion: QMultiLineEdit QtMultiLineEdit
  • getNetworkProtocol: QNetworkProtocol QUrlOperator
  • getOpenFileName: QFileDialog
  • getOpenFileNames: QFileDialog
  • getPluginDescriptionString: QNPlugin
  • getPluginNameString: QNPlugin
  • getRange: QSplitter
  • getRgba: QColorDialog
  • getSaveFileName: QFileDialog
  • getSelection: QLineEdit QTextEdit
  • getString: QtMultiLineEdit
  • getText: QInputDialog
  • getURL: QNPInstance
  • getURLNotify: QNPInstance
  • getValidRect: QMovie
  • getVersionInfo: QNPlugin
  • getWFlags: QWidget
  • getch: QFile QIODevice QSocket
  • glDraw: QGLWidget
  • glInit: QGLWidget
  • globalPos: QContextMenuEvent QMouseEvent QTabletEvent QWheelEvent
  • globalStrut: QApplication
  • globalX: QContextMenuEvent QMouseEvent QTabletEvent QWheelEvent
  • globalY: QContextMenuEvent QMouseEvent QTabletEvent QWheelEvent
  • gotFocus: QFocusEvent
  • grabFrameBuffer: QGLWidget
  • grabKeyboard: QWidget
  • grabMouse: QWidget
  • grabWidget: QPixmap
  • grabWindow: QPixmap
  • greaterThan: QUrlInfo
  • green: QColor
  • grep: QStringList
  • gridSize: QGridView
  • gridX: QIconView
  • gridY: QIconView
  • group: QButton QCheckBox QFileInfo QPushButton QRadioButton QToolTip QUrlInfo QWidgetPlugin
  • groupId: QFileInfo
  • guiThreadAwake: QApplication
  • hMargin: QtMultiLineEdit
  • hScrollBarMode: QScrollView
  • handle: QCursor QFile QFont QPaintDevice QPainter QRegion QSessionManager
  • handleError: QDataBrowser QDataTable
  • handlePosition: QDockArea
  • hasAlphaBuffer: QImage
  • hasApplyButton: QTabDialog
  • hasAttribute: QDomElement
  • hasAttributeNS: QDomElement
  • hasAttributes: QDomNode
  • hasCancelButton: QTabDialog
  • hasChildNodes: QDomNode
  • hasClipping: QPainter
  • hasDefaultButton: QTabDialog
  • hasDockWindow: QDockArea QMainWindow
  • hasFeature: QDomImplementation QSqlDriver QXmlReader
  • hasFocus: QWidget
  • hasGlobalMouseTracking: QApplication
  • hasHeightForWidth: QBoxLayout QGridLayout QLayoutItem QSizePolicy
  • hasHelpButton: QTabDialog
  • hasHost: QUrl
  • hasMarkedText: QMultiLineEdit QtMultiLineEdit
  • hasMouse: QWidget
  • hasMouseTracking: QWidget
  • hasOkButton: QTabDialog
  • hasOnlyLocalFileSystem: QNetworkProtocol
  • hasOpenGL: QGLFormat
  • hasOpenGLOverlays: QGLFormat
  • hasOverlay: QGLFormat
  • hasPassword: QUrl
  • hasPath: QUrl
  • hasPendingEvents: QApplication
  • hasPort: QUrl
  • hasProperty: QXmlReader
  • hasRef: QUrl
  • hasScaledContents: QLabel
  • hasSelectedText: QLineEdit QTextEdit
  • hasStaticBackground: QScrollView
  • hasUser: QUrl
  • hasViewXForm: QPainter
  • hasWorldXForm: QPainter
  • hash: QTranslatorMessage
  • head: QPtrQueue
  • header: QListView
  • headerWidth: QHeader
  • height: QCanvas QCanvasEllipse QCanvasRectangle QCanvasSprite QDirectPainter QFontMetrics QIconViewItem QImage QListBoxItem QListBoxPixmap QListBoxText QListViewItem QPaintDeviceMetrics QPixmap QRect QScreen QSimpleRichText QSize QWidget
  • heightForWidth: QBoxLayout QGridLayout QLayoutItem QMenuBar QTextEdit QWidget
  • heightMM: QPaintDeviceMetrics
  • help: QWizard
  • helpButton: QWizard
  • helpButtonPressed: QTabDialog
  • helpClicked: QWizard
  • heuristicContentMatch: QTextCodec
  • heuristicNameMatch: QTextCodec
  • hide: QCanvasItem QMenuBar QToolTip QWSWindow QWidget
  • hideColumn: QTable
  • hideEvent: QScrollBar QWidget
  • hideOrShow: QStatusBar
  • hideRow: QTable
  • highPriority: QObject
  • highlight: QColorGroup
  • highlighted: QComboBox QListBox QMenuBar QPopupMenu QTextBrowser
  • highlightedText: QColorGroup
  • hitButton: QButton
  • home: QDir QFocusData QLineEdit QMultiLineEdit QTextBrowser QtMultiLineEdit
  • homeDirPath: QDir
  • horData: QSizePolicy
  • horStretch: QSizePolicy
  • horizontalAlignment: QApplication
  • horizontalHeader: QTable
  • horizontalScrollBar: QScrollView QtTableView
  • host: QUrl
  • hostFound: QSocket
  • hostName: QSqlDatabase
  • hostNames: QDns
  • hotSpot: QCursor
  • hour: QTime
  • hsv: QColor
  • icon: QMessageBox QWidget
  • iconPixmap: QMessageBox
  • iconProvider: QFileDialog
  • iconSet: QAction QHeader QMenuData QPopupMenu QPushButton QTab QToolButton QWidgetPlugin
  • iconSize: QIconSet
  • iconText: QWidget
  • iconView: QIconViewItem
  • id: QButtonGroup QWidgetStack
  • idAfter: QSplitter
  • idAt: QMenuData QPopupMenu
  • identifier: QTab
  • ignorableWhitespace: QXmlContentHandler
  • ignore: QCloseEvent QContextMenuEvent QDragMoveEvent QDropEvent QIMEvent QKeyEvent QMouseEvent QTabletEvent QWheelEvent
  • imComposeEvent: QWidget
  • imEndEvent: QWidget
  • imStartEvent: QWidget
  • image: QCanvasPixmapArray QCanvasSprite QClipboard QImageDecoder QImageIO
  • imageAdvanced: QCanvasSprite
  • imageFormat: QImage QImageIO QPixmap
  • implementation: QDomDocument
  • importNode: QDomDocument
  • inFont: QFontMetrics
  • inSort: QPtrList
  • inText: QSimpleRichText
  • inWhatsThisMode: QWhatsThis
  • inactive: QPalette
  • includeFile: QWidgetPlugin
  • indent: QLabel QTextEdit
  • index: QIconView QIconViewItem QListBox QSqlCursor QXmlAttributes
  • indexChange: QHeader
  • indexOf: QDataTable QMenuData QTabBar QTabWidget QTable QWizard
  • indicatorFollowsStyle: QProgressBar
  • info: QUrlOperator
  • information: QMessageBox
  • inherits: QMetaObject QObject
  • init: QTableSelection
  • initCursor: QScreen
  • initDevice: QScreen
  • initialize: QColor QCursor QFontManager QWindowsMime
  • initializeGL: QGLWidget
  • initializeOverlayGL: QGLWidget
  • initialized: QGLContext
  • inputFormatList: QImage
  • inputFormats: QImage QImageDecoder QImageIO
  • insert: QAsciiCache QAsciiDict QButtonGroup QCString QCache QDataBrowser QDict QIntCache QIntDict QLineEdit QMap QPixmapCache QPtrDict QPtrList QPtrVector QSqlCursor QSqlForm QSqlPropertyMap QSqlRecord QString QTextEdit QTranslator QValueList QValueVector QtMultiLineEdit
  • insertAfter: QDomNode
  • insertAndMark: QMultiLineEdit
  • insertAt: QMultiLineEdit QTextEdit QtMultiLineEdit
  • insertBefore: QDomNode
  • insertChar: QtMultiLineEdit
  • insertChild: QObject
  • insertColumns: QTable
  • insertCurrent: QDataBrowser QDataTable
  • insertData: QDomCharacterData
  • insertInGrid: QIconView
  • insertItem: QAccel QBoxLayout QComboBox QIconView QListBox QListView QListViewItem QMenuBar QMenuData QPopupMenu
  • insertLayout: QBoxLayout
  • insertLine: QMultiLineEdit QtMultiLineEdit
  • insertPage: QWizard
  • insertParagraph: QTextEdit
  • insertRows: QTable
  • insertSearchPath: QSettings
  • insertSeparator: QMenuBar QMenuData QPopupMenu
  • insertSpacing: QBoxLayout
  • insertStrList: QComboBox QListBox
  • insertStretch: QBoxLayout
  • insertStringList: QComboBox QListBox
  • insertSubstitution: QFont
  • insertSubstitutions: QFont
  • insertTab: QTabBar QTabDialog QTabWidget
  • insertTearOffHandle: QPopupMenu
  • insertWidget: QBoxLayout QTable
  • inserted: QChildEvent
  • insertionPolicy: QComboBox
  • insideMargin: QGroupBox
  • insideSpacing: QGroupBox
  • installDefaultFactory: QEditorFactory QSqlEditorFactory
  • installDefaultMap: QSqlPropertyMap
  • installEditorFactory: QDataTable
  • installEventFilter: QObject
  • installIOHandler: QImageFormatPlugin
  • installPropertyMap: QDataTable QSqlForm
  • installTranslator: QApplication
  • instance: QNPStream QNPWidget
  • intValue: QLCDNumber
  • internalEntityDecl: QXmlDeclHandler
  • internalGfx: QPainter
  • internalSubset: QDomDocumentType
  • interpretText: QSpinBox
  • intersect: QRect QRegion
  • intersects: QIconViewItem QRect
  • invalidate: QBoxLayout QGridLayout QLayout QLayoutItem
  • invalidateHeight: QListViewItem
  • inverseWorldMatrix: QCanvasView
  • invert: QWMatrix
  • invertPixels: QImage
  • invertSelection: QIconView QListBox QListView
  • ioDevice: QImageIO
  • ip4Addr: QHostAddress
  • isA: QObject
  • isAccepted: QCloseEvent QContextMenuEvent QDropEvent QIMEvent QKeyEvent QMouseEvent QTabletEvent QWheelEvent
  • isActionAccepted: QDropEvent
  • isActive: QCanvasItem QPainter QSqlQuery QSqlResult QTableSelection QTimer
  • isActiveWindow: QWidget QXtWidget
  • isAnchor: QStyleSheetItem
  • isAsynchronous: QIODevice
  • isAttr: QDomAttr QDomNode
  • isAutoRepeat: QKeyEvent
  • isAvailable: QSound
  • isBitmapScalable: QFontDatabase
  • isBuffered: QIODevice
  • isCDATASection: QDomCDATASection QDomNode
  • isCalculated: QSqlCursor QSqlFieldInfo
  • isCharacterData: QDomCharacterData QDomNode
  • isCheckable: QPopupMenu
  • isChecked: QCheckBox QCheckTableItem QRadioButton
  • isClickEnabled: QHeader
  • isCloseEnabled: QDockWindow
  • isColumnReadOnly: QTable
  • isColumnSelected: QTable
  • isColumnStretchable: QTable
  • isCombinedAccess: QIODevice
  • isComment: QDomComment QDomNode
  • isConsumed: QContextMenuEvent
  • isContainer: QWidgetPlugin
  • isContentsPreviewEnabled: QFileDialog
  • isCopyOf: QFont QPalette
  • isCurrent: QListBoxItem
  • isCustomizable: QMainWindow
  • isDefault: QPushButton QStyleOption
  • isDefaultUp: QMenuBar
  • isDescending: QSqlIndex
  • isDesktop: QWidget
  • isDialog: QWidget
  • isDigit: QChar
  • isDir: QFileInfo QUrlInfo QUrlOperator
  • isDirectAccess: QIODevice
  • isDockEnabled: QMainWindow
  • isDockMenuEnabled: QMainWindow
  • isDockWindowAccepted: QDockArea
  • isDocument: QDomDocument QDomNode
  • isDocumentFragment: QDomDocumentFragment QDomNode
  • isDocumentType: QDomDocumentType QDomNode
  • isDown: QButton QCheckBox QPushButton QRadioButton
  • isEditable: QComboTableItem
  • isEditing: QTable
  • isEffectEnabled: QApplication
  • isElement: QDomElement QDomNode
  • isEmpty: QAsciiCache QAsciiCacheIterator QAsciiDict QAsciiDictIterator QCString QCache QCacheIterator QDict QDictIterator QDockArea QGLColormap QIntCache QIntCacheIterator QIntDict QIntDictIterator QLayout QLayoutItem QMap QMemArray QObjectCleanupHandler QPtrDict QPtrDictIterator QPtrList QPtrListIterator QPtrQueue QPtrStack QPtrVector QRect QRegExp QRegion QSize QSpacerItem QSqlRecord QString QValueList QWidgetItem
  • isEnabled: QAccel QAction QCanvasItem QLayout QListViewItem QSocketNotifier QTab QTableItem QWidget
  • isEnabledTo: QWidget
  • isEndOfParagraph: QtMultiLineEdit
  • isEntity: QDomEntity QDomNode
  • isEntityReference: QDomEntityReference QDomNode
  • isEnumType: QMetaProperty
  • isExclusive: QActionGroup QButtonGroup
  • isExclusiveToggle: QButton QCheckBox QPushButton QRadioButton
  • isExecutable: QFileInfo QUrlInfo
  • isExpandable: QListViewItem
  • isExtDev: QPaintDevice
  • isFile: QFileInfo QUrlInfo
  • isFinished: QSound
  • isFixedPitch: QFontDatabase
  • isFlat: QPushButton
  • isFocusEnabled: QWidget
  • isForwardOnly: QSqlResult
  • isFullyObscured: QWSWindow
  • isGenerated: QIconSet QSqlFieldInfo QSqlRecord
  • isGloballyEnabled: QToolTip
  • isGrayscale: QImage
  • isHidden: QWidget
  • isHorizontallyStretchable: QDockWindow
  • isIdentity: QWMatrix
  • isInactive: QIODevice
  • isInfoPreviewEnabled: QFileDialog
  • isInterlaced: QScreen
  • isInvertible: QWMatrix
  • isIp4Addr: QHostAddress
  • isItemActive: QMenuData
  • isItemChecked: QMenuData QPopupMenu
  • isItemEnabled: QAccel QMenuBar QMenuData QPopupMenu
  • isLetter: QChar
  • isLetterOrNumber: QChar
  • isLoaded: QLibrary
  • isLocalFile: QUrl
  • isMark: QChar
  • isMaximized: QWidget
  • isMinimized: QWidget
  • isModal: QWidget
  • isModified: QTextEdit
  • isMovingEnabled: QDockWindow QHeader
  • isMultiSelection: QListView
  • isNotation: QDomNode QDomNotation
  • isNull: QCString QChar QDate QDateTime QDomImplementation QDomNode QGuardedPtr QIconSet QImage QMemArray QMovie QPicture QPixmap QPoint QPtrVector QRect QRegion QSize QSqlField QSqlQuery QSqlRecord QSqlResult QString QTime
  • isNumber: QChar
  • isOn: QAction QButton QCheckBox QCheckListItem QPushButton QRadioButton
  • isOpen: QIODevice QListView QListViewItem QSqlDatabase QSqlDriver
  • isOpenError: QSqlDatabase QSqlDriver
  • isOverwriteMode: QTextEdit QtMultiLineEdit
  • isPartiallyObscured: QWSWindow
  • isPhase2: QSessionManager
  • isPopup: QWidget
  • isPrint: QChar
  • isPrintableData: QDataStream
  • isProcessingInstruction: QDomNode QDomProcessingInstruction
  • isPunct: QChar
  • isQBitmap: QPixmap
  • isRadioButtonExclusive: QButtonGroup
  • isRaw: QIODevice
  • isReadOnly: QDataBrowser QLineEdit QSqlCursor QSqlField QTable QTextEdit QtMultiLineEdit
  • isReadWrite: QIODevice
  • isReadable: QDir QFileInfo QIODevice QUrlInfo
  • isRedoAvailable: QLineEdit QTextEdit
  • isRegistered: QCopChannel
  • isRelative: QDir QFileInfo
  • isRelativePath: QDir
  • isRelativeUrl: QUrl
  • isRenaming: QIconView QListView
  • isReplaceable: QTableItem
  • isRequired: QSqlFieldInfo
  • isResizeEnabled: QDockWindow QHeader
  • isRoot: QDir
  • isRowReadOnly: QTable
  • isRowSelected: QTable
  • isRowStretchable: QTable
  • isRubberSelecting: QListBox
  • isRunning: QProcess
  • isScalable: QFontDatabase
  • isSelect: QSqlQuery QSqlResult
  • isSelectable: QIconViewItem QListBoxItem QListViewItem
  • isSelected: QCanvasItem QIconViewItem QListBox QListBoxItem QListView QListViewItem QTable
  • isSeparator: QCustomMenuItem
  • isSequentialAccess: QIODevice
  • isSessionRestored: QApplication
  • isSetType: QMetaProperty
  • isSharing: QGLContext QGLWidget
  • isSizeGripEnabled: QDialog QStatusBar
  • isSmoothlyScalable: QFontDatabase
  • isSpace: QChar
  • isStretchEnabled: QHeader
  • isStretchable: QDockWindow
  • isSupported: QDomNode
  • isSymLink: QFileInfo QUrlInfo
  • isSymbol: QChar
  • isSynchronous: QIODevice
  • isTabEnabled: QTabBar QTabDialog QTabWidget
  • isText: QDomNode QDomText
  • isToggleAction: QAction
  • isToggleButton: QButton QCheckBox QPushButton QRadioButton
  • isTopLevel: QLayout QWidget
  • isTransformed: QScreen
  • isTranslated: QIODevice
  • isTrim: QSqlFieldInfo
  • isTrimmed: QSqlCursor
  • isTristate: QCheckBox
  • isUndoAvailable: QLineEdit QTextEdit
  • isUndoEnabled: QtMultiLineEdit
  • isUndoRedoEnabled: QTextEdit
  • isUpdatesEnabled: QWidget
  • isValid: QAccessibleInterface QCanvasPixmapArray QColor QDate QDateTime QGLContext QGLWidget QLock QRect QRegExp QSize QSocketDevice QSqlQuery QSqlResult QTime QUrl QUrlInfo QVariant
  • isVerticallyStretchable: QDockWindow
  • isVirtualDesktop: QDesktopWidget
  • isVisible: QCanvasItem QListViewItem QWSWindow QWidget
  • isVisibleTo: QWidget
  • isWidgetType: QObject
  • isWorking: QDns
  • isWritable: QFileInfo QIODevice QUrlInfo
  • italic: QFont QFontDatabase QFontInfo QTextEdit
  • item: QDomNamedNodeMap QDomNodeList QListBox QStyleSheet QTable
  • itemAbove: QListViewItem
  • itemAt: QListBox QListView
  • itemBelow: QListViewItem
  • itemChanged: QNetworkProtocol QUrlOperator
  • itemHeight: QListBox QPopupMenu
  • itemMargin: QListView
  • itemParameter: QMenuData QPopupMenu
  • itemPos: QListView QListViewItem
  • itemRect: QListBox QListView QStyle
  • itemRenamed: QIconView QListView
  • itemTextBackground: QIconView
  • itemTextPos: QIconView
  • itemVisible: QListBox
  • itemsMovable: QIconView
  • iterator: QLayout QLayoutItem
  • join: QStringList
  • joinStyle: QPen
  • joining: QChar
  • jumpTable: QImage
  • key: QAccel QFont QIconViewItem QKeyEvent QListViewItem QMapConstIterator QMapIterator QTableItem
  • keyMap: QWSServer
  • keyPressEvent: QLineEdit QTextBrowser QTextEdit QWidget QtMultiLineEdit
  • keyReleaseEvent: QWidget
  • keyToValue: QMetaProperty
  • keyboardFocusTab: QTabBar
  • keyboardGrabber: QWidget
  • keyboardHandler: QWSServer
  • keys: QImageFormatPlugin QMap QSqlDriverPlugin QStyleFactory QStylePlugin QWidgetPlugin
  • keysToValue: QMetaProperty
  • kill: QProcess
  • killLine: QMultiLineEdit QtMultiLineEdit
  • killTimer: QObject
  • killTimers: QObject
  • label: QDns QHeader QTabWidget QToolBar
  • labelText: QProgressDialog
  • last: QDataBrowser QPtrList QSqlQuery QValueList
  • lastChild: QDomNode
  • lastColVisible: QtTableView
  • lastError: QSqlDatabase QSqlDriver QSqlQuery QSqlResult
  • lastItem: QIconView QListView
  • lastModified: QFileInfo QNPStream QUrlInfo
  • lastOp: QScreen
  • lastQuery: QSqlQuery QSqlResult
  • lastRead: QFileInfo QUrlInfo
  • lastRecordAvailable: QDataBrowser
  • lastResortFamily: QFont
  • lastResortFont: QFont
  • lastRowVisible: QtTableView
  • lastWindowClosed: QApplication
  • latin1: QChar QString
  • launch: QProcess
  • launchFinished: QProcess
  • layOutButtonRow: QWizard
  • layOutTitleRow: QWizard
  • layout: QLayoutItem QWidget
  • layoutTabs: QTabBar
  • leading: QFontMetrics
  • leapYear: QDate
  • leaveAllocContext: QColor
  • leaveEvent: QWidget
  • leaveInstance: QNPWidget
  • leaveWhatsThisMode: QWhatsThis
  • left: QCString QRect QString
  • leftBearing: QFontMetrics
  • leftCell: QtTableView
  • leftCol: QTableSelection
  • leftDock: QMainWindow
  • leftEdge: QCanvasSprite
  • leftJustify: QCString QString
  • leftMargin: QScrollView
  • length: QCString QDomCharacterData QDomNamedNodeMap QDomNodeList QSqlFieldInfo QString QTextEdit QXmlAttributes QtMultiLineEdit
  • lessThan: QUrlInfo
  • lexicalHandler: QXmlReader
  • library: QLibrary
  • libraryPaths: QApplication
  • light: QColor QColorGroup
  • lineEdit: QComboBox
  • lineLength: QMultiLineEdit QtMultiLineEdit
  • lineNumber: QXmlLocator QXmlParseException
  • lineOfChar: QTextEdit
  • lineSpacing: QFontMetrics
  • lineStep: QDial QDirectPainter QRangeControl QScrollBar QSlider QSpinBox
  • lineTo: QPainter
  • lineUp: QDockArea
  • lineUpDockWindows: QMainWindow
  • lineWidth: QFontMetrics QFrame QStyleOption
  • lines: QTextEdit
  • linesOfParagraph: QTextEdit
  • linestep: QScreen
  • link: QColorGroup
  • linkClicked: QTextBrowser
  • linkUnderline: QTextEdit
  • linkVisited: QColorGroup
  • listBegin: QVariant
  • listBox: QComboBox QListBoxItem
  • listChildren: QUrlOperator
  • listEnd: QVariant
  • listStyle: QStyleSheetItem
  • listView: QListViewItem
  • listViewItem: QStyleOption
  • listen: QSocketDevice
  • load: QImage QLibrary QPicture QPixmap QTranslator
  • loadCharmap: QTextCodec
  • loadCharmapFile: QTextCodec
  • loadFromData: QImage QPixmap
  • loadImages: QWidgetFactory
  • local8Bit: QString
  • localFileToUri: QUriDrag
  • localName: QDomNode QXmlAttributes
  • locale: QTextCodec
  • localeAwareCompare: QString
  • lock: QApplication QLock QMutex
  • locked: QApplication QLock QMutex
  • logicalDpiX: QPaintDeviceMetrics
  • logicalDpiY: QPaintDeviceMetrics
  • logicalFontSize: QStyleSheetItem
  • logicalFontSizeStep: QStyleSheetItem
  • longDayName: QDate
  • longMonthName: QDate
  • loopLevel: QApplication
  • loops: QSound
  • loopsRemaining: QSound
  • lostFocus: QFocusEvent
  • lower: QCString QChar QString QWSWindow QWidget
  • m11: QWMatrix
  • m12: QWMatrix
  • m21: QWMatrix
  • m22: QWMatrix
  • macEvent: QWidget
  • macEventFilter: QApplication
  • mailServers: QDns
  • mainWidget: QApplication QLayout
  • mainWindow: QToolBar
  • makeAbsolute: QMimeSourceFactory
  • makeArc: QPointArray
  • makeCurrent: QGLContext QGLWidget
  • makeDecoder: QTextCodec
  • makeEllipse: QPointArray
  • makeEncoder: QTextCodec
  • makeOverlayCurrent: QGLWidget
  • makeRowLayout: QIconView
  • manager: QWSServer
  • manhattanLength: QPoint
  • map: QSignalMapper QWMatrix
  • mapBegin: QVariant
  • mapEnd: QVariant
  • mapFind: QVariant
  • mapFrom: QWidget
  • mapFromDevice: QScreen
  • mapFromGlobal: QWidget
  • mapFromParent: QWidget
  • mapRect: QWMatrix
  • mapTextToValue: QSpinBox
  • mapTo: QWidget
  • mapToDevice: QScreen
  • mapToGlobal: QWidget
  • mapToIndex: QHeader
  • mapToParent: QWidget
  • mapToSection: QHeader
  • mapValueToText: QSpinBox
  • mapped: QSignalMapper
  • margin: QFrame QLayout QStyleSheetItem QTabWidget
  • margins: QPrinter
  • markedText: QMultiLineEdit QtMultiLineEdit
  • mask: QCursor QPixmap
  • match: QDir
  • matchAllDirs: QDir
  • matchedLength: QRegExp
  • maxColOffset: QtTableView
  • maxColors: QColor
  • maxCost: QAsciiCache QCache QIntCache
  • maxCount: QComboBox
  • maxIconWidth: QStyleOption
  • maxItemTextLength: QIconView
  • maxItemWidth: QIconView QListBox
  • maxLength: QLineEdit QtMultiLineEdit
  • maxLineLength: QtMultiLineEdit
  • maxLineWidth: QtMultiLineEdit
  • maxLines: QtMultiLineEdit
  • maxPage: QPrinter
  • maxRowOffset: QtTableView
  • maxValue: QDateEdit QDial QRangeControl QScrollBar QSlider QSpinBox QTimeEdit
  • maxViewX: QtTableView
  • maxViewY: QtTableView
  • maxWidth: QFontMetrics
  • maxXOffset: QtTableView
  • maxYOffset: QtTableView
  • maximize: QWSDecoration
  • maximumHeight: QWidget
  • maximumSize: QBoxLayout QGridLayout QLayout QLayoutItem QSpacerItem QWidget QWidgetItem
  • maximumWidth: QWidget
  • mayGrowHorizontally: QSizePolicy
  • mayGrowVertically: QSizePolicy
  • mayShrinkHorizontally: QSizePolicy
  • mayShrinkVertically: QSizePolicy
  • maybeReady: QDataSink QDataSource
  • maybeTip: QToolTip
  • menu: QWSDecoration
  • menuAboutToShow: QMainWindow
  • menuBar: QLayout QMainWindow
  • menuContentsChanged: QMenuBar QMenuData
  • menuDelPopup: QMenuData
  • menuInsPopup: QMenuData
  • menuItem: QStyleOption
  • menuStateChanged: QMenuBar QMenuData
  • menuText: QAction
  • message: QErrorMessage QStatusBar QXmlParseException
  • messages: QTranslator
  • metaObject: QObject
  • metric: QPicture QPixmap QWidget
  • mibEnum: QEucJpCodec QTextCodec
  • mibEnums: QTextCodecPlugin
  • microFocusHint: QWidget
  • mid: QCString QColorGroup QString
  • midLineWidth: QFrame QStyleOption
  • midlight: QColorGroup
  • mightBeRichText: QStyleSheet
  • mimeFor: QWindowsMime
  • mimeName: QEucJpCodec QEucKrCodec QGbkCodec QHebrewCodec QJisCodec QSjisCodec QTextCodec
  • mimeSourceFactory: QTextEdit
  • minLeftBearing: QFontMetrics
  • minPage: QPrinter
  • minRightBearing: QFontMetrics
  • minValue: QDateEdit QDial QRangeControl QScrollBar QSlider QSpinBox QTimeEdit
  • minViewX: QtTableView
  • minViewY: QtTableView
  • minimal: QRegExp
  • minimize: QWSDecoration
  • minimumDuration: QProgressDialog
  • minimumHeight: QWidget
  • minimumSize: QBoxLayout QGridLayout QLayout QLayoutItem QSpacerItem QWidget QWidgetItem
  • minimumSizeHint: QLineEdit QWidget QtMultiLineEdit
  • minimumWidth: QWidget
  • minute: QTime
  • mirror: QImage
  • mirrored: QChar
  • mirroredChar: QChar
  • mixedColor: QPlatinumStyle
  • mkdir: QDir QUrlOperator
  • mode: QFileDialog QIODevice QLCDNumber QNPInstance QSqlCursor
  • modificationChanged: QTextEdit
  • month: QDate
  • mouseButtonClicked: QIconView QListBox QListView
  • mouseButtonPressed: QIconView QListBox QListView
  • mouseChanged: QWSMouseHandler
  • mouseDoubleClickEvent: QWidget
  • mouseGrabber: QWidget
  • mouseHandler: QWSServer
  • mouseMoveEvent: QSizeGrip QWidget
  • mousePressEvent: QSizeGrip QWidget
  • mouseReleaseEvent: QWidget
  • move: QCanvasItem QCanvasSprite QIconViewItem QWidget
  • moveBottomLeft: QRect
  • moveBottomRight: QRect
  • moveBy: QCanvasItem QIconViewItem QRect
  • moveCenter: QRect
  • moveChild: QScrollView
  • moveCursor: QTextEdit
  • moveDockWindow: QDockArea QMainWindow
  • moveEvent: QWidget
  • moveFocus: QButtonGroup
  • moveItem: QListViewItem
  • moveSection: QHeader
  • moveSplitter: QSplitter
  • moveTo: QPainter
  • moveToFirst: QSplitter
  • moveToLast: QSplitter
  • moveTopLeft: QRect
  • moveTopRight: QRect
  • moved: QIconView
  • movie: QLabel
  • msec: QTime
  • msecsTo: QTime
  • msleep: QThread
  • multiLinesEnabled: QListViewItem
  • name: QColor QDomAttr QDomDocumentType QFile QMetaProperty QObject QSqlCursor QSqlField QSqlFieldInfo QSqlIndex QStyleSheetItem QTextCodec QUrlInfo QWSWindow
  • nameFilter: QDir QUrlOperator
  • nameToType: QVariant
  • namedItem: QDomNamedNodeMap QDomNode
  • namedItemNS: QDomNamedNodeMap
  • names: QTextCodecPlugin
  • namespaceURI: QDomNode
  • navigate: QAccessibleInterface
  • networkOrdered: QChar
  • newChannel: QWSServer
  • newChild: QNetworkProtocol
  • newChildren: QNetworkProtocol QUrlOperator
  • newConnection: QServerSocket
  • newInstance: QNPlugin
  • newItem: QPtrCollection
  • newLine: QDockWindow QMultiLineEdit QtMultiLineEdit
  • newPage: QPrinter
  • newStream: QNPInstance
  • newStreamCreated: QNPInstance
  • newWindow: QNPInstance
  • next: QDataBrowser QFocusData QGLayoutIterator QListBoxItem QPtrList QSqlQuery QWizard QXmlInputSource
  • nextButton: QWizard
  • nextItem: QIconViewItem
  • nextLine: QScrollBar
  • nextPage: QScrollBar
  • nextRecordAvailable: QDataBrowser
  • nextSibling: QDomNode QListViewItem
  • nodeName: QDomNode
  • nodeType: QDomAttr QDomCDATASection QDomCharacterData QDomComment QDomDocument QDomDocumentFragment QDomDocumentType QDomElement QDomEntity QDomEntityReference QDomNode QDomNotation QDomProcessingInstruction QDomText
  • nodeValue: QDomNode
  • normalExit: QProcess
  • normalize: QDomNode QRect
  • normalizeSignalSlot: QObject
  • notationDecl: QXmlDTDHandler
  • notationName: QDomEntity
  • notations: QDomDocumentType
  • notchSize: QDial
  • notchTarget: QDial
  • notchesVisible: QDial
  • notify: QApplication
  • notifyURL: QNPInstance
  • nrefs: QMemArray
  • nullText: QDataTable QSqlDriver
  • numBitPlanes: QColor
  • numBytes: QImage
  • numClassInfo: QMetaObject
  • numColors: QImage QPaintDeviceMetrics
  • numCols: QDataTable QGridLayout QGridView QScreen QTable QtTableView
  • numColumns: QListBox
  • numCopies: QPrinter
  • numDigits: QLCDNumber
  • numItemsVisible: QListBox
  • numLines: QMultiLineEdit QtMultiLineEdit
  • numProperties: QMetaObject
  • numRects: QDirectPainter
  • numRows: QDataTable QGridLayout QGridView QListBox QTable QtTableView
  • numRowsAffected: QSqlQuery QSqlResult
  • numScreens: QDesktopWidget
  • numSelections: QTable
  • numSignals: QMetaObject
  • numSlots: QMetaObject
  • number: QSqlError QString
  • object: QAccessibleObject
  • objectTrees: QObject
  • offset: QDirectPainter QDockWindow QHeader QImage
  • offsetX: QCanvasPixmap
  • offsetY: QCanvasPixmap
  • ok: QServerSocket
  • okRename: QListViewItem
  • okay: QNPStream
  • oldPos: QMoveEvent
  • oldSize: QResizeEvent
  • onCanvas: QCanvas
  • onCard: QScreen
  • onItem: QIconView QListBox QListView
  • onViewport: QIconView QListBox QListView
  • opType: QScreen
  • opaqueMoving: QDockWindow QMainWindow
  • opaqueResize: QSplitter
  • open: QFile QIODevice QSocket QSqlDatabase QSqlDriver
  • openKeyboard: QWSServer
  • openMouse: QWSServer
  • openPopup: QToolButton
  • operation: QNetworkOperation
  • operationGet: QNetworkProtocol
  • operationInProgress: QNetworkProtocol
  • operationListChildren: QNetworkProtocol
  • operationMkDir: QNetworkProtocol
  • operationPut: QNetworkProtocol
  • operationRemove: QNetworkProtocol
  • operationRename: QNetworkProtocol
  • operator QString: QKeySequence QUrl
  • operator T *: QGuardedPtr
  • operator char: QChar
  • operator const char *: QCString QString
  • operator const type *: QMemArray
  • operator int: QBitVal QKeySequence
  • operator type *: QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QIntCacheIterator QIntDictIterator QPtrDictIterator QPtrListIterator QPtrQueue QPtrStack
  • operator!: QString
  • operator!=: QBrush QCString QChar QColor QColorGroup QDate QDateTime QDir QDomImplementation QDomNamedNodeMap QDomNode QDomNodeList QFont QGuardedPtr QImage QKeySequence QMapConstIterator QMapIterator QMemArray QPalette QPen QPoint QRect QRegExp QRegion QSize QSizePolicy QString QTableSelection QTime QTranslatorMessage QValueList QValueListConstIterator QValueListIterator QVariant QWMatrix
  • operator&: QBitArray QRect QRegion
  • operator&=: QBitArray QRect QRegion
  • operator(): QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QIntCacheIterator QIntDictIterator QPtrDictIterator QPtrListIterator
  • operator*: QGuardedPtr QMapConstIterator QMapIterator QPoint QPtrListIterator QSize QValueListConstIterator QValueListIterator QWMatrix
  • operator*=: QPoint QSize QWMatrix
  • operator+: QCString QPoint QRegion QSize QString QValueList
  • operator++: QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QIntCacheIterator QIntDictIterator QLayoutIterator QListViewItemIterator QMapConstIterator QMapIterator QPtrDictIterator QPtrListIterator QSemaphore QValueListConstIterator QValueListIterator
  • operator+=: QAsciiCacheIterator QAsciiDictIterator QCString QCacheIterator QIntCacheIterator QIntDictIterator QListViewItemIterator QPoint QPtrDictIterator QPtrListIterator QRegion QSemaphore QSize QString QValueList
  • operator-: QPoint QRegion QSize
  • operator--: QAsciiCacheIterator QCacheIterator QIntCacheIterator QListViewItemIterator QMapConstIterator QMapIterator QPtrListIterator QSemaphore QValueListConstIterator QValueListIterator
  • operator-=: QAsciiCacheIterator QCacheIterator QIntCacheIterator QListViewItemIterator QPoint QPtrListIterator QRegion QSemaphore QSize
  • operator->: QGuardedPtr
  • operator/: QPoint QSize
  • operator/=: QPoint QSize
  • operator<: QCString QChar QDate QDateTime QString QTime QTranslatorMessage
  • operator<<: QBitArray QBrush QCString QColor QColorGroup QCursor QDataStream QDate QDateTime QDockArea QDomNode QFont QImage QKeySequence QMainWindow QMap QMemArray QPalette QPen QPicture QPixmap QPoint QPointArray QRect QRegion QSize QString QTextStream QTime QValueList QWMatrix
  • operator<=: QCString QChar QDate QDateTime QString QTime QTranslatorMessage
  • operator=: QAsciiCacheIterator QAsciiDict QBitArray QBitVal QBitmap QBrush QCString QCacheIterator QColor QColorGroup QCursor QDict QDir QDomAttr QDomCDATASection QDomCharacterData QDomComment QDomDocument QDomDocumentFragment QDomDocumentType QDomElement QDomEntity QDomEntityReference QDomImplementation QDomNamedNodeMap QDomNode QDomNodeList QDomNotation QDomProcessingInstruction QDomText QFileInfo QFont QFontInfo QFontMetrics QGLColormap QGuardedPtr QHostAddress QIconSet QImage QIntCacheIterator QIntDict fnord QKeySequence QLayoutIterator QListViewItemIterator QMap QMemArray QMovie QObjectList QObjectListIt QPalette QPen QPicture QPixmap QPointArray QPtrDict QPtrList QPtrListIterator QPtrQueue QPtrStack QPtrVector QRegExp QRegion QSortedList QSqlCursor QSqlError QSqlField QSqlFieldInfo QSqlIndex QSqlQuery QSqlRecord QStrList QString QTranslatorMessage QUrl QUrlInfo QValueList QValueVector QVariant
  • operator==: QBrush QCString QChar QColor QColorGroup QDate QDateTime QDir QDomImplementation QDomNamedNodeMap QDomNode QDomNodeList QFont QGuardedPtr QHostAddress QImage QKeySequence QMapConstIterator QMapIterator QMemArray QPalette QPen QPoint QPtrList QPtrVector QRect QRegExp QRegion QSize QSizePolicy QSqlField QSqlFieldInfo QString QTableSelection QTime QTranslatorMessage QUrl QUrlInfo QValueList QValueListConstIterator QValueListIterator QValueVector QVariant QWMatrix
  • operator>: QCString QChar QDate QDateTime QString QTime QTranslatorMessage
  • operator>=: QCString QChar QDate QDateTime QString QTime QTranslatorMessage
  • operator>>: QBitArray QBrush QCString QColor QCursor QDataStream QDate QDateTime QDockArea QFont QImage QKeySequence QMainWindow QMap QMemArray QPalette QPen QPicture QPixmap QPoint QPointArray QRect QRegion QSize QString QTextStream QTime QValueList QWMatrix
  • operator[]: QAsciiCache QAsciiDict QBitArray QCache QDict QDir QIntCache QIntDict QMap QMemArray QPtrDict QPtrVector QString QValueList QValueVector
  • operator^: QBitArray QRegion
  • operator^=: QBitArray QRegion
  • operator|: QBitArray QRect QRegion
  • operator|=: QBitArray QRect QRegion
  • operator~: QBitArray
  • optimization: QPixmap
  • order: QDateEdit
  • orientation: QDialog QDockArea QDockWindow QGroupBox QHeader QPrinter QScrollBar QSlider QSplitter QWheelEvent
  • orientationChanged: QDockWindow
  • origin: QGridLayout
  • outputFileName: QPrinter
  • outputFormatList: QImage
  • outputFormats: QImage QImageIO
  • outputToFile: QPrinter
  • overflow: QLCDNumber
  • overlayContext: QGLWidget
  • overlayTransparentColor: QGLContext
  • overrideCursor: QApplication
  • ownCursor: QWidget
  • ownFont: QWidget
  • ownPalette: QWidget
  • owner: QFileInfo QUrlInfo
  • ownerDocument: QDomNode
  • ownerElement: QDomAttr
  • ownerId: QFileInfo
  • ownsClipboard: QClipboard
  • ownsSelection: QClipboard
  • packImage: QPNGImagePacker
  • page: QTabWidget QWizard
  • pageCount: QWizard
  • pageDown: QMultiLineEdit QtMultiLineEdit
  • pageOrder: QPrinter
  • pageSize: QPrinter
  • pageStep: QDial QRangeControl QScrollBar QSlider
  • pageUp: QMultiLineEdit QtMultiLineEdit
  • paint: QCustomMenuItem QListBoxItem QListBoxPixmap QListBoxText QTabBar QTableItem QWSDecoration
  • paintBranches: QListViewItem
  • paintButton: QWSDecoration
  • paintCell: QCheckListItem QGridView QListBox QListViewItem QTable QtMultiLineEdit QtTableView
  • paintEmptyArea: QGridView QListView QTable
  • paintEvent: QButton QFrame QGLWidget QSizeGrip QStatusBar QTabBar QWidget QtTableView
  • paintField: QDataTable
  • paintFocus: QCheckListItem QIconViewItem QListViewItem QTable
  • paintGL: QGLWidget
  • paintItem: QIconViewItem
  • paintLabel: QTabBar
  • paintOverlayGL: QGLWidget
  • paintSection: QHeader
  • paintSectionLabel: QHeader
  • paintingActive: QPaintDevice
  • palette: QApplication QToolTip QWidget
  • paletteBackgroundColor: QWidget
  • paletteBackgroundPixmap: QWidget
  • paletteChange: QWidget
  • paletteForegroundColor: QWidget
  • paper: QTextEdit
  • paperSource: QPrinter
  • paragraphAt: QTextEdit
  • paragraphBackgroundColor: QTextEdit
  • paragraphLength: QTextEdit
  • paragraphRect: QTextEdit
  • paragraphs: QTextEdit
  • parameters: QImageIO
  • parent: QListViewItem QObject
  • parentNode: QDomNode
  • parentWidget: QToolTip QWidget
  • parse: QUrl QXmlReader QXmlSimpleReader
  • parseContinue: QXmlSimpleReader
  • parseDir: QFtp
  • password: QSqlDatabase QUrl
  • passwordChar: QLineEdit
  • paste: QLineEdit QTextEdit QtMultiLineEdit
  • pasteSubType: QTextEdit QtMultiLineEdit
  • path: QDir QUrl
  • pattern: QRegExp
  • pause: QMovie
  • paused: QMovie
  • peerAddress: QSocket QSocketDevice
  • peerName: QSocket
  • peerPort: QSocket QSocketDevice
  • pen: QCanvasPolygonalItem QPainter
  • percentageVisible: QProgressBar
  • permission: QFileInfo
  • permissions: QUrlInfo
  • picture: QIconViewItem QLabel
  • pixel: QColor QImage
  • pixelIndex: QImage
  • pixelMetric: QStyle
  • pixelSize: QFont QFontInfo
  • pixelType: QScreen
  • pixmap: QBrush QButton QCheckBox QClipboard QComboBox QDragObject QFileIconProvider QIconSet QIconViewItem QLabel QListBox QListBoxItem QListBoxPixmap QListViewItem QMenuData QPopupMenu QPushButton QRadioButton QTable QTableItem
  • pixmapDepth: QScreen
  • pixmapHotSpot: QDragObject
  • pixmapLinestepAlignment: QScreen
  • pixmapOffsetAlignment: QScreen
  • pixmapRect: QIconViewItem
  • pixmapSizeChanged: QMainWindow
  • place: QDockWindow
  • placeChanged: QDockWindow
  • placeCursor: QTextEdit
  • plane: QGLFormat
  • play: QPicture QSound
  • point: QPointArray
  • pointSize: QFont QFontInfo QTextEdit
  • pointSizeFloat: QFont
  • pointSizes: QFontDatabase
  • points: QCanvasPolygon
  • polish: QApplication QStyle QWidget
  • polishPopupMenu: QStyle
  • pop: QPtrStack QValueStack
  • popContext: QXmlNamespaceSupport
  • pop_back: QValueList QValueVector
  • pop_front: QValueList
  • popup: QComboBox QPopupMenu QPushButton QToolButton
  • popupDelay: QToolButton
  • port: QServerSocket QSocket QSocketDevice QSqlDatabase QUrl
  • pos: QContextMenuEvent QCursor QDropEvent QIconViewItem QMouseEvent QMoveEvent QPainter QRegExp QTabletEvent QWheelEvent QWidget
  • position: QSqlRecord
  • positionFromValue: QRangeControl
  • postEvent: QApplication QThread
  • postURL: QNPInstance
  • precision: QSqlFieldInfo QTextStream
  • prefix: QDomNode QSpinBox QXmlNamespaceSupport
  • prefixes: QXmlNamespaceSupport
  • prepend: QCString QPtrList QString QValueList
  • pressed: QButton QButtonGroup QCheckBox QHeader QIconView QListBox QListView QPushButton QRadioButton QTable
  • pressure: QTabletEvent
  • prev: QDataBrowser QFocusData QListBoxItem QPtrList QSqlQuery
  • prevItem: QIconViewItem
  • prevLine: QScrollBar
  • prevPage: QScrollBar
  • prevRecordAvailable: QDataBrowser
  • prevValue: QRangeControl
  • previewMode: QFileDialog
  • previewUrl: QFilePreview
  • previousSibling: QDomNode
  • primaryIndex: QSqlCursor QSqlDatabase QSqlDriver
  • primaryScreen: QDesktopWidget
  • primeDelete: QDataBrowser QDataTable QSqlCursor
  • primeInsert: QDataBrowser QDataTable QSqlCursor
  • primeUpdate: QDataBrowser QDataTable QSqlCursor
  • print: QNPInstance
  • printFullPage: QNPInstance
  • printProgram: QPrinter
  • printerName: QPrinter
  • printerSelectionOption: QPrinter
  • processEvents: QApplication
  • processExited: QProcess
  • processIdentifier: QProcess
  • processKeyEvent: QWSKeyboardHandler
  • processName: QXmlNamespaceSupport
  • processOneEvent: QApplication
  • processingInstruction: QXmlContentHandler
  • progress: QProgressBar QProgressDialog
  • progressString: QProgressBar
  • property: QMetaObject QObject QSqlPropertyMap QXmlReader
  • propertyNames: QMetaObject
  • protocol: QUrl
  • protocolDetail: QNetworkOperation
  • provides: QDropEvent QMimeSource
  • publicId: QDomDocumentType QDomEntity QDomNotation QXmlParseException
  • push: QPtrStack QValueStack
  • pushContext: QXmlNamespaceSupport
  • pushData: QMovie
  • pushSpace: QMovie
  • push_back: QValueList QValueVector
  • push_front: QValueList
  • put: QUrlOperator
  • putPoints: QPointArray
  • putch: QFile QIODevice QSocket
  • qAddPostRoutine: QApplication
  • qAlpha: QColor
  • qBlue: QColor
  • qChecksum: QMemArray
  • qDebug: QApplication
  • qDrawPlainRect: QPainter
  • qDrawShadeLine: QPainter
  • qDrawShadePanel: QPainter
  • qDrawShadeRect: QPainter
  • qDrawWinButton: QPainter
  • qDrawWinPanel: QPainter
  • qFatal: QApplication
  • qGray: QColor
  • qGreen: QColor
  • qInitNetworkProtocols: QUrlOperator
  • qInstallMsgHandler: QApplication
  • qMakePair: QPair
  • qName: QXmlAttributes
  • qRed: QColor
  • qRgb: QColor
  • qRgba: QColor
  • qSysInfo: QApplication
  • qSystemWarning: QApplication
  • qVersion: QApplication
  • qWarning: QApplication
  • qglClearColor: QGLWidget
  • qglColor: QGLWidget
  • qmemmove: QCString
  • qstrcmp: QCString
  • qstrcpy: QCString
  • qstrdup: QCString
  • qstricmp: QCString
  • qstrncmp: QCString
  • qstrncpy: QCString
  • qstrnicmp: QCString
  • qtHandler: QErrorMessage
  • qt_find_obj_child: QObject
  • qualifiedNames: QDns
  • quality: QImageIO
  • query: QUrl
  • queryAccessibleInterface: QAccessible
  • queryChild: QAccessibleInterface
  • queryList: QObject
  • queryParent: QAccessibleInterface
  • querySubControl: QStyle
  • querySubControlMetrics: QStyle
  • quit: QApplication
  • qwsDecoration: QApplication
  • qwsEvent: QWidget
  • qwsEventFilter: QApplication
  • qwsRenderToDisk: QFont
  • qwsSetCustomColors: QApplication
  • qwsSetDecoration: QApplication
  • rBottom: QRect
  • rLeft: QRect
  • rRight: QRect
  • rTop: QRect
  • raise: QWSWindow QWidget
  • raiseWidget: QWidgetStack
  • rangeChange: QDial QRangeControl QSlider QSpinBox
  • rasterOp: QPainter
  • rawArg: QNetworkOperation
  • rawMode: QFont QFontInfo
  • rawName: QFont
  • read: QAsciiDict QDict QImageIO QIntDict QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector QTextStream
  • readAll: QFile QIODevice
  • readBlock: QFile QIODevice QSocket QSocketDevice
  • readBoolEntry: QSettings
  • readBytes: QDataStream
  • readCollisionMasks: QCanvasPixmapArray
  • readDoubleEntry: QSettings
  • readEntry: QSettings
  • readField: QSqlForm
  • readFields: QDataBrowser QDataView QSqlForm
  • readLine: QFile QIODevice QSocket QTextStream
  • readLineStderr: QProcess
  • readLineStdout: QProcess
  • readLink: QFileInfo
  • readListEntry: QSettings
  • readNumEntry: QSettings
  • readPixmaps: QCanvasPixmapArray
  • readRawBytes: QDataStream QTextStream
  • readStderr: QProcess
  • readStdout: QProcess
  • ready: QAsyncIO
  • readyRead: QFtp QSocket
  • readyReadStderr: QProcess
  • readyReadStdout: QProcess
  • readyToReceive: QDataSink
  • readyToSend: QDataSource QIODeviceSource
  • reason: QContextMenuEvent QFocusEvent
  • receive: QCopChannel QDataSink
  • receiveBufferSize: QSocketDevice
  • received: QCopChannel
  • record: QDataView QSqlDatabase QSqlDriver
  • recordInfo: QSqlDatabase QSqlDriver
  • recordType: QDns
  • rect: QAccessibleInterface QCanvas QCanvasRectangle QDirectPainter QIconViewItem QImage QPaintEvent QPixmap QRect QTab QWidget
  • rects: QRegion
  • red: QColor
  • redirect: QPainter
  • redo: QLineEdit QTextEdit QtMultiLineEdit
  • redoAvailable: QTextEdit QtMultiLineEdit
  • ref: QString QUrl
  • reformat: QStatusBar
  • refresh: QDataBrowser QDataTable QDataView QFileInfo QSplitter QWSServer
  • regExp: QRegExpValidator
  • region: QDirectPainter QPaintEvent QWSDecoration
  • registerDecoderFactory: QImageDecoder
  • registerNetworkProtocol: QNetworkProtocol
  • reject: QDialog
  • release: QSessionManager
  • releaseKeyboard: QWidget
  • releaseMouse: QWidget
  • released: QButton QButtonGroup QCheckBox QHeader QPushButton QRadioButton
  • reload: QTextBrowser
  • remove: QAsciiCache QAsciiDict QButtonGroup QCString QCache QDict QDir QFile QIntCache QIntDict QMap QObjectCleanupHandler QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector QSqlCursor QSqlForm QSqlPropertyMap QSqlRecord QString QToolTip QTranslator QUrlOperator QValueList QWhatsThis
  • removeAttribute: QDomElement
  • removeAttributeNS: QDomElement
  • removeAttributeNode: QDomElement
  • removeChild: QDomNode QObject QScrollView
  • removeColumn: QDataTable QListView QTable
  • removeColumns: QTable
  • removeDatabase: QSqlDatabase
  • removeDockWindow: QDockArea QMainWindow
  • removeEntry: QSettings
  • removeEventFilter: QObject
  • removeFactory: QMimeSourceFactory
  • removeFirst: QPtrList
  • removeFrom: QAction
  • removeItem: QAccel QComboBox QListBox QMenuBar QMenuData QPopupMenu
  • removeItemAt: QMenuData QPopupMenu
  • removeLabel: QHeader
  • removeLast: QPtrList
  • removeLibraryPath: QApplication
  • removeLine: QMultiLineEdit QtMultiLineEdit
  • removeMappings: QSignalMapper
  • removeNamedItem: QDomNamedNodeMap
  • removeNamedItemNS: QDomNamedNodeMap
  • removeNode: QPtrList
  • removePage: QTabDialog QTabWidget QWizard
  • removeParagraph: QTextEdit
  • removePostedEvents: QApplication
  • removeRef: QPtrList
  • removeRenameBox: QIconViewItem
  • removeRow: QTable
  • removeRows: QTable
  • removeSearchPath: QSettings
  • removeSelectedText: QTextEdit
  • removeSelection: QTable QTextEdit
  • removeSubstitution: QFont
  • removeTab: QTabBar
  • removeTabToolTip: QTabWidget
  • removeTip: QToolTipGroup
  • removeToolTip: QTabBar
  • removeTranslator: QApplication
  • removeWidget: QStatusBar QWidgetStack
  • removed: QChildEvent QNetworkProtocol QUrlOperator
  • rename: QDir QIconViewItem QUrlOperator
  • renameEnabled: QIconViewItem QListViewItem
  • renderPixmap: QGLWidget
  • repaint: QIconViewItem QListViewItem QWidget QtTableView
  • repaintCell: QGridView
  • repaintChanged: QTextEdit
  • repaintContents: QScrollView
  • repaintItem: QIconView QListView
  • repaintScreen: QDial
  • repaintSelections: QTable
  • repairEventFilter: QAccel
  • reparent: QWidget
  • replace: QAsciiDict QCString QDict QIntDict QMap QPtrDict QString
  • replaceChild: QDomNode
  • replaceData: QDomCharacterData
  • requestPhase2: QSessionManager
  • requestRead: QNPStream
  • requested: QWSWindow
  • requestedFormat: QGLContext
  • rereadDir: QFileDialog
  • reserve: QValueVector
  • reset: QDataTable QGLContext QIODevice QIconSet QImage QMetaProperty QProgressBar QProgressDialog QSqlResult QTextStream QUrl QWMatrix QXmlInputSource QXmlNamespaceSupport
  • resetInputContext: QWidget
  • resetRawData: QMemArray
  • resetReason: QFocusEvent
  • resetStatus: QIODevice
  • resetXForm: QPainter
  • resize: QAsciiDict QBitArray QCString QCanvas QDict QIntDict QMemArray QPixmap QPtrDict QPtrVector QValueVector QWidget
  • resizeContents: QScrollView
  • resizeData: QTable
  • resizeEvent: QFrame QGLWidget QListView QWidget
  • resizeGL: QGLWidget
  • resizeMode: QIconView QLayout QListView
  • resizeOverlayGL: QGLWidget
  • resizePolicy: QScrollView
  • resizeSection: QHeader
  • resized: QCanvas
  • resolution: QPrinter
  • resolve: QLibrary
  • resolveEntity: QXmlEntityResolver
  • resortDir: QFileDialog
  • restart: QMovie QTime
  • restartCommand: QSessionManager
  • restartHint: QSessionManager
  • restore: QPainter QScreen
  • restoreOverrideCursor: QApplication
  • result: QDialog QSqlQuery
  • resultsReady: QDns
  • retune: QCanvas
  • returnPressed: QIconView QLineEdit QListBox QListView QTextEdit QtMultiLineEdit
  • reverseLayout: QApplication
  • rewind: QDataSource QIODeviceSource
  • rewindable: QDataSource QIODeviceSource
  • rgb: QColor
  • rgba: QGLFormat
  • rheight: QSize
  • right: QCString QRect QString
  • rightBearing: QFontMetrics
  • rightButtonClicked: QIconView QListBox QListView
  • rightButtonPressed: QIconView QListBox QListView
  • rightCol: QTableSelection
  • rightDock: QMainWindow
  • rightEdge: QCanvasSprite
  • rightJustification: QMainWindow
  • rightJustify: QCString QString
  • rightMargin: QScrollView
  • rmdir: QDir
  • role: QAccessibleInterface
  • rollback: QSqlDatabase
  • rollbackTransaction: QSqlDriver
  • root: QDir
  • rootDirPath: QDir
  • rootIsDecorated: QListView
  • rotate: QPainter QWMatrix
  • row: QChar QTableItem
  • rowAt: QGridView QTable
  • rowHeight: QTable
  • rowHeightChanged: QTable
  • rowIndexChanged: QTable
  • rowIsVisible: QtTableView
  • rowMode: QListBox
  • rowMovingEnabled: QTable
  • rowPos: QTable
  • rowSpan: QTableItem
  • rowStretch: QGridLayout
  • rowYPos: QtTableView
  • rtti: QCanvasEllipse QCanvasItem QCanvasLine QCanvasPolygon QCanvasPolygonalItem QCanvasRectangle QCanvasSpline QCanvasSprite QCanvasText QCheckListItem QCheckTableItem QComboTableItem QIconViewItem QListBoxItem QListViewItem QTableItem
  • run: QThread
  • running: QMovie QThread
  • rwidth: QSize
  • rx: QPoint
  • ry: QPoint
  • sRect: QHeader
  • save: QDomNode QImage QPainter QPicture QPixmap QScreen QTranslator
  • saveState: QApplication
  • scale: QImage QPainter QWMatrix
  • scaleFont: QStyleSheet
  • scaleHeight: QImage
  • scaleWidth: QImage
  • scanLine: QImage
  • screen: QDesktopWidget
  • screenGeometry: QDesktopWidget
  • screenGfx: QScreen
  • screenNumber: QDesktopWidget
  • screenSaverActivate: QWSServer
  • screenSaverActive: QWSServer
  • screenSize: QScreen
  • scriptName: QFontDatabase
  • scriptSample: QFontDatabase
  • scriptable: QMetaProperty
  • scroll: QWidget QtTableView
  • scrollBar: QListBox
  • scrollBarsEnabled: QWorkspace
  • scrollBy: QScrollView
  • scrollToAnchor: QTextEdit
  • scrollToBottom: QTextEdit
  • search: QRegExp
  • searchRev: QRegExp
  • second: QTime
  • secsTo: QDateTime QTime
  • section: QString
  • sectionAt: QHeader
  • sectionFormattedText: QDateEdit QTimeEdit
  • sectionPos: QHeader
  • sectionRect: QHeader
  • sectionSize: QHeader
  • seek: QDataBrowser QSqlQuery
  • seekable: QNPStream
  • segmentStyle: QLCDNumber
  • select: QSqlCursor
  • selectAll: QFileDialog QIconView QLineEdit QListBox QListView QSpinBox QTextEdit QtMultiLineEdit
  • selectTab: QTabBar
  • selected: QActionGroup QButtonGroup QListBox QTabBar QWizard
  • selectedFile: QFileDialog
  • selectedFiles: QFileDialog
  • selectedFilter: QFileDialog
  • selectedItem: QListView
  • selectedText: QLineEdit QTextEdit
  • selection: QAccessibleInterface QTable
  • selectionChanged: QClipboard QIconView QLineEdit QListBox QListView QTable QTextEdit
  • selectionMode: QIconView QListBox QListView QTable
  • selectionModeEnabled: QClipboard
  • selfMask: QPixmap
  • selfNesting: QStyleSheetItem
  • send: QCopChannel
  • sendBufferSize: QSocketDevice
  • sendEvent: QApplication
  • sendKeyEvent: QWSServer
  • sendPostedEvents: QApplication
  • sendTo: QDataSource QIODeviceSource
  • sender: QObject
  • separator: QDateEdit QDir QTimeEdit
  • serialNumber: QMimeSource QPalette QPixmap
  • servers: QDns
  • sessionId: QApplication QSessionManager
  • set: QScreen
  • setAccel: QAction QButton QCheckBox QMenuData QPopupMenu QPushButton QRadioButton
  • setAcceptDockWindow: QDockArea
  • setAcceptDrops: QWidget
  • setAccum: QGLFormat
  • setAction: QDropEvent
  • setActive: QCanvasItem QPalette QSqlResult
  • setActiveItem: QPopupMenu
  • setActiveWindow: QWSWindow QWidget QXtWidget
  • setAddress: QHostAddress
  • setAddressReusable: QSocketDevice
  • setAdvancePeriod: QCanvas
  • setAlignment: QGroupBox QLabel QLayoutItem QLineEdit QMultiLineEdit QStyleSheetItem QTextEdit QtMultiLineEdit
  • setAllChanged: QCanvas
  • setAllColumnsShowFocus: QListView
  • setAlpha: QGLFormat
  • setAlphaBuffer: QImage
  • setAnchor: QStyleSheetItem
  • setAngles: QCanvasEllipse
  • setAnimated: QCanvasItem
  • setApplyButton: QTabDialog
  • setAppropriate: QMainWindow QWizard
  • setAreaChanged: QDirectPainter
  • setArg: QNetworkOperation
  • setArguments: QProcess
  • setArrangement: QIconView
  • setAt: QSqlResult
  • setAttribute: QDomElement
  • setAttributeNS: QDomElement
  • setAttributeNode: QDomElement
  • setAttributeNodeNS: QDomElement
  • setAutoAdd: QLayout
  • setAutoAdvance: QDateEdit QDateTimeEdit QTimeEdit
  • setAutoArrange: QIconView
  • setAutoBottomScrollBar: QListBox
  • setAutoBufferSwap: QGLWidget
  • setAutoClose: QProgressDialog
  • setAutoCompletion: QComboBox
  • setAutoDefault: QPushButton
  • setAutoDelete: QAsciiDict QCache QDataTable QDict QIntDict QNetworkProtocol QPtrCollection QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector
  • setAutoEdit: QDataBrowser QDataTable
  • setAutoMask: QWidget
  • setAutoRaise: QToolButton
  • setAutoRepeat: QButton QCheckBox QPushButton QRadioButton
  • setAutoReset: QProgressDialog
  • setAutoScrollBar: QListBox
  • setAutoUnload: QLibrary
  • setAutoUpdate: QtMultiLineEdit QtTableView
  • setBackEnabled: QWizard
  • setBackgroundColor: QCanvas QMovie QPainter
  • setBackgroundMode: QPainter QWidget
  • setBackgroundOrigin: QWidget
  • setBackgroundPixmap: QCanvas
  • setBar: QProgressDialog
  • setBaseSize: QWidget
  • setBinMode: QLCDNumber
  • setBit: QBitArray
  • setBlocking: QSocketDevice
  • setBold: QFont QTextEdit
  • setBottom: QDoubleValidator QIntValidator QRect
  • setBottomItem: QListBox
  • setBottomScrollBar: QListBox
  • setBoundaryChecking: QDataBrowser
  • setBrush: QCanvasPolygonalItem QColorGroup QPainter QPalette
  • setBrushOrigin: QPainter
  • setBuddy: QLabel
  • setBuffer: QBuffer
  • setButton: QButtonGroup
  • setButtonSymbols: QSpinBox
  • setButtonText: QMessageBox
  • setByteOrder: QDataStream
  • setCacheLimit: QPixmapCache
  • setCaching: QFileInfo
  • setCalculated: QSqlCursor QSqlFieldInfo
  • setCancelButton: QProgressDialog QTabDialog
  • setCancelButtonText: QProgressDialog
  • setCanvas: QCanvasItem QCanvasView
  • setCapStyle: QPen
  • setCaption: QWidget
  • setCaseSensitive: QRegExp
  • setCellContentFromEditor: QTable
  • setCellHeight: QGridView QtTableView
  • setCellWidget: QTable
  • setCellWidth: QGridView QtTableView
  • setCenterIndicator: QProgressBar
  • setCentralWidget: QMainWindow
  • setChanged: QCanvas
  • setCheckable: QPopupMenu
  • setChecked: QCheckBox QCheckTableItem QRadioButton
  • setChildGeometries: QWidgetStack
  • setClickEnabled: QHeader
  • setClipRect: QPainter
  • setClipRegion: QPainter
  • setClipping: QPainter
  • setCloseMode: QDockWindow
  • setCodec: QTextStream
  • setCodecForLocale: QTextCodec
  • setCol: QTableItem
  • setColStretch: QGridLayout
  • setColor: QBrush QCanvasText QColorDrag QColorGroup QImage QPalette QPen QStyleSheetItem QTextEdit
  • setColorMode: QPrinter
  • setColorSpec: QApplication
  • setColormap: QGLWidget
  • setColumn: QDataTable
  • setColumnAlignment: QListView
  • setColumnLayout: QGroupBox
  • setColumnMode: QListBox
  • setColumnMovingEnabled: QTable
  • setColumnReadOnly: QTable
  • setColumnStretchable: QTable
  • setColumnText: QListView
  • setColumnWidth: QDataTable QListView QTable
  • setColumnWidthMode: QListView
  • setColumns: QGroupBox
  • setCommunication: QProcess
  • setConfirmCancels: QDataBrowser QDataTable
  • setConfirmDelete: QDataBrowser QDataTable
  • setConfirmEdits: QDataBrowser QDataTable
  • setConfirmInsert: QDataBrowser QDataTable
  • setConfirmUpdate: QDataBrowser QDataTable
  • setContent: QDomDocument
  • setContentFromEditor: QTableItem
  • setContentHandler: QXmlReader
  • setContentsPos: QScrollView
  • setContentsPreview: QFileDialog
  • setContentsPreviewEnabled: QFileDialog
  • setContexts: QStyleSheetItem
  • setControlPoints: QCanvasSpline
  • setCoords: QRect
  • setCornerWidget: QScrollView
  • setCreator: QPrinter
  • setCurrent: QDir
  • setCurrentCell: QTable
  • setCurrentFont: QTextEdit
  • setCurrentItem: QComboBox QComboTableItem QIconView QListBox QListView
  • setCurrentPage: QTabWidget
  • setCurrentTab: QTabBar
  • setCurrentText: QComboBox
  • setCursor: QWidget
  • setCursorFlashTime: QApplication
  • setCursorName: QSqlIndex
  • setCursorPosition: QLineEdit QMultiLineEdit QTextEdit QtMultiLineEdit
  • setCustomColor: QColorDialog
  • setCustomHighlighting: QListBoxItem
  • setDTDHandler: QXmlReader
  • setData: QClipboard QCustomEvent QDomCharacterData QDomProcessingInstruction QIconDragItem QMimeSourceFactory QPicture QXmlInputSource
  • setDatabaseName: QSqlDatabase
  • setDatabaseText: QSqlError
  • setDate: QDateEdit QDateTime
  • setDateFormat: QDataTable
  • setDateTime: QDateTimeEdit
  • setDay: QDateEdit
  • setDecMode: QLCDNumber
  • setDecimals: QDoubleValidator
  • setDeclHandler: QXmlReader
  • setDecodingFunction: QFile
  • setDefault: QPushButton
  • setDefaultButton: QTabDialog
  • setDefaultCodec: QApplication
  • setDefaultFactory: QMimeSourceFactory
  • setDefaultFont: QSimpleRichText
  • setDefaultFormat: QGLFormat
  • setDefaultKeyboard: QWSServer
  • setDefaultMouse: QWSServer
  • setDefaultOptimization: QPixmap
  • setDefaultOverlayFormat: QGLFormat
  • setDefaultRenameAction: QListView
  • setDefaultSheet: QStyleSheet
  • setDefaultTabStop: QtMultiLineEdit
  • setDefaultUp: QMenuBar
  • setDelay: QToolTipGroup
  • setDepth: QGLFormat
  • setDescending: QSqlIndex
  • setDescription: QImageIO
  • setDesktopBackground: QWSServer
  • setDesktopSettingsAware: QApplication
  • setDevice: QDataStream QTextStream
  • setDir: QFileDialog QUrlInfo
  • setDirectRendering: QGLFormat
  • setDirection: QBoxLayout
  • setDirty: QScreen
  • setDisabled: QPalette QWidget
  • setDiscardCommand: QSessionManager
  • setDisplayMode: QStyleSheetItem
  • setDocName: QPrinter
  • setDockEnabled: QMainWindow
  • setDockMenuEnabled: QMainWindow
  • setDockWindowsMovable: QMainWindow
  • setDocumentLocator: QXmlContentHandler
  • setDotsPerMeterX: QImage
  • setDotsPerMeterY: QImage
  • setDoubleBuffer: QGLFormat
  • setDoubleBuffering: QCanvas
  • setDoubleClickInterval: QApplication
  • setDown: QButton QCheckBox QPushButton QRadioButton
  • setDragAutoScroll: QScrollView
  • setDragEnabled: QIconViewItem QLineEdit QListViewItem QTable
  • setDriverText: QSqlError
  • setDropEnabled: QIconViewItem QListViewItem
  • setDuplicatesEnabled: QComboBox
  • setEchoMode: QLineEdit QtMultiLineEdit
  • setEditMode: QTable
  • setEditText: QComboBox
  • setEditable: QComboBox QComboTableItem
  • setEdited: QLineEdit QMultiLineEdit QtMultiLineEdit
  • setEffectEnabled: QApplication
  • setEnabled: QAccel QAction QCanvasItem QLayout QListViewItem QSocketNotifier QTab QTableItem QToolTipGroup QWidget
  • setEncodedData: QStoredDrag
  • setEncodedPathAndQuery: QUrl
  • setEncoding: QTextStream
  • setEncodingFunction: QFile
  • setEntityResolver: QXmlReader
  • setEntries: QGLColormap
  • setEntry: QGLColormap
  • setEraseColor: QWidget
  • setErasePixmap: QWidget
  • setError: QSocketDevice
  • setErrorCode: QNetworkOperation
  • setErrorHandler: QXmlReader
  • setExclusive: QActionGroup QButtonGroup
  • setExpand: QCString
  • setExpandable: QListViewItem
  • setExtension: QDialog
  • setExtensionType: QMimeSourceFactory
  • setFalseText: QDataTable
  • setFamily: QFont QTextEdit
  • setFeature: QXmlReader
  • setFile: QFileInfo QUrlInfo
  • setFileName: QImageIO QUrl
  • setFileNames: QUriDrag
  • setFilePath: QMimeSourceFactory
  • setFilter: QDataBrowser QDataTable QDir QFileDialog QSqlCursor
  • setFilters: QFileDialog
  • setFinishEnabled: QWizard
  • setFixedExtentHeight: QDockWindow
  • setFixedExtentWidth: QDockWindow
  • setFixedHeight: QWidget
  • setFixedPitch: QFont
  • setFixedSize: QWidget
  • setFixedVisibleLines: QtMultiLineEdit
  • setFixedWidth: QWidget
  • setFlat: QPushButton
  • setFocus: QAccessibleInterface QWidget
  • setFocusPolicy: QWidget
  • setFocusProxy: QWidget
  • setFocusStyle: QTable
  • setFont: QApplication QCanvasText QComboBox QCustomMenuItem QLabel QPainter QTabDialog QToolTip QWidget
  • setFontFamily: QStyleSheetItem
  • setFontItalic: QStyleSheetItem
  • setFontSize: QStyleSheetItem
  • setFontStrikeOut: QStyleSheetItem
  • setFontUnderline: QStyleSheetItem
  • setFontWeight: QStyleSheetItem
  • setForm: QDataBrowser QDataView
  • setFormat: QGLContext QImageIO
  • setForwardOnly: QSqlResult
  • setFrame: QCanvasSprite QLineEdit
  • setFrameAnimation: QCanvasSprite
  • setFramePeriod: QImageConsumer
  • setFrameRect: QFrame
  • setFrameShadow: QFrame
  • setFrameShape: QFrame
  • setFrameStyle: QFrame
  • setFromTo: QPrinter
  • setFullPage: QPrinter
  • setGamma: QImageIO
  • setGenerated: QSqlCursor QSqlFieldInfo QSqlRecord
  • setGeometry: QBoxLayout QGridLayout QLayout QLayoutItem QSpacerItem QWidget QWidgetItem
  • setGlobalMouseTracking: QApplication
  • setGlobalStrut: QApplication
  • setGloballyEnabled: QToolTip
  • setGridX: QIconView
  • setGridY: QIconView
  • setGroup: QUrlInfo
  • setHBarGeometry: QScrollView
  • setHMS: QTime
  • setHMargin: QtMultiLineEdit
  • setHScrollBarMode: QScrollView
  • setHeight: QListViewItem QRect QSize
  • setHeightForWidth: QSizePolicy
  • setHelpButton: QTabDialog
  • setHelpEnabled: QWizard
  • setHexMode: QLCDNumber
  • setHorData: QSizePolicy
  • setHorStretch: QSizePolicy
  • setHorizontallyStretchable: QDockWindow
  • setHost: QUrl
  • setHostName: QSqlDatabase
  • setHour: QTimeEdit
  • setHsv: QColor
  • setIODevice: QImageIO
  • setIcon: QMessageBox QWidget
  • setIconPixmap: QMessageBox
  • setIconProvider: QFileDialog
  • setIconSet: QAction QPushButton QTab QToolButton
  • setIconSize: QIconSet
  • setIconText: QWidget
  • setId: QMenuData
  • setIdentifier: QTab
  • setImage: QCanvasPixmapArray QClipboard QImageDrag QImageIO QMimeSourceFactory
  • setInactive: QPalette
  • setIndent: QLabel
  • setIndicator: QProgressBar
  • setIndicatorFollowsStyle: QProgressBar
  • setInfoPreview: QFileDialog
  • setInfoPreviewEnabled: QFileDialog
  • setInitialized: QGLContext
  • setInsertionPolicy: QComboBox
  • setInsideMargin: QGroupBox
  • setInsideSpacing: QGroupBox
  • setItalic: QFont QTextEdit
  • setItem: QTable
  • setItemChecked: QMenuData QPopupMenu
  • setItemEnabled: QAccel QMenuBar QMenuData QPopupMenu
  • setItemMargin: QListView
  • setItemParameter: QMenuData QPopupMenu
  • setItemRect: QIconViewItem
  • setItemTextBackground: QIconView
  • setItemTextPos: QIconView
  • setItemsMovable: QIconView
  • setJoinStyle: QPen
  • setKey: QIconViewItem
  • setKeyCompression: QWidget
  • setKeyboardFilter: QWSServer
  • setKeyboardHandler: QWSServer
  • setLabel: QDns QHeader QProgressDialog QToolBar
  • setLabelText: QProgressDialog
  • setLastError: QSqlDriver QSqlResult
  • setLastModified: QUrlInfo
  • setLatin1: QString
  • setLeft: QRect
  • setLeftCell: QtTableView
  • setLeftMargin: QTable
  • setLength: QString
  • setLexicalHandler: QXmlReader
  • setLibraryPaths: QApplication
  • setLineEdit: QComboBox
  • setLineSpacing: QStyleSheetItem
  • setLineStep: QDial QScrollBar QSlider QSpinBox
  • setLineWidth: QFrame
  • setLinkUnderline: QTextEdit
  • setListBox: QComboBox
  • setListStyle: QStyleSheetItem
  • setLogicalFontSize: QStyleSheetItem
  • setLogicalFontSizeStep: QStyleSheetItem
  • setLooping: QImageConsumer
  • setLoops: QSound
  • setMainWidget: QApplication
  • setManagerProperty: QSessionManager
  • setMapping: QSignalMapper
  • setMargin: QFrame QLayout QStyleSheetItem QTabWidget
  • setMargins: QScrollView
  • setMask: QPixmap QWidget
  • setMatchAllDirs: QDir
  • setMatrix: QWMatrix
  • setMaxCost: QAsciiCache QCache QIntCache
  • setMaxCount: QComboBox
  • setMaxItemTextLength: QIconView
  • setMaxItemWidth: QIconView
  • setMaxLength: QLineEdit QtMultiLineEdit
  • setMaxLineLength: QtMultiLineEdit
  • setMaxLines: QtMultiLineEdit
  • setMaxValue: QDateEdit QDial QRangeControl QScrollBar QSlider QSpinBox QTimeEdit
  • setMaxWindowRect: QWSServer
  • setMaximumHeight: QWidget
  • setMaximumSize: QWidget
  • setMaximumWidth: QWidget
  • setMenuBar: QLayout
  • setMenuText: QAction
  • setMicroFocusHint: QWidget
  • setMidLineWidth: QFrame
  • setMimeSourceFactory: QTextEdit
  • setMinMax: QPrinter
  • setMinValue: QDateEdit QDial QRangeControl QScrollBar QSlider QSpinBox QTimeEdit
  • setMinimal: QRegExp
  • setMinimumDuration: QProgressDialog
  • setMinimumHeight: QWidget
  • setMinimumSize: QWidget
  • setMinimumWidth: QWidget
  • setMinute: QTimeEdit
  • setMode: QFileDialog QLCDNumber QScreen QSqlCursor
  • setModified: QTextEdit
  • setMonth: QDateEdit
  • setMouseTracking: QWidget
  • setMovie: QLabel
  • setMovingEnabled: QDockWindow QHeader
  • setMultiLinesEnabled: QListViewItem
  • setMultiSelection: QListView
  • setName: QFile QObject QSqlCursor QSqlField QSqlIndex QUrlInfo
  • setNameFilter: QDir QUrlOperator
  • setNamedColor: QColor
  • setNamedItem: QDomNamedNodeMap
  • setNamedItemNS: QDomNamedNodeMap
  • setNewLine: QDockWindow
  • setNextEnabled: QWizard
  • setNoChange: QCheckBox
  • setNodeValue: QDomNode
  • setNotchTarget: QDial
  • setNotchesVisible: QDial
  • setNull: QSqlField QSqlRecord
  • setNullText: QDataTable
  • setNum: QCString QLabel QString
  • setNumColors: QImage
  • setNumCols: QGridView QTable QtTableView
  • setNumCopies: QPrinter
  • setNumDigits: QLCDNumber
  • setNumRows: QGridView QTable QtTableView
  • setNumber: QSqlError
  • setOctMode: QLCDNumber
  • setOffset: QCanvasPixmap QDockWindow QHeader QImage QtTableView
  • setOkButton: QTabDialog
  • setOn: QAction QButton QCheckListItem QPushButton QToolButton
  • setOpaqueMoving: QDockWindow QMainWindow
  • setOpaqueResize: QSplitter
  • setOpen: QListView QListViewItem QSqlDriver
  • setOpenError: QSqlDriver
  • setOptimization: QPixmap
  • setOption: QGLFormat
  • setOrder: QDateEdit
  • setOrientation: QDialog QDockWindow QGroupBox QHeader QPrinter QScrollBar QSlider QSplitter
  • setOrigin: QGridLayout
  • setOutputFileName: QPrinter
  • setOutputToFile: QPrinter
  • setOverlay: QGLFormat
  • setOverrideCursor: QApplication
  • setOverwriteMode: QTextEdit QtMultiLineEdit
  • setOwner: QUrlInfo
  • setPageOrder: QPrinter
  • setPageSize: QPrinter
  • setPageStep: QDial QScrollBar QSlider
  • setPalette: QApplication QComboBox QScrollBar QSlider QToolTip QWidget
  • setPaletteBackgroundColor: QWidget
  • setPaletteBackgroundPixmap: QWidget
  • setPaletteForegroundColor: QWidget
  • setPaper: QTextEdit
  • setPaperSource: QPrinter
  • setParagraphBackgroundColor: QTextEdit
  • setParameters: QImageIO
  • setPassword: QSqlDatabase QUrl
  • setPasswordChar: QLineEdit
  • setPath: QDir QUrl
  • setPattern: QRegExp
  • setPen: QCanvasPolygonalItem QPainter
  • setPercentageVisible: QProgressBar
  • setPermissions: QUrlInfo
  • setPicture: QIconViewItem QLabel
  • setPixel: QImage
  • setPixelAlignment: QPNGImagePacker
  • setPixelSize: QFont
  • setPixmap: QBrush QButton QCheckBox QClipboard QDragObject QIconSet QIconViewItem QLabel QListViewItem QMimeSourceFactory QPushButton QRadioButton QTable QTableItem
  • setPixmapRect: QIconViewItem
  • setPlane: QGLFormat
  • setPoint: QDropEvent QPointArray
  • setPointSize: QFont QTextEdit
  • setPointSizeFloat: QFont
  • setPoints: QCanvasLine QCanvasPolygon
  • setPopup: QPushButton QToolButton
  • setPopupDelay: QToolButton
  • setPort: QSqlDatabase QUrl
  • setPos: QCursor
  • setPrefix: QDomNode QSpinBox QXmlNamespaceSupport
  • setPreviewMode: QFileDialog
  • setPrimaryIndex: QSqlCursor
  • setPrintProgram: QPrinter
  • setPrintableData: QDataStream
  • setPrinterName: QPrinter
  • setPrinterSelectionOption: QPrinter
  • setProgress: QProgressBar QProgressDialog
  • setProperty: QObject QSqlPropertyMap QXmlReader
  • setProtocol: QUrl
  • setProtocolDetail: QNetworkOperation
  • setQuality: QImageIO
  • setQuery: QSqlResult QUrl
  • setRadioButtonExclusive: QButtonGroup
  • setRange: QDateEdit QDoubleValidator QIntValidator QRangeControl QSlider QTimeEdit
  • setRasterOp: QPainter
  • setRawArg: QNetworkOperation
  • setRawData: QMemArray
  • setRawMode: QFont
  • setRawName: QFont
  • setReadOnly: QDataBrowser QLineEdit QSqlField QTable QTextEdit QtMultiLineEdit
  • setReadable: QUrlInfo
  • setReason: QFocusEvent
  • setReceiveBufferSize: QSocketDevice
  • setRecord: QDataView QSqlForm
  • setRecordType: QDns
  • setRect: QRect QTab
  • setRef: QUrl
  • setRegExp: QRegExpValidator
  • setRenameEnabled: QIconViewItem QListViewItem
  • setReplaceable: QTableItem
  • setResizeEnabled: QDockWindow QHeader
  • setResizeMode: QIconView QLayout QListView QSplitter
  • setResizePolicy: QScrollView
  • setResolution: QPrinter
  • setRestartCommand: QSessionManager
  • setRestartHint: QSessionManager
  • setResult: QDialog
  • setReverseLayout: QApplication
  • setRgb: QColor
  • setRgba: QGLFormat
  • setRight: QRect
  • setRightJustification: QMainWindow
  • setRootIsDecorated: QListView
  • setRow: QTableItem
  • setRowHeight: QTable
  • setRowMode: QListBox
  • setRowMovingEnabled: QTable
  • setRowReadOnly: QTable
  • setRowStretch: QGridLayout
  • setRowStretchable: QTable
  • setRubberband: QSplitter
  • setScaledContents: QLabel
  • setScreenSaver: QWSServer
  • setScreenSaverInterval: QWSServer
  • setScreenSaverIntervals: QWSServer
  • setScrollBar: QListBox
  • setScrollBarsEnabled: QWorkspace
  • setSecond: QTimeEdit
  • setSegmentStyle: QLCDNumber
  • setSelect: QSqlResult
  • setSelectable: QIconViewItem QListBoxItem QListViewItem
  • setSelected: QAccessibleInterface QCanvasItem QIconView QIconViewItem QListBox QListView QListViewItem
  • setSelectedFilter: QFileDialog
  • setSelection: QFileDialog QLineEdit QTextEdit QtMultiLineEdit
  • setSelectionAttributes: QTextEdit
  • setSelectionMode: QClipboard QIconView QListBox QListView QTable
  • setSelfNesting: QStyleSheetItem
  • setSendBufferSize: QSocketDevice
  • setSeparator: QDateEdit QTimeEdit
  • setSequence: QCanvasSprite
  • setShape: QCursor QTabBar
  • setShowGrid: QTable
  • setShowHiddenFiles: QFileDialog
  • setShowSortIndicator: QListView
  • setShowToolTips: QIconView QListView
  • setSize: QCanvasEllipse QCanvasRectangle QDataTable QImageConsumer QRect QUrlInfo
  • setSizeGripEnabled: QDialog QStatusBar
  • setSizeIncrement: QWidget
  • setSizeLimit: QComboBox
  • setSizePolicy: QWidget
  • setSizes: QSplitter
  • setSmallDecimalPoint: QLCDNumber
  • setSocket: QServerSocket QSocket QSocketDevice
  • setSocketDevice: QSocket
  • setSort: QDataBrowser QDataTable QSqlCursor
  • setSortIndicator: QHeader
  • setSorting: QDir QIconView QListView QTable
  • setSource: QTextBrowser
  • setSpacing: QGrid QHBox QIconView QLayout
  • setSpan: QTableItem
  • setSpecialValueText: QSpinBox
  • setSpeed: QMovie
  • setSqlCursor: QDataBrowser QDataTable
  • setStartDragDistance: QApplication
  • setStartDragTime: QApplication
  • setState: QButton QNetworkOperation
  • setStaticBackground: QScrollView
  • setStatus: QImageIO
  • setStatusTip: QAction
  • setStencil: QGLFormat
  • setSteps: QRangeControl
  • setStereo: QGLFormat
  • setStr: QCString
  • setStretchEnabled: QHeader
  • setStretchFactor: QBoxLayout QHBox
  • setStretchableWidget: QToolBar
  • setStrikeOut: QFont
  • setStringList: QComboTableItem
  • setStyle: QApplication QBrush QPen QWidget
  • setStyleHint: QFont
  • setStyleSheet: QTextEdit
  • setStyleStrategy: QFont
  • setSubtype: QTextDrag
  • setSuffix: QSpinBox
  • setSupportsMargin: QLayout
  • setSymLink: QUrlInfo
  • setTabArray: QPainter
  • setTabBar: QTabDialog QTabWidget
  • setTabEnabled: QTabBar QTabDialog QTabWidget
  • setTabIconSet: QTabWidget
  • setTabLabel: QTabWidget
  • setTabOrder: QWidget
  • setTabPosition: QTabWidget
  • setTabShape: QTabWidget
  • setTabStopWidth: QTextEdit
  • setTabStops: QPainter
  • setTabToolTip: QTabWidget
  • setTableFlags: QtTableView
  • setTagName: QDomElement
  • setText: QAccessibleInterface QAction QButton QCanvasText QCheckBox QClipboard QIconViewItem QImage QLabel QLineEdit QListBoxItem QListViewItem QMessageBox QMimeSourceFactory QPushButton QRadioButton QTab QTable QTableItem QTextDrag QTextEdit QtMultiLineEdit
  • setTextFlags: QCanvasText
  • setTextFormat: QLabel QMessageBox QTextEdit
  • setTextLabel: QToolButton
  • setTextRect: QIconViewItem
  • setTickInterval: QSlider
  • setTickmarks: QSlider
  • setTile: QCanvas
  • setTiles: QCanvas
  • setTime: QDateTime QTimeEdit
  • setTime_t: QDateTime
  • setTitle: QGroupBox QWizard
  • setTitleFont: QWizard
  • setToggleAction: QAction
  • setToggleButton: QButton QPushButton QToolButton
  • setToggleType: QButton
  • setToolTip: QAction QTabBar
  • setTop: QDoubleValidator QIntValidator QRect
  • setTopCell: QtTableView
  • setTopItem: QListBox
  • setTopLeftCell: QtTableView
  • setTopMargin: QTable
  • setTotalSteps: QProgressBar QProgressDialog
  • setTracking: QDial QHeader QScrollBar QSlider
  • setTranslation: QTranslatorMessage
  • setTreeStepSize: QListView
  • setTrim: QSqlFieldInfo
  • setTrimmed: QSqlCursor
  • setTristate: QCheckBox
  • setTrueText: QDataTable
  • setType: QSqlError
  • setUnchanged: QCanvas
  • setUnderline: QFont QTextEdit
  • setUndoDepth: QTextEdit QtMultiLineEdit
  • setUndoEnabled: QtMultiLineEdit
  • setUndoRedoEnabled: QTextEdit
  • setUnicode: QString
  • setUnicodeCodes: QString
  • setUnicodeUris: QUriDrag
  • setUpLayout: QMainWindow
  • setUpdatePeriod: QCanvas
  • setUpdatesEnabled: QWidget
  • setUris: QUriDrag
  • setUrl: QFileDialog QNetworkProtocol
  • setUseHighlightColors: QMotifStyle
  • setUser: QUrl
  • setUserName: QSqlDatabase
  • setUsesBigPixmap: QToolButton
  • setUsesBigPixmaps: QMainWindow
  • setUsesDropDown: QActionGroup
  • setUsesTextLabel: QMainWindow QToolButton
  • setVBarGeometry: QScrollView
  • setVScrollBarMode: QScrollView
  • setValidator: QComboBox QLineEdit QSpinBox QtMultiLineEdit
  • setValue: QDial QDomAttr QRangeControl QScrollBar QSignal QSlider QSpinBox QSqlField QSqlRecord
  • setVariableHeight: QListBox
  • setVariableWidth: QListBox
  • setVelocity: QCanvasItem
  • setVerData: QSizePolicy
  • setVerStretch: QSizePolicy
  • setVersion: QDataStream
  • setVerticalAlignment: QStyleSheetItem QTextEdit
  • setVerticallyStretchable: QDockWindow
  • setViewMode: QFileDialog
  • setViewXForm: QPainter
  • setViewport: QPainter
  • setVisible: QCanvasItem QListViewItem
  • setWFlags: QWidget
  • setWeight: QFont
  • setWhatsThis: QAccel QAction QMenuData QPopupMenu
  • setWheelScrollLines: QApplication
  • setWhiteSpaceMode: QStyleSheetItem
  • setWidget: QDockWindow
  • setWidth: QPen QRect QSimpleRichText QSize
  • setWildcard: QRegExp
  • setWinding: QCanvasPolygonalItem
  • setWindow: QPainter
  • setWindowCreated: QGLContext
  • setWordWrap: QTableItem QTextEdit QtMultiLineEdit
  • setWordWrapIconText: QIconView
  • setWorkingDirectory: QProcess
  • setWorldMatrix: QCanvasView QPainter
  • setWorldXForm: QPainter
  • setWrapColumnOrWidth: QTextEdit QtMultiLineEdit
  • setWrapPolicy: QTextEdit QtMultiLineEdit
  • setWrapping: QDial QSpinBox
  • setWritable: QUrlInfo
  • setX: QCanvasItem QPoint QRect
  • setXOffset: QtTableView
  • setXVelocity: QCanvasItem
  • setY: QCanvasItem QPoint QRect
  • setYMD: QDate
  • setYOffset: QtTableView
  • setYVelocity: QCanvasItem
  • setYear: QDateEdit
  • setZ: QCanvasItem
  • setf: QTextStream
  • setup: QListViewItem QPrinter
  • setupPainter: QtTableView
  • shadow: QColorGroup
  • shape: QCursor QTabBar
  • shear: QPainter QWMatrix
  • shortDayName: QDate
  • shortMonthName: QDate
  • shortcutKey: QAccel
  • show: QCanvasItem QDialog QMenuBar QWSWindow QWidget
  • showColumn: QTable
  • showDockMenu: QMainWindow
  • showEvent: QWidget
  • showExtension: QDialog
  • showFullScreen: QWidget
  • showGrid: QTable
  • showHiddenFiles: QFileDialog
  • showMaximized: QWidget
  • showMinimized: QWidget
  • showNormal: QWidget
  • showPage: QTabDialog QTabWidget QWizard
  • showRow: QTable
  • showSortIndicator: QListView
  • showTip: QToolTipGroup
  • showToolTips: QIconView QListView
  • shutdownDevice: QScreen
  • signalNames: QMetaObject
  • signalsBlocked: QObject
  • simpleHeuristicNameMatch: QTextCodec
  • simplifyWhiteSpace: QCString QString
  • singleShot: QTimer
  • size: QAsciiCache QAsciiDict QBitArray QCache QCanvas QCanvasRectangle QDict QDirectPainter QFile QFileInfo QFontMetrics QGLColormap QIODevice QIconViewItem QImage QIntCache QIntDict QMap QMemArray QPicture QPixmap QPtrDict QPtrVector QRect QResizeEvent QSocket QSqlQuery QSqlResult QUrlInfo QValueList QValueVector QWidget
  • sizeChange: QHeader
  • sizeFromContents: QStyle
  • sizeHint: QBoxLayout QCustomMenuItem QGridLayout QLayoutItem QLineEdit QProgressDialog QSizeGrip QSpacerItem QTableItem QWidget QWidgetItem
  • sizeIncrement: QWidget
  • sizeLimit: QComboBox
  • sizePolicy: QWidget
  • sizes: QSplitter
  • skipWhiteSpace: QTextStream
  • skippedEntity: QXmlContentHandler
  • sleep: QThread
  • sliderMoved: QScrollBar QSlider
  • sliderPressed: QScrollBar QSlider
  • sliderRect: QScrollBar QSlider
  • sliderReleased: QScrollBar QSlider
  • sliderStart: QScrollBar QSlider
  • slotNames: QMetaObject
  • slotUpdate: QIconView
  • smallDecimalPoint: QLCDNumber
  • smoothScale: QImage
  • smoothSizes: QFontDatabase
  • sn_read: QSocket
  • sn_write: QSocket
  • socket: QServerSocket QSocket QSocketDevice QSocketNotifier
  • socketDevice: QServerSocket QSocket
  • sort: QDataBrowser QDataTable QIconView QListBox QListView QListViewItem QMemArray QPtrList QPtrVector QSqlCursor QStringList
  • sortAscending: QDataTable
  • sortChildItems: QListViewItem
  • sortColumn: QDataTable QTable
  • sortDescending: QDataTable
  • sortDirection: QIconView
  • sorting: QDir QIconView QTable
  • source: QDragObject QDropEvent QTextBrowser
  • sourceText: QTranslatorMessage
  • spacePressed: QListView
  • spacerItem: QLayoutItem
  • spacing: QIconView QLayout
  • specialValueText: QSpinBox
  • specified: QDomAttr
  • speed: QMovie
  • split: QStringList
  • splitName: QXmlNamespaceSupport
  • splitText: QDomText
  • spontaneous: QEvent
  • sprintf: QCString QString
  • sqlCursor: QDataBrowser QDataTable
  • squeeze: QTranslator
  • stackUnder: QWidget
  • standardIcon: QMessageBox
  • standardSizes: QFontDatabase
  • start: QNetworkProtocol QProcess QThread QTime QTimer QUrlOperator
  • startCDATA: QXmlLexicalHandler
  • startDTD: QXmlLexicalHandler
  • startDocument: QXmlContentHandler
  • startDrag: QIconView QListView QTable
  • startDragDistance: QApplication
  • startDragTime: QApplication
  • startElement: QXmlContentHandler
  • startEntity: QXmlLexicalHandler
  • startPoint: QCanvasLine
  • startPrefixMapping: QXmlContentHandler
  • startRename: QListViewItem
  • startTimer: QObject
  • startedNextCopy: QUrlOperator
  • startingUp: QApplication
  • startsWith: QString
  • state: QAccessibleInterface QButton QCheckBox QContextMenuEvent QIODevice QKeyEvent QMouseEvent QNetworkOperation QPushButton QRadioButton QSocket QWheelEvent
  • stateAfter: QKeyEvent QMouseEvent
  • stateChange: QCheckListItem
  • stateChanged: QButton QCheckBox QPushButton QRadioButton
  • statistics: QAsciiCache QAsciiDict QCache QDict QIntCache QIntDict QPtrDict
  • status: QIODevice QImageIO QNPInstance
  • statusBar: QMainWindow
  • statusTip: QAction
  • stencil: QGLFormat
  • step: QMovie
  • stepChange: QRangeControl
  • stepDown: QSpinBox
  • stepUp: QSpinBox
  • steps: QMovie
  • stereo: QGLFormat
  • stop: QNetworkProtocol QSound QTimer QUrlOperator
  • stored: QMetaProperty
  • streamAsFile: QNPInstance
  • streamDestroyed: QNPInstance
  • strikeOut: QFont
  • strikeOutPos: QFontMetrics
  • string: QConstString
  • stringListBegin: QVariant
  • stringListEnd: QVariant
  • stringShown: QtMultiLineEdit
  • stripWhiteSpace: QCString QString
  • style: QApplication QBrush QPen QWidget
  • styleChange: QWidget
  • styleHint: QFont QFontInfo QStyle
  • stylePixmap: QStyle
  • styleSheet: QStyleSheetItem QTextEdit
  • styleStrategy: QFont
  • styleString: QFontDatabase
  • styles: QFontDatabase
  • subRect: QStyle
  • subkeyList: QSettings
  • substitute: QFont
  • substitutes: QFont
  • substitutions: QFont
  • substringData: QDomCharacterData
  • subtract: QRegion
  • subtractLine: QDial QRangeControl
  • subtractPage: QDial QRangeControl
  • subtractStep: QSlider
  • suffix: QSpinBox
  • superClass: QMetaObject
  • superClassName: QMetaObject
  • supportedOperations: QNetworkProtocol
  • supportsDepth: QScreen
  • supportsMargin: QLayout
  • supportsSelection: QClipboard
  • swapBuffers: QGLContext QGLWidget
  • swapCells: QTable
  • swapColumns: QTable
  • swapRGB: QImage
  • swapRows: QTable
  • syncX: QApplication
  • systemBitOrder: QImage
  • systemByteOrder: QImage
  • systemId: QDomDocumentType QDomEntity QDomNotation QXmlParseException
  • tab: QStyleOption QTabBar
  • tabArray: QPainter
  • tabAt: QTabBar
  • tabBar: QTabDialog QTabWidget
  • tabIconSet: QTabWidget
  • tabLabel: QTabDialog QTabWidget
  • tabList: QTabBar
  • tabPosition: QTabWidget
  • tabShape: QTabWidget
  • tabStopWidth: QTextEdit
  • tabStops: QPainter
  • tabToolTip: QTabWidget
  • tabWidth: QStyleOption
  • table: QTableItem
  • tableFlags: QtTableView
  • tables: QSqlDatabase QSqlDriver
  • tabletEvent: QWidget
  • tag: QStyleSheet
  • tagName: QDomElement
  • take: QAsciiCache QAsciiDict QCache QDict QIntCache QIntDict QPtrDict QPtrList QPtrVector
  • takeCurrent: QGLayoutIterator QLayoutIterator
  • takeDefaultFactory: QMimeSourceFactory
  • takeItem: QIconView QListBox QListView QListViewItem QTable
  • takeNode: QPtrList
  • target: QDomProcessingInstruction QDragObject
  • testBit: QBitArray
  • testOption: QGLFormat
  • testTableFlags: QtTableView
  • testWFlags: QWidget
  • text: QAccessibleInterface QAction QButton QCanvasText QCheckBox QCheckListItem QClipboard QColorGroup QComboBox QComboTableItem QDataTable QDomElement QIMEvent QIconViewItem QImage QKeyEvent QLabel QLineEdit QListBox QListBoxItem QListViewItem QMenuData QMessageBox QPopupMenu QPushButton QRadioButton QSpinBox QTab QTable QTableItem QTextEdit QWhatsThis QtMultiLineEdit
  • textChanged: QComboBox QLineEdit QSpinBox QTextEdit QtMultiLineEdit
  • textCursor: QTextEdit
  • textFlags: QCanvasText
  • textFor: QToolTip QWhatsThis
  • textFormat: QLabel QMessageBox QTextEdit
  • textKeys: QImage
  • textLabel: QToolButton
  • textLanguages: QImage
  • textLine: QMultiLineEdit QtMultiLineEdit
  • textList: QImage
  • textRect: QIconViewItem
  • textWidth: QtMultiLineEdit
  • texts: QDns
  • tickInterval: QSlider
  • tickmarks: QSlider
  • tile: QCanvas QWorkspace
  • tileHeight: QCanvas
  • tileWidth: QCanvas
  • tilesHorizontally: QCanvas
  • tilesVertically: QCanvas
  • time: QDateTime QTimeEdit
  • timeEdit: QDateTimeEdit
  • timeout: QTimer
  • timerEvent: QObject
  • timerId: QTimerEvent
  • tip: QToolTip
  • title: QGroupBox QWizard
  • titleFont: QWizard
  • toAttr: QDomNode
  • toBitArray: QVariant
  • toBitmap: QVariant
  • toBool: QVariant
  • toBrush: QVariant
  • toByteArray: QVariant
  • toCDATASection: QDomNode
  • toCString: QDomDocument QVariant
  • toCharacterData: QDomNode
  • toColor: QVariant
  • toColorGroup: QVariant
  • toComment: QDomNode
  • toCursor: QVariant
  • toDate: QVariant
  • toDateTime: QVariant
  • toDocument: QDomNode
  • toDocumentFragment: QDomNode
  • toDocumentType: QDomNode
  • toDouble: QCString QString QVariant
  • toElement: QDomNode
  • toEntity: QDomNode
  • toEntityReference: QDomNode
  • toField: QSqlFieldInfo
  • toFirst: QAsciiCacheIterator QAsciiDictIterator QCacheIterator QDictIterator QIntCacheIterator QIntDictIterator QPtrDictIterator QPtrListIterator
  • toFloat: QCString QString
  • toFont: QVariant
  • toIconSet: QVariant
  • toImage: QVariant
  • toInt: QCString QString QVariant
  • toKeySequence: QVariant
  • toLast: QAsciiCacheIterator QCacheIterator QIntCacheIterator QPtrListIterator
  • toList: QPtrVector QVariant
  • toLong: QCString QString
  • toMap: QVariant
  • toNotation: QDomNode
  • toPage: QPrinter
  • toPalette: QVariant
  • toPixmap: QVariant
  • toPoint: QVariant
  • toPointArray: QVariant
  • toProcessingInstruction: QDomNode
  • toRecord: QSqlRecordInfo
  • toRect: QVariant
  • toRegion: QVariant
  • toShort: QCString QString
  • toSize: QVariant
  • toSizePolicy: QVariant
  • toString: QDate QDateTime QDomDocument QFont QHostAddress QSqlCursor QSqlRecord QTime QUrl QVariant
  • toStringList: QSqlRecord QVariant
  • toText: QDomNode
  • toTime: QVariant
  • toUInt: QCString QString QVariant
  • toULong: QCString QString
  • toUShort: QCString QString
  • toUnicode: QTextCodec QTextDecoder
  • toVector: QPtrList
  • toggle: QAction QButton QCheckBox QPushButton QRadioButton QToolButton
  • toggleBit: QBitArray
  • toggleCurrentItem: QListBox
  • toggleType: QButton
  • toggled: QAction QButton QCheckBox QPushButton QRadioButton
  • toolBars: QMainWindow
  • toolTip: QAction QTabBar QWidgetPlugin
  • toolTipGroup: QMainWindow
  • top: QDoubleValidator QIntValidator QPtrStack QRect QValueStack
  • topCell: QtTableView
  • topDock: QMainWindow
  • topEdge: QCanvasSprite
  • topItem: QListBox
  • topLeft: QRect
  • topLevelWidget: QWidget
  • topLevelWidgets: QApplication
  • topMargin: QScrollView
  • topRight: QRect
  • topRow: QTableSelection
  • total: QSemaphore
  • totalCost: QAsciiCache QCache QIntCache
  • totalHeight: QListViewItem QtTableView
  • totalSize: QScreen
  • totalSteps: QProgressBar QProgressDialog
  • totalWidth: QtTableView
  • tr: QObject
  • trUtf8: QObject
  • tracking: QDial QHeader QScrollBar QSlider
  • transaction: QSqlDatabase
  • transformOrientation: QDirectPainter QScreen
  • translate: QApplication QPainter QPointArray QRegion QWMatrix
  • translation: QTranslatorMessage
  • transpose: QSize
  • treeStepSize: QListView
  • triggerUpdate: QListBox QListView
  • trueMatrix: QPixmap
  • trueText: QDataTable
  • truncate: QCString QMemArray QString
  • tryAccess: QSemaphore
  • tryLock: QApplication QMutex
  • tryTerminate: QProcess
  • turnOffChild: QCheckListItem
  • type: QApplication QCheckListItem QEvent QMetaProperty QNPStream QSocketDevice QSocketNotifier QSqlError QSqlField QSqlFieldInfo QVariant QXmlAttributes
  • typeID: QSqlFieldInfo
  • typeName: QVariant
  • typeToName: QVariant
  • unPolish: QStyle
  • uncache: QScreen
  • underline: QFont QTextEdit
  • underlinePos: QFontMetrics
  • undo: QLineEdit QTextEdit QtMultiLineEdit
  • undoAvailable: QTextEdit QtMultiLineEdit
  • undoDepth: QTextEdit QtMultiLineEdit
  • undock: QDockWindow
  • ungetch: QFile QIODevice QSocket
  • unicode: QChar QString
  • unicodeUriToUri: QUriDrag
  • uniqueId: QTabletEvent
  • unite: QRect QRegion
  • unload: QLibrary
  • unlock: QApplication QLock QMutex
  • unparsedEntityDecl: QXmlDTDHandler
  • unpause: QMovie
  • unregisterDecoderFactory: QImageDecoder
  • unsetCursor: QWidget
  • unsetDevice: QDataStream QTextStream
  • unsetFont: QWidget
  • unsetPalette: QWidget
  • unsetf: QTextStream
  • unsqueeze: QTranslator
  • unuseJavaClass: QNPlugin
  • upRect: QSpinBox
  • update: QCanvas QCanvasItem QDataBrowser QSqlCursor QWidget
  • updateAccessibility: QAccessible
  • updateBoundary: QDataBrowser
  • updateButtons: QDateEdit QTimeEdit
  • updateCell: QGridView QTable QtTableView
  • updateContents: QListView QScrollView
  • updateCurrent: QDataBrowser QDataTable
  • updateDisplay: QSpinBox
  • updateGL: QGLWidget
  • updateGeometry: QWidget
  • updateItem: QListBox QMenuData QPopupMenu
  • updateMask: QWidget
  • updateOverlayGL: QGLWidget
  • updateScrollBars: QScrollView QtTableView
  • updateTableSize: QtTableView
  • upper: QCString QChar QString
  • uri: QXmlAttributes QXmlNamespaceSupport
  • uriToLocalFile: QUriDrag
  • uriToUnicodeUri: QUriDrag
  • url: QFileDialog QNPStream QNetworkProtocol
  • useHighlightColors: QMotifStyle
  • user: QUrl
  • userAgent: QNPInstance
  • userName: QSqlDatabase
  • uses3D: QToolButton
  • usesBigPixmap: QToolButton
  • usesBigPixmaps: QMainWindow
  • usesDropDown: QActionGroup
  • usesTextLabel: QMainWindow QToolButton
  • usesTextLabelChanged: QMainWindow
  • usleep: QThread
  • utf8: QString
  • vScrollBarMode: QScrollView
  • valid: QImage
  • validChunk: QCanvas
  • validate: QDoubleValidator QIntValidator QRegExpValidator QValidator
  • validateAndSet: QLineEdit
  • validator: QComboBox QLineEdit QSpinBox QtMultiLineEdit
  • value: QDataTable QDial QDomAttr QLCDNumber QRangeControl QScrollBar QSignal QSlider QSpinBox QSqlField QSqlQuery QSqlRecord QXmlAttributes
  • valueChange: QDial QRangeControl QSlider QSpinBox
  • valueChanged: QDateEdit QDateTimeEdit QDial QScrollBar QSlider QSpinBox QTable QTimeEdit
  • valueFromPosition: QRangeControl
  • valueToKey: QMetaProperty
  • valueToKeys: QMetaProperty
  • values: QMap
  • variableHeight: QListBox
  • variableWidth: QListBox
  • verData: QSizePolicy
  • verStretch: QSizePolicy
  • version: QDataStream
  • verticalAlignment: QStyleSheetItem
  • verticalHeader: QTable
  • verticalScrollBar: QScrollView QtTableView
  • viewHeight: QtTableView
  • viewMode: QFileDialog
  • viewRect: QtTableView
  • viewWidth: QtTableView
  • viewport: QPainter QScrollView
  • viewportPaintEvent: QScrollView
  • viewportResizeEvent: QScrollView
  • viewportSize: QScrollView
  • viewportToContents: QScrollView
  • visibilityChanged: QDockWindow
  • visibleHeight: QScrollView
  • visibleRect: QWidget
  • visibleWidget: QWidgetStack
  • visibleWidth: QScrollView
  • visualRect: QStyle
  • wait: QThread QWaitCondition
  • waitForMore: QSocket QSocketDevice
  • wakeAll: QWaitCondition
  • wakeOne: QWaitCondition
  • wakeUpGuiThread: QApplication
  • warning: QMessageBox QXmlErrorHandler
  • wasCancelled: QProgressDialog
  • weight: QFont QFontDatabase QFontInfo
  • whatsThis: QAccel QAction QMainWindow QMenuData QPopupMenu QWidgetPlugin
  • whatsThisButton: QWhatsThis
  • wheelEvent: QWidget
  • wheelScrollLines: QApplication
  • whiteSpaceMode: QStyleSheetItem
  • widget: QDockWindow QLayoutItem QNPInstance QSqlForm QWidgetItem QWidgetStack
  • widgetAt: QApplication
  • widgetToField: QSqlForm
  • width: QCanvas QCanvasEllipse QCanvasRectangle QCanvasSprite QDirectPainter QFontMetrics QIconViewItem QImage QListBoxItem QListBoxPixmap QListBoxText QListViewItem QPaintDeviceMetrics QPen QPixmap QRect QScreen QSimpleRichText QSize QTextStream QWidget
  • widthChanged: QListViewItem
  • widthMM: QPaintDeviceMetrics
  • widthUsed: QSimpleRichText
  • wildcard: QRegExp
  • winEvent: QWidget
  • winEventFilter: QApplication
  • winFocus: QApplication
  • winId: QWSWindow QWidget
  • winPageSize: QPrinter
  • winVersion: QApplication
  • winding: QCanvasPolygonalItem
  • window: QPainter
  • windowActivated: QWorkspace
  • windowActivationChange: QWidget
  • windowAt: QWSServer
  • windowCreated: QGLContext
  • windowEvent: QWSServer
  • windowList: QWorkspace
  • wordWrap: QTableItem QTextEdit QtMultiLineEdit
  • wordWrapIconText: QIconView
  • workingDirectory: QProcess
  • worldMatrix: QCanvasView QPainter
  • wrapColumnOrWidth: QTextEdit QtMultiLineEdit
  • wrapPolicy: QTextEdit QtMultiLineEdit
  • wrapping: QDial QSpinBox
  • writable: QMetaProperty
  • write: QAsciiDict QDict QImageIO QIntDict QNPInstance QNPStream QPtrDict QPtrList QPtrQueue QPtrStack QPtrVector QTranslatorMessage
  • writeBlock: QBuffer QIODevice QSocket QSocketDevice
  • writeBytes: QDataStream
  • writeEntry: QSettings
  • writeField: QSqlForm
  • writeFields: QDataBrowser QDataView QSqlForm
  • writeRawBytes: QDataStream QTextStream
  • writeReady: QNPInstance
  • writeToStdin: QProcess
  • wroteToStdin: QProcess
  • x: QCanvasItem QContextMenuEvent QIconViewItem QMouseEvent QPoint QRect QTabletEvent QWheelEvent QWidget
  • x11AppCells: QPaintDevice
  • x11AppColormap: QPaintDevice
  • x11AppDefaultColormap: QPaintDevice
  • x11AppDefaultVisual: QPaintDevice
  • x11AppDepth: QPaintDevice
  • x11AppDisplay: QPaintDevice
  • x11AppDpiX: QPaintDevice
  • x11AppDpiY: QPaintDevice
  • x11AppScreen: QPaintDevice
  • x11AppVisual: QPaintDevice
  • x11Cells: QPaintDevice
  • x11Colormap: QPaintDevice
  • x11DefaultColormap: QPaintDevice
  • x11DefaultVisual: QPaintDevice
  • x11Depth: QPaintDevice
  • x11Display: QPaintDevice
  • x11Event: QWidget QXtWidget
  • x11EventFilter: QApplication
  • x11ProcessEvent: QApplication
  • x11Screen: QPaintDevice
  • x11SetAppDpiX: QPaintDevice
  • x11SetAppDpiY: QPaintDevice
  • x11Visual: QPaintDevice
  • xForm: QBitmap QImage QPainter QPixmap
  • xFormDev: QPainter
  • xOffset: QDirectPainter QtTableView
  • xTilt: QTabletEvent
  • xVelocity: QCanvasItem
  • xtWidget: QXtWidget
  • y: QCanvasItem QContextMenuEvent QIconViewItem QMouseEvent QPoint QRect QTabletEvent QWheelEvent QWidget
  • yOffset: QDirectPainter QtTableView
  • yTilt: QTabletEvent
  • yVelocity: QCanvasItem
  • year: QDate
  • z: QCanvasItem
  • zoomIn: QTextEdit
  • zoomOut: QTextEdit
  • zoomTo: QTextEdit


Header File Index

Here are the header files that make up the Qt API:

  • qaccel.h
  • qaccessible.h
  • qaction.h
  • qapplication.h
  • qasciicache.h
  • qasciidict.h
  • qasyncimageio.h
  • qasyncio.h
  • qbitarray.h
  • qbitmap.h
  • qbrush.h
  • qbuffer.h
  • qbutton.h
  • qbuttongroup.h
  • qcache.h
  • qcanvas.h
  • qcdestyle.h
  • qcheckbox.h
  • qclipboard.h
  • qcolor.h
  • qcolordialog.h
  • qcombobox.h
  • qcommonstyle.h
  • qcopchannel_qws.h
  • qcstring.h
  • qcursor.h
  • qdatabrowser.h
  • qdatastream.h
  • qdatatable.h
  • qdataview.h
  • qdatetime.h
  • qdatetimeedit.h
  • qdesktopwidget.h
  • qdial.h
  • qdialog.h
  • qdict.h
  • qdir.h
  • qdirectpainter_qws.h
  • qdns.h
  • qdockarea.h
  • qdockwindow.h
  • qdom.h
  • qdragobject.h
  • qdrawutil.h
  • qdropsite.h
  • qeditorfactory.h
  • qerrormessage.h
  • qeucjpcodec.h
  • qeuckrcodec.h
  • qevent.h
  • qfile.h
  • qfiledialog.h
  • qfileinfo.h
  • qfocusdata.h
  • qfont.h
  • qfontdatabase.h
  • qfontdialog.h
  • qfontinfo.h
  • qfontmanager_qws.h
  • qfontmetrics.h
  • qframe.h
  • qftp.h
  • qgb18030codec.h
  • qgfx_qws.h
  • qgl.h
  • qglcolormap.h
  • qglobal.h
  • qgrid.h
  • qgridview.h
  • qgroupbox.h
  • qguardedptr.h
  • qhbox.h
  • qhbuttongroup.h
  • qheader.h
  • qhgroupbox.h
  • qhostaddress.h
  • qhttp.h
  • qiconset.h
  • qiconview.h
  • qimage.h
  • qimageformatplugin.h
  • qinputdialog.h
  • qintcache.h
  • qintdict.h
  • qiodevice.h
  • qjiscodec.h
  • qkeyboard_qws.h
  • qkeysequence.h
  • qlabel.h
  • qlayout.h
  • qlcdnumber.h
  • qlibrary.h
  • qlineedit.h
  • qlistbox.h
  • qlistview.h
  • qlocalfs.h
  • qlock_qws.h
  • qmainwindow.h
  • qmap.h
  • qmemarray.h
  • qmenubar.h
  • qmenudata.h
  • qmessagebox.h
  • qmetaobject.h
  • qmime.h
  • qmotifplusstyle.h
  • qmotifstyle.h
  • qmovie.h
  • qmultilineedit.h
  • qmutex.h
  • qnamespace.h
  • qnetworkprotocol.h
  • qnp.h
  • qobject.h
  • qobjectcleanuphandler.h
  • qobjectlist.h
  • qpaintdevice.h
  • qpaintdevicemetrics.h
  • qpainter.h
  • qpair.h
  • qpalette.h
  • qpen.h
  • qpicture.h
  • qpixmap.h
  • qpixmapcache.h
  • qplatinumstyle.h
  • qpngio.h
  • qpoint.h
  • qpointarray.h
  • qpopupmenu.h
  • qprinter.h
  • qprocess.h
  • qprogressbar.h
  • qprogressdialog.h
  • qptrcollection.h
  • qptrdict.h
  • qptrlist.h
  • qptrqueue.h
  • qptrstack.h
  • qptrvector.h
  • qpushbutton.h
  • qradiobutton.h
  • qrangecontrol.h
  • qrect.h
  • qregexp.h
  • qregion.h
  • qrtlcodec.h
  • qscrollbar.h
  • qscrollview.h
  • qsemaphore.h
  • qserversocket.h
  • qsessionmanager.h
  • qsettings.h
  • qsgistyle.h
  • qsignal.h
  • qsignalmapper.h
  • qsimplerichtext.h
  • qsize.h
  • qsizegrip.h
  • qsizepolicy.h
  • qsjiscodec.h
  • qslider.h
  • qsocket.h
  • qsocketdevice.h
  • qsocketnotifier.h
  • qsortedlist.h
  • qsound.h
  • qspinbox.h
  • qsplitter.h
  • qsql.h
  • qsqlcursor.h
  • qsqldatabase.h
  • qsqldriver.h
  • qsqldriverplugin.h
  • qsqleditorfactory.h
  • qsqlerror.h
  • qsqlfield.h
  • qsqlform.h
  • qsqlindex.h
  • qsqlpropertymap.h
  • qsqlquery.h
  • qsqlrecord.h
  • qsqlresult.h
  • qstatusbar.h
  • qstring.h
  • qstringlist.h
  • qstrlist.h
  • qstyle.h
  • qstylefactory.h
  • qstyleplugin.h
  • qstylesheet.h
  • qtabbar.h
  • qtabdialog.h
  • qtable.h
  • qtabwidget.h
  • qtextbrowser.h
  • qtextcodec.h
  • qtextcodecplugin.h
  • qtextedit.h
  • qtextstream.h
  • qtextview.h
  • qthread.h
  • qtimer.h
  • qtmultilineedit.h
  • qtoolbar.h
  • qtoolbutton.h
  • qtooltip.h
  • qtranslator.h
  • qtsciicodec.h
  • qttableview.h
  • qurl.h
  • qurlinfo.h
  • qurloperator.h
  • qvalidator.h
  • qvaluelist.h
  • qvaluestack.h
  • qvaluevector.h
  • qvariant.h
  • qvbox.h
  • qvbuttongroup.h
  • qvgroupbox.h
  • qwaitcondition.h
  • qwhatsthis.h
  • qwidget.h
  • qwidgetfactory.h
  • qwidgetplugin.h
  • qwidgetstack.h
  • qwindowdefs.h
  • qwindowsstyle.h
  • qwindowsystem_qws.h
  • qwizard.h
  • qwmatrix.h
  • qworkspace.h
  • qwsdecoration_qws.h
  • qwsmouse_qws.h
  • qxml.h
  • qxt.h


关于模块

当你安装Qt时，这些模块会被构建到库中。在Qt企业版、Qt评估版和Qt自由版中，包含所有的模块。对于Qt专业版，提供基本的模块——工具、核心、窗口部件、对话框、图标视图和工作区模块。Trolltech公司现在还不单独出售模块。

所有模块的使用都与相应版本的许可证条款相关。

  • 画布模块
  • 图标视图模块
  • 网络模块
  • OpenGL模块
  • SQL模块
  • 表格模块
  • 工作区（MDI）模块
  • XML模块

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


画布模块

这个模块是Qt企业版的一部分。

画布模块提供了一个名为QCanvas的高度优化的二维绘图区。 画布可以有任意数量的QCanvasItems。画布项则可以有任意的形状、尺寸和内容，在画布中能自由的移动，并且能被检查出是否有冲突。画布项能被设置成在画布中自动地移动以及使画布项支持QCanvasSprite。（如果你需要三维绘图请看Qt的OpenGL模块。）

画布模块使用文档/视图模型。QCanvasView 类是被用来显示画布的特定视图。多视图能同时在同一画布中显示。每一个视图在画布中使用一个任意的变换矩阵，以便能使其容易的实现诸如缩放的特性。

Screenshot of a canvas

Qt提供了一系列预定义的QCanvas项，如下所示:

  • QCanvasItem--一个所有画布项的抽象基类。
  • QCanvasEllipse--椭圆或者“饼的部分”。
  • QCanvasLine--线条部分。
  • QCanvasPolygon--多边形。
  • QCanvasPolygonalItem--一个含有非矩形形状的基类。大多数画布项都派生于此类。
  • QCanvasRectangle--矩形。此类矩形不能被倾斜或旋转。绘制可旋转的矩形使用QCanvasPolygon。
  • QCanvasSpline--多重贝塞尔曲线。
  • QCanvasSprite--活动的图片。
  • QCanvasText--文本字符串。

QCanvasPixmap和QCanvasPixmapArray这两个类是由QCanvasSprite类来显示在画布上的活动和移动的图片。

更多的专门的项能够通过继承画布项类来实现。从一个QCanvasItem的派生类（通常为 QCanvasPolygonalItem）来实现比直接从QCanvasItem继承更容易。

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


图标视图模块

图标视图模块提供了一个功能强大的名为QIconView可视化窗口部件。API和特性类似于QListView和QListBox。它包含可选的带标签图片条目，这些条目可供用户选择、拖拽、重命名、删除以及更多操作。

Screenshot of QIconVIew

详情请查阅类文档。

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


Network Module

This module is part of the Qt Enterprise Edition.

  • Introduction
  • Working Network Protocol independent with QUrlOperator and QNetworkOperation
    • Implementing your own Network Protocol
    • Error Handling

Introduction

The network module offers classes to make network programming easier and portable. Basically there are three sets of classes, first very basic classes like QSocket, QServerSocket, QDns, etc. which allow to work in a portable way with TCP/IP sockets. In addition, there are classes like QNetworkProtocol, QNetworkOperation in the Qt base library, which provide an abstract layer for implementing network protocols and QUrlOperator which operates on such network protocols. Finally the third set of network classes are the passive ones, namely QUrl and QUrlInfo which do URL parsing and similar stuff.

The first set of classes (QSocket, QServerSocket, QDns, QFtp, etc.) are included in the "network" module of Qt.

The QSocket classes are not directly related to the QNetwork classes, but QSocket should and will be used for implementing network protocols, which are directly related to the QNetwork classes. E.g. the QFtp class (implementation of the FTP protocol) uses QSockets. But QSockets don't need to be used for protocol implementations, e.g. QLocalFs (which is an implementation of the local filesystem as network protocol) uses QDir and no QSocket. Using QNetworkProtocols you can implement everything which fits into a hierarchical structure and can be accessed using URLs. This could be e.g. a protocol which can read pictures from a digital camera using a serial connection.

Working Network Protocol independent with QUrlOperator and QNetworkOperation

To just use existing network protocol implementations and operate on URLs using them is quite easy. E.g. downloading a file from an FTP server to the local filesystem can be done with following code:

    QUrlOperator op;
    op.copy( "ftp://ftp.trolltech.com/qt/source/qt-2.1.0.tar.gz", "file:/tmp", FALSE );

And that's all! Of course an implementation of the FTP protocol has to be available and registered for doing that. More information on that later.

You can also do stuff like creating directories, removing files, renaming, etc. E.g. to create a folder on a private FTP account do

    QUrlOperator op( "ftp://username:password@host.domain.no/home/username" );
    op.mkdir( "New Directory" );

That's it again. To see all available operations, look at the QUrlOperator class documentation.

Now as everything works asynchronous, the function call for an operation returns before the operation has been processed. So you don't get a return value which tells you something about failure or success. The return value always is a pointer to a QNetworkOperation.

In this QNetworkOperation all information about the operation is stored. There is e.g. a method of QNetworkOperation which returns the state of this operation. Using that you can find out all the time in which state the operation currently is. Also you get the arguments you passed to the QUrlOperator method, the type of the operation and some more stuff from this QNetworkOperation object. For more details see the class documentation of QNetworkOperation.

Now, later you get signals emitted by the QUrlOperator, which inform you about the process of the operations. As you can call many methods which operate on a URL of one QUrlOperator, it queues up all these operations. So you can't know which operation the QUrlOperator just processes. Because of this you get in each signal as the last argument a pointer to the QNetworkOperation object which is just processed and from which this signal comes.

Some of these operations send a start() signal at the beginning (depending if it makes sense or not), then some of them send some signals during processing the operation, and all operations send a finished() signal after they are done. Now, finished could mean that the operation has been successfully finished or that it failed. To find that out you can use the QNetworkOperation pointer you got with the finished() signal. If QNetworkOperation::state() equals QNetworkProtocol::StDone the operation finished successful, if it is QNetworkProtocol::StFailed the operation failed.

Now, a slot which you connected to the QUrlOperator::finished( QNetworkOperation * ) signal could look like this

void MyClass::slotOperationFinished( QNetworkOperation *op )
{
    switch ( op->operation() ) {
    case QNetworkProtocol::OpMkDir: {
        if ( op->state() == QNetworkProtocol::StFailed )
            qDebug( "Couldn't create directory %s", op->arg( 0 ).latin1() );
        else
            qDebug( "Successfully created directory %s", op->arg( 0 ).latin1() );
    } break;
    // ... and so on
    }
}

As mentioned before, some operations send other signals too. Let's take the list children operation as an example (e.g. read the directory of a directory on a FTP server):

QUrlOperator op;

MyClass::MyClass() : QObject(), op( "ftp://ftp.trolltech.com" )
{
    connect( &op, SIGNAL( newChildren( const QValueList<QUrlInfo> &, QNetworkOperation * ) ),
             this, SLOT( slotInsertEntries( const QValueList<QUrlInfo> &, QNetworkOperation * ) ) );
    connect( &op, SIGNAL( start( QNetworkOperation * ) ),
             this, SLOT( slotStart( QNetworkOperation *) ) );
    connect( &op, SIGNAL( finished( QNetworkOperation * ) ),
             this, SLOT( slotFinished( QNetworkOperation *) ) );
}

void MyClass::slotInsertEntries( const QValueList<QUrlInfo> &info, QNetworkOperation * )
{
    QValueList<QUrlInfo>::ConstIterator it = info.begin();
    for ( ; it != info.end(); ++it ) {
        const QUrlInfo &inf = *it;
        qDebug( "Name: %s, Size: %d, Last Modified: %s",
            inf.name().latin1(), inf.size(), inf.lastModified().toString().latin1() );
    }
}

void MyClass::slotStart( QNetworkOperation * )
{
    qDebug( "Start reading '%s'", op.toString().latin1() );
}

void MyClass::slotFinished( QNetworkOperation *operation )
{
    if ( operation->operation() == QNetworkProtocol::OpListChildren ) {
        if ( operation->state() == QNetworkProtocol::StFailed )
            qDebug( "Couldn't read '%s'! Following error occurred: %s",
                op.toString().latin1(), operation->protocolDetail().latin1() );
        else
            qDebug( "Finished reading '%s'!", op.toString().latin1() );
    }
}

These examples explained now how to use the QUrlOperator and QNetworkOperations. The network extension will contain some good examples for this too.

Implementing your own Network Protocol

QNetworkProtocol provides a base class for implementations of network protocols and an architecture to a dynamic registration and unregistration of network protocols. If you use this architecture you also don't need to care about asynchronous programming, as the architecture hides this and does all the work for you.

Limitation: As it is quite hard to design a base class for network protocols which satisfies all network protocols, the architecture described here is designed to work with all kinds of hierarchical structures, like filesystems. So everything which can be interpreted as hierarchical structure and accessed via URLs, can be implemented as network protocol and easily used in Qt. This is not limited to filesystems only!

To implement a network protocol create a class derived from QNetworkProtocol.

Other classes will use this network protocol implementation to operate on it. So you should reimplement following protected members

    void QNetworkProtocol::operationListChildren( QNetworkOperation *op );
    void QNetworkProtocol::operationMkDir( QNetworkOperation *op );
    void QNetworkProtocol::operationRemove( QNetworkOperation *op );
    void QNetworkProtocol::operationRename( QNetworkOperation *op );
    void QNetworkProtocol::operationGet( QNetworkOperation *op );
    void QNetworkProtocol::operationPut( QNetworkOperation *op );

Some words about how to reimplement these methods: You always get a pointer to a QNetworkOperation as argument. This pointer holds all information about the operation in the current state. If you start processing such an operation, set the state to QNetworkProtocol::StInProgress. If you finished processing the operation, set the state to QNetworkProtocol::StDone if it was successful or QNetworkProtocol::StFailed if an error occurred. If an error occurred you have to set an error code (see QNetworkOperation::setErrorCode() ) and if you know some details (e.g. an error message) you can also set this message to the operation pointer (see QNetworkOperation::setProtocolDetail() ). Also you get all information (type, arguments, etc.) of the operation from this QNetworkOperation pointer. For details about which arguments you can get and set look at the class documentation of QNetworkOperation.

If you reimplement such an operation method, it's also very important to emit the correct signals at the correct time: In general always emit at the end of an operation (when you either successfully finished processing the operation or and error occurred) the finished() signal with the network operation as argument. The whole network architecture relies on correctly emitted finished() signals! So be careful with that! Then there are some more special signals which are specific to operations:

  • Emit in operationListChildren:
    • start() just before starting listing the children
    • newChildren() when new children are read
  • Emit in operationMkDir:
    • createdDirectory() after the directory has been created
    • newChild() (or newChildren()) after the directory has been created (as a new directory is a new child)
  • Emit in operationRemove:
    • removed() after the child has been removed
  • Emit in operationRename:
    • itemChanged() after the child has been renamed
  • Emit in operationGet:
    • data() each time new data has been read
    • dataTransferProgress() each time new data has been read to indicate how much of the data has been read now.
  • Emit in operationPut:
    • dataTransferProgress() each time data has been written to indicate how much of the data has been written. Although you know the whole data when this operation is called, it's suggested not to write the whole data at once, but to do it step by step to avoid blocking the GUI and also this way the progress can be made visible to the user.

And remember, always emit the finished() signal at the end!

For more details about the arguments of these signals take a look at the QNetworkProtocol class documentation.

Now, as argument in such a method you get the QNetworkOperation which you process. Here is a list which arguments of the QNetworkOperation you can get and which you have to set in which method:

(To get the URL on which you should work, use the QNetworkProtocol::url() method which returns the pointer to the URL operator. Using that you can get the path, host, name filter and everything else of the URL)

  • In operationListChildren:
    • Nothing.
  • In operationMkDir:
    • QNetworkOperation::arg( 0 ) contains the name of the directory which should be created
  • In operationRemove:
    • QNetworkOperation::arg( 0 ) contains the name of the file which should be removed. Normally this is a relative name. But it may be absolute too, so use QUrl( op->arg( 0 ) ).fileName() to get the filename.
  • In operationRename:
    • QNetworkOperation::arg( 0 ) contains the name of the file which should be renamed
    • QNetworkOperation::arg( 1 ) contains the name to which it should be renamed.
  • In operationGet:
    • QNetworkOperation::arg( 0 ) contains the full URL of the file which should be retrieved.
  • In operationPut:
    • QNetworkOperation::arg( 0 ) contains the full URL of the file in which the data should be stored.
    • QNetworkOperation::rawArg( 1 ) contains the data which should be stored in QNetworkOperation::arg( 0 )

So, to sum it up: If you reimplement such an operation method, you have to emit some special signals and always at the end a finished() signal, either on success or on failure. Also you have to change the state of the QNetworkOperation during processing it and can get and set arguments of the operation as well.

But it's unlikely that the network protocol you implement supports all these operations. So, just reimplement the operations, which are supported by the protocol. Additionally you have to specify which operations are supported then. This is done by reimplementing

    int QNetworkProtocol::supportedOperations() const;

In your implementation of this method return an int value which is constructed by or'ing together the correct values (supported operations) of the following enum (of QNetworkProtocol):

    enum Operation {
        OpListChildren = 1,
        OpMkDir = 2,
        OpRemove = 4,
        OpRename = 8,
        OpGet = 32,
        OpPut = 64
    };

So, if your protocol e.g. supports listing children and renaming them, do in your implementation of supportedOperations():

    return OpListChildren | OpRename;

The last method you have to reimplement is

    bool QNetworkProtocol::checkConnection( QNetworkOperation *op );

Here you have to return TRUE, if the connection is up and ok (this means operations on the protocol can be done). If the connection is not ok, return FALSE and start to try opening it. If you will not be able to open the connection at all (e.g. because the host is not found), emit a finished() signal and set an error code and the QNetworkProtocol::StFailed state to the QNetworkOperation pointer you get here.

Now, you never need to check before doing an operation yourself, if the connection is ok. The network architecture does this, this means using checkConnection() it looks if an operation could be done and if not, it tries it again and again for some time and only calls an operation method if the connection is ok.

Using this knowledge it should be possible to implement network protocols. Finally to be able to use it with a QUrlOperator (and so e.g. in the QFileDialog), you have to register the network protocol implementation. This can be done like this:

    QNetworkProtocol::registerNetworkProtocol( "myprot", new QNetworkProtocolFactory<MyProtocol> );

In this case MyProtocol would be a class you implemented like described here (derived from QNetworkProtocol) and the name of the protocol would be myprot. So if you want to use it, you would do something like

    QUrlOperator op( "myprot://host/path" );
    op.listChildren();

Finally as example for a network protocol implementation you could look at the implementation of QLocalFs. The network extension will also contain an example implementation of a network protocol

Error Handling

Error handling is important for both, implementing new network protocols and using them (through QUrlOperator). So first some words about error handling when using the network protocols:

As already mentioned quite some times after processing an operation has been finished the network operation and so the QUrlOperator emits the finished() signal. This has as argument the pointer to the processed QNetworkOperation. If the state of this operation is QNetworkProtocol::StFailed, the operation contains some more information about this error. Following error codes are defined in QNetworkProtocol:

  • QNetworkProtocol::NoError - No error occurred
  • QNetworkProtocol::ErrValid - The URL you are operating on is not valid
  • QNetworkProtocol::ErrUnknownProtocol - There is no protocol implementation available for the protocol of the URL you are operating on (e.g. if the protocol is http and no http implementation has been registered)
  • QNetworkProtocol::ErrUnsupported - The operation is not supported by the protocol
  • QNetworkProtocol::ErrParse - Parse error of the URL
  • QNetworkProtocol::ErrLoginIncorrect - You needed to login but the username and or password are wrong
  • QNetworkProtocol::ErrHostNotFound - The specified host (in the URL) couldn't be found
  • QNetworkProtocol::ErrListChildren - An error occurred while listing the children
  • QNetworkProtocol::ErrMkDir - An error occurred when creating a directory
  • QNetworkProtocol::ErrRemove -An error occurred while removing a child
  • QNetworkProtocol::ErrRename - An error occurred while renaming a child
  • QNetworkProtocol::ErrGet - An error occurred while getting (retrieving) data
  • QNetworkProtocol::ErrPut - An error occurred while putting (uploading) data
  • QNetworkProtocol::ErrFileNotExisting - A file which is needed by the operation doesn't exist
  • QNetworkProtocol::ErrPermissionDenied - The permission for doing the operation has been denied

QNetworkOperation::errorCode() returns then one of these codes or maybe a different one if you use an own network protocol implementation which defines additional error codes.

QNetworkOperation::protocolDetails() may also return a string which contains an error message then which could e.g. be displayed for the user.

According to this information it should be possible to react on errors.

Now, if you implement your own network protocol, you will need to tell about errors which occurred. First you always need to be able to access the QNetworkOperation which is processed at the moment. This can be done using QNetworkOperation::operationInProgress(), which returns a pointer to the current network operation or 0 if no operation is processed at the moment.

Now if and error occurred and you need to handle it, do

    if ( operationInProgress() ) {
        operationInProgress()->setErrorCode( error_code_of_your_error );
        operationInProgress()->setProtocolDetails( detail ); // optional!
        emit finished( operationInProgress() );
        return;
    }

That's all. The connection to the QUrlOperator and so on is done automatically. Additionally, if the error was really bad so that no more operations can be done in the current state (e.g. if the host couldn't be found), call QNetworkProtocol::clearOperationStack() before emitting finished().

Now, as error code you should use, if possible, one of the predefined error codes of QNetworkProtocol. If this is not possible, you can add own error codes - they are just normal integers. Just be careful that the value of the error code doesn't conflict with an existing one.

Documentation about the low-level classes like QSocket, QDns, etc. will be included in the seperate network extension.

For internal use only.


Qt OpenGL三维绘图

这个模块是Qt企业版的一部分。

简介

OpenGL是为三维绘图提供的标准应用编程接口。

OpenGL处理的仅仅是三维绘图方面，而很少或是根本不提供图形用户界面编程方面的支持。OpenGL*应用程序的用户界面必须由其它工具包创建，比如在X平台下的Motif，在Windows平台下的微软基本类库（MFC）——或是在这两种平台下都能使用的Qt。

Qt的OpenGL模块使在Qt应用程序中使用OpenGL变的更加容易。它提供了一个OpenGL的部件类，这个部件类除了打开一个OpenGL显示缓冲，利用这个缓冲使用OpenGL应用编程接口来提供内容外，能像其它Qt部件那样的使用，。

Qt OpenGL模块的运作是一个与平台无关的Qt/C++的包装，这个包装则是和平台有关的GLX、WGL或AGL的C的应用编程接口。 其提供的功能则是和Mark Kilgard的GLUT库极为相似，但是Qt的OpenGL模块还有更多的非OpenGL特有的GUI机能，即它们都是Qt的应用编程接口。

安装

当你在X11中安装Qt时候，配置脚本将会自动检测你的系统上是否已安装了OpenGL的头文件和库，如果已正确安装了，在Qt的库中就会包括Qt OpenGL模块。（如果你的OpenGL头文件或库放置在一个非标准的目录下，你需要根据你的系统而修改config文件中的SYSCONF_CXXFLAGS_OPENGL和/或 SYSCONF_LFLAGS_OPENGL）。 对于OpenGL的一些配置需要线程生效，所以如果OpenGL没有被检测到，试一下configure -thread。

当你在Windows中安装Qt时候，Qt的OpenGL模块总是被包含的。

Qt的OpenGL模块的使用没有授权给Qt专业版，如需要OpenGL支持的话，可以考虑升级为Qt企业版。

在X11上使用Mesa时请注意: Mesa 3.1之前的版本在库中使用的名为“MesaGL”和“MesaGLU”，而不是“GL”和“GLU”。如果你想使用Mesa 3.1之前的版本的话，你必须改变Makefile来使用这些库的名字。最简单的方法就是编辑config文件中的SYSCONF_LIBS_OPENGL行，将“-lGL -lGLU”改成“-lMesaGL -lMesaGLU”，然后再次运行“configure”。

QGL类

在Qt中OpenGL提供支持的类为：

  • QGLWidget：一个容易使用的Qt部件，它提供了OpenGL场景。
  • QGLContext：封装了OpenGL提供的上下文。
  • QGLFormat：对于一个给定的上下文，指定特定的显示模式。
  • QGLColormap：在GL-index中处理编入索引的colormaps。

许多应用程序仅需要高等级的QGLWidget类。其它的QGL类提供了高级特性。X11的用户可能要阅读一下overlays中的注释。

参照OpenGL实例。

QGL的文档假设你熟悉OpenGL编程。如果你在这方面是个新手的话，一个好的起点就是http://www.opengl.org/。

*OpenGL是Silicon Graphics公司在美国和其它国家的注册商标。

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


SQL模块

这个模块是Qt企业版的一部分。

  • 介绍
  • SQL模块架构
  • SQL驱动程序插件
  • 连接数据库
  • 连接单一数据库
    • 连接多个数据库
  • 使用QSqlQuery执行SQL命令
    • 事务处理
    • 基本浏览
    • 基本数据处理
    • 定位数据集
  • 使用QSqlCursor
    • 检索记录
      • 排序和过滤记录
      • 提取数据
    • 处理记录
      • 插入记录
      • 更新记录
      • 删除记录
  • 基于数据的窗口部件
    • 基于数据的表
    • 创建基于数据的窗体
      • 显示记录
      • 在数据窗体中显示记录
      • 编辑记录
    • 自定义编辑器窗口部件
      • 为表格自定义编辑器窗口部件
  • 继承QSqlCursor
  • 实例表

介绍

Qt的SQL类帮助你给你的Qt应用程序提供无缝的数据库集成。

这个概述假设你已经至少有一些SQL的基础知识。你需要能够理解简单的SELECT、INSERT、UPDATE和DELETE命令。尽管QSqlCursor类提供了数据库浏览和编辑的界面不需要SQL的知识，但是对于SQL的基本理解还是被高度推荐的。一本SQL数据库的标准文本是C. J. Date所作的《数据库系统的介绍》（第七版），ISBN 0201385902。

本文所描述的实例是从完全人工编写代码的角度出发的，你还可以参考Qt设计器的用户手册中“创建数据库应用程序”这一节，它提供了更高层次的实现方法来演示窗口部件、执行挖掘和处理外键查找等相关的操作。

这份文档被分为六个部分：

SQL模块架构。描述了这些类是如何结合在一起的。

连接数据库。这部分解释了如何使用QSqlDatabase类建立数据库连接。

执行SQL命令。描述如何执行标准的数据操作命令，比如SELECT、INSERT、UPDATE和DELETE。（当然任何有效的SQL指令均可被送往数据库）。焦点在于用QSqlQuery进行交互处理。

使用游标。描述如何使用QSqlCursor类来实现更为强大的应用编程接口函数而不象在QSqlQuery中执行SQL语句。

基于数据的窗口部件。描述如何把数据库与用户接口链接起来。在这一节中我们介绍QDataTable、QSqlForm、QSqlPropertyMap和QSqlEditorFactory类，演示如何使用自定义的基于数据的窗口部件。Qt设计器提供了一个方便的可视化途径来实现同样的事情。请参考Qt设计器的手册，更多的详细情况请见QDataBrowser和QDataView。

继承QSqlCursor。本节给出了继承QSqlCursor的实例。继承类可为字段提供默认值与计算字段等功能（比如以一个自动数值为主键的索引列），以及显示计算字段等等的内容。比如显示一个名称而不是一个外键的标识符。

这个文档中所使用的表的定义的所有实例都在实例表部分。

SQL模块架构

SQL类分成以下三层：

用户接口层。这些类提供了基于数据的窗口部件，这些窗口部件不仅连接数据库还可为用户所浏览。（以QSqlCursor作为数据源)。终端用户通过这些组件来浏览与编辑数据。Qt设计器集成了这些类并可用来创建基于数据的窗体。这些窗口部件也可在程序中与你的C++代码直接交互。支持这一层的类包括QSqlEditorFactory、QSqlForm、QSqlPropertyMap、QDataTable、QDataBrowser和QDataView。

SQL应用编程接口层。这些类存取数据库。QSqlDatabase类用来连接数据库。数据交互的实现要么通过QSqlQuery类以SQL语句来实现，要么用QSqlCursor类，它封装了SQL命令集。除了QSqlDatabase、QSqlCursor和QSqlQuery这些类外，QSqlError、QSqlField、QSqlIndex和QSqlRecord也支持该层。

驱动程序层。本层由三个类组成：QSqlResult、QSqlDriver和QSqlDriverFactoryInterface。这个层在数据库和SQL类之间提供了底层的桥梁。这个层的文档是另外的，因为它只和驱动程序编写者有关，并且在标准数据库应用程序编程中很少用到。对于实现Qt的SQL驱动程序插件的详细情况请参考这里。

SQL驱动程序插件

Qt的SQL模块可以在运行期动态地装载新的驱动程序，这是通过插件实现的。

SQL驱动程序文档描述了如何为一个特定的数据库建立相应的插件。

一旦该插件被建立，Qt可以自动地装载它，之后就可为QSqlDatabase所用（详细信息请参考QSqlDatabase::drivers()）。

连接数据库

如果要使用QSqlQuery或QSqlCursor类，则少要连接并打开一个数据库连接。

如果应用程序只需要一个数据库连接，QSqlDatabase类可以创建一个为所有SQL操作所利用的默认连接，如果需要多个数据库连接，每个连接也可以容易地建立。

QSqlDatabase需要qsqldatabase.h这个头文件。

连接单一数据库

创建一个数据库连接需要三个操作：激活驱动程序、设置连接信息、打开连接。

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include "../login.h"

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

        QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
        if ( defaultDB ) {
            defaultDB->setDatabaseName( DB_SALES_DBNAME );
            defaultDB->setUserName( DB_SALES_USER );
            defaultDB->setPassword( DB_SALES_PASSWD );
            defaultDB->setHostName( DB_SALES_HOST );

            if ( defaultDB->open() ) {
                // 数据库被成功打开，我们现在可以运行SQL命令。
            }
        }

        return 0;
    }

来自sql/overview/connect1/main.cpp

在以上代码中我们先通过QSqlDatabase::addDatabase()激活了一个数据库驱动程序，传入了驱动程序名。现在可利用的驱动程序为：QODBC3（开放数据库连接）、QOCI8（Oracle 8和9）、QTDS7（Sybase Adaptive Server和Microsoft SQL Server）、QPSQL7（PostgreSQL 6和7）和QMYSQL3（MySQL）。请注意部分驱动程序并未包括在Qt的自由版中，详细情款请查看README文件。

连接创建后就成为应用程序的默认数据库连接并可为Qt的SQL类所使用。

其次我们调用了setDatabaseName()、setUserName()、setPassword()和setHostName()来初使化连接信息。对于QOCI8（Oracle 8和9），TNS服务名称必须由setDatbaseName()传递。当连接ODBC数据源时，数据源名称（DSN）必须在setDatabaseName()调用中使用。

最后我们调用了open()来打开数据库以存取数据，如果该步失败将返回假，用户可通过QSqlDatabase::lastError()来查明错误信息。

连接多个数据库

连接至多个数据库需要在使用QSqlDatabase::addDatabase()传入两个参数，其中第二个参数用来指明这个连接的唯一标识符。

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include "../login.h"

    bool createConnections();

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

        if ( createConnections() ) {
            // 数据库被成功打开，得到它们的指针：
            QSqlDatabase *oracledb = QSqlDatabase::database( "ORACLE" );
            // 现在我们可以在oracle连接或默认连接上执行SQL命令
        }

        return 0;
    }

    bool createConnections()
    {
        // 创建默认数据库连接
        QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
        if ( ! defaultDB ) {
            qWarning( "Failed to connect to driver" );
            return FALSE;
        }
        defaultDB->setDatabaseName( DB_SALES_DBNAME );
        defaultDB->setUserName( DB_SALES_USER );
        defaultDB->setPassword( DB_SALES_PASSWD );
        defaultDB->setHostName( DB_SALES_HOST );
        if ( ! defaultDB->open() ) {
            qWarning( "Failed to open sales database: " +
                      defaultDB->lastError().driverText() );
            qWarning( defaultDB->lastError().databaseText() );
            return FALSE;
        }

        // 创建一个名为oracle的连接
        QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
        if ( ! oracle ) {
            qWarning( "Failed to connect to oracle driver" );
            return FALSE;
        }
        oracle->setDatabaseName( DB_ORDERS_DBNAME );
        oracle->setUserName( DB_ORDERS_USER );
        oracle->setPassword( DB_ORDERS_PASSWD );
        oracle->setHostName( DB_ORDERS_HOST );
        if ( ! oracle->open() ) {
            qWarning( "Failed to open orders database: " +
                      oracle->lastError().driverText() );
            qWarning( oracle->lastError().databaseText() );
            return FALSE;
        }

        return TRUE;
    }

来自sql/overview/create_connections/main.cpp

在这个实例中我们打开了两个连接并加入了错误处理。静态函数QSqlDatabase::database()可以在任何地方调用以获得一个数据库连接的指针。如果我们在调用此函数时未使用参数则返回默认连接，如果有参数则返回指定的连接，如上例中的“ORACLE”。

如果你使用Qt设计器来创建一个main.cpp，它将不会包含我们的实例createConnections()函数。这也就是说在Qt设计器中预览正确的应用程序将不会运行，除非你实现了你自己的数据库连接函数。

请注意以上的代码上ODBC连接没有被命名，因此被作为默认连接。QSqlDatabase维护着通过addDatabase()这个静态函数返回的的连接指针。如果有移去一个连接，先调用QSqlDatabase::close()来关闭连接，然后通过静态函数QSqlDatabase::removeDatabase()来移除连接。

使用QSqlQuery执行SQL命令

QSqlQuery类提供了一个接口来执行SQL命令。它也提供相应的函数来定位SELECT查询的数据集和检索的不同的记录和字段值。

QSqlCursor类在下一节中讲述。它为我们提供了更高层的接口来实现SQL命令。QSqlCursor特别适用于在屏幕上显示的可视窗口部件。不熟悉SQL的程序员可略过这一节，直接去阅读“使用 QSqlCursor”来了解QSqlCursor类。

事务处理

如果下面的数据库引擎支持事务处理，则函数QSqlDriver::hasFeature（QSqlDriver::Transactions）将返回 真。你可以通过调用QSqlDatabase::transaction()来初始化一个事务处理。之后执行你想在该事务处理的工作。完了再执行QSqlDatabase::commit()来提交事务处理或QSqlDatabase::rollback()取消事务处理。

基本浏览

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include <qsqlquery.h>
    #include "../login.h"

    bool createConnections();

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

        if ( createConnections() ) {
            QSqlDatabase *oracledb = QSqlDatabase::database( "ORACLE" );
            // 从oracle数据库向ODBC（默认）数据库复制数据
            QSqlQuery target;
            QSqlQuery query( "SELECT id, name FROM people;", oracledb );
            if ( query.isActive() ) {
                while ( query.next() ) {
                    target.exec( "INSERT INTO people ( id, name ) VALUES ( " +
                                  query.value(0).toString() +
                                  ", '" + query.value(1).toString() +  "' );" );
                }
            }
        }

        return 0;
    }

来自sql/overview/basicbrowsing/main.cpp

在以上实例中我们加入了一个头文件：qsqlquery.h. 我们使用缺省数据库创建了一个查询：target，其初始值是空的。我们使用“ORACLE”数据库创建了第二个查询以存取数据。数据连接的设置在createConnections()中完成。

在创建了一个SELECT语句后，函数isActive()被用来检测该命令是否被成功执行。之后的next()被用来遍历整个数据集。value()函数返回字段中的值，其数据类型为QVariants。插入操作通过先前就已创建的target QSqlQuery来完成。

注意这个实例和这份文档中所有的实例使用的表的定义都在实例表中。

            int count = 0;
            if ( query.isActive() ) {
                while ( query.next() ) {
                    target.exec( "INSERT INTO people ( id, name ) VALUES ( " +
                                  query.value(0).toString() +
                                  ", '" + query.value(1).toString() +  "' );" );
                    if ( target.isActive() )
                        count += target.numRowsAffected();
                }
            }

来自sql/overview/basicbrowsing2/main.cpp

以上的代码来统计有多少记录被成功地插入数据库。如果操作，比如插入，失败则isActive()将返回假，如果记录行的数量不能被决定，比如查询失败，numRowsAffected()将返回-1。

基本数据处理

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

        int rows = 0;

        if ( createConnections() ) {
            QSqlQuery query( "INSERT INTO staff ( id, forename, surname, salary ) "
                         "VALUES ( 1155, 'Ginger', 'Davis', 50000 );" );
            if ( query.isActive() ) rows += query.numRowsAffected() ;

            query.exec( "UPDATE staff SET salary=60000 WHERE id=1155;" );
            if ( query.isActive() ) rows += query.numRowsAffected() ;

            query.exec( "DELETE FROM staff WHERE id=1155;" );
            if ( query.isActive() ) rows += query.numRowsAffected() ;
        }

        return ( rows == 3 ) ? 0 : 1;
    }

来自sql/overview/basicdatamanip/main.cpp

这个实例演示了直接的SQL DML（数据操作语言）命令。既然我们没有在QSqlQuery的构造函数中指明数据库则默认数据库将被使用。QSqlQuery也可以用来执行SQL DDL（数据定义语言）命令，诸如CREATE TABLE与CREATE INDEX。

定位数据集

一旦SELECT查询语句被成功执行，我们就可以存取与之对应的结果集。我们先前已使用了一个浏览函数：next()。它可以顺序扫描整个记录集。QSqlQuery同时也提供了first()、last()、next()和prev()。执行其中的任意一个函数后我们都可以通过isValid()来检验是否成功执行。

我们也可以通过seek()来定位至任意一条记录。第一条记录号为零。最后一条记录号为记录的总数减一。请注意并不时所有的数据都为SELECT查询提供记录总数这样的信息，此时size()将返回-1。

        if ( createConnections() ) {
            QSqlQuery query( "SELECT id, name FROM people ORDER BY name;" );
            if ( ! query.isActive() ) return 1; // 查询失败
            int i;
            i = query.size();               // 在这个实例中我们有9个记录，i==9。
            query.first();                  // 移动到第一条记录。
            i = query.at();                 // i==0
            query.last();                   // 移动到最后一条记录。
            i = query.at();                 // i==8
            query.seek( query.size() / 2 ); // 移动到中间那条记录。
            i = query.at();                 // i==4
        }

来自sql/overview/navigating/main.cpp

以上实例显示了一些定位函的用法。

注意不是所有的驱动程序都支持size()，我们可以通过以下的示例来获知驱动程序是否支持这一特征：

    QSqlDatabase* defaultDB = QSqlDatabase::database();
    if ( defaultDB->driver()->hasFeature( QSqlDriver::QuerySize ) ) {
        // QSqlQuery::size()支持
    }
    else {
        // QSqlQuery::size()不能被依赖
    }

当我们定位了一定记录录后我们往往希望取出这条记录的内容。

        if ( createConnections() ) {
            QSqlQuery query( "SELECT id, surname FROM staff;" );
            if ( query.isActive() ) {
                while ( query.next() ) {
                    qDebug( query.value(0).toString() + ": " +
                            query.value(1).toString() );
                }
            }
        }

来自sql/overview/retrieve1/main.cpp

注意如果你只是希望扫描整个记录集你只需不断地进行next()操作。

提示：函数lastQuery()返回最后一次的的Sql语句，有时你可能想检查一下最后那次操作是否是你所想象中的操作。

使用QSqlCursor

QSqlCursor类提供了一个更高层次的接口来浏览与编辑记录，它不需要你写SQL语句。

QSqlCursor几乎可以做QSqlQuery所能做的所有事情。有两点例外：由于其代表的是数据库中的一张表或视图。默认情况下 当你浏览记录时QSqlCursor对象总是取出记录中的所有字段。如果你只关心其中的一部分字段你需要进行一些配置，或者使用QSqlRecord::setGenerated()来屏蔽掉一些字段。当然你也可以使用QSqlQuery来完成这个功能。 如果表或者视图有其唯一索引你可以通过QSqlCursor来编辑记录。否则就只能通过QSqlQuery来编辑了。（请注意不是所有的数据库支持可编辑的视图。）

QSqlCursor一次只操作一条记录。无论是执行insert、update还是 delete，QSqlCursor都只是影响一条记录。当浏览记录集时无论何时都只有一条记录处于应用状态。也就是说QSqlCursor只维护了一条记录的“可编辑缓冲区”。“定位缓冲区”单独放置，因此当你浏览记录时该缓冲并不会受其影响。

当我们使用QSqlCursor对象前我们必须先创建与打开一个数据库连接。数据库连接在上面的连接数据库一节中已经被讲述。在实例中我们假设已经通过createConnections()创建了连接如同在QSqlDatabase实例描述的那样。

在随后的基于数据的窗口部件一节中我们将展示如何连接窗口部件至数据库，当我们了解了游标和基于数据的窗口部件后我们就可以讨论继承QSqlCursor。

QSqlCursor类需要qsqlcursor.h这个头文件。

检索记录

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include <qsqlcursor.h>
    #include "../login.h"

    bool createConnections();

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

        if ( createConnections() ) {
            QSqlCursor cur( "staff" ); // 指定表/视图名称
            cur.select(); // 我们将检索每一条记录
            while ( cur.next() ) {
                qDebug( cur.value( "id" ).toString() + ": " +
                        cur.value( "surname" ).toString() + " " +
                        cur.value( "salary" ).toString() );
            }
        }

        return 0;
    }

来自sql/overview/retrieve2/main.cpp

我们指定表或视图的名字来创建QSqlCursor对象，如果我们使用的不是缺省的数据库我们需要在QSqlCursor的构造函数中指明。

cur.select()将自动执行以下的Sql语句：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid FROM staff

然后我们通过cur.next()来遍历整个记录集。获取字段值的方法与QSqlQuery类似，不过它指明的是字段名而不是value()和 setValue()的数字索引。

排序和过滤记录

如果我们需要取记录子集，我们可以在select()函数中指定过滤条件，随后取到的结果集就都是满足条件的记录（过滤条件在SQL语言中由WHERE负责)）。

    cur.select( "id > 100" );

这个select()调用将执行SQL命令：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid
    FROM staff WHERE staff.id > 100

这将检索出id大于100的职员。

与过滤类似我们也可以对指定记录集进行排序。这个功能需要通过QSqlIndex对象来实现，它可以包括排序的字段的名称并且可以传递这个对象给select()调用。

    QSqlCursor cur( "staff" );
    QSqlIndex nameIndex = cur.index( "surname" );
    cur.select( nameIndex );

以上语句使用“surname”字段创建了一个QSqlIndex对象，当我们把该对象与select()函数集合起来以后，得到的记录集就是按staff.surname进行排序的，在索引对象中的每个字段通过ORDER BY组织起来，被执行的SQL语句如下所示：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid
    FROM staff ORDER BY staff.surname ASC

把过滤与排序结合起来的方法也是简单易懂的。

    cur.select( "surname LIKE 'A%'", nameIndex );

过滤字符串引起WHERE操作，QSqlIndex对象引起ORDER BY的操作，最后的命令如下：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid
    FROM staff WHERE staff.surname LIKE 'A%' ORDER BY staff.surname ASC

如果需要对不止一个字段进行排序，则索引对象创建时可包含多个字段。顺序还是倒序也可以通过QSqlIndex::setDescending()来指定，默认是升序排序。

            QSqlCursor cur( "staff" );
            QStringList fields = QStringList() << "surname" << "forename";
            QSqlIndex order = cur.index( fields );
            cur.select( order );
            while ( cur.next() ) {

来自sql/overview/order1/main.cpp

以上代码中我们通过一个字符串队列来存放不止一个字段，排序中它们都将被用到。然后我们基于这些字段创建了QSqlIndex对象，最后的select()操作将执行以下语句：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid
    FROM staff ORDER BY staff.surname ASC, staff.forename ASC

你可以在多重排序中加入过滤条件。

            QSqlCursor cur( "staff" );
            QStringList fields = QStringList() << "id" << "forename";
            QSqlIndex order = cur.index( fields );
            QSqlIndex filter = cur.index( "surname" );
            cur.setValue( "surname", "Bloggs" );
            cur.select( filter, order );
            while ( cur.next() ) {

来自sql/overview/order2/main.cpp

这将执行以下的SQL语句：

    SELECT staff.id, staff.forename, staff.surname, staff.salary, staff.statusid
    FROM staff WHERE staff.surname='Bloggs' ORDER BY staff.id ASC, staff.forename ASC

QSqlIndex对象“order”包含了两个字段：“id”和“forename”，它们被用来对记录集排序。QSqlIndex对象“filter”包含了一个字段：“surname”。当索引对象被作为过滤条件传给select()函数的时候，该对象中的字段名将被用来进行条件限制的列名，即fieldname=value。其中的value即是对应字段的限定值。我们可以用setValue()来确定每一个过滤字段的限定值。

提取数据

            QSqlCursor cur( "creditors" );
            QStringList orderFields = QStringList() << "surname" << "forename";
            QSqlIndex order = cur.index( orderFields );

            QStringList filterFields = QStringList() << "surname" << "city";
            QSqlIndex filter = cur.index( filterFields );
            cur.setValue( "surname", "Chirac" );
            cur.setValue( "city", "Paris" );

            cur.select( filter, order );

            while ( cur.next() ) {
                int id = cur.value( "id" ).toInt();
                QString name = cur.value( "forename" ).toString() + " " +
                               cur.value( "surname" ).toString();
                qDebug( QString::number( id ) + ": " + name );
            }

来自sql/overview/extract/main.cpp

在以上的实例中，我们为creditors表创建了一个游标,我们创建了两个QSqlIndex对象，第一个“order”创建于“orderFields”字串列，第二个“filter”创建于“filterFields”字串列，我们为过滤字段“surname”与“city”分别设定了条件值。现在我们调用select()，产生的SQL语句如下：

    SELECT creditors.city, creditors.surname, creditors.forename, creditors.id
    FROM creditors
    WHERE creditors.surname = 'Chirac' AND creditors.city = 'Paris'
    ORDER BY creditors.surname ASC, creditors.forename ASC
过滤字段用于WHERE语句，排序字段用于ORDER BY语句。

现在我们遍历整个符合条件的记录集（如果有的话），我们得到字段id、forename与surname的值并把它们传入我们需要处理的函数中去，在这个实例是一个简单的qDebug()调用。

处理记录

当一张表或视图有唯一索引的情况下，使用QSqlCursor可对表或视图的记录进行插入、更新与删除操作。否则只能用QSqlQuery来进行操作。（注意不是所有数据库都支持可编辑的视图。）

每一个游标有一个内部的编辑缓冲区用于编辑操作（insert、update和delete）。 编辑过程对于每种操作都是类似是：获取指向相关缓冲区的指针，调用setValue()来更新缓冲，调用insert()或update()或del()来执行所需要的操作。举例来说，当通过游标来插入记录时，你通过primeInsert()来获得一个指向编辑缓冲区的指针，调用setValue()来刷新缓冲区中每个字段的值，然后调用QSQlCursor::insert()把缓冲区的数据插入数据库。类似的，当刷新（或删除）一条记录的时候，缓冲区中的数据将刷新（或删除）至数据库。你调用任何一个游标定位的函数都不会影响缓冲区中的内容。请注意如果你调用setValue()传入的是一个单引号括起来的字符串，单引号将被忽略，因为单引号在SQL中有着特殊的意义。

primeInsert()、primeUpdate()和primeDelete()这样的方法都返回一个指向内部可编辑缓冲区的指针，每一种方法在返回前都会在可编辑缓冲区上执行一些不同的隐藏操作，默认情况下，QSqlCursor::primeInsert()清空缓冲区上所有字段的值。（请参考QSqlRecord::clearValues()）。QSqlCursor::primeUpdate()和QSqlCursor::primeDelete()在缓冲区中初始化当前游标处的各个字段值，这三个函数都是虚函数，因些你可以重新定义它们的行为。（比如重载primeInsert()以便对自动数值型的字段作出处理)。用户界面的数据感知组件会发出信号，比如primeInsert()，这样就可以进行连接，这些操作都会传递一个指针至合适的缓冲，因些子数据操作可能并不需要。相应信息请见继承QSqlCursor。参考Qt设计器的用户手册可了解与primeInsert()有关的信号。

当你调用了insert()、update()或del()之后，游标将无法定位至一条有效的记录并且实际上是不可用的。如果你还想继续浏览记录的话你必须调用select()以便从数据库读取更改后的记录。

插入记录

            QSqlCursor cur( "prices" );
            QStringList names = QStringList() <<
                "Screwdriver" << "Hammer" << "Wrench" << "Saw";
            int id = 20;
            for ( QStringList::Iterator name = names.begin();
                  name != names.end(); ++name ) {
                QSqlRecord *buffer = cur.primeInsert();
                buffer->setValue( "id", id );
                buffer->setValue( "name", *name );
                buffer->setValue( "price", 100.0 + (double)id );
                count += cur.insert();
                id++;
            }

来自sql/overview/insert/main.cpp

在以上的实例中我们为“prices”表创建了一个游标，然后我们创建了一个产品名列表并进入了一个循环。在循环中我们调用了游标的primeInsert()方法。该方法返回了一个指向QSqlRecord缓冲区的指针，该缓冲区的所有字段均置为空值。（请注意QSqlCursor::primeInsert()是虚函数，可以在继承类中定制，请参考QSqlCursor）。然后我们调用setValue()来设置每一个字段，最后调用insert()来实际插入记录。insert()返回值告诉我们有多少记录被实际插入。

我们通过primeInsert()调用来获得指向QSqlRecord对象的指针。QSqlRecord对象存储一条记录的数据以及相关的中间数据。在实际的应用程序中大多数与QSqlRecord有关的操作只是简单进行value()与setValue()的调用。就象上面以及下面的实例一样。

更新记录

            QSqlCursor cur( "prices" );
            cur.select( "id=202" );
            if ( cur.next() ) {
                QSqlRecord *buffer = cur.primeUpdate();
                double price = buffer->value( "price" ).toDouble();
                double newprice = price * 1.05;
                buffer->setValue( "price", newprice );
                cur.update();
            }

来自sql/overview/update/main.cpp

以上代码我们先在价格表上创建了一个游标。调用select()把需更新的记录选出来，通过next()进行定位。再调用primeUpdate()来获得一个指向QSqlRecord的指针，该缓冲区中的内容将被当前记录的数据所填充。我们获得当前字段的价格值再计算出一个新的价格。最后调用update()来更新记录，update()返回实际被更新的记录数。

如果有许多同样的更新需要执行，比如说更新一批价格，通过QSqlQuery来执行一条SQL语句的效率可能更高一些。

    QSqlQuery query( "UPDATE prices SET price = price * 1.05"  );

删除记录

            QSqlCursor cur( "prices" );
            cur.select( "id=999" );
            if ( cur.next() ) {
                cur.primeDelete();
                cur.del();

来自sql/overview/del/main.cpp

需要删除记录时，选择相应的记录然后定位，调用primeDelete()使缓冲区保存当前记录的值，然后调用QSqlCursor::del()来进行删除操作。

与更新操作一样，如果有多条类似的记录需要删除，使用一条SQL语句的效率可能更高一些。

    QSqlQuery query( "DELETE FROM prices WHERE id >= 2450 AND id <= 2500" );

基于数据的窗口部件

基于数据的窗口部件通过简便而强有力的方法把数据与用户界面结合起来。使用Qt设计器来创建与维护基于数据的窗口部件是一件方便的事情。本节为那些致力于完全用编程语言实现下述实例的开发人员们做出一个导引。请注意在Qt设计器的手册中“创建数据库应用程序”这一节所讲述的应用以及附带的实例。

基于数据的表

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include <qsqlcursor.h>
    #include <qdatatable.h>
    #include "../login.h"

    bool createConnections();

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

        if ( createConnections() ) {
            QSqlCursor staffCursor( "staff" );
            QDataTable *staffTable = new QDataTable( &staffCursor, TRUE );
            app.setMainWidget( staffTable );
            staffTable->refresh();
            staffTable->show();

            return app.exec();
        }

        return 0;
    }

来自sql/overview/table1/main.cpp

基于数据的表需要qdatatable.h和qsqlcursor.h这两个头文件。我们创建应用程序对象，然后调用createConnections()并创建游标。之后使用游标的指针创建QDataTable对象，设置autoPopulate标志为TRUE。再把QDataTable设为主窗口部件，调用 refresh()来获取数据，调用show()使其为用户可见。

autoPopulate标志告诉QDataTable是否根据当前游标创建列。该标志并不影响数据的的读入。数据的读入是由refresh()完成的。

            QSqlCursor staffCursor( "staff" );
            QDataTable *staffTable = new QDataTable( &staffCursor );

            app.setMainWidget( staffTable );

            staffTable->addColumn( "forename", "Forename" );
            staffTable->addColumn( "surname",  "Surname" );
            staffTable->addColumn( "salary",   "Annual Salary" );

            QStringList order = QStringList() << "surname" << "forename";
            staffTable->setSort( order );

            staffTable->refresh();
            staffTable->show();

来自sql/overview/table2/main.cpp

在以上代码中我们创建了一个空的QDataTable，然后人工指定将显示的列，每一列我们都可以指定显示的标题。

我们可以在表中对记录进行排序，或者也可以让设置游标让其完成排序工作。

当所有设置工作完成后就可以调用refresh()以便从数据库中获得数据，然后调用show()使其可见。

QDataTables只接收可见的记录集（依赖于驱动程序），这样做使得即使是一张大表也可以被迅速地显示同时消耗较少的内存。

创建基于数据的窗体

创建一个基于数据的窗体要比使用基于数据的窗口部件要麻烦很多，这是因为我们必须单独处理每一个数据列，以下所示的代码绝大部分都可以由Qt设计器所产生，相关资料可参考Qt设计器的用户手册。

显示记录

    #include <qapplication.h>
    #include <qdialog.h>
    #include <qlabel.h>
    #include <qlayout.h>
    #include <qlineedit.h>
    #include <qsqldatabase.h>
    #include <qsqlcursor.h>
    #include <qsqlform.h>
    #include "../login.h"

    bool createConnections();

    class FormDialog : public QDialog
    {
        public:
            FormDialog();
    };

    FormDialog::FormDialog()
    {
        QLabel *forenameLabel   = new QLabel( "Forename:", this );
        QLabel *forenameDisplay = new QLabel( this );
        QLabel *surnameLabel    = new QLabel( "Surname:", this );
        QLabel *surnameDisplay  = new QLabel( this );
        QLabel *salaryLabel     = new QLabel( "Salary:", this );
        QLineEdit *salaryEdit   = new QLineEdit( this );

        QGridLayout *grid = new QGridLayout( this );
        grid->addWidget( forenameLabel,     0, 0 );
        grid->addWidget( forenameDisplay,   0, 1 );
        grid->addWidget( surnameLabel,      1, 0 );
        grid->addWidget( surnameDisplay,    1, 1 );
        grid->addWidget( salaryLabel,       2, 0 );
        grid->addWidget( salaryEdit,        2, 1 );
        grid->activate();

        QSqlCursor staffCursor( "staff" );
        staffCursor.select();
        staffCursor.next();

        QSqlForm sqlForm( this );
        sqlForm.setRecord( staffCursor.primeUpdate() );
        sqlForm.insert( forenameDisplay, "forename" );
        sqlForm.insert( surnameDisplay, "surname" );
        sqlForm.insert( salaryEdit, "salary" );
        sqlForm.readFields();
    }

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

        if ( ! createConnections() ) return 1;

        FormDialog *formDialog = new FormDialog();
        formDialog->show();
        app.setMainWidget( formDialog );

        return app.exec();
    }

来自sql/overview/form1/main.cpp

我们需要引用各组件所需要的头文件，我们还加入qsqldatabase.h和qsqlcursor.h，同时还有qsqlform.h。

本窗体是以对话框形式出现的，窗体类FormDialog继承于QDialog。我们使用了一个QLineEdit来显示薪水同时也允许用户对其进行修改。所有的组件显示在一个网格中。

我们为staff表创建了一个游标。让它从数据库取出所有的记录并定位至第一条记录。

现在我们创建了一个QSqlForm对象并把QSqlForm的记录缓冲区与游标的更新缓冲区对应起来。对于每个我们希望其数据感知的组件都把与相应的字段名结合进QSqlForm，最后我们调用readFields()把游标缓冲区中的数据刷新至关联窗口部件。

在数据窗体中显示记录

QDataView是一个可以拥有只读QSqlForm。与QSqlForm类似它也提供了一个槽refresh( QSqlRecord * )，因此它可以比较容易地与QDataTable连接在一起用来显示数据：

    connect( myDataTable, SIGNAL( currentChanged( QSqlRecord* ) ),
             myDataView, SLOT( refresh( QSqlRecord* ) ) );

编辑记录

这个实例与上述的比较相似，所以我们讨论不同部分。

    class FormDialog : public QDialog
    {
        Q_OBJECT
        public:
            FormDialog();
            ~FormDialog();
        public slots:
            void save();
        private:
            QSqlCursor staffCursor;
            QSqlForm *sqlForm;
            QSqlIndex idIndex;
    };

来自sql/overview/form2/main.h

这个save槽将被用于一个按纽以便让用户进行数据刷新的确认。 我们也保存QSqlCursor和QSqlForm的指针，因为它们将需要在构造函数之外被访问。

        staffCursor.setTrimmed( "forename", TRUE );
        staffCursor.setTrimmed( "surname",  TRUE );

我们在文本字段上调用setTrimmed()以便获取到数据的时候自动消除右面的空格。

我们可以根据需要设置一些属性，比如对齐方式与有效性检查。相对应的函数为QLineEdit::setAlignment与QLineEdit::setValidator。

        QLineEdit   *forenameEdit  = new QLineEdit( this );

        QPushButton *saveButton    = new QPushButton( "&Save", this );
        connect( saveButton, SIGNAL(clicked()), this, SLOT(save()) );

FormDialog的构造函数类似于先前的实例。我们更改forename与surname窗口部件的类型至QLineEdits以便使其内容可编辑。然后又加入QPushButton以便用户点击确认保存他们的更新。

        grid->addWidget( saveButton,    3, 0 );

我们在网格中添加了一行来容纳这个save按钮。

        idIndex = staffCursor.index( "id" );
        staffCursor.select( idIndex );
        staffCursor.first();

我们创建了一个QSqlIndex对象然后使用索引执行一个select()操作。然后定位至第一条记录。

        sqlForm = new QSqlForm( this );
        sqlForm->setRecord( staffCursor.primeUpdate() );

我们创建了一个新的QSqlForm对象并把它的缓冲区与游标的更新缓冲区关联起来。

        sqlForm->insert( forenameEdit, "forename" );
        sqlForm->insert( surnameEdit, "surname" );
        sqlForm->insert( salaryEdit, "salary" );
        sqlForm->readFields();

现在我们把缓冲区的各个字段与QLineEdit控件关联起来。（在先前的实例中我们把它与游标的各个字段相关联）。函数readFields()使得各控件获得数据。

    FormDialog::~FormDialog()
    {

    }

在析构函数中我们无需关注各控件或QSqlForm的处理，由于它们都是窗体的孩子，因此将被Qt在适当的时候清除。

    void FormDialog::save()
    {
        sqlForm->writeFields();
        staffCursor.update();
        staffCursor.select( idIndex );
        staffCursor.first();
    }

最后我们加入了保存这一个功能，当用户点击保存按纽时该函数将被执行。最后我们调用writeFields()使得数据回写入QSqlRecord缓冲区。然后我们利用游标的update()函数来更新数据。此后游标不再可用，因此使用QSqlIndex再次调用select()来获得数据并定位至第一条记录。

QDataBrowser和QDataView这两个窗口部件提供了以上这些功能的许多函数。QDataBrowser提供了一个数据标识来指明是否允许编辑与记录浏览。QDataView提供了一个数据的只读形式。相关资料可查看类文档或Qt设计器的手册。

链接到sql/overview/form2/main.cpp

自定义编辑器窗口部件

QSqlForm使用了QSqlPropertyMap来控制数据在组件与数据库字段间的传输。自定义窗口部件同样可以使用属性映射，其中包含了如何转递数据的信息。

本实例基于前述的form2实例。因此这里只讲述不同部分，完整源码在sql/overview/custom1/main.h和sql/overview/custom1/main.cpp

    class CustomEdit : public QLineEdit
    {
        Q_OBJECT
        Q_PROPERTY( QString upperLine READ upperLine WRITE setUpperLine )
        public:
            CustomEdit( QWidget *parent=0, const char *name=0 );
            QString upperLine() const;
            void setUpperLine( const QString &line );
        public slots:
            void changed( const QString &line );
        private:
            QString upperLineText;
    };

我们从QLineEdit这儿继承了一个类，加入了属性：upperLineText，以便其中存放字符串的大写。加入一个changed槽。

            QSqlPropertyMap *propMap;

由于我们将使用属性映射因此我们把属性映射的指针与FormDialog的私有数据关联起来。

    CustomEdit::CustomEdit( QWidget *parent, const char *name ) :
        QLineEdit( parent, name )
    {
        connect( this, SIGNAL(textChanged(const QString &)),
                 this, SLOT(changed(const QString &)) );
    }

在CustomEdit的构造函数中，我们执行了QLineEdit的构造函数，然后在textChanged信号与changed槽之间建立了连接。

    void CustomEdit::changed( const QString &line )
    {
        setUpperLine( line );
    }

changed()槽调用setUpperLine()这个函数。

    void CustomEdit::setUpperLine( const QString &line )
    {
        upperLineText = line.upper();
        setText( upperLineText );
    }

setUpperLine()函数将对文本进行处理以获得一份大写后的拷贝并把它设置成窗口部件的数据。

我们的CustomEdit类确保输入的数据始终是大写并提供了一个属性以便在属性映射中使用，使得CustomEdit的实例可与数据库字段相连。

        CustomEdit  *forenameEdit   = new CustomEdit( this );

        CustomEdit  *surnameEdit    = new CustomEdit( this );

我们使用先前用过的FormDialog，只是这一次我们把原先使用的QLineEdit窗口部件替换成自己的CustomEdit窗口部件。

在网格中的分布以及游标的设置与先前相同。

        propMap = new QSqlPropertyMap;
        propMap->insert( forenameEdit->className(), "upperLine" );

我们在堆中建立一个新的属性映射，注册CustomEdit类并把upperLine属性关联进属性映射。

        sqlForm = new QSqlForm( this );
        sqlForm->setRecord( staffCursor->primeUpdate() );
        sqlForm->installPropertyMap( propMap );

最后的变化是把属性映射装入QSqlForm，这样可把属性映射的内存加载入QSqlForm，由于QSqlForm属于FormDialog，因此Qt将在适当的时候删除它们。

这个实例与前述实例其本相同，例外的是forename与surname字段由于使用了自定义的CustomEdit窗口部件因此它们都将被大写。

为表格自定义编辑器窗口部件

我们必须重新实现QSqlEditorFactory以便使用自定义编辑器窗口部件。在下面的实例中我们将以QComboBox为基类创建自定义窗口部件件并定重载QSqlEditorFactory以便在QDataTable使用自定义窗口部件。

    class StatusPicker : public QComboBox
    {
        Q_OBJECT
        Q_PROPERTY( int statusid READ statusId WRITE setStatusId )
        public:
            StatusPicker( QWidget *parent=0, const char *name=0 );
            int statusId() const;
            void setStatusId( int id );
        private:
            QMap< int, int > index2id;
    };

来自sql/overview/table3/main.h

我们创建了一个属性：statusid，定义了它的读取与写入的方法，由于statusid并不与combobox的索引对应因此我们创建了一个QMap以映射combobox的索引与statusid的关系。

    class CustomSqlEditorFactory : public QSqlEditorFactory
    {
        Q_OBJECT
        public:
            QWidget *createEditor( QWidget *parent, const QSqlField *field );
    };

我们同样需要继承QSqlEditorFactory，声明一个createEditor()函数，该函数是我们唯一需要重新实现的。

    StatusPicker::StatusPicker( QWidget *parent, const char *name )
        : QComboBox( parent, name )
    {
        QSqlCursor cur( "status" );
        cur.select( cur.index( "name" ) );

        int i = 0;
        while ( cur.next() ) {
            insertItem( cur.value( "name" ).toString(), i );
            index2id[i] = cur.value( "id" ).toInt();
            i++;
        }

来自sql/overview/table3/main.cpp

在StatusPicker的构造函数中我们创建了一个游标，遍历整个记录集把每一个name插入combobox，同时通过QMap型的变量index2id把combobox的索引与id列的值关联起来。

    int StatusPicker::statusId() const
    {
        return index2id[ currentItem() ];
    }

statusid的读取函数只是简单地利用combobox的索引从index2id中取值。

    void StatusPicker::setStatusId( int statusid )
    {
        QMap<int,int>::Iterator it;
        for ( it = index2id.begin(); it != index2id.end(); ++it ) {
            if ( it.data() == statusid ) {
                setCurrentItem( it.key() );
                break;
            }
        }
    }

statusId()函数实现statusid的定入方法。我们创建了一个迭代器遍历整个QMap，取出其中的数据如果有与statusid相等的就把combobox的索引设成statusid对应的索引，然后离开循环。

当用户在QDataTable中编辑status字段时，就有一个combobox出现以便用户选值。为了不编辑的时候在表中显示status的名称我们需要继承QDataTable并重新实现paintField()函数。

    class CustomTable : public QDataTable
    {
        Q_OBJECT
    public:
        CustomTable(
                QSqlCursor *cursor, bool autoPopulate = FALSE,
                QWidget * parent = 0, const char * name = 0 ) :
            QDataTable( cursor, autoPopulate, parent, name ) {}
        void paintField(
                QPainter * p, const QSqlField* field, const QRect & cr, bool );

    };

来自sql/overview/table4/main.h

我们只需简单地调用QDataTable的原始构造函数而不需做任何改动。同时还声明了paintField函数。

    void CustomTable::paintField( QPainter * p, const QSqlField* field,
                                  const QRect & cr, bool b)
    {
        if ( !field )
            return;
        if ( field->name() == "statusid" ) {
            QSqlQuery query( "SELECT name FROM status WHERE id=" +
                         field->value().toString() );
            QString text;
            if ( query.next() ) {
                text = query.value( 0 ).toString();
            }
            p->drawText( 2,2, cr.width()-4, cr.height()-4, fieldAlignment( field ), text );
        }
        else {
            QDataTable::paintField( p, field, cr, b) ;
        }

来自sql/overview/table4/main.cpp

paintField函数的代码基于QDataTable中的源码。我们需要做三个改动，首先加入一个if语句：field->name() == "statusid"，此情况下使用QSqlQuery获得数据。 其次为其他字段调用基类函数。最后的变化是在主函数staffTable由QDataTable改为自定义的CustomTable。

继承QSqlCursor

    #include <qapplication.h>
    #include <qsqldatabase.h>
    #include <qsqlcursor.h>
    #include <qdatatable.h>
    #include "../login.h"

    bool createConnections();

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

        if ( createConnections() ) {
            QSqlCursor invoiceItemCursor( "invoiceitem" );

            QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

            app.setMainWidget( invoiceItemTable );

            invoiceItemTable->addColumn( "pricesid", "PriceID" );
            invoiceItemTable->addColumn( "quantity", "Quantity" );
            invoiceItemTable->addColumn( "paiddate", "Paid" );

            invoiceItemTable->refresh();
            invoiceItemTable->show();

            return app.exec();
        }

        return 1;
    }

来自sql/overview/subclass1/main.cpp

这个实例与前述的table1实例很相似。我们创建了一个游标，在QDataTable中加入字段与对应的标题。调用refresh()获取数据，再执行show()来显示组件。

不幸的是这个实例并不完整，在设置时我们需要输入每一个字段，这是一个单调的工作。如果在显示价格代码的时候显示产品名牌可能会更合适一些。既然我们知道产品的价格与数量我们还可以显示产品的花费。最后如果能填入默认值（或者是一些主键）将更加实用 。

    class InvoiceItemCursor : public QSqlCursor
    {
        public:
            InvoiceItemCursor();
    };

来自sql/overview/subclass2/main.h

我们创建了一个单独的头文件并继承了QSqlCursor。

    InvoiceItemCursor::InvoiceItemCursor() :
        QSqlCursor( "invoiceitem" )
    {
        // 空操作
    }

来自sql/overview/subclass2/main.cpp

在继承类的构造函数中我们仅仅调用了QSqlCursor的构造函数。

            InvoiceItemCursor invoiceItemCursor;

当我们需要在invoiceitem表上使用的游标时我们可以创建InvoiceItemCursor而还是常用的QSqlCursor。

我们仍需要显示产品的名称而不是价格代码。

        protected:
            QVariant calculateField( const QString & name );

来自sql/overview/subclass3/main.h

在头文件中的改动很小：我们简单地加入calculateField()以便重新实现。

    InvoiceItemCursor::InvoiceItemCursor() :
        QSqlCursor( "invoiceitem" )
    {
        QSqlFieldInfo productName( "productname", QVariant::String );
        append( productName );
        setCalculated( productName.name(), TRUE );
    }

    QVariant InvoiceItemCursor::calculateField( const QString & name )
    {
        if ( name == "productname" ) {
            QSqlQuery query( "SELECT name FROM prices WHERE id=" +
                         field( "pricesid" )->value().toString() + ";" );
            if ( query.next() )
                return query.value( 0 );
        }

        return QVariant( QString::null );
    }

来自sql/overview/subclass3/main.cpp

我们已更改了InvoiceItemCursor的构造函数，我们创建了一个QSqlField的对象productname，然后把它加入 InvoiceItemCursor的字段集。我们在productname上调用setCalculated()使其成为一个计算字段。在setCalculated()中第一个参数是字段名，第二个参数是一个布尔参数，当其为TRUE时意味着calculateField()必须被调用以获得字段的值。

            invoiceItemTable->addColumn( "productname", "Product" );

我们调用addColumn()来加入一个字段并指定显示名称。

我们必须定义自己的calculateField()函数。在我们的实例数据库中，invoiceitem表内价格代码（pricesid）是价格表的一个外键，我们使用pricesid在价格表中执行Sql语句以获得产品名称。

现在我们可以扩展实例，包括进一个计算字段并执行真正的计算工作。

头文件sql/overview/subclass4/main.h与前述实例一样。但构造函数与calculateField()函数需要一些简单扩展。我们来逐行地看一下。

    InvoiceItemCursor::InvoiceItemCursor() :
        QSqlCursor( "invoiceitem" )
    {
        QSqlFieldInfo productName( "productname", QVariant::String );
        append( productName );
        setCalculated( productName.name(), TRUE );

        QSqlFieldInfo productPrice( "price", QVariant::Double );
        append( productPrice );
        setCalculated( productPrice.name(), TRUE );

        QSqlFieldInfo productCost( "cost", QVariant::Double );
        append( productCost );
        setCalculated( productCost.name(), TRUE );
    }

来自sql/overview/subclass4/main.cpp

我们创建了两个额外的字段：价格price与花费cost。把它们加入游标中字段集，此两个都通过调用setCalculated()被注册成为计算字段。

    QVariant InvoiceItemCursor::calculateField( const QString & name )
    {

        if ( name == "productname" ) {
            QSqlQuery query( "SELECT name FROM prices WHERE id=" +
                         field( "pricesid" )->value().toString() + ";" );
            if ( query.next() )
                return query.value( 0 );
        }
        else if ( name == "price" ) {
            QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                         field( "pricesid" )->value().toString() + ";" );
            if ( query.next() )
                return query.value( 0 );
        }
        else if ( name == "cost" ) {
            QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                         field( "pricesid" )->value().toString() + ";" );
            if ( query.next() )
                return QVariant( query.value( 0 ).toDouble() *
                                 value( "quantity").toDouble() );
        }

        return QVariant( QString::null );
    }

来自sql/overview/subclass4/main.cpp

calculateField()函数的内容进行了一些增加，因为我们必须计算三个字段。productname与price字段是通过价格代码pricesid被选出来的。cost字段是计算出来的：价格与数量的乘积。请注意cost字段是以QVariant类型返回的，这是calculateField()函数所要求的。

我们使用了三个独立的查询而不是一个，这使得应用程序更为真实就好象它们是从三个不同的表或视图中取得的一样。

最后一个特征是当用户插入一条新记录时我们为它加入默认值。

            QSqlRecord *primeInsert();

来自sql/overview/subclass5/main.h

我们申明了自已的primeInsert()函数以便重新实现。

构造函数与calculateField()函数没有变化。

    QSqlRecord *InvoiceItemCursor::primeInsert()
    {
        QSqlRecord *buffer = editBuffer();
        QSqlQuery query( "SELECT NEXTVAL( 'invoiceitem_seq' );" );
        if ( query.next() )
            buffer->setValue( "id", query.value( 0 ) );
        buffer->setValue( "paiddate", QDate::currentDate() );
        buffer->setValue( "quantity", 1 );

        return buffer;
    }

来自sql/overview/subclass5/main.cpp

我们取得了一个指向可编辑缓冲区的指针以便游标用来插入与更新。字段id是一个用invoiceitem_seq产生的唯一整形，字段paiddate则默认为今天的日期。数量默认为1。最后我们返回一个指向该缓冲区的指针。余下的代码与前述实例没有区别。

实例表

所使用的实例表可以用以下标准SQL语句产生，你可能需要改变数据库名称以便与你所使用的匹配。

create table people (id integer primary key, name char(40))

create table staff (id integer primary key, forename char(40),
                    surname char(40), salary float, statusid integer)

create table status (id integer primary key, name char(30))

create table creditors (id integer primary key, forename char(40),
                        surname char(40), city char(30))

create table prices (id integer primary key, name char(40), price float)

create table invoiceitem (id integer primary key,
                          pricesid integer, quantity integer,
                          paiddate date)

在以上的calculateField()实例中使用了一个顺序（sequence），请注意并不是所有的数据库都支持它。

create sequence invoiceitem_seq

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


表格模块

这个模块是Qt企业版的一部分。

表格模块提供了一个灵活的和可编辑的表格部件，QTable。对很多应用程序来说，QTable能直接地、简单地拿来使用， 并且QTable提供了一个可编辑单元的栅格。QTable能够通过一个直接的方式被派生，并能提供很大的稀疏的表格，例如，1,000,000乘1,000,000个单元格。

Screenshot of QTable

表格模块提供了以下这些类：

  • QTable自身是一个抽象的部件，用在当你需要提供给你的用户显示和编辑表列数据，诸如电子数据表或数据库数据。
  • QTableItem对象用在含有数据的QTable中，每一个表项含有一个单元的内容。
  • QComboTableItem类为QTable提供了高效内存的combobox项。
  • QCheckTableItem类为QTable提供了高效内存的checkbox项。
  • QTableSelection提供了访问一个QTable中所选择的单元。
  • QHeader提供了访问表格的水平标题（列标题）和垂直标题（行标题）。

详情请查看相关类文档和参照Qt表格实例的应用示范。

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


工作区模块

工作区模块提供了一个工作区窗口，这个窗口包含为多文档界面（MDI）修饰过的文档窗口。

它是在一个单独的类QWorkspace中实现的。

详情请查阅类文档。

Copyright © 2002 TrolltechTrademarks
译者：dirtfei
Qt version 3.0.5


XML Module

This module is part of the Qt Enterprise Edition.

  • Overview of the XML architecture in Qt
  • The Qt SAX2 classes
    • Introduction to SAX2
    • Features
    • Namespace support via features
      • Summary
    • Properties
    • Further reading
  • The Qt DOM classes
    • Introduction to DOM
    • Further reading
  • An introduction to namespaces
    • Conventions used in Qt XML documentation

Overview of the XML architecture in Qt

The XML module provides a well-formed XML parser using the SAX2 (Simple API for XML) interface plus an implementation of the DOM Level 2 (Document Object Model).

SAX is an event-based standard interface for XML parsers. The Qt interface follows the design of the SAX2 Java implementation. Its naming scheme was adapted to fit the Qt naming conventions. Details on SAX2 can be found at http://www.megginson.com/SAX/.

Support for SAX2 filters and the reader factory are under development. Furthermore the Qt implementation does not include the SAX1 compatibility classes present in the Java interface.

For an introduction to Qt's SAX2 classes see "The Qt SAX2 classes". A code example is discussed in the "tagreader walkthrough".

DOM Level 2 is a W3C Recommendation for XML interfaces that maps the constituents of an XML document to a tree structure. Details and the specification of DOM Level 2 can be found at http://www.w3.org/DOM/. More information about the DOM classes in Qt is provided in the Qt DOM classes.

Qt provides the following XML related classes:

  • QDomAttr -- Represents one attribute of a QDomElement
  • QDomCDATASection -- Represents an XML CDATA section
  • QDomCharacterData -- Represents a generic string in the DOM
  • QDomComment -- Represents an XML comment
  • QDomDocument -- The representation of an XML document
  • QDomDocumentFragment -- Tree of QDomNodes which is usually not a complete QDomDocument
  • QDomDocumentType -- The representation of the DTD in the document tree
  • QDomElement -- Represents one element in the DOM tree
  • QDomEntity -- Represents an XML entity
  • QDomEntityReference -- Represents an XML entity reference
  • QDomImplementation -- Information about the features of the DOM implementation
  • QDomNamedNodeMap -- Collection of nodes that can be accessed by name
  • QDomNode -- The base class for all nodes of the DOM tree
  • QDomNodeList -- List of QDomNode objects
  • QDomNotation -- Represents an XML notation
  • QDomProcessingInstruction -- Represents an XML processing instruction
  • QDomText -- Represents textual data in the parsed XML document
  • QXmlAttributes -- XML attributes
  • QXmlContentHandler -- Interface to report logical content of XML data
  • QXmlDeclHandler -- Interface to report declaration content of XML data
  • QXmlDefaultHandler -- Default implementation of all XML handler classes
  • QXmlDTDHandler -- Interface to report DTD content of XML data
  • QXmlEntityResolver -- Interface to resolve extern entities contained in XML data
  • QXmlErrorHandler -- Interface to report errors in XML data
  • QXmlInputSource -- The input data for the QXmlReader subclasses
  • QXmlLexicalHandler -- Interface to report lexical content of XML data
  • QXmlLocator -- The XML handler classes with information about the actual parsing position
  • QXmlNamespaceSupport -- Helper class for XML readers which want to include namespace support
  • QXmlParseException -- Used to report errors with the QXmlErrorHandler interface
  • QXmlReader -- Interface for XML readers (i.e. for SAX2 parsers)
  • QXmlSimpleReader -- Implementation of a simple XML reader (a SAX2 parser)

The Qt SAX2 classes

Introduction to SAX2

The SAX2 interface is an event-driven mechanism to provide the user with document information. "Event" in this context has nothing to do with the term "event" you probably know from windowing systems; it means that the parser reports certain document information while parsing the document. These reported information is referred to as "event".

To make it less abstract consider the following example:

<quote>To make it less abstract consider the following example:</quote>

Whilst reading (a SAX2 parser is usually referred to as "reader") the above document three events would be triggered:

  1. A start tag occurs (<quote>).
  2. Character data (i.e. text) is found.
  3. An end tag is parsed (</quote>).

Each time such an event occurs the parser reports it so that a suitable event handling routine can be invoked.

Whilst this is a fast and simple approach to read XML documents manipulation is difficult because data are not stored, simply handled and discarded serially. This is when the DOM interface comes handy.

The Qt XML module provides an abstract class, QXmlReader, that defines the interface for potential SAX2 readers. At the moment Qt ships with one reader implementation, QXmlSimpleReader.

The reader reports parsing events through special handler classes. In Qt the following ones are available:

  • QXmlContentHandler reports events related to the content of a document (e.g. the start tag or characters).
  • QXmlDTDHandler reports events related to the DTD (e.g. notation declarations).
  • QXmlErrorHandler reports errors or warnings that occurred during parsing.
  • QXmlEntityResolver reports external entities during parsing and allows the user to resolve external entities him- or herself instead of leaving it to the reader.
  • QXmlDeclHandler reports further DTD related events (e.g. attribute declarations). Usually users are not interested in them, but under certain circumstances this class comes handy.
  • QXmlLexicalHandler reports events related to the lexical structure of the document (the beginning of the DTD, comments etc.). Occasionally this might be useful.

These classes are abstract classes describing the interface. The QXmlDefaultHandler class provides a "do nothing" default implementation for all of them. Therefore users need to overload only the QXmlDefaultHandler functions they are interested in.

To read input XML data a special class QXmlInputSource is used.

Apart from the already mentioned ones the following SAX2 support classes provide the user with useful functionality:

  • QXmlAttributes is used to pass attributes in a start element event.
  • QXmlLocator is used to obtain the actual parsing position of an event.
  • QXmlNamespaceSupport is used to easily implement namespace support for a reader. Note that namespaces do not change the parsing behavior. They are only reported through the handler.

Features

The behaviour of an XML reader depends on whether it supports certain optional features or not. As an example a reader can have the feature "report attributes used for namespace declarations and prefixes along with the local name of a tag". Like every other feature this has a unique name represented by a URI: it is called http://xml.org/sax/features/namespace-prefixes.

The Qt SAX2 implementation allows you to find out whether the reader has this ability using QXmlReader::hasFeature(). If the return value is TRUE it is possible to turn the relevant feature on and off. To do this use QXmlReader::setFeature(). Whether a supported feature is on or off (TRUE or FALSE) can be queried using QXmlReader::feature().

Consider the example

<document xmlns:book = 'http://trolltech.com/fnord/book/'
          xmlns      = 'http://trolltech.com/fnord/' >
A reader not supporting the http://xml.org/sax/features/namespace-prefixes feature would clearly report the element name document but not its attributes xmlns:book and xmlns with their values. A reader with the feature http://xml.org/sax/features/namespace-prefixes reports the namespace attributes if QXmlReader::feature() is TRUE and disregards them if the feature is FALSE.

Other features include http://xml.org/sax/features/namespace (namespace processing, implies http://xml.org/sax/features/namespace-prefixes) or http://xml.org/sax/features/validation (the ability to report validation errors).

Whilst SAX2 leaves it to the user to define and implement whatever features are required, support for http://xml.org/sax/features/namespace (and thus http://xml.org/sax/features/namespace-prefixes) is mandantory. Accordingly QXmlSimpleReader, the implementation of QXmlReader that comes with the Qt XML module, supports both of them, and therefore can do namespace processing.

Being a non-validating parser QXmlSimpleReader does not support http://xml.org/sax/features/validation and other features.

Namespace support via features

As we have seen in the previous section we can configure the behavior of the reader when it comes to namespace processing. This is done by setting and unsetting the http://xml.org/sax/features/namespaces and http://xml.org/sax/features/namespace-prefixes features.

They influence the reporting behavior in the following way:

  1. Namespace prefixes and local parts of elements and attributes can be reported.
  2. The qualified names of elements and attributes are reported.
  3. QXmlContentHandler::startPrefixMapping() and QXmlContentHandler::endPrefixMapping() are called by the reader.
  4. Attributes that declare namespaces (i.e. the attribute xmlns and attributes starting with xmlns: ) are reported.

Consider the following element:

<author xmlns:fnord = 'http://trolltech.com/fnord/'
             title="Ms"
             fnord:title="Goddess"
             name="Eris Kallisti"/>

With http://xml.org/sax/features/namespace-prefixes set to TRUE the reader will report four attributes, with the namespace-prefixes feature set to FALSE only three: The xmlns:fnord attribute defining a namespace is then "unvisible" for the reader.

The http://xml.org/sax/features/namespaces feature on the other hand is responsible for reporting local names, namespace prefixes and -URIs. With http://xml.org/sax/features/namespaces set to TRUE the parser will report title as the local name of fnord:title attribute, fnord being the namespace prefix and http://trolltech.com/fnord/ as the namespace URI. When http://xml.org/sax/features/namespaces is FALSE none of them are reported.

In the current implementation the Qt XML classes follow the definition that the prefix xmlns itself isn't associated with any namespace at all (see http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-using). Therefore even with http://xml.org/sax/features/namespaces and http://xml.org/sax/features/namespace-prefixes both set to TRUE the reader won't return either a local name, a namespace prefix or a namespace URI for xmlns:fnord.

This might be changed in the future following the W3C suggestion http://www.w3.org/2000/xmlns/ to associate xmlns with the namespace http://www.w3.org/2000/xmlns.

As the SAX2 standard suggests QXmlSimpleReader by default has http://xml.org/sax/features/namespaces set to TRUE and http://xml.org/sax/features/namespace-prefixes set to FALSE. When changing this behavior using QXmlSimpleReader::setFeature() note that the combination of both features set to FALSE is illegal.

For a practical demonstration of how the two features affect the output of the reader run the tagreader with features example.

Summary

QXmlSimpleReader implements the following behavior:

(namespaces, namespace-prefixes) | Namespace prefix and local part | Qualified names | Prefix mapping | xmlns attributes
(TRUE, FALSE) | Yes | Yes* | Yes | No
(TRUE, TRUE) | Yes | Yes | Yes | Yes
(FALSE, TRUE) | No* | Yes | No* | Yes
(FALSE, FALSE) | Illegal

For the entries marked with a "*", SAX does not require a particuliar behavior.

Properties

Properties are a more general concept. They also have a unique name, represented as an URI, but their value is void*. Thus nearly everything can be used as a property value. This concept involves some danger, though: there are no means to ensure type-safety; the user must take care that he or she passes the correct type. Properties are useful if a reader supports special handler classes.

The URIs used for features and properties often look like URLs, e.g. http://xml.org/sax/features/namespace. This does not mean that whatsoever data is required at this address. It is simply a way to define unique names.

Everybody can define and use new SAX2 properties for his or her readers. Property support is however not required.

To set or query properties the following functions are provided: QXmlReader::setProperty(), QXmlReader::property() and QXmlReader::hasProperty().

Further reading

For a practical example on how to use the Qt SAX2 classes see the tagreader walkthrough.

More information about XML (e.g. namespaces) can be found in the introduction to the Qt XML module.

The Qt DOM classes

Introduction to DOM

DOM provides an interface to access and change the content and structure of an XML file. It makes a hierarchical view of the document (tree) available with the root element of the XML file serving as its root. Thus -- in contrast to the SAX2 interface -- an object model of the document is resident in memory after parsing which makes manipulation easy.

In the Qt implementation of the DOM all nodes in the document tree are subclasses of QDomNode. The document itself is represented as a QDomDocument object.

Here are the available node classes and their potential children classes:

  • QDomDocument: Possible children are
    • QDomElement (at most one)
    • QDomProcessingInstruction
    • QDomComment
    • QDomDocumentType
  • QDomDocumentFragment: Possible children are
    • QDomElement
    • QDomProcessingInstruction
    • QDomComment
    • QDomText
    • QDomCDATASection
    • QDomEntityReference
  • QDomDocumentType: No children
  • QDomEntityReference: Possible children are
    • QDomElement
    • QDomProcessingInstruction
    • QDomComment
    • QDomText
    • QDomCDATASection
    • QDomEntityReference
  • QDomElement: Possible children are
    • QDomElement
    • QDomText
    • QDomComment
    • QDomProcessingInstruction
    • QDomCDATASection
    • QDomEntityReference
  • QDomAttr: Possible children are
    • QDomText
    • QDomEntityReference
  • QDomProcessingInstruction: No children
  • QDomComment: No children
  • QDomText: No children
  • QDomCDATASection: No children
  • QDomEntity: Possible children are
    • QDomElement
    • QDomProcessingInstruction
    • QDomComment
    • QDomText
    • QDomCDATASection
    • QDomEntityReference
  • QDomNotation: No children

With QDomNodeList and QDomNamedNodeMap two collection classes are provided: QDomNodeList is a list of nodes whereas QDomNamedNodeMap is used to handle unordered sets of nodes (often used for attributes).

The QDomImplementation class allows the user to query features of the DOM implementation.

Further reading

To get started please refer to the QDomDocument documentation that describes basic usage.

An introduction to namespaces

Parts of the Qt XML module documentation assume that you are familiar with XML namespaces. Here we present a brief introduction; skip to Qt XML documentation conventions if you know this material.

Namespaces are a concept introduced into XML to allow a more modular design. With their help data processing software can easily resolve naming conflicts in XML documents.

Consider the following example:

<document>
<book>
  <title>Practical XML</title>
  <author title="Ms" name="Eris Kallisti"/>
  <chapter>
    <title>A Namespace Called fnord</title>
  </chapter>
</book>
</document>

Here we find three different uses of the name title. If you wish to process this document you will encounter problems because each of the titles should be displayed in a different manner -- even though they have the same name.

The solution would be to have some means of identifying the first occurrence of title as the title of a book, i.e. to use the title element of a book namespace to distinguish it from for example the chapter title, e.g.:

<book:title>Practical XML</book:title>

book in this case is a prefix denoting the namespace.

Before we can apply a namespace to element or attribute names we must declare it.

Namespaces are URIs like http://trolltech.com/fnord/book/. This does not mean that data must be available at this address; the URI is simply used to provide a unique name.

We declare namespaces in the same way as attributes; strictly speaking they are attributes. To make for example http://trolltech.com/fnord/ the document's default XML namespace xmlns we write

xmlns="http://trolltech.com/fnord/"

To distinguish the http://trolltech.com/fnord/book/ namespace from the default, we have to supply it with a prefix:

xmlns:book="http://trolltech.com/fnord/book/"

A namespace that is declared like this can be applied to element and attribute names by prepending the appropriate prefix and a ":" delimiter. We have already seen this with the book:title element.

Element names without a prefix belong to the default namespace. This rule does not apply to attributes: an attribute without a prefix does not belong to any of the declared XML namespaces at all. Attributes always belong to the "traditional" namespace of the element in which they appear. A "traditional" namespace is not an XML namespace, it simply means that all attribute names belonging to one element must be different. Later we will see how to assign an XML namespace to an attribute.

Due to the fact that attributes without prefixes are not in any XML namespace there is no collision between the attribute title (that belongs to the author element) and for example the title element within a chapter.

Let's clarify matters with an example:

<document xmlns:book = 'http://trolltech.com/fnord/book/'
          xmlns      = 'http://trolltech.com/fnord/' >
<book>
  <book:title>Practical XML</book:title>
  <book:author xmlns:fnord = 'http://trolltech.com/fnord/'
               title="Ms"
               fnord:title="Goddess"
               name="Eris Kallisti"/>
  <chapter>
    <title>A Namespace Called fnord</title>
  </chapter>
</book>
</document>

Within the document element we have two namespaces declared. The default namespace http://trolltech.com/fnord/ applies to the book element, the chapter element, the appropriate title element and of course to document itself.

The book:author and book:title elements belong to the namespace with the URI http://trolltech.com/fnord/book/.

The two book:author attributes title and name have no XML namespace assigned. They are only members of the "traditional" namespace of the element book:author, meaning that for example two title attributes in book:author are forbidden.

In the above example we circumvent the last rule by adding a title attribute from the http://trolltech.com/fnord/ namespace to book:author: the fnord:title comes from the namespace with the prefix fnord that is declared in the book:author element.

Clearly the fnord namespace has the same namespace URI as the default namespace. So why didn't we simply use the default namespace we'd already declared? The answer is quite complex:

  • attributes without a prefix don't belong to any XML namespace at all, even not to the default namespace;
  • additionally omitting the prefix would lead to a title-title clash;
  • writing it as xmlns:title would declare a new namespace with the prefix title instead of applying the default xmlns namespace.

With the Qt XML classes elements and attributes can be accessed in two ways: either by refering to their qualified names consisting of the namespace prefix and the "real" name (or local name) or by the combination of local name and namespace URI.

More information on XML namespaces can be found at http://www.w3.org/TR/REC-xml-names/.

Conventions used in Qt XML documentation

The following terms are used to distinguish the parts of names within the context of namespaces:

  • The qualified name is the name as it appears in the document. (In the above example book:title is a qualified name.)
  • A namespace prefix in a qualified name is the part to the left of the ":". (book is the namespace prefix in book:title.)
  • The local part of a name (also refered to as the local name) appears to the right of the ":". (Thus title is the local part of book:title.)
  • The namespace URI ("Uniform Resource Identifier") is a unique identifier for a namespace. It looks like a URL (e.g. http://trolltech.com/fnord/ ) but does not require data to be accessible by the given protocol at the named address.

Elements without a ":" (like chapter in the example) do not have a namespace prefix. In this case the local part and the qualified name are identical (i.e. chapter).


概述与HOWTO

Qt对象模型 | 几何结构和布局
  • Qt对象模型
  • 对象树和对象所有权
  • 信号与槽
  • 元对象系统
  • 属性
  • 使用元对象编译器
  • 为什么Qt不用模板来实现信号和槽？

  • 布局类
  • 写你自己的布局管理器
  • 坐标系统
  • 窗口几何结构
国际化
  • Qt中的国际化
  • Qt的文本引擎
  • 关于Unicode
概要 | Qt/嵌入式
  • 移植到Qt 3.x
  • 常见问题解答
  • Qt插件
  • QDataStream操作符的格式
  • 调试技术
  • 拖放
  • Qt的版本
  • 事件和事件过滤器
  • 如何购买Qt
  • 如何报告bug
  • 键盘焦点概述
  • 基于Qt的保持连接的插件
  • 邮件列表
  • OpenGL覆盖（X11）
  • 设置应用程序图标
  • 对话管理
  • 共享类
  • 风格概述
  • Qt模板库
  • Qt中的线程支持
  • 定时器
  • 绝大多数Qt窗口部件的图片
  • Qt对Xt/Motif支持扩展

  • QVFb工具 - Qt/嵌入式的虚拟帧缓冲

  • 安装Qt/嵌入式
  • 特征定义文件
  • Qt/嵌入式中的特有类
  • 添加一个图像加速器驱动程序到Qt/嵌入式
  • Qt/嵌入式案例学习 - Cassiopeia E-100
  • 启用Linux帧缓冲
  • 运行Qt/嵌入式应用程序
  • Qt/嵌入式中的字符输入
  • Qt/嵌入式中的字体
  • Qt/嵌入式指针操作
  • Qt/嵌入式环境变量
  • 移植你的应用程序到Qt/嵌入式
  • 关于移植Qt/嵌入式到其它操作系统的讨论
  • Qt/嵌入式性能调节
  • Qt/嵌入式作为VNC服务器

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt对象模型

标准的C++对象模型为对象范例提供了十分有效的运行时刻支持。但是这种C++对象 模型的静态性质在一定的问题领域是不够灵活的。图形用户界面编程就是一个同时 需要运行时刻的效率和高水平的灵活性的领域。Qt通过结合C++的速度为这一领域 提供了Qt对象模型的灵活性。

Qt把下面这些特性添加到了C++当中：

  • 一种关于无缝对象通讯被称为信号和槽的非常强大的机制，
  • 可查询和可设计的属性，
  • 强大的事件和事件过滤器，
  • 根据上下文进行国际化的字符串翻译，
  • 完善的时间间隔驱动的计时器使得在一个事件 驱动的图形界面程序中很好地集成许多任务成为可能。
  • 以一种自然的方式组织对象所有权的分层次和可查询的对象树。
  • 被守护的指针，QGuardedPtr，当参考对象被破坏时，可以自动地设置为无效， 不像正常的C++指针在它们的对象被破坏的时候变成了“摇摆指针”。

许多Qt的特性是基于QObject的继承，通过标准C++技术实现的。其他的， 比如对象通讯机制和虚拟属性系统，都需要Qt自己的元对象编译器(moc) 提供的元对象系统。

元对象系统是一种可以使语言更加适用于真正的组件图形用户界面程序的C++扩展。 尽管模板也可以用来扩展C++，元对象系统提供给标准C++而模板所不能提供的益处， 请看为什么Qt不用模板来实现信号和槽？。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


信号和槽

信号和槽用于对象间的通讯。信号/槽机制是Qt的一个中心特征并且也许是Qt与 其它工具包的最不相同的部分。

在图形用户界面编程中，我们经常希望一个窗口部件的一个变化被通知给另一个 窗口部件。更一般地，我们希望任何一类的对象可以和其它对象进行通讯。例如，如 果我们正在解析一个XML文件，当我们遇到一个新的标签时，我们也许希望通知列表 视图我们正在用来表达XML文件的结构。

较老的工具包使用一种被称作回调的通讯方式来实现同一目的。回调是指一个函 数的指针，所以如果你希望一个处理函数通知你一些事件，你可以把另一个函数（回 调）的指针传递给处理函数。处理函数在适当的时候调用回调。回调有两个主要缺 点。首先他们不是类型安全的。我们从来都不能确定处理函数使用了正确的参数来调 用回调。其次回调和处理函数是非常强有力地联系在一起的，因为处理函数必须知道 要调用哪个回调。

一个关于一些信号和槽连接的摘要图

在Qt中我们有一种可以替代回调的技术。我们使用信号和槽。当 一个特定事件发生的时候，一个信号被发射。Qt的窗口部件有很多预定义的信号， 但是我们总是可以通过继承来加入我们自己的信号。槽就是一个可以被调用处理特定 信号的函数。Qt的窗口部件又很多预定义的槽，但是通常的习惯是你可以加入自己的 槽，这样你就可以处理你所感兴趣的信号。

信号和槽的机制是类型安全的：一个信号的签名必须与它的接收槽的签名相匹 配。（实际上一个槽的签名可以比它接收的信号的签名少，因为它可以忽略额外的 签名。）因为签名是一致的，编译器就可以帮助我们检测类型不匹配。信号和槽是 宽松地联系在一起的：一个发射信号的类不用知道也不用注意哪个槽要接收这个信 号。Qt的信号和槽的机制可以保证如果你把一个信号和一个槽连接起来，槽会在正 确的时间使用信号的参数而被调用。信号和槽可以使用任何数量、任何类型的参 数。它们是完全类型安全的：不会再有回调核心转储(core dump)。

从QObject类或者它的一个子类 （比如QWidget类）继承的所有类可以包含信号和槽。 当对象改变它们的状态的时候，信号被发送，从某种意义上讲，它们也许对外面的 世界感兴趣。这就是所有的对象通讯时所做的一切。它不知道也不注意无论有没有 东西接收它所发射的信号。这就是真正的信息封装，并且确保对象可以用作一个软 件组件。

一个信号和槽连接的例子

槽可以用来接收信号，但它们是正常的成员函数。一个槽不知道 它是否被任意信号连接。此外，对象不知道关于这种通讯机制和能够被用作一个真正 的软件组件。

你可以把许多信号和你所希望的单一槽相连，并且一个信号也可以和你所期望的 许多槽相连。把一个信号和另一个信号直接相连也是可以的。（这时，只要第一个信 号被发射时，第二个信号立刻就被发射。）

总体来看，信号和槽构成了一个强有力的组件编程机制。

一个小例子

一个最小的C++类声明如下：

    class Foo
    {
    public:
        Foo();
        int value() const { return val; }
        void setValue( int );
    private:
        int val;
    };

一个小的Qt类如下：

    class Foo : public QObject
    {
        Q_OBJECT
    public:
        Foo();
        int value() const { return val; }
    public slots:
        void setValue( int );
    signals:
        void valueChanged( int );
    private:
        int val;
    };

这个类有同样的内部状态，和公有方法来访问状态，但是另外它也支持使用信号 和槽的组件编程：这个类可以通过发射一个信号，valueChanged()，来告 诉外面的世界它的状态发生了变化，并且它有一个槽，其它对象可以发送信号给这个 槽。

所有包含信号和/或者槽的类必须在它们的声明中提到Q_OBJECT。

槽可以由应用程序的编写者来实现。这里是Foo::setValue()的一个可能的实现：

    void Foo::setValue( int v )
    {
        if ( v != val ) {
            val = v;
            emit valueChanged(v);
        }
    }

emit valueChanged(v)这一行从对象中发射valueChanged信 号。正如你所能看到的，你通过使用emit signal(arguments)来发射信号。

下面是把两个对象连接在一起的一种方法：

    Foo a, b;
    connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));
    b.setValue( 11 ); // a == undefined  b == 11
    a.setValue( 79 ); // a == 79         b == 79
    b.value();

调用a.setValue(79)会使a发射一个valueChanged() 信号，b将会在它的setValue()槽中接收这个信号，也就是b.setValue(79) 被调用。接下来b会发射同样的valueChanged()信号，但是因为 没有槽被连接到b的valueChanged()信号，所以没有发生任何事 （信号消失了）。

 注意只有当v != val的时候setValue()函数才会设置这个值
并且发射信号。这样就避免了在循环连接的情况下（比如b.valueChanged()
和a.setValue()连接在一起）出现无休止的循环的情况。

这个例子说明了对象之间可以在互相不知道的情况下一起工作，只要在最初的时在 它们中间建立连接。

预处理程序改变或者移除了signals、slots和emit 这些关键字，这样就可以使用标准的C++编译器。

在一个定义有信号和槽的类上运行moc。这样就会生成 一个可以和其它对象文件编译和连接成引用程序的C++源文件。

信号

当对象的内部状态发生改变，信号就被发射，在某些方面对于 对象代理或者所有者也许是很有趣的。只有定义了一个信号的类和它的子类才能发射 这个信号。

例如，一个列表框同时发射highlighted()和activated()这 两个信号。绝大多数对象也许只对activated()这个信号感兴趣，但是有时 想知道列表框中的哪个条目在当前是高亮的。如果两个不同的类对同一个信号感兴趣， 你可以把这个信号和这两个对象连接起来。

当一个信号被发射，它所连接的槽会被立即执行，就像一个普通函数调用一样。 信号/槽机制完全不依赖于任何一种图形用户界面的事件回路。当所有的槽都返回后 emit也将返回。

如果几个槽被连接到一个信号，当信号被发射时，这些槽就会被按任意顺序一个 接一个地执行。

信号会由moc自动生成并且一定不要在.cpp文件中 实现。它们也不能有任何返回类型（比如使用void）。

关于参数需要注意。我们的经验显示如果信号和槽不使用特殊的类型， 它们都可以多次使用。如果QScrollBar::valueChanged() 使用了一个特殊的类型，比如hypothetical QRangeControl::Range，它就只能被连 接到被设计成可以处理QRangeControl的槽。简 单的和教程1的第5部分一样的程序将是不可 能的。

槽

当一个和槽连接的信号被发射的时候，这个操被调用。槽也是 普通的C++函数并且可以像它们一样被调用；它们唯一的特点就是它们可以被信号连 接。槽的参数不能含有默认值，并且和信号一样，为了槽的参数而使用自己特定的类 型是很不明智的。

因为槽就是普通成员函数，但却有一点非常有意思的东西，它们也和普通成员函 数一样有访问权限。一个槽的访问权限决定了谁可以和它相连：

一个public slots:区包含了任何信号都可以相连的槽。这对于组件编 程来说非常有用：你生成了许多对象，它们互相并不知道，把它们的信号和槽连接起 来，这样信息就可以正确地传递，并且就像一个铁路模型，把它打开然后让它跑起来。

一个protected slots:区包含了之后这个类和它的子类的信号才能连接 的槽。这就是说这些槽只是类的实现的一部分，而不是它和外界的接口。

一个private slots:区包含了之后这个类本身的信号可以连接的槽。这 就是说它和这个类是非常紧密的，甚至它的子类都没有获得连接权利这样的信任。

你也可以把槽定义为虚的，这在实践中被发现也是非常有用的。

信号和槽的机制是非常有效的，但是它不像“真正的”回调那样快。信号和槽稍 微有些慢，这是因为它们所提供的灵活性，尽管在实际应用中这些不同可以被忽略。 通常，发射一个和槽相连的信号，大约只比直接调用那些非虚函数调用的接收器慢 十倍。这是定位连接对象所需的开销，可以安全地重复所有地连接（例如在发射期 间检查并发接收器是否被破坏）并且可以按一般的方式安排任何参数。当十个非虚 函数调用听起来很多时，举个例子来说，时间开销只不过比任何一个“new”或者 “delete”操作要少些。当你执行一个字符串、矢量或者列表操作时，需要“new”或者 “delete”，信号和槽仅仅对一个完整函数调用地时间开销中的一个非常小的部分负 责。无论何时你在一个槽中使用一个系统调用和间接地调用超过十个函数的时间是 相同的。在一台i585-500机器上，你每秒钟可以发射2，000，000个左右连接到一个 接收器上的信号，或者发射1，200，000个左右连接到两个接收器的信号。信号和槽 机制的简单性和灵活性对于时间的开销来说是非常值得的，你的用户甚至察觉不出来。

元对象信息

元对象编译器（moc） 解析一个C++文件中的类声明并且生成初始化元对象的C++代码。元对象包括所有信号 和槽函数的名称，还有这些函数的指针。（要获得更多的信息，请看为什么Qt不用模板来实现信号和槽？）

元对象包括一些额外的信息，比如对象的类名称。 你也可以检查一个对象是否继承了一个特定的类， 比如：

  if ( widget->inherits("QButton") ) {
        // 是的，它是一个Push Button、Radio Button或者其它按钮。
  }

一个真实的例子

这是一个注释过的简单的例子（代码片断选自qlcdnumber.h）。

    #include "qframe.h"
    #include "qbitarray.h"

    class QLCDNumber : public QFrame

QLCDNumber通过QFrame和QWidget，还有#include这样的相关声明继承了含有绝大 多数信号/槽知识的QObject。

    {
        Q_OBJECT

Q_OBJECT是由预处理器展开声明几个由moc来实现的成员函数，如果你得到了几行 “virtual function QButton::className not defined”这样的编译器错误信息，你也 许忘记运行moc或者忘记在连接命令中包含moc输出。

    public:
        QLCDNumber( QWidget *parent=0, const char *name=0 );
        QLCDNumber( uint numDigits, QWidget *parent=0, const char *name=0 );

它并不和moc直接相关，但是如果你继承了QWidget，你当然想在你的构造器中获 得parent和name这两个参数，而且把它们传递到父类的构造器中。

一些解析器和成员函数在这里省略掉了，moc忽略了这些成员函数。

    signals:
        void    overflow();

当QLCDNumber被请求显示一个不可能值时，它 发射一个信号。

如果你没有留意溢出，或者你认为溢出不会发生，你可以忽略overflow()信号， 也就是说你可以不把它连接到任何一个槽上。

另一方面如果当数字溢出时，你想调用两个不同的错误函数，很简单地你可 以把这个信号和两个不同的槽连接起来。Qt将会两个都调用（按任意顺序）。

    public slots:
        void    display( int num );
        void    display( double num );
        void    display( const char *str );
        void    setHexMode();
        void    setDecMode();
        void    setOctMode();
        void    setBinMode();
        void    smallDecimalPoint( bool );

一个槽就是一个接收函数，用来获得其它窗口部件状态变或的信息。QLCDNumber 使用它，就像上面的代码一样，来设置显示的数字。因为display()是这个 类和程序的其它的部分的一个接口，所以这个槽是公有的。

几个例程把QScrollBar的newValue信号连接到display槽，所以LCD数字可以继续显示滚动条的值。

请注意display()被重载了，当你把一个信号和这个槽相连的时候，Qt将会选择适 当的版本。如果使用回调，你会发现五个不同的名字并且自己来跟踪类型。

一些不相关的成员函数已经从例子中省略了。

    };

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


窗口几何结构

概述

QWidget提供了几个处理窗口几何结构的函数。这些函数中的几个操作纯客户区域（例如不包含窗口框架的窗口），其它一些包括窗口框架。它们之间的区别在某种意义上被完成覆盖明显地最普通的方法。

包括窗口的框架：
x(), y(), frameGeometry(), pos() and move()
不包括窗口的框架：
geometry(), width(), height(), rect() and size()

请注意这这种区别仅仅对于被装饰的顶层窗口部件有效。对于所有的子窗口部件，框架的几何结构和这个窗口部件的客户几何结构相同。

这个图显示了我们所使用的绝大多数函数：

Unix/X11特性

在Unix/X11中，一个窗口没有框架直到窗口管理器来装饰它。这种情况发生在异步情况下调用show()之后和窗口接收到第一个绘画事件的一些点中，否则它根本就不会发生。请记住X11是自由策略的（其它人把它称为灵活的）。因此你不能作出关于你的窗口得到装饰框架这样的任何安全假设。基本规则：总是会有用户使用窗口管理器来打破你的假设，并且他还会向你抱怨。

此外，一个工具包不能简单地把窗口放置到屏幕上。Qt所能做的一切是把一些确定的提示发送给窗口管理器。窗口管理器，一个单独的进程，也许会遵守、忽略或者误解它们。由于部分不清楚的客户间通信约定（ICCCM），在存在的窗口管理器中窗口放置的处理非常困难。

当窗口被装饰的时候，X11没有提供标准的或者容易的方式来获得框架的几何结构。Qt使用了可以工作在今天存在的大量的窗口管理器中的非常富有启发性和巧妙的代码来解决这一问题。如果你发现某种情况下frameGeometry()返回了虚假的结果的时候，请不要惊讶。

X11同样也不提供最大化一个窗口的方法。因此Qt中的showMaximized()函数不得不模拟这一功能。它的结果完全取决于frameGeometry()的结果和窗口管理器作出正确的窗口放置的能力，但这两个都不能被保证。

恢复窗口几何结构

现代的应用程序的一个普通任务就是在稍后的对话中恢复一个窗口的几何结构。在Windows中，这基本上通过存储geometry()的结果和在下一个对话中还没有框架之前调用setGeometry()。在X11中，这样将不会工作，因为一个没有显示的窗口还没有框架呢。窗口管理器将会在稍后装饰这个窗口。当这些发生的时候，窗口朝着依赖于装饰框架的大小的屏幕的右下角偏移。X从理论上提供了一种可以避免这种偏移的方法。尽管，我们的测试已经显示，绝大多数窗口管理器都不能实现这一特性。

一个工作区在show()之后调用setGeometry()。这样做有两个缺点，是窗口部件会在一毫秒中出现在一个错误的位置（结果是闪烁）和通常在一秒之后窗口管理器会正确地得到它。一个安全的方式是存储pos()和size()并且在show()之前调用resize()和move()来恢复几何结构，就像下面这个例子一样装饰：

    MyWidget* widget = new MyWidget
    ...
    QPoint p = widget->pos();   // 存储位置
    QSize s = widget->size();   // 存储大小
    ...
    widget = new MyWidget;
    widget->resize( s );        // 恢复大小
    widget->move( p );          // 恢复位置
    widget->show();             // 显示窗口部件

这种方法可以在MS-Windows和绝大多数现存的X11窗口管理器上工作。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


事件和事件过滤器

在Qt里，一个事件是继承自QEvent的对象。事件通过调用QObject::event()，被发送到继承自 QObject 的对象。事件发送就是一个事件已经产生，由 QEvent正好去表达，且QObject 需要去回应。多数事件针对 QWidget和他的子类的，此外还有些不和图形相关的重要事件，比如，套接字激活，——某种被用于QSocketNotifier运作的事件。

某些事件来自窗口系统，如QMouseEvent，某些来自其他源头，如QTimerEvent，而某些来自应用程序。Qt一视同仁，因此像通常一样，你可以准确地发送事件，这和Qt自己的事件循环所作的方式一样。

多数事件类型具有特定的类，最常见的QResizeEvent、QPaintEvent、QMouseEvent、QKeyEvent和QCloseEvent。有很多别的，差不多40种左右，但大都是相当零碎。

每个类派生自QEvent且添加事件特定的函数；例如，QResizeEvent。在QResizeEvent中，就被加入了QResizeEvent::size()和QResizeEvent::oldSize()。

某些类支持多种事件类型。QMouseEvent支持鼠标移动、按压、粘滞按压、拖拽、点击、右按压，等等。

因为程序需要在多变且复杂的方式下作用，Qt的事件派发机制就是灵活的。QApplication::notify() 的文档扼要地叙述其整个来龙去脉，我们揭示在这里的内容满足99％的应用。

对于事件去被派发的正常的办法是调用一个虚拟函数。如，QPaintEvent通过调用QWidget::paintEvent()被使用。这个虚拟函数负责引起适当的响应，一般是重画窗口部件。

有时，并不存在一个特定事件函数，或者特定事件功能不足。最普通的例如按下tab键。正常情况下，被QWidget看成是去移动 键盘焦点，但少数窗口部件 需要自行解释。

这些对象能重新实现QObject::event()，按常规事件处理，以及要么在通常的处理之前，或之后处理，或完全重写。一个与众不同的的窗口部件，它解释了tab，也含有一个该应用特定的可能包含的自定制事件：

  bool MyClass:event( QEvent * e ) {
      if ( e->type() == QEvent::KeyPress ) {
          QKeyEvent * ke = (QKeyEvent*) e;
          if ( ke->key() == Key_Tab ) {
              // 这里是特定的tab处理
              k->accept();
              return TRUE;
          }
      } else if ( e->type() >= QEvent::User ) {
          QCustomEvent * c = (QCustomEvent*) e;
          // 这里是自定义事件处理
          return TRUE;
      }
      QWidget::event( e );
  }

更一般的，一个对象需要去考虑其它的事件。Qt用QObject::installEventFilter()支持这个目的（相应的有移除）。如，对话框通常要为某些窗口部件去过滤按键，比如，去修改Return键的处理。

一个事件过滤器在目标对象处理之前得以去处理事件。过滤器的QObject::eventFilter()实现被调用，它可以接受或丢弃过滤，也可容许或拒绝进一步去处理事件。如果所有的事件过滤器允许进一步的处理事件，事件自己就被送达目标对象。如果它们之一停止处理，目标和任何后面的事件过滤器根本就对该事件一无所知了。

整个应用程序中过滤所有的事件也是可能的，通过在QApplication上安装一个事件过滤器。这里有QToolTip为了处理全部鼠标和键盘行为的实作。这个功能相当强大，但其在整个应用中也拖慢了每单个事件的派送，因此最好避免这种应用方式。

全局事件过滤器在对象特定的过滤器前被调用。

许多应用程序都要创建和发送他们自己的事件。

创建一种内置类型的事件是非常简单的：创建一个相应的类型的对象，然后调用QApplication::sendEvent()或者QApplication::postEvent()。

sendEvent() 立即处理事件——当sendEvent() 返回，（事件过滤器和）对象已经处理过事件了。对于很多事件类，调用isAccepted()函数，他告知你该事件能否被目前调用的处理者所接受或者拒绝。

postEvent()投送事件于一个队列，以使能延迟派发。在下次Qt的主事件循环运行，他派发全部事件，带有些优化。举例，若有数个resize事件，它们就被压缩到一个。对于paint事件同样如此：QWidget::update()调用 postEvent()，最小化闪屏和避免多次重画，以增加速度。

postEvent()在对象初始化期间常常被使用，因为在对象完成初始化后，投送的消息会被很快派发。

去创建一个自定义类型的事件，你需要定义一个事件号，其必须大于QEvent::User，可能你也需要从QCustomEvent去派生，为了传递有关你的自定义事件的特性。看QCustomEvent的文档了解细节。

Copyright © 2002 Trolltech Trademarks 译者:Blueneno
Qt 3.0.5版


以Qt国际化

Qt国际化

应用的国际化就是使应用成为能被非本国的人使用的过程。

有的情况下，国际化很简单，例如，使一个US应用可被Australian或者British用户理解，工作可能少于几个拼写修正。但是使一个US应用可以被Japanese用户使用，或者一个Korean应用可被German用户使用，就会需要软件不仅工作于不同语言下，还要使用不同的输入技术、字符编码和表达习惯。

也参见Qt语言学家手册。

Step by Step

以Qt来编写多平台国际化的软件是一个和缓的、逐步增加的过程。你的软件可以按下面的几个阶段实现国际化：

对所有用户可见的文本使用QString

既然QString内部就使用Unicode编码，那么使用常见的文本处理手段，就可以透彻地处理世界上的每种语言。同时，既然所有向用户呈现文本的Qt函数都把QString作为参数，也就没有了char*到QString的转换的时间开销。

在“程序员空间”（例如QObject的名称和文件格式文本）的字符串不需要使用QString；传统的char*或者QCString类就够用了。

你不大可能注意到你在使用Unicode；QString和QChar就如同早期版本的传统C中的粗糙的const char*和char。

对所有文字形式的文本使用tr()

无论你的程序在哪里对将会呈现给用户的文本使用了"quoted text"，要确保它被QApplication::translate()函数处理过。其实做到这一点只需要使用QObject::tr()。例如，假设LoginWidget是QWidget的一个子类：

    LoginWidget::LoginWidget()
    {
        QLabel *label = new QLabel( tr("Password:"), this );
        ...
    }

这就解决了你可能要写的用户可见的字符串的99％。

如果这些quoted text不是在QObject子类的成员函数中，可以使用一个适当的类的tr()函数，或者直接使用QApplication::translate()函数：

    void some_global_function( LoginWidget *logwid )
    {
        QLabel *label = new QLabel(
                LoginWidget::tr("Password:"), logwid );
    }

    void same_global_function( LoginWidget *logwid )
    {
        QLabel *label = new QLabel(
                qApp->translate("LoginWidget", "Password:"),
                logwid );
    }

如果你需要不在函数里的可翻译文本，有两个宏可以帮忙：QT_TR_NOOP()和QT_TRANSLATE_NOOP()。它们仅仅标示出文本，以便于被下面描述的lupdate工具提取。宏扩展为只是文本（没有上下文）。

QT_TR_NOOP()的例子：

    QString FriendlyConversation::greeting( int greet_type )
    {
        static const char* greeting_strings[] = {
            QT_TR_NOOP( "Hello" ),
            QT_TR_NOOP( "Goodbye" )
        };
        return tr( greeting_strings[greet_type] );
    }

QT_TRANSLATE_NOOP()的例子：

    static const char* greeting_strings[] = {
        QT_TRANSLATE_NOOP( "FriendlyConversation", "Hello" ),
        QT_TRANSLATE_NOOP( "FriendlyConversation", "Goodbye" )
    };

    QString FriendlyConversation::greeting( int greet_type )
    {
        return tr( greeting_strings[greet_type] );
    }

    QString global_greeting( int greet_type )
    {
        return qApp->translate( "FriendlyConversation",
                                greeting_strings[greet_type] );
    }

如果你使用定义的宏QT_NO_CAST_ASCII编译你的软件，从而关闭了从const char*到QString的自动转换，你很可能会捕捉到你错过的字符串。更多信息参见QString::fromLatin1()。关闭这个转换会使编程有点儿麻烦。

如果你的源码语言使用Latin-1之外的字符集，你会发现QObject::trUtf8()比QObject::tr()更好用，因为tr()依赖于QApplication::defaultCodec()，这使它比QObject::trUtf8()更脆弱。

对于加速键值（Accelerator value）使用QKeySequence()

加速键值，例如Ctrl+Q或者Alt+F，也需要翻译。 如果你的应用给“Quit”直接编码（hardcode）为CTRL+Key_Q，翻译者就不能重载它了。正确的习惯用法是

    QPopupMenu *file = new QPopupMenu( this );
    file->insertItem( tr("&Quit"), this, SLOT(quit()),
                      QKeySequence(tr("Ctrl+Q", "File|Quit")) );

对简单参数使用QString::arg()

对于国际化的文本，在字符串中类似printf()风格的插入参数一般是不好的选择，因为有时候有必要在翻译时改变参数的顺序。不管怎样，QString::arg()函数为参数替换提供了一种简单的途径：

    void FileCopier::showProgress( int done, int total,
                                   const QString& current_file )
    {
        label.setText( tr("%1 of %2 files copied.\nCopying: %3")
                        .arg(done)
                        .arg(total)
                        .arg(current_file) );
    }

创作译本

在应用中通篇使用tr()之后，你就可以开始创作程序中用户可见的文本的译本了。

Qt语言学家手册提供了关于Qt翻译工具、Qt语言学家、lupdate和lrelease的进一步信息。

Qt应用的翻译过程分为三步：

  1. 运行lupdate，以提取出Qt应用的C++源代码中的可翻译文本，会产生一个给翻译者的信息文件（.ts文件）。该工具识别出tr()结构和上面描述的QT_*_NOOP宏，产生.ts文件（通常每种语言一个）。
  2. 使用Qt语言学家提供.ts文件中源文本的译文。既然.ts文件是XML格式，你也可以手工编辑它们。
  3. 运行lrelease，以从.ts文件中得到只适用于最后使用的轻量级的信息文件（.qm文件）。你可以把.ts文件看成“源文件”，把.qm文件看成“目标文件”。翻译者编辑的是.ts文件，可是你的应用的用户只需要.qm文件。这两种文件都是平台和地区（locale）无关的。

典型地，你将对应用地每个发表版本重复这几步。lupdate工具会尽力重用以前的发表版本的译文。

在你运行lupdate之前，你应该准备一个项目文件。这是一个项目文件（.pro文件）的例子：

    HEADERS         = funnydialog.h \
                      wackywidget.h
    SOURCES         = funnydialog.cpp \
                      main.cpp \
                      wackywidget.cpp
    FORMS           = fancybox.ui
    TRANSLATIONS    = superapp_dk.ts \
                      superapp_fi.ts \
                      superapp_no.ts \
                      superapp_se.ts

当你运行lupdate或者lrelease时，你必须以命令行参数给出项目文件的名称。

在本例中，支持四种语言：Danish、Finnish、Norwegian和Swedish。如果你使用qmake（或者tmake），你一般不需要给lupdate的附加项目文件；只要你加上TRANSLATIONS条目，你的qmake项目文件就会正常工作。

在应用中，你必须使用QTranslator::load()来装载对应用户语言的译文文件，再使用QApplication::installTranslator()来安装它们。

如果你一直使用以前的Qt工具（findtr、msg2qm和mergetr），可以使用qm2ts来转换你以前的.qm文件。

语言学家、lupdate和lrelease安装在$QTDIR/bin。在Qt语言学家中点击Help|Manual，就可访问用户手册，它包含了让你起步的演示教程。

虽然这些工具提供了生成.qm文件的方便途径，可任何能编写.qm文件的系统也都够用。你可以制做一个应用，以利用QTranslator::insert()把译文加入到QTranslator中，接着再利用QTranslator::save()写出一个.qm文件。 用这种办法可以从任何你选择的源文件中产生译文。

Qt本身包含有大约400个也需要翻译为目标语言的字符串。在$QTDIR/translations下，你会找到French和German的译文文件，也可以作为翻译为其他语言的模板。

典型地，你的应用的main()函数会类似这样：

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

        // translation file for Qt
        QTranslator qt( 0 );
        qt.load( QString( "qt_" ) + QTextCodec::locale(), "." );
        app.installTranslator( &qt );

        // translation file for application strings
        QTranslator myapp( 0 );
        myapp.load( QString( "myapp_" ) + QTextCodec::locale(), "." );
        app.installTranslator( &myapp );

        ...

        return app.exec();
    }

编码支持

QTextCodec类和QTextStream中的工具，方便你支持很多对于用户数据的输入输出编码。当应用启动时，机器的地区（locale）决定了处理8-bit数据——例如对于字体选择、文本显示、8-bit文本I/O和字符输入——所用的8-bit编码。

应用有时会需要不同于缺省本地8-bit编码的编码。例如，一个Cyrillic KOI8-R locale（俄罗斯的事实标准locale）的应用 可能需要以ISO 8859-5编码输出Cyrillic。这样的代码可能会是：

    QString string = ...; // some Unicode text

    QTextCodec* codec = QTextCodec::codecForName( "ISO 8859-5" );
    QCString encoded_string = codec->fromUnicode( string );

    ...; // use encoded_string in 8-bit operations

对于把Unicode转换为本地8-bit编码，有一个快捷办法：QString的local8Bit()方法返回的就是这样的8-bit数据。另一个有用的快捷办法是utf8()方法，它以8-bit的UTF-8编码返回文本——有趣之处在于， 如果Unicode完全是US-ASCII的话，它可以完全保留Unicode信息，而看起来又是一般的US-ASCII。

至于其他方式的转换，有QString::fromUtf8()和QString::fromLocal8Bit()两个方便的函数，或者通用的代码，按下面从ISO 8859-5 Cyrillic到Unicode所演示：

    QCString encoded_string = ...; // Some ISO 8859-5 encoded text.

    QTextCodec* codec = QTextCodec::codecForName("ISO 8859-5");
    QString string = codec->toUnicode(encoded_string);

    ...; // Use string in all of Qt's QString operations.

理想状态下应该使用Unicode的I/O，因为这最大地提高了世界各地的用户之间的文档兼容性。可实际上，支持所有适当的你的用户为处理已存在的文档而会需要用到的编码，也是有用的。通常，Unicode（UTF16或者UTF8）最适于在任何人之间传递信息，然而在同一语言或者民族群体内部，一种本地标准一般更为合适。 要支持的最重要的编码是由QTextCodec::codecForLocale()所返回的那个，因为这是用户最可能需要用来与其他人和应用（这是local8Bit()所使用的编码器）通讯的一个。

考虑到大多数Unix系统对本地8-bit编码和Unicode之间的转换没有内建支持，可能有必要编写你自己的QTextCodec子类。视紧迫程度而定，可以联系Trolltech的技术支持或者询问qt-interest邮件列表以看看是否已经有别人已经致力于支持某种编码。 一个有用的过渡办法是，可以使用QTextCodec::loadCharmapFile()函数以构造一个数据驱动的编码器，虽然这种办法会有内存和速度上的恶化，尤其是带有动态装载库。关于编写自己的QTextCodec详情，参见QTextCodec主类的文档。

本地化

本地化是适应本地习惯比如日期时间表达方式的过程。 这样的本地化可以使用适当的tr()字符串完成，即使是"magic" words，像这个有些做作的例子所示意的：

    void Clock::setTime(const QTime& t)
    {
        if ( tr("AMPM") == "AMPM" ) {
            // 12-hour clock
        } else {
            // 24-hour clock
        }
    }

图象本地化不推荐。请选择清晰的适用于任何地区的图标，而不要依赖于当地的双关语或者引申的暗喻。

系统支持

支持Unicode的操作系统和窗口系统还处于开发初期。底层系统所能得到的支持程度会影响Qt在该平台上所提供的支持，但是以Qt编写的应用一般不必太关心实际限制。

Unix/X11

  • 本地导向的（Locale-oriented）字体和输入法。Qt隐藏了这些，而代之以Unicode输入和输出。
  • 在一些Unix变种的文件系统中的约定，例如UTF-8，正在开发中。所有Qt的文件函数都认可Unicode，但把所有的文件名转换为本地8-bit编码，因为这是Unix的惯例（研究代用的编码，参见QFile::setEncodingFunction()）。
  • 文件I/O缺省为本地8-bit编码，在QTextStream中带有Unicode选项。

Windows 95/98/NT

  • Qt提供完整的Unicode支持，包括输入法、字体、剪贴板、拖放和文件名。
  • 文件I/O缺省为Latin-1，在QTextStream中带有Unicode选项。注意，有的Windows程序并不能领会高位在前（big-endian）的Unicode文本文件，即使这是没有更高级的协议时Unicode标准所规定的次序。
  • 不像使用MFC或者一般winlib的程序，Qt程序可以在Windows 95/98和Windows NT之间移植。你不需要不同的二进制码以支持Unicode。

支持更多的输入法

Trolltech并没有那么多资源或者专门技术，可以在Qt里立即加入世界上所有语言的支持。所以我们很期待与有这些专门技术的人一起工作。在下几个次版本号中，我们希望能对你选择的语言加入支持，直到任何人都可以使用Qt和以Qt开发的所有程序，而不管他们使用什么语言。

单字节编码（European Latin-1和KOI8-R等）和多字节编码（East Asian EUC-JP等）的语言都已支持。 对于那些“复杂”的编码——需要从右至左输入或者复杂字符组成的编码（例如Arabic、Hebrew和Thai script）——已经实现，但是Indic script的范畴（Hindi、Devanagari、Bengali等）还在开发中。现在的情况是：

编码 | 状态
Windows上的所有编码 | 本地的编码总是支持。
ISO标准编码 ISO 8859-1、 ISO 8859-2、 ISO 8859-3、 ISO 8859-4、 ISO 8859-5、 ISO 8859-7、 ISO 8859-9和 ISO 8859-15 | 完全支持。
KOI8-R | 完全支持。
eucJP、JIS和ShiftJIS | 完全支持。在X11上对于XIM协议使用eucJP，在Japanese Windows NT上使用IME Windows NT。Serika Kurusugawa和其他人正在介入这个工作。kinput2是X11上测试过的输入法。
eucKR | 支持。Mizi Research正在介入这个工作。hanIM是测试过的输入法。
Big5 | Qt包含着一个由Ming Che-Chuang开发的Big5编解码器。正在xcin (2.5.x) XIM server上展开测试。
eucTW | 外部开发中。

关于Qt中对不同的writing system的支持，更多信息参见关于writing systems的文档。

如果你有兴趣参与已有的成果，或是支持以上提到的之外的新编码，你的工作可以被考虑包括在Qt官方发布中，或者只是与你的应用打包在一起。

最后，我们希望能帮助Unix成为面向Unicode（Unicode-oriented），正如Windows正在做的那样。这就意味着，在字体服务器中使用新的进展而带来的更好的字体支持，例如xfsft、xfstt和x-tt；同时还有UTF-8（一种Unicode编码）文件名，比如使用Solaris 7上的Unicode支持。

关于X11上的Locale的注意事项

对于有的locale，很多Unix发布版只包括部分支持。例如，如果你有/usr/share/locale/ja_JP.EUC目录，这并不一定意味着你可以显示Japanese文本；你还需要JIS编码的字体（或者Unicode字体），以及/usr/share/locale/ja_JP.EUC目录，才能够达到目的。要达到最好的结果，使用你的系统提供商那里来的完全locale。

有关的Qt类

这些类同国际化Qt应用有关。

QEucJpCodec | 从和到EUC-JP字符集的转换
QEucKrCodec | 从和到EUC-KR字符集的转换
QGb18030Codec | 从和到Chinese GB18030/GBK/GB2312编码的转换
QGbkCodec | 从和到Chinese GBK编码的转换
QHebrewCodec | 从和到visually ordered Hebrew的转换
QJisCodec | 从和到JIS字符集的转换
QSjisCodec | 从和到Shift-JIS的转换
QTextCodec | 文本编码之间的转换
QTextDecoder | 基于状态（State-based）的解码器
QTextEncoder | 基于状态的编码器
QTranslator | 文本输出的国际化支持
QTranslatorMessage | Translator的信息及其属性
QTsciiCodec | 从和到Tamil TSCII编码的转换

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


调试技术

现在我们为您的基于Qt的软件的调试提供一些有用的提示。

命令行参数

当你运行Qt程序时，你可以指定几个命令行参数来帮助你调试。

  • -nograb 应用程序不再捕获鼠标或者键盘。当程序在Linux下运行在gdb调试器中时这个选项是默认的。
  • -dograb 忽略任何隐含的或明显得-nograb。即使-nograb出现在命令行的最后，-dograb也会超过-nograb生效的。
  • -sync 在X同步模式下运行应用程序。同步模式强迫X服务器立即执行每一个X客户端的请求，而并不能使用缓存优化。它使得程序更加容易测试并且通常会更慢。-sync模式只对X11版本的Qt有效。

警告和调试消息

Qt包含了三个全局函数来写出警告和调试文本。

  • qDebug()用来为测试及其它写调试输出。
  • qWarning()用来在程序发生错误时写警告输出。
  • qFatal()用来写致命错误消息并且退出。

这些函数的Qt实现是在Unix/X11下把文本打印到标准错误（stderr）输出，在Windows下会打印到调试器。你可以通过安装一个消息处理器，qInstallMsgHandler()来接收这些函数。

当应用程序看起来或者用起来很奇怪的时候，调试函数QObject::dumpObjectTree()和QObject::dumpObjectInfo()很有用。如果你使用了对象名称，这将会更有用，但通常情况下是没有名称的。

调试宏

qglobal.h头文件包含了很多调试宏和#defines。

两个重要的宏是：

  • Q_ASSERT(b)里面的b是一个布尔表达式，当b是FALSE的时候，写出警告信息：“ASSERT: 'b' in file file.cpp (234)”。
  • Q_CHECK_PTR(p)里面的p是一个指针。如果p是空的话，写出警告信息：“In file file.cpp, line 234: Out of memory”。

这些宏在检测程序错误时很有用，比如像这样：

  char *alloc( int size )
  {
      Q_ASSERT( size > 0 );
      char *p = new char[size];
      Q_CHECK_PTR( p );
      return p;
  }

如果你定义了QT_FATAL_ASSERT标记，Q_ASSERT将会调用fatal()而不是warning()，所以一个错误声明将会导致在打印错误消息后使程序退出。

注意如果QT_CHECK_STATE未定义，Q_ASSERT宏就是一个空的表达式（参见下面）。在里面的任何代码都不会被执行。相似的，如果QT_CHECK_NULL未定义，Q_CHECK_PTR也是一个空的表达式。这里就是一个不应该如此使用Q_ASSERT和Q_CHECK_PTR的例子：

  char *alloc( int size )
  {
      char *p;
      Q_CHECK_PTR( p = new char[size] ); // WRONG
      return p;
  }

这个问题是棘手的：仅仅在正确的检测标记被定义时，p才会被设置为健全的值。如果QT_CHECK_NULL标记没有被定义，代码被编译了，在Q_CHECK_PTR表达式中的代码是不会被执行的（正确地，因为它仅仅用于调试目的）并且会分配一个疯狂的指针。

Qt库包含了几百个内部检查，当一些错误被检测出时，会打印警告信息。

Qt中的健全测试和作为结果的警告信息是有条件的，基于不同的调试标记的状态：

  • QT_CHECK_STATE：检测一致的/期望的对象状态
  • QT_CHECK_RANGE：检测变量范围错误
  • QT_CHECK_NULL：检测危险的空指针
  • QT_CHECK_MATH：检测危险的数学，比如被0除
  • QT_NO_CHECK：关闭所有的QT_CHECK_...标记
  • QT_DEBUG：使调试代码生效
  • QT_NO_DEBUG：关闭QT_DEBUG标记

默认情况下，QT_DEBUG和所有的QT_CHECK标记都是打开的。如果要关闭QT_DEBUG，请定义QT_NO_DEBUG。如果要关闭QT_CHECK标记，请定义QT_NO_CHECK。

实例：

  void f( char *p, int i )
  {
  #if defined(QT_CHECK_NULL)
      if ( p == 0 )
          qWarning( "f: Null pointer not allowed" );
  #endif

  #if defined(QT_CHECK_RANGE)
      if ( i < 0 )
          qWarning( "f: The index cannot be negative" );
  #endif
  }

普通的Bug

这是一个如此普通的bug，所以要在这里提到：如果你你在类生命中包含了Q_OBJECT宏并且运行了moc，但是忘记了把moc生成的对象代码连接到你的可执行程序中，你就会得到非常困惑的错误消息。

任何一个会提示缺乏vtbl、_vtbl、__vtbl或者和这个类似的连接错误都有可能是这样的问题。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt中的线程支持

Qt对线程提供了支持，基本形式有独立于平台的线程类、线程安全方式的事件传递和一个全局Qt库互斥量允许你可以从不同的线程调用Qt方法。

这个文档是提供给那些对多线程编程有丰富的知识和经验的听众的。推荐阅读：

  • Threads Primer: A Guide to Multithreaded Programming
  • Thread Time: The Multithreaded Programming Guide
  • Pthreads Programming: A POSIX Standard for Better Multiprocessing (O'Reilly Nutshell)
  • Win32 Multithreaded Programming

警告：所有的GUI类（比如，QWidget和它的子类），操作系统核心类（比如，QProcess）和网络类都不是线程安全的。

QRegExp使用一个静态缓存并且也不是线程安全的，即使通过使用QMutex来保护的QRegExp对象。

启用线程支持

在Windows上安装Qt时，在一些编译器上线程支持是一个选项。

在Mac OS X和Unix上，线程支持可以当你在运行configure脚本时添加-thread选项就可以生效了。在Unix平台上，多线程程序必须用特殊的方式连接，比如使用特殊的libc，安装程序将会创建另外一个库libqt-mt并且因此线程程序必须和这个库进行连接（使用-lqt-mt）而不是标准的Qt库。

在两个平台上，你都应该定义宏QT_THREAD_SUPPORT来编译（比如，编译时使用-DQT_THREAD_SUPPORT）。在Windows上，这个通常可以在qconfig.h写一个条目来解决。

线程类

最重要的类是QThread，也就是说要开始一个新的线程，就是开始执行你重新实现的QThread::run()。这和Java的线程类很相似。

为了写线程程序，在两个线程同时希望访问同一个数据时，对数据进行保护是很必要的。因此这里也有一个QMutex类，一个线程可以锁定互斥量，并且在它锁定之后，其它线程就不能再锁定这个互斥量了，试图这样做的线程都会被阻塞直到互斥量被释放。例如：

    class MyClass
    {
    public:
        void doStuff( int );

    private:
        QMutex mutex;
        int a;
        int b;
    };

    // 这里设置a为c，b为c*2。

    void MyClass::doStuff( int c )
    {
        mutex.lock();
        a = c;
        b = c * 2;
        mutex.unlock();
    }

这保证了同一时间只有一个线程可以进入MyClass::doStuff()，所以b将永远等于c * 2。

另外一个线程也需要在一个给定的条件下等待其它线程的唤醒，QWaitCondition类就被提供了。线程等待的条件QWaitCondition指出发生了什么事情，阻塞将一直持续到这种事情发生。当某种事情发生了，QWaitCondition可以唤醒等待这一事件的线程之一或全部。（这和POSIX线程条件变量是具有相同功能的并且它也是Unix上的一种实现。）例如：

    #include <qapplication.h>
    #include <qpushbutton.h>

    // 全局条件变量
    QWaitCondition mycond;

    // Worker类实现
    class Worker : public QPushButton, public QThread
    {
        Q_OBJECT

    public:
        Worker(QWidget *parent = 0, const char *name = 0)
            : QPushButton(parent, name)
        {
            setText("Start Working");

            // 连接从QPushButton继承来的信号和我们的slotClicked()方法
            connect(this, SIGNAL(clicked()), SLOT(slotClicked()));

            // 调用从QThread继承来的start()方法……这将立即开始线程的执行
            QThread::start();
        }

    public slots:
        void slotClicked()
        {
            // 唤醒等待这个条件变量的一个线程
            mycond.wakeOne();
        }

    protected:
        void run()
        {
            // 这个方法将被新创建的线程调用……

            while ( TRUE ) {
                // 锁定应用程序互斥锁，并且设置窗口标题来表明我们正在等待开始工作
                qApp->lock();
                setCaption( "Waiting" );
                qApp->unlock();

                // 等待直到我们被告知可以继续
                mycond.wait();

                // 如果我们到了这里，我们已经被另一个线程唤醒……让我们来设置标题来表明我们正在工作
                qApp->lock();
                setCaption( "Working!" );
                qApp->unlock();

                // 这可能会占用一些时间，几秒、几分钟或者几小时等等，因为这个一个和GUI线程分开的线程，在处理事件时，GUI线程不会停下来……
                do_complicated_thing();
            }
        }
    };

    // 主线程——所有的GUI事件都由这个线程处理。
    int main( int argc, char **argv )
    {
        QApplication app( argc, argv );

        // 创建一个worker……当我们这样做的时候，这个worker将在一个线程中运行
        Worker firstworker( 0, "worker" );

        app.setMainWidget( &worker );
        worker.show();

        return app.exec();
    }

只要你按下按钮，这个程序就会唤醒worker线程，这个线程将会进行并且做一些工作并且然后会回来继续等待被告知做更多的工作。如果当按钮被按下时，worker线程正在工作，那么就什么也不会发生。当线程完成了工作并且再次调用QWaitCondition::wait()，然后它就会被开始。

线程安全的事件传递

在Qt中，一个线程总是一个事件线程——确实是这样的，线程从窗口系统中拉出事件并且把它们分发给窗口部件。静态方法QThread::postEvent从线程中传递事件，而不同于事件线程。事件线程被唤醒并且事件就像一个普通窗口系统事件那样在事件线程中被分发。例如，你可以强制一个窗口部件通过如下这样做的一个不同的线程来进行重绘：

    QWidget *mywidget;
    QThread::postEvent( mywidget, new QPaintEvent( QRect(0, 0, 100, 100) ) );

这（异步地）将使mywidget重绘一块100*100的正方形区域。

Qt库互斥量

Qt库互斥量提供了从线程而不是事件线程中调用Qt方法的一种方法。例如：

  QApplication *qApp;
  QWidget *mywidget;

  qApp->lock();

  mywidget->setGeometry(0,0,100,100);

  QPainter p;
  p.begin(mywidget);
  p.drawLine(0,0,100,100);
  p.end();

  qApp->unlock();

在Qt中没有使用互斥量而调用一个函数通常情况下结果将是不可预知的。从另外一个线程中调用Qt的一个GUI相关函数需要使用Qt库互斥量。在这种情况下，所有可能最终访问任何图形或者窗口系统资源的都是GUI相关的。使用容器类，字符串或者输入/输出类，如果对象只被一个线程使用就不需要任何互斥量了。

告诫

当进行线程编程时，需要注意的一些事情：

  • 当使用Qt库互斥量的时候不要做任何阻塞操作。这将会冻结事件循环。

  • 确认你锁定一个递归QMutex的次数和解锁的次数一样，不能多也不能少。

  • 在调用除了Qt容器和工具类的任何东西之前锁定Qt应用程序互斥量。

  • 谨防隐含地共享类，你应该避免在线程之间使用操作符=()来复制它们。这将会在Qt的未来主要的或次要的发行版本中进行改进。

  • 谨防那些没有被设计为线程安全的Qt类，例如，QPtrList的应用程序接口就不是线程安全的并且如果不同的线程需要遍历一个QPtrList，它们应该在调用QPtrList::first()之前锁定并且在到达终点之后解锁，而不是在QPtrList::next()的前后进行锁定和解锁。

  • 确认只在GUI线程中创建的继承和使用了QWidget、QTimer和QSocketNotifier的对象。在一些平台上，在某个不是GUI线程的线程中创建这样的对象将永远不会接受到底层窗口系统的事件。

  • 和上面很相似，只在GUI线程中使用QNetwork类。一个经常被问到的问题是一个QSocket是否可以在多线程中使用。这不是必须得，因为所有的QNetwork类都是异步的。

  • 不要在不是GUI线程的线程中试图调用processEvents()函数。这也包括QDialog::exec()、QPopupMenu::exec()、QApplication::processEvents()和其它一些。

  • 在你的应用程序中，不要把普通的Qt库和支持线程的Qt库混合使用。这也就是说如果你的程序使用了支持线程的Qt库，你就不应该连接普通的Qt库、动态的载入普通Qt库或者动态地连接其它依赖普通Qt库的库或者插件。在一些系统上，这样做会导致Qt库中使用的静态数据变得不可靠了。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt插件HOWTO

Qt提供了一个简单地插件接口，可以轻松地生成作为独立组件的定制数据库驱动、图象格式、文本编解码器（text codec）、风格（style）和部件。

警告：Qt 3.0.5对插件的一些方面做了改变，具体涉及到装载、路径操作和库版本。这些变化的结果是，Qt 3.0.4及以前版本编译的插件都不能用于Qt 3.0.5及以后版本。

写一个插件通过以下方式完成：写适当的插件基类的子类，实现几个函数，再添加一个宏。

一共有五个插件基类。派生的插件缺省保存于标准插件目录。

基类 | 缺省路径
QImageFormatPlugin | $QTDIR/plugins/imageformats
QSqlDriverPlugin | $QTDIR/plugins/sqldrivers
QStylePlugin | $QTDIR/plugins/styles
QTextCodecPlugin | $QTDIR/plugins/codecs
QWidgetPlugin | $QTDIR/plugins/designer

假设你有一个新的风格类，叫做'MyStyle'，你要把它做成插件的形式。需要的代码直截了当：

    class MyStylePlugin : public QStylePlugin
    {
    public:
        MyStylePlugin() {}
        ~MyStylePlugin() {}

        QStringList keys() const {
            return QStringList() << "MyStyle";
        }

        QStyle* create( const QString& key ) {
            if ( key == "MyStyle" )
                return new MyStyle;
            return 0;
        }
    };

    Q_EXPORT_PLUGIN( MyStylePlugin )

构造器和解构器不需要做什么，空的就可以。有两个虚函数一定要实现。第一个是keys()，它返回在插件中实现的类的一个字符串列表。（我们在上面的例子中刚刚实现了一个类。）第二个是一个函数，它返回所要的类的一个对象（或者0，如果插件被要求生成一个不存在的类的对象）。对于QStylePlugin来说，这第二个函数叫做create()。

可以在一个插件里实现任意数目的插件子类，只要他们都是由同一个基类，比如说，QStylePlugin，派生出来的。

对于数据库驱动、图象格式、定制部件和文本编解码器，不需要显式的对象生成过程。Qt会按需求查找并生成他们。风格则是例外，因为你可能想以代码显式地设置一个风格。应用一个风格，可以使用类似代码：

    QApplication::setStyle( QStyleFactory::create( "MyStyle" ) );

有的插件类还需要实现其他函数。关于一个QWidgetPlugin的完全例子，可参见Qt设计器手册中'生成定制部件'一章的'生成定制部件'节。这个例子实现了额外的函数，以把该插件集成到Qt设计器中去。QWidgetFactory类提供了关于QWidgetPlugin的附加信息。

关于每种类型的插件必须要实现哪些虚拟函数，详见该类的文档。

Qt的应用自动辨识哪些插件可用，因为插件都是保存在标准插件子目录下的。为此，应用不需要任何查找和装载插件的代码，既然Qt已自动处理了。

插件的缺省目录是$QTDIR/plugins，每种类型的插件在那种类型的子目录下，比如说，风格（styles）。如果你想要你的应用使用插件但不要标准插件路径，可以让你的安装程序决定你要为插件使用的路径，然后保存该路径，比如说使用QSettings，以使应用在运行时可以读取。之后应用可以用该路径调用QApplication::addLibraryPath()，就可以使用你的插件了。注意，路径的最后部分，也就是说，styles、widgets等等，不能改变。

应用包括一个插件的正规方法是，要么把插件与应用一起编译，要么把插件编译为DLL（或者so或者其他平台指定的库类型），像其他库那样使用。如果要让插件可装载，一个方法是，生成一个应用下的子目录，例如，appdir/plugins/designer，把插件放置到该目录下。

装载与校验插件

在装载插件时，Qt库做了一些稳健的检查，以确定插件是否可以装载和使用。这一点保证了多重版本的能力和分头所安装的Qt库的配置。

  • 与高一点的主版本和／或次版本的Qt库链接的插件，不能被低的主版本和／或次版本的库所装载。（译者注：补丁版本不限）

    原因解释：

    依靠新的Qt库而链接的插件可能使用了一些旧版本没有的新特性。Trolltech有一项政策：只在次级发布（minor release）之间添加新特性和API，这就是为什么本测试只看主版本号和次版本号，不看补丁级版本号的缘故。

  • 依靠带有线程支持的Qt库而链接的插件，只能被带有线程支持的Qt库所装载。

    原因解释：

    线程和非线程的Qt库有不同的名称。带有线程支持的库装载一个依靠不带有线程支持的Qt库而链接的插件，将会导致在内存中同时有同一库的两个版本。在UNIX系统中，这会导致非线程Qt库被装载。这时，Qt库中的所有静态对象的构造器都会被调用第二次，但是它们是对已经在内存中的对象进行操作。没有办法绕过这一点，因为这是对象二进制格式的一个特征：已经被线程Qt库定义的静态符号，不能在被非线程Qt库被装载的时候被替换或者拷贝。

  • 依靠不带有线程支持的Qt库而链接的插件，只能被不带有线程支持的Qt库所装载。

    原因解释：

    参见上面的解释。

  • 从Qt 3.0.5开始，Qt库与所有插件都使用联编关键字（build key）来联编。Qt库中的联编关键字被与插件中的联编关键字对照，如果相符，插件就被装载。如果联编关键字不符，Qt库就拒绝装载该插件。

    原因解释：

    参见下面对于build key的解释。

联编关键字（build key）

联编关键字包含一下信息：

  • 体系结构（Architecture）、操作系统和编译器。

    原因解释：

    在同一编译器的不同版本并不产生二进制兼容代码的场合，编译器的版本也体现在联编关键字里。

  • Qt的配置。这个配置是一个列表，包括了影响库中可用到的API的那些缺少的特性。

    原因解释：

    两个同一版本的Qt库的不同配置不是二进制兼容的。装载插件的Qt库使用这个（缺少的）特性列表来判断插件是不是二进制兼容的。

    注意：也存在这种情况，插件可以使用在两个不同配置里可用到的特性。但是，编写插件的开发者需要知道，哪些特性在他们的插件和Qt的公用工具类中都在被使用。Qt库在装载插件时会需要复杂的特性与依赖性的查询确认。这些需求给开发者添了一个不必要的负担，也增加了装载插件的系统开销。为了减少开发时间，降低应用的运行时消耗，可以使用对联编关键字的简单字符串比较。

  • 可选地，可以在配置脚本命令行指定一个附加的字符串。

    原因解释：

    在发布带有应用的Qt库的二进制时，这给开发者提供了一个办法，来编写只能被插件以之链接的那个库所装载的插件。

插件与线程应用

如果你想联编一个使用线程Qt库的插件（不管插件本身是否使用线程），你必须使用线程环境。具体说来，你必须用线程Qt库链接插件，必须用该库联编Qt设计器。你用于插件的.pro文件必须包括这一行：

    CONFIG += thread

警告：不要在应用中混用一般的Qt库与线程Qt库。如果你的应用使用了线程Qt库，你不应该用一般Qt库链接你的插件，也不应该动态装载一般Qt库或者动态装载依赖一般Qt库的另一个库，比如一个插件。在一些系统中，混用线程与非线程库或者插件会破坏（corrupt）Qt库中使用的静态数据。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


Pictures of Most Qt Widgets

Most of these widgets are shown in either Motif or Windows style. All widgets are supported in both styles (and other styles), but for clarity we just present a selection.

Below we have three views seperated by QSplitters. At the top-left there's a QListBox, at the top-right there's a QListView with a QHeader and two QScrollBars. And at the bottom there's a QIconView.

Below we present a QMainWindow which has a QMenuBar and some QToolBars that contain various widgets, e.g. QToolButtons and QComboBoxes. The central widget is a QWorkspace which is used for MDI window management and which contains an MDI-Window featuring a QTextEdit. At the bottom you see a QStatusBar and at the bottom-right a QSizeGrip.

The image below shows a QFileDialog. On the Macintosh and Windows platforms you can either use a QFileDialog or the native file dialog. This is explained in the QFileDialog class documentation.

Below is a QPrintDialog. On Macintosh and Windows the native print dialog is used, but for other platforms we provide QPrintDialog. Use QPrinter::setup() for portability instead of the QPrintDialog if you need to be platform independent.

Below is a QFontDialog.

Windows

The screenshot below shows a QColorDialog.

Messages are presented using QMessageBoxes, as shown below.

The image below shows a QProgressDialog. The QProgressBar can also be used as a separate widget.

In the screenshot below we have a QGroupBox that contains a QLineEdit, a read-only QComboBox and an editable QComboBox.

The screenshot below shows a QPopupMenu.

In the screenshot below there's a QButtonGroup containing four QRadioButtons and two QCheckBoxes.

The screenshot below shows a QTabDialog. The tabs (QTabBar) or the more convenient class QTabWidget, which combines a tab bar with the pages, can be used separately. In the visible page you see a QLabel, the range controls QSlider and QSpinBox and below a QLCDNumber. In the bottom row there are some QPushButtons.

In the screenshot below there's a QTextBrowser displaying a HTML page. See also QTextEdit.


Qt的工具

Qt提供了几种命令行和图形工具来减轻和加速开发过程。每一种工具都在这里列出，并给出它们的文档的链接。

  • Qt设计器——可视化地设计视窗
  • Qt语言学家，lupdate和lrelease——翻译应用程序使之能够进入国际市场
  • Qt助手——快速地发现你所需要的帮助
  • qmake——由简单的宇平台无关的项目文件生成Makefile
  • qembed——转换数据，比如把图片转还为C++代码
  • qvfb——在桌面上运行和测试嵌入式应用程序
  • makeqpf——为嵌入式设备提供预先做好的字体
  • moc——元对象编译器
  • uic——用户界面编译器
  • qtconfig——一个基于Unix的Qt配置工具，这里是在线帮助

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt设计器手册

前言

创建一个Qt应用程序

创建含有工具栏和菜单的主窗口

走近设计器

派生类和动态对话框

创建自定义窗口部件

创建数据库应用程序

定制和集成Qt设计器

参考：快捷键

参考：菜单选项

参考：工具栏按钮

参考：对话框

参考：向导

参考：窗口

参考：.ui文件格式

Copyright © 2002 Trolltech Trademarks 译者:hackerjun
Qt 3.0.5版


前言

介绍

这本参考手册是有关于Qt设计器的，Qt设计器是用来设计和实现用户界面并能够在多平台下使用的一种工具。Qt设计器可以使用户界面设计实验变得简单。在任何时候你可以要求所生成的代码去重建Qt设计器产生的用户界面文件，并可以根据你的喜好来改变你的设计。假如你使用的是先前的版本，你将发现在新的版本下自己可以立即进入工作，因为新的版本在界面上基本没有什么变化。但是你将发现根据你们的反馈而开发出的新的部件和新的或者改进的功能。

Qt设计器帮助你使用部局工具在运行时自动的移动和缩放你的部件（Windows中的术语控件）来构建用户界面。最终界面是既好用又好看，使最终用户拥有一个舒适的操作环境并且能够方便的进行参数选择。Qt设计器支持信号和槽机制以使部件间能够进行有效的通信。Qt设计器包含一个代码编辑器，使你能够在合成的代码里面嵌入自己定制的槽。那些更喜欢使用手工方法分解合成代码的朋友也能够继续使用基类，因为从第一版的Qt设计器开始就把这些基类移植进去了。

这本手册通过讲述开发例程来向你介绍Qt设计器。一开始的六章是设计指南，而且各自间都尽可能设计成是独立的。接下来要介绍的是除了首章以外的每一章，并假定你已经熟悉了第一章的内容，该章包含使用Qt设计器创建一个Qt应用程序的基础。以下是便各章的简要概述：

  • 第一章，创建一个Qt应用程序，通过带着你一步一步的创建一个小但功能完整的应用程序来介绍Qt设计器的使用。按照着这种方法你将学到如何创建一个窗体并且向窗体中添加部件。在你阅读这一章的过程中你将使用窗体和属性编辑器来定制你的应用程序，并且学习怎样使用部局工具来对一个窗体进行部局。你也将学到如何使用信号和槽机制和Qt设计器的内建代码编辑器来制造应用程序的各种功能。我们也将解释如何使用qmake来生成Makefile，以致于你能够编译和运行应用程序。

  • 第二章，创建含有工具栏和菜单的主窗口，我们将创建一个简单的文本编辑器。通过写这个应用程序你将学到如何使用菜单栏和工具栏来创建一个主窗口。我们将看到如何使用Qt的内建功能来处理一般任务(e.g. 复制粘贴操作)还将看到如何为我们自己的菜单栏选项和工具栏按钮创建我们自己的功能。

  • 第三章，走近设计器，提供有关Qt设计器的信息如相关的开发应用程序，并且还对Qt设计器背后的一些基本原理进行解释。

  • 第四章，派生类和动态对话框， 将展示如何派生一个窗体；这将让你清楚的通过执行关键代码的功能来分解用户界面。本章中还附加有关qmake和 uic的信息。本章也将阐述如何使用QWidgetFactory把.ui文件放进你的应用程序从而动态的加载对话框和如何访问这些对话框的部件和派生部件。

  • 第五章，创建自定义窗口部件，告诉你如何才能创建自定义部件。既有在第一版的Qt设计器中就被介绍的简单方法，又有像利用插件这种新的更有效的的方法都在这一章里被介绍了。

  • 第六章， 创建数据库应用程序介绍了Qt的SQL类并且带着你通过一个实例来演示如何执行查询和如何设置主要关系的细节，深入讲解和处理外关键字。

  • 第七章，定制和集成Qt设计器，聚焦Qt设计器本身，向你展示如何定制设计器，如何使用可视化工作室集成设计器和如何创建一个Makefiles。

这剩下的章节提供了一些参考资料，用以讲述Qt设计器的菜单选项、工具栏、快捷键以及对话框等的细节。

你所应该知道的

该手册假定你已经有了一些有关C++和Qt应用程序开发框架的基础。假如你需要学习C++或者Qt，这儿有大量的C++的书可供使用和少量的但是数量却在不断增长的有关Qt的书。你可以尝试一下大量伴随着Qt的联机文档和许多例程。

企业版的Qt包含了SQL模块。在创建数据库应用程序一章里我们演示了如何使用Qt设计器来编写SQL应用程序；这一章需要一些SQL和关系数据库的知识。

Qt设计器中的新东西

该版本的Qt设计器较其前一版本来说增加了更加多的功能。自己定制的槽功能代码可以直接在Qt设计器中编辑；操作工具栏、菜单栏就可以创建主窗口了；部局可以结合使用分解器；一些插件还允许你把大量的自定义部件进行打包并且在Qt设计器中可以使用他们。从对用户界面微小的改善到提高效率还有很多其它增强功能被结使在里面，例如在一个应用程序里的所有窗体可以有效的共享像素映射。

该版本的Qt设计器创建的工程文件使得开关在一个应用程序中的所有窗体变得十分简单，而且仍然保持了一个通常的数据库设置和映象。通过对派生类的全面支持，为直接在Qt设计器中编写代码带来了很多的益处，这些知识已经全面涵盖在走近设计器一章中了。

还介绍了一个新的库libqui，该库允许你在运行时从Qt设计器的.ui文件中自动加载对话框。这允计你提供给你的应用程序用户相当可观的自定义界面自由度，否则就需要使用C++了。

如果你仅仅想要一个简单而功能强大的单对话框可视设计工具，虽然新版本的Qt设计器介绍了新的进阶和技术但你可以忽略这些方面并且正确的使用与Qt 2.x相同的方法。

Qt设计器

反馈

如果你关于这个手册有一些注释、建议、批评或者适当的赞美，请访问doc@trolltech.com让我们知道。关于Qt或者Qt设计器的bug报告可以发送至Qt-bugs@trolltech.com。你也许也想要加入专门由开发者阅读和捐献的Qt-interest邮件列表；请访问http://www.trolltech.com以了解更多的细节。

[Qt设计器首页] [下一章：创建一个Qt应用程序]

Copyright © 2002 Trolltech Trademarks 译者:hackerjun
Qt 3.0.5版


Creating a Qt Application

Starting and Exiting Qt Designer

Qt Designer is controlled in the same way as any other modern desktop application. To start Qt Designer under Windows click the Start button and click Programs|Qt X.x.x|Designer. (X.x.x is the Qt version number, e.g. 3.0.0.) If you're running a Unix or Linux operating system you can either double click the Qt Designer icon or enter designer & in an xterm.

When you've finished using Qt Designer click File|Exit; you will be prompted to save any unsaved changes. Help is available by pressing F1 or from the Help menu.

To get the most benefit from the tutorial chapters we recommend that you start Qt Designer now and create the example applications as you read. Most of the work involves using Qt Designer's menus, dialogs and editors, with only small amounts of code to type in.

When you start Qt Designer, by default, you will see a menu bar and various toolbars at the top. On the left hand side are three windows, the first is the Files window, the second is the Widgets and Source window (the Object Explorer) and the third is the Properties window. The Files window lists the files and images associated with the project; to open any form single click it in the Files list. The Widgets and Source window lists the current form's widgets and slots. The Properties window is used to view and change the properties of forms and widgets. We will cover the use of Qt Designer's windows, dialogs, menu options and toolbar buttons as we create example applications.

In this chapter we will build an application called 'multiclip' which allows you to store and retrieve multiple text clippings to and from the clipboard.

The Multiclip Application

Creating a New Project

Whenever you create a new application we strongly recommend that you create a project file and open the project rather than individual .ui files. Using a project has the advantage that all the forms you create for the project are available via a single mouse click rather than having to be loaded individually through file open dialogs. An additional benefit of using project files is that they allow you to store all your images in a single file rather than duplicate them in each form in which they appear. See The Designer Approach chapter's Project management section for detailed information on the benefits of using project files.

Start Qt Designer if you haven't already. Click File|New to invoke the New File dialog. Click the 'C++ Project' icon, then click OK to invoke the Project Settings dialog. You need to give the project a name, and we recommend that you put each project in its own subdirectory. Click the ellipsis ... button to invoke the Save As dialog and navigate to where you want to put the new project. Click the Create New Folder toolbar button to create the 'multiclip' directory. Double click the 'multiclip' directory to make it the current directory. Enter a file name of 'multiclip.pro', and click the Save button. The 'Project File' field of the Project Settings dialog will have the path and name of your new project; click OK to create the project.

Creating a New Project

The name of the current project is shown in the Files toolbar which is the top left toolbar by default. Once we have a project we can add forms and begin to build our application. (See Customizing Qt Designer for information on changing Qt Designer's toolbars and windows to suit your preferences.)

Creating a New Form

Click File|New to invoke the New File dialog. Several default forms are supplied but we will use the default Dialog form, so just click OK. A new form called 'Form1' will appear. Note that the new form is listed in the Files list and the Properties window shows the form's default property settings.

Click the Value beside the name property and change the form's name to 'MulticlipForm'. Change the form's caption to 'Multiclip'. The properties are ordered in accordance with the inheritance hierarchy, and caption is roughly in the middle of the property editor. Save the form: click File|Save, enter the name 'multiclip.ui', then click the Save button.

Creating a New Form

Using the Property Editor

The Property Editor has two columns, the Property column which lists property names and the Value column which lists the values. Some property names have a plus sign '+' in a square to their left; this signifies that the property name is the collective name for a set of related properties. Click the form to make the Property Editor show the form's properties. Click the sizePolicy property's plus sign; you will see four properties appear indented below sizePolicy, hSizeType, vSizeType, horizontalStretch and verticalStretch. These properties are edited in the same way as any other properties.

Property Editor

Some properties have simple values, for example, the name property has a text value, the width property (within minimumSize for example) has a numeric value. To change a text value click the existing text and type in your new text. To change a numeric value click the value and either type in a new number, or use the spin buttons to increase or decrease the existing number until it reaches the value you want. Some properties have a fixed list of values, for example the mouseTracking property is boolean and can take the values True or False. The cursor property also has a fixed list of values. If you click the cursor property or the mouseTracking property the value will be shown in a drop down combobox; click the down arrow to see what values are available. Some properties have complex sets of values; for example the font property. If you click the font property an ellipsis button (...) will appear; click this button and a Select Font dialog will pop up which you can use to change any of the font settings. Other properties have ellipsis buttons which lead to different dialogs depending on what settings the property can have. For example, if you have a lot of text to enter for a text property you could click the ellipsis button to invoke the multi-line text editor dialog.

The names of properties which have changed are shown in bold. If you've changed a property but want to revert it to its default value click the property's value and then click the red 'X' button to the right of the value. Some properties have an initial value, e.g. 'TextEdit1', but no default value; if you revert a property that has an initial value but no default value (by clicking the red 'X') the value will become empty unless the property, e.g. name, is not allowed to be empty.

If multiple widgets are selected, the property editor shows the properties that the selected widgets have in common. Changing one of these properties will cause all the selected widgets to have this property changed.

The property editor fully supports Undo and Redo (Ctrl+Z and Ctrl+Y, also available from the Edit menu).

Adding Widgets

The multiclip application consists of a text box to display the current clipboard text (if any), a list box showing the previous clippings, a length indicator, a checkbox and buttons. If you run the application and resize it all the widgets will scale properly.

The Qt Designer approach to laying out a form is to place the required widgets on the form in the approximate positions that they should occupy and then use the layout tools to size and position them correctly. We'll now add the multiclip form's widgets.

  1. We'll start with the current clipping text box. Click the Text Label toolbar button and click towards the top left of the form. (If you hover the mouse over a toolbar button its name will appear in a tooltip.) We won't bother renaming the label since we'll never refer to it in code; but we need to change its text, so change its text property to 'Current Clipping'. (See the Using the Property Editor sidebar for an explanation of the property editor.)

    Click the Line Edit toolbar button and click towards the top right of the form. Use the Property Editor to change the widget's name to 'currentLineEdit'.

  2. Now we'll add another label and the list box. Click the Text Label toolbar button and click below the Current Clipping label. Change the text property to 'Previous Clippings'. Don't worry about positioning the widgets precisely, nor about the fact that they are the wrong size; the layout tools (covered in the next section) will take care of this.

    Click the List Box toolbar button and click the form below the 'Previous Clippings' label. Change the list box's name to 'clippingsListBox'. By default Qt Designer creates list boxes with a single initial value of 'New Item'. We don't want this value (we'll be populating our list box in code later), so we need to remove the value. Right click the list box then click the Edit menu item on the popup menu to invoke the listbox's value editor dialog. Click Delete Item to delete the default item, then click OK. (See the Value Editors sidebar.)

  3. We want to know the length of the current clipping so we'll add a label and an LCD Number widget.

    Click the Text Label toolbar button and click below the Line Edit. Change its text property's value to 'Length'. Click the LCD Number toolbar button and click below the length label. Change the LCD Number's name to 'lengthLCDNumber'.

  4. Multiclip can be made to detect clipboard changes and automatically add new clippings. We want the user to have control over whether this should happen or not so we will provide a check box which they can use to indicate their preference.

    Click the Check Box toolbar button and click below the LCD Number. Change the checkbox's name to 'autoCheckBox' and its text to 'A&uto Add Clippings'. Note that the accel property automatically changes to Alt+U because the ampersand in the text signifies a keyboard shortcut.

  5. The last widgets we require are the buttons. One way to add the same kind of widget multiple times is to add one, copy it, then paste repeatedly. We will use another approach.

    Double click the Push Button toolbar button; now click below the checkbox to place a button. Click below the button we've just added to add a second button. Add a third and fourth button. Now click the Pointer toolbar button to switch off automatically adding the same widget. Change the first button's name to 'addPushButton' and its text to '&Add Clipping'. Change the second button's name to 'copyPushButton' and its text to '&Copy Previous'. Change the third button's name and text properties to 'deletePushButton' and '&Delete Clipping' respectively. Similarly change the fourth button's name and text to 'quitPushButton' and '&Quit'.

All our widgets have been placed on the form with their properties changed to suit our application's needs. In the next section we will use Qt Designer's layout tools to size and position the widgets correctly and in such a way that when the user resizes the form the widgets will scale properly.

Adding Widgets to the Form

Value Editors

Whilst the Property Editor is used to customize the generic properties of widgets, value editors are used to edit values held within instances of particular widgets. For example a QLineEdit can only contain a single line of text, but a QListBox can contain any number of items each of which may be a line of text, a pixmap, or both. To invoke a widget's value editor double click the widget. (Alternatively right click the widget and a popup menu will appear; if the first menu item is 'Edit', you can click this to access the widget's value editor dialog.) Different widgets have different value editors. See the Value Editors chapter for more details.

Laying Out Widgets and Previewing

Introduction to Layouts

Layouts work by grouping together widgets and groups of widgets, horizontally, vertically or in a grid. Widgets that are laid out together horizontally or vertically can be grouped either with a Layout or with a Splitter; the only difference is that a user can manipulate a Splitter themselves.

If we want to lay out some widgets side by side we would select them and then click the Lay Out Horizontally toolbar button. If we want our widgets to be lined up one above the other we would use the Lay Out Vertically toolbar button. Once we've grouped some widgets together we can then lay out the groups in relation to each other, again using vertical, horizontal or grid layouts. Once we have a collection of laid out groups we then click on the form itself and lay out the groups within the form using one of the layout buttons.

Some widgets will grow to fill the available space, vertically or horizontally or both ways. Buttons and line edits will fill horizontal space for example, whereas a ListView will fill space in both directions. The easiest way to achieve the layout you want is to use Qt Designer's layout tools. When you apply a layout to some widgets in some situations the widgets may not lay out the way you want. If a widget does not fill up enough space try changing its sizePolicy to Expanding. If a widget takes up too much space one approach is to change its sizePolicy, and another approach is to use a Spacer to consume excess space.

Spacers have no visual appearance on the running form and are used purely to insert space between widgets or groups of widgets. Suppose you have a widget that takes up too much space. You could break the layout and resize the widget to make room for a spacer. Then you would insert the spacer and layout the spacer with the widgets and the spacer will consume the excess space. If the spacer doesn't take up the right amount of space you can change its sizePolicy for finer control.

The best way to learn about layouts and spacers is to try them out. Experimenting with layouts is easy. If you make any changes that you aren't happy with you can easily undo them by clicking Edit|Undo or by pressing Ctrl+Z. In the next section we'll lay out our multiclip example step-by-step.

Laying Out Widgets

Layouts provide a means of grouping widgets and groups of widgets together in horizontal and vertical pairs and in grids. If you use layouts your forms and the widgets they contain will scale automatically when the user resizes the window. This is better than using absolute sizes and positions since you don't have to write any code to achieve the scaling and your users can make the most of their screen size whether they have a laptop or a very large screen desktop machine. Layouts use standard sizes for margins and widget spacing which helps give your applications a consistent and proportional look without requiring any effort on your part. Layouts are also easier and faster to use than absolute positioning; you can just place your widgets on the form in approximate positions and leave the layout tools to size and scale the widgets correctly.

Selecting Widgets and Inserting Widgets

To select an individual widget, either click the widget itself or click its Name in the Object Explorer window. To select a group either click a fraction outside its red outline or click its Name in the Object Explorer window. To select multiple widgets or groups, click the form to deselect any selected widgets, then Ctrl+Click one widget or group then drag the rubber band so that it touches the other widgets or groups that you want to select. This technique is particularly useful for selecting widgets that are inside another widget. For example to select the radio buttons in a button group but not the button group itself you would click the form then Ctrl+Click one of the radio buttons and drag the rubber band to touch the other radio buttons.

If we want to insert a widget into a gap between widgets which are in a layout we can click the toolbar button for the new widget and then click in the gap. Qt Designer will ask us if we want to break the layout and if we click Break Layout the layout will be broken and our widget inserted. We can then select the widgets and groups we want to lay out and lay them out again. The same effect can be achieved by clicking the group and either clicking the Break Layout toolbar button or pressing Ctrl+B.

The layout we want to achieve is to have the current clipping label and currentLineEdit side by side at the top of the form. We want the previous clippings label and the clippingsListBox to occupy the left hand side of the form with the remaining widgets in a column on the right. We want to divide left and right with a splitter and make the left hand side larger by default. We'll leave the sizing of the widgets to Qt Designer. The layout controls are in the Layout toolbar. (By default this is the fourth toolbar counting left to right.) We'll now lay out the widgets we've placed on the form.

  1. Click the current clipping label and Shift+Click the currentLineEdit Line Edit. (Shift+Click means hold down the shift key whilst clicking; this will ensure that Qt Designer performs multiple selections.) Most of the layout toolbar buttons will now be available. Click the Lay Out Horizontally toolbar button. (If you hover the mouse over a toolbar button a tooltip giving the button's name will appear.) The two widgets will be moved together with a thin red line surrounding them. It doesn't matter that the widgets aren't the right size or in exactly the right place; as we progress with the layout Qt Designer will size and place them correctly.

    Layout Current Clipping Label and currentLineEdit

  2. Click the Previous Clippings label and Shift+Click the clippingsListBox. Click the Lay Out Vertically toolbar button.

  3. We want the remaining widgets to be grouped together vertically. We could Shift+Click each one but instead click the form above the Length label, then drag until the Length label, the LCD Number, the check box and all the buttons are all touching the rubber band (a black outline rectangle) that appears when you drag. Release the mouse, and all the remaining widgets should be selected. If you missed any Shift+Click them. Now click the Lay Out Vertically toolbar button.

    Selecting a Group of Widgets

We now have three groups of widgets which must be laid out in relation to each other and then laid out in relation to the form itself.

Groups of Layed Out Widgets

  1. Shift+Clicking is used to select individual widgets. To select a group we must click the form to deselect any selected widgets, then Ctrl+Click the group and drag so that the rubber band touches the groups we want to lay out and then release. With the buttons and other widgets already laid out and selected, Ctrl+Click the list box and drag the rubber band over the one of the buttons, then release. Both groups should now be selected. Click the Lay Out Horizontally (in Splitter) toolbar button.

    Layout Groups of Widgets

  2. We now have two groups, the top one with the Current Clipping label and the line edit and the group we've just created with the list box, buttons and other widgets. We now want to lay these out in relation to the form. Click the form and click the Lay Out Vertically toolbar button. The widgets will be resized to fill the entire form.

    Lay out Widgets in Relation to the Form

Unfortunately the Length label and the LCD Number take up far too much space, so we will have to revise the layout. With experience you will find that you do not need to rework layouts very often. We will insert a spacer which will use the extra space.

  1. First we must make some room for the spacer. Click the LCD Number to select it. Now click the Break Layout toolbar button. Move the LCD Number up a little bit, there's no need to be exact we just want to create some space below it.

  2. Now we'll add the spacer. Click the Spacer toolbar button, then click the form in the space you've created between the LCD Number and the check box. A popup menu with two options, Horizontal and Vertical, will appear; click Vertical. We choose vertical because we want the spacer to consume excess vertical space.

    Adding a Vertical Spacer

  3. We need to regroup the buttons and other widgets in a vertical group. Drag the mouse from near the bottom right of the form so that the rubber band includes or touches the buttons, the check box, the spacer, the LCD Number and the Length label; then release. If you selected any other widgets by mistake, click the form and try the drag again. Click the Lay Out Vertically toolbar button.

  4. We now have three groups as we had before, only this time with the small addition of the spacer. Select the list box and the buttons by clicking the form, dragging and releasing once the rubber band covers or touches both groups. Click Lay Out Horizontally (in Splitter) to regroup them with the splitter.

  5. The last step is to lay out the form itself. Click the form and click Lay Out Vertically. The form should now be laid out correctly.

    Lay Out the Form

There are two small deficiencies in the layout that we have achieved. Firstly the list box and buttons take up an equal width whereas we'd rather have the list box take up about three quarters of the width. Secondly the Length label, the check box and the buttons extend right up to the splitter. They would look more attractive if there was a little bit of space separating them from the splitter.

Expanding the list box half of the splitter would require us to add an init() function with the following code:

    void MulticlipForm::init()
    {
    QValueList< int > sizes;
    sizes << 250 << 40;
    Splitter->setSizes( sizes );
    }

We won't add this code now since we'll deal with the code when we come to implement the application's functionality later in the chapter.

We will create some space around the splitter by changing the margins of the layout groups that it joins together. To click a layout either click a fraction above the layout's top red line or click the layout's name in the Object Explorer (the Widgets and Source window). (See Object Explorer Window sidebar for an explanation of the Object Explorer window.) Click the layout that contains the list box, and change the layoutMargin property to 6, then press Enter. Click the layout that contains the buttons and other widgets, and change its layoutMargin to the same value in the same way.

The Object Explorer

View the Object Explorer (Widgets and Source) window by clicking Window|Views|Object Explorer. The Object Explorer has two tabs, the Widgets tab which shows the object hierarchy, and the Source tab which shows the source code you have added to the form. Clicking the name of a widget in the Widget tab will select the widget and show its properties in the Property Editor. It is easy to see and select widgets in the Object Explorer which is especially useful for forms that have many widgets or which use layouts.

Object Explorer

In the original version of Qt Designer if you wanted to provide code for a form you had to subclass the form and put your code in the subclass. This version fully supports the subclassing approach, but now provides an alternative: placing your code directly into forms. Writing code in Qt Designer is not quite the same as subclassing, for example you cannot get direct access to the form's constructor or destructor. If you need code to be executed by the constructor create a slot called void init(); if it exists it will be called from the constructor. Similarly, if you need to be executed before destruction create a slot called void destroy(). You can also add your own class variables which will be put in the generated constructor's code, and you can add forward declarations and any includes you require. To add a variable or declaration right click the appropriate item, e.g. Class Variables, then click New then enter your text, e.g. QString fileName. If one or more items exist right clicking will popup a two item menu with New and Delete as options. To edit code just click the name of a function to invoke the code editor. Code editing and creating slots are covered later.

If you subclass the form you create your own .cpp files which can contain your own constructor, destructor, functions, slots, declarations and variables as your requirements dictate. (See Subclassing for more information.)

In the example we used Qt Designer's layout tools to lay out our widgets. We will use the layout tools again in the examples presented in later chapters. If you want to use absolute positioning, i.e. to place and size your widgets with exact pixel sizes you can easily do so. To place a widget click it and drag it to the desired position. To resize it, click it, and drag one of the sizing handles (these are small blue squares) until the size is right. To stop the widget from resizing when the window is resized change the hSizeType and vSizeType (these are properties within the sizePolicy property), to Fixed.

Previewing

Although Qt Designer presents an accurate view of our forms we often want to see what a form looks like when it is run. It is also useful to be able to test out some aspects of the form, for example how the form scales when resized or how the splitters work in practice. If we're building multiplatform applications it is also useful to see how the form will look in different environments.

To see a preview either click Preview|Preview Form or press Ctrl+T. To leave preview mode close the window in the standard way for your environment. To view previews which show how the application will look on other platforms click the Preview menu and click one of the menu items that drop down.

Preview the multiclip form and try out the splitter and try resizing the form. In all probability you moved the splitter to the right to reduce the size of the buttons to make the form more attractive. The splitter seemed like a good idea but in practice we want the buttons and the other widgets on the right hand side to take up a fixed amount of space. Qt Designer makes changing layouts very easy, so we'll fix this straight away.

Previewing Multiclip

Click the splitter then click the Break Layout toolbar button; the splitter will be removed. Now click the form itself, near the bottom, and drag the rubber band so that it touches both the list box and some of the buttons, then release. The list box group and the buttons group are selected; click the Lay Out Horizontally toolbar button. Click the form then click the Lay Out Vertically toolbar button. The form is now laid out as we require. Preview the form (press Ctrl+T) and try resizing it.

It would be useful if you experimented further with layouts since they work visually and are best learnt through practice. To remove a layout click the Break Layout toolbar button; to apply a layout select the relevant widgets or groups and click a layout button. You can preview as often as you like and you can always undo any changes that you make.

Let's try an experiment, to see how the grid layout works. Click the list box, then press Ctrl+B (break layout). Click one of the buttons and press Ctrl+B. Click the form at the bottom and drag until all the widgets are touching or within the rubber band, (but excluding the Current Clipping label and the currentLineEdit line edit); then release. Press Ctrl+G (lay out in a grid). Click the form, then click Ctrl+L (lay out vertically). Our original design is back -- but this time using a grid layout.

Changing the Tab Order

Keyboard users press the Tab key to move the focus from widget to widget as they use a form. The order in which the focus moves is called the tab order. Preview multiclip (press Ctrl+T) and try tabbing through the widgets. The tab order may not be what we want so we'll go into tab order mode and change it to the order we want.

When you click the Tab Order toolbar button a number in a blue circle will appear next to every widget that can accept keyboard focus. The numbers represent each widget's tab order, starting from 1. You change the tab order by clicking the widgets in the order you want to be the new tab order. If you make a mistake and need to start again, double click the widget you want to be first, then click the other widgets in the required order as before. When you've finished press Esc to leave tab order mode. If you made a mistake or preferred the previous tab order you can undo your changes by leaving tab order and undoing (press Esc then Ctrl+Z).

Click the Tab Order toolbar button, then click the current clipping Line Edit -- even if it is already number one in the tab order. Next click the previous clipping ListBox, then the auto add clippings CheckBox. Click each button in turn from top (add clipping) to bottom (quit). Press Esc to finish tab order mode, then preview the form and try tabbing through the widgets.

Note that you can stop clicking if the tab order numbers for all the widgets is correct; just press Esc to leave tab order mode.

Setting the Tab Order

Connecting Signals and Slots

Qt provides the signals and slots mechanism for communicating between widgets. Signals are emitted by widgets when particular events occur. We can connect signals to slots, either pre-defined slots or those we create ourselves. In older toolkits this communication would be achieved using callbacks. (For a full explanation of Qt's signals and slots mechanism see the on-line Signals and Slots documentation.)

Connecting Predefined Signals and Slots

Some of an application's functionality can be obtained simply by connecting pre-defined signals and slots. In multiclip there is only one pre-defined connection that we can use, but in the richedit application that we'll build in Creating Main Windows with Actions, Toolbars and Menus we will use many pre-defined signals and slots to get a lot of the functionality we need without having to write any code.

We will connect the Quit button's clicked() signal to the form's accept() slot. The accept() slot notifies the dialog's caller that the dialog is no longer required; since our dialog is our main window this will close the application. Preview the form (press Ctrl+T); click the Quit button. The button works visually but does nothing. Press Esc or close the preview window to leave the preview.

Click the Connect Signals/Slots toolbar button. Click the Quit button, drag to the form and release. The Edit Connections dialog will pop up. The top left hand list box lists the Signals that the widget we've clicked can emit. At the top right is a combobox which lists the form and its widgets; any of these are candidates for receiving signals. Since we released on the form rather than a widget the slots combobox shows the form's name, 'MulticlipForm'. Beneath the combobox is a list box which shows the slots available in the form or widget shown in the combobox. Note that only those slots that can be connected to the highlighted signal are shown. If you clicked a different signal, for example the toggled() toggled() signal, the list of available slots would change. Click the signal, then click the The connection will be shown in the Connections list box. Click OK.

Connecting the clicked() Signal to the accept() Slot

We will make lots of signal/slot connections as we work through the examples, including connections to our own custom slots. Signal/slot connections (using pre-defined signals and slots) work in preview mode. Press Ctrl+T to preview the form; click the form's Quit button. The button now works correctly.

Creating and Connecting Custom Slots

In the first version of Qt Designer you could create the signatures of your custom slots and make the connections, but you could not implement your slots directly. Instead you had to subclass the form and code your slots in the subclass. The subclassing approach is still available, and makes sense in some situations. But now you can implement your slots directly in Qt Designer, so for many dialogs and windows subclassing is no longer necessary. (Qt Designer stores the slot implementations in a .ui.h file; see The ui.h extension approach in The Designer Approach chapter for more about these files.)

The multiclip application requires four slots, one for each button, but only three need to be custom slots since we connected a signal to a pre-defined slot to make the Quit button functional. We need a slot for the Add Clipping button; this will add the current clipping to the list box. The Copy Previous button requires a slot which will copy the selected list box item to the current clipping line edit (and to the clipboard). The Delete Clipping button needs a slot to delete the current clipping and the current list box item. We will also need to write some initialization code so that when the application starts it will put the current clipboard text (if any) into the line edit. The code is written directly in Qt Designer; the snippets are taken from the generated qt/tools/designer/examples/multiclip/multiclip.ui.h file.

We'll need Qt's global clipboard object throughout the code which would mean calling QApplication::clipboard() or qApp->clipboard() in several places. Rather than perform all these function calls we'll keep a pointer to the clipboard in the form itself. Click the Source tab of the Object Explorer. (If the Object Explorer isn't visible click Window|Views|Object Explorer.) The Source tab shows us the functions in our form, the class variables, the forward declarations and the names of the include files we've asked for.

Right click the Class Variables item (near the bottom; you may have to click the scrollbar), then click New on the popup menu. (If there had been any existing variables the popup menu would also have a Delete option.) Type in 'QClipboard *cb;' and press Enter. We will create an init() function in which we will assign this pointer to Qt's global clipboard object. We also need to declare the clipboard header file. Right click Includes (in Declaration), then click New. Type in '<qclipboard.h>' and press Enter. Since we need to refer to the global application object, qApp, we need to add another include declaration. Right click Includes (in Implementation), then click New. Type in '<qapplication.h>' and press Enter. The variable and declarations will be included in the code generated from Qt Designer's .ui file.

We will invoke Qt Designer's code editor and write the code.

We'll create the init() function first. One way of invoking the code editor is to click the Source tab, then click the name of the function you want to work on. If you have no functions or wish to create a new function you need to use the Source tab. Right click the 'protected' item in the Source tab's Slots list, then left click New to launch the Edit Slots dialog. Change the slot's name from 'newSlot' to 'init()' then click OK. You can then click inside the editor window that appears to enter your code.

Note that you are not forced to use Qt Designer's code editor; so long as you add, delete and rename your slots all within Qt Designer, you can edit the implementation code for your slots using a separate external editor and Qt Designer will preserve the code you write.

    void MulticlipForm::init()
    {
        lengthLCDNumber->setBackgroundColor( darkBlue );
        currentLineEdit->setFocus();

        cb = qApp->clipboard();
        connect( cb, SIGNAL( dataChanged() ), SLOT( dataChanged() ) );
        if ( cb->supportsSelection() )
            connect( cb, SIGNAL( selectionChanged() ), SLOT( selectionChanged() ) );

        dataChanged();
    }

The first couple of lines change the LCD number's background color and make the form start with the focus in the line edit. We take a pointer to Qt's global clipboard and keep it in our class variable, cb. We connect the clipboard's dataChanged() signal to a slot called dataChanged(); we will create this slot ourselves shortly. If the clipboard supports selection (under the X Window system for example), we also connect the clipboard's selectionChanged() selectionChanged() signal to a slot of the same name that we will create. Finally we call our dataChanged() dataChanged() slot to populate the line edit with the clipboard's text (if any) when the application begins.

Since we've referred to the dataChanged() and selectionChanged() slots we'll code them next, starting with dataChanged().

    void MulticlipForm::dataChanged()
    {
        QString text;
        text = cb->text();
        clippingChanged( text );
        if ( autoCheckBox->isChecked() )
            addClipping();
    }

We take a copy of the clipboard's text and call our own clippingChanged() slot with the text we've retrieved. If the user has checked the Auto Add Clippings checkbox we call our addClipping() slot to add the clipping to the list box.

The only applicable under the X Window System. Users of MS Windows can still include the code to ensure that the application works multiplatform.

    void MulticlipForm::selectionChanged()
    {
        cb->setSelectionMode( TRUE );
        dataChanged();
        cb->setSelectionMode( FALSE );
    }

We tell the clipboard to use selection mode, we call our dataChanged() dataChanged() slot to retrieve any selected text, then set the clipboard back to its default mode.

In the another custom slot, clippingChanged().

    void MulticlipForm::clippingChanged( const QString & clipping )
    {
        currentLineEdit->setText( clipping );
        lengthLCDNumber->display( (int)clipping.length() );
    }

We set the line edit to whatever text is passed to the clippingChanged() slot and update the LCD number with the length of the new text.

The next slot we'll code will perform the Add Clipping function. This slot is called by our code internally (see the dataChanged() slot above), and when the user clicks the Add Clipping button. Since we want Qt Designer to be able to set up a connection to this slot instead of just typing it in the editor window we'll let Qt Designer create its skeleton for us. Click Edit|Slots to invoke the Edit Slots dialog. Click New Slot and replace the default name of 'new_slot()' with 'addClipping()'. There is no need to change the access specifier or return type. Now that we've created our slot we can implement it in the code editor where it has now appeared.

The Add Clipping button is used to copy the clipping from the Current Clipping line edit into the list box. We also update the length number.

    void MulticlipForm::addClipping()
    {
        QString text = currentLineEdit->text();
        if ( ! text.isEmpty() ) {
            lengthLCDNumber->display( (int)text.length() );
            int i = 0;
            for ( ; i < (int)clippingsListBox->count(); i++ ) {
                if ( clippingsListBox->text( i ) == text ) {
                    i = -1; // Do not add duplicates
                    break;
                }
            }
            if ( i != -1 )
                clippingsListBox->insertItem( text, 0 );
        }
    }

If there is some text we change the LCD's value to the length of the text. We then iterate over all the items in the list box to see if we have the same text already. If the text is not already in the list box we insert it.

To make the Add Clipping button functional we need to connect the button's addClipping() slot. Click the Connect Signals/Slots toolbar button. Click the Add Clipping button, drag to the form and release. (Make sure you drag to the form rather than another widget -- the form will have a thin pink border during the drag. If you make a mistake simply change the name in the Slots combobox.) The Edit Connections dialog will appear. Click the addClipping() slot. Click OK to confirm the connection.

The Copy Previous button is used to copy the selected clipping from the list box into the line edit. The clipping is also placed on the clipboard. The procedure is the same as for the Add Clipping button: first we create the slot, then we implement it and finally we connect to it:

  1. Create the slot.

    Click the Edit|Slots menu item to invoke the Edit Slots dialog. Click New Slot and replace the default 'new_slot()' name with 'copyPrevious()'. Click OK.

  2. Implement the slot.

        void MulticlipForm::copyPrevious()
    {
        if ( clippingsListBox->currentItem() != -1 ) {
            cb->setText( clippingsListBox->currentText() );
            if ( cb->supportsSelection() ) {
                cb->setSelectionMode( TRUE );
                cb->setText( clippingsListBox->currentText() );
                cb->setSelectionMode( FALSE );
            }
        }
    }

    The code for Copy Previous checks to see if there is a selected item in the list box. If there is the item is copied to the line edit. If we are using a system that supports selection we have to repeat the copy, this time with selection mode set. We don't explicitly update the clipboard. When the line edit's text is changed it emits a dataChanged() signal which our dataChanged() slot receives. Our dataChanged() slot updates the clipboard.

  3. Connect to the slot.

    Click the Connect Signals/Slots toolbar button. Click the Copy Previous button, drag to the form and release. The Edit Connections dialog will pop up. Click the clicked() signal and the copyPrevious() slot. Click OK.

We take the same approach to the Delete Clipping button.

  1. Click Edit|Slots to invoke the Edit Slots dialog. Click New Slot and replace the default name with 'deleteClipping()'. Click OK.

  2. The Delete button must delete the current item in the list box and clear the line edit.

        void MulticlipForm::deleteClipping()
    {
        clippingChanged( "" );
        clippingsListBox->removeItem( clippingsListBox->currentItem() );
    }

    We call our own clippingChanged() slot with an empty string and use the list box's removeItem() function to remove the current item.

  3. Connect the Delete Clipping button's clicked() signal to our deleteClipping() slot. (Press F3 -- which is the same as clicking the Connect Signals/Slots toolbar button. Click the Delete Clipping button and drag to the form; release. The Edit Connections dialog will appear. Click the clicked() signal and the deleteClipping() slot. Click OK.)

Compiling and Building an Application

So far we have written about 99% of a Qt application entirely in Qt Designer. To make the application compile and run we must create a main.cpp file from which we can call our form.

The simplest way to create a new source file is by clicking File|New to invoke the 'New File' dialog, then click 'C++ Source' or 'C++ Header' as appropriate, then click OK. A new empty source window will appear. Click File|Save to invoke the Save As dialog, enter 'main.cpp', then click Save.

Enter the following code in the main.cpp C++ editor window:

    #include <qapplication.h>
    #include "multiclip.h"

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

        MulticlipForm clippingForm;
        app.setMainWidget( &clippingForm );
        clippingForm.show();

        return app.exec();
    }

The program creates a QApplication object and an instance of our MulticlipForm, sets the form to be the main widget and shows the form. The app.exec() call starts off the event loop.

Now start up a console (or xterm), change directory to the multiclip application and run qmake. A Makefile compatible with your system will be generated:

qmake -o Makefile multiclip.pro

You can now make the application, e.g. by running make or nmake. Try compililng and running multiclip. There are many improvement you could make and experimenting with both the layout and the code will help you learn more about Qt and Qt Designer.

This chapter has introduced you to creating multiplatform applications with Qt Designer. We've created a form, populated it with widgets and laid the widgets out neatly and scalably. We've used Qt's signals and slots mechanism to make the application functional and generated the Makefile. These techniques for adding widgets to a form and laying them out with the layout tools; and for creating, coding and connecting slots will be used time and again as you create applications with Qt Designer. The following chapters will present further examples and explore more techniques for using Qt Designer.

[Prev: Preface] [Home] [Next: Creating Main Windows with Actions, Toolbars and Menus]


Creating Main Windows with Actions, Toolbars and Menus

In this chapter we will explain how to create an application's main window and how to add actions (explained shortly), menus and toolbars. We will also demonstrate how some common actions, like cut and paste in a QTextEdit, can be performed automatically simply by making the appropriate signals and slots connections. We will build the richedit application to illustrate the necessary techniques.

The Richedit Application

We begin by creating a project file. Start Qt Designer or if it is already running, close any existing projects and files. Click File|New to invoke the New File dialog. Click the 'C++ Project' icon, then click OK to invoke the Project Settings dialog. Click the ellipsis button to invoke the Save As dialog and navigate to where you want to put the new project. Use the Create New Folder toolbar button to create the 'richedit' directory if it doesn't exist. Make sure you're in the 'richedit' directory (double click it) and enter a file name of 'richedit.pro'. Click the Save button. The 'Project File' field of the Project Settings dialog will have the path and name of your new project; click OK to create the project.

If you're unfamiliar with Actions and Action Groups the sidebar provides the necessary introduction; otherwise skip ahead to "Designing the Main Window".

Actions and Action Groups

An action is an operation that the user initiates through the user interface, for example, saving a file or changing some text's font weight to bold.

We often want the user to be able to perform an action using a variety of means. For example, to save a file we might want the user to be able to press Ctrl+S, or to click the Save toolbar button or to click the File|Save menu option. Although the means of invoking the action are all different, the underlying operation is the same and we don't want to duplicate the code that performs the operation. In Qt we can create an action (a QAction object) which will call the appropriate function when the action is invoked. We can assign an accelerator, (e.g. Ctrl+S), to an action. We can also add an action to a menu item and to a toolbar button.

If the action has an on/off state, e.g. bold is on or off, when the user changes the state, for example by clicking a toolbar button, the state of everything associated with the action, e.g. menu items and toolbar buttons, are updated.

Some actions should operate together like radio buttons. For example, if we have left align, center align and right align actions, only one should be 'on' at any one time. An action group (a QActionGroup object) is used to group a set of actions together. If the action group's exclusive property is TRUE then only one of the actions in the group can be on at any one time. If the user changes the state of an action in an action group where exclusive is TRUE, everything associated with the actions in the action group, e.g. menu items and toolbar buttons, are updated.

Qt Designer can create actions and action groups visually, can assign accelerators to them, and can associate them with menu items and toolbar buttons.

Designing the Main Window

We will use the main window wizard to build a main window. The wizard allows us to create actions and a menu bar and a toolbar through which the user can invoke the actions. We will also create our own actions, menus and toolbar. We will add some widgets to the toolbar and add a main widget to the main window. Finally we will connect signals to slots to take advantage of Qt's default functionality and minimize our coding.

Creating the Main Window

Click File|New to invoke the New File dialog, click Mainwindow, then click OK. A new QMainWindow form will be created and the Mainwindow Wizard will pop up.

  1. The Choose available menus and toolbars wizard page appears first. It presents three categories of default actions, File Actions, Edit Actions and Help Actions. For each category you can choose to have Qt Designer create menu items, toolbar buttons and signal/slots connections for the relevant actions. You can always add or delete actions, menu items, toolbar buttons and connections later.

    We will accept the defaults for File Actions, i.e. have menu items, toolbar buttons and the relevant connections created. But for the Edit Actions we don't want any connections created since we'll be connecting the actions directly to the QTextEdit we'll create later, so uncheck the Edit Action's Create Slots and Connections checkbox. We won't have any Help Actions on the toolbar so uncheck the Help Action's Toolbar checkbox. Click Next to move on to the next wizard page.

    Main Window Wizard- Choosing menus and toolbars

  2. The Setup Toolbar wizard page is used to populate a toolbar with actions from each of the default action categories. The Category combobox is used to select which set of actions you wish to work on. The Actions list box lists the actions available for the current category. The Toolbar listbox lists the toolbar buttons you want to create. The blue left and right arrow buttons are used to move actions into or out of the Toolbar list box. The blue up and down arrow buttons are used to move actions up and down within the Toolbar list box. Note that the '<Separator>' item in the Actions list box may be moved to the Toolbar list box as often as required and will cause a separator to appear in the finished toolbar.

    Copy the New, Open and Save Actions to the Toolbar list box. Copy a <Separator> to the Toolbar list box. Change the Category to Edit and copy the Undo, Redo, Cut Copy and Paste actions to the Toolbar list box. Click Next and then click Finish.

    Main Window Wizard- Setting up the toolbar

If you preview the form (Ctrl+T) the File and Edit menus will be available and you'll be able to drag the toolbar either into an independent window of its own, or to dock it to the left, right, bottom or top of the window. The menus and toolbars are not functional yet but we will rectify this as we progress.

Previewing the Form

Click File|Save to save the form as richedit.ui.

Creating and Deleting Actions and Action Groups

Creating Actions

Our application requires more menu items and toolbar buttons than the the defaults we created with the main window wizard. But before we create the menu items and toolbar buttons we will create the actions that they'll invoke. The Action Editor appears automatically when you create a main window. You can also access it through the Window menu (click Window|Action Editor).

Action Editor

For the richedit application we need to create actions for indicating bold, italic and underlined font attributes, and to set text alignment.

Right click in the Action Editor where the actions are listed, then left click New Action. This will create a new action called 'Action' at the top of the list of actions. The Property Editor will change to show the default settings for the new action. We'll now go through all the properties we need to change.

  1. Change the name of the action to 'boldAction'.

  2. Since bold can only be on or off change the toggleAction property to True.

  3. The iconSet property is used to set an icon which will appear to the left of the action's name in any menu you associate the action with. The iconSet is also used for the toolbar button if you associate the action with a toolbar. Click the ellipsis button (...) to invoke the Choose an Image dialog. The ellipsis button appears when you click in the Value part of the Properties list by a pixmap or iconSet property. The pixmap we require is not in the default collection. Click the Add button and a file dialog will appear. The icons we require are in the Qt examples directory, qt/examples/textedit/. Navigate to the textedit directory and select the textbold.xpm file and then click Open. Click the new textbold icon in the pixmap collection then click OK.

    Properties of Bold Action

  4. Change the text property to 'bold'. This automatically changes the menuText, toolTip and statusTip properties.

  5. Change the menu text to '&Bold'. If we choose to associate this action with a menu item then this property is used; otherwise it is ignored.

  6. Change the accel property to 'CTRL+B'. This will associate the Ctrl+B keyboard accelerator with this action.

    Properties for the Bold Action

Note that at this point the only way to invoke this action is to use the keyboard accelerator (Ctrl+B), because we have not yet associated the action with a menu item or with a toolbar button.

We need to add two more actions, italic and underline. For each one right click the Action Editor and click New Action. Then repeat the steps listed above to change each action's properties:

  • For the italic action change its name to 'italicAction' and ensure its toggleAction property is True. The iconSet is in the textedit directory and is called textitalic.xpm; add its pixmap in the same way that we added the bold pixmap. (For example, click the ellipsis (...), click Add, navigate to the textedit directory and click the textitalic.xpm pixmap and then click Open. Then click the textitalic icon in the pixmap collection and click OK). Change the action's text to 'italic', its menuText to '&Italic' and its accel to 'CTRL+I'.

  • For the underline action change its name to 'underlineAction' and set its toggleAction property to True. The iconSet is in the same directory and is called textunder.xpm; add it in the same way as the previous pixmaps. Change its text to 'underline', its menuText to '&Underline' and its accel to 'CTRL+U'.

Creating Action Groups

It is perfectly possible to have bold, italic and underline all active at once. But for alignment, i.e. left align, right align and centered, it only makes sense for one of them to be active at any one time. Because we need the alignment actions to operate in sync with one another we must create an Action Group which will automatically manage the behaviour of the actions it contains in the way we require.

Right click the Action Editor then left click New Action Group. Change the action group's name in the Property Editor to 'alignActionGroup', and change its text to 'align'. The 'exclusive' property's default is True. This ensures that only one action within the action group can be 'on' at any one time which is the behaviour we require.

We create the actions within the action group in almost the same way as before. The only difference is that we must right click the alignActionGroup (rather than an Action) and then left click New Action to create a new action within the action group. We will create three new actions within the alignActionGroup:

  1. Create a new action within the alignActionGroup action group. Change the name of this action to 'leftAlignAction' and ensure its toggleAction property is True. Use the iconSet in the textedit directory called textleft.xpm, adding the pixmap to the pixmap collection in the same way as we added the textbold pixmap earlier. Change its text to 'left', its menuText to '&Left' and its accel to 'CTRL+L'.

    Creating an Action group

  2. Create another new action within alignActionGroup. Change this action's name to 'rightAlignAction' and set its toggleAction property to True. Set its iconSet to textright.xpm using the pixmap collection as before. Change its text to 'right', its menuText to '&Right' and its accel to 'CTRL+R'.

  3. Create a third action within alignActionGroup. Change its name to 'centerAlignAction' and make its toggleAction property True. Change its iconSet to textcenter.xpm. Change its text to 'center' and its menuText to '&Center'. We won't set an accelerator for this action.

    Align Action Group

Note that the toolTip and statusTip properties were inherited from the action group; you may wish to change these to be specific to the actions concerned.

Deleting Actions and Action Groups

We have some actions that we don't intend providing for this first release, for example, the editFindAction and the filePrintAction. Click editFindAction and then click the Delete Action toolbar button. Delete the filePrintAction in the same way. Action Groups (including any actions they contain) can also be deleted with the Delete Action toolbar button.

Deleting editFindAction

Creating and Populating a Toolbar

All the actions we require are now in place and we are ready to create a new toolbar and add some of our actions to it. Right click on the right hand side of the toolbar area, or on the form, then left click Add Toolbar. The new toolbar is empty and is visible only by its toolbar handle. (Toolbar handle's are usually represented as a gray area containing either two thick vertical lines or with many small pits).

Toolbar Handle

We'll add the new actions we've just created. Drag the alignActionGroup, (not any action it contains), to the new toolbar and drop it on the toolbar handle to the right of the vertical lines. The three alignment actions will be added to the toolbar.

Dragging the Action Group to the Toolbar

Populating the Toolbar with an Action Group

The bold, italic and underline actions do not belong to an action group, and must be dragged to the toolbar individually. Drag the bold action to the toolbar: when the mouse is over the toolbar a thick red line will appear indicating the position at which the toolbar button will be inserted; drop the bold action on the toolbar. Drag the italic and underline actions to the toolbar and drop them next to the bold button. Separate the alignment toolbar buttons from the font related buttons by right clicking the centered toolbar button and clicking Insert Separator.

Toolbar buttons and separators (usually represented as indented vertical gray lines), can be dragged and dropped into new positions in the toolbar at any time. Separators can be inserted by right clicking a toolbar button and clicking Insert Separator. Toolbar buttons and separators can be deleted by right clicking them and clicking Delete Item. Toolbars can be deleted by right clicking their toolbar handle and clicking Delete Toolbar.

If you preview the application you'll find that both the original and new toolbar can be dragged to different docking points or dragged out of the application as independent tool windows.

Toolbar with all the Actions Added

Adding Widgets to the Toolbar

We want our users to be able to choose the font and font size from the toolbar. To achieve this we'll create a font combobox and a font size spinbox and place them in the formatting toolbar we created in the previous section.

Click Qt Designer's ComboBox toolbar button and click the last (right-most) toolbar button in the application's new toolbar. Change the combobox's name to 'fontComboBox'. Click the SpinBox toolbar button and click the combobox we've just added to insert the spinbox next to it. Change the spinbox's minValue property to 6, its value property to 10 and its suffix to a space followed by 'pt'. Insert a separator to the left of the combobox.

Adding Widgets to the Toolbar

Although you can put any widget into a toolbar we recommend that widgets which can be associated with an action should not be added to the toolbar directly. For these widgets, i.e. menu items, toolbar buttons and lists of items, you should create an action (drop down action for a list of items), associate the action with the widget, and add the action to the toolbar. Widgets that can sensibly be inserted directly into a toolbar are ComboBoxes, SpinBoxes and Line Edits.

Creating Menus

We'll now add the actions we added to the new toolbar to a new menu and modify the existing menus slightly.

Right click our application's menu bar and click Add Menu Item. A new menu item called 'Menu' will appear. Right click this menu item and click Rename Item. Change its name to 'F&ormat'.

Format Menu

Click the menu item and a red bar will appear beneath it -- this is the empty menu. Drag the alignActionGroup from the Action Editor to the Format menu item and drop the action group on the menu. (The menu's red bar will appear and a thick red line will be drawn where the new menu items will appear -- drop when the red line is in the position you require.) Now if you click the Format menu item the three alignment actions will be displayed. Just like the toolbar we must add the bold, italic and underline actions individually. Drag the bold action to the Format menu and move the mouse so that the red line is positioned at the bottom of the menu, then drop the action. Repeat this process for the italic and underline actions.

Draggin the Action Group to the Menu Bar

Dragging and Dropping Align Action Group to the Format Menu

We'll now deal with the separators in the menus. Firstly we'll add a separator in the Format menu and then we'll remove some redundant separators from the other menus. Click the Format menu and right click the bold item towards the top of the highlighted area; click Insert Separator. Note that you could also right click the center align item towards the bottom of the highlighted area to insert the separator between the align actions and the font actions. ###Click the File menu and right click one of the separators above the Exit action; click Delete Item. Click the Edit menu, right click the separator at the very bottom of the menu and click Delete Item. Delete Item can be used to delete separators, menu items and menus.###

Click the Format menu and drag it to the left of the Help menu, then drop the Format menu. (A thick red bar will appear to indicate the insertion postion.) Both menus and menu items may be dragged and dropped to different positions in the same way.

Preview the application and try clicking the alignment and font style toolbar buttons and menu items. Qt will automatically keep the state of the menu items and the toolbar buttons synchronized.

Adding and Connecting the Main Widget

Our application is a rich text editor, but so far there has been nowhere for the user to edit text. We'll add a QTextEdit widget and use Qt's signals and slots mechanism to minimize the code we have to write to make it functional.

Click Qt Designer's Richtext Editor (Text Edit) toolbar button and click in the center of the form. Click the form, then click the Lay Out Horizontally toolbar button. We're now ready to make the connections we need; but first we will do some renaming to make things easier to understand. Click on the Text Edit widget and change its name property to 'textEdit'. Change the textFormat property to 'RichText'. Change the name of the form to 'EditorForm' and its caption to 'Rich Edit'.

Adding Rich Text Edit Widget

The QTextEdit widget contains built-in functionality for cut and paste and various other editing functions. By connecting the appropriate signals to our textEdit we can take advantage of this functionality without the need to write any code.

Connecting Actions to Change Font Attributes

Click the underlineAction in the Action Editor, then click the Connect button in the Action Editor toolbar. The Edit Connections dialog will appear. Click the toggled() signal. Since we wish to connect this signal to the text edit widget, drop down the Slots combobox and click textEdit. The text edit's slots that can respond to a toggled signal will appear in the right hand list box. Click the setUnderline() setUnderline() slot, then click OK.

Connecting the Underline Action

Connect up the bold and italic actions in the same way. (For example, click the bold action and click Connect. Click the toggled() signal, change the Slots combobox item to textEdit and click the Click OK.) If you preview the form you'll find that you can enter text and that choosing bold, italic or underline will work.

Connecting Actions to Implement Cut, Copy, Paste, Undo and Redo

The cut, copy, paste, undo and redo actions are connected in the same way as the font attributes. For example, click the editPasteAction action and click Connect. Click the activated() signal, change the Slots combobox item to textEdit and click the the connection. Connect the cut, copy, undo and redo actions in the same way. (For example, click the editCopyAction action, click Connect, click the signal, change the Slots combobox item to textEdit, click the copy() copy() slot then click OK.) Then the cut, copy, paste, undo and redo actions will all work in preview mode.

Connecting for Text Alignment

We need to create a slot to receive signals from alignment actions and set the textEdit widget's alignment state accordingly. One approach would be to connect each individual alignment action to our slot, but because the align actions are in a group we will connect the alignActionGroup to our slot and determine which alignment the user chose from the QAction pointer that is passed.

Create a new slot with the signature changeAlignment(QAction *align). (Click Edit|Slots, click New Slot, enter the slot's signature and click OK.) Click alignActionGroup in the Action Editor, then click Connect. Connect the selected(QAction*) signal to our change alignment slot, then click OK.

Connecting the Alignment Actions

We'll have to write the code to set the alignment ourselves; we'll cover this in Aligning Text.

Connecting for Font Names and Sizes

We'll start by dealing with font size since it's easiest. Click the Connect Signals/Slots toolbar button then click the spinbox and drag to the text edit widget; release on the text edit. Click the signal and then click the textEdit's setPointSize(int) slot. Click OK and font sizes are done. (Since font sizes are handled purely through built-in signals and slots they work in preview mode.)

Connecting the Font Sizes

Connect the fontComboBox's activated() signal to the textEdit's setFamily() slot. This connection will handle updating the textEdit's font family with the user's choice of font. Note that when you invoke the Edit Connections dialog the first signal that is highlighted is activated(int). Since the setFamily() setFamily() slot takes a QString argument it does not appear in the list of slots. Only those slots which are compatible with the highlighted signal are shown, in this case, slots which take no argument or which take an integer argument. Click the activated(const QString&) signal and the list of slots will change to those which take no argument or which take a QString argument; the list will now include setFamily() since this takes a QString argument. We will have to populate the combobox with the font names for the user to choose from in code. (See the in Changing Fonts.) It's a good idea to connect the fontComboBox's the textEdit's will ensure that after the user has changed font the focus will return to the text.

The richedit application is nearly complete. We will have to write code to handle text alignment, font family and file loading and saving. We will also write the code for application exit to deal correctly with any unsaved changes.

Converting the Design into an Executable Application

We've built the user interface through Qt Designer and connected those slots that provided sufficient default functionality. The last steps are to code the slots that require customization and then to create main.cpp so that we can compile and build our application.

Implementing the Main Window's Functionality

When the user starts the richedit application we want the focus to be in the textEdit widget so we need to create an init() function with one line of code to achieve this. (All the code snippets are from qt/tools/designer/examples/richedit/richedit.ui.h.)

    void EditorForm::init()
    {
        textEdit->setFocus();
            }

We'll add more to this function later.

New Files and Loading and Saving Existing Files

The code for these tasks is straightforward. When the user clicks File|New we check to see if there are unsaved changes in the existing text and give them the opportunity to save, continue without saving or cancel the operation. When the user opts to open an existing file or exit the application we perform the same check and offer them the same choices.

    void EditorForm::fileNew()
    {
        if ( saveAndContinue( "New" ) )
            textEdit->clear();
    }

The fileNew() function clears the text and the filename.

    void EditorForm::fileOpen()
    {
        if ( saveAndContinue( "Open" ) ) {
            QString fn( QFileDialog::getOpenFileName(
                            QString::null,
                            "Rich Text Files (*.htm*)", this ) );
            if ( !fn.isEmpty() ) {
                fileName = fn;
                QFile file( fileName );
                if ( file.open( IO_ReadOnly ) ) {
                    QTextStream ts( &file );
                    textEdit->setText( ts.read() );
                }
            }
        }
    }

The fileOpen() function asks the user to choose a file using QFileDialog::getOpenFileName(). If they choose a file we set the fileName member to its name, open it and read its contents directly into the text edit via a text stream.

    void EditorForm::fileSave()
    {
        if ( fileName.isEmpty() ) {
            fileSaveAs();
        } else {
            QFile f( fileName );
            if ( f.open( IO_WriteOnly ) ) {
                QTextStream ts( &f );
                ts << textEdit->text();
                textEdit->setModified( FALSE );
            }
        }
    }

If there is no current file name we call fileSaveAs() which will prompt for a file name and if a file name is given calls fileSave(). If we have a file name we open a file and write the text from the text edit into the file via a text stream. We also set the text edit's modified property to FALSE.

    void EditorForm::fileSaveAs()
    {
        QString fn = QFileDialog::getSaveFileName(
                                    "", "Rich Text Files (*.htm*)", this );
        if ( !fn.isEmpty() ) {
            fileName = fn;
            fileSave();
        }
    }

The fileSaveAs function prompts the user for a file name and if they give a file name, saves the text to the file by calling fileSave().

    void EditorForm::fileExit()
    {
        if ( saveAndContinue( "Exit" ) )
            qApp->exit();
    }

When we exit the application we must perform the same check for unsaved changes as we've done in the preceding functions, so we've included the fileExit() function's code here.

    int EditorForm::saveAndContinue(const QString & action)
    {
        int continueAction = 1;

        if ( textEdit->isModified() ) {
            switch( QMessageBox::information(
                    this, "Rich Edit",
                    "The document contains unsaved changes.\n"
                    "Do you want to save the changes?",
                    "&Save", "&Don't Save", "&Cancel " + action,
                    0, // Enter == button 0
                    2 ) ) { // Escape == button 2
            case 0: // Save; continue
                    fileSave();
                    break;
            case 1: // Do not save; continue
                    break;
            case 2: // Cancel
                    continueAction = 0;
                    break;
            }
        }

        return continueAction;
    }

The saveAndContinue() function is included for completeness.

Aligning Text
    void EditorForm::changeAlignment(QAction * align)
    {
        if ( align == leftAlignAction )
            textEdit->setAlignment( Qt::AlignLeft );
        else if ( align == rightAlignAction )
            textEdit->setAlignment( Qt::AlignRight );
        else if ( align == centerAlignAction )
            textEdit->setAlignment( Qt::AlignCenter );
    }

We compare the chosen alignment action's pointer to the the pointers stored in the form and if we get a match set the appropriate alignment in the textEdit widget.

Changing Fonts

We've already connected the fontComboBox's activated() signal to the textEdit's setFamily() slot so we just have to populate the combobox with the font names when we call init().

    void EditorForm::init()
    {
        textEdit->setFocus();

        QFontDatabase fonts;
        fontComboBox->insertStringList( fonts.families() );
        QString font = textEdit->family();
        font = font.lower();
        for ( int i = 0 ; i < fontComboBox->count(); i++ ) {
            if ( font == fontComboBox->text( i ) ) {
                fontComboBox->setCurrentItem( i );
                break;
            }
        }
    }

The first line sets the focus as we've already mentioned. We then create a QFontDatabase object and insert its list of font families into the fontComboBox. Finally we set the fontComboBox's current item to the textEdit's current font.

Making the Application Run

With all the connections and code in place we are now ready to make our application run. Click on the Source tab of the Object Hierarchy window and click on the Includes (in Implementation) item. We need to include the files that our source code depends on. Right click the Includes item and click New. Type in <qapplication.h> for fileExit()'s exit() call. In the same way add <qmessagebox.h> for saveAndContinue()'s message box, <qfiledialog.h> for the fileOpen() and fileSaveAs() functions, and <qfontdatabase.h> for the QFontDatabase class in init().

We referred to a member variable, fileName, in our source code so we must add it to the form. Click the Source tab, right click the Class Variables item, click New from the pop up menu, then enter 'QString fileName;'.

The simplest way to create a new source file is by clicking File|New to invoke the 'New File' dialog, then click 'C++ Source' or 'C++ Header' as appropriate, then click OK. A new empty source window will appear. Click File|Save to invoke the Save As dialog, enter 'main.cpp', then click Save. Enter the following code in the main.cpp C++ editor window:

    #include <qapplication.h>
    #include "richedit.h"

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

        EditorForm richeditForm;
        app.setMainWidget( &richeditForm );
        richeditForm.show();

        return app.exec();
    }

All that's left to do is to generate the Makefile, compile and run. The Makefile is created with qmake: qmake -o Makefile richedit.pro.

The richedit application demonstrates how easy it is to create a Qt application's main window with menus and dockable toolbars. A great deal of functionality was obtained by connecting the appropriate built-in signals and slots. The remaining functionality was achieved by connecting built-in signals to our own custom slots. We could continue developing the application, for example updating the fontComboBox, the font size spinbox and the actions with the font attributes as the user moves the cursor through their text. But our objective has been to demonstrate the creation of a main window with actions, menus and toolbars so we must stop at this point and leave further development and experimentation to you.

[Prev: Creating a Qt Application] [Home] [Next: The Designer Approach]


The Designer Approach

Introduction

In Qt 2.x, Qt Designer was a visual form designer for editing files in the .ui file format. Qt Designer's primary goal was to turn the most tedious part of GUI programming -- dialog design -- into a pleasant experience. From an architectural point of view, Qt Designer in 2.x is a fairly simple program. It reads and writes .ui files. Each .ui file contains an XML description of a single dialog form. A second utility -- the user interface compiler uic -- is used during the build process of an application to generate C++ code from those XML descriptions.

For Qt 3.0 our ambitions for Qt Designer have grown beyond single dialog editing. In addition to many new design features like the ability to creating main windows and actions, the new version introduces:

  • project management for the user interface part of your application;

  • code in forms Qt Designer provides a code editor so that you can code your slots directly; the code is stored in .ui.h files and eliminates the need for sub-classing (although you can still subclass if you prefer);

  • dynamic form loading allows you to load .ui files at runtime which provides great scope for design customisation separate from the underlying code.

The purpose of this chapter is to explain the motivation for making these changes, describe the new concepts involved and show how these features work internally.

Qt Designer is and remains a visual design tool: it is not a complete integrated development environment. Our policy is to make GUI development as easy and powerful as possible without locking our users into any particular tool: Qt Designer makes it easy to create and modify GUI designs, but you can still achieve the same results directly in code using a plain text editor if you prefer.

To make working more convenient, Qt Designer now includes a C++ editor (as a plugin). If you want to create or edit a form, use Qt Designer. If you want edit code for that form, you can use the C++ editor in Qt Designer as well. This built-in editor has certain benefits stemming from its tight integration with the visual form design process that we will explain later. However, if you prefer using the editor you're used to, vim, emacs, notepad, Microsoft Visual Studio, etc. you can still do so.

Project management

Reading and writing single, non-connected .ui files is conceptually simple and worked fairly well in Qt 2.x. However, it lacked certain features that made us introduce project management for the GUI part of an application in Qt Designer. The main benefits of project management are:

  • Grouping forms that belong together.

  • Sharing images between different forms.

  • Sharing database information between different forms.

The following sections explain these benefits in more detail, and why project management is required to achieve them.

Grouping forms

Grouping forms means that Qt Designer maintains a list of the .ui files that belong to the same project. This makes it easy to switch between forms with a single mouse click.

Sharing images in a image collection

In Qt 2.x's Qt Designer each form included the images it required and no images were shared. This led to duplication when several forms needed to use the same images. Furthermore the images were stored in the XML .ui files which made them large.

As a workaround, we introduced a pixmap-loading function that you could define in Qt Designer. It then was your responsibility to provide the implementation of this function in your application code. The big disadvantage of this approach was that you couldn't see the images during the design process in Qt Designer. This not only makes designing a form less visually interesting, but also has a noticeable impact on geometry management.

In the Qt 3.0 version of Qt Designer we've introduced the concept of a project image collection. If you use a project you can add images to the project's image collection, and these images can be shared and used by any of the forms you include in the project. The images are stored as PNGs (portable network graphics) in a subdirectory, images/, inside the project's directory. Whenever you modify the image collection, Qt Designer creates a source file which contains both the image data in binary format and a function to instantiate the images. The images are accessible by all forms in the project and the data is shared.

A further benefit of using an image collection is that the images are added to the default QMimeSourceFactory. This way they are accessible from rich-text labels, What's This? context help and even tooltips through standard HTML image tags. The source argument of the image tag is simply the image's name in the image collection. This also works during the design process in Qt Designer.

Sharing database settings

Qt 3.0 introduces a brand new database module, the Qt SQL module. Qt Designer is fully integrated with the SQL module and can show live data from the databases that you connect to.

When you've opened or created a project you can set up its database connections using the Edit Database Connections dialog (invoked by the Project|Database Connections menu option). The connections you make are stored in a .db file. When you reload a project you can reconnect by going to the Edit Database Connections dialog, clicking a connection in the list and clicking the Connect button.

In most non-trivial database applications you will want to access the database from more than one form. This is why the .db file is part of a project, not just part of a single form.

.pro files

Qt Designer needs to store information on projects, for example, the list of forms, the image collection and information about available databases and how to access them. The majority of Qt users already use a project file format to create multiplatform makefiles: tmake (and with Qt 3.0 qmake) project .pro files. These files already contain the list of forms, .ui files, used in the project for uic.

We've extended the sections in the .pro file to include the extra information that Qt Designer needs to manage projects. For example, when you add a form to your project in Qt Designer, it is automatically added to the FORMS section of the project file, and thus qmake will generate the required build rules without any further work. Similarly, the images are added to the IMAGES section and thus gets automatically compiled into your executable.

We don't force you to use qmake; if you prefer another build system, for example automake/autoconf or jam, you can still continue to use it. Look upon the .pro file as a file that describes the GUI part of your application. All you need to do -- as previously -- is add the .ui files and the images collection to your own Makefiles.

Extending the functionality of a form

First let us look at a small figure that shows the relationship between .ui files, generated code and application code:

Qt Designer reads and writes .ui files, e.g. form.ui. The user interface compiler, uic, creates both a header file, e.g. form.h, and an implementation file, e.g. form.cpp, from the .ui file. The application code in main.cpp #includes form.h. Typically main.cpp is used to instantiate the QApplication object and start off the event loop.

While this approach is simple, it isn't sufficient for more complex dialogs. Complex dialogs tend to have quite a lot of logic attached to the form's widgets, more logic than can usually be expressed with predefined signals and slots. One way of handling this extra logic is to write a controller class in the application code that adds functionality to the form. This is possible because uic generated classes expose a form's controls and their signals to the public space. The big disadvantage of this method is that it's not exactly Qt-style. If you were not using Qt Designer, you would almost always add the logic to the form itself, where it belongs.

This is why the capability of adding custom slots and member variables to a form was added to Qt Designer early on. The big additional benefit with this approach is that you can use Qt Designer to connect signals to those custom slots, in the same elegant graphical way that is used to connect signals to predefined slots. The uic then adds an empty stub for each custom slot to the generated form.cpp implementation file.

The big question now is how to add custom implementation code to those custom slots. Adding code to the generated form.cpp is not an option, as this file gets recreated by the uic whenever the form changes -- and we don't want a combination of generated and handwritten code. There are two possible solutions, which we'll cover next.

The subclassing approach

A very clean way to implement custom slots for generated forms is via C++ inheritance as shown in the next figure:

Here the user wrote an additional class FormImpl, which is split into the header file formimpl.h and the implementation file formimpl.cpp. The header file includes the uic generated form.h and reimplements all the custom slots. This is possible because uic generated custom slots are virtual. In addition to implementing custom slots, this approach gives the user a way to do extra initialization work in the constructor of the subclass, and extra cleanups in the destructor.

Because of these benefits and its flexibility, this approach became the primary way of using Qt Designer in Qt 2.x.

Note: To keep the namespace clean, most users did not follow the Form and FormImpl naming scheme shown in the figure, but instead named their Qt Designer forms FormBase and their subclasses Form. This made a lot of sense, because they always subclassed and were using those subclasses in application code.

The ui.h extension approach

Despite its flexibility and cleanness, the subclassing approach has some disadvantages:

  • Subclassing is not natural and easy for everybody. Newcomers to object-oriented techniques may feel uneasy about being forced to subclass for such a simple and natural thing like the implementation of a custom slot.

  • Inheriting generated classes is an additional possible source of programming mistakes, especially if the number of reimplemented functions is high and the signatures change often during the design process. To make the development process smoother, uic generates empty stubs for custom slots rather than pure virtual functions. While this approach keeps the code compiling and running, programmers can find themselves in a situation where they miss a runtime warning message and lose time before they find a small spelling error in their subclass.

  • In larger projects with hundreds of forms, the additional subclasses can make a noticeable difference in terms of compilation speed and code size.

There may be more disadvantages, but these were reason enough for us to investigate alternative solutions. For Qt 3.0, we came up with a new concept, the ui.h extension.

This is how it works:

In addition to the .ui file, form.ui, Qt Designer reads and writes another associated file form.ui.h. This .ui.h file is an ordinary C++ source file that contains implementations of custom slots. The file gets included from the generated form implementation file form.cpp and thus can be totally ignored by other user code. The reason we use a .h extension for the .ui.h file even though it contains C++ code is because it is always included, and because it is easier to integrate into the build process with a .h extension.

The form.ui.h file has a special position among all other files. It is a shared source file that gets written and read by both the user and Qt Designer. As such it is an ordinary revision controlled source file and not generated by uic. Qt Designer's responsibility is to keep the file in sync with the custom slot definitions of the associated form:

  1. Whenever the users adds a new slots to the form, Qt Designer adds a stub to the .ui.h file.

  2. Whenever the user changes a custom slot's signature, Qt Designer updates the corresponding implementation.

  3. Whenever the user removes a custom slot, Qt Designer removes it from the .ui.h file.

This way integrity is guaranteed, there is no more need for subclassing and no more danger of forgotten or misspelled slots in subclasses.

You can edit .ui.h files either directly in Qt Designer with the built-in C++ editor plugin, or with whatever editor you prefer. You should only put slot implementations in the .ui.h file and you should always add, delete or rename slots within Qt Designer. You can edit the implementations of the slots either within Qt Designer or using your own editor; if you use your own editor Qt Designer will keep your changes.

Construction and destruction

The ui.h extension approach has one disadvantage compared to subclassing. The ui.h file only contains custom slot implementations, but the objects are still entirely constructed and destructed inside the generated form.cpp code. This leaves the user without the possibility of doing further form initializations or cleanups that you normally would do within the constructor and destructor functions of a C++ class.

To work around this limitation, we created the init/destroy convention. If you add a slot Form::init() to your form, this slot will be called automatically at the end of the generated form constructor. Similarly, if you add a slot Form::destroy() to your form, the slot will automatically be invoked by the destructor before any form controls get deleted. (These slots should return void.) If you prefer to use your own editor you must still create these functions in Qt Designer; once created you can then write your implementation code either using Qt Designer's C++ editor plugin or using your own editor.

Loading forms dynamically

We extracted the part of Qt Designer that is responsible for loading and previewing a form into a library of its own, libqui. A new class QWidgetFactory makes it possible to load .ui files at runtime and instantiate forms from them.

This dynamic approach keeps the GUI design and the code separate and is useful in environments where the GUI may have to change more often than the underlying application logic. Ultimately, you can provide users of your application the ability to modify the graphical user interface without the need for a complete C++ development environment.

Since the .ui file is not compiled it cannot include any C++ code, (e.g. custom slot implementations). We provide a way of adding those implementations via a controlling QObject subclass that you pass as receiver to the widget factory.

This concept and its usage is explained in detail in the Subclassing and Dynamic Dialogs chapter.

[Prev: Creating Main Windows with Actions, Toolbars and Menus] [Home] [Next: Subclassing and Dynamic Dialogs]


Subclassing and Dynamic Dialogs

This chapter describes two different approaches that you can take to creating forms with Qt Designer. Subclassing is used to extend the functionality of a form by creating your own class based upon a form you create in Qt Designer. Dynamic dialogs are .ui files which can be executed by a Qt application; this keeps the GUI design and the code separate and is useful in environments where the GUI may have to change more often than the underlying application logic.

Subclassing

We'll start with a general description of how to subclass a form and follow with a short example. Note that subclassing has some disadvantages compared with putting your code into a form directly; see Extending the functionality of a form in The Designer Approach chapter for details.

Generating Source Code from Qt Designer .ui Files

Qt Designer reads and writes qmake .pro (project) files which are used to record the files used to build the application and from which Makefiles are generated. Qt Designer also reads and writes .ui (user interface) files. These are XML files that record the widgets, layouts, source code and settings you've used for a form. Every .ui file is converted by the uic (user interface compiler) into a C++ .h file and a C++ .cpp file. These C++ files are then read by moc (meta object compiler), and finally compiled by your compiler into a working application.

If you create applications wholly within Qt Designer you only need to create a main.cpp.

If you create the main.cpp file within Qt Designer, it will automatically be added to your project file by Qt Designer. If you create the main.cpp file outside of Qt Designer you must add it to the project file manually by adding the following line at the end of your project's .pro file:

SOURCES += main.cpp

You can then use qmake to generate the Makefile. (For example qmake -o Makefile myproject.pro.) Running make (Linux, Unix or Borland compilers), or nmake (Visual C++), will then call uic, moc and your compiler as necessary to build your application.

If you use Qt Designer to create your main window and dialogs, but also add other C++ files, or if you subclass any of your forms you will need to add these files to the .pro file so that they are compiled with the rest of your application's source files. Each .h file that you create separately from Qt Designer should be added to the HEADERS line, and each .cpp file should be added to the SOURCES line, just as we've done for main.cpp. If you get undefined reference errors it is worth checking that you've added the names of all your header and implementation files to the .pro file.

Subclassing a Form

When subclassing a form it is helpful to use a naming convention to help us identify which files are generated from Qt Designer's .ui files and which are hand coded.

Suppose, for example, that we are developing a dialog and writing the code directly in Qt Designer. We might call our dialog 'OptionsForm' and the .ui file, optionsform.ui. The automatically generated files will be optionsform.h and optionsform.cpp.

If we were developing another dialog, but this time one that we intended to subclass, we want to make it easy to distinguish between the automatically generated files and our hand coded files. For example, we might call our dialog 'SettingsFormBase' and the .ui file settingsformbase.ui. The automatically generated files would then be called settingsformbase.h and settingsformbase.cpp. We would then call our subclass 'SettingsForm' and code it in the files settingsform.h and settingsform.cpp.

Any subclass of a form should include the Q_OBJECT macro so that slots and signals will work correctly. Once you've created your subclass be sure to add the .h and the .cpp files to the .pro project file. For example we would add the following lines for our subclassed 'SettingsForm' at the end of the .pro file:

HEADERS += settingsform.h
SOURCES += settingsform.cpp

The simplest way to create a new source file is by clicking File|New to invoke the 'New File' dialog, then click 'C++ Source' or 'C++ Header' as appropriate, then click OK. A new empty source window will appear. You don't need to manually edit the .pro file since Qt Designer will add them for you automatically.

Qt Designer will have added

FORMS = settingsformbase.ui

to the project file. The settingsformbase.h and settingsformbase.cpp files will be generated from the .ui file automatically.

A Subclassing Example

We will write a small example dialog to show the use of subclassing in practice. The dialog will present a choice of customer credit ratings with an option of choosing a 'special' rating for which a specific amount must be given. We'll implement the functionality in a subclass. We'll start by creating the base form and connecting its signals and slots, then we'll create the subclass and a simple main.cpp so that we can test it.

Designing the Form

We'll begin by creating a new project. Click File|New, then click the 'C++ Project' icon to invoke the Project Settings dialog. Click the ellipsis button to invoke the Save As dialog; navigate to the project's directory (creating it if necessary). Make sure you're in the project's directory, then enter a project name of 'credit.pro'. Click the Save button to return to the Project Settings dialog, then click OK. Now we'll add a form to the project. Click File|New to invoke the New File dialog. The default form is Dialog which is what we want; click OK. Resize the form to make it smaller; it should be about 2 inches (5 cm) square. Change the form's name to 'CreditFormBase' and the caption to 'Credit Rating'. Save the form as creditformbase.ui.

We'll now add the widgets we need.

  1. Click the Button Group toolbar button, then click near the top left of the form. Resize the button group so that it takes up approximately half the form. Change the button group's name to 'creditButtonGroup' and its title property to 'Credit Rating'.

  2. We'll now add some radio buttons. Double click the Radio Button toolbar button. Click towards the top of the Credit Rating button group and a radio button will appear. Click below this button, to create a second radio button, then click below the second button to create a third. Now we will switch off the effect of the double click by clicking the Pointer (arrow) toolbar button. The pointer will now behave normally, i.e. clicking the form will no longer create more radio buttons. Change the first radio button's name to 'stdRadioButton' and its text to '&Standard'. Change its checked property to True. Change the second button's name to 'noneRadioButton' and its text to '&None'. Change the third radio button's properties to 'specialRadioButton' and 'Sp&ecial' respectively.

  3. If the user chooses the special credit rating they must specify an amount. Click the SpinBox toolbar button and click the form just below the button group. Change the spin box's name to 'amountSpinBox'. Change its prefix to '$ ' (note the space), its maxValue to '100000' and its lineStep to '10000'. Change its enabled property to False.

  4. Click the Push Button toolbar button and click the form below the spin box. Change the button's name to 'okPushButton', its text to 'OK' and its default property to 'True'. Add a second button to the right of the first. Change the second button's name to 'cancelPushButton' and its text to 'Cancel'.

We'll now lay out the widgets and connect up the slots we need.

  1. Click the credit rating group box then press Ctrl+L (lay out vertically).

  2. Click the form so that the button group is no longer selected. Ctrl+Click the OK button and drag the rubber band to touch the Cancel button, then release. Press Ctrl+H.

  3. Click the form, then press Ctrl+L.

    The widgets will be laid out vertically, each one stretching to fill up the maximum space both vertically and horizontally. The buttons look rather large since they've expanded to take up the full width of the form. It might look more attractive to make the buttons smaller using spacers. Click the OK button, then press Ctrl+B (break layout). Resize both buttons to make them narrower leaving space on either side of them. Click the Spacer toolbar button then click to the left of the OK button; click Horizontal from the pop up spacer menu. Copy this spacer and place the copy between the two buttons. Copy the spacer again and place the copy to the right of the Cancel button. (For the second and third spacers, click on the first spacer, press Ctrl+C then Ctrl+V. Drag the new spacer to the desired position.) Ctrl+Click the left most spacer and drag the rubber band so that it touches the buttons and the spacers, then release. Press Ctrl+H. Click the form then press Ctrl+L.

We'll now connect the signals and slots. Press F3 (connect signals/slots), then click the OK button. Drag to the form and release. In the Edit Connections dialog that pops up connect the clicked() signal to the accept() slot. (Click the clicked() signal, click the accept() slot, then click OK.) Connect the Cancel button to the reject() slot using the same technique.

We want the amount spin box to be enabled only if the special radio button is checked. Press F3 (connect signals/slots), then click the special radio button. Drag to the spin box and release. In the Edit Connections dialog that pops up click the toggled() signal and the setEnabled() slot.

If the user checks the standard or none radio buttons we want to set the amount accordingly. Press F3, then click the credit rating button group. Drag to the form and release. Click the clicked() signal. We want to connect this signal to our own custom slot, but we haven't created one yet. Click the Edit Slots button and the Edit Slots dialog will pop up. Click New Slot and change the Slot's name to 'setAmount()'. Click OK. This new slot is now available in the list of slots. Click the setAmount() slot then click OK.

We'll subclass the form to set the amount in the spin box depending on which radio button is checked. Save the form as 'creditformbase.ui' (press Ctrl+S).

Creating the Test Harness

Although we intend our dialog to be used within an application it is useful to create a test harness so that we can develop and test it stand-alone. Click File|New to invoke the 'New File' dialog, then click 'C++ Source', then click OK. In the editor window that pops up, enter the following code:

#include <qapplication.h>
#include "creditformbase.h"

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

    CreditFormBase creditForm;
    app.setMainWidget( &creditForm );
    creditForm.show();

    return app.exec();
}

Note that we're including creditformbase.h and instantiating a CreditFormBase object; once we've written our subclass we'll replace the header with our subclass, creditform.h, and instantiate a CreditForm.

We can now generate the application with qmake, e.g. qmake -o Makefile credit.pro, make it and run it. The form should run fine, but doesn't yet have the behaviour we require.

Creating the Subclass

We need to create a header and an implementation file for our subclass. The code for our subclass is minimal. The header file is qt/tools/designer/examples/credit/creditform.h:

    #include "creditformbase.h"

    class CreditForm : public CreditFormBase
    {
        Q_OBJECT
    public:
        CreditForm( QWidget* parent = 0, const char* name = 0,
                    bool modal = FALSE, WFlags fl = 0 );
        ~CreditForm();
    public slots:
        void setAmount();
    };

We've declared the slot, setAmount(), that we created in Qt Designer. The Q_OBJECT macro is included because it is essential for classes that use signals and slots.

The implementation in qt/tools/designer/examples/credit/creditform.cpp is simple:

    #include <qradiobutton.h>
    #include <qspinbox.h>
    #include "creditform.h"

    CreditForm::CreditForm( QWidget* parent, const char* name,
                            bool modal, WFlags fl )
        : CreditFormBase( parent, name, modal, fl )
    {
        setAmount();
    }

    CreditForm::~CreditForm() { /* NOOP */ }

    void CreditForm::setAmount()
    {
        if ( stdRadioButton->isChecked() )
            amountSpinBox->setValue( amountSpinBox->maxValue() / 2 );
        else if ( noneRadioButton->isChecked() )
            amountSpinBox->setValue( amountSpinBox->minValue() );
    }

We call setAmount() in the constructor to ensure that the correct amount is shown when the form starts based on whichever radio button we checked in Qt Designer. In setAmount() we set the amount if the standard or none radio button is checked. If the user has checked the special radio button they are free to change the amount themselves.

To be able to test our subclass we change main.cpp to include creditform.h rather than creditformbase.h and change the instantiation of the creditForm object:

    #include <qapplication.h>
    #include "creditform.h"

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

        CreditForm creditForm;
        app.setMainWidget( &creditForm );
        creditForm.show();

        return app.exec();
    }

If you created the creditform.h and creditform.cpp files in Qt Designer, they are already in the project file, but if you created them manually you must also update the project file by adding these two new lines at the end:

HEADERS += creditform.h
SOURCES += creditform.cpp

To test the form rerun qmake to regenerate the Makefile, then make and run.

The subclassing example we've used is simple, but this reflects subclassing forms in Qt: it is easy to do.

Creating Dynamic Dialogs from .ui Files

Qt programs are capable of loading Qt Designer .ui files and instantiating the forms represented by the .ui files. Since the .ui file is not compiled it cannot include any C++ code, (e.g. slot implementations). In this section we will explain how to load a dynamic dialog and how to create a class that can be used to implement the dynamic dialog's custom slots.

We will use the credit form that we created in the subclassing section as our example form. We will start by simply instantiating and running the form and then we'll cover how to implement custom slots.

We'll create a main.cpp file to use as a test harness, and manually create a project file.

Creating the Project File

The project file qt/tools/designer/examples/receiver1/receiver.pro looks like this:

TEMPLATE    = app
CONFIG     += qt warn_on release
TARGET      = receiver
SOURCES    += main.cpp
unix:LIBS  += -lqui
win32:LIBS += $(QTDIR)/lib/qui.lib
FORMS      = mainform.ui
LANGUAGE    = C++
INCLUDEPATH += $(QTDIR)/tools/designer/uilib

We do not include the creditformbase.ui file since this file will be read at runtime, as we'll see shortly. We must include the qresource library since the functionality we require is not part of the standard Qt library.

Creating main.cpp

The main.cpp is quite standard. It will invoke the form we're going to create in Qt Designer as its main form. This form will then load and execute the dynamic dialog.

    #include <qapplication.h>
    #include "mainform.h"

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

        MainForm *mainForm = new MainForm;
        app.setMainWidget( mainForm );
        mainForm->show();

        return app.exec();
    }

We create a new instance of our MainForm class, set it to be the main widget, show it and enter the event loop in the app.exec() call.

Creating the Main Form

Designing the Form

  1. Open the receiver.pro project file in Qt Designer. We'll create a dialog as our main window which we'll use to invoke the dynamic dialog. Press Ctrl+N to launch the New File dialog and click OK to get the default which is a dialog. Change the dialog's name to 'MainForm' and its caption to 'Main Form'. Add two buttons, one called 'creditPushButton' with the text '&Credit Dialog', and the other called 'quitPushButton' with the text '&Quit'. (For each button click the Push Button toolbar button, then click the form. Change the properties in the property window to those we've just described.)

  2. We will now add a couple of labels so that we can show the settings the user chose in the dynamic dialog. Click the Text Label toolbar button, then click the form below the Credit Dialog button. Change the label's text to 'Credit Rating'. Add another text label below the Quit button. Change its name to 'ratingTextLabel' and its text to 'Unrated'.

  3. We'll now lay out the widgets. Click the form then press Ctrl+G (lay out in a grid).

  4. We'll now handle the signals and slots connections. Press F3 (connect signals/slots). Click the Credit Dialog button, drag to the form and release. Click the clicked() signal. We'll need to implement a custom slot. Click Edit Slots to invoke the Edit Slots dialog. Click New Slot and type in the Slot name 'creditDialog()'. Click OK. The new slot is now in the list of slots; click the creditDialog() slot to make the connection then click OK. Connect the Quit button's clicked() signal to the dialog's accept() function. (Press F3. Click the Quit button and drag to the form; release. Click the clicked() signal and the accept() slot, then click OK.)

Save the form and call it mainform.ui. (Press Ctrl+S and enter the filename.) In the next section we'll write the code for loading and launching the dynamic dialog directly in Qt Designer.

Loading and Executing a Dynamic Dialog

We'll now add the code to invoke the credit dialog. Before we can do this we need to add the widget factory's header file to the form. Click the Source tab in the Object Hierarchy. Right click Included (in Implementation), then click New. Type in '<qwidgetfactory.h>', then press Enter. Because we will need to access the spin box in the dynamic dialog we must add its header file. Right click Included (in Implmentation), then click New. Type in '<qspinbox.h>', then press Enter.

In our main form we created a slot called creditDialog(). We will implement this slot directly in Qt Designer and use it to load and execute the dynamic dialog. The code is taken from qt/tools/designer/examples/receiver1/mainform.ui.h which contains the C++ implementation of mainform.ui's slots.

    void MainForm::creditDialog()
    {
        QDialog *creditForm = (QDialog *)
            QWidgetFactory::create( "../credit/creditformbase.ui" );
        // Set up the dynamic dialog here

        if ( creditForm->exec() ) {
            // The user accepted, act accordingly
            QSpinBox *amount = (QSpinBox *) creditForm->child( "amountSpinBox", "QSpinBox" );
            if ( amount )
                ratingTextLabel->setText( amount->text() );
        }
        delete creditForm;
    }

The create() function is a static QWidgetFactory function. It loads the specified .ui file and returns a pointer to the toplevel QWidget created from the .ui file. We have cast the pointer to QDialog since we know that the creditformbase.ui file defines a QDialog. After creating the dialog we exec() it. If the user clicked OK the dialog returns Accepted and we enter the body of the if statement. We want to know the amount of credit that the user selected. We call the child() function on the dialog passing it the name of the widget we're interested in. The child() function returns a pointer to the widget with the name we passed, or returns 0 if no widget of that name was found. In the example we call child() to get a pointer to the 'amountSpinBox'. If the pointer we get back is not 0 we set the rating text to the amount in the dialog's spin box. At the end we delete the dynamic dialog. Deleting the dialog ensures that we free up its resources as soon as it is no longer required.

We used the child() to gain access to a widget within the dynamic dialog, passing it the name of the widget we were interested in. In some situations we might not know what a widget is called. We can access the first widget of a specified class by calling child() with a null widget name and a classname, e.g. child(0,"QPushButton"). This will return a pointer to the first QPushButton it finds (or 0 if there isn't one). If you want pointers to all the widgets of a given class you can call the QObject::queryList() function, passing it the name of the class. It returns a QObjectList pointer which points to every object in the dialog that is derived from the given class. See the online QObject documentation for further details.

Implementing Slots for Dynamic Dialogs

There is one outstanding issue that we haven't addressed: the dynamic dialog does not have the behaviour of the original credit dialog because we have not implemented the setAmount() slot. We can implement slots for dynamic dialogs by creating a QObject subclass. We then create an instance of this subclass and pass a pointer to it to the QWidgetFactory::create() function which will connect the dynamic dialog's signals to the slots implemented in our subclass.

We need to create a QObject subclass and change our creditDialog() to create an instance of our subclass that can be passed to the QWidgetFactory::create() function. Here is the modified creditDialog() function from the qt/tools/designer/examples/receiver2/mainform.ui.h file that contains the code for mainform.ui's slots:

    void MainForm::creditDialog()
    {
        Receiver *receiver = new Receiver;
        QDialog *creditForm = (QDialog *)
        QWidgetFactory::create( "../credit/creditformbase.ui", receiver );
        receiver->setParent( creditForm );

        // Set up the dynamic dialog here

        if ( creditForm->exec() ) {
            // The user accepted, act accordingly
            QSpinBox *amount = (QSpinBox *) creditForm->child( "amountSpinBox", "QSpinBox" );
            if ( amount )
                ratingTextLabel->setText( amount->text() );
        }

        delete receiver;
        delete creditForm;
    }

We create a new instance of our 'Receiver' subclass. (We'll write the code for this class shortly.) We then create the QDialog using QWidgetFactory::create(). This call differs from our previous example because we pass in the subclass object so that the create() function can set up the signals/slots connections automatically for us. Since our slot must access the widgets in the dynamic form we pass a pointer to the form to the receiver object through our setParent() function. The remainder of the function is the same as before except that we delete our receiver object.

We'll now look at the implementation of our 'Receiver' subclass. The code is taken from qt/tools/designer/examples/receiver2/receiver.h and the corresponding receiver.cpp file. We'll start with the header file.

#include <qobject.h>
#include <qdialog.h>

class Receiver : public QObject
{
    Q_OBJECT
public:
    void setParent( QDialog *parent );
public slots:
    void setAmount();
private:
    QDialog *p;
};

Our class must be a QObject subclass and because we're using signals and slots it must include the Q_OBJECT macro. We declare a function and the setAmount() slot that we wish to implement as well as a private QDialog pointer.

We'll discuss the implementation of each function in receiver.cpp separately.

    void Receiver::setParent( QDialog *parent )
    {
        p = parent;
        setAmount();
    }

The setParent() function assigns a pointer to the dynamic dialog to our private pointer. We could not do this in a constructor call because we have to construct our Receiver object before we call QWidgetFactory::create(), since we must pass the Receiver object to the create() function. Once we've called create() we then have a pointer to the dynamic dialog which we can then pass via setParent() to our Receiver class. In the subclass version of this example we called setAmount() in the constructor; but we cannot do that here because the implementation of setAmount() depends on knowledge of the dynamic dialog which is not available at construction time. Because of this we call setAmount() in the setParent() function.

    void Receiver::setAmount()
    {
        QSpinBox *amount =
            (QSpinBox *) p->child( "amountSpinBox", "QSpinBox" );

        QRadioButton *radio =
            (QRadioButton *) p->child( "stdRadioButton", "QRadioButton" );
        if ( radio && radio->isChecked() ) {
            if ( amount )
                amount->setValue( amount->maxValue() / 2 );
            return;
        }

        radio =
            (QRadioButton *) p->child( "noneRadioButton", "QRadioButton" );
        if ( radio && radio->isChecked() )
            if ( amount )
                amount->setValue( amount->minValue() );
    }

Since we may be updating the amount spin box we need to get a pointer to it. We call child() on the pointer p which points to the dynamic dialog assigned in the setParent() call. We cast the resulting pointer to the correct type so that we can call any functions relevant to that type. In the example we call child() to get a pointer to the amount spin box, and then call child() again to get a pointer to the 'stdRadioButton'. If we get a pointer to the radio button and the button is checked we set the amount providing we have a pointer to the amount spin box. If this radio button was checked we're finished so we return. If the 'stdRadioButton' isn't checked we get a pointer to the 'noneRadioButton' and set the amount if this button is checked. We do nothing if the 'specialRadioButton' is checked because the user is free to enter a value of their choice.

Compiling vs Dynamically Loading Dialogs

The differences between using a 'compiled in' .ui file and a dynamically loaded .ui file are these:

  • Dynamic dialogs cannot have any C++ code in the .ui file; any custom slots must be implemented via a QObject subclass. Compiled dialogs can contain code either in the .ui file or in a subclass.

  • Dynamic dialogs will load slower because the .ui file must be read and a QWidget instance instantiated based on the .ui file's parse tree. Compiled code will load much faster because no file reading or parsing is necessary. Note that the user may not notice any difference in speed since the difference may be mere fractions of a second.

  • Dynamic dialogs allow you to change the .ui file independently of the code so long as none of the changes impact the code. This means that you can change the appearance of the form, e.g. move widgets and lay them out differently. If you want to change a compiled dialog you must change the .ui file and recompile. If you are building an application and want your customers to be able to customize aspects of the user interface you can give them a copy of Qt Designer and use dynamic dialogs.

[Prev: The Designer Approach] [Home] [Next: Creating Custom Widgets]


Creating Custom Widgets

Custom widgets are created in code. They may comprise a combination of existing widgets but with additional functionality, slots and signals, or they may be written from scratch, or a mixture of both.

Qt Designer provides two mechanisms for incorporating custom widgets:

  1. The original method involves little more than completing a dialog box. Widgets incorporated this way appear as flat pixmaps when added to a form in Qt Designer, even in preview mode. They only appear in their true form at runtime. We'll explain how to create custom widgets using the original approach in "Simple Custom Widgets".

  2. The new method involves embedding the widgets in a plugin. Widgets that are incorporated through plugins appear in their true form in Qt Designer, both when laying out the form and in preview mode. This approach provides more power and flexibility than the original method and is covered in Creating Custom Widgets with Plugins.

Simple Custom Widgets

There are two stages to creating a custom widget. Firstly we must create a class that defines the widget, and secondly we must incorporate the widget into Qt Designer. Creating the widget has to be done whether we are creating a simple custom widget or a plugin, but for simple custom widgets the incorporation into Qt Designer is very easy.

We will create a VCR style widget comprising four buttons, rewind, play, next and stop. The widget will emit signals according to which button is clicked.

Coding the Custom Widget

A custom widget may consist of one or more standard widgets placed together in a particular combination, or may be written from scratch. We will combine some QPushButton widgets to form the basis of our custom widget.

We'll look at the header file, qt/tools/designer/examples/vcr/vcr.h first.

    #include <qwidget.h>

    class Vcr : public QWidget
    {
        Q_OBJECT
    public:
        Vcr( QWidget *parent = 0, const char *name = 0 );
        ~Vcr() {}
    signals:
        void rewind();
        void play();
        void next();
        void stop();
    };

We include qwidget.h since we'll be deriving our custom widget from QWidget. We declare a constructor where the widget will be created and the four signals we want our widget to emit. Since we're using signals we must also include the Q_OBJECT macro.

The implementation is straightforward. The only function we implement is the constructor. The rest of the file consists of include statements and embedded .xpm images.

    Vcr::Vcr( QWidget *parent, const char *name )
        : QWidget( parent, name )
    {
        QHBoxLayout *layout = new QHBoxLayout( this );
        layout->setMargin( 0 );

        QPushButton *rewind = new QPushButton( QPixmap( rewind_xpm ), 0, this, "vcr_rewind" );
        layout->addWidget( rewind );

We create a QHBoxLayout in which we'll place the buttons. We've only shown the rewind button in the code above since all the others are identical except for the names of the buttons, pixmaps and signals. For each of the buttons we require we call the QPushButton constructor passing it the appropriate embedded pixmap. We then add it to the layout. Finally we connect the button's clicked() signal to the appropriate signal. Since the clicked() signals aren't specific to our widget we want to emit signals that reflect the widget's use. The rewind(), play(), etc. signals are meaningful in the context of our widget so we propagate each button's clicked() signal to the appropriate widget-specific signal.

The implementation is complete, but to make sure that our widget compiles and runs we'll create a tiny test harness. The test harness will require two files, a .pro project file and a main.cpp. The qt/tools/designer/examples/vcr/vcr.pro project file:

SOURCES += vcr.cpp main.cpp
HEADERS += vcr.h
TARGET   = vcr
TEMPLATE        =app
CONFIG  += qt warn_on release
DBFILE  = vcr.db
LANGUAGE        = C++

The qt/tools/designer/examples/vcr/main.cpp file is also brief:

    #include <qapplication.h>
    #include "vcr.h"

    int main( int argc, char ** argv )
    {
        QApplication app( argc, argv );
        Vcr *vcr = new Vcr;
        vcr->show();
        return app.exec();
    }

Once we're satisfied that the custom widget compiles and runs we are ready to incorporate it into Qt Designer.

In Base-class Templates the creation of a container custom widget is described.

Adding the Custom Widget to Qt Designer

Click Tools|Custom|Edit Custom Widgets to invoke the Edit Custom Widgets dialog.

  1. Click New Widget so that we are ready to add our new widget.

  2. Change the Class name from 'MyCustomWidget' to 'Vcr'.

  3. Click the ellipsis (...) button to the right of the Headerfile line edit to invoke the file Open dialog. Locate vcr.h, select it, and click Open. It will now appear as the header file.

  4. If you have a pixmap that you want to use to identify your widget on the toolbar click the ellipsis button to the right of Pixmap property. (The ellipsis button appears when you click in the Value part of the Properties list by a pixmap or iconSet property.)

    In our example we have the file qt/tools/designer/examples/vcr/play.xpm which we'll use for this purpose.

  5. Since we know the minimum sensible size for our widget we'll put these values into the Size Hint spin boxes. Enter a width of 80 (in the left hand spin box), and a height of 20 (in the right hand spin box).

The remaining items to be completed will depend on the characteristics of the widget you've created. If, for example, your widget can be used to contain other widgets you'd check the Container Widget checkbox. In the case of our Vcr example the only items we need to add are its signals.

Click the Signals tab. Click the New Signal button and type in the signal name 'rewind()'. Click New Signal again and this time type in 'play()'. Add the 'next()' and 'stop()' signals in the same way.

Since our example hasn't any slots or properties we've finished and can click Close. A new icon will appear in Qt Designer's toolbars which represents the new widget. If you create a new form you can add Vcr widgets and connect the Vcr's signals to your slots.

Incorporating custom widgets that have their own slots and properties is achieved in a similar way to adding signals. All the required information is in our custom widget's header file.

Creating Custom Widgets with Plugins

This section will show you how to write a custom widget and how to embed the custom widget into a plugin. There are no restrictions or special considerations that must be taken into account when creating a widget that is destined to become a plugin. If you are an experienced Qt programmer you can safely skip the section on creating a custom widget and go directly to Creating a Plugin.

Creating a Custom Widget

A custom widget is often a specialization (subclass) of another widget or a combination of widgets working together or a blend of both these approaches. If you simply want a collection of widgets in a particular configuration it is easiest to create them, select them as a group, and copy and paste them as required within Qt Designer. Custom widgets are generally created when you need to add new functionality to existing widgets or groups of widgets.

We have two recommendations that you should consider when creating a custom widget for a plugin:

  1. Using Qt's property system will provide Qt Designer users with a direct means of configuring the widget through the property editor. (See the Qt Properties documentation.)

  2. Consider making your widget's public 'set' functions into public slots so that you can perform signal-slot connections with the widget in Qt Designer.

In the course of this chapter we will create a simple but useful widget, 'FileChooser', which we'll later make available in Qt Designer as a plugin. In practice most custom widgets are created to add functionality rather than to compose widgets, so we will create our widget in code rather than using Qt Designer to reflect this approach. FileChooser consists of a QLineEdit and a QPushButton. The QLineEdit is used to hold a file or directory name, the QPushButton is used to launch a file dialog through which the user can choose a file or directory.

The FileChooser Custom Widget

If you've followed the manual up to this point you may well be able to create this custom widget yourself. If you're confident that you can make your own version of the widget, or have another widget that you want to turn into a plugin, skip ahead to Creating a Plugin. If you prefer to read how we created the widget then read on.

Coding the Widget's Interface

We will work step-by-step through the widget's header file, qt/tools/designer/examples/filechooser/widget/filechooser.h.

    #include <qwidget.h>

    class QLineEdit;
    class QPushButton;

Our widget will be derived from QWidget so we include the qwidget.h header file. We also forward declare the two classes that our widget will be built from.

We include the Q_OBJECT macro since this is required for classes that declare signals or slots. The Q_ENUMS declaration is used to register the Mode enumeration. Our widget has two properties, mode, to store whether the user should select a File or a Directory and fileName which stores the file or directory they chose.

    class FileChooser : public QWidget
    {
        Q_OBJECT

        Q_ENUMS( Mode )
        Q_PROPERTY( Mode mode READ mode WRITE setMode )
        Q_PROPERTY( QString fileName READ fileName WRITE setFileName )

    public:
        FileChooser( QWidget *parent = 0, const char *name = 0);

        enum Mode { File, Directory };

        QString fileName() const;
        Mode mode() const;

The constructor is declared in the standard way for widgets. We declare two public functions, fileName() to return the filename, and mode() to return the mode.

    public slots:
        void setFileName( const QString &fn );
        void setMode( Mode m );

    signals:
        void fileNameChanged( const QString & );

    private slots:
        void chooseFile();

The two 'set' functions are declared as public slots. setFileName() and setMode() set the filename and mode respectively. We declare a single signal, fileNameChanged(). The private slot, chooseFile() is called by the widget itself when its button is clicked.

    private:
        QLineEdit *lineEdit;
        QPushButton *button;
        Mode md;

    };

A pointer to QLineEdit and QPushButton, as well as a Mode variable are held as private data.

Coding the Implementation

We will work step-by-step through the implementation which is in qt/tools/designer/examples/filechooser/widget/filechooser.cpp.

    FileChooser::FileChooser( QWidget *parent, const char *name )
        : QWidget( parent, name ), md( File )
    {

The constructor passes the parent and name to its superclass, QWidget, and also initializes the private mode data, md, to File mode.

        QHBoxLayout *layout = new QHBoxLayout( this );
        layout->setMargin( 0 );

        lineEdit = new QLineEdit( this, "filechooser_lineedit" );
        layout->addWidget( lineEdit );

We begin by creating a horizontal box layout (QHBoxLayout) and add a QLineEdit and a QPushButton to it.

        connect( lineEdit, SIGNAL( textChanged( const QString & ) ),
                 this, SIGNAL( fileNameChanged( const QString & ) ) );

        button = new QPushButton( "...", this, "filechooser_button" );
        button->setFixedWidth( button->fontMetrics().width( " ... " ) );
        layout->addWidget( button );

        connect( button, SIGNAL( clicked() ),
                 this, SLOT( chooseFile() ) );

We connect the lineEdit's textChanged() signal to the custom widget's fileNameChanged() signal. This ensures that if the user changes the text in the QLineEdit this fact will be propagated via the custom widget's own signal. The button's clicked() signal is connected to the custom widget's chooseFile() slot which invokes the appropriate dialog for the user to choose their file or directory.

        setFocusProxy( lineEdit );
    }

We set the lineEdit as the focus proxy for our custom widget. This means that when the widget is given focus the focus actually goes to the lineEdit.

    void FileChooser::setFileName( const QString &fn )
    {
        lineEdit->setText( fn );
    }

    QString FileChooser::fileName() const
    {
        return lineEdit->text();
    }

The setFileName() function sets the filename in the QLineEdit, and the fileName() function returns the filename from the QLineEdit. The setMode() and mode() functions (not shown) are similarly set and return the given mode.

    void FileChooser::chooseFile()
    {
        QString fn;
        if ( mode() == File )
            fn = QFileDialog::getOpenFileName( lineEdit->text(), QString::null, this );
        else
            fn = QFileDialog::getExistingDirectory( lineEdit->text(),this );

        if ( !fn.isEmpty() ) {
            lineEdit->setText( fn );
            emit fileNameChanged( fn );
        }
    }

When chooseFile() is called it presents the user with a file or directory dialog depending on the mode. If the user chooses a file or directory the QLineEdit is updated with the chosen file or directory and the fileNameChanged() signal is emitted.

Although these two files complete the implementation of the FileChooser widget it is good practice to write a test harness to check that the widget behaves as expected before attempting to put it into a plugin.

Testing the Implementation

We present a rudimentary test harness which will allow us to run our custom widget. The test harness requires two files, a main.cpp to contain the FileChooser, and a .pro file to create the Makefile from. Here is qt/tools/designer/examples/filechooser/widget/main.cpp:

    #include <qapplication.h>
    #include "filechooser.h"

    int main( int argc, char ** argv )
    {
        QApplication a( argc, argv );
        FileChooser *fc = new FileChooser;
        fc->show();
        return a.exec();
    }

And here is qt/tools/designer/examples/filechooser/widget/filechooser.pro

SOURCES += filechooser.cpp main.cpp
HEADERS += filechooser.h
TARGET          = filechooser
TEMPLATE        =app
CONFIG  += qt warn_on release
DBFILE  = filechooser.db
LANGUAGE        = C++

We can create the makefile using qmake: qmake -o Makefile filechooser.pro, then we can make and run the harness to test our new widget. Once we're satisfied that the custom widget is robust and has the behaviour we require we can embed it into a plugin.

Creating a Plugin

Qt Plugins can be used to provide self-contained software components for Qt applications. Qt currently supports the creation of five kinds of plugins: codecs, image formats, database drivers, styles and custom widgets. In this section we will explain how to convert our filechooser custom widget into a Qt Designer custom widget plugin.

A Qt Designer custom widget plugin is always derived from QWidgetPlugin. The amout of code that needs to be written is minimal.

To make your own plugin it is probably easiest to start by copying our example plugin.h and plugin.cpp files and changing 'CustomWidgetPlugin' to the name you wish to use for your widget plugin implementation class. Below we provide an introduction to the header file although it needs no changes beyond class renaming. The implementation file requires simple changes, mostly more class renaming; we will review each function in turn and explain what you need to do.

The CustomWidgetPlugin Implementation

We have called our header file plugin.h and we've called our plugin class CustomWidgetPlugin since we will be using our plugin class to wrap our custom widgets. We present the entire header file to give you an impression of the scope of the implementation required. Most of the functions require just a few lines of code.

    #include <qwidgetplugin.h>

    class QT_WIDGET_PLUGIN_EXPORT CustomWidgetPlugin : public QWidgetPlugin
    {
    public:
        CustomWidgetPlugin();

        QStringList keys() const;
        QWidget* create( const QString &classname, QWidget* parent = 0, const char* name = 0 );
        QString group( const QString& ) const;
        QIconSet iconSet( const QString& ) const;
        QString includeFile( const QString& ) const;
        QString toolTip( const QString& ) const;
        QString whatsThis( const QString& ) const;
        bool isContainer( const QString& ) const;
    };

From qt/tools/designer/examples/filechooser/plugin/plugin.h

The QWidgetPlugin Functions

Create your own plugin .cpp file by copying our plugin.cpp file and changing all occurrences of 'CustomWidgetPlugin' to the name you wish to use for your widget plugin implementation. Most of the other changes are simply replacing the name of our custom control, 'FileChooser', with the name of your custom control. You may need to add extra else if clauses if you have more than one custom control in your plugin implementation.

We'll now look at the constructor.

    CustomWidgetPlugin::CustomWidgetPlugin()
    {
    }

The constructor does not have to do anything. Simply copy ours with the class name you wish to use for your widget plugin implementation.

No destructor is necessary.

The keys function.

    QStringList CustomWidgetPlugin::keys() const
    {
        QStringList list;
        list << "FileChooser";
        return list;
    }

For each widget class that you want to wrap in the plugin implementation you should supply a key by which the class can be identified. This key must be your class's name, so in our example we add a single key, 'FileChooser'.

The create() function.

    QWidget* CustomWidgetPlugin::create( const QString &key, QWidget* parent, const char* name )
    {
        if ( key == "FileChooser" )
            return new FileChooser( parent, name );
        return 0;
    }

In this function we create an instance of the requested class and return a QWidget pointer to the newly created widget. Copy this function changing the class name and the feature name and create an instance of your widget just as we've done here. (See the Qt Plugin documentation for more information.)

The includeFile() function.

    QString CustomWidgetPlugin::includeFile( const QString& feature ) const
    {
        if ( feature == "FileChooser" )
            return "filechooser.h";
        return QString::null;
    }

This function returns the name of the include file for the custom widget. Copy this function changing the class name, key and include filename to suit your own custom widget.

The group(), iconSet(), toolTip() and whatsThis() functions.

    QString CustomWidgetPlugin::group( const QString& feature ) const
    {
        if ( feature == "FileChooser" )
            return "Input";
        return QString::null;
    }

    QIconSet CustomWidgetPlugin::iconSet( const QString& ) const
    {
        return QIconSet( QPixmap( filechooser_pixmap ) );
    }

    QString CustomWidgetPlugin::includeFile( const QString& feature ) const
    {
        if ( feature == "FileChooser" )
            return "filechooser.h";
        return QString::null;
    }

    QString CustomWidgetPlugin::toolTip( const QString& feature ) const
    {
        if ( feature == "FileChooser" )
            return "File Chooser Widget";
        return QString::null;
    }

    QString CustomWidgetPlugin::whatsThis( const QString& feature ) const
    {
        if ( feature == "FileChooser" )
            return "A widget to choose a file or directory";
        return QString::null;
    }

We use the group() function to identify which Qt Designer toolbar group this custom widget should be part of. If we use a name that is not in use Qt Designer will create a new toolbar group with the given name. Copy this function, changing the class name, key and group name to suit your own widget plugin implementation.

The iconSet() function returns the pixmap to use in the toolbar to represent the custom widget. The toolTip() function returns the tooltip text and the whatsThis() function returns the Whats This text. Copy each of these functions changing the class name, key and the string you return to suit your own widget plugin implementation.

The isContainer() function.

    bool CustomWidgetPlugin::isContainer( const QString& ) const
    {
        return FALSE;
    }

Copy this function changing the class name to suit your widget plugin implementation. It should return TRUE if your custom widget can contain other widgets, e.g. like QFrame, or FALSE if it must not contain other widgets, e.g. like QPushButton.

The Q_EXPORT_PLUGIN macro.

    Q_EXPORT_PLUGIN( CustomWidgetPlugin )

This macro identifies the module as a plugin -- all the other code simply implements the relevant interface, i.e. wraps the classes you wish to make available.

This macro must appear once in your plugin. It should be copied with the class name changed to the name of your plugin's class. (See the Qt Plugin documentation for more information on the plugin entry point.)

Each widget you wrap in a widget plugin implementation becomes a class that the plugin implementation offers. There is no limit to the number of classes that you may include in an plugin implementation.

The Project File

The project file for a plugin is somewhat different from an application's project file but in most cases you can use our project file changing only the HEADERS and SOURCES lines.

SOURCES  += plugin.cpp ../widget/filechooser.cpp
HEADERS  += plugin.h ../widget/filechooser.h
DESTDIR   = ../../../../../plugins/designer
TARGET    = filechooser

target.path=$$plugins.path
isEmpty(target.path):target.path=$$QT_PREFIX/plugins
INSTALLS    += target
TEMPLATE     = lib
CONFIG      += qt warn_on release plugin
INCLUDEPATH += $(QTDIR)/tools/designer/interfaces
DBFILE       = plugin.db
LANGUAGE     = C++

qt/tools/designer/examples/filechooser/plugin/plugin.pro

Change the HEADERS line to list your plugin's header file plus a header file for each of your widgets. Make the equivalent change for the SOURCES line. If you create a Makefile with qmake and make the project the plugin will be created and placed in a directory where Qt Designer can find it. The next time you run Qt Designer it will detect your new plugin and load it automatically, displaying its icon in the toolbar you specified.

Using the Widget Plugin

Once the plugin has been compiled it will automatically be found and loaded by Qt Designer the next time Qt Designer is run. Use your custom widget just like any other.

If you want to use the plugin in another of your projects you can link against it by adding an appropriate line to the project, e.g. by adding a line like this to the project's .pro file:

LIBS += filechooser.lib

When you want to distribute your application, include the compiled plugin with the executable. Install the plugin in $QTDIR/plugins/widgets. If you don't want to use the standard plugin path, have your installation process determine the path you want to use for the plugin, and save the path, e.g. using QSettings, for the application to read when it runs. The application can then call QApplication::addLibraryPath() with this path and your plugins will be available to the application. Note that the final part of the path, i.e. styles, widgets, etc. cannot be changed.

 Plugins and Threaded Applications

If you want to build a plugin which you want to use with a threaded Qt library (whether or not the plugin itself uses threads) you must use a threaded environment. Specifically, you must use a threaded Qt library, and you must build Qt Designer with that library. Your .pro file for your plugin must include the line:

    CONFIG += thread

Do not mix the normal Qt library and the threaded Qt library in an application. If your application uses the threaded Qt library, you should not link with the normal Qt library. Nor should you dynamically load the normal Qt library or dynamically load another library, e.g. a plugin, that depends on the normal Qt library. On some systems, mixing threaded and non-threaded libraries or plugins will corrupt the static data used in the Qt library.

[Prev: Subclassing and Dynamic Dialogs] [Home] [Next: Creating Database Applications]

Copyright © 2002
TrolltechTrademarks

Qt version 3.0.5


Creating Database Applications

This chapter shows you how to use Qt's data-aware widgets from within Qt Designer. It demonstrates INSERT, UPDATE and DELETE in both QDataTables (tables) and QDataBrowsers (forms). It also shows how to code Master-Detail relationships and Drilldown. A simple approach to foreign key handling is presented here; a more sophisticated approach is shown in the online SQL module documentation.

If you wish to run the examples or create your own applications using these widgets you need access to an SQL database and a Qt database driver that can connect to the database. At the time of writing the drivers that Qt supports are QODBC3 (Open Database Connectivity), QOCI8 (Oracle), QPSQL7 (PostgreSQL 6 and 7) and QMYSQL3 (MySQL).

Although you can use the Qt data-aware widgets to browse and edit data in SQL databases without having to write any SQL, a basic understanding of SQL is highly recommended. We assume that you have some familiarity with SELECT, INSERT, UPDATE and DELETE statements. We also assume a basic understanding of the concepts of normalisation and of primary and foreign keys. A standard text covering SQL databases is An Introduction to Database Systems (7th ed.) by C. J. Date, ISBN 0201385902.

In the following text we describe the creation of a 'book' database application. The application demonstrates how to use QDataTables including in-place record editing and how to set up master-detail relationships between QDataTables. It also explains how to drill down from a QDataTable to another widget, for example, to a QDataBrowser or a QDataView and how to perform record editing in a QDataBrowser. A great deal of functionality is available from the classes directly in Qt Designer although subclassing is always available for finer control. If you want to build the 'book' examples you will need to create the example schema on your database.

The Book Application

The Example Schema

Note that the examples in this chapter all use the tables, views and records which are defined in the qt/tools/designer/examples/book/book.sql file. This file has been tested with PostgreSQL 6 and PostgreSQL 7. You may need to modify the SQL in this file to recreate the example database on your own system.

Schema CREATE TABLE Statements

    CREATE TABLE author
    ( id integer primary key,
    forename varchar(40),
    surname varchar(40) );

    CREATE TABLE book
    ( id integer primary key,
    title varchar(40),
    price numeric(10,2),
    authorid integer,
    notes varchar(255) );

    CREATE TABLE sequence
    ( tablename varchar(10),
    sequence numeric);

The 'book' table is simplified for the purposes of the example. It can only relate a book to a single author (authorid) and lacks an ISBN field. The 'sequence' table is used for generating unique index values for the example tables. Note that SQL databases often provide their own method for creating sequences (for example, using the CREATE SEQUENCE command) which is very likely to be a more optimal solution. For the sake of portability the examples will use a 'sequence' table which will work with the vast majority of SQL databases.

Setting Up Database Connections

There are two aspects of database connections that we must consider. Firstly the connection we wish to use within Qt Designer itself, and secondly the connection we wish to use in the applications that we create.

Setting Up Qt Designer's Connections

Database Connections Dialog

Choose Project|Database Connections from the menu bar. The Database Connections dialog will appear. Click New Connection. For applications that use a single database it will probably be most convenient to use the default connection name of '(default)'. If you use more than one database then each one must be given a unique name. A driver must be chosen from the Driver combo box. The database name may be available in the Database Name combo box or may have to be typed in. The database name, username, password and hostname should be provided by your database system administrator. When the Connection information has been completed click Connect. If the connection is made the connection name will appear in the list box on the left hand side of the dialog. You can now close the dialog; the connection settings will remain in effect until you change or delete them or exit from Qt Designer.

Qt Designer can remember database connection settings in qmake project files. Create a new project, e.g. click File|New, then click the 'C++ Project' icon to invoke the Project Settings dialog. Click the ellipsis button to invoke the Save As dialog; navigate to the project's directory (creating it if necessary). Make sure you're in the project's directory, then enter a project name of 'book.pro'. Click the Save button to return to the Project Settings dialog, then click OK. Next time you start Qt Designer instead of opening individual .ui files open the .pro project file instead and Qt Designer will automatically reload the project's connection settings. To activate the connection click Project|Database Connections. The connections previously saved with the project will be listed in the left hand list box. Click the connection you wish to use and then click Connect. This connection will be used from now on, e.g. for previewing QDataTables. Opening a project file also causes Qt Designer to load in the list of forms associated with the project into the Form List window. In most of the explanation that follows we will assume that you use project files and have clicked Connect so that there is always a connection available when you work in Qt Designer.

Setting Up Connections for Applications

The applications you create must make their own connections to the SQL database. We provide an example function, createConnections(), that you can use as a basis for your own code.

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( "QPSQL7" );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( "book" );
    defaultDB->setUserName( "bookuser" );
    defaultDB->setPassword( "bookpw" );
    defaultDB->setHostName( "bookhost" );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open books database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}

We call addDatabase() passing it the name of the driver we wish to use. We then set the connection information by calling the set... functions. Finally we attempt to open the connection. If we succeed we return TRUE, otherwise we output some error information and return FALSE. From qt/tools/designer/examples/book/book1/main.cpp

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

        if ( ! createConnections() )
            return 1;

        BookForm bookForm;
        app.setMainWidget( &bookForm );
        bookForm.show();

        return app.exec();
    }

All the examples presented in this chapter call createConnections() after creating the QApplication object in their main.cpp file and make use of the default connection. If you need to connect to multiple databases use the two-argument form of addDatabase(), passing it both the name of the driver and a unique identifier. This is explained further in the Qt SQL Module documentation.

You do not need to keep a reference to database connections. If you use a single database connection, this becomes the default connection and database functions will use this connection automatically. We can always get a pointer to any of our connections by calling QSqlDatabase::database().

If you create a main.cpp file using Qt Designer, this file will not include createConnections(). We do not include this function because it needs the username and password for the database connection, and you may prefer to handle these differently from our simple example function. As a result, applications that preview correctly in Qt Designer will not run unless you implement your own database connections function.

Using QDataTable

QDataTables may be placed on any form to provide browsing of database tables and views. QDataTables can also be used to update or delete records in-place, i.e. inside the cells themselves. Inserting records via a QDataTable usually requires connecting to the primeInsert() signal, so that we can generate primary keys for example, or provide default values. If we wish to present records using a form view (perhaps combining data from several tables and views) we might use several QDataBrowsers and QDataViews.

Quickly Viewing a Database Table

This example, along with all the other examples in this chapter, has the project name 'book' and uses the database created by the book.sql script. As we work through the chapter we will build the 'book' application step by step. Create or copy the qt/tools/designer/examples/book/book1/main.cpp file shown earlier. The project file for this first example is qt/tools/designer/examples/book/book1/book.pro. Start a new project by clicking File|New, then click the 'C++ Project' icon to invoke the Project Settings dialog. Click the ellipsis button to invoke the Save As dialog; navigate to the project's directory (creating it if necessary). Make sure you're in the project's directory, then enter a project name of 'book.pro'. Click the Save button to return to the Project Settings dialog, then click OK. Now click Project|Database Connections. Fill in the connection information appropriate to your database then press Connect. The connection name should now appear in the left hand list box. (If this doesn't happen you'll need to contact your database systems administrator for help.) Close the dialog.

We will now create a new form with a QDataTable that's connected to one of our database tables.

Click File|New. The New File dialog presents us with a number of form templates to choose from. Choose the 'Dialog' form and click OK. Now click File|Save. You will be prompted for a filename, call it book.ui.

Setting up a QDataTable

To place a QDataTable widget on the form either click Tools|Views|QDataTable or click the QDataTable toolbar button. Click on the form and the SQL Table Wizard will appear.

  1. The Database Connection and Table wizard page is used to set up a connection if one doesn't exist and to choose the table or view for the QDataTable. (See Setting Up Qt Designer's Connections.)

    Click the connection you wish to use, listed in the left hand list box, e.g. "(default)". The available tables and views will appear in the right hand Table list box. Click the 'author' table and then click the Next button.

  2. The Displayed Fields wizard page provides a means of selecting which fields should be displayed in the QDataTable and in what order. By default all fields except the primary key (if there is one) are in the Displayed Fields list box. The left- and right-pointing blue arrow buttons can be used to move fields between the Displayed Fields and the Available Fields list boxes. The blue up and down pointing arrow buttons are used to select the display order of the displayed fields.

    The default settings are the ones we want so simply click Next.

  3. The Table Properties wizard page provides convenient access to some of the database-related properties of the QDataTable.

    Make sure the Confirm Deletes checkbox is checked, then click Next.

  4. The SQL wizard page is used to set the QDataTable's Filter and Sort properties. The Filter is an SQL WHERE clause (without the word 'WHERE'). For example, to only list authors whose surnames begin with 'P', we would enter title LIKE 'P%'. We'll leave the filter empty. The Available Fields list box lists all the fields. The Sort By list box lists the fields that the QDataTable is to sort by and the direction of their sorting (ASCending or DESCending). The left and right blue arrows are used to move fields between the two list boxes. The up and down blue arrows move fields up and down within the Sort By list box. The ASC or DESC setting is changed with the 'sort order' toolbar button.

    Move the surname and forename fields into the Sort By list box and click Next.

  5. The Finish wizard page gives us the opportunity to go back and change any of our settings. We will be able to change them later through the QDataTable's properties so we can finish with the wizard.

    Click Finish.

The table will appear on the form with each column labelled with a default column name. If you wish to change the settings then most of them are available in the property window. The display names, the fields they are based upon, and the order of appearance of the columns can be changed using the Edit Table dialog (explained later) by right clicking the QDataTable and left clicking Edit.

Laying out the Form

Click on the form and click the Lay Out Vertically toolbar button. Now click Preview|Preview Form; the form will run and the table will automatically display all the records.

To turn the form we've created into an executable application we must add the main.cpp file to the project file and make the project. We should also do some renaming to make things easier to understand.

  1. Click on the form and change its name to 'BookForm' and its caption to 'Book'. Click on the QDataTable and change its name to 'AuthorDataTable'.

  2. Click File|Save All.

  3. Open the project file, e.g. book.pro, in a plain text editor and add the line: SOURCES += main.cpp at the end of the file.

  4. Run qmake to generate the make file, e.g. qmake -o Makefile book.pro, then make and run the book program.

This example shows how easy it is to use QDataTable to show the contents of a database table or view. You can use the application we've just built to update and delete author records. In the examples that follow we will cover insertions, setting up master-detail relationships, drilldown and foreign key lookups.

A Note on Foreign Keys

In most relational databases tables contain fields which are foreign keys into other tables. In our 'book' database example the authorid in the book table is a foreign key into the author table. When we present a form to the end user we do not usually want the foreign key itself to be visible but rather the text associated with it. Thus, we would want the author's name to appear rather than the author id when we show book information. In many databases, this can be achieved by using a view. See your database's documentation for details.

Inserting Records in QDataTables

Record insertion into a relational database usually requires the generation of a primary key value which uniquely identifies the record in the table. Also we often want to create default values for some fields to minimize the user's work. We will create a slot to capture the QDataTables primeInsert() signal and populate the QSqlRecord insertion buffer with a unique primary key.

  1. Click Edit|Slots to invoke the Edit Slots dialog. Click New Slot, then enter the slot name primeInsertAuthor(QSqlRecord*) into the Slot Properties' Slot line edit box. Click OK.

  2. Click the Connect Signals/Slots toolbar button, then click the AuthorDataTable, drag to the form and release the mouse. The Edit Connections dialog will now appear. Click the primeInsert() signal and then the primeInsertAuthor() slot to make the connection. Now click OK.

  3. Click the Source tab of the Object Hierarchy window (click Window|Object Hierarchy to make the window visible if necessary). Click the primeInsertAuthor() slot and an editor window will appear.

  4. We must change the BookForm::primeInsertAuthor() slot to specify the parameter name and perform the necessary action:

        void BookForm::primeInsertAuthor( QSqlRecord * buffer )
    {
        QSqlQuery query;
        query.exec( "UPDATE sequence SET sequence = sequence + 1 WHERE tablename='author';" );
        query.exec( "SELECT sequence FROM sequence WHERE tablename='author';" );
        if ( query.next() ) {
            buffer->setValue( "id", query.value( 0 ) );
        }
    }

    A QSqlQuery object is used to increment and retrieve a unique 'sequence' number for the author table. The signal passed us a pointer to the insertion buffer and we then put the value we've retrieved, i.e. the next sequence number, into the buffer's id field. (Again, note that SQL databases often support a native 'sequence' function. The method used here is inappropriate for production systems, and is for example purposes only. See your database's documentation for details on how to generate unique keys in code. In many cases, the database can generate them automatically, or the database may provide a special syntax for dealing with sequences.)

If we rebuild the application it will now support INSERT as well as UPDATE and DELETE. We could easily have added additional code to insert default values, e.g. today's date into a date field, if necessary.

Browsing is supported by clicking records and by using the arrow keys. Once a record is active (highlighted) we can edit the it. Press the Insert key to INSERT a new record; press F2 to UPDATE the current record; press the Del key to DELETE the current record. All these operations take place immediately. Users can be given the opportunity to confirm their edits by setting the QDataTable's confirmEdits property to True. If the confirmEdits property is True then user confirmation will be required for all insertions, updates and deletes. For finer control you can set the confirmInsert, confirmUpdate and confirmDelete properties individually.

QDataTable User Interface Interaction

The default user-interface behaviour for QDataTables is as follows:

  • Users can move to records by clicking the scrollbar and clicking records with the mouse. They can also use the keyboard's navigation keys, e.g. Left Arrow, Right Arrow, Up Arrow, Down Arrow, Page Up, Page Down, Home and End.

  • INSERT is initiated by right-clicking the record and clicking Insert or by pressing the Ins (Insert) key. The user moves between fields using Tab and Shift+Tab. The INSERT will take place if the user presses Enter or Tabs off the last field. If autoEdit is TRUE the insert will take place if the user navigates to another record. INSERT is cancelled by pressing Esc (Escape). If autoEdit is FALSE navigating to another record also cancels the INSERT. Setting confirmInsert to TRUE will require the user to confirm each INSERT.

  • UPDATE is initiated by right-clicking the record and clicking Update or by pressing F2. The update will take place if the user presses Enter or Tabs off the last field. If autoEdit is TRUE the update will take place if the user navigates to another record. UPDATE is cancelled by pressing Esc. If autoEdit is FALSE navigating to another record also cancels the UPDATE. Setting confirmUpdate to TRUE will require the user to confirm each UPDATE.

  • DELETE is achieved by right-clicking the record and clicking Delete or by pressing the Del (Delete) key. Setting confirmDelete to TRUE will require the user to confirm each DELETE.

You can change this default behaviour programmatically if required.

Relating Two Tables Together (Master-Detail)

Databases often have pairs of tables that are related. For example, an invoice table might list the numbers, dates and customers for invoices, but not the actual invoice items, which an invoice item table might store. In the 'book' application we wish to have a QDataTable that we can use to browse through the authors table and a second QDataTable to show the books they've written.

Open the book project if it isn't already open Qt Designer. We will modify this project to show two QDataTables that relate the author table to the book table.

  1. Click the author QDataTable and then click the Break Layout toolbutton.

  2. Resize the QDataTable so that it only occupies the top half of the form.

  3. Now click on the QDataTable toolbutton and click on the bottom half of the form. The SQL Table Wizard will appear. (This Wizard is explained in Quickly Viewing a Database Table.)

    1. Click the connection you're using and click the book table. Click the Next button.

    2. Since we do not want them visible, make sure the authorid and id fields are moved to the Available Fields list box by using the arrow buttons. Move the title field to the top of the Displayed Fields, and move the price field above the notes field. Click the Next button.

    3. On the Table Properties page click the Read Only checkbox then click the Next button.

    4. On the SQL page we will leave the Filter (WHERE clause) empty. Move the title field to the Sort By list box and click Next. Now click Finish.

    5. Change this QDataTable's name to "BookDataTable".

  4. Shift+Click the top QDataTable so that both QDataTables are selected and then click the Lay Out Vertically (in Splitter) toolbar button.

  5. Click on the form and click the Lay Out Vertically toolbar button.

Run the form by clicking Preview|Preview Form. All the authors are displayed in the top QDataTable and all the books are displayed in the bottom QDataTable. However we only want the books of the currently selected author showing in the bottom QDataTable. We will deal with this by filtering the records in the book table according to the author selected in the author table.

Using the Table Editor

Edit Table Dialog

QDataTables are created and set up using the SQL Table Wizard. Like any other Qt Designer widget their properties may be changed in the Properties window. Some of the column and row based properties can also be be changed using the Edit Table dialog. This dialog is invoked by right clicking the QDataTable and left clicking the Edit menu item. The right hand half of the Edit Table dialog is where we choose the fields we wish to display, their order and their labels. The procedure for creating columns is as follows:

  1. Click the New Column button.

  2. Drop down the Field combobox to list the available fields.

  3. Click the field you wish to include at this point.

  4. Optionally edit the Label if the default isn't appropriate.

  5. Optionally click the Pixmap ellipsis (...) button to choose a pixmap to be displayed to the left of the column's label. (The ellipsis button appears when you click in the Value part of the Properties list by a pixmap or iconSet property.)

Repeat the steps listed above for each column you wish to add. Once all the fields have been added you can change their ordering by using the blue up and down arrow buttons. At any point you can press Apply to see how the table will look. Finally click the OK button to save the properties you have set. You can always return to the table editor to change these settings later.

Filtering One QDataTable by Another

To filter the book table's records we need to capture the author QDataTable's currentChanged() signal and change the BookDataTable's filter accordingly.

  1. Click Edit|Slots. In the Edit Slots dialog click New Slot and enter a slot name of newCurrentAuthor(QSqlRecord*). Click OK.

  2. Click Connect Signals/Slots, then click the AuthorDataTable QDataTable and drag to the form; release the mouse on the form. The Edit Connections dialog will appear. Click the currentChanged() signal and the newCurrentAuthor slot. Click OK.

  3. Click the Source tab of the Object Hierarchy window (click Window|Object Hierarchy to make the window visible if necessary). Click the newCurrentAuthor() slot and an editor window will appear.

  4. We must change the BookForm::newCurrentAuthor() slot to specify the parameter name and perform the necessary action:

        void BookForm::newCurrentAuthor( QSqlRecord *author )
    {
        BookDataTable->setFilter( "authorid=" + author->value( "id" ).toString() );
        BookDataTable->refresh();
    }

    All that's required now is to change the BookDataTable's filter and refresh the QDataTable to show the results of the filter.

Preparing the Interface for Drilldown

We can now browse and edit authors and see their books in the BookDataTable. In the next section we explore QDataBrowser, which will allow us to drill down to a dialog through which we can edit books. For now we will add some buttons to the main BookForm which we will use to invoke the book editing dialog.

  1. Click the form, then click the Break Layout toolbar button. Resize the form to make room for some buttons at the bottom.

  2. Add two buttons to the bottom of the form. Change their names and labels to the following:

    • EditPushButton -- &Edit Books

    • QuitPushButton -- &Quit

    Hold down the Shift key and Click both buttons (i.e. Shift+Click the buttons) and click the Lay Out Horizontally toolbar button. Click the form and click the Lay Out Vertically toolbar button.

  3. We will provide the Quit button with functionality now and work on the rest shortly. Click Connect Signals/Slots, then click the Quit button and drag to the form; release the mouse on the form. The Edit Connections dialog will appear. Click the clicked() signal and the accept() slot. Click OK.

Using QDataBrowser and QDataView

The Book Application's Edit Books Dialog

Drilling Down to a Form using QDataBrowser

Setting up a QDataBrowser

We will now create a new form to allow users to edit book records. Click the New toolbar button, click the Dialog template from the New File dialog and click OK. Change the name of the form to EditBookForm and its caption to 'Edit Books'. Click the Save toolbar button and call the file editbook.ui. Now that we have the form we can add a QDataBrowser to show the book records.

  1. Click the Data Browser toolbar button, then click the form. The Data Browser Wizard will appear.

  2. The Database Connection and Table wizard page is used to set up a connection if one doesn't exist and to choose the table or view for the QDataBrowser. (See Setting Up Qt Designer's Connections.)

    Click the connection you wish to use, listed in the Connection list box, e.g. "(default)". The available tables and views will appear in the Table list box. Click the book table and then click the Next button.

  3. The Displayed Fields wizard page provides a means of selecting which fields should be displayed in the QDataBrowser and in what order. By default all fields except the primary key (if there is one) are in the right hand Displayed Fields list box. The left and right blue arrow buttons can be used to move fields between the Displayed Fields and the Available Fields list boxes. The blue up and down arrow buttons are used to select the display order of the displayed fields.

    We don't want to see the authorid foreign key field on the form, so move it to the Available Fields list box. Also, move the title field to the top of the Displayed Fields list. Click the Next button.

  4. The Navigation and Editing wizard page allows us to choose which navigation and editing buttons should appear on the form.

    We will accept the defaults and simply click the Next button.

  5. The SQL wizard page is used to set the QDataBrowser's Filter and Sort properties. The Filter is an SQL WHERE clause (without the word 'WHERE'). For example, to only list books that cost less than 50 (of some currency, e.g. dollars), we would enter price < 50. We will leave the filter empty. The Available Fields list box lists all the fields. The Sort By list box lists the fields that the QDataBrowser is to sort by and the direction of their sorting (ASCending or DESCending). The left and right blue arrows are used to move fields between the two list boxes. The up and down blue arrows move fields up and down within the Sort By list box. The ASC or DESC setting is changed with the sort order button.

    Move the title field into the Sort By list box and click Next.

  6. The Layout wizard page is used to specify the initial layout of the form.

    Change the Number of Columns to 1, then click Next. Now click Finish.

  7. The QDataBrowser will now appear on the form. Resize the form to make it shorter. Click the QDataBrowser then click the Break Layout toolbar button. Click the buttons then click the Break Layout toolbar button. Add another button called 'PushButtonClose' with the text '&Close' and place it to the right of the Delete button.

  8. Shift+Click the Insert, Update, Delete and Close buttons, then click the Lay Out Horizontally toolbar button. Click the QDataBrowser, then click the Lay Out in a Grid toolbar button. Finally click the form and click the Lay Out Vertically toolbar button. Now click the QDataBrowser and rename it 'BookDataBrowser'.

  9. Qt Designer will generate the necessary code to make the browser operational (including generating the appropriate cursor, sort and filter code).

    For finer control over the form, we will be creating our own database cursor. Therefore, set the BookDataBrowser's frameworkCode property to FALSE in the Properties window to prevent Qt Designer from generating redundant code for the cursor.

QDataBrowser User Interface Interaction

The user-interface behaviour for QDataBrowsers is created by connecting slots and signals. The slots provided are:

  • insert(), update() and del() for editing;

  • first(), next(), prev(), and last() for navigation;

  • refresh() to refresh the cursor from the database;

  • readFields() to read data from the cursor's edit buffer and writeFields() to write the form's data to the cursor's edit buffer;

  • clearValues() to clear the form's values.

If you use Qt Designer's QDataBrowser wizard you will be given the option of creating a default set of buttons for navigation and editing. The behaviour of these buttons is set up using the slots described above to provide the following functionality:

  • INSERT is initiated by pressing the Ins (Insert) button. The user moves between fields using Tab and Shift+Tab. If the user presses the Update button the INSERT will take place and the user will be taken to the record they have just inserted. If the user presses the Insert button (i.e. a second time) the INSERT will take place and a new insertion will be initiated. If autoEdit is TRUE the INSERT will take place if the user navigates to another record. INSERT is cancelled by pressing the Esc key or by pressing the Del (Delete) button. If autoEdit is FALSE then navigating to another record also cancels the INSERT. Setting confirmInsert to TRUE will require the user to confirm each INSERT.

  • UPDATE is automatically initiated whenever the user navigates to a record. An update will take place if the user presses the Update button. If autoEdit is TRUE the update will take place if the user navigates to another record. UPDATE is cancelled by pressing the Esc key or by pressing the Del button. If autoEdit is FALSE then navigating to another record also cancels the UPDATE. Setting confirmUpdate to TRUE will require the user to confirm each UPDATE.

  • DELETE is achieved by pressing the Del button. Setting confirmDelete to TRUE will require the user to confirm each DELETE.

Performing the Drilldown

We now have a working form for editing book records. We need to start the form when the user clicks our 'Edit Books' button, and to navigate to the record they have selected in the BookDataTable. We also need to provide a means of editing the foreign keys, e.g. authorid.

  1. We need to make a new slot to connect the Edit Books' button's clicked() signal to. Click on the Book form to make it Qt Designer's active form. Invoke the Edit Slots dialog and create a new slot called editClicked(). Now click the Connect Signals/Slots toolbar button. Click the Edit Books button and drag to the form; release the mouse on the form. In the Edit Connections dialog connect the clicked() signal to the editClicked() slot. Click OK to leave the dialog.

  2. In the Object Hierarchy window click Source and then click the editClicked function. We need to change it to the following:

        void BookForm::editClicked()
    {
        EditBookForm *dialog = new EditBookForm( this, "Edit Book Form", TRUE );
        QSqlCursor cur( "book" );
        dialog->BookDataBrowser->setSqlCursor( &cur );
        dialog->BookDataBrowser->setFilter( BookDataTable->filter() );
        dialog->BookDataBrowser->setSort(QSqlIndex::fromStringList(
            BookDataTable->sort(), &cur ) );
        dialog->BookDataBrowser->refresh();
        int i = BookDataTable->currentRow();
        if ( i == -1 ) i = 0; // Always use the first row
        dialog->BookDataBrowser->seek( i );
        dialog->exec();
        delete dialog;
        BookDataTable->refresh();
    }

    We create our dialog as before. We also create a cursor over the book table and set the dialog's QDataBrowser, BookDataBrowser, to use this new cursor. We set the QDataBrowser's filter and sort to those that applied to the main form's book QDataTable. We refresh the QDataBrowser and seek to the same record the user was viewing on the main form. Then we exec the dialog and delete it when the user has finished with it. Finally we update the BookDataTable in the main form to reflect any changes that were made in the dialog.

  3. Because our code refers to a class declared in editbook.h and to a QDataBrowser we need to add two additional include files. Click on the BookForm, then click on the Source tab of the Object Hierarchy window. Right click the 'Includes (In Declaration)' item and click New. Type in "editbook.h". Now add a second include, this time, <qdatabrowser.h>.

Now when we navigate through the author and book records in the BookForm we can click the Edit Books button to launch our Edit Books dialog. Although the dialog supports UPDATE, DELETE and navigation over the book table, we cannot edit the foreign keys nor perform inserts. We will deal with insertion in the same way as we did with the QDataTable, then we will handle the foreign key relationship to author.

Inserting into a QDataBrowser

We will create a slot to receive the Edit Books form's primeInsert() signal so that we can insert a unique primary key.

  1. Click on the Edit Books form, then create a new Slot called primeInsertBook(QSqlRecord*).

    Click Edit|Slots, then click the New Slot button and type the new slot name in the Slot Properties Slot edit box. Click OK.

  2. Connect the BookDataBrowser's primeInsert() signal to the primeInsertBook() slot.

    Click the Connect Signals/Slots toolbar button, then click the BookDataBrowser and drag to the form; release the mouse on the form. Now click the primeInsert() signal and the primeInsertBook slot. Click OK.

  3. In the Object Hierarchy window click Source and then click the primeInsertBook slot. We need to change it to the following:

        void EditBookForm::primeInsertBook( QSqlRecord * buffer )
    {
        QSqlQuery query;
        query.exec( "UPDATE sequence SET sequence = sequence + 1 WHERE tablename='book';" );
        query.exec( "SELECT sequence FROM sequence WHERE tablename='book';" );
        if ( query.next() ) {
            buffer->setValue( "id", query.value( 0 ) );
        }
    }

  4. We will also tidy up the user interface slightly. Click the Update button and set its default property to True. Connect the Close button's clicked() signal to the EditBookForm's accept() slot.

Handling Foreign Keys in a QDataBrowser

Qt's SQL module provides two approaches to dealing with foreign keys. The most powerful and flexible is to subclass widgets and use property maps to relate the widgets to the database. This approach is described in the Qt SQL Module documentation, particularly the StatusPicker example. A simpler approach that can be taken wholly within Qt Designer is presented here.

We will add a new field to the EditBookForm so that authors can be edited along with the title and price. Once we've handled the visual design we'll write the code to make it all work.

  1. First we'll add the new widgets. Click the BookDataBrowser and click the Break Layout toolbar button. Resize the form to make it larger and drag each set of buttons down to make some room below the title and price QLineEdits. Click the Text Label toolbar button and click on the form beneath the Price label. Click the Text Label and change its text to 'Author'. Click the ComboBox toolbar button and click on the form beneath the price QLineEdit. In the Property Window change the ComboBox's name to ComboBoxAuthor and change its sizePolicy hSizeType to Expanding.

  2. Now we'll lay out the dialog. Shift+Click the Author label and the ComboBox then click the Lay Out Horizontally toolbar button. Now click the BookDataBrowser and click the Lay Out in a Grid toolbar button.

We need to write some code so that the ComboBox will be populated with author names and scroll to the current book's author. We also need to ensure that we put the author's id into the book table's authorid field when a book record is inserted or updated. We'll ensure the code is executed at the right time by putting it in slots and connecting signals to our slots.

  1. Create two new slots called beforeUpdateBook(QSqlRecord *buffer) and primeUpdateBook(QSqlRecord *buffer). (Click Edit|Slots, then in the Edit Slots dialog click New Slot and enter the first new slot. Click New Slot again and enter the second slot then click OK.)

  2. When the user navigates through the dialog, each time they move to a new record, a primeUpdate() signal is emitted. We connect to this so that we can update the ComboBox's display. Just before a record is updated or inserted into the database a beforeUpdate() or beforeInsert() signal is emitted. We connect our beforeUpdateBook() slot to both these signals so that we can ensure that the book's authorid field is correctly populated.

    Click the BookDataBrowser and drag the mouse to the form; release the mouse and the Edit Connections dialog will appear. Connect the beforeUpdate() signal to our beforeUpdateBook() slot. Connect the beforeInsert() signal to our beforeUpdateBook() slot. Finally connect the primeUpdate() signal to our primeUpdateBook() slot.

  3. All that remains is to write the underlying code. All the code snippets are taken from qt/tools/designer/examples/book/book7/editbook.ui.

    1. We start with the init() function; this is called after the dialog is constructed and we will use it to populate the ComboBox with author names.

          void EditBookForm::init()
    {
        QSqlQuery query( "SELECT surname FROM author ORDER BY surname;" );
        while ( query.next() )
            ComboBoxAuthor->insertItem( query.value( 0 ).toString());
    }

      Here we execute a query to get a list of author names and insert each one into the ComboBox.

    2. We next write the code which will be executed just before a record is updated (or inserted) in the database.

          void EditBookForm::beforeUpdateBook( QSqlRecord * buffer )
    {
        QSqlQuery query( "SELECT id FROM author WHERE surname ='" +
            ComboBoxAuthor->currentText() + "';" );
        if ( query.next() )
            buffer->setValue( "authorid", query.value( 0 ) );
    }

      We look up the id of the ComboBox's current author and place it in the update (or insert) buffer's authorid field.

    3. As the user navigates through the records we ensure that the ComboBox reflects the current author.

          void EditBookForm::primeUpdateBook( QSqlRecord * buffer )
    {
        // Who is this book's author?
        QSqlQuery query( "SELECT surname FROM author WHERE id='" +
            buffer->value( "authorid" ).toString() + "';" );
        QString author = "";
        if ( query.next() )
            author = query.value( 0 ).toString();
        // Set the ComboBox to the right author
        for ( int i = 0; i < ComboBoxAuthor->count(); i++ ) {
            if ( ComboBoxAuthor->text( i ) == author ) {
                ComboBoxAuthor->setCurrentItem( i ) ;
                break;
            }
        }
    }

      Firstly we look up the book's author and secondly we iterate through the ComboBox's items until we find the author and set the ComboBox's current item to the matching author.

If the author name has changed or been deleted the query will fail and no author id will be inserted into the buffer causing the INSERT to fail. An alternative is to record the author id's as we populate the ComboBox and store them in a QMap which we can then look up as required. This approach requires changes to the init(), beforeUpdateBook() and primeInsertBook() functions and the addition of a new function, mapAuthor(). The relevant code from qt/tools/designer/examples/book/book8/editbook.ui is shown below.

  1. First we need to create a class variable to map author names to author id's. Click in the Source tab of the Object Hierarchy, then right click the Class Variables item and click New. Type in 'QMap<QString,int> authorMap;'.

  2. We now record the author id's in the init() function.

        void EditBookForm::init()
    {
        QSqlQuery query( "SELECT surname, id FROM author ORDER BY surname;" );
        while ( query.next() ) {
            ComboBoxAuthor->insertItem( query.value( 0 ).toString() );
            int id = query.value( 1 ).toInt();
            mapAuthor( query.value( 0 ).toString(), id, TRUE );
        }
    }

    After inserting each author's name into the ComboBox we populate a QMap with the author's name and id.

  3. Instead of looking up the author's id in the database we look it up in the QMap.

        void EditBookForm::beforeUpdateBook( QSqlRecord * buffer )
    {
        int id;
        mapAuthor( ComboBoxAuthor->currentText(), id, FALSE );
        buffer->setValue( "authorid", id );
    }

  4. We use a single function for storing author id's and returning them so that we can use a static data structure.

        void EditBookForm::mapAuthor( const QString & name, int & id, bool populate )
    {
        if ( populate )
            authorMap[ name ] = id;
        else
            id = authorMap[ name ];
    }

    If the populate flag is TRUE, we store the author's name and id in the QMap, otherwise we look up the given author name and set id appropriately.

  5. Before we perform an update we need to know who the book's author is, and we need to update the combobox.

        void EditBookForm::primeUpdateBook( QSqlRecord * buffer )
    {
        // Who is this book's author?
        QSqlQuery query( "SELECT surname FROM author WHERE id=" +
            buffer->value( "authorid" ).toString() + ";" );
        QString author = "";
        if ( query.next() )
            author = query.value( 0 ).toString();
        // Set the ComboBox to the right author
        for ( int i = 0; i < ComboBoxAuthor->count(); i++ ) {
            if ( ComboBoxAuthor->text( i ) == author ) {
                ComboBoxAuthor->setCurrentItem( i ) ;
                break;
            }
        }
    }

Another approach which is especially useful if the same foreign key lookups are required in different parts of the application is to subclass a cursor and use this for our lookups. This is described in the Qt SQL Module documentation, particulary the section on subclassing QSqlCursor.

The 'book' example demonstrates the basic techniques needed for SQL programming with Qt. Additional information on the Qt SQL classes, especially the QSqlQuery and QSqlCursor classes is provided in the Qt SQL Module documentation.

[Prev: Creating Custom Widgets] [Home] [Next: Customizing and Integrating Qt Designer]


Customizing and Integrating Qt Designer

Customizing Qt Designer

Qt Designer can be customized in two ways: you can add custom widgets, and you can change aspects of how Qt Designer works. Custom widgets are covered in Creating Custom Widgets. This section will focus on customizing Qt Designer itself.

Qt Designer's toolbars are all dockable so they can be dragged by their toolbar handles and arranged how you like. The Files, Object Hierarchy, Property Editor and Output Windows are also dockable so you can also drag them to the positions that you prefer. You can also make them into floating windows by dragging them outside Qt Designer's dock areas.

General preferences can be set by clicking Edit|Preferences to invoke the Preferences dialog. If you check the 'Restore Last Workspace on Startup' checkbox then Qt Designer will remember the sizes and positions of the toolbars and the dockable windows. You can change Qt Designer's main window background either by selecting a color or a pixmap. You can also switch off the grid (uncheck Show Grid) since using layouts makes the grid redundant.

The Preferences dialog may have additional tabs, depending on what plugins you have installed. We'll describe the C++ Editor tab since this is installed by default.

The C++ Editor tab is used to set your preferred fonts for syntax highlighting in Qt Designer's code editor. The base font for all elements is set in the 'Standard' element which is the last item in the list. If you want one font to be used throughout then set the 'Standard' font and all the other elements will inherit its setting.

Qt Designer's Code Editor

The code editor is available if an Editor plugin is installed. The C++ Editor plugin is installed by default.

The code editor provides the following keystrokes:

  • Left Arrow -- Moves the cursor one character left

  • Right Arrow -- Moves the cursor one character right

  • Up Arrow -- Moves the cursor one line up

  • Down Arrow -- Moves the cursor one line down

  • Page Up -- Moves the cursor one page up

  • Page Down -- Moves the cursor one page down

  • Backspace -- Deletes the character to the left of the cursor

  • Home -- Moves the cursor to the beginning of the line

  • End -- Moves the cursor to the end of the line

  • Delete -- Deletes the character to the right of the cursor

  • Ctrl+A -- Moves the cursor to the beginning of the line

  • Ctrl+B -- Moves the cursor one character left

  • Ctrl+C -- Copies the selected text to the clipboard (also Ctrl+Insert under Windows)

  • Ctrl+D -- Deletes the character to the right of the cursor

  • Ctrl+E -- Moves the cursor to the end of the line

  • Ctrl+F -- Invokes the Find Text dialog

  • Ctrl+G -- Invokes the Goto Line dialog

  • Ctrl+H -- Deletes the character to the left of the cursor

  • Ctrl+I -- Indent the line or selected text that contains the cursor

  • Alt+I -- Starts incremental search (see below)

  • Ctrl+K -- Deletes from the cursor position to the end of the line

  • Ctrl+N -- Moves the cursor one line down

  • Ctrl+P -- Moves the cursor one line up

  • Ctrl+R -- Invokes the Replace Text dialog

  • Ctrl+V -- Pastes the clipboard text into line edit (also Shift+Insert under Windows)

  • Ctrl+X -- Cuts the marked text, copy to clipboard (also Shift+Delete under Windows)

  • Ctrl+Y -- Redoes the last operation

  • Ctrl+Z -- Undoes the last operation

  • Ctrl+Left Arrow -- Moves the cursor one word left

  • Ctrl+Right Arrow -- Moves the cursor one word right

  • Ctrl+Up Arrow -- Moves the cursor one word up

  • Ctrl+Down Arrow -- Moves the cursor one word down

  • Ctrl+Home Arrow -- Moves the cursor to the beginning of the text

  • Ctrl+End Arrow -- Moves the cursor to the end of the text

  • Tab -- Completion (see below)

To select (mark) text hold down the Shift key whilst pressing one of the movement keystrokes, for example, Shift+Right Arrow will select the character to the right, and Shift+Ctrl+Right Arrow will select the word to the right, etc.

Pressing Alt+I starts incremental search. The characters you type will appear in the Incremental Search line edit in the Search toolbar and the cursor will be moved to the first matching text in the editor. As you type the search will continue. Press Return to move to the next match and press Esc to cancel the search at the position you've reached.

Pressing Tab after you've typed one or more characters invokes completion. Completion works like this: start typing some text then press Tab. If the editor can find another item of text that begins with the same characters it will complete your text for you; if it finds more than one possibility it will pop up a list of choices. You can use the arrow keys to choose a piece of text then press Return, or press Esc to continue typing. You can switch off completion in the Preferences dialog.

When you enter -> or . the editor will pop up a command completion list; use the arrow keys to move to the item you want and press Return, or press Esc to ignore the list.

Creating and Using Templates

Qt Designer supports two approaches to creating template forms. The simplest approach involves little more than saving a .ui file into the templates directory. The second approach involves creating a container widget class to be used as a base class for forms that use the template. We will explain both techniques.

Simple Templates

These templates are most useful when you want to create a whole set of forms which all have some common widgets. For example, you might have a project that will require many forms, all of which need to be branded with a company name and logo.

First we'll create the simple template.

  1. Click File|New to invoke the New File dialog. Click the Dialog template then click OK.

  2. Click the Text Label toolbar button, then click near the top left of the form. Change the font Point Size property to 16 and change the text property to your or your company's name. Click the Line toolbar button, then click the form below the label; click Horizontal on the pop-up menu.

  3. Select the label and the line. (Ctrl+Click the form, then drag the rubber band so that it touches or includes the line and the label.) Press Ctrl+L to lay them out vertically.

  4. Click the Save toolbar button. In the Save As dialog, navigate to Qt Designer's templates directory, e.g. (qt/tools/designer/templates. Type in the name 'Simple_Dialog.ui' and click Save.

  5. Right click the form in the Forms list, then click Remove form from project.

Now that we have the simple template we are ready to use it. Click File|New to invoke the New File dialog. One of the templates that will appear is 'Simple Dialog'. Click the simple dialog, then click OK. A new form will appear with the same widgets and layout as the template. Add any other widgets and functionality. When you attempt to save the form you will be prompted for a new form name.

Base-class Templates

These templates are useful when you want to provide some default functionality that all the forms based on the base class can inherit. In our example we'll use a class called SizeAware that remembers and restores its size as the basis of a template. We won't describe the class itself, but will focus instead on making use of it as a Qt Designer template. The source for the class is in qt/tools/designer/examples/sizeaware.

The template can either be based on a custom widget or on any existing container widget.

If you want to base the template on a custom widget you must first add it to Qt Designer's custom widgets. Click Tools|Custom|Edit Custom Widgets to invoke the Edit Custom Widgets dialog. (This dialog is explained in more detail in Simple Custom Widgets.) Click New Widget. Change the Class from 'MyCustomWidget' to 'SizeAware'. Click the Headerfile ellipsis button and select the file qt/tools/designer/examples/sizeaware/sizeaware.h. Check the Container Widget checkbox. This class provides two properties. Click the Properties tab. Click New Property and change the property name to 'company'. Click the New Property again and change the property name to 'settingsFile'. Click Close.

To create a template, based on an existing widget or on your own custom widget, click File|Create Template to invoke the Create Template dialog. Change the Template Name to 'SizeAware' and click the SizeAware base class, then click Create. The dialog will create the template and close itself immediately. Close Qt Designer and restart it.

A new template, 'SizeAware' is now available from the list of templates. Click File|New, click SizeAware and click OK. Note that the two properties, company and settingsFile, are available in the Properties window. Any forms based on this template will remember their size and resize when reloaded. (In practical applications having one settingsFile per form is not recommended, so this template would only really be useful for applications that have a single main window.)

Integrating Qt Designer with Visual Studio

Qt Designer can be integrated into Visual Studio using the qmsdev.dsp file that is supplied with Qt.

Start up Visual Studio and click File|Open Workspace. Open %QTDIR%\tools\designer\integration\qmsdev\qmsdev.dsp. Click Build|Set Active Configuration and in the list click 'QMsDev - Win32 Release', then click OK. Now click Build|Build qmsdev.dll. You should now copy the file %QTDIR%\tools\designer\integration\qmsdev\Release\qmsdev.dll into Microsoft Visual Studio\Common\MSDev98\AddIns. Now click Tools|Customize. Click the Add-in Macro Files tab, then click the Browse button. Change the file type to 'Add-ins (.dll)' and navigate to Microsoft Visual Studio\Common\MSDev98\AddIns. Click the qmsdev.dll file, click Open, then click Close.

A new toolbar will appear in Visual Studio with the following toolbar buttons:

  • New Qt Project -- A small application wizard

  • Generate Qt Project -- Runs qmake (or the functionally equivalent tmake) with a .pro file

  • New Qt Dialog -- Add an empty Qt Dialog to the active project

  • Qt GUI Designer -- Run Qt Designer

  • Use Qt -- Add the Qt libraries to the active project

  • Add MOC -- Add the moc precompiler to the active file

  • Add UIC -- Add the uic precompiler to the active file

Double clicking a .ui file in the workspace overview will now launch Qt Designer.

If you create a .cpp file which contains the Q_OBJECT macro you will need an additional file which is generated by the moc to be included in your project. For example, if you have 'file.cpp', then the last line would be #include "file.moc" and the additional file would be called 'file.moc'. To ensure that Visual Studio executes the moc and generates this file you must create a custom dependency. Double click the .cpp file (in your project workspace) that contains the Q_OBJECT macro. Click the Add MOC toolbar button; this will create an empty .moc file in your project workspace. Right click the newly created .moc file, then click Settings from the pop-up menu to invoke the Project Settings dialog. Click the Custom Build tab. Click the Dependencies button to pop up the User Defined Dependencies dialog. Type in $(InputDir)\$(InputPath), then press Return. Click OK to leave the Dependencies dialog, then click OK to leave the Project Settings dialog.

If you wish to delete the add-in remove it from the toolbar then delete the qmsdev.dll file from the add-ins directory.

Creating Makefiles without qmake

The qmake tool provided with Qt can create Makefiles appropriate to your platform based on .pro project files. This section describes the dependencies involved in building a Qt application and gives a couple of simple example Makefiles. This section assumes that you have a good understanding of Makefiles.

Qt Designer produces .ui files which are used to generate .h and .cpp files for the compiler to compile. The .ui files are processed by uic. Classes which inherit from QObject, e.g. those which use slots and signals, require an additional .cpp file to be generated. These files are generated by the moc and are named 'moc_file.cpp' where the original .cpp file is called 'file.cpp'. If your .cpp file contains the Q_OBJECT macro an additional file 'file.moc' should be generated which must be #included in the .cpp, normally at the end. This requires an extra dependency being created.

Processing .ui files with uic is done twice:

uic myform.ui -o myform.h
uic myform.ui -i myform.h -o myform.cpp

The first execution creates the header file, the second creates the .cpp file. If you wish to subclass a form you can use uic to generate subclass skeletons:

uic formbase.ui -o formbase.h
uic formbase.ui -i formbase.h -o formbase.cpp
uic -subdecl Form formbase.h formbase.ui -o form.h
uic -subimpl Form form.h formbase.ui -o form.cpp

First we generate the header and implementation file for our base class. Then we generate the header and implementation skeletons for our subclass. Note that the use of uic to generate skeletons is not something that would be done in a Makefile, we mention it here because it can be useful for command line users. Note also that the command line for -subdecl and for subimpl are subtly different.

For implementation files that contain classes which inherit from QObject we must create moc files:

moc myform.h -o moc_myform.cpp

We'll look at a simple Makefile to see the dependencies in practice.

myapp: moc_myform.o myform.o main.o
        g++ -lqt -o myapp moc_myform.o myform.o main.o

main.o: main.cpp
        g++ -o main.o main.cpp

moc_myform.o: moc_myform.cpp
        g++ -o moc_myform.o moc_myform.cpp

moc_myform.cpp: myform.h
        moc myform.h -o moc_myform.cpp

myform.o: myform.cpp
        g++ -o myform.o myform.cpp

myform.cpp: myform.h myform.ui
        uic myform.ui -i myform.h -o myform.cpp

myform.h: myform.ui
        uic myform.ui -o myform.h

Note that you may need to include the full path to the commands in your Makefile, and under Windows the filenames are moc.exe and uic.exe.

In Unix/Linux environments the make command may be able to do more for us, so we should be able to use a simpler Makefile like this:

myapp: moc_myform.o myform.o main.o
        g++ -lq -o $@ $^

%.o: %.cpp
        g++ -o $^ $@

moc_%.cpp: %.h
        moc $^ -o $@

myform.cpp: myform.h myform.ui
        uic myform.ui -i myform.h -o myform.cpp

myform.h: myform.ui
        uic myform.ui -o myform.h

To see more sophisticated Makefiles simply generate them using qmake on any of your Qt projects or any of the examples supplied with Qt.

Importing Foreign File Formats

To import a file in a supported foreign file format click File|Open, then click the File Type combobox to choose the file type you wish to load. Click the required file and Qt Designer will convert and load the file.

The filters that Qt Designer uses to read foreign file formats are 'works in progress'. You may have different filters available in your version of Qt Designer than those described here. The easiest way to see which filters are available is to invoke the file open dialog; all your filters are listed in the File Type combobox.

Importing Qt Architect Files

Qt Architect is a free GUI builder for Qt written by Jeff Harris and Klaus Ebner. The .dlg extension is associated with Qt Architect dialog files.

Qt Designer can read files generated by Qt Architect version 2.1 and above. When given a .dlg file from a previous version of Qt Architect, Qt Designer tells you how to convert it to the file format of version 2.1. (The conversion procedure varies depending on the version of the .dlg file.)

The import filter does a good job of importing .dlg files; the result is almost identical to what you get in Qt Architect. However, the C++ code that uses the dialogs will probably need some adaptation.

There are a few drawbacks to converting Qt Architect files to Qt Designer's format due to differences between the two tools; these are listed below:

  • Layout spacing and margins

    If the .dlg file layouts use the Qt Architect defaults for layout spacing and margins, Qt Designer will override these with its standard defaults. You can change the "layoutSpacing" and "layoutMargin" properties manually afterwards if necessary.

  • Layout stretches and spacings

    Qt Architect gives access to more features of Qt's layout system than Qt Designer, namely stretches and spacings. Qt Designer will attempt to cope with .dlg files that use these features, but sometimes the resizing will not be what you want. The solution typically involves setting the "sizePolicy" properties of some widgets and inserting or deleting spacers.

  • Mixing managed and unmanaged widgets

    Qt Architect allows a widget to have some child widgets managed by a layout and other child widgets with fixed positions. When presented with a .dlg file that uses this facility, Qt Designer will silently put the fixed position widgets into the layout.

  • Pixmaps

    Qt Designer ignores pixmaps specified in .dlg files. These have to be restored manually in Qt Designer.

Importing Glade Files

Glade is a free GUI builder for GTK+ and GNOME written by Damon Chaplin. The .glade extension is associated with Glade files.

Qt Designer has been tested with Glade files up to version 0.6.0 and might work with later versions as well.

Although Glade does not target Qt, the layout system and the widget set of GTK+ are similar to those of Qt, so the filter will retain most of the information in the .glade file.

There are some considerations regarding the conversion of Glade files, as listed below:

  • Ampersands (&) in labels

    Qt displays an ampersand when a QLabel has no buddy. (A buddy is a widget that accepts focus on behalf of a QLabel.) Glade allows GtkLabel widgets with an (underlined) accelerator key but with no buddy. This is an error since users expect underlined characters to be accelerators. In this situation, Qt displays the ampersand itself instead of underlining the accelerator key. You should go over these QLabel widgets and set their "buddy" property.

  • Layout placeholders

    GTK allows a layout position to be occupied by a placeholder. Qt Designer converts those placeholders into QLabels whose text is "?" in red, so that you can find them and fix them manually.

  • GTK+ or GNOME widget with no Qt equivalent

    Qt has equivalents for most GTK+ widgets, but Glade also supports GNOME, whose goal is to provide a complete desktop environment. Because Qt's scope is narrower, when Qt Designer encounters a widget it cannot convert, it replaces it with a label that indicates the problem. For example, a GnomePaperSelector will be replaced by a QLabel whose text is "GnomePaperSelector?" in red. If you are porting to KDE, you might want to use the corresponding KDE widget.

    Other GTK+/GNOME widgets are only supported in certain contexts. For example, the GnomeDruid can be embedded in another widget, whereas the corresponding QWizard class cannot.

  • Message boxes and other high-level dialogs

    Glade supports editing of GnomeMessageBox, GtkFileSelection, GtkFontSelectionDialog and others. This is trivially achieved in Qt by means of a QMessageBox dialog, a QFileDialog, a QFontDialog, etc., in C++ code.

  • Stand-alone popup menus

    Qt Designer only supports popup menus inside a QMainWindow. If you need a stand-alone popup menu (presumably a context menu), you can easily write code that does this using QPopupMenu.

  • Size policy parameters

    Glade provides size policies in the "Place" tab of the property editor. Qt Designer does not attempt to make use of the padding, expand, shrink and fill information, as the Qt defaults are usually good enough. In a few cases, you might have to set the "sizePolicy" property manually to obtain the effect you want.

  • GNOME standard icons

    GNOME provides a large set of standard icons. Qt Designer will ignore references to these. If you are porting to KDE, you might want to manually set the standard KDE icons.

  • Packer layout

    GTK+ provides a class called GtkPacker that provides for exotic layouts; Qt provides no QPackerLayout and never will. Qt Designer will treat packer layouts as if they were vertical layouts and you will probably have to change them to whatever combination of layouts that produces the right effect.

  • Incorrectly-justified text after conversion

    The "hAlign" property is sometimes set wrongly, in which case you have to change it manually. It is caused by a quirk in Glade.

[Prev: Creating Database Applications] [Home] [Next: Reference: Key Bindings]


Reference: Key Bindings

  • Ctrl+A -- Selects all GUI elements in the active form.

  • Ctrl+B -- Breaks the selected layout so that you can add or delete GUI elements.

  • Ctrl+C -- Copies the selected GUI elements from the active form into the clipboard.

  • Alt+E -- Pulls down the Edit menu.

  • Alt+F -- Pulls down the File menu.

  • Ctrl+G -- Applies a grid layout to the selected container, or creates a new container containing the selected GUI elements and applies a grid layout to this container.

  • Ctrl+H -- Applies a horizontal box layout to the selected container, or creates a new container containing the selected GUI elements and applies a horizontal box layout to this container.

  • Alt+H -- Pulls down the Help menu.

  • Ctrl+J Adjusts the size of the selected GUI element (or elements) so that it has the minimal size needed for displaying itself properly.

  • Ctrl+L -- Applies a vertical box layout to the selected container, or creates a new container containing the selected GUI elements and applies a vertical box layout to this container.

  • Alt+L -- Pulls down the Layout menu.

  • Ctrl+M -- Opens an online version of this manual in Qt Assistant.

  • Ctrl+N -- Invokes the New File dialog.

  • Ctrl+O -- Invokes the Open File dialog.

  • Alt+P -- Pulls down the Preview menu.

  • Ctrl+R -- Checks the accelerators in the active form for duplicates.

  • Ctrl+S -- Saves the active form.

  • Ctrl+T -- Previews the active form in the default GUI style of the platform.

  • Alt+T -- Pulls down the Tools menu.

  • Ctrl+V -- Pastes the GUI element (or elements) in the clipboard into the active form at the position it had in its original form plus a little offset. Does nothing if the clipboard does not contain a GUI element.

  • Alt+W -- Pulls down the Window menu.

  • Ctrl+X -- Cuts the selected GUI element (or elements) from the active form and puts it into the clipboard.

  • Ctrl+Y -- Redoes the last undo action.

  • Ctrl+Z -- Undoes the last action.

  • Del -- Deletes the selected GUI elements from the active form.

  • F1 -- Opens the introductory page of the Qt Designer manual in Qt Assistant.

  • Shift-F1 -- Turns on What's This mode, which lets you click on a GUI element in Qt Designer to get a small description window for this element.

  • F2 -- Activates the pointer tool that lets you select GUI elements.

  • F3 -- Activates the connection tool that lets you edit the connections between signals and slots in a form.

  • F4 -- Activates the tab order tool that lets you change the tab order of the GUI elements on the active form.

  • Ctrl+F4 -- Closes the active window.

  • Ctrl+F6 -- Activates the next window in the order of window creation.

  • Ctrl+Shift-F6 -- Activates the previous window in the order of window creation.

[Prev: Customizing and Integrating Qt Designer] [Home] [Next: Reference: Menu Options]


Reference: Menu Options

Introduction

Qt Designer provides menu options that invoke the actions necessary to create applications. Many menu options lead to dialog boxes that provide additional options and functionality. The most commonly used menu options also have corresponding toolbar buttons. This chapter explains each menu option and its use. For menu options that invoke a dialog box or which have a corresponding toolbar button, there is a cross-reference to the detailed explanation that appears in the relevant chapter.

The File Menu

The File Menu

This menu is invoked with Alt+F, and provides the following options:

  • File|New
    Click this menu option (or press Ctrl+N) to create a new project, form or file. This option invokes the New File Dialog.

  • File|Open
    Click this menu option (or press Ctrl+O) to open existing projects, forms or files. The File Open Dialog is invoked through which a file name can be selected.

  • File|Close
    Click this menu option to close the currently open project. If the project has unsaved changes, the Save Form Dialog appears.

  • File|Save
    Click this menu option (or press Ctrl+S) to save the project along with its forms and files. For a project that has forms or files, click 'Save' to save the project before exiting. For new forms, click 'Save' and the Save Form As Dialog appears. For forms that have been saved previously click 'Save'. For new files or for files that have been changed, click 'Save'.

  • File|Save As
    Click this menu option to save and name the current form or file. This option invokes the Save Form As Dialog.

  • File|Save All
    Click this menu option to save every open file and form in every open project.

  • File|Create Template
    Click this menu option to create a form template. This option invokes the Create Template Dialog dialog.

  • File|Recently Opened Files
    Click this menu option to list the most recently opened files. Click one of the files listed to open it. Note that we recommend that you open projects rather than files. You can open a file by clicking the file's name in the project's File Overview Window.

  • File|Recently Opened Projects
    Click this menu option to list the most recently opened projects. Click one of the projects listed to open it.

  • File|Exit
    Click this menu option to exit Qt Designer. If any open files have unsaved changes, the Save Form Dialog message box will appear for each of them, before Qt Designer exits. Note that for a form that has not been saved previously but has had changes made to it or that has been saved but has had changes made to it, the Save Form Dialog is invoked. Click Yes to invoke the Save Form As dialog.

See also The File Toolbar Buttons.

The Edit Menu

The Edit Menu

This menu is invoked with Alt+E, and provides the following options:

  • Edit|Undo
    Click this menu option (or press Ctrl+Z) to undo an action. The name of the last action that was performed appears after the word 'Undo'.

  • Edit|Redo
    Click this menu option (or press Ctrl+Y) to redo an action. The name of the last action that was performed appears after the word 'Redo'.

  • Edit|Cut
    Click this menu option (or press Ctrl+X) to delete the selected item from the current form or file and copy it to the clipboard.

  • Edit|Copy
    Click this menu option (or press Ctrl+C) to copy the selected item from the current form or file to the clipboard.

  • Edit|Paste
    Click this menu option (or press Ctrl+V) to paste the clipboard item (if any) into the current form or file.

  • Edit|Delete
    Click this menu option (or press Del) to delete the selected item from the current form or file.

  • Edit|Select All
    Click this menu option (or press Ctrl+A) to highlight all the widgets on the current form or all the text in the current file.

  • Edit|Check Accelerators
    Click this menu option (or press Alt+R) to verify that all the accelerators are used only once. If an accelerator is used more than once, a message box appears with the statement 'The accelerator 'x' is used 'y' times'. Click Select to highlight the widgets with the same accelerator, or click Cancel to exit the message box without taking any action.

  • Edit|Slots
    Click this menu option to edit and create slots. This option invokes the Edit Slots Dialog.

  • Edit|Connections
    Click this menu option to invoke the View Connections Dialog.

  • Edit|Form Settings
    Click this menu option to invoke the Form Settings Dialog.

  • Edit|Preferences
    Click this menu option to invoke the Preferences Dialog.

See also The Edit Toolbar Buttons.

The Project Menu

The Project Menu

This menu is invoked with Alt+O, and provides the following options:

  • Project|Active Project
    Click this menu option to toggle between projects if there is more than one project open. You can also toggle between projects using the Active Project drop-down combobox in the The File Toolbar Buttons.

  • Project|Add File
    Click this menu option to invoke the Add Dialog

  • Project|Project Settings
    Click this menu option to invoke the Project Settings Dialog.

  • Project|Image Collection
    Click this menu option to invoke the Image Collection Dialog.

  • Project|Database Connections
    Click this menu option to invoke the Edit Database Connections Dialog.

See also The File Toolbar Buttons.

The Search Menu

The Search Menu

This menu is invoked with Alt+S, and provides the following options:

  • Search|Find
    Click this menu option (or press Ctrl+F) to invoke the Find Text Dialog.

  • Search|Find Incremental
    Click this menu option (or press Alt+I) to place the cursor in the text box located next to the Find toolbar button. Type characters into the text box; as you type, Qt Designer will highlight the first occurrence of the text that it finds in the file. Press the Enter key to go to the next occurrence of the text. Press the Esc key once you have found the word you are looking for to place the cursor in the editor.

  • Search|Replace
    Click this menu option (or press Ctrl+R) to invoke the Replace Text Dialog to replace specific words or characters.

  • Search|Goto line
    Click this menu option (or press Alt+G) to invoke the Goto Line Dialog to go to a specific line in the file.

See also The Search Toolbar Buttons.

The Tools Menu

The Tools Menu

This menu is invoked with Alt+T, and provides the following options:

  • Tools|Pointer
    Click this menu option (or press F2) to de-select any selected widget toolbar button. The pointer is also used to stop inserting new widgets on the form if you double clicked a widget toolbar button. Press the Esc key to return to the pointer at any time.

  • Tools|Connect Signals and Slots
    Click this menu option (or press F3) to connect signals and slots. Click on a widget and drag the connection line to the widget (or form) that you want to connect to. Release the mouse button and the Edit Connections Dialog will appear.

  • Tools|Tab Order
    Click this menu option (or press F4) to set the tab order for all the widgets on the form that can accept keyboard focus. Choose this option and blue circles with numbers on them appear next to the widgets. Click the widget that you want to be first in the tab order, then click the widget that should be next in the tab order, and continue until all the widgets have the tab order numbers you want. If you make a mistake, double click the first widget and start again. Press Esc to leave tab order mode. If you want to revert your changes, leave tab order mode, then undo.

  • Tools|Buttons|PushButton
    Click this menu option and then click the form to place a PushButton on the form.

  • Tools|Buttons|ToolButton
    Click this menu option and then click the form to place a ToolButton on the form.

  • Tools|Buttons|RadioButton
    Click this menu option and then click the form to place a RadioButton on the form. It is recommended that you place RadioButtons inside ButtonGroups so that Qt will automatically ensure that only one RadioButton in the group is active at any one time.

  • Tools|Buttons|CheckBox
    Click this menu option and then click the form to place a CheckBox on the form.

  • Tools|Containers|GroupBox
    Click this menu option and then click the form to place a GroupBox on the form.

  • Tools|Containers|ButtonGroup
    Click this menu option and then click the form to place a ButtonGroup on the form.

  • Tools|Containers|Frame
    Click this menu option and then click the form to place a Frame on the form.

  • Tools|Containers|TabWidget
    Click this menu option and then click the form to place a TabWidget on the form. To add or remove tabs, right click the tab widget and choose 'Add Page' or 'Remove Page'.

  • Tools|Views|ListBox
    Click this menu option and then click the form to place a ListBox on the form.

  • Tools|Views|ListView
    Click this menu option and then click the form to place a ListView on the form.

  • Tools|Views|Icon View
    Click this menu option and then click the form to place an IconView on the form.

  • Tools|Views|Table
    Click this menu option and then click the form to place a Table on the form.

  • Tools|Database|DataTable
    Click this menu option and then click the form to place a DataTable on the form.

  • Tools|Database|DataBrowser
    Click this menu option and then click the form to place a DataBrowser on the form.

  • Tools|Database|DataView
    Click this menu option and then click the form to place a DataView on the form.

  • Tools|Input|LineEdit
    Click this menu option and then click the form to place a LineEdit on the form.

  • Tools|Input|SpinBox
    Click this menu option and then click the form to place a SpinBox on the form.

  • Tools|Input|DateEdit
    Click this menu option and then click the form to place a DateEdit on the form.

  • Tools|Input|TimeEdit
    Click this menu option and then click the form to place a TimeEdit on the form.

  • Tools|Input|DateTimeEdit
    Click this menu option and then click the form to place a DateTimeEdit on the form.

  • Tools|Input|TextEdit
    Click this menu option and then click the form to place a TextEdit on the form.

  • Tools|Input|ComboBox
    Click this menu option and then click the form to place a ComboBox on the form.

  • Tools|Input|Slider
    Click this menu option and then click the form to place a Slider on the form.

  • Tools|Input|ScrollBar
    Click this menu option and then click the form to place a Scrollbar on the form.

  • Tools|Input|Dial
    Click this menu option and then click the form to place a Dial on the form.

  • Tools|Display|TextLabel
    Click this menu option and then click the form to place a TextLabel on the form.

  • Tools|Display|PixmapLabel
    Click this menu option and then click the form to place a PixmapLabel on the form.

  • Tools|Display|LCDNumber
    Click this menu option and then click the form to place a LCDNumber on the form.

  • Tools|Display|Line
    Click this menu option and then click the form to place a Line on the form.

  • Tools|Display|ProgressBar
    Click this menu option and then click the form to place a ProgressBar on the form.

  • Tools|Display|TextBrowser
    Click this menu option and then click the form to place a TextBrowser on the form.

  • Tools|Custom|Edit Custom Widgets
    Click this menu option to invoke the Edit Custom Widgets Dialog.

  • Tools|Custom|
    Click this menu option and then click the form to place the Custom Widget on the form. Note that this menu option only appears if you have created a widget using Tools|Custom|Edit Custom Widgets.

See also The Tools Toolbar Buttons.

The Layout Menu

The Layout Menu

This menu is invoked with Alt+L, and provides the following options:

  • Layout|Adjust Size
    Click this menu option (or press Ctrl+J) to adjust the size of the widget to it's recommended size.

  • Layout|Lay Out Horizontally
    Click this menu option (or press Ctrl+H) to lay out the selected widgets or layouts side by side. Use Shift+Click to select each widget or layout, and then choose this menu option to group them horizontally. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window. If only one widget is selected, its child widgets will be laid out horizontally.

  • Layout|Lay Out Vertically
    Click this menu option (or press Ctrl+L) to lay out the selected widgets one above the other. Use Shift+Click to select each widget or layout, and then choose this menu option to group them vertically. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window. If only one widget is selected, its child widgets will be laid out vertically.

  • Layout|Lay Out in a Grid
    Click this menu option (or press Ctrl+G) to lay out the selected widgets in a grid. If only one widget is selected, its child widgets will be laid out in a grid.

  • Layout|Lay Out Horizontally (in Splitter)
    Click this menu option to lay out the selected widgets or layouts side by side with a splitter between each. Use Shift+Click to select each widget or layout, and then choose this menu option to group them horizontally. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Layout|Lay Out Vertically (in Splitter)
    Click this menu option to lay out the selected widgets or layouts one above the other with a splitter between each. Use Shift+Click to select each widget or layout, and then choose this menu option to group them vertically. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Layout|Break Layout
    Click this menu option (or press Ctrl+B) to break a layout. Click on the layout, then select this option; the layout is deleted.

  • Layout|Add Spacer
    Click this menu option to add a vertical or horizontal spacer to widgets that take up too much space on the form. The spacer consumes extra space in the layout.

See also The Layout Toolbar Buttons.

The Preview Menu

The Preview Menu

This menu is invoked with Alt+P, and provides the following options:

  • Preview|Preview Form
    Click this menu option (or press Ctrl+T) to preview the form within Qt Designer.

  • Preview|...in Windows Style
    Click this menu option to preview the form in the Windows style.

  • Preview|...in Motif Style
    Click this menu option to preview the form in the Motif style.

  • Preview|...in CDE Style
    Click this menu option to preview the form in the CDE style.

  • Preview|...in MotifPlus Style
    Click this menu option to preview the form in the MotifPlus style.

  • Preview|...in Platinum Style
    Click this menu option to preview the form in the Platinum style.

  • Preview|...in SGI Style
    Click this menu option to preview the form in the SGI style.

The Window Menu

The Window Menu

This menu is invoked with Alt+W, and provides the following options:

  • Window|Close
    Click this menu option (or press Ctrl+F4) to close the window that is currently active.

  • Window|Close All
    Click this menu option to close all the windows that are currently open.

  • Window|Next
    Click this menu option (or press Ctrl+F6) to make the next window active. The order is the order in which the windows were opened.

  • Window|Previous
    Click this menu option (or press Ctrl+Shift+F6) to make the previous window active. The order is the order in which the windows were opened.

  • Window|Tile
    Click this menu option to arrange all the open files and forms side by side so that each window is visible.

  • Window|Cascade
    Click this menu option to stack all the open file and forms, one on top of the other, but with an overlap so that each window's title bar is visible.

  • Window|Views|File Overview
    Click this menu option to make the File Overview Window visible, or to hide it if it is already visible. If the window is currently visible, a check mark will appear next to the name in the menu.

  • Window|Views|Property Editor/Signal Handlers
    Click this menu option to make the Property Editor/Signal Handlers Window visible, or to hide it if it is already visible. If the window is currently visible, a check mark will appear next to the name in the menu.

  • Window|Views|Object Explorer
    Click this menu option to make the Object Explorer Window visible, or to hide it if it is already visible. If the window is currently visible, a check mark will appear next to the name in the menu.

  • Window|Views|Line Up
    Click this menu option to eliminate any extra space between toolbars and line them up next to each other all at once, rather than moving each individual toolbar into place.

  • Window|Toolbars|File
    Click this menu option to make the File toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Edit
    Click this menu option to make the Edit toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Search
    Click this menu option to make the Search toolbar buttons visible, or to hide them if they are already visible. if the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Layout
    Click this menu option to make the Layout toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Tools
    Click this menu option to make the Tools toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Buttons
    Click this menu option to make the Buttons toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Containers
    Click this menu option to make the Containers toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Views
    Click this menu option to make the Views toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Database
    Click this menu option to make the Database toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Input
    Click this menu option to make the Input toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Display
    Click this menu option to make the Display toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Custom
    Click this menu option to make the Custom toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Help
    Click this menu option to make the Help toolbar buttons visible, or to hide them if they are already visible. If the toolbar buttons are currently visible, a check mark will appear next to the name in the menu.

  • Window|Toolbars|Line Up
    Click this menu option to eliminate extra space between toolbars and line them up next to each other all at once, rather than moving each individual toolbar into place.

  • Window|n
    Click one of the numbered menu options that list the currently open files and forms to switch to the named file or form.

The Help Menu

The Help Menu

This menu is invoked with Alt+H, and provides the following options:

  • Help|Contents
    Click this menu option (or press F1) to invoke the Qt Assistant application which provides on-line help. The on-line help is context sensitive, so you can type the item you want more information about in the line edit and Qt Assistant will automatically find it if it is available.

  • Help|Manual
    Click this menu option (or press Ctrl+M) to invoke the Qt Assistant application which opens showing this manual.

  • Help|About...
    Click this menu option to invoke the About Qt Designer dialog which gives the version number and some licensing information.

  • Help|About Qt...
    Click this menu option to invoke a dialog which provides information about Qt.

  • Help|What's This?
    Click this menu option to invoke a small question mark that is attached to the mouse pointer. Click on a feature which you would like more information about. A popup box appears with information about the feature.

See also The Help Toolbar Button.

[Prev: Reference: Key Bindings] [Home] [Next: Reference: Toolbar Buttons]


Reference: Toolbar Buttons

Introduction

Qt Designer's toolbar buttons provide fast access to common functionality.

Toolbar buttons are grouped in several toolbars. Toolbars have a handle at the left hand side which can be clicked to minimize the toolbar. Toolbars that have been minimized have their handle appear just under the menu bar; click the handle to restore the toolbar to the last position it occupied. You can drag a toolbar's handle to move the toolbar to a different position in the toolbar area. Toolbars can be dragged out of the toolbar area entirely and made into stand-alone tool dock windows. To hide a tool dock window click its close button. To restore a hidden tool dock window, right click the tool area, then click the name of the tool dock window you wish to restore.

File Toolbuttons

The File Toolbar Buttons

  • New
    Click this toolbar button (or press Ctrl+N) to create a new project, form or file. This option invokes the New File Dialog.

  • Open
    Click this toolbar button (or press Ctrl+O) to open existing projects, forms or files. This button invokes the File Open Dialog which is used to select files.

  • Save
    Click this toolbar button (or press Ctrl+S) to save the project, forms and files. For a new project that has no forms or files, click 'Save' to save the project before exiting. For new forms, click 'Save' and the Save Form As Dialog appears.

  • Active Project
    Click the combobox to view the names of the projects that are currently open and select a project name to toggle between the projects.

Edit Toolbuttons

The Edit Toolbar Buttons

  • Undo
    Click this toolbar button (or press Ctrl+Z) to undo an action. The name of the last action that was performed appears after the word 'Undo' in this toolbar button's tooltip.

  • Redo
    Click this toolbar button (or press Ctrl+Y) to redo an action. The name of the last action that was performed appears after the word 'Redo' in this toolbar button's tooltip.

  • Cut
    Click this toolbar button (or press Ctrl+X) to delete the selected item from the current form or file and copy it to the clipboard.

  • Copy
    Click this toolbar button (or press Ctrl+C) to copy the selected item from the current form or file to the clipboard.

  • Paste
    Click this toolbar button (or press Ctrl+V) to paste the selected item (if any) from the clipboard into the current form or file.

Search Toolbuttons

The Search Toolbar Buttons

  • Find
    Click this toolbar button (or press Ctrl+F) to invoke the Find Text Dialog.

  • Find Incremental
    Click this toolbar button (or press Alt+I) to place the cursor in the text box located next to the Find toolbar button. Type characters into the text box; as you type, Qt Designer will highlight the first occurrence of the text that it finds in the file. Press the Enter key to go to the next occurrence of the text. Press the Esc key once you have found the word you are looking for to place the cursor in the editor.

The Tools Toolbar Buttons

If you want to add the same kind of widget several times to a form, for example, several push buttons, double click the widget's toolbar button. After this, every time you click the form a new widget will be added. Click the Pointer toolbar button to leave this mode.

Tools

Tools

  • Pointer
    Click this toolbar button (or press F2) to de-select any selected widget toolbar button. The pointer is also used to stop inserting new widgets if you double clicked a widget toolbar button. Press the Esc key to return to the pointer at any time.

  • Connect Signals and Slots
    Click this toolbar button (or press F3) to connect signals and slots. Then click on a widget and drag the connection line to the widget (or the form) that you want to connect to. Release the mouse button and the Edit Connections Dialog will appear.

  • Tab Order
    Click this toolbar button (or press F4) to set the tab order for all the widgets on the form that can accept keyboard focus. Click this toolbar button and blue circles with numbers on them appear next to the widgets. Click the widget that you want to be first in the tab order, then click the widget that should be next in the tab order, and continue until all the widgets have the tab order numbers you want. If you make a mistake, double click the first widget and start again. Press Esc to leave tab order mode. If you want to revert your changes, leave tab order mode, then undo.

Buttons

Buttons

  • PushButton
    Click this toolbar button, then click the form, to place a Pushbutton on the form.

  • ToolButton
    Click this toolbar button, then click the form, to place a Toolbutton on the form.

  • RadioButton
    Click this toolbar button, then click the form, to place a Radiobutton on the form. It is recommended that you place RadioButtons inside ButtonGroups so that Qt will automatically ensure that only one RadioButton in the group is active at any one time.

  • CheckBox
    Click this toolbar button, then click the form, to place a CheckBox on the form.

Containers

Containers

  • GroupBox
    Click this toolbar button, then click the form, to place a GroupBox on the form.

  • ButtonGroup
    Click this toolbar button, then click the form, to place a ButtonGroup on the form.

  • Frame
    Click this toolbar button, then click the form, to place a Frame on the form.

  • TabWidget
    Click this toolbar button, then click the form, to place a TabWidget on the form. To add or remove tabs, right click the tab widget and choose 'Add Page' or 'Remove Page'.

Views

Views

  • ListBox
    Click this toolbar button, then click the form, to place a ListBox on the form.

  • ListView
    Click this toolbar button, then click the form, to place a ListView on the form.

  • Icon View
    Click this toolbar button, then click the form, to place an IconView on the form.

  • Table
    Click this toolbar button, then click the form to place a Table on the form.

Database Toolbuttons

Database

  • DataTable
    Click this toolbar button, then click the form, to place a DataTable on the form.

  • DataBrowser
    Click this toolbar button, then click the form, to place a DataBrowser on the form.

  • DataView
    Click this toolbar button, then click the form, to place a DataView on the form.

Input Toolbuttons

Input

  • LineEdit
    Click this toolbar button, then click the form, to place a LineEdit on the form.

  • SpinBox
    Click this toolbar button, then click the form, to place a SpinBox on the form.

  • DateEdit
    Click this toolbar button, then click the form, to place a DateEdit on the form.

  • TimeEdit
    Click this toolbar button, then click the form, to place a TimeEdit on the form.

  • DateTimeEdit
    Click this toolbar button, then click the form, to place a DateTimeEdit on the form.

  • TextEdit
    Click this toolbar button, then click the form, to place a TextEdit on the form.

  • ComboBox
    Click this toolbar button, then click the form, to place a ComboBox on the form.

  • Slider
    Click this toolbar button, then click the form, to place a Slider on the form.

  • ScrollBar
    Click this toolbar button, then click the form, to place a Scrollbar on the form.

  • Dial
    Click this toolbar button, then click the form, to place a Dial on the form.

Display Toolbuttons

Display

  • TextLabel
    Click this toolbar button, then click the form, to place a TextLabel on the form.

  • PixmapLabel
    Click this toolbar button, then click the form, to place a PixmapLabel on the form.

  • LCDNumber
    Click this toolbar button, then click the form, to place a LCDNumber on the form.

  • Line
    Click this toolbar button, then click the form, to place a Line on the form.

  • ProgressBar
    Click this toolbar button, then click the form, to place a ProgressBar on the form.

  • TextBrowser
    Click this toolbar button, then click the form, to place a TextBrowser on the form.

Custom Widget Toolbutton

Custom

  • My Custom Widget
    Click this toolbar button, then click the form, to place a Custom Widget on the form. Note: this toolbar button only appears if you have created a custom widget using Tools|Custom|Edit Custom Widgets.

Layout Toolbuttons

The Layout Toolbar Buttons

  • Adjust Size
    Click this toolbar button (or press Ctrl+J) to adjust the size of the widget to it's recommended size.

  • Lay Out Horizontally
    Click this toolbar button (or press Ctrl+H) to lay out the selected widgets or layouts side by side. Use Shift+Click to select each widget or layout, and then choose this toolbar button to group them horizontally. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Lay Out Vertically
    Click this toolbar button (or press Ctrl+L) to lay out the selected widgets one above the other. Use Shift+Click to select each widget or layout, and then choose this toolbar button to group them vertically. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Lay out in a Grid
    Click the widgets you want and then click this toolbar button (or press Ctrl+G) to lay out widgets in a grid.

  • Lay Out Horizontally (in Splitter)
    Click this toolbar button to lay out the selected groups of widgets or layouts side by side with a splitter between each group. Use Shift+Click to select each widget or layout, and then choose this toolbar button to group them horizontally. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Lay Out Vertically (in Splitter)
    Click this toolbar button to lay out the selected groups of widgets or layouts one above the other with a splitter between each group. Use Shift+Click to select each widget or layout, and then choose this toolbar button to group them vertically. Note that for complex widgets it is sometimes easiest to select widgets and layouts by clicking them in the Widgets tab of the Object Explorer Window.

  • Break Layout
    Click this toolbar button (or press Ctrl+B) to break a layout. Click on the layout and select this option; the layout is deleted.

  • Add Spacer
    Click this toolbar button to add a spacer to widgets that take up too much space on the form. The spacer consumes extra space in the layout.

Help Toolbutton

The Help Toolbar Button

  • What's This?
    Click this menu option to invoke a small question mark that is attached to the mouse pointer. Click on a feature which you would like more information about. A message box appears with information about the feature.

[Prev: Reference: Menu Options] [Home] [Next: Reference: Dialogs]


Reference: Dialogs

Introduction

This chapter describes and explains every Qt Designer dialog.

The File Dialogs

New File Dialog

New File Dialog

Click File|New (or press Ctrl+N) to invoke the New File dialog. This dialog offers four kinds of file to choose from: C++ Project, Forms, Source files, and Main files.

The 'Insert Into' drop-down combobox lists the open projects, defaulting to the current project. New files are added to the project displayed in this combobox. To add a new file to a different project, choose the project you want to use in the 'Insert Into' combobox.

The 'Dialog' file type is highlighted by default when the New File dialog pops up. Click on the file type you want to use and click OK to create it. Click Cancel to leave the dialog without creating a new file. Note that if you select C++ Project, the 'Insert Into' combobox will be disabled, since it is not possible to insert a new C++ Project into an existing project.

C++ Project Files

Click C++ Project to start a new project. This option invokes the Project Settings Dialog. C++ projects are saved as .pro files, which include the information Qt Designer needs to manage projects. When you add a form to your project in Qt Designer, it is automatically added to the FORMS section of the project file. The .pro file contains the list of forms (.ui files) used in the project. Qt Designer reads and writes .ui files, e.g. form.ui. The uic (user interface compiler) creates both a header file, e.g. form.h, and an implementation file, e.g. form.cpp, from the .ui file.

Dialog Forms

Click Dialog to create a plain dialog form. Typically, this type of form is used to present the user with configuration options, or to present related sets of choices, for example, printer setting dialogs and find and replace dialogs.

Wizard Forms

Click Wizard to create a wizard form. A wizard is a special type of input dialog that consists of a sequence of dialog pages. A wizard's purpose is to assist a user by automating a task by walking the user through the process step by step. Wizards are useful for complex or infrequently occurring tasks that people may find difficult to learn or do. Initially the wizard form consists of a single dialog page. Use the right click context menu to add additional pages and to change page titles.

Widget Forms

Click Widget to create a form whose superclass is QWidget rather than QDialog.

Main Window Form

Click Main Window to invoke the Main Window Wizard. This wizard is used to create actions, menu options and toolbars through which the user can invoke actions. This form is used to create typical main-window style applications.

Configuration Dialog Form

Click Configuration Dialog creates a form with a listbox on the left, and a tabwidget filling the body of the form, along with Help, OK and Cancel buttons.

Dialog with Buttons (Bottom) Form

The Dialog with Buttons (Bottom) form is a template with default buttons at the bottom of the form.

Dialog with Buttons Form (Right)

The Dialog with Buttons (Right) form is a template with default buttons at the right of the form.

Tab Dialog Form

The Tab Dialog form has a tab widget as its central widget, along with Help, OK and Cancel buttons along the bottom.

C++ Source File

Click C++ Source File to create a new empty C++ file. The file will automatically be added to the project when it is saved.

C++ Header File

Click C++ Header File to create a new empty C++ header file. The file will automatically be added to the project when it is saved.

C++ Main File

Click C++ Main File to invoke the Configure Main-File Dialog which will create a basic main.cpp file automatically.

File Open Dialog

File Open Dialog

Click File|Open (or pressCtrl+O) to invoke the Open dialog. Use this dialog to open existing files.

The Open dialog shows the current directory and default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type' combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click Open to open the selected file. Click Cancel to leave the dialog without opening a new file.

Note: For Windows, the System File Dialogs are used.

Save As

Save As

Click File|Save As to invoke the Save As dialog. Use this dialog to save files to a directory.

The Save As dialog shows the current directory and default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type'combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click Save to save the selected file. Click Cancel to leave the dialog without saving the file.

Note: For Windows, the System File Dialogs are used.

Create Template

Create Template Dialog

Click File|Create Template to invoke the Create Template dialog. Use this dialog to create templates.

The 'Template Name' line edit defaults to 'New Template'. To change the name to a different name, type it in the line edit. Click the 'Baseclass for Template' scroll bar to choose a base class for the template.

Click Create to create the template. Click Cancel to leave the dialog without creating a template.

If you create a template it will appear in the New File Dialog. Templates are useful when you have to produce a large number of similar forms, or where you want to 'brand' your forms.

The Edit Dialogs

Edit Slots

Edit Slots Dialog

Click Edit|Slots to invoke the Edit Slots dialog. Use this dialog to edit or create slots which are used in conjunction with signals to provide communication between objects.

When this dialog is invoked, all existing slots are shown in the 'Slot' listbox. The column headers Slot, Type, Specifier, Access, and In-Use provide details about each slot that is listed. Click on any of the column headers to sort the slots. To create a new slot, click the New Slot button. The new slot has a default name that you should replace by typing the new name in the 'Slot' line edit. The 'Return Type' is also a default that can be changed by typing in the line edit. To change the 'Specifier' or 'Access', click the combobox and choose the required specifier or access. To remove a slot, click the slot you want to delete, and then click the Delete Slot button.

Click OK to save all changes made to slots. Click Cancel to leave the dialog without making any changes to slots.

View Connections

View Connections Dialog

Click Edit|Connections to invoke the View Connections dialog. This dialog displays the current signals and slots connections.

When this dialog is invoked, all existing connections are shown in the listbox. The column headers Sender, Signal, Receiver, and Slot provide details about each connection. Click the column headers to sort the connections. To remove a connection from the listbox, click the connection you want to disconnect and then click Disconnect. To edit a connection, click the Edit... button to invoke the Edit Connections Dialog.

Changes made in this dialog take immediate effect. Click the Close button to leave the dialog.

Form Settings

Form Settings Dialog

Click Edit|Form Settings to invoke the Form Settings dialog. Use this dialog to save the form's settings, pixmap, and layout properties.

Settings

In the Settings section, you can change or add the name of the class that will be created by typing in the 'Class Name' line edit. Note that the default name is the form name, but it can be changed. You can also enter text to the 'Comment' and 'Author' line edits or leave them blank, since they are not required.

Pixmaps

The default (for projects) is 'Project Imagefile'. This is the recommended option. Images are handled automatically, with Qt Designer storing the images in a subdirectory, and uic producing code that contains the images and the necessary supporting code. Each image is stored just once, no matter how many forms it is used in.

If you do not want Qt Designer to handle the images, (or are not using a project) choose either 'Save Inline' or 'Use Function'. 'Save Inline' saves the pixmaps in the .ui files. The disadvantage of this approach is that it stores images in the forms in which they're used, meaning that images cannot be shared across forms. Click 'Use Function' to use your own icon-loader function for loading pixmaps. Type the function's name (with no signature) in the 'Use Function' line edit. This function will be used in the generated code for loading pixmaps. Your function will be called with the text you put in the pixmap property (e.g. the image name) whenever an image is required.

Layouts

Click the 'Default Margin' spinbox or the 'Default Spacing' spinbox to change the default layout of the current form.

Click OK to accept changes to the form settings. Click Cancel to leave the dialog without making any changes.

Preferences Dialog

Click Edit|Preferences to invoke the Preferences dialog. This dialog has a tab for 'General' preferences. If you have the C++ Editor plugin, the dialog will also have a tab for the C++ Editor.

Preferences- General Tab

General Tab

The 'General' tab has sections for Background, Grid, General, and Toolbars.

The Background section defaults to 'Pixmap'. To change the default, click the Select a Pixmap button next to the 'Pixmap' radio button to invoke the Choose a Pixmap... Dialog. Click the 'Color' radio button to change the background to a color instead of a pixmap. Click the Choose a Color button located to the right of the 'Color' radio button to invoke the Select Color Dialog.

The 'General' section of the General tab has three checkboxes that are checked by default. Click the 'Restore last workspace on startup' checkbox to save the size and positions of the windows and toolbars of Qt Designer. The next time you start up Qt Designer, the windows and toolbars are restored to their last positions. Click the 'Show Splash Screen on startup' checkbox to display the Qt Designer splash screen when you start up the application. Click the 'Disable Database Auto-Edit in Preview' checkbox to disable the ability to update or delete data in the database to which you are connected when working with database widgets. To change the path Qt Designer uses to find it's online documentation, click the 'Documentation Path' line edit and type a new path. It would be unlikely to have to change this path. Another way to change the path is to click the (ellipsis) button located to the right of the line edit. This invokes the Find Directory Dialog.

The 'Grid' section has options for customizing the grid on the form. The 'Show Grid' checkbox located above the 'Grid' section is checked by default. Developers using Qt Designer almost always use Qt's layouts to design their forms and rarely make any use of the grid. The grid is provided for the rare occasions when a form is created using widgets with fixed sizes and positions. When 'Show Grid' is checked, you can customize the grid's appearance. When it is unchecked, the 'Grid' section is disabled. The 'Snap to Grid' checkbox is also checked by default. When it is checked, widgets are placed on a dot (snap to the grid) using the X|Y resolution. When it is unchecked, the 'Grid-X' and 'Grid-Y' spin boxes are disabled. Click the 'Grid X' and 'Grid Y' spinboxes to customize the grid settings for all forms.

The 'Toolbars' section has a 'Show Text Labels' checkbox. Click the checkbox to display the text labels for each icon shown in the Qt Designer toolbar.

Preferences- C++ Editor Tab

C++ Editor Tab

The C++ Editor tab provides options for customizing the editor. The 'Syntax Highlighting' section lets you change the way the syntax is viewed in the editor. Click the 'Element' listbox and choose an element. Click the 'Family' listbox to change the font style for that element. Click the 'Size' spinbox to choose a font size. You can change the font to Bold, Italic, or Underline by clicking the corresponding checkbox. Note, that all the fonts used derive from the 'Standard' element, so if you want to change the font used for everything, change the 'Standard' element. Click the Color button to invoke the Select Color Dialog. As you make changes to each element, you can view the changes in the 'Preview' line edit.

The 'Options' section has the Wordwrap, Completion, and Parentheses Matching checkboxes checked by default. Click the checkboxes to de-select them.

Click OK to accept changes to Preferences dialog. Click Cancel to leave the dialog without making any changes.

The Project Dialogs

Add Dialog

Add Dialog

Click Project|Add File to invoke the Add dialog. Use this dialog to add files to the current project.

The Add dialog defaults the directory and file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type' combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click Open to open the selected file. Click Cancel to leave the dialog without opening a file.

Manage Image Collection

Image Collection Dialog

Click Project|Image Collection to invoke the Manage Image Collection Dialog. Use this dialog to view the project's images, add new images, or delete images.

To add an image, click the Add button to invoke the Choose Images... Dialog. To delete an image from from the iconview, click the image and then click the Delete button.

Changes made to the image collection are applied immediately. Click the Close button to leave the dialog.

Edit Database Connections

Edit Database Connections Dialog

Click Project|Database Connections to invoke the Edit Database Connections Dialog. Use this dialog to connect your project to a database or to edit the current connections.

Click New Connection to create a new database connection. For applications that use a single database it will probably be most convenient to use the default connection name of '(default)'. If you use more than one database then each one must be given a unique name. A driver must be chosen from the Driver combo box. The database name may be available in the Database Name combo box or may have to be typed in. The database name, username, password and hostname should be provided by your database system administrator. When the Connection information has been completed click Connect. If the connection is made the connection name will appear in the list box on the left hand side of the dialog.

To remove a connection, click the connection in the listbox and then click the Delete Connection button.

Click Close to leave the Database Connections dialog.

Project Settings Dialog

Click Project|Project Settings to invoke the Project Settings Dialog. Use this dialog to make changes to the project settings.

Project Settings- Settings Tab

Settings Tab

The 'Settings' tab shows information about the project. The Project File line edit defaults the project name. To change the name, type a new name in the line edit. To save the project, click the (ellipsis) button located next to Project File to invoke the Save As Dialog. The 'Language' combobox is disabled. Click the 'Description' line edit if you want to add additional information about the project.

Project Settings- Files Tab

Files Tab

Click the 'Files' tab to enter a name in the 'Database File' line edit. Click the (ellipsis) button to invoke the Save As Dialog.

Project Settings- C++ Tab

C++ Tab

Click the C++ Tab to change the qmake options. See the qmake documentation for details on what these options mean. Click the 'Template' combobox and choose application or library to create makefiles for building applications or libraries. Click the 'Config' combobox to select the project configuration and compiler options for all platforms, or specific platforms. Type the Config value in the line edit. Note: Unix defaults to a shared library. If you want a shared library in Windows, type 'dll' at the end of the default config command and make sure you select lib from the Template combobox. Click the 'Libs' combobox to select a platform. Type the libraries in the line edit. Click the 'Defines' combobox and select a platform. 'Defines' values are added as compiler pre-processor macros. Type the 'Defines' values in the line edit. Click the 'Includepath' combobox to select a platform. Includepath specifies the directories that should be searched for include files when compiling the project. Type the 'Includepath' values in the line edit.

Cick OK to accept changes to the project settings. Click Cancel to exit the dialog without making any changes to the project settings.

The Search Dialogs

Find Text

Find Text Dialog

Click Search|Find (or press Ctrl+F) to invoke the Find Text Dialog. Use this dialog to find specific text in a project file.

To find the text you want in a file, type the text in the 'Find' combobox. You can make the search more specific by checking any or all of the checkboxes in the 'Options' section. Click the 'Whole words only' checkbox to narrow the search to whole words. Click 'Case Sensitive' to search for text that is identical to the text typed in the combobox. Click 'Start at Beginning' to start the search from the beginning of the file. The 'Direction' section offers the 'Forward' radio button and the 'Backward' radio button to specify the direction to perform the search in the file. Click the Find button to start the search. When the text is found, it is highlighted in the file. Continue clicking Find to search for subsequent occurrences of the search text.

Click the Close button to leave the dialog.

Replace Text

Replace Text Dialog

Click Search|Replace (or press Ctrl+R) to invoke the Replace Text Dialog. Use this dialog to replace text in a project file.

To replace text, type the text you would like to replace in the 'Find' combobox. Type the new text in the 'Replace' combobox. You can make the search more specific by checking any or all of the checkboxes in the 'Options' section. Click the 'Whole words only' checkbox to narrow the search to whole words. Click 'Case Sensitive' to search for text that identical to the text you typed in the combobox. Click 'Start at Beginning' to start the search from the beginning of the file. The 'Direction' section offers the 'Forward' radio button and the 'Backward' radio button to specify the direction to perform the search in the file.

Click the Replace button to search and replace the text. When the text is found, it is highlighted in the file. Continue clicking Replace button to search and replace each occurrence of the text in the file. Click Replace All button to replace all occurences of the search text in the file at once.

Click the Close button to leave the dialog.

Goto Line

Goto Line Dialog

Click Search|Goto line (or press Alt+G) to invoke the Goto Line Dialog. Use this dialog to go to a specific line in the file.

To choose a line number, type the number in the 'Line' spinbox, or click the up and down arrows in the spinbox. Click the Goto button. The cursor is placed at the beginning of the line in the file.

Click the Close button to leave the dialog.

The Help Dialogs

Qt Designer Dialog

Click Help|About... to invoke the Qt Designer Dialog. This dialog provides information about Qt Designer such as the version, the licensing terms, conditions, and disclaimers.

Click the 'x' located at the top right corner of the dialog to close the dialog.

Qt Designer Dialog

Click Help|About Qt... to invoke the Qt Designer Dialog. This dialog provides information about Qt.

Click the 'x' located at the title of the dialog to close the dialog.

Configure Main-File Dialog

Configure Main-File Dialog

Click File|New|C++ Main-File to invoke the Configure Main-File dialog. Use this dialog to configure the main file and its forms.

To change the default file name, type it in the 'Filename' line edit. Choose the form to use as the application's main form from the line edit by clicking it.

Click OK to accept the configurations and Qt Designer will create a default main.cpp file. Click Cancel to leave the dialog.

Note for database programmers: If you create a main.cpp file using Qt Designer, this file will not include the createConnections() function. We do not include this function because it needs the username and password for the database connection, and you may prefer to handle these differently from our simple example function. As a result, applications that preview correctly in Qt Designer will not run unless you implement your own database connections function.

Save Project Settings

Save Project Settings Dialog

The Save Project Settings message box is invoked by clicking File|Close or File|Exit for an open project with unsaved changes. The dialog displays the text 'Save changes to your project.pro'?. Click Yes to save the changes. If the project has any forms with unsaved changes, the Save Form As dialog is invoked when you click Yes. Click No to close the project without saving any changes. Click Cancel to leave the dialog without closing the project and without making any changes.

Save Form

Save Form Dialog

The Save Form message is invoked in several ways. One way is to click File|Close for a form that has never been saved, or has been saved previously but has had changes made to it. The dialog is also invoked by clicking File|Exit for a form that has never been saved, or has been saved previously but has had changes made to it. The dialog displays 'Save Changes to the Form?'. Click Yes to save the form. If the form has not been previously saved, the Save Form As Dialog is invoked. Click No to close the form without saving any changes or without saving the form if it has not been saved previously. Click Cancel to leave the dialog without closing or exiting the form and without saving the form.

Save Form As Dialog

Save Form As Dialog

The Save Form As dialog is invoked in three different ways. One way is to click File|Save for a form in a project that has never saved. Another way to invoke the dialog is by clicking File|Close for a form that has not been previously saved and has had changes made to it. The third way to invoke the dialog is by clicking File|Exit for a form that has not been saved previously or that has been saved but has had changes made to it. File|Close and File|Exit invoke the Save Form Dialog. Click Yes to invoke the Save Form As dialog.

The Save Form As dialog shows the current directory and the default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type'combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click Save to save the selected form. Click Cancel to leave the dialog without saving the form.

Edit Connections

Edit Connections Dialog

Invoke the Edit Connections dialog to modify connections between signals and slots.

The top left hand listbox displays the Signals that the widget can emit. The top right combobox lists the form and its widgets. Beneath the combobox is the 'Slots' listbox which shows the slots available in the form or widget displayed in the 'Slots' combobox which are compatible with the highlighted signal. To connect a signal to a slot, choose a signal from the 'Signals' listbox by clicking on it. Then choose a form or widget from the 'Slots' combobox. Choose a slot for the widget or form you select from the listbox. The Connect button will flash and the new connection will appear in the 'Connections' listbox, along with any existing connections. Click the column headers Sender, Signal, Receiver, or Slot to sort the connections. To disconnect an existing connection, choose the connection from the 'Connections' listbox and click the Disconnect button. Click Edit Slots to invoke the Edit Slots Dialog.

Click OK to accept changes to the connections. Click Cancel to leave the dialog without making changes to the connections.

Find Directory

Find Directory Dialog

Invoke this dialog to locate a directory.

The Find Directory dialog shows the current directory and the default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type' combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click OK to accept the directory. Click Cancel to leave the dialog without choosing a directory.

Choose a Pixmap

Choose a Pixmap Dialog

Invoke this dialog to select a pixmap to use in the current project.

The Choose a Pixmap dialog shows the current directory and the default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type'combobox. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files. View a sample of the pixmap file you select in the preview box located on the right side of the dialog.

Click OK to accept the pixmap file. Click Cancel to leave the dialog without choosing a pixmap file.

Edit Custom Widgets Dialog

Invoke this dialog by clicking Tools|Custom|Edit Custom Widgets. Use this dialog to create custom widgets.

Custom widgets are created in code. They may contain a combination of existing widgets but with additional functionality, slots and signals, or they may be written from scratch, or a mixture of both. A custom widget is often a specialization (subclass) of another widget or a combination of widgets working together or a blend of both these approaches. If you simply want a collection of widgets in a particular configuration it is easiest to create them, select them as a group, and copy and paste them as required within Qt Designer. Custom widgets are generally created when you need to add new functionality to existing widgets or groups of widgets. To add create a new widget, click the New Widget button. You will find more information about adding new widgets in the 'Definitions Section'. To load a file which contains descriptions of custom widgets, click the Load Descriptions button. Clicking this button invokes the Open Dialog. To save the descriptions of the listed custom widgets, click the Save Descriptions button, which invokes the Save As Dialog. To delete a widget, click the widget in the listbox and then click the Delete Widget button.

Click Close to leave the Edit Custom Widgets dialog.

Edit Custom Widgets- Definition Tab

The Definition Tab

To create a custom widget, click New Widget. Click the Definition tab if you are not already there. You should change the 'Class' name from 'MyCustomWidget' to a unique name by typing in the line edit. Type in the 'Headerfile' line edit to change the name or type the name of a header file you want to use. To search for a saved header file in a directory, click the (ellipsis) button to the right of the Headerfile line edit to invoke the Open Dialog. Click the 'Select Access' combobox to choose how the file will be included. Global include files will be included using angle brackets (<>). Local files will be included using quotation marks. If you have a pixmap that you want to use to identify your widget on the toolbar, click the (ellipsis) button to the right of the 'Pixmap' label. This invokes the Choose a Pixmap Dialog. Click the 'Size Hint' spin boxes to select the recommended size for the widget. If you do not want to have a recommended size, enter -1/-1 in the spinboxes. Click the 'Size Policy' comboboxes to select the vertical size properties of the widget. Click the 'Container Widget' checkbox if the custom widget you are creating should be able to contain other widgets (children).

Edit Custom Widgets- Signals Tab

The Signals Tab

Click the Signals tab to view a list of all the signals the selected custom widget can emit. To add a new signal, click the New Signal button. Click the 'Signal' line edit and provide an argument for the signal and give the signal a unique name. To delete a signal from the listbox, click the signal to choose it and then click the Delete Signal button.

Edit Custom Widgets- Slots Tab

The Slots Tab

Click the Slots tab to view a list of all the slots for the selected custom widget. Click the 'Slot' or 'Access' cloumn headers to sort the slots in the listbox. To add a slot, click the New Slot button. Click the 'Slot' line edit and provide an argument for the slot and give the slot a unique name. Click the 'Access' combobox to choose between public or protected access for your widget. To delete a slot from the listbox, click the slot and then click Delete Slot.

Edit Custom Widgets- Properties Tab

The Properties Tab

Click the Properties tab to view the list of properties for the selected widget. Click the 'Property' or 'Type' column headers to sort the properties in the listbox. To add a property, click the New Property button. Click the 'Property Name' line edit if you want to change the default name of the property. Note that properties must be implemented in the class using the property system of Qt. To choose a property type, click the 'Type' combobox. To delete a property from the listbox, click the property and then click the Delete Property button.

Click Close to leave the Edit Custom Widgets dialog.

Choose Images

Choose Images Dialog

Invoke the Choose Images dialog to choose images to use in a project.

This dialog shows the current the directory and the default file type. To choose a different directory, click the 'Look In' combobox. Choose a file and the name will appear in the 'File Name' combobox. To choose a different file type, click the 'File Type'combobox. As you choose different files, you can preview the images in the window located on the right side of the dialog. Click the 'Create New Folder' toolbar button to create a new directory. Click the 'List View' toolbar button to view folders and files in a list with only the names showing. Click the 'Details' toolbar button to view the folders and file names along with their size, type, date, and attributes. Click the Size, Type, Date, or Attributes column headers to sort the folders or files.

Click Open to open the selected file. Click Cancel to leave the dialog without opening a file.

Choose an Image

Choose an Image Dialog

The Choose an Image dialog is used to choose an image to use for a widget.

To choose an image from the listbox, click the image and then click OK. To add an image, click the Add button to invoke the Choose Images... Dialog. To delete an image, click the image in the listbox and then click the Delete button.

Click Cancel to leave the dialog without making any changes to images.

Select Color

Select Color Dialog

The Select Color dialog is used to select color preferences or to create color palettes.

Choose a color from the 'Basic Colors' section and a sample of the color will appear in the small preview box at the bottom of the dialog. To the right of the color sample, you will see line edits that have information about the location of the color in the color spectrum. In addition, the crosshairs in the larger color spectrum window show the location of the color. You can also create a palette of custom colors. There are two ways to do add custom colors. Click a color on the color spectrum window. When the color appears in the small box below the window, click the color and drag it to one of the blank boxes in the 'Custom Color' section of the dialog. You can also click and drag colors from the 'Basic Colors' section. Another way to add colors is to click the Add to Custom Colors when you have chosen a color.

Click OK to accept changes to the Select Color dialog. Click Cancel to exit the dialog without selecting a color or adding custom colors.

Edit Palette

Edit Palette Dialog

The Edit Palette dialog is used to change the palette of the current widget or form. You can use a generated palette, or select colors for each color group and each color role. The palette can be tested with different widget layouts in the preview section.

The 'Build Palette' section contains three buttons to help you build the palette. Click the 3-D Effects button to invoke the Select Color Dialog. Click the Background to invoke the Select Color Dialog. Click the Tune Palette button to invoke the Tune Palette Dialog. Click the 'Select Palette' combobox in the 'Preview' section to choose a palette to preview.

Click OK to accept the changes to the palette. Click Cancel to leave the dialog without making changes to the palette.

Tune Palette

Tune Palette Dialog

The Tune Palette dialog is used to choose options for a widget's palette.

Click the 'Select Palette' combobox to choose options for active, inactive, or disabled palettes. If you choose 'Active Palette', the dialog presents three categories used for designing the palette. The categories are the Auto, Central Color Roles, and 3-D Shadow Effects. If you choose 'Inactive Palette' or 'Disabled Palette', all categories are disabled except 'Auto'. Click the 'Auto' section checkboxes to build the inactive or disabled palettes from the active palette. For an active palette, click the 'Central color roles' combobox to select a color role for the palette. Click the Choose Pixmap button to invoke the Choose a Pixmap Dialog. Click the Select Color button to invoke the Select Color Dialog. Check the 'Build from button color' checkbox in the '3-D shadow effects' section to allow 3-D effects colors to be calculated from the button color. Uncheck the checkbox to enable the 'Choose 3-D effect color role' combobox. Click the combobox to select a color role for the 3-D effects. Click the Select Color button to invoke the Select Color Dialog.

Click OK to accept changes to the palette. Click Cancel to leave the dialog without making changes to the palette.

Select Font

Select Font Dialog

The Select Font dialog is used to make changes to the font size and style.

Click the 'Font' listbox to choose a font type. The current selected type appears in the line edit above the 'Font' listbox. Click the 'Font Style' listbox to choose a style for the font. The choices available in the listbox are limited to the type of font you choose. Not all fonts have all styles available. The selected style appears in the line edit above the 'Font Style' listbox. Click the 'Size' listbox to choose a size for the font. The current selected size appears in the line edit above the 'Size' line edit. Click the checkboxes in the 'Effects' section to create a 'Strikeout' or 'Underline' effect for the selected font. Click the 'Script' and choose a style of writing. View your font selections and styles in the 'Sample' listbox.

Click OK to accept changes to the font. Click Cancel to leave the dialog without making any changes to the font.

Text Dialog

Text Dialog

The Text dialog is used to type text.

Click OK to accept the text. Click Cancel to leave the dialog without saving any text.

Title Dialog

Title Dialog

Use this dialog to change the title of a selected widget by typing the new title in the line edit.

Click OK to accept changes to the title. Click Cancel to leave the dialog without making changes to the title.

Page Title Dialog

Page Title Dialog

Right click a tab widget on the form and select Edit Page Title to invoke the Page Title dialog. Use this dialog to change the name of each tab in the Tab widget.

Click OK to accept new page titles. Click Cancel to leave the dialog without making any changes.

Edit Listbox

Edit Listbox Dialog

Right click or double click a Listbox on the form and select 'Edit' to invoke the Edit Listbox dialog. Use this dialog to add items to the list box and to change the item's properties.

To add an item to the listbox, click the New Item. If you want to change the default name of the item, click the 'Text' line edit in the 'Item Properties' section and type a new name for the item. Click the Select a Pixmap to invoke the Choose an Image Dialog. Click a pixmap and then click the Delete Pixmap button to delete the selected pixmap. To delete an item from the listbox, click the item and then click the Delete button. To move an item up or down in the listbox, click the Move Up or Move Down buttons. Click Apply to accept the changes.

Click Apply to accept changes to the listbox widget. Click OK to leave the dialog once the changes have been accepted. Click Cancel to leave the dialog without saving any changes.

Edit Listview

Right click or double click a listview widget on the form and select 'Edit' to invoke the Edit Listview dialog. Use this dialog to add items to the listview. The Edit Listview dialog has two tabs, one for items and one for columns.

Edit Listview- Items Tab

The Items Tab

The dialog defaults to the Items tab. Use this tab to add, change, or remove items in the listview. To add a new item, click the New Item button. The new item is shown at the top of the listbox. To add sub-items to an existing item, click the item and then click the New Subitem button. Click the 'Column' spinbox to choose a column for which the item text or pixmap will be placed. Click the 'Text' line edit to type text for a column, or to change the name of an item or subitem. Click a pixmap and then click the Delete Pixmap button to delete the selected pixmap. To delete an item from the listbox, click the item and then click the Delete button. To move an item up or down within the hierarchy level, click the Move Up or Move Down buttons. To move an item up or down one level, click the Move Left or Move Right buttons.

Edit Listview- Columns Tab

The Columns Tab

Click this tab to change the column configuration of the listview. To add a column, click the New Column button. The new column is shown at the top of the listbox. To change the column name, click a column in the listbox and then click the 'Text' line edit and type a new name. To add a pixmap, click the (ellipsis) button, which invokes the Choose an Image Dialog. To remove a pixmap, click the Delete Pixmap button. Click the 'Clickable' checkbox if you want the columns to respond to mouse clicks. Click the 'Resizeable' checkbox if you want to be able to change the column's width. To remove a column, click the column in the listbox and then click the Delete Column button. To move a column up or down in the listbox, click the Move Up or the Move Down buttons.

Click Apply to accept changes to the listview widget. Click OK to leave the dialog once the changes have been accepted. Click Cancel to leave the dialog without saving any changes.

Edit Iconview

Edit Iconview

Right click or double click an iconview widget on the form and select 'Edit' to invoke the Edit Iconview dialog. Use the dialog to add, change, or remove items from the iconview. To add an item to the iconview, click the New Item button. To change the name of the item, click the 'Text' line edit and type a new name. To add a pixmap, click the (ellipsis) button, which invokes the Choose an Image Dialog. To remove a pixmap, click the Delete Pixmap button. To delete an item from the iconview, click the item and then click the Delete Item button.

Click Apply to accept changes to the iconview widget. Click OK to leave the dialog once the changes have been accepted. Click Cancel to leave the dialog without saving any changes.

Edit Table

Right click or double click a table widget on the form and select 'Edit' to invoke the Edit Table dialog. Use the dialog to add, change, or remove columns or rows from the table.

Edit Table- Columns Tab

The Column Tab

To add a column to the table, click the New Column button. To delete a column from the table, click the column you want to delete from the table, or click the column number in the 'Columns' listbox and then click the Delete Column button. To change a column name, click the 'Label' line edit and type the new text. To add a pixmap, click the (ellipsis) button, which invokes the Choose an Image Dialog. To remove a pixmap from the current column of the selected item, click the Delete Pixmap button. To move a column in the listbox, click the Move Up or Move Down buttons.

Edit Table- Rows Tab

The Rows Tab

To add a row to the table, click the New Row button. To delete a row from the table, click the row you want to delete from the table, or click the row number in the 'Rows' listbox and then click the Delete Column button. To change a row's name, click the row, or the row number, and then click the 'Label' line edit and type the new text. To add a pixmap, click the (ellipsis) button, which invokes the Choose an Image Dialog. To remove a pixmap from the current row of the selected item, click the Delete Pixmap button. To move a row in the listbox, click the Move Up or Move Down buttons.

Click Apply to accept changes to the table widget. Click OK to leave the dialog once the changes have been accepted. Click Cancel to leave the dialog without saving any changes.

Edit Forward Declarations

Edit Forward Declarations Dialog

From the Source tab in the Object Explorer Window, right click the 'Forward Declarations' folder and select 'Edit' from the context menu to invoke the Edit Forward Declarations dialog. Use this dialog to add, edit, or remove declarations in the source code.

To add a new declaration, click the Add button. A line edit will appear for you to type the declaration. Press Enter after you have typed the declaration. To delete a declaration from the listbox, click the declaration and then click Remove. To rename an existing declaration, click the declaration and then click Rename. The cursor will appear in the line edit, allowing you to change the name.

Click Close to leave the Edit Forward Declarations dialog.

Edit Includes (in Declaration)

Edit Includes (in Declaration) Dialog

From the Source tab in the Object Explorer Window, right click the 'Includes (in Declaration)' folder and select 'Edit' from the context menu to invoke the Edit Includes (in Declarations) dialog. Use this dialog to add, edit, or remove includes in the source code.

To add a new include, click the Add button. A line edit will appear for you to type the include. Press Enter after you have typed the include. To delete an include from the listbox, click the include and then click Remove. To rename an existing include, click the include and then click Rename. The cursor will appear in the line edit, allowing you to change the name.

Click Close to leave the Edit Include (in Declaration) dialog.

Edit Includes (in Implementation)

Edit Includes (in Implementation) Dialog

From the Source tab in the Object Explorer Window, right click the 'Includes (in Implementation)' folder and select 'Edit' from the context menu to invoke the Edit Includes (in Implementation) dialog. Use this dialog to add, edit, or remove includes in the source code.

To add a new include, click the Add button. A line edit will appear for you to type the include. Press Enter after you have typed the include. To delete an include from the listbox, click the include and then click Remove. To rename an existing include, click the include and then click Rename. The cursor will appear in the line edit, allowing you to change the name.

Click Close to leave the Edit Include (in Implementation) dialog.

Edit Class Variables

Edit Class Variables Dialog

From the Source tab in the Object Explorer Window, right click the 'Class Variables' folder and select 'Edit' from the context menu to invoke the Edit Class Variables dialog. Use this dialog to add, edit, or remove class variables in the source code.

To add a new variable, click the Add button. A line edit will appear for you to type the variable. Press enter after you have typed the variable. To delete an include from the listbox, click the variable and then click Remove. To rename an existing variable, click the variable and then click Rename. The cursor will appear in the line edit, allowing you to change the name.

Click Close to leave the Edit Class Variables dialog.

[Prev: Reference: Toolbar Buttons] [Home] [Next: Reference: Wizards]


Reference: Wizards

Introduction

In Qt Designer, some of the toolbars, menu options and templates invoke wizards to take you step-by-step through particular tasks. In this chapter we explain each Qt Designer wizard.

Main Window Wizard

The Main Window Wizard is invoked by clicking the Main Window form template in the New File Dialog. This wizard helps you to create a main window with actions, menu options and toolbars.

Choose Available Menus and Toolbars

The 'Choose available menus and toolbars' wizard page appears first. It presents three categories of default actions, File Actions, Edit Actions and Help Actions. For each category you can choose to have Qt Designer create menu items, toolbar buttons and signal/slots connections for the relevant actions. You can always add or delete actions, menu items, toolbar buttons and connections later. Check or uncheck the checkboxes to reflect your preferences.

Click Next to move on to the next wizard page.

Setup Toolbar

The 'Setup Toolbar' wizard page is used to populate a toolbar with actions from each of the default action categories. Click the Category combobox to select which set of actions you wish to work on. The Actions listbox lists the actions available for the current category. The Toolbar listbox lists the toolbar buttons you want to create. Click the blue left and right arrow buttons to move actions into or out of the Toolbar list box. Click the blue up and down arrow buttons to move actions up and down within the Toolbar list box. Note that the '<Separator>' item in the Actions list box may be moved to the Toolbar list box as often as required and will cause a separator to appear in the finished toolbar.

Click Back if you want to return to the 'Choose available menus and toolbars' wizard page. Click Finish to populate the main window and to exit the wizard. Click Cancel on any of the wizard pages to leave the wizard without making any changes.

Data Table Wizard

The Data Table Wizard is automatically invoked by clicking the datatable widget and placing it on the form. The datatable widget is used to create tabular views of database data.

Choose the Database and Table

The 'Choose the Database and Table' wizard page appears first. The available databases are displayed in the 'Database Connection' listbox. Choose a connection by clicking it. If there are no connections listed in the listbox, click Setup Database Connections to invoke the Edit Database Connections Dialog. The 'Table' listbox shows all the tables and views that are available through the selected database connection. Select a table or view by clicking it.

Click Next to move on to the next wizard page.

Displayed Fields

The 'Displayed Fields' wizard page is used to select fields that will be displayed in the table. By default, every field except the table or view's primary key, is initially placed in the 'Displayed Fields' list. Click the blue left and right arrow buttons to move fields from the 'Available Fields' listbox and into or out of the 'Displayed Fields' listbox. Click the blue up and down arrow buttons to move fields up and down within the 'Displayed Fields' listbox. The order in which fields appear in the 'Displayed Fields' listbox is the order they are shown in the Data Table, with the top-most field being in the left-most column.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Choose the Database and Table' wizard page.

Table Properties

The 'Table Properties' wizard page is used to set the Data Table's initial editing options. Check the 'Read-Only' checkbox to prevent records from being edited, deleted or added. Check the checkboxes in the 'Confirmations' section to force the user to confirm their changes. By default users must confirm deletions. Click 'Allow column sorting' to allow the user to sort the data by clicking a column's header (which displays the field name).

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Displayed Fields' wizard page.

SQL

The 'SQL' wizard page is used to apply filters and sorts to the data in the table. Click the 'Filter' line edit and enter a valid SQL WHERE clause without the WHERE keyword. The filter applies to the data shown in the table.

To sort the available fields in the table, click the blue left and right arrow buttons to move fields from the 'Available Fields' listbox into or out of the 'Sort By' listbox. Click the blue up and down arrow buttons to move fields up and down within the 'Sort By' listbox. Click the A-Z button to change the sort order of the selected field in the 'Sort By' listbox from ascending to descending and vice versa.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Table Properties' wizard page.

Finish

The 'Finish' wizard page is used to select auto-editing and to leave the wizard. If you want user edits, e.g. inserts and updates, to be automatically applied when the user navigates to another record, check the 'AutoEditing' checkbox. If 'AutoEditing' is unchecked, users must press Enter to confirm their edit before moving to another record, or their edit will be lost.

Click Finish to create the datatable widget with all of the options you selected in the wizard. Click Back if you want to return to the 'SQL' wizard page. Click Cancel on any of the wizard pages to leave the wizard without making any changes.

Data Browser Wizard

The Data Browser wizard is automatically invoked by clicking the DataBrowser widget and placing it on the form. The DataBrowser widget is used to create a form view of database data.

Choose the Database and Table

The 'Choose the Database and Table' wizard page appears first. The available databases are displayed in the 'Database Connection' listbox. Choose a connection by clicking it. If there are no connections listed in the listbox, click Setup Database Connections to invoke the Edit Database Connections Dialog. The 'Table' listbox shows all the tables and views that are available through the selected database connection. Select a table or view by clicking it.

Click Next to move on to the next wizard page.

Displayed Fields

The 'Displayed Fields' wizard page is used to select fields that will be displayed in the table. Click the blue left and right arrow buttons to move fields from the 'Available Fields' listbox and into or out of the 'Displayed Fields' listbox. Click the blue up and down arrow buttons to move fields up and down within the 'Displayed Fields' listbox.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Choose the Database and Table' wizard page.

Navigation and Editing

The 'Navigation and Editing' wizard page is used to create navigation and editing buttons.

Check the 'Include Navigation Buttons' checkbox to include navigation buttons. In the 'Navigation section, click 'Previous' to display the 'Previous' button on the form. This option allows you to navigate to the previous record in the table. Click 'Next' to display the 'next' button on the form. This button allows you to navigate to the next record in the table. Click 'First' to display the 'First' button on the form. This option allows you to navigate to the first record in the table. Click 'Last' to display the 'Last' button on the form. This button allows you to navigate to the last record in the table.

Click the 'Include Edit Buttons' checkbox to include editing buttons. In the 'Editing' section, check the 'Insert' checkbox to create an 'Insert' button for adding new records. Check the 'Update' checkbox to create an 'Update' button for updating existing records. Check the 'Delete' checkbox to create a 'Delete' button for deleting records.

The navigation buttons, and 'Update' and 'Delete' buttons will work without requiring any code. Since most database designs expect new records to be created with a unique key the 'Insert' button will not work. This can easily be fixed by generating the key in a slot connected to the QDataBrowser::beforeInsert() signal.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Displayed Fields' wizard page.

SQL

The 'SQL' wizard page is used to apply filters and sorts to the data in the table. Click the 'Filter' line edit and type a valid SQL WHERE clause without the WHERE keyword. The filter applies to the data shown in the table.

To sort the available fields in the table, click the blue left and right arrow buttons to move fields from the 'Available Fields' listbox into or out of the 'Sort By' listbox. Click the blue up and down arrow buttons to move fields up and down within the 'Sort By' listbox. Click the A-Z button to change the sort order of the selected field in the 'Sort By' listbox from ascending to descending and vice versa.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Navigation and Editing' wizard page.

Layout

The 'Layout' wizard page is used to design the layout of the database browser. To choose the number of columns the form will use, click the 'Number of Columns' spinbox. To make labels appear to the left of the data entry fields, click the 'Labels to left' radio button. To make labels appear above the data entry fields, click the 'Labels on top' radio button.

Click the 'Create layout for fields' checkbox to arrange all fields inside of a box layout. Click the 'Create layout for buttons' checkbox to arrange all buttons inside of a box layout. Click 'Create layout for all' to create a box layout for the whole widget.

You can always break the layouts and redo them later if you change your mind.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'SQL' wizard page.

Finish

The 'Finish' wizard page is used to select auto-editing and to leave the wizard. If you want user edits, e.g. inserts and updates, to be automatically applied when the user navigates to another record, check the 'AutoEditing' checkbox. If 'AutoEditing' is unchecked, users must press Enter to confirm their edit before moving to another record, or their edit will be lost. This property can be changed later if desired.

Click Finish to create the databrowser widget with all of the options you selected in the wizard. Click Back if you want to return to the 'Layout' wizard page. Click Cancel on any of the wizard pages to leave the wizard without making any changes.

Data View Wizard

The Data View wizard is automatically invoked by clicking the dataview widget and placing it on the form. The Dataview widget is used to create a read-only form view of database data.

Choose the Database and Table

The 'Choose the Database and Table' wizard page appears first. The available databases are displayed in the 'Database Connection' listbox. Choose a connection by clicking it. If there are no connections listed in the listbox, click Setup Database Connections to invoke the Edit Database Connections Dialog. The 'Table' listbox shows all the tables and views that are available through the selected database connection. Select a table or view by clicking it.

Click Next to move on to the next wizard page.

Displayed Fields

The 'Displayed Fields' wizard page is used to select fields that will be displayed in the table. Click the blue left and right arrow buttons to move fields from the 'Available Fields' listbox and into or out of the 'Displayed Fields' listbox. Click the blue up and down arrow buttons to move fields up and down within the 'Displayed Fields' listbox.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Choose the Database and Table' wizard page.

Layout

The 'Layout' wizard page is used to design the layout of the data view. To choose the number of columns the form will use, click the 'Number of Columns' spinbox. To make labels appear to the left of the data entry fields, click the 'Labels to left' radio button. To make labels appear above the data entry fields, click the 'Labels on top' radio button.

Click Next to move on to the next wizard page. Click Back if you want to return to the 'Displayed Fields' wizard page.

Finish

The 'Finish' wizard page is used to create the wizard once you have selected all the option you want on the previous wizard pages.

Click Finish to create the databrowser widget with all of the options you selected in the wizard. Click Back if you want to return to the 'Layout' wizard page. Click Cancel on any of the wizard pages to leave the wizard without making any changes.

[Prev: Reference: Dialogs] [Home] [Next: Reference: Windows]


Reference: Windows

Introduction

By default Qt Designer starts up with three windows on the left hand side. They are the File Overview Window, the Object Explorer Window, and the Property Editor/Signal Handlers Window. This chapter explains each window in detail.

File Overview Window

File Overview Window

This window lists all the files associated with the project. To open a form or file single click it in the Files list. To rapidly switch between forms and files, type the name of the file in the line edit above the files list and Qt Designer will perform an incremental search to show any matching files or forms.

Right-click a file (or the project) to get a context menu of options, for example, 'Open form' or 'Remove form from project'.

Object Explorer Window

The Object Explorer window lists the current form's widgets and slots. The window contains two tabs, the Widgets tab and the Source tab.

Widget Tab

Widget Tab

Click the Widgets tab to view all the widgets for the current form. The widgets are listed by name and class. Click a widget in the list to highlight it in the corresponding form.

Source Tab

Source Tab

Click the Source tab to view the current form's slots, forward declarations, includes, and class variables. The Source tab uses a tree view to display its information. Items which have a '+' sign have sub-items which are revealed by clicking the '+'. Right click any item in the tree view to popup a context menu.

To edit or add slots, right click the Slots folder and select 'Edit' to invoke the Edit Slots Dialog. Right click the Public, Protected, or Private subdirectories and click 'New' to invoke the Edit Slots Dialog. Right click a slot in the list to invoke a menu with additional options for the slot. To add new slots, choose 'New' from the menu, which invokes the Edit Slots Dialog. To change the properties of the selected slot, choose 'Properties' which invokes the Edit Slots Dialog. To open the C++ editor and jump to the implementation of the selected slot, choose 'Goto Implementation'. To remove the selected slot, choose 'Delete'. Signals can be added or deleted in the same way as slots.

Right click 'Forward Declarations', 'Includes (in declaration)', 'Class Variables', and 'Includes (in implementation)' to invoke a context menu with the 'new' or 'edit' options. Choose 'New' to invoke a line edit for typing a declaration, variable, or include. Right click 'Forward Declarations' and choose 'Edit' to invoke the Edit Forward Declarations Dialog. Right click 'Includes (in declaration)' and choose'Edit' to invoke the Edit Includes (in Declaration) Dialog. Right click 'Class variables' and choose 'Edit' to invoke the Edit Class Variables Dialog. Right click 'Includes (in Implementation)' and choose 'Edit' to invoke the Edit Includes (in Implementation) Dialog.

Property Editor/Signal Handlers Window

Click the Property Editor/Signal Handlers window to view and change the properties of forms, widgets and menus. This window has a 'Properties' tab and a 'Signal Handlers' tab.

Properties Tab

The Properties Tab

Click the 'Properties' tab to change the appearance and behaviour of the selected widget. (For menus, click the menu bar to show the menu item properties in the Property Editor.) The Property Editor has two columns, the Property column which lists property names and the Value column which lists the values. Click the column headers to sort the properties or values. Some property names have a plus sign '+' in a square to their left; this signifies that the property name is the collective name for a set of related properties.

Some properties have simple values, for example, the name property has a text value, the width property (within minimumSize for example) has a numeric value. To change a text value click the existing text and type in your new text. To change a numeric value click the value and either type in a new number, or use the spin buttons to increase or decrease the existing number until it reaches the value you want. Some properties have a fixed list of values, for example the mouseTracking property is boolean and can take the values True or False. The cursor property also has a fixed list of values. If you click the cursor property or the mouseTracking property the value will be shown in a drop down combobox; click the down arrow to see what values are available.

Some properties have complex sets of values; for example the font property. If you click the font property an ellipsis button (...) will appear; click this button and a Select Font dialog will pop up which you can use to change any of the font settings. Other properties have ellipsis buttons which lead to different dialogs depending on what settings the property can have. For example, if you have a lot of text to enter for a text property you could click the ellipsis button to invoke the multi-line text editor dialog. The names of properties which have changed are shown in bold. If you've changed a property but want to revert it to its default value click the property's value and then click the red 'X' button to the right of the value. Some properties have an initial value, e.g. 'TextEdit1', but no default value; if you revert a property that has an initial value but no default value (by clicking the red 'X') the value will become empty unless the property, e.g. name, is not allowed to be empty.

The property editor fully supports Undo and Redo (Ctrl+Z and Ctrl+Y, also available from the Edit menu).

Signal Handlers Tab

The Signal Handlers Tab

Click the 'Signal Handlers' tab to view or create the connections between signals of widgets and custom slots of the form.

[Prev: Reference: Wizards] [Home] [Next: Reference: The .ui File Format]


Reference: The .ui File Format

Qt Designer stores forms in .ui files. These files use an XML format to represent form elements and their characteristics. This document provides an overview of the XML format used, and should provide enough information for developers to write their own .ui parsers so that they can read and modify .ui files programatically.

One way to parse a .ui file is to use Qt and the QDomDocument class; this is how Qt Designer does it: see the uilib/qwidgetfactory.h and uilib/qwidgetfactory.cpp source files. For information on dynamically loading and running .ui files see Loading and Executing a Dynamic Dialog.

The doctype of a .ui file is simply "UI", so the doctype tag is:

<!DOCTYPE UI>

The root element is a "UI", which encloses the entire contents:

<UI version="3.0" stdsetdef="1">
...
</UI>

Within the UI entity, there may one or zero of the following element types:

  • actions - actions, for QMainWindow forms

  • author - the form's author

  • class - the form's class name

  • comment - comments, e.g. copyright notices

  • connections - signal/slot connections

  • customwidgets - custom widgets (old-style)

  • exportmacro - Windows-specific

  • forwards - forward declarations

  • images - embedded images: only for .ui files than include embedded images; images are normally stored in a separate images directory

  • includes - include files

  • layoutdefaults - default values for layout attributes

  • menubar - menu bar, for QMainWindow forms

  • pixmapfunction - the name of the function to use for retrieving pixmaps if neither embedded nor external pixmaps are being used

  • pixmapinproject - an element whose presence ndicates that the pixmaps are handled by the .pro file

  • signals - signal declarations

  • slots - slot declarations

  • tabstops - the form's tab order

  • toolbars - toolbars, for QMainWindow forms

  • variables - class variables

  • widget - the form itself; this element may contain other elements, including other widget elements

  • forward - Qt 3.x beta backwards compatibility

  • include - Qt 2.x backwards compatibility

  • variable - Qt 3.x beta backwards compatibility

The ordering of elements is arbitrary, although it is common for the class element to be first.

UI Elements

actions

This element is used to store the form's actions. It only occurs in QMainWindow forms.

The actions element contains one or more action elements. Each action element contains one or more properties. Each property has a name attribute, and a single value which is contained within a datatype element.

<actions>
    <action>
        <property name="name">
            <cstring>fileNewAction</cstring>
        </property>
        <property name="iconSet">
            <iconset>filenew</iconset>
        </property>
        <property name="text">
            <string>New</string>
        </property>
        <property name="menuText">
            <string>&amp;New</string>
        </property>
        <property name="accel">
            <number>4194382</number>
        </property>
    </action>
    ...
</actions>

author

This element is used to store the author's name as a simple string.

<author>Barney Rubble</author>

class

This element is used to store the form's class name as a simple string.

<class>InsuranceForm</class>

comment

This element is used to store comments, for example, copyright notices, as a simple string.

<comment>*********************************************************************
** Copyright (C) 2002 Trolltech AS.  All rights reserved.
**
** This file is part of Qt Designer.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
*********************************************************************</comment>
</comment>

connections

This element is used to record the signals and slots connections in the form.

The connections element contains one or more connection elements and one or more slot elements. Each connection element identifies the signaling object and its signal, and the receiving object and its slot. Each slot element provides a slot's prototype.

<connections>
    ...
    <connection language="C++">
        <sender>alignActionGroup</sender>
        <signal>selected(QAction*)</signal>
        <receiver>EditorForm</receiver>
        <slot>changeAlignment(QAction*)</slot>
    </connection>
    ...
    <slot access="public" specifier="virtual" language="C++"
    returnType="void">changeAlignment(QAction* align)</slot>
    ...
</connections>

customwidgets

Qt Designer can operate with custom widgets. A custom widget is represented in a .ui file using the <customwidget> element.

Note that these are the 'old-style' custom widgets that show up on the form as grey rectangles. Use plugins to seamlessly integrate your custom widgets into Qt Designer -- see Creating Custom Widgets with Plugins.

Each custom widget has a class name and a header file. They also have a size hint and size policy. A pixmap can be specified; this is displayed on a Qt Designer toolbar button which the user can use to create an instance of the custom widget. Custom widgets usually emit signals, and these are listed. The name and type of any properties that the widget has are also included.

<customwidgets>
    <customwidget>
        <class>StyledButton</class>
        <header location="local">styledbutton.h</header>
        <sizehint>
            <width>40</width>
            <height>25</height>
        </sizehint>
        <container>0</container>
        <sizepolicy>
            <hordata>5</hordata>
            <verdata>5</verdata>
        </sizepolicy>
        <pixmap>image0</pixmap>
        <signal>clicked()</signal>
        <signal>changed()</signal>
        <property type="Color">color</property>
        <property type="Pixmap">pixmap</property>
        <property type="Bool">scale</property>
    </customwidget>
</customwidgets>

exportmacro

This tag is only relevant to Windows users.

If you have a class that requires some Windows-specific export macro, e.g. for classes in a DLL that need to be declared like this: class win_specific_declaration_goes_here Class, you can use the <exportmacro> tag. (In standard Qt we use the Q_EXPORT macro, e.g. class Q_EXPORT QWidget.) If you use this tag you must also:

  1. include the file which contains the macro definition;

  2. add the export macro to the form -- this is achieved by entering the macro's name in the 'export macro' sub-property of the form's name property.

Following these steps will ensure that uic will create the correct class YOUR_MACRO Form declarations.

<exportmacro>EDITOR_EXPORT</exportmacro>

forwards

It is sometimes necessary to forward declare classes, particularly if code is being written in .ui.h files within Qt Designer. Each forward declaration is listed as it should appear in the generated C++ code.

<forwards>
    <forward>class QStringList;</forward>
</forwards>

images

Images are normally stored in their own files and associated with forms using project files. This has the advantage that images can be shared across any number of forms in a project, and between projects.

In some cases it may be desireable to store image data directly in a form, and the <image> tag allows for this.

It is possible to store images in both PNG and XPM formats, although in practice only XPM is recommended because of bugs in some PNG libraries. See the saveImageData function in resource.cpp to see how the image data is encoded.

<images>
    <image name="image0">
        <data format="XPM.GZ" length="409">789cd3d7528808f055d0d2e72a2e492cc94c5648ce482c52d04a29cdcdad8c8eb5ade6523234530022630543251d2e253d856405bffcbc54105b19c856360003103711c6b53006ab440370316528264b4c198450c5808a94d1ed00aac214832b43124b544ec414d34b4c4c441103f11341120831309758313d0cf3b0840b7258d55a73010092c14eca</data>
    </image>
</images>

includes

It is sometimes necessary to #include header files in a .ui file. Header files may be 'local', i.e. relative to the project's directory, or 'global', i.e. part of Qt or the compilers standard libraries. Header files are declared in the implementation wherever possible, although sometimes it is necessary to declare them in the declaration (header) file.

Qt Designer automatically adds <include> tags for a .ui's .ui.h file.

<includes>
    <include location="local" impldecl="in implementation">pixmapcollection.h</include>
    <include location="local" impldecl="in implementation">pixmapchooser.h</include>
    <include location="local" impldecl="in implementation">project.h</include>
    <include location="global" impldecl="in implementation">qfileinfo.h</include>
    <include location="global" impldecl="in implementation">qimage.h</include>
    <include location="global" impldecl="in declaration">qpixmap.h</include>
    <include location="local" impldecl="in implementation">pixmapcollectioneditor.ui.h</include>
</includes>

layoutdefaults

Every form has a default spacing and margin size. These can be overridden on a case-by-case basis.

<layoutdefaults spacing="6" margin="11"/>

menubar

Applications that use QMainWindow often have a menubar. The menubar has a name property and one or more popup menu items. Each menu item has one or more actions and optionally separators.

<menubar>
    <property name="name">
        <cstring>menubar</cstring>
    </property>
    <item text="&amp;File" name="PopupMenu">
        <action name="fileSaveAction"/>
        <separator/>
        <action name="fileExitAction"/>
    </item>
    <item text="&amp;Help" name="PopupMenu_2">
        <action name="helpAboutAction"/>
        <action name="helpAboutQtAction"/>
    </item>
</menubar>

pixmapfunction

Images are normally included by listing their filenames in project files. Images can also be included inline using the images tag. Another way of dealing with images is to specify a function name. This function will be called, with the name (or 'key') of the relevant image, and is responsible for loading the appropriate image. To specify such a function the <pixmapfunction> tag is used.

<pixmapfunction>splashScreen</pixmapfunction>

pixmapinproject

Most applications store their images as separate files listed in the application's project file. This can be signified by including the <pixmapinproject> tag.

<pixmapinproject/>

signals

See connections.

slots

See connections.

tabstops

Tabstops indicate the widgets that get the focus as the user tabs through the form. The <tabstops> tag contains a list of tabstops, in order, each of which holds the name of a widget.

<tabstops>
    <tabstop>templateView</tabstop>
    <tabstop>helpButton</tabstop>
    <tabstop>buttonOk</tabstop>
    <tabstop>buttonCancel</tabstop>
</tabstops>

toolbars

Forms that have toolbars (dock windows) use the <toolbars> tag to hold the details. These forms are normally QMainWindows (or subclasses). Each toolbar has a dock attribute which identifies which dock window the toolbar initially belongs to. They also have both name and label properties. Each toolbar button is represented by an action. Toolbars can also hold other widgets, in which case the <toolbar> tag includes appropriate <widget> tags which give the class, name and any non-default property values for the relevant widget.

<toolbars>
    <toolbar dock="2">
        <property name="name">
            <cstring>toolBar</cstring>
        </property>
        <property name="label">
            <string>Tools</string>
        </property>
        <action name="fileNewAction"/>
        <action name="fileOpenAction"/>
        <action name="fileSaveAction"/>
        <separator/>
        <action name="editUndoAction"/>
        <action name="editRedoAction"/>
        <action name="editCutAction"/>
        <action name="editCopyAction"/>
        <action name="editPasteAction"/>
    </toolbar>
    <toolbar dock="2">
        <property name="name">
            <cstring>Toolbar</cstring>
        </property>
        <property name="label">
            <string>Toolbar</string>
        </property>
        <action name="leftAlignAction"/>
        <action name="centerAlignAction"/>
        <action name="rightAlignAction"/>
        <separator/>
        <action name="boldAction"/>
        <action name="italicAction"/>
        <action name="underlineAction"/>
        <separator/>
        <widget class="QComboBox">
            <property name="name">
                <cstring>fontComboBox</cstring>
            </property>
        </widget>
        <widget class="QSpinBox">
            <property name="name">
                <cstring>SpinBox2</cstring>
            </property>
            <property name="minValue">
                <number>6</number>
            </property>
            <property name="value">
                <number>10</number>
            </property>
        </widget>
    </toolbar>
</toolbars>

variables

Module variables are held in the <variables> tag. Variable type names often include < and >, which must be stored as entities.

<variables>
    <variable>SettingsDialog * settings;</variable>
    <variable>QMap&lt;int, QString&gt; bookmarks;</variable>
    <variable>HelpWindow *browser;</variable>
    <variable>HelpDialog *helpDock;</variable>
    <variable>QGuardedPtr&lt;FindDialog&gt; findDialog;</variable>
    <variable>static QPtrList&lt;MainWindow&gt; *windows;</variable>
</variables>

widget

Widgets are used at multiple levels within a .ui file. The whole form itself is a widget, and it contains other widgets, usually within the context of layouts such as hboxes, vboxes and grids.

Below is an example of a complete .ui file. The form itself is a QWidget with various non-default properties set. This widget contains a single hbox, which also has some non-default properties, and which contains a single QTextBrowser widget.

<!DOCTYPE UI><UI version="3.0" stdsetdef="1">
<class>WinIntroPage</class>
<widget class="QWidget">
    <property name="name">
        <cstring>WinIntroPage</cstring>
    </property>
    <property name="geometry">
        <rect>
            <x>0</x>
            <y>0</y>
            <width>387</width>
            <height>228</height>
        </rect>
    </property>
    <property name="caption">
        <string>Form1</string>
    </property>
    <hbox>
        <property name="name">
            <cstring>unnamed</cstring>
        </property>
        <property name="margin">
            <number>11</number>
        </property>
        <property name="spacing">
            <number>6</number>
        </property>
        <widget class="QTextBrowser">
            <property name="name">
                <cstring>TextBrowser1</cstring>
            </property>
            <property name="text">
                <string>This program installs Qt.</string>
            </property>
        </widget>
    </hbox>
</widget>
<layoutdefaults spacing="6" margin="11"/>
</UI>

forward

This tag is included for Qt 3.x beta backwards compatibility, and should not be used. Use forwards instead.

include

This tag is included for Qt 2.x beta backwards compatibility, and should not be used. Use includes instead.

variable

This tag is included for Qt 3.x beta backwards compatibility, and should not be used. Use variables instead.

Datatype Elements

  • bool - a boolean value (0 or 1), e.g. <bool>1</bool>

  • color - a color, e.g. <color><red>192</red><green>0</green><blue>255</blue></color>

  • cstring - a C string value (8-bit), e.g. <cstring>Some text</cstring>

  • cursor - an integer which indicates the cursor type, e.g. <cursor>4</cursor>. The valid integers for the cursor type are:

    • 0 - ArrowCursor

    • 1 - UpArrowCursor

    • 2 - CrossCursor

    • 3 - WaitCursor

    • 4 - IbeamCursor

    • 5 - SizeVerCursor

    • 6 - SizeHorCursor

    • 7 - SizeBDiagCursor

    • 8 - SizeFDiagCursor

    • 9 - SizeAllCursor

    • 10 - BlankCursor

    • 11 - SplitVCursor

    • 12 - SplitHCursor

    • 13 - PointingHandCursor

    • 14 - ForbiddenCursor

  • enum - an enum name, e.g. <enum>StrongFocus</enum>

  • font - a font description, e.g.

    <font>
    <family>Helvetica</family>
    <pointsize>16</pointsize>
    <weight>50</weight>
    <italic>1</italic>
    <underline>0</underline>
    <strikeout>0</strikeout>
</font>

  • iconset - an iconset (see pixmap), e.g. <iconset>filenew</iconset>

  • number - an integer with an optional sign, e.g. <number>947</number>

  • palette - a palette

  • pixmap - a pixmap, normally the name or "key" of the pixmap; the name is used if pixmaps are stored in the project, the key is used if a user defined function is used to access the pixmap. It is also possible for pixmaps to be included inline. Example: <pixmap>chair</pixmap>

  • point - a point, e.g. <point><x>15</x><y>95</y></point>

  • rect - a rectangle, e.g.

    <rect>
    <x>20</x>
    <y>35</y>
    <width>225</width>
    <height>45</height>
</rect>

  • set - a list of names separated by |'s, e.g. <set>AlignLeft|AlignTop</set>

  • size - a size, e.g. <size><width>150</width><height>105</height></size>

  • sizepolicy - an integer which indicates the size type, e.g. <hsizetype>5</hsizetype><vsizetype>4</vsizetype>. The valid integers for the size type are:

    • 0 - Fixed

    • 1 - Minimum

    • 3 - MinimumExpanding

    • 4 - Maximum

    • 5 - Preferred

    • 7 - Expanding

  • string - a Unicode string value (in UTF8), e.g. <string>Some text</string>

Complex Datatype Elements

palette

This element holds colors for user interface elements for each color group. For example:

<palette>
  <active>
    <color> ... Foreground    ... </color>
    <color> ... Button        ... </color>
    <color> ... Light         ... </color>
    <color> ... Midlight      ... </color>
    <color> ... Dark	      ... </color>
    <color> ... Mid	      ... </color>
    <color> ... Text          ... </color>
    <color> ... BrightText    ... </color>
    <color> ... ButtonText    ... </color>
    <color> ... Base          ... </color>
    <color> ... Background    ... </color>
    <color> ... Shadow	      ... </color>
    <color> ... Highlight     ... </color>
    <color> ... HighlightText ... </color>
  </active>
  <disabled>
    <color><red>128</red><green>128</green><blue>128</blue></color>
    ...
    <color><red>255</red><green>255</green><blue>255</blue></color>
  </disabled>
  <inactive>
    <color><red>0</red><green>0</green><blue>0</blue></color>
    ...
    <color><red>255</red><green>255</green><blue>255</blue></color>
  </inactive>
</palette>

See color for the format of the <color> element.


Qt翻译工具指南

介绍

发布管理器

翻译人员

程序员

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


介绍

Qt提供对于把应用程序翻译为本地语言的极好的支持。本指南解释了在翻译应用程序的时候每个角色如何使用Qt的翻译工具。本指南从一些必须考虑的的方面的一个简要的概述开始，接下来的各章将针对每个角色和所提供的工具支持。

第二章：发布管理器针对的是对程序发布负全部责任的人。他们将主要来协调软件工程师和翻译人员的工作。这一章说明了两个工具的用法。lupdate工具用来同步源程序和翻译。lrelease工具用来创建在发布应用程序时要用到的实时翻译文件。

第三章：翻译人员针对的是翻译人员。它说明了Qt语言学家这个工具的用法。不需要比开始一个程序更多的计算机知识的能力，并且需要使用文本编辑器或者文字处理软件。

第四章：程序员针对的是Qt程序员。它解释了如何创建可以使用翻译文本的Qt应用程序。它也对翻译人员如何识别短语出现的上下文提供了指导。这一章的三个小教程覆盖了程序员所要做的一切事情。

翻译过程的概述

应用程序中要被翻译的绝大多数文本都是单个词或者短语。这些通常出现在窗口标题、菜单条目、弹出帮助文本（气球帮助）和按钮、复选框和单选按钮的标签。

程序员把需要翻译的短语按照他们自己的语言，使用一种简单但特殊的语法放到源代码中。Qt工具为帮助翻译人员对每个短语提供了上下文信息，并且程序员能够在需要的时候为短语添加额外的上下文信息。发布管理器从源代码中生成一套翻译文件并且传递给翻译人员。翻译人员使用Qt语言学家打开这个翻译文件，输入他们的翻译并且把结果保存为翻译文件再传递给发布管理器。发布管理器再为应用程序的使用把这些已经提供的翻译文件生成为更加快速紧凑的版本。这个工具被设计用于当应用程序的变化和发展的重复的周期，能够保存已有的翻译并且能够很容易的标明需要翻译的新的内容。Qt语言学家也提供了一个短语工具书来帮助确保多个应用程序和项目的翻译的一致性。

由于人类语言的细微差别和复杂性，翻译人员和程序员必须注意以下一些问题：

  • 一个词也许需要根据上下文来翻译成不同的形式，比如英语中的open可能就会变成如下形式：德语中的öffnen，“open file”（中文中的“打开文件”）或者德语中的aufbauen，“open internet connection”（中文中的“开打互联网连接”）。

  • 键盘快捷键可能需要改变，但是没有介绍冲突，比如英文中的“&Quit”变成了挪威文中的不再含有“Q”的“Avslutt”。我们不能改变这个正在使用中的字母——除非我们改变几个快捷键。

  • 短语中包含变量，比如，“The 25 files selected will take 63 seconds to process”，运行时被程序自动的插入的两个数字也许需要重新叙述，因为在不同的语言中词序不同，所以变量的位置也许需要变化。

这个Qt翻译工具对这些问题提供了简单清晰的解决方案。

关于这个教程如果有任何注释和建议请写信到Qt文档小组。工具中的bug请寄到qt-bugs。

[Qt语言学家首页] [下一章：发布管理器]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


发布管理器

发布管理器提供了两个工具，lupdate和lrelease。这些工具依赖于qmake项目文件。尽管你不必使用qmake。

Qt项目文件

lupdate和lrelease依赖于应用程序的.proQt项目文件。在项目文件中必须有除了本地语言的之外的附加语言的TRANSLATIONS部分。一个比较有代表性的条目就像这样：

    TRANSLATIONS    = tt2_fr.ts \
                      tt2_nl.ts

在翻译文件的名称中包含有一个场所对于运行时决定调用那种语言很有用处。这个将会在第四章：程序员中进行解释。

一个含有四个翻译源文件的完整的.pro文件的实例：

    HEADERS         = main-dlg.h \
              options-dlg.h
    SOURCES         = main-dlg.cpp \
              options-dlg.cpp \
              main.cpp
    FORMS           = search-dlg.ui
    TRANSLATIONS    = superapp_dk.ts \
              superapp_fi.ts \
              superapp_no.ts \
              superapp_se.ts

QApplication::setDefaultCodec()可以使在被tr()调用中出现的文字字符串所要选择使用的一种8位编码方式成为可能。如果没有编码方式被指定，tr()使用Latin-1。

如果你在你的应用程序中使用QApplication::defaultCodec()机制，Qt语言学家需要你在.pro文件中也设置DEFAULTCODEC条目。例如：

    DEFAULTCODEC    = ISO-8859-5

lupdate

用法：lupdate myproject.pro

这是一个简单的命令行工具。lupdate读取一个Qt.pro项目文件并且产生或者更新项目文件中列出的.ts翻译源文件。翻译人员可以用Qt语言学家来读取这个翻译文件并且插入翻译。

有自己的翻译人员的公司会发现像应用程序开发人员那样定期地（也许每个月）运行lupdate会很有用处的。这样可以使翻译工作能够很均匀地分布在整个项目周期中并且这将可以允许翻译人员可以同时为大量的项目工作。

雇佣翻译人员的公司只需要在整个应用程序开发周期中运行几次lupdate，第一次运行也许正好在第一个测试阶段之前。这样可以把一个充实的单一工作块提供给翻译人员并且翻译缺陷也可以在最初的测试阶段很容易地被发现。第二次以及后来的lupdate运行可以发生在最后的beta测试阶段。

.ts文件格式是一种很简单的人们可读的XML格式，并且如果必要的话，可以使用版本控制系统。

lrelease

用法：lrelease myproject.pro

这是另一个简单的命令行工具。它读取Qt.pro项目文件并且根据项目文件中列出的每一个.ts翻译源文件产生一个应用程序所要用到的.qm文件。.qm文件格式是一个紧凑的二进制格式，它可以提供更快速的翻译查找。

只要应用程序要被发布，从最初的测试版本一直到最终的发布版本，就要运行这个工具。如果.qm文件没有被创建，比如，因为一个alpha发布需要在翻译完成之前出来，应用程序也可以使用程序员放置在源文件中的文本正常运行。一旦.qm文件被提供，应用程序就可以检测它们并且自动地使用它们。

注意：lrelease只是合并那些被标记为“done”的翻译。如果缺少一个翻译，或者有不成功的确认，那么最初的文本将会被使用。

缺少的翻译

lupdate和lrelease也可以用在不完全的.ts翻译源文件上。缺少的翻译将会在运行的时候由本地的语言短语替换。

[上一章：介绍] [Qt语言学家首页] [下一章：翻译人员]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Translators

Linguist Main Window

The One Minute Guide to Using Qt Linguist

Qt Linguist is a tool for adding translations to Qt applications. It introduces the concept of a translation "context" which means a group of phrases that appear together on the screen e.g. in the same menu or dialog.

To start, run Qt Linguist, either from the taskbar menu, or by double clicking the desktop icon, or type linguist (followed by Enter) at the command line. Once Qt Linguist has started choose File|Open from the menu bar and select a .ts translation source file to work on.

Qt Linguist's main window is divided into four main areas. The left hand side contains the Context list, the top right is the Source text area, the middle right is the translation area and the bottom right is the phrases and guesses area. We'll describe them in detail later.

Click on one of the contexts in the context list (left hand side) and then click on one of the phrases that appears in the Source text area (top right). The phrase will be copied into the translation area (middle right). Click under the word 'Translation' and type in the translation. Click Ctrl+Enter (Done & Next) to confirm that you have completed the translation and to move on to the next phrase that requires translation.

The cycle of entering a translation then pressing Ctrl+Enter can be repeated until all the translations are done or until you finish the session. Linguist will attempt to fill the "phrases and guesses" area with possible translations from any open phrase books and any previous translations. Each has a keyboard shortcut, e.g. Ctrl+1, Ctrl+2, etc., which you can use to copy the guess into the Translation area. (Mouse users can double click a phrase or guess to move it into the Translation area.) At the end of the session choose File|Save from the menu bar and then File|Exit to quit.

Qt Linguist's Main Window

Context List

This appears at the left hand side of the main window by default. The first column, 'Done', identifies whether or not the translations for the context have been done. A tick indicates that all the translations have been done and are valid. A question mark indicates that one or more translations have not been done or have failed validation. The second column, 'Context' is the name of the context in which the translation phrases appear. The third column, 'Items' shows two numbers, the first is the number of translations that have been done, and the second is the number of phrases that are in the context; if the numbers are equal then all the translations have been done. Note that a greyed out tick indicates an obsolete translation, i.e. a phrase that was translated in a previous version of the application but which does not occur in the new version.

The contexts are ordered alphabetically. The phrases within each context are in the order in which they appear in the source program and this may not be the order in which they are shown on screen.

The Context List is a dockable window so it can be dragged to another position in the main window, or dragged out of the main window to be a window in its own right. If you move the Context List, Qt Linguist will remember its position and restore it whenever you start the program.

Source Text Area

This appears at the top right of the main window by default. The first column, 'Done', signifies the status of the translation. A tick indicates that the phrase has been translated and passed validation. A question mark indicates that the translation has not been done. An exclamation mark indicates that the translation has failed validation. The second column 'Source text' shows the text that must be translated. The third column shows the translation.

Qt Linguist provides three kinds of validation: accelerator, punctuation and phrase. If the source text contains an accelerator i.e. an ampersand, '&' and the translated text does not contain an ampersand the translation will fail the accelerator validation. Similarly, if the source text ends with a particular punctuation mark, e.g. '?', '!' or '.' and the translation ends with a different punctuation mark the translation will fail the punctuation validation. If the source text has a translation in one of the open phrase books that differs from the translation used the translation will fail phrase validation. (See Validation.)

The Source Text Area is a dockable window.

Translation Area

This area appears at the middle right of the main window by default. It is comprised of three vertical sections. The first section is labelled 'Source text' below which the source text appears. The second section contains contextual information on a light blue background that the programmer has added to assist the translator. If no contextual information has been given this section does not appear. The third section is labelled 'Translation' and this is where you enter the translation of the source text.

Phrases and Guesses Area

This area appears at the bottom right of the main window by default. When you move to a new phrase if the phrase is in one of the phrase books that has been loaded the phrase will appear in this area with its translation. If the phrase is the same or similar to another phrase that has already been translated the phrase and translation will be shown in this area. To copy a translation from the phrases and guesses area press F6 to move to the phrases and guesses area, use the up and down arrow keys to move to the phrase you want to use and press Enter to copy it. If you decide that you don't want to copy a phrase after all, press Esc. In both cases the focus will return to the Translation area. Alternatively, double click the translation you want to use and it will be copied into the translation area.

The Phrases and Guesses Area is a dockable window.

Common Tasks

Leaving a Translation for Later

If you wish to leave a translation press Ctrl+L (Next Unfinished) to move to the next unfinished translation. An unfinished translation is one that either has not been translated at all or one which fails validation. To move to the next phrase press Shift+Ctrl+L. You can also navigate using the Translation menu. If you want to go to a different context entirely, click the context you want to work on in the Context list, then click the source text in the Source Text area.

Phrases That Require Multiple Translations Depending on Context

The same phrase may occur in two or more contexts without conflict. Once a phrase has been translated in one context, Qt Linguist notes that the translation has been made and when the translator reaches a later occurrence of the same phrase Qt Linguist will provide the previous translation as a possible translation candidate in the phrases and guesses area. If the previous translation is acceptable just click the Done & Next button (press Alt+Enter) to move on to the next unfinished phrase.

If a phrase occurs more than once in a particular context it will only be shown once in Qt Linguist's context list and the translation will be applied to every occurrence within the context. If the same phrase needs to be translated differently within the same context the programmer must provide a distinguishing comment for each of the phrases concerned. If such comments are used the duplicate phrases will appear in the context list. The programmers comments will appear in the translation area on a light blue background.

Changing Keyboard Accelerators

A keyboard accelerator is a key combination that when pressed will cause an application to perform an action. Keyboard accelerators normally come in two forms: Alt key and Ctrl key accelerators.

Alt key accelerators are used for menus and buttons. The underlining signifies that pressing the Alt key with the underlined letter is the same as clicking the menu item with the mouse. For example, most applications have a File menu with the "F" in the word "file" underlined. In these applications the file menu can be invoked either by clicking the word "File" on the menu bar or by pressing Alt+F. The accelerator key which is underlined is signified by preceeding it with an ampersand, e.g. &File. If a source phrase appears with an ampersand in it then the translation should also contain an ampersand, preferably in front of the same letter. The meaning of Alt key accelerators can be determined from the phrase in which the ampersand is embedded. The translator may need to change the letter used with the Alt key, e.g. if the translated phrase does not contain the original accelerator letter. Conflicts with other keys, i.e. having two Alt key accelerators using the same letter in the same context, must be avoided. Note that some Alt key accelerators, usually those on the menu bar, may apply in other contexts.

Ctrl key accelerators can exist independently of any visual control. They are often used to invoke actions in menus that would otherwise take several keystrokes or mouse clicks. They may also be used to perform actions that do not appear in any menu or on any button. For example, most applications that have a File menu have a submenu item called New. In many applications this will appear as "New... Ctrl+N". This menu option could be invoked by clicking File then clicking New with the mouse. Or you could press Alt+F then press N since these letters are underlined. But the same thing can be achieved simply by pressing Ctrl+Enter. Accelerators that use the Ctrl key are shown literally in the source text, e.g. Ctrl+Enter. Ctrl key accelerators have no phrase so the translator must rely on the programmer to add a "comment" which appears in the top right hand pane. This comment should explain what action the Ctrl key accelerator performs. Ideally Ctrl key accelerators are translated simply by copying them by clicking the Begin from Source button. However in some cases the letter will not make sense in the target language and must be changed. Whatever letter (or digit) is chosen, the translation should always be in the form "Ctrl+" followed by the letter or digit in upper case. As with Alt key accelerators, if the translator changes the key it must not conflict with any other Ctrl key accelerator.

Later versions of Qt Linguist are expected to help the translator avoid accelerator conflicts.

Dealing with Phrases that Contain Variables

Some phrases contain variables. Variables are placeholders for items of text that are filled in at runtime. They are signified in the source text with a percent sign followed by a digit, e.g. After processing file %1, file %2 is next in line. In this example, %1 will be replaced at runtime with the name of the first file to be processed and %2 with the name of the next file to be processed. In the translated version the variables must still appear. For example a German translation might reverse the phrases, e.g. Datei %2 wird bearbeitet, wenn. Datei %1 fertig ist. Note that both variables are still used but their order has changed. The order in which variables appear does not matter; %1 will always be replaced by the same text at runtime no matter where it appears in the source text or translation and similarly %2, etc.

Reusing Translations

If the translated text is similar to the source text, click the Begin from Source button (press Alt+T) which will copy the source text into the translation area.

Qt Linguist automatically lists phrases from the open phrase books and similar or identical phrases that have already been translated in the Phrases and guesses area.

Creating and Using Phrase Books

Phrase Book Dialog

A Qt Linguist phrase book is a set of source phrases, target (translated) phrases, and optional definitions. Phrase Books are created independently of any application, although typically one phrase book will be created per application or family of applications.

If the translator reaches an untranslated phrase that is the same as a source phrase in the phrase book, Qt Linguist will show the phrase book entry in the Relevant phrases panel at the bottom right of the main window. Phrases which have translations that conflict with those given in the phrase book are marked with a question mark in the source text pane. Phrase Books are used to provide a common set of translations to help ensure consistency. They can also be used to avoid duplication of effort since the translations for a family of applications can be produced once in the phrase book and the phrase book used for the majority of translations in each application.

Before a phrase book can be edited it must be created or if it already exists, opened. Create a new phrase book by selecting Phrase|New Phrase Book from the menu bar. You must enter a filename and may change the location of the file if you wish. A newly created phrase book is automatically opened. Open an existing phrase book by choosing Phrase|Open Phrase Book from the menu bar.

To add a new phrase click the New Phrase button (or press Alt+N) and type in a new source phrase. Press Tab and type in the translation. Optionally press Tab and enter a definition -- this is useful to distinguish different translations of the same source phrase. This process may be repeated as often as necessary.

You can delete a phrase by selecting it in the phrases list and clicking Remove Phrase.

Click the Save button (press Alt+S) and then click the Close button (press Esc) once you've finished adding (and removing) phrases.

When a phrase or set of phrases appears in the phrase book double clicking the required target phrase will copy it to the translation pane at the text cursor position. If you want to replace the text in the translation pane with the target phrase, click the translation pane, choose Edit|Select All (press Alt+A) and then double click the target phrase.

Validation

Qt Linguist provides three kinds of validation on translated phrases.

  1. Accelerator validation detects translated phrases that do not have an ampersand when the source phrase does and vice versa.

  2. Punctuation validation detects differences in the terminating punctuation between source and translated phrases when this may be significant, e.g. warns if the source phrase ends with an ellipsis, exclamation mark or question mark, and the translated phrase doesn't and vice versa.

  3. Phrases validation detects source phrases that are also in the phrase book but whose translation differs from that given in the phrase book.

Validation may be switched on or off from the menu bar's Validation item or using the toolbar buttons. Phrases that fail validation are marked with a question mark in the source text pane. If you switch validation off and then switch it on later, Qt Linguist will recheck all phrases and mark any that fail validation.

If any phrase in a context is invalid then the context itself will be marked with a question mark; if all the phrases in a context are done and are valid the context will be marked with a tick.

Note that only phrases which are marked as done (with a tick) will appear in the application. Invalid phrases and phrases which are translated but not marked as done are kept in the translation source file but are not used by the application.

Qt Linguist Reference

File Types

Qt Linguist makes use of three kinds of file:

  • .ts translation source files
    are human-readable XML files containing source phrases and their translations. These files are usually created and updated by lupdate and are specific to an application.

  • .qm Qt message files
    are binary files that contain translations used by an application at runtime. These files are generated by lrelease, but can also be generated by Qt Linguist.

  • .qph Qt phrase book files
    are human-readable XML files containing standard phrases and their translations. These files are created and updated by Qt Linguist and may be used by any number of projects and applications.

The Menu Bar

Menu Bar

  • File

    • Open... Ctrl+O
      pops up an open file dialog from which a translation source .ts file can be chosen.

    • Save Ctrl+S
      saves the current translation source .ts file.

    • Save As...
      pops up a save as file dialog so that the current translation source .ts file may be saved with a different name and/or put in a different location.

    • Release...
      pops up a save as file dialog. The filename entered will be a Qt message .qm file of the translation based on the current translation source file. The release manager's command line tool lrelease performs the same function on all of an application's translation source files.

    • Print... Ctrl+P
      pops up a print dialog. If you click OK the translation source and the translations will be printed.

    • Recently opened files
      shows the .ts files that have been opened recently, click one to open it.

    • Exit Ctrl+Q
      closes Qt Linguist.

  • Edit

    • Undo Ctrl+Z
      undoes the last editing action in the translation pane.

    • Redo Ctrl+Y
      redoes the last editing action in the translation pane.

    • Cut Ctrl+X
      deletes any highlighted text in the translation pane and saves a copy to the clipboard.

    • Copy Ctrl+C
      copies the highlighted text in the translation pane to the clipboard.

    • Paste Ctrl+V
      pastes the clipboard text into the translation pane.

    • Select All Ctrl+A
      selects all the text in the translation pane ready for copying or deleting.

    • Find... Ctrl+F
      pops up the Find dialog. When the dialog pops up enter the text to be found and click the Find Next button. Source phrases, translations and comments may be searched.

    • Find Next F3
      finds the next occurrence of the text that was last entered in the Find dialog.

  • Translation

    • Prev Unfinished Ctrl+K
      moves to the nearest previous unfinished source phrase (unfinished means untranslated or translated but failed validation).

    • Next Unfinished Ctrl+L
      moves to the next unfinished source phrase.

    • Prev Shift+Ctrl+K
      moves to the previous source phrase.

    • Next Shift+Ctrl+L
      moves to the next source phrase.

    • Done & NextCtrl+Enter
      mark this phrase as 'done' (translated) and move to the next unfinished source phrase.

    • Begin from Source Ctrl+B
      copies the source text into the translation.

  • Validation (See the Validation section)

    • Accelerators
      toggles validation on or off for Alt accelerators.

    • Ending Punctuation
      switches validation on or off for phrase ending punctuation, e.g. ellipsis, exclamation mark, question mark, etc.

    • Phrase Matches
      sets validation on or off for matching against translations that are in the current phrase book.

  • Phrase (See the section Creating and Using Phrase Books for details.)

    • New Phrase Book... Ctrl+N
      pops up a save as file dialog. You must enter a filename to be used for the phrase book and save the file. Once saved you should open the phrase book to begin using it.

    • Open Phrase Book... Ctrl+H
      pops up an open file dialog. Find and choose a phrase book to open.

    • Close Phrase Book
      closes the current phrase book. This will stop any further phrase validation taking place. The same effect can be achieved by switching off phrase validation using the Validation menu or the phrase toolbar button.

    • Edit Phrase Book...
      pops up the phrase book dialog where you can add, edit or delete phrases.

    • Print Phrase Book...
      pops up a print dialog. If you click OK the phrase book will be printed.

  • View

    • Revert Sorting
      puts the phrases in the source text pane into their original order.

    • Display Guesses
      turns the display of phrases and guesses on or off.

    • Views
      toggles the visibility of the Context, Source text and Phrase views.

    • Toolbars
      toggles the visibility of the different toolbars.

The Toolbar

Toolbar

  • Pops up the open file dialog to open a new translation source .ts file.

  • Saves the current translation source .ts file.

  • Prints the current translation source .ts file.

  • Pops up the file open dialog to open a new phrase book .qph file.

  • Undoes the last editing action in the translation pane.

  • Redoes the last editing action in the translation pane.

  • Deletes any highlighted text in the translation pane and save a copy to the clipboard.

  • Copies the highlighted text in the translation pane to the clipboard.

  • Pastes the clipboard text into the translation pane.

  • Pops up the Find dialog.

  • Moves to the previous source phrase.

  • Moves to the next source phrase.

  • Moves to the previous unfinished source phrase.

  • Moves to the next unfinished source phrase.

  • Marks the phrase as 'done' (translated) and move to the next unfinished source phrase.

  • Toggles accelerator validation on and off.

  • Toggles phrase ending punctuation validation on and off.

  • Toggles phrase book validation on or off.

The Find Dialog

The Find Dialog

Choose Edit|Find from the menu bar or press Ctrl+F to pop up the Find dialog. Press F3 to repeat the last search. By default the source phrases, translations and comments will all be searched and the search will be case-insensitive. These settings can be changed by checking or unchecking the checkboxes to reflect your preferences.

The Phrase Dialog

This dialog is explained in the Creating and Using Phrase Books section.

[Prev: Release Manager] [Home] [Next: Programmers]


Programmers

Support for multiple languages is extremely simple in Qt applications and adds little overhead to the programmer's workload.

Qt minimizes the performance cost of using translations by translating the phrases for each window as they are created. In most applications the main window is created just once. Dialogs are often created once and then shown and hidden as required. Once the initial translation has taken place there is no further runtime overhead for the translated windows. Only those windows that are created, destroyed and subsequently created will have a translation performance cost -- although the overhead is still very low.

Creating applications that can switch language at runtime is possible with Qt, but requires a certain amount of programmer intervention and will of course incur some runtime performance cost.

Making the Application Translation Aware

Programmers should make their application look for and load the appropriate translation file and mark user-visible text and Ctrl keyboard accelerators as targets for translation.

Each piece of text that requires translating requires context to help the translator identify where in the program the text occurs. In the case of multiple identical texts that require different translations the translator also requires some information to disambiguate the source texts. Marking text for translation will automatically cause the class name to be used as basic context information. In some cases the programmer may be required to add additional information to help the translator.

Creating Translation Files

Translation files consist of all the user-visible text and Ctrl key accelerators in an application and translations of that text. Translation files are created as follows:

  1. Run lupdate initially to generate the first set of .ts translation source files with all the user-visible text but no translations.

  2. The .ts files are given to the translator who adds translations using Qt Linguist. Qt Linguist takes care of any changed or deleted source text.

  3. Run lupdate to incorporate any new text added to the application. lupdate synchronizes the user-visible text from the application with the translations; it does not destroy any data.

  4. Steps 2 and 3 are repeated as often as necessary.

  5. When a release of the application is needed lrelease is run to read the .ts files and produce the .qm files used by the application at runtime.

For lupdate to work successfully, it must know which translation files to produce. The files are simply listed in the application's .pro Qt project file, for example:

    TRANSLATIONS    = tt2_fr.ts \
                      tt2_nl.ts

See the "lupdate" and "lrelease" sections.

Loading Translations

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

This is how a simple main() function of a Qt application begins.

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

        QTranslator translator( 0 );
        translator.load( "tt1_la", "." );
        app.installTranslator( &translator );

For a translation-aware application a translator object is created, a translation is loaded and the translator object installed into the application.

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

        QTranslator translator( 0 );
        translator.load( QString( "tt2_" ) + QTextCodec::locale(), "." );
        app.installTranslator( &translator );

In production applications a more flexible approach, for example, loading translations according to locale, might be more appropriate. If the .ts files are all named according to a convention such as appname_locale, e.g. tt2_fr, tt2_de etc, then the code above will load the current locale's translation at runtime.

If there is no translation file for the current locale the application will fall back to using the original source text.

Making the Application Translate User-Visible Strings

User-visible strings are marked as translation targets by wrapping them in a tr() call, for example:

    button = new QPushButton( "&Quit", this );

would become

    button = new QPushButton( tr( "&Quit" ), this);

All QObject subclasses that use the Q_OBJECT macro have a reimplementation of the tr() function.

Although the tr() call is normally made directly since it is usually called as a member function of a QObject subclass, in other cases an explicit class name can be supplied, for example:

    QPushButton::tr( "&Quit" )

or

    QObject::tr( "&Quit" )

Distinguishing Identical Strings That Require Different Translations

The lupdate program automatically provides a context for every source text. This context is the class name of the class that contains the tr() call. This is sufficient in the vast majority of cases. Sometimes however, the translator will need further information to uniquely identify a source text; for example, a dialog that contained two separate frames, each of which contained an "Enabled" option would need each identified because in some languages the translation would differ between the two. This is easily achieved using the two argument form of the tr() call, e.g.

    rbc = new QRadioButton( tr( "Enabled", "Color frame" ), this);

and

    rbh = new QRadioButton( tr( "Enabled", "Hue frame" ), this);

Ctrl key accelerators are also translatable:

        file->insertItem( tr( "E&xit" ), qApp, SLOT(quit()),
                          QAccel::stringToKey( tr("Ctrl+Q", "Quit") ) );

It is strongly recommended that the two argument form of tr() is used for Ctrl key accelerators. The second argument is the only clue the translator has as to the function performed by the accelerator.

Helping The Translator With Navigation Information

In large complex applications it may be difficult for the translator to see where a particular source text comes from. This problem can be solved by adding a comment using the keyword TRANSLATOR which describes the navigation steps to reach the text in question; e.g.

    /*  TRANSLATOR FindDialog

    Choose Edit|Find from the menu bar or press Ctrl+F to pop up the
    Find dialog.
    */

These comments are particularly useful for widget classes.

Coping With C++ Namespaces

C++ namespaces and the using namespace statement can confuse lupdate. It will interpret MyClass::tr() as meaning just that, not as MyNamespace::MyClass::tr(), even if MyClass is defined in the MyNamespace namespace. Run-time translation of these strings will fail because of that.

You can work around this limitation by putting a TRANSLATOR comment at the beginning of the source files that use MyClass::tr():

    /* TRANSLATOR MyNamespace::MyClass */

After the comment, all references to MyClass::tr() will be understood as meaning MyNamespace::MyClass::tr().

Translating Text that is Outside of a QObject subclass

Using QApplication::translate()

If the quoted text is not in a member function of a QObject subclass, use either the tr() function of an appropriate class, or the QApplication::translate() function directly:

    void some_global_function( LoginWidget *logwid )
    {
        QLabel *label = new QLabel(
                LoginWidget::tr("Password:"), logwid );
    }

    void same_global_function( LoginWidget *logwid )
    {
        QLabel *label = new QLabel(
                qApp->translate("LoginWidget", "Password:"),
                logwid );
    }
Using QT_TR_NOOP and QT_TRANSLATE_NOOP

If you need to have translatable text completely outside a function, there are two macros to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). These macros merely mark the text for extraction by lupdate. The macros expand to just the text (without the context).

Example of QT_TR_NOOP():

    QString FriendlyConversation::greeting( int greet_type )
    {
        static const char* greeting_strings[] = {
            QT_TR_NOOP( "Hello" ),
            QT_TR_NOOP( "Goodbye" )
        };
        return tr( greeting_strings[greet_type] );
    }

Example of QT_TRANSLATE_NOOP():

    static const char* greeting_strings[] = {
        QT_TRANSLATE_NOOP( "FriendlyConversation", "Hello" ),
        QT_TRANSLATE_NOOP( "FriendlyConversation", "Goodbye" )
    };

    QString FriendlyConversation::greeting( int greet_type )
    {
        return tr( greeting_strings[greet_type] );
    }

    QString global_greeting( int greet_type )
    {
        return qApp->translate( "FriendlyConversation",
                                greeting_strings[greet_type] );
    }

Tutorials

Three tutorials are presented. The first demonstrates the creation of a QTranslator object. It also shows the simplest use of the tr() function to mark user-visible source text for translation. The second tutorial explains how to make the application load the translation file applicable to the current locale. It also shows the use of the two-argument form of tr() which provides additional information to the translator. The third tutorial explains how identical source texts can be distinguished even when they occur in the same context. This tutorial also discusses how the translation tools help minimize the translator's work when an application is upgraded.

Tutorial 1: Loading and Using Translations

Tutorial 1 Screenshot, English version

TEMPLATE        = app
CONFIG          += qt warn_on
SOURCES         = main.cpp
TRANSLATIONS    = tt1_la.ts

tt1.pro

/****************************************************************
**
** Translation tutorial 1
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qtranslator.h>

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

    QTranslator translator( 0 );
    translator.load( "tt1_la", "." );
    app.installTranslator( &translator );

    QPushButton hello( QPushButton::tr( "Hello world!" ), 0 );

    app.setMainWidget( &hello );
    hello.show();
    return app.exec();
}

main.cpp

This example is a reworking of the "hello-world" example from Tutorial #1, with a Latin translation. The Tutorial 1 Screenshot, English version, above, shows the English version.

Line by Line Walk-through
    #include <qtranslator.h>

This line includes the definition of the QTranslator class. Objects of this class provide translations for user-visible text.

        QTranslator translator( 0 );

Creates a QTranslator object without a parent.

        translator.load( "tt1_la", "." );

Try to load a file called tt1_la.qm (the .qm file extension is implicit) that contains Latin translations for the source texts used in the program. No error will occur if the file is not found.

        app.installTranslator( &translator );

Add the translations from tt1_la.qm to the pool of translations used by the program. No error will occur if the file is not found.

        QPushButton hello( QPushButton::tr( "Hello world!" ), 0 );

Creates a push button that displays "Hello world!". If tt1_la.qm was found and contains a translation for "Hello world!", the translation appears; if not, the source text appears.

All classes that inherit QObject have a tr() function. Inside a member function of a QObject class, we simply write tr("Hello world!") instead of QPushButton::tr("Hello world!") or QObject::tr("Hello world!").

Running the Application in English

Since we haven't made the translation file tt1_la.qm, the source text is shown when we run the application:

Tutorial 1 Screenshot, English version

Creating a Latin Message File

The first step is to create a project file, tt1.pro, that lists all the source files for the project. The project file can be a qmake project file, or even an ordinary makefile. Any file that contains

    SOURCES         = main.cpp
    TRANSLATIONS    = tt1_la.ts

will work. TRANSLATIONS specifies the message files we want to maintain. In this example, we just maintain one set of translations, namely Latin.

Note that the file extension is .ts, not .qm. The .ts translation source format is designed for use during the application's development. Programmers or release managers run the lupdate program to generate and update .ts files with the source text that is extracted from the source code. Translators read and update the .ts files using Qt Linguist adding and editing their translations.

The .ts format is human-readable XML that can be emailed directly and is easy to put under version control. If you edit this file manually, be aware that the default encoding for XML is UTF-8, not Latin-1 (ISO 8859-1). One way to type in a Latin-1 character such as 'ø' (Norwegian o with slash) is to use an XML entity: "&#xf8;". This will work for any Unicode character.

Once the translations are complete the lrelease program is used to convert the .ts files into the .qm Qt message file format. The .qm format is a compact binary format designed to deliver very fast lookup performance. Both lupdate and lrelease read all the project's source and header files (as specified in the HEADERS and SOURCES lines of the project file) and extract the strings that appear in tr() function calls.

lupdate is used to create and update the message files (tt1_la.ts in this case) to keep them in sync with the source code. It is safe to run lupdate at any time, as lupdate does not remove any information. For example, you can put it in the makefile, so the .ts files are updated whenever the source changes.

Try running lupdate right now, like this:

    lupdate tt1.pro

You should now have a file tt1_la.ts in the current directory, containing this

    <!DOCTYPE TS><TS>
    <context>
        <name>QPushButton</name>
        <message>
            <source>Hello world!</source>
            <translation type="unfinished"></translation>
        </message>
    </context>
    </TS>

You don't need to understand the file format since it is read and updated using tools, e.g. lupdate and Qt Linguist.

Translating to Latin with Qt Linguist

We will use Qt Linguist to provide the translation, although you can use any XML or plain text editor to enter a translation into a .ts file.

To start Qt Linguist, type

    linguist tt1_la.ts

You should now see the text "QPushButton" in the top left pane. Double-click it, then click on "Hello world!" and enter "Orbis, te saluto!" in the Translation pane (the middle right of the window). Don't forget the exclamation mark!

Click the Done checkbox and choose File|Save from the menu bar. The .ts file will no longer contain

    <translation type='unfinished'></translation>

but instead will have

    <translation>Orbis, te saluto!</translation>
Running the Application in Latin

To see the application running in Latin, we have to generate a .qm file from the .ts file. Generating a .qm file can be achieved either from within Qt Linguist (for a single .ts file), or by using the command line program lrelease which will produce one .qm file for each of the .ts files listed in the project file. Generate tt1_la.qm from tt1_la.ts by choosing File|Release from Qt Linguist's menu bar and pressing Save in the file save dialog that pops up. Now run the tt1 example program again. This time the button will be labelled "Orbis, te saluto!".

Tutorial 1 Screenshot, Latin version

Tutorial 2: Using Two or More Languages

Tutorial 2 Screenshot, English version

TEMPLATE        = app
CONFIG          += qt warn_on
HEADERS         = arrowpad.h \
                  mainwindow.h
SOURCES         = arrowpad.cpp \
                  main.cpp \
                  mainwindow.cpp
TRANSLATIONS    = tt2_fr.ts \
                  tt2_nl.ts

tt2.pro

This example is a slightly more involved and introduces a key Qt Linguist concept: "contexts".

  • arrowpad.h contains the definition of ArrowPad, a custom widget;

  • arrowpad.cpp contains the implementation of ArrowPad;

  • mainwindow.h contains the definition of MainWindow, a subclass of QMainWindow

  • mainwindow.cpp contains the implementation of MainWindow;

  • main.cpp contains main().

We will use two translations, French and Dutch, although there is no effective limit on the number of possible translations that can be used with an application. The relevant lines of tt2.pro are

    HEADERS         = arrowpad.h \
                      mainwindow.h
    SOURCES         = arrowpad.cpp \
                      main.cpp \
                      mainwindow.cpp
    TRANSLATIONS    = tt2_fr.ts \
                      tt2_nl.ts

Run lupdate; it should produce two identical message files tt2_fr.ts and tt2_nl.ts. These files will contain all the source texts marked for translation with tr() calls and their contexts.

Line by Line Walk-through

In arrowpad.h we define the ArrowPad subclass which is a subclass of QWidget. In the Tutorial 2 Screenshot, English version, above, the central widget with the four buttons is an ArrowPad.

    class ArrowPad : public QGrid

When lupdate is run it not only extracts the source texts but it also groups them into contexts. A context is the name of the class in which the source text appears. Thus, in this example, "ArrowPad" is a context: it is the context of the texts in the ArrowPad class. The Q_OBJECT macro defines tr(x) in ArrowPad like this

    qApp->translate( "ArrowPad", x )

Knowing which class each source text appears in enables Qt Linguist to group texts that are logically related together, e.g. all the text in a dialog will have the context of the dialog's class name and will be shown together. This provides useful information for the translator since the context in which text appears may influence how it should be translated. For some translations keyboard accelerators may need to be changed and having all the source texts in a particular context (class) grouped together makes it easier for the translator to perform any accelerator changes without introducing conflicts.

In arrowpad.cpp we implement the ArrowPad class.

        (void) new QPushButton( tr( "&Up" ), this );

We call ArrowPad::tr() for each button's label since the labels are user-visible text.

Tutorial 2 Screenshot, English version

    class MainWindow : public QMainWindow
    {
        Q_OBJECT

In the Tutorial 2 Screenshot, English version, above, the whole window is a MainWindow. This is defined in the mainwindow.h header file. Here too, we use Q_OBJECT, so that MainWindow will become a context in Qt Linguist.

In the implementation of MainWindow, mainwindow.cpp, we create an instance of our ArrowPad class

        ArrowPad *ap = new ArrowPad( this, "arrow pad" );

We also call MainWindow::tr() twice, once for the menu item and once for the accelerator.

        file->insertItem( tr( "E&xit" ), qApp, SLOT(quit()),
                          QAccel::stringToKey( tr( "Ctrl+Q", "Quit" ) ) );

Note the use of QAccel::stringToKey() to support different keys in other languages. "Ctrl+Q" is a good choice for Quit in English, but a Dutch translator might want to use "Ctrl+A" (for Afsluiten) and a German translator "Strg+E" (for Beenden). When using tr() for Ctrl key accelerators the two argument form should be used with the second argument describing the function that the accelerator performs.

Our main() function is defined in main.cpp as usual.

        QTranslator translator( 0 );
        translator.load( QString( "tt2_" ) + QTextCodec::locale(), "." );
        app.installTranslator( &translator );

We choose which translation to use according to the current locale. QTextCodec::locale() can be influenced by setting the LANG environment variable, for example. Notice that the use of a naming convention that incorporates the locale for .qm message files, (and .ts files), makes it easy to implement choosing the translation file according to locale.

If there is no .qm message file for the locale chosen the original source text will be used and no error raised.

Translating to French and Dutch

We'll begin by translating the example application into French. Start Qt Linguist with tt2_fr.ts. You should get the seven source texts ("&Up", "&Left", etc.) grouped in two contexts ("ArrowPad" and "MainWindow").

Now, enter the following translations:

  • ArrowPad

    • &Up - &Haut

    • &Left - &Gauche

    • &Right - &Droite

    • &Down - &Bas

  • MainWindow

    • E&xit - &Quitter

    • Ctrl+Q - Ctrl+Q

    • &File - &Fichier

It's quickest to press Alt+D (which clicks the Done & Next button) after typing each translation, since this marks the translation as done and moves on to the next source text.

Save the file and do the same for Dutch working with tt2_nl.ts:

  • ArrowPad

    • &Up - &Boven

    • &Left - &Links

    • &Right - &Rechts

    • &Down - &Onder

  • MainWindow

    • E&xit - &Afsluiten

    • Ctrl+Q - Ctrl+A

    • File - &Bestand

We have to convert the tt1_fr.ts and tt1_nl.ts translation source files into .qm files. We could use Qt Linguist as we've done before; however using the command line tool lrelease ensures that all the .qm files for the application are created without us having to remember to load and File|Release each one individually from Qt Linguist.

In practice we would include calls to lupdate and lrelease in the application's makefile to ensure that the latest translations are used.

Type

    lrelease tt2.pro

This should create both tt2_fr.qm and tt2_nl.qm. Set the LANG environment variable to fr. In Unix, one of the two following commands should work

    export LANG=fr
    setenv LANG fr

In Windows, either modify autoexec.bat or run

    set LANG=fr

When you run the program, you should now see the French version:

Tutorial 2 Screenshot, French version

Try the same with Dutch, by setting LANG=nl. Now the Dutch version should appear:

Tutorial 2 Screenshot, Dutch version

Exercises

Mark one of the translations in Qt Linguist as not done, i.e. by unchecking the "done" checkbox; run lupdate, then lrelease, then the example. What effect did this change have?

Set LANG=fr_CA (French Canada) and run the example program again. Explain why the result is the same as with LANG=fr.

Change one of the accelerators in the Dutch translation to eliminate the conflict between &Bestand and &Boven.

Tutorial 3: Disambiguating Identical Strings

Tutorial 3 Screenshot, "Troll Print 1.0", English version

TEMPLATE        = app
CONFIG          += qt warn_on
HEADERS         = mainwindow.h \
                  printpanel.h
SOURCES         = main.cpp \
                  mainwindow.cpp \
                  printpanel.cpp
TRANSLATIONS    = tt3_pt.ts

tt3.pro

We've included a translation file, tt3_pt.ts, which contains some Portuguese translations for this example.

We will consider two releases of the same application: Troll Print 1.0 and 1.1. We will learn to reuse the translations created for one release in a subsequent release. (In this tutorial, you have to edit some source files. It's probably best to copy all the files to a new temporary directory and work from there.)

Troll Print is a toy example application that lets the user choose printer settings. It comes in two versions: English and Portuguese.

Version 1.0 consists of these files:

  • printpanel.h contains the definition of PrintPanel;

  • printpanel.cpp contains the implementation of PrintPanel;

  • mainwindow.h contains the definition of MainWindow;

  • mainwindow.cpp contains the implementation of MainWindow;

  • main.cpp contains main();

  • tt3.pro is the qmake project file.

  • tt3_pt.ts is the Portuguese message file.

Line by Line Walk-through

The PrintPanel is defined in printpanel.h.

    class PrintPanel : public QVBox
    {
        Q_OBJECT

PrintPanel is a QWidget. It needs the Q_OBJECT macro for tr() to work properly.

The implementation file is printpanel.cpp.

    /*
        QLabel *lab = new QLabel( tr( "<b>TROLL PRINT</b>" ), this );
        lab->setAlignment( AlignCenter );
    */

Some of the code is commented out in Troll Print 1.0; you will uncomment it later, for Troll Print 1.1.

        QHButtonGroup *twoSided = new QHButtonGroup( this );
        twoSided->setTitle( tr( "2-sided" ) );
        but = new QRadioButton( tr( "Enabled" ), twoSided );
        but = new QRadioButton( tr( "Disabled" ), twoSided );
        but->toggle();
        QHButtonGroup *colors = new QHButtonGroup( this );
        colors->setTitle( tr( "Colors" ) );
        but = new QRadioButton( tr( "Enabled" ), colors );
        but = new QRadioButton( tr( "Disabled" ), colors );
        but->toggle();

Notice the two occurrences of tr("Enabled") and of tr("Disabled") in PrintPanel. Since both "Enabled"s and "Disabled"s appear in the same context Qt Linguist will only display one occurrence of each and will use the same translations for the duplicates that it doesn't display. Whilst this is a useful timesaver, in some languages, such as Portuguese, the second occurrence requires a separate translation. We will see how Qt Linguist can be made to display all the occurrences for separate translation shortly.

The header file for MainWindow, mainwindow.h, contains no surprises. In the implementation, mainwindow.cpp, we have some user-visible source texts that must be marked for translation.

        setCaption( tr( "Troll Print 1.0" ) );

We must translate the window's caption.

        file->insertItem( tr( "E&xit" ), qApp, SLOT(quit()),
                          QAccel::stringToKey( tr("Ctrl+Q", "Quit") ) );
        QPopupMenu *help = new QPopupMenu( this );
        help->insertItem( tr( "&About" ), this, SLOT(about()), Key_F1 );
        help->insertItem( tr( "About &Qt" ), this, SLOT(aboutQt()) );

        menuBar()->insertItem( tr( "&File" ), file );
        menuBar()->insertSeparator();
        menuBar()->insertItem( tr( "&Help" ), help );

We also need to translate the menu items. Note that the two argument form of tr() is used for the keyboard accelerator, "Ctrl+Q", since the second argument is the only clue the translator has to indicate what function that accelerator will perform.

        QTranslator translator( 0 );
        translator.load( QString( "tt3_" ) + QTextCodec::locale(), "." );
        app.installTranslator( &translator );

The main() function in main.cpp is the same as the one in Tutorial 2. In particular it chooses a translation file based on the current locale.

Running Troll Print 1.0 in English and in Portuguese

We will use the translations in the tt3_pt.ts file that is provided.

Set the LANG environment variable to pt, and then run tt3. You should still see the English version, as shown in the Tutorial 3 Screenshot, "Troll Print 1.0", English version, above. Now run lrelease, e.g. lrelease tt3.pro, and then run the example again. Now you should see the Portuguese edition (Troll Imprimir 1.0):

Tutorial 3 Screenshot, "Troll Imprimir 1.0", (Bad) Portuguese version

Whilst the translation has appeared correctly, it is in fact wrong. In good Portuguese, the second occurrence of "Enabled" should be "Ativadas", not "Ativado" and the ending for the second translation of "Disabled" must change similarly too.

If you open tt3_pt.ts using Qt Linguist, you will see that there is just one occurrence of "Enabled" and of "Disabled" in the translation source file, even though there are two of each in the source code. This is because Qt Linguist tries to minimize the translator's work by using the same translation for duplicate source texts. In cases such as this where an identical translation is wrong, the programmer must disambiguate the duplicate occurrences. This is easily achieved by using the two argument form of tr().

We can easily determine which file must be changed because the translator's "context" is in fact the class name for the class where the texts that must be changed appears. In this case the file is printpanel.cpp, where the there are four lines to change. Add the second argument "two-sided" in the appropriate tr() calls to the first pair of radio buttons:

    but = new QRadioButton( tr("Enabled", "two-sided"), twoSided );
    but = new QRadioButton( tr("Disabled", "two-sided"), twoSided );

and add the second argument "colors" in the appropriate tr() calls for the second pair of radio buttons:

    but = new QRadioButton( tr("Enabled", "colors"), colors );
    but = new QRadioButton( tr("Disabled", "colors"), colors );

Now run lupdate and open tt3_pt.ts with Qt Linguist. You should now see two changes.

First, the translation source file now contains three "Enabled", "Disabled" pairs. The first pair is marked "(obs.)" signifying that they are obsolete. This is because these texts appeared in tr() calls that have been replaced by new calls with two arguments. The second pair has "two-sided" as their comment, and the third pair has "colors" as their comment. The comments are shown in the Source text and comments area in Qt Linguist.

Second, the translation text "Ativado" and "Desativado" have been automatically used as translations for the new "Enabled" and "Disabled" texts, again to minimize the translator's work. Of course in this case these are not correct for the second occurrence of each word, but they provide a good starting point.

Change the second "Ativado" into "Ativadas" and the second "Desativado" into "Desativadas", then save and quit. Run lrelease to obtain an up-to-date binary tt3_pt.qm file, and run Troll Print (or rather Troll Imprimir).

Tutorial 3 Screenshot, "Troll Imprimir 1.0", (Good) Portuguese version

The second argument to tr() calls, called "comments" in Qt Linguist, distinguish between identical source texts that occur in the same context (class). They are also useful in other cases to give clues to the translator, and in the case of Ctrl key accelerators are the only means of conveying the function performed by the accelerator to the translator.

An additional way of helping the translator is to provide information on how to navigate to the particular part of the application that contains the source texts they must translate. This helps them see the context in which the translation appears and also helps them to find and test the translations. This can be achieved by using a TRANSLATOR comment in the source code:

    /* TRANSLATOR MainWindow

       In this application the whole application is a MainWindow.
       Choose Help|About from the menu bar to see some text
       belonging to MainWindow.
    */

Try adding these comments to some source files, particularly to dialog classes, describing the navigation necessary to reach the dialogs. You could also add them to the example files, e.g. mainwindow.cpp and printpanel.cpp are appropriate files. Run lupdate and then start Qt Linguist and load in tt3_pt.ts. You should see the comments in the Source text and comments area as you browse through the list of source texts.

Sometimes, particularly with large programs, it can be difficult for the translator to find their translations and check that they're correct. Comments that provide good navigation information can save them time:

    /* TRANSLATOR ZClientErrorDialog

    Choose Client|Edit to reach the Client Edit dialog, then choose
    Client Specification from the drop down list at the top and pick
    client Bartel Leendert van der Waerden.  Now check the Profile
    checkbox and then click the Start Processing button.  You should
    now see a pop up window with the text "Error: Name too long!".
    This window is a ZClientErrorDialog.
    */
Troll Print 1.1

We'll now prepare release 1.1 of Troll Print. Start your favorite text editor and follow these steps:

  • Uncomment the two lines that create a QLabel with the text "<b>TROLL PRINT</b>" in printpanel.cpp.

  • Word-tidying: Replace "2-sided" by "Two-sided" in printpanel.cpp.

  • Replace "1.0" with "1.1" everywhere it occurs in mainwindow.cpp.

  • Update the copyright year to 1999-2000 in mainwindow.cpp.

(Of course the version number and copyright year would be consts or #defines in a real application.)

Once finished, run lupdate, then open tt3_pt.ts in Qt Linguist. The following items are of special interest:

  • MainWindow

    • Troll Print 1.0 - marked "(obs.)", obsolete

    • About Troll Print 1.0 - marked "(obs.)", obsolete

    • Troll Print 1.0. Copyright 1999 Macroshaft, Inc. - marked "(obs.)", obsolete

    • Troll Print 1.1 - automatically translated as "Troll Imprimir 1.1"

    • About Troll Print 1.1 - automatically translated as "Troll Imprimir 1.1"

    • Troll Print 1.1. Copyright 1999-2000 Macroshaft, Inc. - automatically translated as "Troll Imprimir 1.1. Copyright 1999-2000 Macroshaft, Inc."

  • PrintPanel

    • 2-sided - marked "(obs.)", obsolete

    • <b>TROLL PRINT</b> - unmarked, i.e. untranslated

    • Two-sided - unmarked, i.e. untranslated.

Notice that lupdate works hard behind the scenes to make revisions easier, and it's pretty smart with numbers.

Go over the translations in MainWindow and mark these as "done". Translate "<b>TROLL PRINT</b>" as "<b>TROLL IMPRIMIR</b>". When you're translating "Two-sided", press the Guess Again button to translate "Two-sided", but change the "2" into "Dois".

Save and quit, then run lrelease. The Portuguese version should look like this:

Tutorial 3 Screenshot, "Troll Imprimir 1.1", Portuguese version

Choose Ajuda|Sobre, (Help|About), to see the about box

Tutorial 3 Screenshot, About box, Portuguese version

If you choose Ajuda|Sobre Qt, (Help|About Qt), you'll get an English dialog... oops! Qt itself needs to be translated. See the document Internationalization with Qt for details.

Now set LANG=en to get the original English version:

Tutorial 3 Screenshot, "Troll Print 1.1", English version

Summary

These tutorials cover all that you need to know to prepare your Qt applications for translation.

At the beginning of a project add the translation source files to be used to the project file and add calls to lupdate and lrelease to the make file.

During the project all the programmer must do is wrap any user-visible text in tr() calls. They should also use the two argument form for Ctrl key accelerators, or when asked by the translator for the cases where the same text translates into two different forms in the same context. The programmer should also include TRANSLATION comments to help the translator navigate the application.


Qt助手和Qt参考文档

介绍

Qt参考文档介绍

1分钟学会使用Qt助手

更多关于Qt助手

Copyright © 2002 Trolltech Trademarks 译者:SKyPP
Qt 3.0.5版


介绍

本文档介绍了Qt助手，Qt助手是一个提供在线文档的工具。本文档还介绍了Qt参考文档，Qt参考文档可以通过使用Qt助手或网页浏览器方便地浏览。文档分以下几个部分：

  • Qt文档介绍

  • 1分钟学会使用Qt助手

  • 更多关于Qt助手

[Qt助手首页] [下一章：Qt参考文档介绍]

Copyright © 2002 Trolltech Trademarks 译者:SKyPP
Qt 3.0.5版


Qt参考文档介绍

Qt库文档是由开发者们自己写入.cpp文件的。文档组为保证这些文档的正确性和可用性，加以校订，并使文档的质量具有可控性。文档组还撰写了更多的文档，其中有些是描述类及类所涉及的概念，也有些是介绍类的函数和属性。

这些文档关心的是API层，而非核心层。我们尽量使API在不同版本之间得到统一兼容，但是至于核心部分，我们则会不厌其烦地加以改进，使其具备更高的性能和更多的功能。

Qt参考文档由近1,500个HTML文件组成(约2,500多个印张)。它们为Qt类提供了极其丰富的文档。由于开放者们各自有着与众不同的思考和工作方式，我们提供了多种不同归类方式的文档集方便开发者们查阅：

  • 所有的类 列出了Qt公共API中所有的类，共有几百个。

  • 主要的类 列出了您最可能频繁使用的类，篇幅比所有的类要短得多，浏览起来也更为容易。

  • 分组的类 提供了一列组，每列组指向与之对应的类，例如高级窗口部件就是如此。

  • 继承关系 提供了一列类，这些类根据Qt类的从属关系列出。

  • 所有的函数 列出了Qt类的全部函数，每个函数名下则列出了使用它们的类。有些只被一个类用到，有些则被好几个类用到。

你无论在浏览文档的哪个部分，都会发现文档是多方面前后引用的。甚至一小段代码也包含了一些有效链接，所以如果你发现代码里有类的使用，那么类名将是一个指向该类的文档的一个链接。

除一些Qt组件的类文档有详细的说明以外，还有一些概观的文档，对Qt库丰富的外观也做了不少绍；而所有这些文档都可从参考文档首页链接访问到。另外，在$QTDIR/examples中还有不少程序例子。

[上一章：介绍] [Qt助手首页] [下一章：1分钟学会使用Qt助手]

Copyright © 2002 Trolltech Trademarks 译者:SKyPP
Qt 3.0.5版


The 1 Minute Guide to using Qt Assistant

Under Windows, Qt Assistant is available as a menu option on the Qt menu. On Unix, run $QTDIR/bin/assistant from an xterm.

When you start up Qt Assistant, you will be presented with a standard main-window style application, with a menu bar and toolbar. Below these, on the left hand side is a navigation window called the Sidebar, and on the right, taking up most of the space, is the documentation window. By default, the Qt Reference Documentation's home page is shown in the documentation window.

Qt Assistant works in a similar way to a web browser. If you click underlined text (which signifies a cross-reference), the documentation window will present the relevant page. You can bookmark pages of particular interest and you can click the Previous and Next toolbar buttons to navigate within the pages you've visited.

Although Qt Assistant can be used just like a web browser to navigate through the Qt documentation set, Qt Assistant offers a powerful means of navigation that web browsers don't provide. Qt Assistant uses an intelligent algorithm to index all the pages in the documentation sets that it presents so that you can search for particular words and phrases.

To perform a search, click the Index tab on the Sidebar (or click Ctrl+I). In the 'Look For' line edit enter a word, e.g. 'homedirpath'. As you type, words are found and highlighted in a list beneath the line edit. If the highlighted text matches what you're looking for, double click it, (or press Enter) and the documentation window will display the relevant page. You rarely have to type in the whole word before Qt Assistant finds a match.

For some words there may be more than one possible page that is relevant. For example, enter 'setenabled' in the 'Look For' line edit. As you type, words are found and highlighted in the list beneath the line edit, as before. Once the highlighted text matches what you're looking for, double click it, (or press Enter). In the case of setEnabled, it is a function name which occurs in several classes, so a dialog pops up listing the possible choices. Click the choice you're interested in (or move to it using the Up and Down arrow keys and press Enter). The relevant page will display in the documentation window.

[Prev: Introduction to the Qt Reference Documentation] [Home] [Next: Qt Assistant in More Detail]


Qt Assistant in More Detail

The Sidebar

The sidebar provides three ways of navigating documentation:

  1. The Contents tab presents a tree view of the documentation sets that are available. If you click an item, its documentation will appear in the documentation window. If you double click an item or click a '+' sign to the left of an item, the item's sub-items will appear. Click a sub-item to make its page appear in the documentation window. Click a '-' sign to the left of an item to hide its sub-items.

  2. The Index tab is used to look up key words or phrases. See The 1 Minute Guide to using Qt Assistant for how to use this tab.

  3. The Bookmarks tab lists any bookmarks you've made. Double click a bookmark to make its page appear in the documentation window. The Bookmarks tab has a New Bookmark button and a Delete Bookmark button at the bottom. Click New Bookmark to bookmark the page that is showing in the documentation window. Click a bookmark in the list, then click Delete Bookmark to delete the highlighted bookmark.

If you want the documentation window to use as much space as possible, you can easily hide or show the Sidebar. If the Sidebar is showing, press Ctrl+T, Ctrl+I or Ctrl+B to hide it. If the Sidebar is hidden, press Ctrl+T to show it on the Contents tab, or press Ctrl+I to show it on the Index tab (with the focus in the 'Look For' line edit box), or press Ctrl+B to show it on the Bookmarks tab.

The Sidebar is a dock window, so you can drag it to the top, left, right or bottom of Qt Assistant's window, or you can drag it outside Qt Assistant to float it.

The Toolbar

The toolbar provides fast access to the most common actions.

  • Previous takes you to the previous page. The menu option is Go|Previous and the keyboard shortcut is Alt+Left Arrow.

  • Next takes you to the next page. The menu option is Go|Next and the keyboard shortcut is Alt+Right Arrow.

  • Home takes you to the home page (normally the home page of the Qt Reference Documentation). The menu option is Go|Home and the keyboard shortcut is Ctrl+Home.

  • Copy copies any selected text to the clipboard. The menu option is Edit|Copy and the keyboard shortcut is Ctrl+C.

  • Find in Text invokes the Find Text dialog. The menu option is Edit|Find in Text and the keyboard shortcut is Ctrl+F.

  • Print invokes the Print dialog. The menu option is File|Print and the keyboard shortcut is Ctrl+P.

  • Zoom in increases the font size. The menu option is View|Zoom in and the keyboard shortcut is Ctrl++.

  • Zoom out decreases the font size. The menu option is View|Zoom out and the keyboard shortcut is Ctrl+-.

The remaining toolbar buttons are bookmarks and will vary depending on your configuration.

The Menus

The File Menu

  • File|Print invokes the Print dialog.

  • File|Exit terminates Qt Assistant.

The Edit Menu

  • Edit|Copy copies any selected text to the clipboard.

  • Edit|Find in Text invokes the Find Text dialog.

  • Edit|Settings invokes the Settings dialog.

The View Menu

  • View|Zoom in increases the font size.

  • View|Zoom out decreases the font size.

  • View|Views|Sidebar toggles the display of the Sidebar.

  • View|Views|Toolbar toggles the display of the Toolbar.

  • View|Views|Line up lines up the toolbar buttons in the Toolbar.

The Go Menu

  • Go|Previous display the previous page.

  • Go|Next display the next page.

  • Go|home go to the home page.

This menu also has additional items; these are pre-defined bookmarks that vary depending on your configuration.

The Bookmarks Menu

  • Bookmarks|Add add the current page to the list of bookmarks.

This menu may have additional items, i.e. any bookmarks that you have already made. If you want to delete a bookmark go to the Bookmarks tab on the Sidebar.

The Dialogs

The Print Dialog

This dialog is platform-specific. It gives access to various printer options and can be used to print the current page.

The Find Text Dialog

This dialog is used to find text in the current page. Enter the text you want to find in the Find line edit. If you check the 'Whole words only' checkbox, the search will only consider whole words, i.e. if you search for 'spin' with this checkbox checked it will not match 'spinbox', but will match 'spin'. If you check the 'Case sensitive' check box then, for example, 'spin' will match 'spin' but not 'Spin'. You can search Forward or Backward from your current position in the page by clicking one of the Direction radio buttons. Click the Find button to search (or search again), and click the Close button to finish.

The Settings Dialog

This dialog is used to set your preferences for Qt Assistant. You can change the base font used throughout by choosing a new font from the Font combobox. You can choose a new fixed-width font, e.g. used to show code snippets, by choosing a new font from the 'Fixed font' combobox. You can change the color of hypertext links by clicking the 'Link color' color button. Uncheck the 'Underline links' checkbox if you don't want underlined links. Click OK to confirm your changes or click Cancel to keep the previous settings.

Qt Assistant will remember your settings between sessions, including window sizes and positions, and which page(s) you have open.


qmake用户手册

qmake的介绍

安装qmake

10分钟学会使用qmake

qmake教程

qmake概念

qmake高级概念

qmake命令参考

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmake的介绍

qmake的介绍

qmake是Trolltech公司创建的用来为不同的平台和编译器书写Makefile的工具。

手写Makefile是比较困难并且容易出错的，尤其是需要给不同的平台和编译器组合写几个Makefile。使用qmake，开发者创建一个简单的“项目”文件并且运行qmake生成适当的Makefile。qmake会注意所有的编译器和平台的依赖性，可以把开发者解放出来只关心他们的代码。Trolltech公司使用qmake作为Qt库和Qt所提供的工具的主要连编工具。

qmake也注意了Qt的特殊需求，可以自动的包含moc和uic的连编规则。

[qmake首页] [下一章：安装qmake]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


安装qmake

安装qmake

当Qt被连编的时候，默认情况下qmake也会被连编。

这一部分解释如何手工连编qmake。如果你已经有了qmake，可以跳过这里，请看10分钟学会使用qmake。

手动安装qmake

在手工连编Qt之前，下面这些环境变量必须被设置：

  • QMAKESPEC
    这个必须设置为你所使用的系统的平台和编译器的组合。
    举例来说，加入你使用的是Windows和Microsoft Visual Studio，你应该把环境变量设置为win32-msvc。如果你使用的是Solaris和g++，你应该把环境变量设置为solaris-g++。

    当你在设置QMAKESPEC时，可以从下面的可能的环境变量列表中进行选择：

    aix-64 hpux-cc irix-032 netbsd-g++ solaris-cc unixware7-g++ aix-g++ hpux-g++ linux-cxx openbsd-g++ solaris-g++ win32-borland aix-xlc hpux-n64 linux-g++ openunix-cc sunos-g++ win32-g++ bsdi-g++ hpux-o64 linux-icc qnx-g++ tru64-cxx win32-msvc dgux-g++ hurd-g++ linux-kcc reliant-64 tru64-g++ win32-watc freebsd-g++ irix-64 macx-pbuilder reliant-cds ultrix-g++ win32-visa hpux-acc irix-g++ macx-g++ sco-g++ unixware-g hpux-acc irix-n32 solaris-64 unixware7-cc

    envvar是下面之一时，环境变量应该被设置到qws/envvar：

    linux-arm-g++ linux-generic-g++ linux-mips-g++ linux-x86-g++ linux-freebsd-g++ linux-ipaq-g++ linux-solaris-g++ qnx-rtp-g++

  • QTDIR
    这个必须设置到Qt被（或者将被）安装到的地方。比如，c:\qt和/local/qt。

一旦环境变量被设置到qmake目录，$QTDIR/qmake，比如C:\qt\qmake，现在根据你的编译器运行make或者nmake。

当编译完成时，qmake已经可以使用了。

[上一章：qmake的介绍] [qmake首页] [下一章：10分钟学会使用qmake]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


10分钟学会使用qmake

创建一个项目文件

qmake使用储存在项目（.pro）文件中的信息来决定Makefile文件中该生成什么。

一个基本的项目文件包含关于应用程序的信息，比如，编译应用程序需要哪些文件，并且使用哪些配置设置。

这里是一个简单的示例项目文件：

    SOURCES = hello.cpp
    HEADERS = hello.h
    CONFIG += qt warn_on release

我们将会提供一行一行的简要解释，具体细节将会在手册的后面的部分解释。

    SOURCES = hello.cpp

这一行指定了实现应用程序的源程序文件。在这个例子中，恰好只有一个文件，hello.cpp。大部分应用程序需要多个文件，这种情况下可以把文件列在一行中，以空格分隔，就像这样：

    SOURCES = hello.cpp main.cpp

另一种方式，每一个文件可以被列在一个分开的行里面，通过反斜线另起一行，就像这样：

    SOURCES = hello.cpp \
        main.cpp

一个更冗长的方法是单独地列出每一个文件，就像这样：

    SOURCES += hello.cpp
    SOURCES += main.cpp

这种方法中使用“+=”比“=”更安全，因为它只是向已有的列表中添加新的文件，而不是替换整个列表。

HEADERS这一行中通常用来指定为这个应用程序创建的头文件，举例来说：

    HEADERS += hello.h

列出源文件的任何一个方法对头文件也都适用。

CONFIG这一行是用来告诉qmake关于应用程序的配置信息。

    CONFIG += qt warn_on release

在这里使用“+=”，是因为我们添加我们的配置选项到任何一个已经存在中。这样做比使用“=”那样替换已经指定的所有选项是更安全的。

CONFIG一行中的qt部分告诉qmake这个应用程序是使用Qt来连编的。这也就是说qmake在连接和为编译添加所需的包含路径的时候会考虑到Qt库的。

CONFIG一行中的warn_on部分告诉qmake要把编译器设置为输出警告信息的。

CONFIG一行中的release部分告诉qmake应用程序必须被连编为一个发布的应用程序。在开发过程中，程序员也可以使用debug来替换release，稍后会讨论这里的。

项目文件就是纯文本（比如，可以使用像记事本、vim和xemacs这些编辑器）并且必须存为“.pro”扩展名。应用程序的执行文件的名称必须和项目文件的名称一样，但是扩展名是跟着平台而改变的。举例来说，一个叫做“hello.pro”的项目文件将会在Windows下生成“hello.exe”，而在Unix下生成“hello”。

生成Makefile

当你已经创建好你的项目文件，生成Makefile就很容易了，你所要做的就是先到你所生成的项目文件那里然后输入：

Makefile可以像这样由“.pro”文件生成：

    qmake -o Makefile hello.pro

对于Visual Studio的用户，qmake也可以生成“.dsp”文件，例如：

    qmake -t vcapp -o hello.dsp hello.pro

[上一章：安装qmake] [qmake首页] [下一章：qmake教程]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmake教程

qmake教程介绍

这个教程可以教会你如何使用qmake。我们建议你看完这个教程之后读一下qmake手册。

开始很简单

让我们假设你已经完成了你的应用程序的一个基本实现，并且你已经创建了下述文件：

  • hello.cpp

  • hello.h

  • main.cpp

你可以在qt/qmake/example中发现这些文件。你对这个应用程序的配置仅仅知道的另一件事是它是用Qt写的。首先，使用你所喜欢的纯文本编辑器，在qt/qmake/tutorial中创建一个叫做hello.pro的文件。你所要做的第一件事是添加一些行来告诉qmake关于你所开发的项目中的源文件和头文件这一部分。

我们先把源文件添加到项目文件中。为了做到这点，你需要使用SOURCES变量。只要用SOURCES +=来开始一行，并且把hello.cpp放到它后面。你需要写成这样：

    SOURCES += hello.cpp

我们对项目中的每一个源文件都这样做，直到结束：

    SOURCES += hello.cpp
    SOURCES += main.cpp

如果你喜欢使用像Make一样风格的语法，你也可以写成这样，一行写一个源文件，并用反斜线结尾，然后再起新的一行：

    SOURCES = hello.cpp \
          main.cpp

现在源文件已经被列到项目文件中了，头文件也必须添加。添加的方式和源文件一样，除了变量名是HEADERS。

当你做完这些时，你的项目文件就像现在这样：

    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp

目标名称是自动设置的，它被设置为和项目文件一样的名称，但是为了适合平台所需要的后缀。举例来说，加入项目文件叫做“hello.pro”，在Windows上的目标名称应该是“hello.exe”，在Unix上应该是“hello”。如果你想设置一个不同的名字，你可以在项目文件中设置它：

    TARGET = helloworld

最后一步是设置CONFIG变量。因为这是一个Qt应用程序，我们需要把“qt”放到CONFIG这一行中，这样qmake才会在连接的时候添加相关的库，并且保证moc和uic的连编行也被包含到Makefile中。

最终完成的项目文件应该是这样的：

    CONFIG += qt
    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp

你现在可以使用qmake来为你的应用程序生成Makefile。在你的应用程序目录中，在命令行下输入：

    qmake -o Makefile hello.pro

然后根据你所使用的编译器输入make或者nmake。

使应用程序可以调试

应用程序的发布版本不包含任何调试符号或者其它调试信息。在开发过程中，生成一个含有相关信息的应用程序的调试版本是很有用处的。通过在项目文件的CONFIG变量中添加“debug”就可以很简单地实现。

例如：

    CONFIG += qt debug
    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp

像前面一样使用qmake来生成一个Makefile并且你就能够调试你的应用程序了。

添加特定平台的源文件

在编了几个小时的程序之后，你也许开始为你的应用程序编写与平台相关的部分，并且决定根据平台的不同编写不同的代码。所以现在你有两个信文件要包含到你的项目文件中－hello_win.cpp和hello_x11.cpp。我们不能仅仅把这两个文件放到SOURCES变量中，因为那样的话会把这两个文件都加到Makefile中。所以我们在这里需要做的是根据qmake所运行的平台来使用相应的作用域来进行处理。

为Windows平台添加的依赖平台的文件的简单的作用域看起来就像这样：

    win32 {
    SOURCES += hello_win.cpp
    }

所以如果qmake运行在Windows上的时候，它就会把hello_win.cpp添加到源文件列表中。如果qmake运行在其它平台上的时候，它会很简单地把这部分忽略。现在接下来我们要做的就是添加一个X11依赖文件的作用域。

当你做完了这部分，你的项目文件应该和这样差不多：

    CONFIG += qt debug
    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp
    win32 {
    SOURCES += hello_win.cpp
    }
    x11 {
    SOURCES += hello_x11.cpp
    }

像前面一样使用qmake来生成Makefile。

如果一个文件不存在，停止qmake

如果某一个文件不存在的时候，你也许不想生成一个Makefile。我们可以通过使用exists()函数来检查一个文件是否存在。我们可以通过使用error()函数把正在运行的qmake停下来。这和作用域的工作方式一样。只要很简单地用这个函数来替换作用域条件。对main.cpp文件的检查就像这样：

    !exists( main.cpp ) {
    error( "No main.cpp file found" )
    }

“!”用来否定这个测试，比如，如果文件存在，exists( main.cpp )是真，如果文件不存在，!exists( main.cpp )是真。

    CONFIG += qt debug
    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp
    win32 {
    SOURCES += hello_win.cpp
    }
    x11 {
    SOURCES += hello_x11.cpp
    }
    !exists( main.cpp ) {
    error( "No main.cpp file found" )
    }

像前面一样使用qmake来生成Makefile。如果你临时改变main.cpp的名称，你会看到信息，并且qmake会停止处理。

检查多于一个的条件

假设你使用Windows并且当你在命令行运行你的应用程序的时候你想能够看到qDebug()语句。除非你在连编你的程序的时候使用console设置，你不会看到输出。我们可以很容易地把console添加到CONFIG行中，这样在Windows下，Makefile就会有这个设置。但是如果告诉你我们只是想在当我们的应用程序运行在Windows下并且当debug已经在CONFIG行中的时候，添加console。这需要两个嵌套的作用域；只要生成一个作用域，然后在它里面再生成另一个。把设置放在最里面的作用域里，就像这样：

    win32 {
    debug {
        CONFIG += console
    }
    }

嵌套的作用域可以使用冒号连接起来，所以最终的项目文件看起来像这样：

    CONFIG += qt debug
    HEADERS += hello.h
    SOURCES += hello.cpp
    SOURCES += main.cpp
    win32 {
    SOURCES += hello_win.cpp
    }
    x11 {
    SOURCES += hello_x11.cpp
    }
    !exists( main.cpp ) {
    error( "No main.cpp file found" )
    }
    win32:debug {
    CONFIG += console
    }

就这些了！你现在已经完成了qmake的教程，并且已经准备好为你的开发项目写项目文件了。

[上一章：10分钟学会使用qmake] [qmake首页] [下一章：qmake概念]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmake概念

介绍qmake

qmake是用来为不同的平台的开发项目创建makefile的Trolltech开发一个易于使用的工具。qmake简化了makefile的生成，所以为了创建一个makefile只需要一个只有几行信息的文件。qmake可以供任何一个软件项目使用，而不用管它是不是用Qt写的，尽管它包含了为支持Qt开发所拥有的额外的特征。

qmake基于一个项目文件这样的信息来生成makefile。项目文件可以由开发者生成。项目文件通常很简单，但是如果需要它是非常完善的。不用修改项目文件，qmake也可以为为Microsoft Visual Studio生成项目。

qmake的概念

QMAKESPEC环境变量

举例来说，如果你在Windows下使用Microsoft Visual Studio，然后你需要把QMAKESPEC环境变量设置为win32-msvc。如果你在Solaris上使用gcc，你需要把QMAKESPEC环境变量设置为solaris-g++。

在qt/mkspecs中的每一个目录里面，都有一个包含了平台和编译器特定信息的qmake.conf文件。这些设置适用于你要使用qmake的任何项目，请不要修改它，除非你是一个专家。例如，假如你所有的应用程序都必须和一个特定的库连接，你可以把这个信息添加到相应的qmake.conf文件中。

项目(.pro)文件

一个项目文件是用来告诉qmake关于为这个应用程序创建makefile所需要的细节。例如，一个源文件和头文件的列表、任何应用程序特定配置、例如一个必需要连接的额外库、或者一个额外的包含路径，都应该放到项目文件中。

“#”注释

你可以为项目文件添加注释。注释由“#”符号开始，一直到这一行的结束。

模板

模板变量告诉qmake为这个应用程序生成哪种makefile。下面是可供使用的选择：

  • app - 建立一个应用程序的makefile。这是默认值，所以如果模板没有被指定，这个将被使用。

  • lib - 建立一个库的makefile。

  • vcapp - 建立一个应用程序的Visual Studio项目文件。

  • vclib - 建立一个库的Visual Studio项目文件。

  • subdirs - 这是一个特殊的模板，它可以创建一个能够进入特定目录并且为一个项目文件生成makefile并且为它调用make的makefile。

“app”模板

“app”模板告诉qmake为建立一个应用程序生成一个makefile。当使用这个模板时，下面这些qmake系统变量是被承认的。你应该在你的.pro文件中使用它们来为你的应用程序指定特定信息。

  • HEADERS - 应用程序中的所有头文件的列表。

  • SOURCES - 应用程序中的所有源文件的列表。

  • FORMS - 应用程序中的所有.ui文件（由Qt设计器生成）的列表。

  • LEXSOURCES - 应用程序中的所有lex源文件的列表。

  • YACCSOURCES - 应用程序中的所有yacc源文件的列表。

  • TARGET - 可执行应用程序的名称。默认值为项目文件的名称。（如果需要扩展名，会被自动加上。）

  • DESTDIR - 放置可执行程序目标的目录。

  • DEFINES - 应用程序所需的额外的预处理程序定义的列表。

  • INCLUDEPATH - 应用程序所需的额外的包含路径的列表。

  • DEPENDPATH - 应用程序所依赖的搜索路径。

  • VPATH - 寻找补充文件的搜索路径。

  • DEF_FILE - 只有Windows需要：应用程序所要连接的.def文件。

  • RC_FILE - 只有Windows需要：应用程序的资源文件。

  • RES_FILE - 只有Windows需要：应用程序所要连接的资源文件。

你只需要使用那些你已经有值的系统变量，例如，如果你不需要任何额外的INCLUDEPATH，那么你就不需要指定它，qmake会为所需的提供默认值。例如，一个实例项目文件也许就像这样：

TEMPLATE = app
DESTDIR  = c:\helloapp
HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp
DEFINES += QT_DLL
CONFIG  += qt warn_on release

如果条目是单值的，比如template或者目的目录，我们是用“=”，但如果是多值条目，我们使用“+=”来为这个类型添加现有的条目。使用“=”会用新值替换原有的值，例如，如果我们写了DEFINES=QT_DLL，其它所有的定义都将被删除。

“lib”模板

“lib”模板告诉qmake为建立一个库而生成makefile。当使用这个模板时，除了“app”模板中提到系统变量，还有一个VERSION是被支持的。你需要在为库指定特定信息的.pro文件中使用它们。

  • VERSION - 目标库的版本号，比如，2.3.1。

“subdirs”模板

“subdirs”模板告诉qmake生成一个makefile，它可以进入到特定子目录并为这个目录中的项目文件生成makefile并且为它调用make。

在这个模板中只有一个系统变量SUBDIRS可以被识别。这个变量中包含了所要处理的含有项目文件的子目录的列表。这个项目文件的名称是和子目录同名的，这样qmake就可以发现它。例如，如果子目里是“myapp”，那么在这个目录中的项目文件应该被叫做myapp.pro。

CONFIG变量

配置变量指定了编译器所要使用的选项和所需要被连接的库。配置变量中可以添加任何东西，但只有下面这些选项可以被qmake识别。

下面这些选项控制着使用哪些编译器标志：

  • release - 应用程序将以release模式连编。如果“debug”被指定，它将被忽略。

  • debug - 应用程序将以debug模式连编。

  • warn_on - 编译器会输出尽可能多的警告信息。如果“warn_off”被指定，它将被忽略。

  • warn_off - 编译器会输出尽可能少的警告信息。

下面这些选项定义了所要连编的库/应用程序的类型：

  • qt - 应用程序是一个Qt应用程序，并且Qt库将会被连接。

  • thread - 应用程序是一个多线程应用程序。

  • x11 - 应用程序是一个X11应用程序或库。

  • windows - 只用于“app”模板：应用程序是一个Windows下的窗口应用程序。

  • console - 只用于“app”模板：应用程序是一个Windows下的控制台应用程序。

  • dll - 只用于“lib”模板：库是一个共享库（dll）。

  • staticlib - 只用于“lib”模板：库是一个静态库。

  • plugin - 只用于“lib”模板：库是一个插件，这将会使dll选项生效。

例如，如果你的应用程序使用Qt库，并且你想把它连编为一个可调试的多线程的应用程序，你的项目文件应该会有下面这行：

    CONFIG += qt thread debug

注意，你必须使用“+=”，不要使用“=”，否则qmake就不能正确使用连编Qt的设置了，比如没法获得所编译的Qt库的类型了。

[上一章：qmake教程] [qmake首页] [下一章：qmake高级概念]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmake高级概念

qmake高级概念

迄今为止，我们见到的qmake项目文件都非常简单，仅仅是一些name = value和name += value的列表行。qmake提供了很多更强大的功能，比如你可以使用一个简单的项目文件来为多个平台生成makefile。

操作符

到目前为止，你已经看到在项目文件中使用的=操作符和+=操作符。这里能够提供更多的可供使用的操作符，但是其中的一些需要谨慎地使用，因为它们也许会比你期待的改变的更多。

“=”操作符

这个操作符简单分配一个值给一个变量。使用方法如下：

    TARGET = myapp

这将会设置TARGET变量为myapp。这将会删除原来对TARGET的任何设置。

“+=”操作符

这个操作符将会向一个变量的值的列表中添加一个值。使用方法如下：

    DEFINES += QT_DLL

这将会把QT_DLL添加到被放到makefile中的预处理定义的列表中。

“-=”操作符

这个操作符将会从一个变量的值的列表中移去一个值。使用方法如下：

    DEFINES -= QT_DLL

这将会从被放到makefile中的预处理定义的列表中移去QT_DLL。

“*=”操作符

这个操作符仅仅在一个值不存在于一个变量的值的列表中的时候，把它添加进去。使用方法如下：

    DEFINES *= QT_DLL

只用在QT_DLL没有被定义在预处理定义的列表中时，它才会被添加进去。

“~=”操作符

这个操作符将会替换任何与指定的值的正则表达式匹配的任何值。使用方法如下：

    DEFINES ~= s/QT_[DT].+/QT

这将会用QT来替代任何以QT_D或QT_T开头的变量中的QT_D或QT_T。

作用域

作用域和“if”语句很相似，如果某个条件为真，作用域中的设置就会被处理。作用域使用方法如下：

    win32 {
        DEFINES += QT_DLL
    }

上面的代码的作用是，如果在Windows平台上使用qmake，QT_DLL定义就会被添加到makefile中。如果在Windows平台以外的平台上使用qmake，这个定义就会被忽略。你也可以使用qmake执行一个单行的条件/任务，就像这样：

    win32:DEFINES += QT_DLL

比如，假设我们想在除了Windows平台意外的所有平台处理些什么。我们想这样使用作用域来达到这种否定效果：

    !win32 {
        DEFINES += QT_DLL
    }

CONFIG行中的任何条目也都是一个作用域。比如，你这样写：

    CONFIG += warn_on

你将会得到一个称作“warn_on”的作用域。这样将会使在不丢失特定条件下可能所需的所有自定义设置的条件下，很容易地修改项目中的配置。因为你可能把你自己的值放到CONFIG行中，这将会为你的makefile而提供给你一个非常强大的配置工具。比如：

    CONFIG += qt warn_on debug
    debug {
        TARGET = myappdebug
    }
    release {
        TARGET = myapp
    }

在上面的代码中，两个作用域被创建，它们依赖于CONFIG行中设置的是什么。在这个例子中，debug在CONFIG行中，所以TARGET变量被设置为myappdebug。如果release在CONFIG行中，那么TARGET变量将会被设置为myapp。

当然也可以在处理一些设置之前检查两个事物。例如，如果你想检查平台是否是Windows并且线程设置是否被设定，你可以这样写：

    win32 {
        thread {
            DEFINES += QT_THREAD_SUPPORT
        }
    }

为了避免写出许多嵌套作用域，你可以这样使用冒号来嵌套作用域：

    win32:thread {
        DEFINES += QT_THREAD_SUPPORT
    }

一旦一个测试被执行，你也许也要做else/elseif操作。这种情况下，你可以很容易地写出复杂的测试。这需要使用特殊的“else”作用域，它可以和其它作用域进行组合（也可以向上面一样使用冒号），比如：

    win32:thread {
        DEFINES += QT_THREAD_SUPPORT
    } else:debug {
        DEFINES += QT_NOTHREAD_DEBUG
    } else {
        warning("Unknown configuration")
    }

变量

到目前为止我们遇到的变量都是系统变量，比如DEFINES、SOURCES和HEADERS。你也可以为你自己创建自己的变量，这样你就可以在作用域中使用它们了。创建自己的变量很容易，只要命名它并且分配一些东西给它。比如：

    MY_VARIABLE = value

现在你对你自己的变量做什么是没有限制的，同样地，qmake将会忽略它们，除非需要在一个作用域中考虑它们。

你也可以通过在其它任何一个变量的变量名前加$$来把这个变量的值分配给当前的变量。例如：

    MY_DEFINES = $$DEFINES

现在MY_DEFINES变量包含了项目文件在这点时DEFINES变量的值。这也和下面的语句一样：

    MY_DEFINES = $${DEFINES}

第二种方法允许你把一个变量和其它变量连接起来，而不用使用空格。qmake将允许一个变量包含任何东西（包括$(VALUE)，可以直接在makefile中直接放置，并且允许它适当地扩张，通常是一个环境变量）。无论如何，如果你需要立即设置一个环境变量，然后你就可以使用$$()方法。比如：

    MY_DEFINES = $$(ENV_DEFINES)

这将会设置MY_DEFINES为环境变量ENV_DEFINES传递给.pro文件地值。另外你可以在替换的变量里调用内置函数。这些函数（不会和下一节中列举的测试函数混淆）列出如下：

join( variablename, glue, before, after )

这将会在variablename的各个值中间加入glue。如果这个变量的值为非空，那么就会在值的前面加一个前缀before和一个后缀after。只有variablename是必须的字段，其它默认情况下为空串。如果你需要在glue、before或者after中使用空格的话，你必须提供它们。

member( variablename, position )

这将会放置variablename的列表中的position位置的值。如果variablename不够长，这将会返回一个空串。variablename是唯一必须的字段，如果没有指定位置，则默认为列表中的第一个值。

find( variablename, substr )

这将会放置variablename中所有匹配substr的值。substr也可以是正则表达式，而因此将被匹配。

    MY_VAR = one two three four
    MY_VAR2 = $$join(MY_VAR, " -L", -L) -Lfive
    MY_VAR3 = $$member(MY_VAR, 2) $$find(MY_VAR, t.*)

MY_VAR2将会包含“-Lone -Ltwo -Lthree -Lfour -Lfive”，并且MYVAR3将会包含“three two three”。

system( program_and_args )

这将会返回程序执行在标准输出/标准错误输出的内容，并且正像平时所期待地分析它。比如你可以使用这个来询问有关平台的信息。

    UNAME = $$system(uname -s)
    contains( UNAME, [lL]inux ):message( This looks like Linux ($$UNAME) to me )

测试函数

qmake提供了可以简单执行，但强大测试的内置函数。这些测试也可以用在作用域中（就像上面一样），在一些情况下，忽略它的测试值，它自己使用测试函数是很有用的。

contains( variablename, value )

如果value存在于一个被叫做variablename的变量的值的列表中，那么这个作用域中的设置将会被处理。例如：

    contains( CONFIG, thread ) {
        DEFINES += QT_THREAD_SUPPORT
    }

如果thread存在于CONFIG变量的值的列表中时，那么QT_THREAD_SUPPORT将会被加入到DEFINES变量的值的列表中。

count( variablename, number )

如果number与一个被叫做variablename的变量的值的数量一致，那么这个作用域中的设置将会被处理。例如：

    count( DEFINES, 5 ) {
        CONFIG += debug
    }

error( string )

这个函数输出所给定的字符串，然后会使qmake退出。例如：

    error( "An error has occured" )

文本“An error has occured”将会被显示在控制台上并且qmake将会退出。

exists( filename )

如果指定文件存在，那么这个作用域中的设置将会被处理。例如：

    exists( /local/qt/qmake/main.cpp ) {
        SOURCES += main.cpp
    }

如果/local/qt/qmake/main.cpp存在，那么main.cpp将会被添加到源文件列表中。

注意可以不用考虑平台使用“/”作为目录的分隔符。

include( filename )

项目文件在这一点时包含这个文件名的内容，所以指定文件中的任何设置都将会被处理。例如：

    include( myotherapp.pro )

myotherapp.pro项目文件中的任何设置现在都会被处理。

isEmpty( variablename )

这和使用count( variablename, 0 )是一样的。如果叫做variablename的变量没有任何元素，那么这个作用域中的设置将会被处理。例如：

    isEmpty( CONFIG ) {
        CONFIG += qt warn_on debug
    }

message( string )

这个函数只是简单地在控制台上输出消息。

    message( "This is a message" )

文本“This is a message”被输出到控制台上并且对于项目文件的处理将会继续进行。

system( command )

特定指令被执行并且如果它返回一个1的退出值，那么这个作用域中的设置将会被处理。例如：

    system( ls /bin ) {
        SOURCES += bin/main.cpp
        HEADERS += bin/main.h
    }

所以如果命令ls /bin返回1，那么bin/main.cpp将被添加到源文件列表中并且bin/main.h将被添加到头文件列表中。

infile( filename, var, val )

如果filename文件（当它被qmake自己解析时）包含一个值为val的变量var，那么这个函数将会返回成功。你也可以不传递第三个参数（val），这时函数将只测试文件中是否分配有这样一个变量var。

[上一章：qmake概念] [qmake首页] [下一章：qmake命令参考]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmake Command Reference

qmake Command Reference

  • About This Reference

  • Command Line Options

  • System Variables

  • Functions

  • Environment Variables and Configuration

About This Reference

This reference is a detailed index of all command line options, configurations and internal variables used by the cross-platform makefile generation utility qmake.

In addition to the variables and functions described in the following sections, qmake project files may also include comments. Comments begin with the '#' symbol and run to the end of the line.

Command Line Options

Syntax

qmake [options] files

Options

The following options can be specified on the command line to qmake:

  • -o file
    qmake output will be directed to file. if this argument is not specified, then qmake will try to guess a suitable name. If '-' is specified, output is directed to stdout.

  • -unix
    qmake will run in unix mode. In this mode, Unix file naming and path conventions will be used, additionally testing for unix (as a scope) will succeed. This is the default mode on all Unices.

  • -macx
    qmake will run in Mac OS X mode. In this mode, Unix file naming and path conventions will be used, additionally testing for macx (as a scope) will succeed. This is the default mode on Mac OS X.

  • -win32
    qmake will run in win32 mode. In this mode, Windows file naming and path conventions will be used, additionally testing for win32 (as a scope) will succeed. This is the default mode on Windows.

  • -d
    qmake will output (hopefully) useful debugging information.

  • -t tmpl
    qmake will override any set TEMPLATE variables with tmpl.

  • -help
    qmake will go over these features and give some useful help.

There are also warning options that can help to find problems in your project file:

  • -Wall
    With this qmake will turn on all known warnings.

  • -Wnone
    No warning information will be generated by qmake.

  • -Wparser
    qmake will only generate parser warnings, this will alert you to common pitfalls, and potential problems in the parsing of your .pro files.

  • -Wlogic
    Again qmake will warn of common pitfalls, and potential problems. This can include (but not limited to) checking if a file is placed into a list of files multiple times, if a file cannot be found, etc.

qmake supports two different modes of operation. The first mode, which is the default is makefile generation. In this mode, qmake will take a .pro file and turn it into a makefile. Creating makefiles is covered by this reference guide, there is another mode which generates .pro files.

To toggle between these modes you must specify in the first argument what mode you want to use. If no mode is specified, qmake will assume you want makefile mode. The available modes are:

  • -makefile
    qmake output will be a makefile (Makefile mode).

  • -project
    qmake output will be a project file (Project file mode).

Makefile Mode

In Makefile mode qmake will generate a makefile. Additionally you may supply the following arguments in this mode:

  • -after
    qmake will process assignments given on the commandline after the specified files.

  • -nocache
    qmake will ignore the .qmake.cache file.

  • -nodepend
    qmake will not generate any dependency information.

  • -cache file
    qmake will use file as the cache file, ignoring any other .qmake.cache file found

  • -spec spec
    qmake will use spec as a path to platform-compiler information and QMAKESPEC will be ignored.

The files argument can be a list of one or more project files, separated by spaces. You may also pass qmake assignments on the command line here and they will be processed before all files specified, for example:

qmake -makefile -unix -o Makefile "CONFIG+=test" test.pro

If however you are certain you want your variables processed after the the files specified, then you may pass the -after argument. When this is specified all assignments on the commandline after the -after option will be postponed until after the specified files are parsed.

This will generate a Makefile, from test.pro with Unix pathnames. However many of these arguments aren't necessary as they are the default. Therefore the line can be simplified on Unix to:

qmake "CONFIG+=test" test.pro

Projectfile Mode

In Projectfile mode qmake will generate a project file. Additionally, you may supply the following arguments in this mode:

  • -r
    qmake will look through supplied directories recursively

  • -nopwd
    qmake will not look in your current working directory for source code and only use the specified files

The files argument can be a list of files or directories. If a directory is specified, then it will be included in the DEPENDPATH variable and relevant code from there will be included in the generated project file, if a file is given it will go into the correct variable depending on extension (i.e. .ui files go into FORMS, .cpp files go into SOURCES, etc). Here too you may pass assignments on the commandline, when doing so these assignments will be placed last in the generated .pro file.

System Variables

  • Frequently Used System Variables

  • Rarely Used System Variables

Frequently Used System Variables

The following variables are recognized by qmake and are used most frequently when creating project files.

CONFIG

The CONFIG variable specifies project configuration and compiler options. The values will be recognized internally by qmake and have special meaning. They are as follows.

These CONFIG values control compilation flags:

  • release - Compile with optimization enabled, ignored if "debug" is specified

  • debug - Compile with debug options enabled

  • warn_on - The compiler should emit more warnings than normally, ignored if "warn_off" is specified

  • warn_off - The compiler should only emit severe warnings.

These options define the application/library type:

  • qt - The target is a Qt application/library and requires the Qt header files/library. The proper include and library paths for the Qt library will automatically be added to the project.

  • opengl - The target requires the OpenGL (or Mesa) headers/libraries. The proper include and library paths for these libraries will automatically be added to the project.

  • thread - The target is a multi-threaded application or library. The proper defines and compiler flags will automatically be added to the project.

  • x11 - The target is a X11 application or library. The proper include paths and libraries will automatically be added to the project.

  • windows - The target is a Win32 window application (app only). The proper include paths,compiler flags and libraries will automatically be added to the project.

  • console - The target is a Win32 console application (app only). The proper include paths, compiler flags and libraries will automatically be added to the project.

  • dll - The target is a shared object/DLL.The proper include paths, compiler flags and libraries will automatically be added to the project.

  • staticlib - The target is a static library (lib only). The proper compiler flags will automatically be added to the project.

  • plugin - The target is a plugin (lib only). This enables dll as well.

The CONFIG variable will also be checked when resolving scopes. You may assign anything to this variable.

For example:

CONFIG += qt console newstuff
...
newstuff {
    SOURCES += new.cpp
    HEADERS += new.h
}
DEFINES

qmake adds the values of this variable as compiler C preprocessor macros (-D option).

For example:

DEFINES += USE_MY_STUFF QT_DLL
DEF_FILE

This is only used on Windows when using the 'app' template.

Specifies a .def file to be included in the project.

DESTDIR

Specifies where to put the target file.

For example:

  DESTDIR = ../../lib
DLLDESTDIR

Specifies where to copy the target dll.

HEADERS

Defines the header files for the project.

qmake will generate dependency information (unless -nodepend is specified on the command line) for the specified headers. qmake will also automatically detect if moc is required by the classes in these headers, and add the appropriate dependencies and files to the project for generating and linking the moc files.

For example:

HEADERS	= myclass.h \
      login.h \
      mainwindow.h

See also SOURCES.

INCLUDEPATH

This variable specifies the #include directories which should be searched when compiling the project. Use ';' or a space as the directory separator.

For example:

  INCLUDEPATH = c:\msdev\include d:\stl\include
FORMS

This variable specifies the .ui files (see Qt Designer) to be processed through uic before compiling. All dependencies, headers and source files required to build these .ui files will automatically be added to the project.

For example:

FORMS = mydialog.ui \
    mywidget.ui \
        myconfig.ui
LEXSOURCES

This variable contains a list of lex source files. All dependencies, headers and source files will automatically be added to the project for building these lex files.

For example:

LEXSOURCES = lexer.l
LIBS

This variable contains a list of libraries to be linked into the project. If you are more comfortable with the Unix convension of -L/-l flags you are free to use them in a cross-platform manner and qmake will do the correct thing with these libraries on Windows (namely this means passing the full path of the library to the linker). The only limitation to this is the library must exist, for qmake to find which directory a -l lib lives in.

For example:

unix:LIBS += -lmath -L/usr/local/lib
win32:LIBS += c:\mylibs\math.lib
MOC_DIR

This variable specifies the directory where all intermediate moc files should be placed.

For example:

unix:MOC_DIR = ../myproject/tmp
win32:MOC_DIR = c:\myproject\tmp
OBJECTS_DIR

This variable specifies the directory where all intermediate objects should be placed.

For example:

unix:OBJECTS_DIR = ../myproject/tmp
win32:OBJECTS__DIR = c:\myproject\tmp
UI_DIR

This variable specifies the directory where all intermediate files from uic should be placed. This variable overrides both UI_SOURCES_DIR and UI_HEADERS_DIR.

For example:

unix:UI_DIR = ../myproject/ui
win32:UI_DIR = c:\myproject\ui
UI_HEADERS_DIR

This variable specifies the directory where all declaration files (as generated by uic) should be placed.

For example:

unix:UI_HEADERS_DIR = ../myproject/ui/include
win32:UI_HEADERS_DIR = c:\myproject\ui\include
UI_SOURCES_DIR

This variable specifies the directory where all implementation files (as generated by uic) should be placed.

For example:

unix:UI_SOURCES_DIR = ../myproject/ui/src
win32:UI_SOURCES_DIR = c:\myproject\ui\src
REQUIRES

This is a special variable processed by qmake. If the contents of this variable do not appear in CONFIG by the time this variable is assigned, then a minimal makefile will be generated that states what dependencies (the values assigned to REQUIRES) are missing.

This is mainly used in Qt's build system for building the examples.

SOURCES

This variable contains the name of all source files in the project.

For example:

SOURCES	= myclass.cpp \
      login.cpp \
      mainwindow.cpp

See also HEADERS

SUBDIRS

This variable, when used with the 'subdir' TEMPLATE contains the names of all subdirectories to look for a project file.

For example:

SUBDIRS = kernel \
      tools
TARGET

This specifies the name of the target file.

For example:

TEMPLATE = app
TARGET = myapp
SOURCES = main.cpp

The project file above would produce an executable named 'myapp' on unix and 'myapp.exe' on windows.

TEMPLATE

This variable contains the name of the template to use when generating the project. The allowed values are:

  • app - Creates a makefile for building applications (the default)

  • lib - Creates a makefile for building libraries

  • subdirs - Creates a makefile for building targets in subdirectories

  • vcapp - win32 only Creates an application project file

  • vclib - win32 only Creates a library project file

For example:

TEMPLATE = lib
SOURCES = main.cpp
TARGET = mylib
VERSION

This variable contains the version number of the library if the 'lib' TEMPLATE is specified.

For example:

VERSION = 1.2.3
DISTFILES

This variable contains a list of files to be included in the dist target. This feature is supported by UnixMake specs only.

For example:

DISTFILES += ../program.txt
YACCSOURCES

This variable contains a list of yacc source files to be included in the project. All dependencies, headers and source files will automatically be included in the project.

For example:

YACCSOURCES = moc.y

Rarely Used System Variables

The following variables are also recognized by qmake but are either internal or very rarely used.

DESTDIR_TARGET

This variable is set internally by qmake, which is basically the DESTDIR variable with the TARGET variable appened at the end. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

DSP_TEMPLATE

This variable is set internally by qmake, which specifies where the dsp template file for basing generated dsp files is stored. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

LEXIMPLS

This variable contains a list of lex implementation files. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

LEXOBJECTS

This variable contains the names of intermediate lex object files.The value of this variable is typically handled by qmake and rarely needs to be modified.

MAKEFILE

This variable specifies the name of the makefile which qmake should use when outputting the dependency information for building a project. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

MAKEFILE_GENERATOR

This variable contains the name of the makefile generator to use when generating a makefile. The value of this variable is typically handled internally by qmake and rarely needs to be modified.

OBJECTS

This variable is generated from the SOURCES variable. The extension of each source file will have been replaced by .o (Unix) or .obj (Win32). The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

OBJMOC

This variable is set by qmake if files can be found that contain the Q_OBJECT macro. OBJMOC contains the name of all intermediate moc object files. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

PRECOMPH

This variable contains a list of header files that require some sort of pre-compilation step (such as with moc). The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE

This variable contains the name of the qmake program itself and is placed in generated makefiles. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKESPEC

This variable contains the name of the qmake configuration to use when generating makefiles. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified. Use the QMAKESPEC environment variable instead.

QMAKE_AIX_SHLIB

If this variable is not empty, then this variable tells qmake to generate the TARGET as an AIX shared library.

QMAKE_APP_FLAG

This variable is empty unless the 'app' TEMPLATE is specified. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified. Use the following instead:

app {
    #conditional code for 'app' template here
}
QMAKE_APP_OR_DLL

This variable is empty unless the 'app' or 'dll' TEMPLATE is specified. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_AR_CMD

This is used on Unix platforms only

This variable contains the command for invoking the program which creates, modifies and extracts archives. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_DEBUG

This variable contains the flags for the C compiler in debug mode.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_MT

This variable contains the compiler flags for creating a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_MT_DBG

This variable contains the compiler flags for creating a debuggable multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_MT_DLL

This is used on Windows only

This variable contains the compiler flags for creating a multi-threaded dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_MT_DLLDBG

This is used on Windows only

This variable contains the compiler flags for creating a debuggable multi-threaded dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_RELEASE

This variable contains the compiler flags for creating a non-debuggable application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_SHLIB

This is used on Unix platforms only

This variable contains the compiler flags for creating a shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_THREAD

This variable contains the compiler flags for creating a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_WARN_OFF

This variable is not empty if the warn_off TEMPLATE option is specified. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CFLAGS_WARN_ON

This variable is not empty if the warn_on TEMPLATE option is specified. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CLEAN

This variable contains any files which are not generated files (such as moc and uic generated files) and object files that should be removed when using "make clean".

QMAKE_CXXFLAGS_DEBUG

This variable contains the C++ compiler flags for creating a debuggable application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_MT

This variable contains the C++ compiler flags for creating a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_MT_DBG

This variable contains the C++ compiler flags for creating a debuggable multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_MT_DLL

This is used on Windows only

This variable contains the C++ compiler flags for creating a multi-threaded dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_MT_DLLDBG

This is used on Windows only

This variable contains the C++ compiler flags for creating a multi-threaded debuggable dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_RELEASE

This variable contains the C++ compiler flags for creating an application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_SHLIB

This variable contains the C++ compiler flags for creating a shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_THREAD

This variable contains the C++ compiler flags for creating a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_WARN_OFF

This variable contains the C++ compiler flags for suppressing compiler warnings. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_CXXFLAGS_WARN_ON

This variable contains C++ compiler flags for generating compiler warnings. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_EXTENSION_SHLIB

This variable contains the extention for shared libraries. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_FAILED_REQUIREMENTS

This variable contains the list of requirements that were failed to be met when qmake was used. For example, the sql module is needed and wasn't compiled into Qt. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_FILETAGS

This variable contains the file tags needed to be entered into the makefile, such as SOURCES and HEADERS. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_HPUX_SHLIB

This is used on Unix platforms only

If this variable is not empty then this variable tells qmake to generate the TARGET as an HPUX shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_HPUX_SHLIBS

This is used on Unix platforms only

If this variable is not empty then this variable tells qmake to generate the TARGET as an HPUX shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_INCDIR

This variable contains the location of all known header files to be added to INCLUDEPATH when building an application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

TARGETDEPS

All libraries that the target depends on can be listed in this variable. Some backends do not support this, these include MSVC Dsp, and ProjectBuilder .pbproj files. Generally this is support internally by these build tools, this is usefull for explicitly listing dependant static libraries.

QMAKE_INCDIR_OPENGL

This variable contains the location of OpenGL header files to be added to INCLUDEPATH when building an application with OpenGL support. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_INCDIR_QT

This variable contains the location of all known header file paths to be added to INCLUDEPATH when building a Qt application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_INCDIR_THREAD

This variable contains the location of all known header file paths to be added to INCLUDEPATH when building a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_INCDIR_X11

This is used on Unix platforms only

This variable contains the location of X11 header file paths to be added to INCLUDEPATH when building a X11 application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_CONSOLE

This is used on Windows only

This variable contains link flags when building console programs. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_CONSOLE_DLL

This is used on Windows only

This variable contains link flags when building console dlls. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_DEBUG

This variable contains link flags when building debuggable applications. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_PLUGIN

This variable contains link flags when building plugins. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_QT_DLL

This variable contains link flags when building programs that use the Qt library built as a dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_RELEASE

This variable contains link flags when building applications for release. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_SHAPP

This variable contains link flags when building applications which are using the 'app' template. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_SHLIB

This variable contains link flags when building shared libraries The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_SONAME

This variable specifies the name of shared objects, such as .so or .dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_THREAD

This variable contains link flags when building multi-threaded projects. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_WINDOWS

This is used on Windows only

This variable contains link flags when building windows projects. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LFLAGS_WINDOWS_DLL

This is used on Windows only

This variable contains link flags when building windows dll projects. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBDIR

This variable contains the location of all known library directories.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBDIR_FLAGS

This is used on Unix platforms only

This variable contains the location of all library directory with -L prefixed. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

VPATH

This variable tells qmake where to search for files it cannot open. With this you may tell qmake where it may look for things like SOURCES, and if it finds an entry in SOURCES that cannot be opened it will look through the entire VPATH list to see if it can find the file on its own.

See also DEPENDPATH.

DEPENDPATH

This variable contains the list of all directories to look in to resolve dependencies. This will be used when crawling through 'included' files.

QMAKE_LIBDIR_OPENGL

This variable contains the location of the OpenGL library directory.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBDIR_QT

This variable contains the location of the Qt library directory.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBDIR_X11

This is used on Unix platforms only

This variable contains the location of the X11 library directory.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS

This variable contains all project libraries. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_CONSOLE

This is used on Windows only

This variable contains all project libraries that should be linked against when building a console application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_OPENGL

This variable contains all OpenGL libraries. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_OPENGL_QT

This variable contains all OpenGL Qt libraries.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_QT

This variable contains all Qt libraries.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_QT_DLL

This is used on Windows only

This variable contains all Qt libraries when Qt is built as a dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_QT_OPENGL

This variable contains all the libraries needed to link against if OpenGL support is turned on. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_QT_THREAD

This variable contains all the libraries needed to link against if thread support is turned on. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_RT

This is used with Borland compilers only

This variable contains the runtime library needed to link against when building an application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_RTMT

This is used with Borland compilers only

This variable contains the runtime library needed to link against when building a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_THREAD

This is used on Unix platforms only

This variable contains all libraries that need to be linked against when building a multi-threaded application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_WINDOWS

This is used on Windows only

This variable contains all windows libraries.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_X11

This is used on Unix platforms only

This variable contains all X11 libraries.The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIBS_X11SM

This is used on Unix platforms only

This variable contains all X11 session management libraries. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LIB_FLAG

This variable is not empty if the 'lib' template is specified. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LINK_SHLIB_CMD

This variable contains the command to execute when creating a shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_LN_SHLIB

This variable contains the command to execute when creating a link to a shared library. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_MAKEFILE

This variable contains the name of the makefile to create. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_MOC_SRC

This variable contains the names of all moc source files to generate and include in the project. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_QMAKE

This variable contains the location of qmake if it is not in the path. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_QT_DLL

This variable is not empty if Qt was built as a dll. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_RUN_CC

This variable specifies the individual rule needed to build an object. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_RUN_CC_IMP

This variable specifies the individual rule needed to build an object. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_RUN_CXX

This variable specifies the individual rule needed to build an object. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_RUN_CXX_IMP

This variable specifies the individual rule needed to build an object. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

QMAKE_TARGET

This variable contains the name of the project target. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

RC_FILE

This variable contains the name of the resource file for the application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

RES_FILE

This variable contains the name of the resource file for the application. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

SRCMOC

This variable is set by qmake if files can be found that contain the Q_OBJECT macro. SRCMOC contains the name of all the generated moc files. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

TARGET_EXT

This variable specifies the target's extension. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

TARGET_x

This variable specifies the target's extension with a major version number. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

TARGET_x.y.z

This variable specifies the target's extension with version number. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

UICIMPLS

This variable contains a list of the generated implementation files by UIC. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

UICOBJECTS

This variable is generated from the UICIMPLS variable. The extension of each file will have been replaced by .o (Unix) or .obj (Win32). The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

VER_MAJ

This variable contains the major version number of the library, if the 'lib' template is specified.

VER_MIN

This variable contains the minor version number of the library, if the 'lib' template is specified.

VER_PAT

This variable contains the patch version number of the library, if the 'lib' template is specified.

QMAKE_EXT_MOC

This variable changes the extention used on included moc files.

See also File Extensions.

QMAKE_EXT_UI

This variable changes the extention used on /e Designer UI files.

See also File Extensions.

QMAKE_EXT_PRL

This variable changes the extention used on created PRL files.

See also File Extensions, Library Dependencies.

QMAKE_EXT_LEX

This variable changes the extention used on files given to lex.

See also File Extensions, LEXSOURCES.

QMAKE_EXT_YACC This variable changes the extention used on files given to yacc.

See also File Extensions, YACCSOURCES.

QMAKE_EXT_OBJ

This variable changes the extention used on generated object files.

See also File Extensions.

QMAKE_EXT_CPP

This variable changes the interpretation of all suffixes in this list of values as files of type C++ source code.

See also File Extensions.

QMAKE_EXT_H

This variable changes the interpretation of all suffixes in this list of values as files of type C header files.

See also File Extensions.

YACCIMPLS

This variable contains a list of yacc source files. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

YACCOBJECTS

This variable contains a list of yacc object files. The value of this variable is typically handled by qmake or qmake.conf and rarely needs to be modified.

Functions

qmake recognizes the following functions:

include( filename )

This function will include the contents of filename into the current project at the point where was included. The function succeeds if filename was included, otherwise it fails. You can check the return value of this function using a scope.

For example:

include( shared.pri )
OPTIONS = standard custom
!include( options.pri ) {
    message( "No custom build options specified" )
    OPTIONS -= custom
}

exists( file )

This function will test if file exists. If the file exists, then it will succeed; otherwise it will fail. You can specify a regular expression in file and it will succeed if any file matches the regular expression specified.

For example:

exists( $(QTDIR)/lib/qt-mt* ) {
      message( "Configuring for multi-threaded Qt..." )
      CONFIG += thread
}

contains( variablename, value )

This function will succeed if the variable variablename contains the value value. You can check the return value of this function using a scope.

For example:

contains( drivers, network ) {
    # drivers contains 'network'
    message( "Configuring for network build..." )
    HEADERS += network.h
    SOURCES += network.cpp
}

count( variablename, number )

This function will succeed if the variable variablename contains number elements, otherwise it will fail. You can check the return value of this function using a scope.

For example:

MYVAR = one two three
count( MYVAR, 3 ) {
    # always true
}

infile( filename, var, val )

This function will succeed if the file filename (when parsed by qmake itself) contains the variable var with a value of val. You may also not pass in a third argument (val) and the function will only test if var has been assigned to in the file.

isEmpty( variablename )

This function will succeed if the variable variablename is empty (same as count(variable, 0)).

system( command )

This function will execute command in a secondary shell and will succeed if the command exits with an exit status of 1. You can check the return value of this function using a scope.

For example:

  system(ls /bin):HAS_BIN=FALSE

message( string )

This function will always succeed, and will display the given string to the user.

error( string )

This function will never return a value. It will display the given string to the user, and then exit qmake. This function should only be used for very fatal configurations.

For example:

  release:debug:error(You can't have release and debug at the same time!)

Environment Variables and Configuration

QMAKESPEC

qmake requires a platform and compiler description file which contains many default values used to generate appropriate makefiles. The standard Qt distribution comes with many of these files, located in the 'mkspecs' subdirectory of the Qt installation.

The QMAKESPEC environment variable can contain any of the following:

  • A complete path to a directory containing a qmake.conf file. In this case qmake will open the qmake.conf file from within that directory. If the file does not exist, qmake will exit with an error.

  • The name of a platform-compiler combination. In this case, qmake will search in the directory specified by the QTDIR environment variable.

Note: the QMAKESPEC path will automatically be added to the INCLUDEPATH system variable.

INSTALLS

It is common on UNIX to be able to install from the same utility as you build with (e.g make install). For this qmake has introduce the concept of an install set. The notation for this is quite simple, first you fill in an "object" in qmake for example:

  documentation.path = /usr/local/program/doc
  documentation.files = docs/*

In this way you are telling qmake several things about this install, first that you plan to install to /usr/local/program/doc (the path member), second that you plan to copy everything in the docs directory. Once this is done you may insert it in the install list:

  INSTALLS += documentation

Now qmake will take over making sure the correct things are copied to the specified places. If however you require greater control you may use the 'extra' member of the object:

  unix:documentation.extra = create_docs; mv master.doc toc.doc

Then qmake will run the things in extra (this is of course platform specific, so you may need to test for your platform first, this case we test for unix). Then it will do the normal processings of the files member. Finally if you appened a builtin install to INSTALLS qmake (and do not specify a files or extra member) will decide what needs to be copied for you, currently the only supported builtin is target:

  target.path = /usr/local/myprogram
  INSTALLS += target

With this qmake will know what you plan need copied, and do this for you.

Cache File

The cache file (mentioned above in the options) is a special file qmake will read to find settings not specified in the qmake.conf file, the .pro file, or the command line. If -nocache is specified, qmake will try to find a file called .qmake.cache in parent directories. If it fails to find this file, it will silently ignore this step of processing.

Library Dependencies

Often when linking against a library qmake relies on the underlying platform to know what other libraries this library links against, and lets the platform pull them in. In many cases, however, this is not sufficent. For example when statically linking a library there are no libraries linked against, and therefore no dependencies to those libraries are created - however an application that later links against this library will need to know where to find the symbols that the linked in library will require. To help with this situation qmake will follow a library's dependencies when it feels appropriate, however this behaviour must be enabled in qmake. To enable requires two steps. First, you must enable it in the library - to do this you must tell qmake to save information about this library:

  CONFIG += create_prl

This is only relevant to the lib template, and will be ignored for all others. When this option is enabled qmake will create a file (called a .prl file) which will save some meta information about the library. This metafile is itself just a qmake project file, but with all internal variables. You are free to view this file, and if deleted qmake will know to recreate it when necesary (either when the .pro file is later read, or if a dependent library (described below) has changed). When installing this library (by using target in INSTALLS, above) qmake will automatically copy the .prl file to your install path.

The second step to enabling this processing is to turn on reading of the meta information created above:

  CONFIG += link_prl

When this is turned on qmake will process all libraries linked to, and find their meta information. With this meta information qmake will figure out what is relevant to linking, specifically it will add to your list of DEFINES as well as LIBS. Once qmake has processed this file, it will then look through the newly introduced LIBS and find their dependent .prl files, and continue until all libraries have been resolved. At this point the makefile is created as usual, and the libraries are linked explicity against your program.

The internals of the .prl file are left closed so they can easily change later. It is not designed to be changed by hand however, and should only be created by qmake - these .prl files should also not be transfered from operating system to operating system as they may be platform dependent (like a makefile).

File Extensions

Under normal circumstances qmake will try to use appropriate file extensions for your platform. There may be times, however, that you would like to override the behavior of these extensions. To do this, you must modify builtin variables in your .pro file, which will in turn changes qmake's interpretation of these files. You may do this as:

  QMAKE_EXT_MOC = .mymoc

The variables are as follows:

  • QMAKE_EXT_MOC - This modifies the extension placed on included moc files.

  • QMAKE_EXT_UI - This modifies the extension used for designer UI files (usually in FORMS).

  • QMAKE_EXT_PRL - This modifies the extension placed on library dependency files.

  • QMAKE_EXT_LEX - This changes the suffix used in files (usually in LEXSOURCES).

  • QMAKE_EXT_YACC - This changes the suffix used in files (usually in YACCSOURCES).

  • QMAKE_EXT_OBJ - This changes the suffix used on generated object files.

All the above accept just the first value, so you must assign to it one value that will be used through your makefile. There are two variables that accept a list of values, they are:

  • QMAKE_EXT_CPP - Changes interpretation all files with these suffixes to be C++ source files.

  • QMAKE_EXT_H - Changes interpretation all files with these suffixes to be C header files.

Customizing Makefile Output

qmake often tries to be all things to all build tools, this is often less than ideal when you really need to run special platform dependent commands. This can be achieved with specific instructions to the different qmake backends (currently this is only supported by the UNIX generator).

The interfaces to customizing the Makefile are done through "objects" as in other places in qmake. The notation for this is quite simple, first you fill in an "object" in qmake for example:

  mytarget.target = .buildfile
  mytarget.commands = touch $$mytarget.target
  mytarget.depends = mytarget2

  mytarget2.commands = @echo Building $$mytarget.target

The information above defines a qmake target called mytarget which contains a Makefile target called .buildfile, .buildfile is generated by 'touch .buildfile', and finally that this Makefile target depends on the qmake target mytarget2. Additionally we've defined the qmake target mytarget2 which simply echo's something to stdout.

The final step to making use of the above is to instruct qmake that this is actually an object used by the target building parts of qmake by:

QMAKE_EXTRA_UNIX_TARGETS += mytarget mytarget2

This is all you need to do to actually build custom targets in qmake, of course you may want to tie one of these targets to actually building the qmake build target. To do this, you simply need to include your Makefile target in the list of TARGETDEPS.


使用元对象编译器

元对象编译器，朋友中的moc，是处理Qt的C++扩展的程序。

元对象编译器读取一个C++源文件。如果它发现其中的一个或多个类的声明中含有Q_OBJECT宏，它就会给这个使用Q_OBJECT宏的类生成另外一个包含元对象代码的C++源文件。尤其是，元对象代码对信号/槽机制、运行时类型信息和动态属性系统是需要的。

一个被元对象编译器生成的C++源文件必须和这个类的实现一起被编译和连接（或者它被包含到（#include）这个类的源文件中）。

如果你是用qmake来生成你的Makefile文件，当需要的时候，编译规则中需要包含调用元对象编译器，所以你不需要直接使用元对象编译器。关于元对象编译器的更多的背景知识，请看为什么Qt不用模板来实现信号和槽？。

用法

元对象编译器很典型地和包含下面这样情况地类声明地输入文件一起使用：

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        MyClass( QObject * parent=0, const char * name=0 );
        ~MyClass();

    signals:
        void mySignal();

    public slots:
        void mySlot();

    };

除了上述提到地信号和槽，元对象编译器在下一个例子中还将实现对象属性。Q_PROPERTY宏声明了一个对象属性，而Q_ENUMS 声明在这个类中的属性系统中可用的枚举类型的一个列表。在这种特殊的情况下，我们声明了一个枚举类型属性Priority，也被称为“priority”，并且读函数为priority()，写函数为setPriority()。

    class MyClass : public QObject
    {
        Q_OBJECT
        Q_PROPERTY( Priority priority READ priority WRITE setPriority )
        Q_ENUMS( Priority )
    public:
        MyClass( QObject * parent=0, const char * name=0 );
        ~MyClass();

        enum Priority { High, Low, VeryHigh, VeryLow };
        void setPriority( Priority );
        Priority priority() const;
    };

属性可以通过Q_OVERRIDE宏在子类中进行修改。Q_SETS宏声明了枚举变量可以进行组合操作，也就是说可以一起读或写。另外一个宏，Q_CLASSINFO，用来给类的元对象添加名称/值这样一组数据：

    class MyClass : public QObject
    {
        Q_OBJECT
        Q_CLASSINFO( "Author", "Oscar Peterson")
        Q_CLASSINFO( "Status", "Very nice class")
    public:
        MyClass( QObject * parent=0, const char * name=0 );
        ~MyClass();
    };

这三个概念：信号和槽、属性和元对象数据是可以组合在一起的。

元对象编译器生成的输出文件必须被编译和连接，就像你的程序中的其它的C++代码一样；否则你的程序的连编将会在最后的连接阶段失败。出于习惯，这种操作是用下述两种方式之一解决的：

方法一：类的声明放在一个头文件（.h文件）中

如果在上述的文件myclass.h中发现类的声明，元对象编译器的输出文件将会被放在一个叫moc_myclass.cpp的文件中。这个文件将会像通常情况一样被编译，作为对象文件的结果是moc_myclass.o（在Unix下）或者moc_myclass.obj（在Windows下）。这个对象接着将会被包含到一个对象文件列表中，它们将会在程序的最后连编阶段被连接在一起。

方法二：类的声明放在一个实现文件（.cpp文件）中

如果上述的文件myclass.cpp中发现类的声明，元对象编译器的输出文件将会被放在一个叫myclass.moc的文件中。这个文件需要被实现文件包含（#include），也就是说myclass.cpp需要包含下面这行
    #include "myclass.moc"
放在所有的代码之后。这样，元对象编译器生成的代码将会和myclass.cpp中普通的类定义一起被编译和连接，所以方法一中的分别编译和连接就是不需要的了。

方法一是常规的方法。方法二用在你想让实现文件自包含，或者Q_OBJECT类是内部实现的并且在头文件中不可见的这些情况下使用。

Makefile中自动使用元对象编译器的方法

除了最简单的测试程序之外的任何程序，建议自动使用元对象编译器。在你的程序的Makefile文件中加入一些规则，make就会在需要的时候运行元对象编译器和处理元对象编译器的输出。

我们建议使用Trolltech的自由makefile生成工具，qmake，来生成你的Makefile。这个工具可以识别方法一和方法二风格的源文件，并建立一个可以做所有必要的元对象编译操作的Makefile。

另一方面如果，你想自己建立你的Makefile，下面是如何包含元对象编译操作的一些提示。

对于在头文件中声明了Q_OBJECT宏的类，如果你只使用GNU的make的话，这是一个很有用的makefile规则：

    moc_%.cpp: %.h
            moc $< -o $@

如果你想更方便地写makefile，你可以按下面的格式写单独的规则：

    moc_NAME.cpp: NAME.h
            moc $< -o $@

你必须记住要把moc_NAME.cpp添加到你的SOURCES（你可以用你喜欢的名字替代）变量中并且把moc_NAME.o或者moc_NAME.obj添加到你的OBJECTS变量中。

（当我们给我们的C++源文件命名为.cpp时，元对象编译器并不留意，所以只要你喜欢，你可以使用.C、.cc、.CC、.cxx或者甚至.c++。）

对于在实现文件（.cpp文件）中声明Q_OBJECT的类，我们建议你使用下面这样的makefile规则：

    NAME.o: NAME.moc

    NAME.moc: NAME.cpp
            moc -i $< -o $@

这将会保证make程序会在编译NAME.cpp之前运行元对象编译器。然后你可以把

    #include "NAME.moc"

放在NAME.cpp的末尾，这样在这个文件中的所有的类声明被完全地知道。

调用元对象编译器moc

这里是元对象编译器moc所支持地命令行选项：

-o file
将输出写到file而不是标准输出。
-f
强制在输出文件中生成#include声明。文件的名称必须符合正则表达式\.[hH][^.]*（也就是说扩展名必须以H或h开始）。这个选项只有在你的头文件没有遵循标准命名法则的时候才有用。
-i
不在输出文件中生成#include声明。当一个C++文件包含一个或多个类声明的时候你也许应该这样使用元对象编译器。然后你应该在.cpp文件中包含（#include）元对象代码。如果-i和-f两个参数都出现，后出现的有效。
-nw
不产生任何警告。不建议使用。
-ldbg
把大量的lex调试信息写到标准输出。
-p path
使元对象编译器生成的（如果有生成的）#include声明的文件名称中预先考虑到path/。
-q path
使元对象编译器在生成的文件中的qt #include文件的名称中预先考虑到path/。

你可以明确地告诉元对象编译器不要解析头文件中的成分。它可以识别包含子字符串MOC_SKIP_BEGIN或者MOC_SKIP_END的任何C++注释（//）。它们正如你所期望的那样工作并且你可以把它们划分为若干层次。元对象编译器所看到的最终结果就好像你把一个MOC_SKIP_BEGIN和一个MOC_SKIP_END当中的所有行删除那样。

诊断

元对象编译器将会警告关于学多在Q_OBJECT类声明中危险的或者不合法的构造。

如果你在你的程序的最后连编阶段得到连接错误，说YourClass::className()是未定义的或者YourClass缺乏vtbl，某样东西已经被做错。绝大多数情况下，你忘记了编译或者#include元对象编译器产生的C++代码，或者（在前面的情况下）没有在连接命令中包含那个对象文件。

限制

元对象编译器并不展开#include或者#define，它简单地忽略它所遇到的所有预处理程序指示。这是遗憾的，但是在实践中它通常情况下不是问题。

元对象编译器不处理所有的C++。主要的问题是类模板不能含有信号和槽。这里是一个例子：

    class SomeTemplate<int> : public QFrame {
        Q_OBJECT
        ...
    signals:
        void bugInMocDetected( int );
    };

次重要的是，后面的构造是不合法的。所有的这些都可以替换为我们通常认为比较好的方案，所以去掉这些限制对于我们来说并不是高优先级的。

多重继承需要把QObject放在第一个

如果你使用多重继承，元对象编译器假设首先继承的类是QObject的一个子类。也就是说，确信仅仅首先继承的类是QObject。

    class SomeClass : public QObject, public OtherClass {
        ...
    };

（这个限制几乎是不可能去掉的；因为元对象编译器并不展开#include或者#define，它不能发现基类中哪个是QObject。）

函数指针不能作为信号和槽的参数

在你考虑使用函数指针作为信号/槽的参数的大多数情况下，我们认为继承是一个不错的替代方法。这里是一个不合法的语法的例子：

    class SomeClass : public QObject {
        Q_OBJECT
        ...
    public slots:
        // 不合法的
        void apply( void (*apply)(List *, void *), char * );
    };

你可以在这样一个限制范围内工作：

    typedef void (*ApplyFunctionType)( List *, void * );

    class SomeClass : public QObject {
        Q_OBJECT
        ...
    public slots:
        void apply( ApplyFunctionType, char * );
    };

有时用继承和虚函数、信号和槽来替换函数指针是更好的。

友声明不能放在信号部分或者槽部分中

有时它也许会工作，但通常情况下，友声明不能放在信号部分或者槽部分中。把它们替换到私有的、保护的或者公有的部分中。这里是一个不合法的语法的例子：

    class SomeClass : public QObject {
        Q_OBJECT
        ...
    signals:
        friend class ClassTemplate<char>; // 错的
    };

信号和槽不能被升级

把继承的成员函数升级为公有状态这一个C++特征并不延伸到包括信号和槽。这里是一个不合法的例子：

    class Whatever : public QButtonGroup {
        ...
    public slots:
        void QButtonGroup::buttonPressed; // 错的
        ...
    };

QButtonGroup::buttonPressed()槽是保护的。

C++测验：如果你试图升级一个被重载的保护成员函数将会发生什么？

  1. 所有的函数都被重载。
  2. 这不是标准的C++。

类型宏不能被用于信号和槽的参数

因为元对象编译器并不展开#define，在信号和槽中类型宏作为一个参数是不能工作的。这里是一个不合法的例子：

    #ifdef ultrix
    #define SIGNEDNESS(a) unsigned a
    #else
    #define SIGNEDNESS(a) a
    #endif

    class Whatever : public QObject {
        ...
    signals:
        void someSignal( SIGNEDNESS(int) );
        ...
    };

不含有参数的#define将会像你所期望的那样工作。

嵌套类不能放在信号部分或者槽部分，也不能含有信号和槽

这里是一个例子：

    class A {
        Q_OBJECT
    public:
        class B {
        public slots:   // 错的
            void b();
            ...
        };
    signals:
        class B {       // 错的
            void b();
            ...
        }:
    };

构造函数不能用于信号部分和槽部分

为什么一个人会把一个构造函数放到信号部分或者槽部分，这对于我们来说都是很神秘的。你无论如何也不能这样做（除去它偶尔能工作的情况）。请把它们放到私有的、保护的或者公有的部分中，它们本该属于的地方。这里是一个不合法的语法的例子：

    class SomeClass : public QObject {
        Q_OBJECT
    public slots:
        SomeClass( QObject *parent, const char *name )
            : QObject( parent, name ) { } // 错的
        ...
    };

属性的声明应该放在含有相应的读写函数的公有部分之前

在包含相应的读写函数的公有部分之中和之后声明属性的话，读写函数就不能像所期望的那样工作了。元对象编译器会抱怨不能找到函数或者解析这个类型。这里是一个不合法的语法的例子：

    class SomeClass : public QObject {
        Q_OBJECT
    public:
        ...
        Q_PROPERTY( Priority priority READ priority WRITE setPriority ) // 错的
        Q_ENUMS( Priority ) // 错的
        enum Priority { High, Low, VeryHigh, VeryLow };
        void setPriority( Priority );
        Priority priority() const;
        ...
    };

根据这个限制，你应该在Q_OBJECT之后，在这个类的声明之前声明所有的属性：

    class SomeClass : public QObject {
        Q_OBJECT
        Q_PROPERTY( Priority priority READ priority WRITE setPriority )
        Q_ENUMS( Priority )
    public:
        ...
        enum Priority { High, Low, VeryHigh, VeryLow };
        void setPriority( Priority );
        Priority priority() const;
        ...
    };

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


User Interface Compiler (uic)

This page documents the User Interface Compiler for the Qt GUI application framework. The uic reads a user interface definition (.ui) file in XML as generated by Qt Designer and creates corresponding C++ header or source files. It can also generate an image file to embed raw image data in C++ source code.

Options

File Generation Options

Generate declaration:

uic  [options]  <file>

Generate implementation:

uic  [options] -impl <headerfile> <file>
  • <headerfile> - name of the declaration file

Generate image collection:

uic  [options] -embed <project> <image1> <image2> <image3> ...
  • <project> - project name
  • <image[0..n]> - image files

For convenience, uic can also generate declaration or implementation stubs for subclasses.

Generate subclass declaration:

uic  [options] -subdecl <classname> <headerfile> <file>
  • <classname> - name of the subclass to generate
  • <headerfile> - declaration file of the baseclass

Generate subclass implementation:

uic  [options] -subimpl <classname> <headerfile> <file>
  • <classname> - name of the subclass to generate
  • <headerfile> - declaration file of the subclass

General Options

  • -o file - write output to 'file' rather than to stdout.
  • -nofwd - omit forward declarations of custom classes in the generated header file. This is necessary if typedef classes are used.
  • -tr func - use func(sourceText, comment) rather than trUtf8(sourceText, comment) for internationalization.

Usage

uic is almost always invoked by make (1), rather than by hand.

Here are useful makefile rules if you only use GNU make:

    %.h: %.ui
        uic $< -o $@

    %.cpp: %.ui
        uic -impl $*.h $< -o $@
If you want to write portably, you can use individual rules of the following form:
    NAME.h: NAME.ui
        uic $< -o $@

    NAME.cpp: NAME.ui
        uic -impl $*.h $< -o $@
You must also remember to add NAME.cpp to your SOURCES (substitute your favorite name) variable and NAME.o to your OBJECTS variable.

(While we prefer to name our C++ source files .cpp, the uic doesn't care, so you can use .C, .cc, .CC, .cxx or even .c++ if you prefer.)


Help System

These classes provide for all forms of online-help in your application, with three levels of detail:

  1. Tool Tips and Status Bar message - flyweight help, extremely brief, entirely integrated in the user interface, requiring little or no user interaction to invoke.
  2. What's This? - lightweight, but can be a three-paragraph explanation.
  3. Online Help - can encompass any amount of information, but is typically slower to call up, somewhat separated from the user's work, and often users feel that using online help is a digression from their real task.

QStatusBar | Horizontal bar suitable for presenting status information
QStyleSheet | Collection of styles for rich text rendering and a generator of tags
QTextBrowser | Rich text browser with hypertext navigation
QToolTip | Tool tips (balloon help) for any widget or rectangular part of a widget
QToolTipGroup | Collects tool tips into related groups
QWhatsThis | Simple description of any widget, i.e. answering the question "What's this?"


Standard Accelerator Keys

Applications invariably need to define accelerator keys for actions. Qt fully supports accelerators, for example with QAccel::shortcutKey().

Here are Microsoft's recommendations for accelerator keys, with comments about the Open Group's recommendations where they exist and differ. For most commands, the Open Group either has no advice or agrees with Microsoft.

The emboldened letter plus Alt is Microsoft's recommended choice, and we recommend supporting it. For an Apply button, for example, we recommend QButton::setText( tr("&Apply") );

If you have conflicting commands (e.g. About and Apply buttons in the same dialog), you must decide for yourself.

  • About
  • Always on Top
  • Apply
  • Back
  • Browse
  • Close (CDE: Alt+F4; Alt+F4 is "close window" in Windows)
  • Copy (CDE: Ctrl+C, Ctrl+Insert)
  • Copy Here
  • Create Shortcut
  • Create Shortcut Here
  • Cut
  • Delete
  • Edit
  • Exit
  • Explore
  • File
  • Find
  • Help
  • Help Topics
  • Hide
  • Insert
  • Insert Object
  • Link Here
  • Maximize
  • Minimize
  • Move
  • Move Here
  • New
  • Next
  • No
  • Open
  • Open With
  • Page Setup
  • Paste
  • Paste Link
  • Paste Shortcut
  • Paste Special
  • Pause
  • Play
  • Print
  • Print Here
  • Properties
  • Quick View
  • Redo (CDE: Ctrl+Y, Alt+Backspace)
  • Repeat
  • Restore
  • Resume
  • Retry
  • Run
  • Save
  • Save As
  • Select All
  • Send To
  • Show
  • Size
  • Split
  • Stop
  • Undo (CDE: Ctrl+Z or Alt+Backspace)
  • View
  • What's This?
  • Window
  • Yes

There are also a lot of other keys and actions (that use other modifier keys than Alt). See the Microsoft and The Open Group documentation for details.

The Microsoft book has ISBN 0735605661. The corresponding Open Group book is very hard to find, rather expensive and we cannot recommend it. However, if you really want it, OGPubs@opengroup.org might be able to help. Ask them for ISBN 1859121047.


Qt Free Edition License Agreement

The Qt Free Edition is distributed under the Q Public License (QPL). It allows free use of Qt Free Edition for running software developed by others, and free use of Qt Free Edition for development of free/Open Source software. There is more information about the QPL at the Trolltech web site.

Note that the Qt/Embedded Free Edition is not distributed under the QPL, but under the GNU General Public License (GPL).

For development non-free/proprietary software, the Qt Professional Edition is available. It has a normal commercial library license, with none of the special restrictions of the QPL or the GPL.

THE Q PUBLIC LICENSE version 1.0

Copyright (C) 1999-2000 Trolltech AS, Norway.
Everyone is permitted to copy and distribute this license document.

The intent of this license is to establish freedom to share and change the software regulated by this license under the open source model.

This license applies to any software containing a notice placed by the copyright holder saying that it may be distributed under the terms of the Q Public License version 1.0. Such software is herein referred to as the Software. This license covers modification and distribution of the Software, use of third-party application programs based on the Software, and development of free software which uses the Software.

Granted Rights

1. You are granted the non-exclusive rights set forth in this license provided you agree to and comply with any and all conditions in this license. Whole or partial distribution of the Software, or software items that link with the Software, in any form signifies acceptance of this license.

2. You may copy and distribute the Software in unmodified form provided that the entire package, including - but not restricted to - copyright, trademark notices and disclaimers, as released by the initial developer of the Software, is distributed.

3. You may make modifications to the Software and distribute your modifications, in a form that is separate from the Software, such as patches. The following restrictions apply to modifications:

a. Modifications must not alter or remove any copyright notices in the Software.

b. When modifications to the Software are released under this license, a non-exclusive royalty-free right is granted to the initial developer of the Software to distribute your modification in future versions of the Software provided such versions remain available under these terms in addition to any other license(s) of the initial developer.

4. You may distribute machine-executable forms of the Software or machine-executable forms of modified versions of the Software, provided that you meet these restrictions:

a. You must include this license document in the distribution.

b. You must ensure that all recipients of the machine-executable forms are also able to receive the complete machine-readable source code to the distributed Software, including all modifications, without any charge beyond the costs of data transfer, and place prominent notices in the distribution explaining this.

c. You must ensure that all modifications included in the machine-executable forms are available under the terms of this license.

5. You may use the original or modified versions of the Software to compile, link and run application programs legally developed by you or by others.

6. You may develop application programs, reusable components and other software items that link with the original or modified versions of the Software. These items, when distributed, are subject to the following requirements:

a. You must ensure that all recipients of machine-executable forms of these items are also able to receive and use the complete machine-readable source code to the items without any charge beyond the costs of data transfer.

b. You must explicitly license all recipients of your items to use and re-distribute original and modified versions of the items in both machine-executable and source code forms. The recipients must be able to do so without any charges whatsoever, and they must be able to re-distribute to anyone they choose.

c. If the items are not available to the general public, and the initial developer of the Software requests a copy of the items, then you must supply one.

Limitations of Liability

In no event shall the initial developers or copyright holders be liable for any damages whatsoever, including - but not restricted to - lost revenue or profits or other direct, indirect, special, incidental or consequential damages, even if they have been advised of the possibility of such damages, except to the extent invariable law, if any, provides otherwise.

No Warranty

The Software and this license document are provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

Choice of Law

This license is governed by the Laws of Norway. Disputes shall be settled by Oslo City Court.


GNU General Public License

The Qt GUI Toolkit is Copyright (C) 1994-2002 Trolltech AS.

The Qt Free Edition and the Qt/Embedded Free Edition are available under the GPL. The Qt Free Edition (for Unix/X11) is also available under the QPL.

 You may use, distribute and copy the Qt GUI Toolkit under the terms of
 GNU General Public License version 2, which is displayed below.

                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                          675 Mass Ave, Cambridge, MA 02139, USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

        Appendix: How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 19yy  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) 19yy name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.


Licenses for Code Used in Qt

Qt contains a little code that is not under the QPL, the GPL, or the Qt Commercial License Agreement, but rather under specific highly permissive license from the original authors. This page lists the licenses used for that code, names the authors, and links to the points where it is used.

Trolltech gratefully acknowledges these and others contribution to Qt. We recommend that all programs that use Qt also acknowledge these contributions, and quote all these license statements in an appendix to the documentation.

Copyright (C) 1989, 1991 by Jef Poskanzer.

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.

  • QImage::smoothScale

Copyright (C) 2000 TurboLinux, Inc. Written by Justin Yu and Sean Chen. Copyright (C) 2001 Turbolinux, Inc. Written by James Su. Copyright (C) 2001 ThizLinux Laboratory Ltd. Written by Anthony Fok.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  • QGb18030Codec

Copyright (c) 1999 Mizi Research Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  • QEucKrCodec

Copyright (c) 1999 Serika Kurusugawa. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS". ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  • QEucJpCodec
  • QJisCodec
  • QSjisCodec

Copyright 1995, Trinity College Computing Center. Written by David Chappell.

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.

TrueType font support. These functions allow PPR to generate PostScript fonts from Microsoft compatible TrueType font files.

The functions in this file do most of the work to convert a TrueType font to a type 3 PostScript font.

Most of the material in this file is derived from a program called "ttf2ps" which L. S. Ng posted to the usenet news group "comp.sources.postscript". The author did not provide a copyright notice or indicate any restrictions on use.

Last revised 11 July 1995.

  • QPrinter

Copyright 1996 Daniel Dardailler.

Permission to use, copy, modify, distribute, and sell this software for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Daniel Dardailler not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Daniel Dardailler makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.

Modifications Copyright 1999 Matt Koss, under the same license as above.

  • Drag and Drop

Copyright 2000 Hans Petter Bieker . All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  • QTsciiCodec

Qt supports GIF reading if it is configured that way during installation (see qgif.h). If it is, we are required to state that "The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated."

Warning: If you are in a country that recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license that technology. Such countries include Canada, Japan, the USA, France, Germany, Italy and the UK.

GIF support may be removed completely in a future version of Qt. We recommend using the MNG or PNG format.

  • QImageDecoder


Thanks!

The following (and probably many others) have provided bug reports, suggestions, patches, beta testing, or done us other favors. We thank you all:

Adam P. Jenkins <ajenkins at cs.umass.edu>
Ahmed Metwally <ametwaly at auc-cs28.eun.eg>
Aidas Kasparas <kaspar at soften.ktu.lt>
Alejandro Aguilar Sierra <asierra at servidor.unam.mx>
Alex <steeper at dial.pipex.com>
Alex Kambis <kambis at eos913c.gsfc.nasa.gov>
Alexander Kozlov <alex at hale.appl.sci-nnov.ru>
Alexander Sanda <alex at darkstar.ping.at>
Amos Leffler <leffler at netaxs.com>
Anders Hanson <andhan at lls.se>
Andreas Schlempp <schlempp at egd.igd.fhg.de>
Andrew Bell <abell at vsys.com>
Andrew Gillham <gillhaa at ghost.whirlpool.com>
Andrew J. Robinson <robinson at eclipse.net>
Andrew Pavlomanolakos <app at novanet.net.au>
Andrew R. Tefft <teffta at crypt.erie.ge.com>
Andrew Vajoczki <vajoczki at interlog.com>
André Johansen <Andre.Johansen at funcom.no>
Andy Shaw <andy at east.no>
Andy Brice <andyb at suntail.net>
Anton Keyter <ant at intekom.co.za>
Arnt Gulbrandsen <arnt at gulbrandsen.priv.no>
Ashley Winters <jql at accessone.com>
Aubrey Soper <azdak at ix.netcom.com>
Axel Schwenke <schwenke at HTWM.DE>
Ben Bergen <ben at gmg.com>
Bernard Leach <B.Leach at compsoc.cs.latrobe.edu.au>
Bernd Johannes Wuebben <wuebben at math.cornell.edu>
Bernd S. Brentrup <bsb at uni-muenster.de>
Bert Haverkamp <b.r.j.haverkamp at et.tudelft.nl>
Bjorn Reese <breese at dit.ou.dk>
Brian Beattie <beattie at drcpdx.stt3.com>
Brian P. Theodore <theodore at std.saic.com>
Brian White <bcwhite at verisim.com>
Bryan Scattergood <bryan at fsel.com>
Carsten Steckel <carsten at cs.newcastle.edu.au>
Chao-Hsin, Lin <linchao at charlie.cns.iit.edu>
Chip Salzenberg <chip at atlantic.net>
Chris Zwilling <crzwlng at cloudnet.com>
Christian Czezatke <e9025461 at student.tuwien.ac.at>
Christopher Andrew Spiking <cas at Cs.Nott.AC.UK>
Christopher J. White <cjwhite at rgit.wustl.edu>
Claus Werner <lzu96cw at reading.ac.uk>
Cloyce D. Spradling <cloyce at austin.ibm.com>
Colin Paul Adams <colin at colina.demon.co.uk>
Cristiano Verondini <cverond at deis219.deis.unibo.it>
Damyan Pepper <damyanp at cogs.susx.ac.uk>
Dan Nickerson <nickersond at uthscsa.edu>
Daniel Brahneborg <basic at well.com>
Daniel Gruner <dgruner at tikva.chem.utoronto.ca>
Daniel J Mitchell <dan at rebellion.co.uk>
Danilo Fiorenzano <danilo at terranet.ab.ca>
Dante Profeta <profeta at neomedia.it>
Darryl Ruggles <001654r at dragon.acadiau.ca>
Dave <dave at stellacore.com>
Dave Steffen <steffend at glitch.physics.colostate.edu>
Dean Hall <dwhall at deskstation.com>
Denis Y. Pershin <dyp at isis.nsu.ru>
Diedrich Vorberg <Diedrich_Vorberg at cp.prima.ruhr.de>
Dietmar Schaefer <dietmar at cs.newcastle.edu.au>
Dimitri Papadopoulos <dpo at club-internet.fr>
Dirk Mueller <mueller at kde.org>
Dirk Schwartmann <dirk.schwartmann at dlr.de>
Dominik Jergus <djergus at ics.uci.edu>
Don Sanders <sanders at kde.org>
Donald A. Seielstad <donald at gromit.scs.uiuc.edu>
Donna J. Armijo <donna at KachinaTech.COM>
Doug Boreland <dborel at amex-trs.com>
Douglas Lenz <dlenz at spedsoft.com>
Dr Mek Buhl Nielsen <m.b.nielsen at bham.ac.uk>
Dr Willem A. Schreuder <Willem.Schreuder at prinmath.com>
E. Kevin Hall <hall at boston.sgi.com>
Ed Mackey <emackey at Early.com>
Edmund Taylor <etaylor at interaccess.com>
Eric Bos <Eric.Bos at adelaide.maptek.com.au>
Eric Brunson <brunson at brunson.com>
Eric Jansen <jansen at photon.com>
Erik Norell <erik at Astrakan.HGS.SE>
Erik Thiele <erik at unterland.de>
Ernie Pasveer <erniep at vsl.com>
FRBall <frb at umr.edu>
FUJIMOTO Koji <kochan at mbox.kyoto-inet.or.jp>
Fergal Mc Carthy <fergal at ilo.dec.com>
Frank Gockel <gockel at etecs4.uni-duisburg.de>
Frank Roscher <frank at chemnitz.abs-rz.de>
Fredrik Markström <fredrik at zod.campus.luth.se>
Fredrik Nehr <fredrik_nehr at ivab.se>
FrenzelBhv at aol.com
Frugal <frugal at wardrobe.demon.co.uk>
Frugal the Curious <Chris.Ward at softcare.co.uk>
Gabor V. Gulyas <gabor at robiomat.com>
Gary E. Sherman <sherman at mrcc.com>
Geoff Carpenter <GCC at watson.ibm.com>
Geoffrey Higginson <ghiggins at gulf.uvic.ca>
Georg Filios <Georg.Filios at post.rwth-aachen.de>
George Simunovich <george at cia-g.com>
Giovanni Carapelli <gcarapel at mbox.vol.it>
Greg Tomalesky <tomalesk at yrkpa.kias.com>
Gregg Jensen <gwj at stl.nexen.com>
Gustav "Gurre" Kalvesten <a94guska at ida.his.se>
Hal DeVore <hdevore at crow.bmc.com>
Hans Flaechsig <hans at hannes.owl.de>
Hans Schlenker <schlenkh at informatik.uni-muenchen.de>
Hardo Mueller <hardo at ipb.uni-bonn.de>
Henty Waker <henty at foxbat.sur.uct.ac.za>
Hrafnkell Eiriksson <hkelle at mmedia.is>
Ildefonso Junquero Martin-Arroyo <junquero at sainsel.es>
Ingo Stapel <ingo.stapel at tu-clausthal.de>
J. Solomon Kostelnik <roz at one.net>
Jae Cho <cs184-dc at ute.CS.Berkeley.EDU>
James McIninch <james at amber.biology.gatech.edu>
Jan Aarsaether <jaa at metis.no>
Jaromir Dolecek <dolecek at ics.muni.cz>
Jason Evans <evans911 at cs.uidaho.edu>
Jay Painter <jay at a42.com>
Jean-Philippe Langlois <jpl at iname.com>
Jeff Harris <jharris at cis.ohio-state.edu>
Jeff Largent <jlargent at iu.net>
Jeffrey Vetter <vetter at lanl.gov>
Jeremy Wohl <jeremy at godzilli.cs.sunysb.edu>
Jim Lauchlan <jim.lauchlan at gecm.com>
Joachim Backes <backes at rhrk.uni-kl.de>
Jochen Scharrlach <jscharrl at BA-Stuttgart.De>
Joe Croft <jcroft at swbell.net>
Joel Lindholm <wizball at kewl.campus.luth.se>
John H. Reppy <jhr at research.att.com>
John Huertas - Jourda <octarine at gte.net>
John Ouellette <ouellet at beluga.phys.UVic.CA>
John Vidar Larring <larring at weatherone.tv>
Jon Brumfitt <jbrumfit at astro.estec.esa.nl>
Jose Castro <jocastro at erols.com>
Julian Enticknap <Julian.Enticknap at UK.Sun.COM>
Jussi-Pekka Sairanen <jussi-pekka.sairanen at research.nokia.com>
Kalle Dalheimer <kalle at dalheimer.hh.eunet.de>
Karl Robillard <karl at skygames.com>
Keith Brown <ksbrown at ix.netcom.com>
Keith Dowsett <kdowsett at rpms.ac.uk>
Ken Hollis <khollis at northwest.com>
Kirill Konyagin <kirill at asplinux.ru>
Klaus Ebner <klaus at gaspode.ndh.com>
Klaus-Georg Adams <Klaus-Georg.Adams at chemie.uni-karlsruhe.de>
Kristof Depraetere <Kristof.Depraetere at rug.ac.be>
Kurt L Anderson <kurt+ at osu.edu>
Larry Lee <lclee at primenet.com>
Lars Knoll <knoll at mpi-hd.mpg.de>
M. G. Berberich <berberic at fmi.uni-passau.de>
Maas-Maarten Zeeman <mzeeman at cs.vu.nl>
Magnus Persson <mpersson at eritel.se>
Mario Weilguni <mweilguni at arctica.sime.com>
Mariya <muha at iclub.nsu.ru>
Mark Summerfield <summer at perlpress.com>
Markku Hihnala <mah at ee.oulu.fi>
Marko Macek <Marko.Macek at snet.fer.uni-lj.si>
Martin Baehr <mbaehr at email.archlab.tuwien.ac.at>
Martin Mueller <mm at lunetix.de>
Martin van Velsen <vvelsen at ronix.ptf.hro.nl>
Matthias Ettrich <ettrich at fisher.informatik.uni-tuebingen.de>
Matthias Suencksen <msuencks at techfak.uni-bielefeld.de>
Mattias Engdegård <f91-men at nada.kth.se>
Michael Figley <figley at ibmoto.com>
Michael George <george at quark.im4u.net>
Michael Graff <explorer at flame.org>
Michael H. Price II <price at ERC.MsState.Edu>
Michael Harnois <mharnois at sbt.net>
Michael Hohmuth <hohmuth at inf.tu-dresden.de>
Michael Leodolter <michael at lab1.psy.univie.ac.at>
Michael Roth <mroth at nessie.de>
Michael Schwendt <Michael_Schwendt at public.uni-hamburg.de>
Michal Polak <mpolak at fi.muni.cz>
Mikael Bourges-Sevenier <bourges at int-evry.fr>
Mike Fearn <hp003 at dra.hmg.gb>
Mike Perik <mikep at crt.com>
Mike Sharkey <msharkey at softarc.com>
Miroslav Flidr <flidr at kky.zcu.cz>
Miyata Shigeru <miyata at kusm.kyoto-u.ac.jp>
Myron Uecker <muecker at csd.net>
NGOk YUK YAU <zzy at compuserve.com>
Neal Sanche <neal at nsdev.org>
Niclas Anderberg <agony at sparta.lu.se>
Oliver Eiden <o.eiden at pop.ruhr.de>
Oliver Elphick <olly at lfix.co.uk>
Olivier Verloove <overloov at ulb.ac.be>
Osku Salerma <osku at iki.fi>
P. J. Leonard <eespjl at ee.bath.ac.uk>
Paolo Galatola <paolo at iris.polito.it>
Pat Dowler <dowler at pt1B1106.FSH.UVic.CA>
Patrice TROGNON <trognon at apogee-com.fr>
Patrick Voigt <Patrick.Voigt at Informatik.TU-Chemnitz.DE>
Paul Bucheit <ptb at k2.cwru.edu>
Paul Kendall <paul at kcbbs.gen.nz>
Paul Marquis <pmarquis at iddptm.iddis.com>
Peter Bender <bender at iib.bauwesen.th-darmstadt.de>
Peter Klotz <p.klotz at icoserve.com>
Peter Pletcher <peter at delilah>
Pierre Rocque <rocque at CRHSC.Umontreal.CA>
Pohorecki Wladyslaw <POHORECKI at novell.ftj.agh.edu.pl>
R.S. MALLOZZI, ES-84, 205-544-0887 <MALLOZZI at bowie.msfc.nasa.gov>
ROHLFS Reiner <Reiner.Rohlfs at obs.unige.ch>
Ralf Stanke <ralf at mcshh.hanse.de>
Reggie Stadlbauer <reggie at kde.org>
Richard D. Jackson <rjackson at bga.com>
Richard Keech <rkeech at colesmyer.com.au>
Richard Moore <moorer at cs.man.ac.uk>
Rick Brohl <rbrohl at uswest.com>
Robert Anderson <Robert.E.Anderson at unh.edu>
Robert Cimrman <cimrman at marius.univ-mrs.fr>
Roberto Alsina <ralsina at ultra7.unl.edu.ar>
Salman Sheikh <salman at vdragon.gsfc.nasa.gov>
Sandro Sigala <ssigala at globalnet.it>
Scott Coppen <scoppen at emerald.tufts.edu>
Sean Vyain <svyain at mail.tds.net>
Sirtaj Singh Kang <ssk at physics.unimelb.EDU.AU>
Sivan Toledo
Stefan Cronert <d93-scr at nada.kth.se>
Stefan Taferner <taf at porsche.co.at>
Steffen Hansen <stefh at dit.ou.dk>
Stephan Pfab <pfab at mathematik.uni-ulm.de>
Stephane Zermatten <szermat at ibm.net>
Sven Fischer <sven at comnets.rwth-aachen.de>
Sven Riedel <lynx at heim8.tu-clausthal.de>
Terje Dalen <terje at norcontrol.no>
Thomas Lineal <thomas at ricci.allcon.com>
Thomas Rath <rath at mac-info-link.de>
Thorsten Ende <the at is-bremen.de>
Tiaan Wessels <tiaan at inetsys.alt.za>
Tim D. Gilman <tdgilman at best.com>
Tom Houlder <thoulder at icor.fr>
Tony Albrecht <Tony.Albrecht at adelaide.maptek.com.au>
Torgeir Hovden <hovden at akkurat.idt.ntnu.no>
Trond Hellem Bø <s638 at ii.uib.no>
Trond Solli <Trond.Solli at marintek.sintef.no>
Ulf Stelbe <ust at egd.igd.fhg.de>
Ulrich Hertlein <uhe at cs.tu-berlin.de>
Ulrich Ring <ur at daveg.com>
Uwe Thiem <uwe at uwix.alt.na>
Vadim Zaliva <lord at crocodile.org>
Val Gough <val at stellacore.com>
Vilhelm Sjöberg <ville at swipnet.se>
Vlad Karpinsky <vlad at crocodile.org>
Volker Poplawski <volkerp at stepnet.de>
Warwick Allison <warwick at it.uq.edu.au>
Xiaojian Li <lixj at monte.rutgers.edu>
Ximenes <ximenes at netset.com>
Y. N. Lo <ynlo at netcom.ca>
Zyklon <zyk at dds.nl>
atsushi konno <jibe at ppp.bekkoame.or.jp>
berry at hxi.com
boris passek <boris at ice.fb12.TU-Berlin.DE>
fidaire <fidaire at bip.fr>
joeh at sugar-river.net
rinsch at aea.ruhr-uni-bochum.de
tsutsui at kekvax.kek.jp
vandevod at cs.rpi.edu
vinckeg at sebb.bel.alcatel.be
yleffler at ucis.vill.edu

We hope there are not too many omissions from the list. Any omissions are bugs and should be reported to qt-bugs@trolltech.com like other bugs in the Qt code or documentation.


Key Features in Qt 3.0

Qt 3.0 adds a lot of new features and improvements over the Qt 2.x series. Some internals have undergone major redesign and new classes and methods have been added.

We have tried to keep the API of Qt 3.0 as compatible as possible with the Qt 2.x series. For most applications only minor changes will be needed to compile and run them successfully using Qt 3.0.

One of the major new features that has been added in the 3.0 release is a module allowing you to easily work with databases. The API is platform independent and database neutral. This module is seamlessly integrated into Qt Designer, greatly simplifying the process of building database applications and using data aware widgets.

Other major new features include a plugin architecture. You can use your own and third party plugins your own applications. The Unicode support of Qt 2.x has been greatly enhanced, it now includes full support for scripts written from right to left (e.g. Arabic and Hebrew) and also provides improved support for Asian languages.

Many new classes have been added to the Qt Library. Amongst them are classes that provide a docking architecture (QDockArea/QDockWindow), a powerful rich text editor (QTextEdit), a class to store and access application settings (QSettings) and a class to create and communicate with processes (QProcess).

Apart from the changes in the library itself a lot has been done to make the development of Qt applications with Qt 3.0 even easier than before. Two new applications have been added: Qt Linguist is a tool to help you translate your application into different languages; Qt Assistant is an easy to use help browser for the Qt documentation that supports bookmarks and can search by keyword.

Another change concerns the Qt build system, which has been reworked to make it a lot easier to port Qt to new platforms. You can use this platform independent build system for your own applications.

The Qt Library

A large number of new features has been added to Qt 3.0. The following list gives an overview of the most important new and changed aspects of the Qt library. A full list of every new method follows the overview.

Database support

One of the major new features in Qt 3.0 is the SQL module that provides multiplatform access to SQL databases, making database application programming with Qt seamless and portable. The API, built with standard SQL, is database-neutral and software development is independent of the underlying database.

A collection of tightly focused C++ classes are provided to give the programmer direct access to SQL databases. Developers can send raw SQL to the database server or have the Qt SQL classes generate SQL queries automatically. Drivers for Oracle, PostgreSQL, MySQL and ODBC are available and writing new drivers is straightforward.

Tying the results of SQL queries to GUI components is fully supported by Qt's SQL widgets. These classes include a tabular data widget (for spreadsheet-like data presentation with in-place editing), a form-based data browser (which provides data navigation and edit functions) and a form-based data viewer (which provides read-only forms). This framework can be extended by using custom field editors, allowing for example, a data table to use custom widgets for in-place editing. The SQL module fully supports Qt's signal/slots mechanism, making it easy for developers to include their own data validation and auditing code.

Qt Designer fully supports Qt's SQL module. All SQL widgets can be laid out within Qt Designer, and relationships can be established between controls visually. Many interactions can be defined purely in terms of Qt's signals/slots mechanism directly in Qt Designer.

Plugins

The QLibrary class provides a platform independent wrapper for runtime loading of shared libraries. QPluginManager makes it trivial to implement plugin support in applications. The Qt library is able to load additional styles, database drivers and text codecs from plugins.

Qt Designer supports custom widgets in plugins, and will use the widgets both when designing and previewing forms.

See the plugins documentation.

Rich text engine and editor

The rich text engine originally introduced in Qt 2.0 has been further optimized and extended to support editing. It allows editing formatted text with different fonts, colors, paragraph styles, tables and images. The editor supports different word wrap modes, command-based undo/redo, multiple selections, drag and drop, and many other features. The new QTextEdit engine is highly optimized for proccesing and displaying large documents quickly and efficiently.

Unicode

Apart from the rich text engine, another new feature of Qt 3.0 that relates to text handling is the greatly improved Unicode support. Qt 3.0 includes an implementation of the bidirectional algorithm (BiDi) as defined in the Unicode standard and a shaping engine for Arabic, which gives full native language support to Arabic and Hebrew speaking people. At the same time the support for Asian languages has been greatly enhanced.

The support is almost transparent for the developer using Qt to develop their applications. This means that developers who developed applications using Qt 2.x will automatically gain the full support for these languages when switching to Qt 3.0. Developers can rely on their application to work for people using writing systems different from Latin1, without having to worry about the complexities involved with these scripts, as Qt takes care of this automatically.

Docked and Floating Windows

Qt 3.0 introduces the concept of Dock Windows and Dock Areas. Dock windows are widgets, that can be attached to, and detached from, dock areas. The commonest kind of dock window is a tool bar. Any number of dock windows may be placed in a dock area. A main window can have dock areas, for example, QMainWindow provides four dock areas (top, left, bottom, right) by default. The user can freely move dock windows and place them at a convenient place in a dock area, or drag them out of the application and have them float freely as top level windows in their own right. Dock windows can also be minimized or hidden.

For developers, dock windows behave just like ordinary widgets. QToolbar for example is now a specialized subclass of a dock window. The API of QMainWindow and QToolBar is source compatible with Qt 2.x, so existing code which uses these classes will continue to work.

Regular Expressions

Qt has always provided regular expression support, but that support was pretty much limited to what was required in common GUI control elements such as file dialogs. Qt 3.0 introduces a new regular expression engine, QRegExp, that supports most of Perl's regex features and is Unicode based. The most useful additions are support for parentheses (capturing and non-capturing) and backreferences.

Storing application settings

Most programs will need to store some settings between runs, for example, user selected fonts, colors and other preferences, or a list of recently used files. The new QSettings class provides a platform independent way to achieve this goal. The API makes it easy to store and retrieve most of the basic data types used in Qt (such as basic C++ types, strings, lists, colors, etc). The class uses the registry on the Windows platform and traditional resource files on Unix.

Creating and controlling other processes

QProcess is a class that allows you to start other programs from within a Qt application in a platform independent manner. It gives you full control over the started program, for example you can redirect the input and output of console applications.

Accessibility

Accessibility means making software usable and accessible to a wide range of users, including those with disabilities. In Qt 3.0, most widgets provide accessibility information for assistive tools that can be used by a wide range of disabled users. Qt standard widgets like buttons or range controls are fully supported. Support for complex widgets, like e.g. QListView, is in development. Existing applications that make use of standard widgets will become accessible just by using Qt 3.0.

Qt uses the Active Accessibility infrastructure on Windows, and needs the MSAA SDK, which is part of most platform SDKs. With improving standardization of accessibility on other platforms, Qt will support assistive technologies on other systems, too.

XML Improvements

The XML framework introduced in Qt 2.2 has been vastly improved. Qt 2.2 already supported level 1 of the Document Object Model (DOM), a W3C standard for accessing and modifying XML documents. Qt 3.0 has added support for DOM Level 2 and XML namespaces.

The XML parser has been extended to allow incremental parsing of XML documents. This allows you to start parsing the document directly after the first parts of the data have arrived, and to continue whenever new data is available. This is especially useful if the XML document is read from a slow source, e.g. over the network, as it allows the application to start working on the data at a very early stage.

SVG support

SVG is a W3C standard for "Scalable Vector Graphics". Qt 3.0's XML support means that QPicture can optionally generate and import static SVG documents. All the SVG features that have an equivalent in QPainter are supported.

Multihead support

Many professional applications, such as DTP and CAD software, are able to display data on two or more monitors. In Qt 3.0 the QDesktopWidget class provides the application with runtime information about the number and geometry of the desktops on the different monitors and such allows applications to efficiently use a multi-monitor setup.

The virtual desktop of Mac OS X, Windows 98, and 2000 is supported, as well as the traditional multi-screen and the newer Xinerama multihead setups on X11.

X11 specific enhancements

Qt 3.0 now complies with the NET WM Specification, recently adopted by KDE 2.0. This allows easy integration and proper execution with desktop environments that support the NET WM specification.

The font handling on X11 has undergone major changes. QFont no longer has a one-to-one relation with window system fonts. QFont is now a logical font that can load multiple window system fonts to simplify Unicode text display. This completely removes the burden of changing/setting fonts for a specific locale/language from the programmer. For end-users, any font can be used in any locale. For example, a user in Norway will be able to see Korean text without having to set their locale to Korean.

Qt 3.0 also supports the new render extension recently added to XFree86. This adds support for anti aliased text and pixmaps with alpha channel (semi transparency) on the systems that support the rendering extension (at the moment XFree 4.0.3 and later).

Printing

Printing support has been enhanced on all platforms. The QPrinter class now supports setting a virtual resolution for the painting process. This makes WYSIWYG printing trivial, and also allows you to take full advantage of the high resolution of a printer when painting on it.

The postscript driver built into Qt and used on Unix has been greatly enhanced. It supports the embedding of true/open type and type1 fonts into the document, and can correctly handle and display Unicode. Support for fonts built into the printer has been enhanced and Qt now knows about the most common printer fonts used for Asian languages.

QHttp

This class provides a simple interface for HTTP downloads and uploads.

Compatibility with the Standard Template Library (STL)

Support for the C++ Standard Template Library has been added to the Qt Template Library (QTL). The QTL classes now contain appropriate copy constructors and typedefs so that they can be freely mixed with other STL containers and algorithms. In addition, new member functions have been added to QTL template classes which correspond to STL-style naming conventions (e.g., push_back()).

Qt Designer

Qt Designer was a pure dialog editor in Qt 2.2 but has now been extended to provide the full functionality of a GUI design tool.

This includes the ability to lay out main windows with menus and toolbars. Actions can be edited within Qt Designer and then plugged into toolbars and menu bars via drag and drop. Splitters can now be used in a way similar to layouts to group widgets horizontally or vertically.

In Qt 2.2, many of the dialogs created by Qt Designer had to be subclassed to implement functionality beyond the predefined signal and slot connections. Whilst the subclassing approach is still fully supported, Qt Designer now offers an alternative: a plugin for editing slots. The editor offers features such as syntax highlighting, completion, parentheses matching and incremental search.

The functionality of Qt Designer can now be extended via plugins. Using Qt Designer's interface or by implementing one of the provided interfaces in a plugin, a two way communication between plugin and Qt Designer can be established. This functionality is used to implement plugins for custom widgets, so that they can be used as real widgets inside the designer.

Basic support for project management has been added. This allows you to read and edit *.pro files, add and remove files to/from the project and do some global operations on the project. You can now open the project file and have one-click access to all the *.ui forms in the project.

In addition to generating code via uic, Qt Designer now supports the dynamic creation of widgets directly from XML user interface description files (*.ui files) at runtime. This eliminates the need of recompiling your application when the GUI changes, and could be used to enable your customers to do their own customizations. Technically, the feature is provided by a new class, QWidgetFactory in the QResource library.

Qt Linguist

Qt Linguist is a GUI utility to support translating the user-visible text in applications written with Qt. It comes with two command-line tools: lupdate and lrelease.

Translation of a Qt application is a three-step process:

  • Run lupdate to extract user-visible text from the C++ source code of the Qt application, resulting in a translation source file (a *.ts file).
  • Provide translations for the source texts in the *.ts file using Qt Linguist.
  • Run lrelease to obtain a light-weight message file (a *.qm file) from the *.ts file, which provides very fast lookup for released applications.

Qt Linguist is a tool suitable for use by translators. Each user-visible (source) text is characterized by the text itself, a context (usually the name of the C++ class containing the text), and an optional comment to help the translator. The C++ class name will usually be the name of the relevant dialog, and the comment will often contain instructions that describe how to navigate to the relevant dialog.

You can create phrase books for Qt Linguist to provide common translations to help ensure consistency and to speed up the translation process. Whenever a translator navigates to a new text to translate, Qt Linguist uses an intelligent algorithm to provide a list of possible translations: the list is composed of relevant text from any open phrase books and also from identical or similar text that has already been translated.

Once a translation is complete it can be marked as "done"; such translations are included in the *.qm file. Text that has not been "done" is included in the *.qm file in its original form. Although Qt Linguist is a GUI application with dock windows and mouse control, toolbars, etc., it has a full set of keyboard shortcuts to make translation as fast and efficient as possible.

When the Qt application that you're developing evolves (e.g. from version 1.0 to version 1.1), the utility lupdate merges the source texts from the new version with the previous translation source file, reusing existing translations. In some typical cases, lupdate may suggest translations. These translations are marked as unfinished, so you can easily find and check them.

Qt Assistant

Thanks to the positive feedback we received about the help system built into Qt Designer, we decided to offer this part as a separate application called Qt Assistant. Qt Assistant can be used to browse the Qt class documentation as well as the manuals for Qt Designer and Qt Linguist. It offers index searching, a contents overview, bookmarks history and incremental search. Qt Assistant is used by both Qt Designer and Qt Linguist for browsing their help documentation.

qmake

To ease portability we now provide the qmake utility to replace tmake. QMake is a C++ version of tmake which offers additional functionallity that is difficult to reproduce in tmake. Trolltech uses qmake in its build system for Qt and related products and we have released it as free software.


Porting to Qt 3.x

This document describes porting applications from Qt 2.x to Qt 3.x.

If you haven't yet made the decision about porting, or are unsure about whether it is worth it, take a look at the key features offered by Qt 3.x.

The Qt 3.x series is not binary compatible with the 2.x series. This means programs compiled for Qt 2.x must be recompiled to work with Qt 3.x. Qt 3.x is also not completely source compatible with 2.x, however all points of incompatibility cause compiler errors or run-time messages (rather than mysterious results). Qt 3.x includes many additional features and discards obsolete functionality. Porting from Qt 2.x to Qt 3.x is straightforward, and once completed makes the considerable additional power and flexibility of Qt 3.x available for use in your applications.

To port code from Qt 2.x to Qt 3.x:

  1. Briefly read the porting notes below to get an idea of what to expect.
  2. Be sure your code compiles and runs well on all your target platforms with Qt 2.x.
  3. Recompile with Qt 3.x. For each error, search below for related identifiers (e.g. function names, class names). This document mentions all relevant identifiers to help you get the information you need at the cost of being a little verbose.
  4. If you get stuck, ask on the qt-interest mailing list, or Trolltech Technical Support if you're a registered licensee.

Table of contents:

  • Link errors on Windows
  • Header file inclusion changes
  • Namespace
  • Removed Functions
  • Obsoleted Functions
  • Collection Class Renaming
  • QButtonGroup
  • QDate
  • QFont
  • QInputDialog
  • QLayout and Other Abstract Layout Classes
  • QMultiLineEdit
  • QPrinter
  • QRegExp
    • New special characters
    • QRegExp::operator=()
    • QRegExp::match()
    • QRegExp::find()
    • QString::findRev() and QString::contains()
    • QString::replace()
  • QSemiModal
  • QSortedList
  • QTableView
  • QToolButton
  • QTextStream
  • QTranslator
  • QWidget
  • QXml Classes
    • QXmlInputSource
    • QXmlLocator
  • Asynchronous I/O Classes
  • Transparent widgets
  • Bezier Curves
  • Locale-aware String Comparisons in QIconView, QListBox, QListView and QTable

Link errors on Windows

On Windows, originally in Qt 2.x, the default configuration of the Qt library is static. If you just use the default configuration you don't need to set certain preprocessor defines. In Qt 3.0, the default configuration of the Qt library is to build it as a shared library, therefore the preprocessor define QT_DLL is needed.

If you use tmake with Qt 2.x, and now use qmake with Qt 3.x, then the cause of the problem is with the project file. In the project file, there is usually line that looks like:

CONFIG = ...

this should be changed to

CONFIG += ...

so that qmake can look at the configuration that Qt was built with and set any relevant preprocessor defines in the makefile.

Header file inclusion changes

Qt 3.x remove some unnecessary nested #include directives from header files. This speeds up compilation when you don't need those nested header files. But in some cases you will find you need to add an extra #include to your files.

For example, if you get a message about QStringList or its functions not being defined, then add #include <qstringlist.h> at the top of the file giving the error.

Header files that you might need to add #include directives for include:

  • <qcursor.h>
  • <qpainter.h>
  • <qpen.h>
  • <qstringlist.h>
  • <qregexp.h>
  • <qstrlist.h>
  • <qstyle.h>
  • <qvaluelist.h>

Namespace

Qt 3.x is namespace clean. A few global identifiers that had been left in Qt 2.x have been discarded.

Enumeration Qt::CursorShape and its values are now part of the special Qt class defined in qnamespace.h. If you get compilation errors about these being missing (unlikely, since most of your code will be in classes that inherit from the Qt namespace class), then apply the following changes:

  • QCursorShape becomes Qt::CursorShape
  • ArrowCursor becomes Qt::ArrowCursor
  • UpArrowCursor becomes Qt::UpArrowCursor
  • CrossCursor becomes Qt::CrossCursor
  • WaitCursor becomes Qt::WaitCursor
  • IbeamCursor becomes Qt::IbeamCursor
  • SizeVerCursor becomes Qt::SizeVerCursor
  • SizeHorCursor becomes Qt::SizeHorCursor
  • SizeBDiagCursor becomes Qt::SizeBDiagCursor
  • SizeFDiagCursor becomes Qt::SizeFDiagCursor
  • SizeAllCursor becomes Qt::SizeAllCursor
  • BlankCursor becomes Qt::BlankCursor
  • SplitVCursor becomes Qt::SplitVCursor
  • SplitHCursor becomes Qt::SplitHCursor
  • PointingHandCursor becomes Qt::PointingHandCursor
  • BitmapCursor becomes Qt::BitmapCursor

The names of some debugging macro variables have been changed. We have tried not to break source compatibility as much as possible. If you observe error messages on the UNIX console or the Windows debugging stream that were previously disabled, please check these macro variables:

  • DEBUG becomes QT_DEBUG
  • NO_DEBUG becomes QT_NO_DEBUG
  • NO_CHECK becomes QT_NO_CHECK
  • CHECK_STATE becomes QT_CHECK_STATE
  • CHECK_RANGE becomes QT_CHECK_RANGE
  • CHECK_NULL becomes QT_CHECK_NULL
  • CHECK_MATH becomes QT_CHECK_MATH

The name of some debugging macro functions has been changed as well but source compatibility should not be affected if the macro variable QT_CLEAN_NAMESPACE is not defined:

  • ASSERT becomes Q_ASSERT
  • CHECK_PTR becomes Q_CHECK_PTR

For the record, undocumented macro variables that are not part of the API have been changed:

  • _OS_*_ becomes Q_OS_*
  • _WS_*_ becomes Q_WS_*
  • _CC_*_ becomes Q_CC_*

Removed Functions

All these functions have been removed in Qt 3.x:

  • QFont::charSet()
  • QFont::setCharSet()
  • QMenuBar::setActItem()
  • QMenuBar::setWindowsAltMode()
  • QPainter::drawQuadBezier()
  • QPointArray::quadBezier()
  • QRegExp::find()
  • QSpinBox::downButton()
  • QSpinBox::upButton()
  • QString::basicDirection()
  • QString::visual()
  • QStyle::set...() functions
  • QWidget::setFontPropagation()
  • QWidget::setPalettePropagation()

Also, to avoid conflicts with <iostream>, the following three global functions have been renamed:

  • setw() (renamed qSetW())
  • setfill() (renamed qSetFill())
  • setprecision() (renamed qSetPrecision())

Obsoleted Functions

The following functions have been obsoleted in Qt 3.0. The documentation of each of these functions should explain how to replace them in Qt 3.0.

Warning: It is best to consult http://doc.trolltech.com/3.0/ rather than the documentation supplied with Qt to obtain the latest information regarding obsolete functions and how to replace them in new code.

  • QAccel::keyToString( QKeySequence k )
  • QAccel::stringToKey( const QString & s )
  • QActionGroup::insert( QAction *a )
  • QButton::autoResize() const
  • QButton::setAutoResize( bool )
  • QCanvasItem::active() const
  • QCanvasItem::enabled() const
  • QCanvasItem::selected() const
  • QCanvasItem::visible() const
  • QCanvasPixmapArray::QCanvasPixmapArray( QPtrList<QPixmap> list, QPtrList<QPoint> hotspots )
  • QCanvasPixmapArray::operator!()
  • QColorGroup::QColorGroup( const QColor & foreground, const QColor & background, const QColor & light, const QColor & dark, const QColor & mid, const QColor & text, const QColor & base )
  • QComboBox::autoResize() const
  • QComboBox::setAutoResize( bool )
  • QDate::dayName( int weekday )
  • QDate::monthName( int month )
  • QDir::encodedEntryList( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • QDir::encodedEntryList( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • QDockWindow::isHorizontalStretchable() const
  • QDockWindow::isVerticalStretchable() const
  • QDockWindow::setHorizontalStretchable( bool b )
  • QDockWindow::setVerticalStretchable( bool b )
  • QFont::defaultFont()
  • QFont::setDefaultFont( const QFont & f )
  • QFont::setPixelSizeFloat( float pixelSize )
  • QFontDatabase::bold( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::families( bool ) const
  • QFontDatabase::font( const QString & familyName, const QString & style, int pointSize, const QString & )
  • QFontDatabase::isBitmapScalable( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::isFixedPitch( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::isScalable( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::isSmoothlyScalable( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::italic( const QString & family, const QString & style, const QString & ) const
  • QFontDatabase::pointSizes( const QString & family, const QString & style, const QString & )
  • QFontDatabase::smoothSizes( const QString & family, const QString & style, const QString & )
  • QFontDatabase::styles( const QString & family, const QString & ) const
  • QFontDatabase::weight( const QString & family, const QString & style, const QString & ) const
  • QLabel::autoResize() const
  • QLabel::setAutoResize( bool enable )
  • QLineEdit::cursorLeft( bool mark, int steps = 1 )
  • QLineEdit::cursorRight( bool mark, int steps = 1 )
  • QLineEdit::hasMarkedText() const
  • QLineEdit::markedText() const
  • QLineEdit::repaintArea( int, int )
  • QListBox::cellHeight( int i ) const
  • QListBox::cellHeight() const
  • QListBox::cellWidth() const
  • QListBox::findItem( int yPos ) const
  • QListBox::inSort( const QListBoxItem *lbi )
  • QListBox::inSort( const QString & text )
  • QListBox::itemYPos( int index, int *yPos ) const
  • QListBox::numCols() const
  • QListBox::totalHeight() const
  • QListBox::totalWidth() const
  • QListBoxItem::current() const
  • QListBoxItem::selected() const
  • QListView::removeItem( QListViewItem *item )
  • QListViewItem::removeItem( QListViewItem *item )
  • QMainWindow::addToolBar( QDockWindow *, Dock = DockTop, bool newLine = FALSE )
  • QMainWindow::addToolBar( QDockWindow *, const QString & label, Dock = DockTop, bool newLine = FALSE )
  • QMainWindow::lineUpToolBars( bool keepNewLines = FALSE )
  • QMainWindow::moveToolBar( QDockWindow *, Dock = DockTop )
  • QMainWindow::moveToolBar( QDockWindow *, Dock, bool nl, int index, int extraOffset = -1 )
  • QMainWindow::removeToolBar( QDockWindow *)
  • QMainWindow::setToolBarsMovable( bool )
  • QMainWindow::toolBarPositionChanged( QToolBar *)
  • QMainWindow::toolBarsMovable() const
  • QMessageBox::message( const QString & caption, const QString & text, const QString & buttonText = QString::null, QWidget *parent = 0, const char *= 0 )
  • QMessageBox::query( const QString & caption, const QString & text, const QString & yesButtonText = QString::null, const QString & noButtonText = QString::null, QWidget *parent = 0, const char *= 0 )
  • QMessageBox::standardIcon( Icon icon, GUIStyle style )
  • QPalette::normal()
  • QRegExp::match( const QString & str, int index = 0, int *len = 0, bool indexIsStart = TRUE ) const
  • QScrollView::childIsVisible( QWidget *child )
  • QScrollView::showChild( QWidget *child, bool show = TRUE )
  • QSignal::block( bool b )
  • QSignal::isBlocked() const
  • QSignal::parameter() const
  • QSignal::setParameter( int value )
  • QSimpleRichText::draw( QPainter *p, int x, int y, const QRegion & clipRegion, const QColorGroup & cg, const QBrush *paper = 0 ) const
  • QString::ascii() const
  • QString::data() const
  • QString::setExpand( uint index, QChar c )
  • QStyle::defaultFrameWidth() const
  • QStyle::scrollBarExtent() const
  • QStyle::tabbarMetrics( const QWidget *t, int & hf, int & vf, int & ov ) const
  • QTabDialog::isTabEnabled( const char *name ) const
  • QTabDialog::selected( const QString & )
  • QTabDialog::selected( const QString & tabLabel )
  • QTabDialog::setTabEnabled( const char *name, bool enable )
  • QTextStream::QTextStream( QString & str, int filemode )
  • QToolBar::QToolBar( const QString & label, QMainWindow *, ToolBarDock = DockTop, bool newLine = FALSE, const char *name = 0 )
  • QToolButton::iconSet( bool on ) const
  • QToolButton::offIconSet() const
  • QToolButton::onIconSet() const
  • QToolButton::setIconSet( const QIconSet & set, bool on )
  • QToolButton::setOffIconSet( const QIconSet & )
  • QToolButton::setOnIconSet( const QIconSet & )
  • QToolTip::enabled()
  • QToolTip::setEnabled( bool enable )
  • QTranslator::find( const char *context, const char *sourceText, const char *comment = 0 ) const
  • QTranslator::insert( const char *context, const char *sourceText, const QString & translation )
  • QTranslator::remove( const char *context, const char *sourceText )
  • QUriDrag::setFilenames( const QStringList & fnames )
  • QWidget::backgroundColor() const
  • QWidget::backgroundPixmap() const
  • QWidget::iconify()
  • QWidget::setBackgroundColor( const QColor & c )
  • QWidget::setBackgroundPixmap( const QPixmap & pm )
  • QWidget::setFont( const QFont & f, bool )
  • QWidget::setPalette( const QPalette & p, bool )
  • QWizard::setFinish( QWidget *, bool )
  • QXmlInputSource::QXmlInputSource( QFile & file )
  • QXmlInputSource::QXmlInputSource( QTextStream & stream )
  • QXmlReader::parse( const QXmlInputSource & input )

Additionally, these preprocessor directives have been removed:

  • #define strlen qstrlen
  • #define strcpy qstrcpy
  • #define strcmp qstrcmp
  • #define strncmp qstrncmp
  • #define stricmp qstricmp
  • #define strnicmp qstrnicmp

See the changes-3.0.0 document for an explanation of why this had to be done. You might have been relying on the non-portable and unpredictable behavior resulting from these directives. We strongly recommend that you either make use of the safe qstr* variants directly or ensure that no 0 pointer is passed to the standard C functions in your code base.

Collection Class Renaming

The classes QArray, QCollection, QList, QListIterator, QQueue, QStack and QVector have been renamed. To ease porting, the old names and the old header-file names are still supported.

Old Name | New Name | New Header File
QArray | QMemArray | <qmemarray.h>
QCollection | QPtrCollection | <qptrcollection.h>
QList | QPtrList | <qptrlist.h>
QListIterator | QPtrListIterator | <qptrlist.h>
QQueue | QPtrQueue | <qptrqueue.h>
QStack | QPtrStack | <qptrstack.h>
QVector | QPtrVector | <qptrvector.h>

QButtonGroup

In Qt 2.x, the function QButtonGroup::selected() returns the selected radio button (QRadioButton). In Qt 3.0, it returns the selected toggle button (QButton::toggleButton), a more general concept. This might affect programs that use QButtonGroups that contain a mixture of radio buttons and non-radio (e.g. QCheckBox) toggle buttons.

QDate

Two QDate member functions that were virtual in Qt 2.0 are not virtual in Qt 3.0. This is only relevant if you subclassed QDate and reimplemented these functions:

  • QString QDate::monthName( int month ) const
  • QString QDate::dayName( int weekday ) const

In addition to no longer being virtual, QDate::monthName() and QDate::dayName() have been renamed QDate::shortMonthName() and QDate::shortDayName() and have been made static (as they should had been in the first place). The old names are still provided for source compatibility.

QFont

The internals of QFont have changed significantly between Qt 2.2 and Qt 3.0, to give better Unicode support and to make developing internationalized applications easier. The original API has been preserved with minimal changes. The CharSet enum and its related functions have disappeared. This is because Qt now handles all charset related issues internally, and removes this burden from the developer.

If you used the CharSet enum or its related functions, e.g QFont::charSet() or QFont::setCharSet(), just remove them from your code. There are a few functions that took a QFont::CharSet as a parameter; in these cases simply remove the charset from the parameter list.

QInputDialog

The two static getText(...) methods in QInputDialog have been merged. The echo parameter is the third parameter and defaults to QLineEdit::Normal.

If you used calls to QInputDialog::getText(...) that provided more than the first two required parameters you will must add a value for the echo parameter.

QLayout and Other Abstract Layout Classes

The definitions of QGLayoutIterator, QLayout, QLayoutItem, QLayoutIterator, QSpacerItem and QWidgetItem have been moved from <qabstractlayout.h> to <qlayout.h>. The header <qabstractlayout.h> now includes <qlayout.h> for compatibility. It might be removed in a future version.

QMultiLineEdit

The QMultiLineEdit was a simple editor widget in previous Qt versions. Since Qt 3.0 includes a new richtext engine, which also supports editing, QMultiLineEdit is obsolete. For the sake of compatibility QMultiLineEdit is still provided. It is now a subclass of QTextEdit which wraps the old QMultiLineEdit so that it is mostly source compatible to keep old applications working.

For new applications and when maintaining existing applications we recommend that you use QTextEdit instead of QMultiLineEdit wherever possible.

Although most of the old QMultiLineEdit API is still available, there is one important difference. The old QMultiLineEdit operated in terms of lines, whereas QTextEdit operates in terms of paragraphs. This is because lines change all the time during wordwrap, whereas paragraphs remain paragraphs. The consequence of this change is that functions which previously operated on lines, e.g. numLines(), textLine(), etc., now work on paragraphs.

Also the function getString() has been removed since it published the internal data structure.

In most cases, applications that used QMultiLineEdit will continue to work without problems. Applications that worked in terms of lines may require some porting.

The source code for the old 2.x version of QMultiLineEdit can be found in $QTDIR/src/attic/qtmultilineedit.h/cpp. Note that the class has been renamed to QtMultiLineEdit to avoid name clashes. If you really need to keep compatibility with the old QMultiLineEdit, simply include this class in your project and rename QMultiLineEdit to QtMultiLineEdit throughout.

QPrinter

QPrinter has undergone some changes, to make it more flexible and to ensure it has the same runtime behaviour on both Unix and Windows. In 2.x, QPrinter behaved differently on Windows and Unix, when using view transformations on the QPainter. This has changed now, and QPrinter behaves consistently across all platforms. A compatibilty mode has been added that forces the old behaviour, to ease porting from Qt 2.x to Qt 3.x. This compatibilty mode can be enabled by passing the QPrinter::Compatible flag to the QPrinter constructor.

On X11, QPrinter used to generate encapsulated postscript when fullPage() was TRUE and only one page was printed. This does not happen by default anymore, providing a more consistent printing output.

QRegExp

The QRegExp class has been rewritten to support many of the features of Perl regular expressions. Both the regular expression syntax and the QRegExp interface have been modified.

Be also aware that <qregexp.h> is no longer included automatically when you include <qstringlist.h>. See above for details.

New special characters

There are five new special characters: (, ), {, | and } (parentheses, braces and pipe). When porting old regular expressions, you must add \ (backslash) in front of any of these (actually, \\ in C++ strings), unless it is already there.

Example: Old code like

    QRegExp rx( "([0-9|]*\\)" );        // works in Qt 2.x
should be converted into
    QRegExp rx( "\\([0-9\\|]*\\)" );      // works in Qt 2.x and 3.x
(Within character classes, the backslash is not necessary in front of certain characters, e.g. |, but it doesn't hurt.)

Wildcard patterns need no conversion. Here are two examples:

    QRegExp wild( "(*.*)" );
    wild.setWildcard( TRUE );

    // TRUE as third argument means wildcard
    QRegExp wild( "(*.*)", FALSE, TRUE );
However, when they are used, make sure to use QRegExp::exactMatch() rather than the obsolete QRegExp::match(). QRegExp::match(), like QRegExp::find(), tries to find a match somewhere in the target string, while QRegExp::exactMatch() tries to match the whole target string.

QRegExp::operator=()

This function has been replaced by QRegExp::setPattern() in Qt 2.2. Old code such as

    QRegExp rx( "alpha" );
    rx.setCaseSensitive( FALSE );
    rx.setWildcard( TRUE );
    rx = "beta";
still compiles with Qt 3, but produces a different result (the case sensitivity and wildcard options are forgotten). This way,
    rx = "beta";
is the same as
    rx = QRegExp( "beta" );
which is what one expects.

QRegExp::match()

The following function is now obsolete, as it has an unwieldy parameter list and was poorly named:

  • bool QRegExp::match( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const
It will be removed in a future version of Qt. Its documentation explains how to replace it.

QRegExp::find()

This function was removed, after a brief appearance in Qt 2.2. Its name clashed with QString::find(). Use QRegExp::search() or QString::find() instead.

QString::findRev() and QString::contains()

QString::findRev()'s and QString::contains()'s semantics have changed between 2.0 and 3.0 to be more consistent with the other overloads.

For example,

    QString( "" ).contains( QRegExp("") )
returns 1 in Qt 2.0; it returns 0 in Qt 3.0. Also, "^" now really means start of input, so
    QString( "Heisan Hoppsan" ).contains( QRegExp("^.*$") )
returns 1, not 13 or 14.

This change affect very few existing programs.

QString::replace()

With Qt 1.0 and 2.0, a QString is converted implicitly into a QRegExp as the first argument to QString::replace():

    QString text = fetch_it_from_somewhere();
    text.replace( QString("[A-Z]+"), "" );
With Qt 3.0, the compiler gives an error. The solution is to use a QRegExp cast:
    text.replace( QRegExp("[A-Z]+"), "" );
This change makes it possible to introduce a QString::replace(QString, QString) overload in a future version of Qt without breaking source compatibility.

QSemiModal

The QSemiModal class is now obsolete. You should call show() on a modal dialog instead.

QSortedList

The QSortedList class is now obsolete. Consider using a QDict, a QMap or a plain QPtrList instead.

QTableView

The QTableView class has been obsoleted and is no longer a part of the Qt API. Either use the powerful QTable class or the simplistic QGridView in any new code you create. If you really need the old table view for compatibility you can find it in $QTDIR/src/attic/qttableview.{cpp,h}. Note that the class has been renamed from QTableView to QtTableView to avoid name clashes. To use it, simply include it in your project and rename QTableView to QtTableView throughout.

QToolButton

The QToolButton class used to distinguish between "on" and "off" icons. In 3.0, this mechanism was moved into the QIconSet class (see QIconSet::State).

The old QToolButton::onIconSet and QToolButton::offIconSet properties are still provided so that old source will compile, but their semantics have changed: they are now synonyms for QToolButton::iconSet. If you used that distinction in Qt 2.x, you will need to adjust your code to use the QIconSet On/Off mechanism.

Likewise, the on parameter of these two functions is now ignored:

  • void QToolButton::setIconSet ( const QIconSet & set, bool on )
  • QIconSet QToolButton::iconSet ( bool on ) const

These functions are only provided for ease of porting. New code should use the following instead:

  • void QToolButton::setIconSet( const QIconSet & set )
  • QIconSet QToolButton::iconSet() const

Finally, this function is no longer virtual:

  • void QToolButton::setIconSet( const QIconSet & set, bool on )

If you have a class that inherits QToolButton and that reimplements QToolButton::setIconSet(), you should make the signature of the reimplementation agree with the new QToolButton::setIconSet(), a virtual function.

QTextStream

The global QTextStream manipulators setw(), setfill() and setprecison() were renamed to qSetW(), qSetFill() and qSetPrecision() to avoid conflicts with <iostream.h>. If you used them, you must rename the occurrences to the new names.

QTranslator

The QTranslator class was extended in Qt 2.2, and these extensions lead to a new interface. This interface is used mainly by translation tools (for example, Qt Linguist). For source compatibility, no member function was effectively removed. The QTranslator documentation points out which functions are obsolete.

This function is no longer virtual:

  • QString QTranslator::find( const char * context, const char * sourceText ) const

If you have a class that inherits QTranslator and which reimplements QTranslator::find(), you should reimplement QTranslator::findMessage() instead. In fact, find() is now defined in terms of findMessage(). By doing the conversion, you will also gain support for translator comments and for any future extensions.

QWidget

 QWidget::backgroundColor(), QWidget::setBackgroundColor(),
QWidget::backgroundPixmap() and QWidget::setBackgroundPixmap() have
often been the source of much confusion in previous releases. Qt 3.0
addresses this by obsoleting these functions and by remplacing them
with eight new functions: QWidget::eraseColor(),
QWidget::setEraseColor(), QWidget::erasePixmap(),
QWidget::setErasePixmap(), QWidget::paletteBackgroundColor(),
QWidget::setPaletteBackgroundColor(),
QWidget::paletteBackgroundPixmap() and
QWidget::setPaletteBackgroundPixmap(). See their documentation for
details.

QXml Classes

QXmlInputSource

The semantics of QXmlInputSource has changed slightly. This change only affects code that parses the same data from the same input source multiple times. In such cases you must call QXmlInputSource::reset() before the second call to QXmlSimpleReader::parse().

So code like

    QXmlInputSource source( &xmlFile );
    QXmlSimpleReader reader;
    ...
    reader.parse( source );
    ...
    reader.parse( source );
must be changed to
    QXmlInputSource source( &xmlFile );
    QXmlSimpleReader reader;
    ...
    reader.parse( source );
    ...
    source.reset();
    reader.parse( source );

QXmlLocator

Due to some internal changes, it was necessary to clean-up the semantics of QXmlLocator: this class is now an abstract class. This shouldn't cause any problems, since programmers usually used the QXmlLocator that was reported by QXmlContentHandler::setDocumentLocator(). If you used this class in some other way, you must adjust your code to use the QXmlLocator that is reported by the QXmlContentHandler::setDocumentLocator() function.

Asynchronous I/O Classes

QASyncIO, QDataSink, QDataSource, QIODeviceSource and QDataPump were used internally in previous versions of Qt, but are not used anymore. They are now obsolete.

Transparent widgets

In Qt 2.x, the AutoMask property was used to obtain a transparent-looking widget. In general, this approach is slow and processor hungry. Qt 3.0 uses the BackgroundOrigin which provides vastly improved performance and more flexibility in most cases. The few classes for which the AutoMask property is still the best approach are QCheckBox, QComboBox, QPushButton, QRadioButton and QTabWidget.

Bezier Curves

The function names for Bezier curves in QPainter and QPointArray have been corrected. They now properly reflect their cubic form instead of a quadratic one. If you have been using either QPainter::drawQuadBezier() or QPointArray::quadBezier() you must replace these calls with

  • void QPainter::drawCubicBezier( const QPointArray &, int index=0 ) and
  • QPointArray QPointArray::cubicBezier() const
respectively. Neither the arguments nor the resulting curve have changed.

Locale-aware String Comparisons in QIconView, QListBox, QListView and QTable

In Qt 2.x, QString only provided string comparisons using the Unicode values of the characters of a string. This is efficient and reliable, but it is not the appropriate order for most languages. For example, French users expect 'é' (e acute) to be treated essentially as 'e' and not put after 'z'.

In Qt 3.0, QString::localeAwareCompare() implements locale aware string comparisions on certain platforms. The classes QIconView, QListBox, QListView and QTable now use QString::localeAwareCompare() instead of QString::compare(). If you want to control the behaviour yourself you can always reimplement QIconViewItem::compare(), QListBox::text(), QListViewItem::compare() or QTableItem::key() as appropriate.


Company Information

Trolltech AS is a computer software company. We provide software development tools and libraries, as well as expert consultancy services.

Our flagship product is Qt, the multi-platform, C++ Graphical User Interfaces toolkit. Qt enables you to build professional, efficient, portable and maintainable GUI applications quickly and easily.

Software that makes Sense

Our motto expresses the vision behind our products. We design our products to give our customers the feeling of "this is the way that things were always meant to be".

We know that it is crucial for our customers to have good tools for making good software. Therefore, we do not compromise our demands for superior design and technical quality when we develop our products.

Trolltech is also known for providing top quality technical support to our customers. At Trolltech, support inquiries are handled by the most qualified developers and designers themselves.

History

Trolltech was founded in 1994. The core team of designers at Trolltech started developing Qt in 1992, and since then Qt has steadily expanded and improved. The first commercial version of Qt was in 1995. Since then, Trolltech has experienced rapid growth, and Qt is currently used in hundreds of successful software development projects world wide.

Contact Information

Email
 | info@trolltech.com |  | sales@trolltech.com
 |  | General inquiries and questions. Please check the FAQ to see if your question is already answered there. |  | Inquires related to purchasing, pricing and availability of Trolltech products
 | www@trolltech.com |  | qt-bugs@trolltech.com
 |  | Comments about our web pages |  | For bug reports. Please check the Platform Notes and FAQ to see if the issue is already solved.
 | Note that Trolltech uses the RBL and RSS databases to cut down on spam. If your mail server is listed, you will regrettably not be able to send us mail. The MAPS TSI pages provide information about how to secure your server.
Norway Office
 | Telephone |  | Street/Mail Address
 |  | General inquiries: +47 21 60 48 00 |  | Waldemar Thranes gate 98 N-0175 Oslo Norway
 | Telefax
 |  | All inquiries: +47 21 60 48 01
USA Office
 | Telephone |  | Street/Mail Address
 |  | General inquiries: +1 408 567 0212 |  | 3350 Scott Blvd. Building 55, Suite 2 Santa Clara CA 95054 USA
 | Telefax
 |  | All inquiries: +1 408 567 0264


如何报告bug

如果你认为你发现了Qt中的bug，我们很高兴听到这些，这样我们就可以修复它了。

在报告bug之前，请检查我们网站上的FAQ和平台注释，查看一下这个问题是否已经知道。

在你的bug报告中通常应该包含以下信息：

  1. 你的编译器的名称和版本
  2. 你的操作系统的名称和版本
  3. 你所使用的Qt的版本和你在编译时使用的配置选项。

如果你报告的问题只是在运行时可见的，请试着建立一个小的测试程序来显示运行时发生的问题。通常情况下，qt/examples目录下有很多示例程序，你只要对其中一个进行一些小的修改就可以了。

请把bug报告寄到qt-bugs@trolltech.com。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Mailing Lists

Trolltech operates several mailing lists for Qt users including qt-announce, qt-interest and snapshot-users.

See http://www.trolltech.com/developer/mailinglists/.

qt-announce

The subscribers to this mailing list receives all official Trolltech announcements when new versions of Qt and other Trolltech products are released, and other Trolltech announcements of general interest.

To subscribe to the qt-announce mailing list, simply press the button below.

You can also subscribe by sending an email containing just the word subscribe or subscribe your@email.address to qt-announce-request@trolltech.com.

To unsubscribe yourself from the qt-announce mailing list, similarly send an email containing just the word unsubscribe or unsubscribe your@email.address to qt-announce-request@trolltech.com.

qt-interest

This mailing list is a discussion forum for Qt users. Typical traffic is 10 to 20 messages per day.

An archive of the messages from qt-interest is available on the Trolltech web site: Qt Mailing List Archive.

To subscribe to the qt-interest mailing list, send an email containing just the word subscribe or subscribe your@email.address to qt-interest-request@trolltech.com.

To unsubscribe yourself from the qt-interest mailing list, similarly send an email containing just the word unsubscribe or unsubscribe your@email.address to qt-interest-request@trolltech.com.

This list is now available as network news using the NNTP protocol from news://nntp.trolltech.com/trolltech.qt-interest/.

snapshot-users

There is a special mailing list, snapshot-users@trolltech.com, for discussion of Qt snapshot-related issues. To subscribe, send a message containing just the word "subscribe" (without the quotes) to snapshot-users-request@trolltech.com. We encourage you to use this mailing list instead of qt-interest for snapshot-specific issues.

Trolltech does not sell or in any way redistribute the addresses on our mailing lists. We also employ active filtering to ensure the mailing lists are virtually free from spam.


抽象窗口部件类

这些类是抽象窗口部件，它们自己通常是不可用的，但是它们提供了很多它们的子类可以使用的功能。

QButton | 按钮窗口部件的抽象基类，提供了按钮所共有的功能
QCanvas | 可以包含QCanvasItem对象的二维区域
QDialog | 对话窗口的基类
QFrame | 有框架的窗口部件的基类
QGridView | 固定大小栅格的抽象基类
QScrollView | 带有滚动条需要的滚动区域
QWidget | 所有用户界面对象的基类
QWizard | 向导对话框的构架

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Analog Clock

This example displays an analog clock widget.

Header file:

/****************************************************************************
** $Id:  qt/aclock.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef ACLOCK_H
#define ACLOCK_H

#include <qwidget.h>
#include <qdatetime.h>

class AnalogClock : public QWidget              // analog clock widget
{
    Q_OBJECT
public:
    AnalogClock( QWidget *parent=0, const char *name=0 );
    void setAutoMask(bool b);

public slots:
    void setTime( const QTime & t );

protected:
    void updateMask();
    void paintEvent( QPaintEvent *);
    void mousePressEvent( QMouseEvent *);
    void mouseMoveEvent( QMouseEvent *);

private slots:
    void drawClock( QPainter* );
    void        timeout();

private:
    QPoint clickPos;
    QTime       time;
};

#endif // ACLOCK_H

Implementation:

/****************************************************************************
** $Id:  qt/aclock.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "aclock.h"
#include <qtimer.h>
#include <qpainter.h>
#include <qbitmap.h>

//
// Constructs an analog clock widget that uses an internal QTimer.
//

AnalogClock::AnalogClock( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    time = QTime::currentTime();                // get current time
    QTimer *internalTimer = new QTimer( this ); // create internal timer
    connect( internalTimer, SIGNAL(timeout()), SLOT(timeout()) );
    internalTimer->start( 5000 );               // emit signal every 5 seconds
}

void AnalogClock::mousePressEvent( QMouseEvent *e )
{
    if(isTopLevel())
        clickPos = e->pos() + QPoint(geometry().topLeft() - frameGeometry().topLeft());
}

void AnalogClock::mouseMoveEvent( QMouseEvent *e )
{
    if(isTopLevel())
        move( e->globalPos() - clickPos );
}

void AnalogClock::setTime( const QTime & t )
{
    time = t;
    timeout();
}

//
// The QTimer::timeout() signal is received by this slot.
//

void AnalogClock::timeout()
{
    QTime new_time = QTime::currentTime();      // get the current time
    time = time.addSecs( 5 );
    if ( new_time.minute() != time.minute() ) { // minute has changed
        if (autoMask())
            updateMask();
        else
            update();
    }
}

void AnalogClock::paintEvent( QPaintEvent * )
{
    if ( autoMask() )
        return;
    QPainter paint( this );
    paint.setBrush( colorGroup().foreground() );
    drawClock( &paint );
}

// If the clock is transparent, we use updateMask()
// instead of paintEvent()

void AnalogClock::updateMask()  // paint clock mask
{
    QBitmap bm( size() );
    bm.fill( color0 );                  //transparent

    QPainter paint;
    paint.begin( &bm, this );
    paint.setBrush( color1 );           // use non-transparent color
    paint.setPen( color1 );

    drawClock( &paint );

    paint.end();
    setMask( bm );
}

//
// The clock is painted using a 1000x1000 square coordinate system, in
// the a centered square, as big as possible.  The painter's pen and
// brush colors are used.
//
void AnalogClock::drawClock( QPainter *paint )
{
    paint->save();

    paint->setWindow( -500,-500, 1000,1000 );

    QRect v = paint->viewport();
    int d = QMIN( v.width(), v.height() );
    paint->setViewport( v.left() + (v.width()-d)/2,
                        v.top() + (v.height()-d)/2, d, d );

    // time = QTime::currentTime();
    QPointArray pts;

    paint->save();
    paint->rotate( 30*(time.hour()%12-3) + time.minute()/2 );
    pts.setPoints( 4, -20,0,  0,-20, 300,0, 0,20 );
    paint->drawConvexPolygon( pts );
    paint->restore();

    paint->save();
    paint->rotate( (time.minute()-15)*6 );
    pts.setPoints( 4, -10,0, 0,-10, 400,0, 0,10 );
    paint->drawConvexPolygon( pts );
    paint->restore();

    for ( int i=0; i<12; i++ ) {
        paint->drawLine( 440,0, 460,0 );
        paint->rotate( 30 );
    }

    paint->restore();
}

void AnalogClock::setAutoMask(bool b)
{
    if (b)
        setBackgroundMode( PaletteForeground );
    else
        setBackgroundMode( PaletteBackground );
    QWidget::setAutoMask(b);
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "aclock.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    AnalogClock *clock = new AnalogClock;
    if ( argc == 2 && strcmp( argv[1], "-transparent" ) == 0 )
        clock->setAutoMask( TRUE );
    clock->resize( 100, 100 );
    a.setMainWidget( clock );
    clock->setCaption("Qt Example - Analog Clock");
    clock->show();
    int result = a.exec();
    delete clock;
    return result;
}

See also Examples.


Walkthrough: A Tiny Editor Illustrating QActionGroup

In the following we will step through a very rudimental editor program that shows one of the most common uses of the QActionGroup class: how to combine several toggle actions in a way that allows one-of-many choices.

If you're not yet familiar with the concept of actions, please refer to the Simple Application Walkthrough featuring QAction.

A tiny main program

    #include <qapplication.h>
    #include "editor.h"

    int main( int argc, char ** argv)
    {
        QApplication app( argc, argv );
        Editor editor;
        editor.setCaption( "Qt Example - Actiongroup" );
        app.setMainWidget( &editor );
        editor.show();
        return app.exec();
    }

This tiny editor is a very small program. It might be unusual for an editor but it does not even provide the possibility to open a file given as a commandline argument. The reason for this is simple: It has nothing to to with QActionGroups.

The crucial point in the above main() is that we make editor, an object constructed from a self-written class Editor, the main widget in our application. This class is defined in editor.h.

When you read through the code and happen to be unsure about something: The Simple Application Walkthrough explains the elements of a typical Qt main program in detail.

The interface of the Editor class

Before implementing the Editor class we should think about what it is supposed to do. Fortunately Qt provides a full-featured rich text editor class, QTextEdit. The only thing left for us is to give it a user interface.

    #include <qmainwindow.h>
    class QTextEdit;
    class QAction;

    class Editor : public QMainWindow
    {
        Q_OBJECT

    public:
        Editor();

    private slots:
        void setFontColor( QAction * );

    private:
        QTextEdit * editor;
        QAction * setRedFont;
    };

As we look for a means to implement one-of-many choices, a nice example would involve two buttons that make the user change the font color: If he or she invokes the setRedFont action the font color changes from default black to red.

To do this color change we need a slot, setFontColor() that takes care about the signal the action emits.

The Editor class itself is derived from QMainWindow. Only the constructor might be called from outside the class.

Action!

    #include "editor.h"

    #include <qtextedit.h>
    #include <qmenubar.h>
    #include <qpopupmenu.h>
    #include <qtoolbar.h>
    #include <qaction.h>

It's not that much that we need for our tiny editor: QTextEdit, QMenuBar, QToolBar, QPopupMenu and last but not least QAction and QActionGroup from qaction.h.

    Editor::Editor()
        : QMainWindow( 0, "main window")
    {
        QActionGroup * colors = new QActionGroup( this, "colors", TRUE );

If one of the buttons is on, the other one must be off. The easiest way to to this is to create an action group, colors, that controls this exclusive behaviour. This is done by setting the third argument of the QActionGroup constructor to TRUE (we could omit it because it's the default). As simple as this we get an exclusive action group that will look after its member actions and switch off all other toggle actions except the one that is on.

        QAction * setBlackFont = new QAction( "black", QPixmap( (const char**)black_xpm ),
                                              "Font color: black", CTRL+Key_B,
                                              colors, "blackfontcolor", TRUE );

Then we create our first action, the one that sets the font color back to default black. It is called setBlackFont and is equipped with a descriptive QAction::text() reading black, a QAction::menuText() reading Font color: black, a QAction::iconSet() derived from the pixmap black_xpm and ALT+B as keyboard accelerator.

The last argument of the action constructor, TRUE, is responsible for making setBlackFont a toggle action that can be switched on or off. Most importantly setBlackFont becomes a member of the colors action group at creation time: colors is defined to be its parent.

        setRedFont = new QAction( "red", QPixmap( (const char**)red_xpm ), "Font color: red",
                                  CTRL+Key_R, colors, "redfontcolor", TRUE );

The same way we create the other toggle action, setRedFont, as a child of colors.

Whenever one of the two members of the colors group emits the QAction::toggled() signal the QActionGroup is notified internally and emits the QActionGroup::selected() signal in turn. QActionGroup::selected() carries the action that caused the signal as its argument.

All we have to do now is to connect this signal to a slot that changes the font color to red or black depending on the toggled action:

        QObject::connect( colors, SIGNAL( selected( QAction * ) ),
                          this, SLOT( setFontColor( QAction * ) ) );

This is the entire trick. Thus let's recall what we have done so far: We created two toggle actions, setRedFont and setBlackFont. Because they are children of an exclusive QActionGroup named colors it is impossible for the user to type red and black at the same time: Whenever he or she invokes one of the actions the other one changes state to off, colors emits a QActionGroup::selected() signal and the setFontColor() slot takes care of it.

All we have to do now is to add our two actions to the Editor window.

        QToolBar * toolbar = new QToolBar( this, "toolbar" );

First we create a tool bar.

        colors->addTo( toolbar );

But instead of adding each action manually we simply add their parent action group to toolbar and are done. colors makes sure that setBlackFont and setRedFont find themselves presented in the tool bar: setBlackFont as a tool button decorated with the black_xpm pixmap on the left, setRedFont (because it was added to colors later) to its right.

        QPopupMenu * font = new QPopupMenu( this );
        menuBar()->insertItem( "&Font", font );

Next we create a popup menu and insert it into the menu bar under the Font entry.

In a menu with this name a user would certainly expect to find more than just two entries to change the font color. You might want to add other font related actions in the future, and therefore it would be nice to group setBlackFont and setRedFont in a submenu entirely dedicated to the purpose of changing font colors.

With an action group this is easy. We simply tell colors to group together all of its members in a single submenu:

        colors->setUsesDropDown( TRUE );

This however causes a problem: a submenu entry must have a menu text, and up to now we don't have any.

When we recall that action groups intrinsically are QActions themselves the solution becomes obvious:

        colors->setMenuText( "Font Color" );

We simply assign the menu text Font Color to colors.

The rest is business as usual:

        colors->addTo( font );

We add the new and improved QActionGroup as a submenu to the font popup menu.

        editor = new QTextEdit( this, "editor" );

Last but not least we create the heart of Editor, the rich text editor ...

        setCentralWidget( editor );

... and make it the central widget in our window.

    }

The only thing left to implement is the setFontColor slot that is responsible for changing the font color to red or black depending on which action was toggled on.

    void Editor::setFontColor( QAction * coloraction )
    {

As the QActionGroup::selected() signal carries the relevant action as its argument, the first thing we have to do is to preserve it in the coloraction variable for later use.

        if ( coloraction == setRedFont )
            editor->setColor( red );

If coloraction is the same as setRedFont we change the editor's font color to red.

        else
            editor->setColor( black );

Otherwise it is set to black.

    }

See also Step-by-step Examples.


A Tiny Example Featuring QActionGroup

This example program shows how to use an exclusive action group.

Detailed explanations of the code can be found in the walkthrough.

Main:

/*
$Id$
*/

#include <qapplication.h>

#include "editor.h"

int main( int argc, char ** argv)
{
    QApplication app( argc, argv );
    Editor editor;
    editor.setCaption( "Qt Example - Actiongroup" );
    app.setMainWidget( &editor );
    editor.show();
    return app.exec();
}

Header file:

/*
$Id$
*/

#ifndef EDITOR_H
#define EDITOR_H

#include <qmainwindow.h>

class QTextEdit;
class QAction;

class Editor : public QMainWindow
{
    Q_OBJECT

public:
    Editor();

private slots:
    void setFontColor( QAction * );

private:
    QTextEdit * editor;
    QAction * setRedFont;
};

#endif

Implementation:

/*
$Id$
*/

/* XPM */
static const char * black_xpm[] = {
"32 32 2 1",
"       c None",
".      c #020202",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................",
"................................"};

/* XPM */
static const char * red_xpm[] = {
"32 32 6 1",
"       c None",
".      c #EE0928",
"+      c #EF0928",
"@      c #EE0A29",
"#      c #EE0B2A",
"$      c #ED0C2B",
"........................+.......",
".+.++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++.+++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
"+++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++.+++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++.+++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++@",
".+++++++++++++++++++++++++++++.#",
".+++++++++++++++++++++++++.+++.$",
".+++++++++++++++++++++++++++++#$",
".+++++++++++++++++++++++++++++.#",
".+++++++++++++++++++++++++++++.#",
".++++++++.+++++++++++++++++++++@",
".++++++.+++++++++++++++++++++++.",
".++++++++++++++++++++++++++++++.",
"..........+.............+......."};

#include "editor.h"

#include <qtextedit.h>
#include <qmenubar.h>
#include <qpopupmenu.h>
#include <qtoolbar.h>
#include <qaction.h>

Editor::Editor()
    : QMainWindow( 0, "main window")
{
    QActionGroup * colors = new QActionGroup( this, "colors", TRUE );

    QAction * setBlackFont = new QAction( "black", QPixmap( (const char**)black_xpm ),
                                          "Font color: black", CTRL+Key_B,
                                          colors, "blackfontcolor", TRUE );
    setRedFont = new QAction( "red", QPixmap( (const char**)red_xpm ), "Font color: red",
                              CTRL+Key_R, colors, "redfontcolor", TRUE );

    QObject::connect( colors, SIGNAL( selected( QAction * ) ),
                      this, SLOT( setFontColor( QAction * ) ) );

    QToolBar * toolbar = new QToolBar( this, "toolbar" );
    colors->addTo( toolbar );

    QPopupMenu * font = new QPopupMenu( this );
    menuBar()->insertItem( "&Font", font );

    colors->setUsesDropDown( TRUE );
    colors->setMenuText( "Font Color" );

    colors->addTo( font );

    editor = new QTextEdit( this, "editor" );
    setCentralWidget( editor );
}

void Editor::setFontColor( QAction * coloraction )
{
    if ( coloraction == setRedFont )
        editor->setColor( red );
    else
        editor->setColor( black );
}

See also QAction Examples.


Simple Addressbook

This examples shows how to write a very simple, but complete application using an addressbook as the example.

Header file of the mainwindow:

/****************************************************************************
** $Id:  qt/mainwindow.h   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef AB_MAINWINDOW_H
#define AB_MAINWINDOW_H

#include <qmainwindow.h>
#include <qstring.h>

class QToolBar;
class QPopupMenu;
class ABCentralWidget;

class ABMainWindow: public QMainWindow
{
    Q_OBJECT

public:
    ABMainWindow();
    ~ABMainWindow();

protected slots:
    void fileNew();
    void fileOpen();
    void fileSave();
    void fileSaveAs();
    void filePrint();
    void closeWindow();

protected:
    void setupMenuBar();
    void setupFileTools();
    void setupStatusBar();
    void setupCentralWidget();

    QToolBar *fileTools;
    QString filename;
    ABCentralWidget *view;

};

#endif

Implementation of the mainwindow:

/****************************************************************************
** $Id:  qt/mainwindow.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "mainwindow.h"
#include "centralwidget.h"

#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qstatusbar.h>
#include <qapplication.h>
#include <qfiledialog.h>

ABMainWindow::ABMainWindow()
    : QMainWindow( 0, "example addressbook application" ),
      filename( QString::null )
{
    setupMenuBar();
    setupFileTools();
    setupStatusBar();
    setupCentralWidget();
}

ABMainWindow::~ABMainWindow()
{
}

void ABMainWindow::setupMenuBar()
{
    QPopupMenu *file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );

    file->insertItem( "New", this, SLOT( fileNew() ), CTRL + Key_N );
    file->insertItem( QPixmap( "fileopen.xpm" ), "Open", this, SLOT( fileOpen() ), CTRL + Key_O );
    file->insertSeparator();
    file->insertItem( QPixmap( "filesave.xpm" ), "Save", this, SLOT( fileSave() ), CTRL + Key_S );
    file->insertItem( "Save As...", this, SLOT( fileSaveAs() ) );
    file->insertSeparator();
    file->insertItem( QPixmap( "fileprint.xpm" ), "Print...", this, SLOT( filePrint() ), CTRL + Key_P );
    file->insertSeparator();
    file->insertItem( "Close", this, SLOT( closeWindow() ), CTRL + Key_W );
    file->insertItem( "Quit", qApp, SLOT( quit() ), CTRL + Key_Q );
}

void ABMainWindow::setupFileTools()
{
    //fileTools = new QToolBar( this, "file operations" );
}

void ABMainWindow::setupStatusBar()
{
    //statusBar()->message( "Ready", 2000 );
}

void ABMainWindow::setupCentralWidget()
{
    view = new ABCentralWidget( this );
    setCentralWidget( view );
}

void ABMainWindow::closeWindow()
{
    close();
}

void ABMainWindow::fileNew()
{
}

void ABMainWindow::fileOpen()
{
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() ) {
        filename = fn;
        view->load( filename );
    }
}

void ABMainWindow::fileSave()
{
    if ( filename.isEmpty() ) {
        fileSaveAs();
        return;
    }

    view->save( filename );
}

void ABMainWindow::fileSaveAs()
{
    QString fn = QFileDialog::getSaveFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() ) {
        filename = fn;
        fileSave();
    }
}

void ABMainWindow::filePrint()
{
}

Header file of the centralwidget:

/****************************************************************************
** $Id:  qt/centralwidget.h   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef AB_CENTRALWIDGET_H
#define AB_CENTRALWIDGET_H

#include <qwidget.h>
#include <qstring.h>

class QTabWidget;
class QListView;
class QGridLayout;
class QLineEdit;
class QPushButton;
class QListViewItem;
class QCheckBox;

class ABCentralWidget : public QWidget
{
    Q_OBJECT

public:
    ABCentralWidget( QWidget *parent, const char *name = 0 );

    void save( const QString &filename );
    void load( const QString &filename );

protected slots:
    void addEntry();
    void changeEntry();
    void itemSelected( QListViewItem* );
    void selectionChanged();
    void toggleFirstName();
    void toggleLastName();
    void toggleAddress();
    void toggleEMail();
    void findEntries();

protected:
    void setupTabWidget();
    void setupListView();

    QGridLayout *mainGrid;
    QTabWidget *tabWidget;
    QListView *listView;
    QPushButton *add, *change, *find;
    QLineEdit *iFirstName, *iLastName, *iAddress, *iEMail,
        *sFirstName, *sLastName, *sAddress, *sEMail;
    QCheckBox *cFirstName, *cLastName, *cAddress, *cEMail;

};

#endif

Implementation of the centralwidget:

/****************************************************************************
** $Id:  qt/centralwidget.cpp   3.0.5   edited Apr 3 15:01 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "centralwidget.h"

#include <qtabwidget.h>
#include <qlistview.h>
#include <qlayout.h>
#include <qwidget.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qlabel.h>
#include <qcheckbox.h>
#include <qfile.h>
#include <qtextstream.h>

ABCentralWidget::ABCentralWidget( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    mainGrid = new QGridLayout( this, 2, 1, 5, 5 );

    setupTabWidget();
    setupListView();

    mainGrid->setRowStretch( 0, 0 );
    mainGrid->setRowStretch( 1, 1 );
}

void ABCentralWidget::save( const QString &filename )
{
    if ( !listView->firstChild() )
        return;

    QFile f( filename );
    if ( !f.open( IO_WriteOnly ) )
        return;

    QTextStream t( &f );

    QListViewItemIterator it( listView );

    for ( ; it.current(); ++it )
        for ( unsigned int i = 0; i < 4; i++ )
            t << it.current()->text( i ) << "\n";

    f.close();
}

void ABCentralWidget::load( const QString &filename )
{
    listView->clear();

    QFile f( filename );
    if ( !f.open( IO_ReadOnly ) )
        return;

    QTextStream t( &f );

    while ( !t.atEnd() ) {
        QListViewItem *item = new QListViewItem( listView );
        for ( unsigned int i = 0; i < 4; i++ )
            item->setText( i, t.readLine() );
    }

    f.close();
}

void ABCentralWidget::setupTabWidget()
{
    tabWidget = new QTabWidget( this );

    QWidget *input = new QWidget( tabWidget );
    QGridLayout *grid1 = new QGridLayout( input, 2, 5, 5, 5 );

    QLabel *liFirstName = new QLabel( "First &Name", input );
    liFirstName->resize( liFirstName->sizeHint() );
    grid1->addWidget( liFirstName, 0, 0 );

    QLabel *liLastName = new QLabel( "&Last Name", input );
    liLastName->resize( liLastName->sizeHint() );
    grid1->addWidget( liLastName, 0, 1 );

    QLabel *liAddress = new QLabel( "Add&ress", input );
    liAddress->resize( liAddress->sizeHint() );
    grid1->addWidget( liAddress, 0, 2 );

    QLabel *liEMail = new QLabel( "&E-Mail", input );
    liEMail->resize( liEMail->sizeHint() );
    grid1->addWidget( liEMail, 0, 3 );

    add = new QPushButton( "A&dd", input );
    add->resize( add->sizeHint() );
    grid1->addWidget( add, 0, 4 );
    connect( add, SIGNAL( clicked() ), this, SLOT( addEntry() ) );

    iFirstName = new QLineEdit( input );
    iFirstName->resize( iFirstName->sizeHint() );
    grid1->addWidget( iFirstName, 1, 0 );
    liFirstName->setBuddy( iFirstName );

    iLastName = new QLineEdit( input );
    iLastName->resize( iLastName->sizeHint() );
    grid1->addWidget( iLastName, 1, 1 );
    liLastName->setBuddy( iLastName );

    iAddress = new QLineEdit( input );
    iAddress->resize( iAddress->sizeHint() );
    grid1->addWidget( iAddress, 1, 2 );
    liAddress->setBuddy( iAddress );

    iEMail = new QLineEdit( input );
    iEMail->resize( iEMail->sizeHint() );
    grid1->addWidget( iEMail, 1, 3 );
    liEMail->setBuddy( iEMail );

    change = new QPushButton( "&Change", input );
    change->resize( change->sizeHint() );
    grid1->addWidget( change, 1, 4 );
    connect( change, SIGNAL( clicked() ), this, SLOT( changeEntry() ) );

    tabWidget->addTab( input, "&Add/Change Entry" );

    // --------------------------------------

    QWidget *search = new QWidget( this );
    QGridLayout *grid2 = new QGridLayout( search, 2, 5, 5, 5 );

    cFirstName = new QCheckBox( "First &Name", search );
    cFirstName->resize( cFirstName->sizeHint() );
    grid2->addWidget( cFirstName, 0, 0 );
    connect( cFirstName, SIGNAL( clicked() ), this, SLOT( toggleFirstName() ) );

    cLastName = new QCheckBox( "&Last Name", search );
    cLastName->resize( cLastName->sizeHint() );
    grid2->addWidget( cLastName, 0, 1 );
    connect( cLastName, SIGNAL( clicked() ), this, SLOT( toggleLastName() ) );

    cAddress = new QCheckBox( "Add&ress", search );
    cAddress->resize( cAddress->sizeHint() );
    grid2->addWidget( cAddress, 0, 2 );
    connect( cAddress, SIGNAL( clicked() ), this, SLOT( toggleAddress() ) );

    cEMail = new QCheckBox( "&E-Mail", search );
    cEMail->resize( cEMail->sizeHint() );
    grid2->addWidget( cEMail, 0, 3 );
    connect( cEMail, SIGNAL( clicked() ), this, SLOT( toggleEMail() ) );

    sFirstName = new QLineEdit( search );
    sFirstName->resize( sFirstName->sizeHint() );
    grid2->addWidget( sFirstName, 1, 0 );

    sLastName = new QLineEdit( search );
    sLastName->resize( sLastName->sizeHint() );
    grid2->addWidget( sLastName, 1, 1 );

    sAddress = new QLineEdit( search );
    sAddress->resize( sAddress->sizeHint() );
    grid2->addWidget( sAddress, 1, 2 );

    sEMail = new QLineEdit( search );
    sEMail->resize( sEMail->sizeHint() );
    grid2->addWidget( sEMail, 1, 3 );

    find = new QPushButton( "F&ind", search );
    find->resize( find->sizeHint() );
    grid2->addWidget( find, 1, 4 );
    connect( find, SIGNAL( clicked() ), this, SLOT( findEntries() ) );

    cFirstName->setChecked( TRUE );
    sFirstName->setEnabled( TRUE );
    sLastName->setEnabled( FALSE );
    sAddress->setEnabled( FALSE );
    sEMail->setEnabled( FALSE );

    tabWidget->addTab( search, "&Search" );

    mainGrid->addWidget( tabWidget, 0, 0 );
}

void ABCentralWidget::setupListView()
{
    listView = new QListView( this );
    listView->addColumn( "First Name" );
    listView->addColumn( "Last Name" );
    listView->addColumn( "Address" );
    listView->addColumn( "E-Mail" );

    listView->setSelectionMode( QListView::Single );

    connect( listView, SIGNAL( clicked( QListViewItem* ) ), this, SLOT( itemSelected( QListViewItem* ) ) );

    mainGrid->addWidget( listView, 1, 0 );
    listView->setAllColumnsShowFocus( TRUE );
}

void ABCentralWidget::addEntry()
{
    if ( !iFirstName->text().isEmpty() || !iLastName->text().isEmpty() ||
         !iAddress->text().isEmpty() || !iEMail->text().isEmpty() ) {
        QListViewItem *item = new QListViewItem( listView );
        item->setText( 0, iFirstName->text() );
        item->setText( 1, iLastName->text() );
        item->setText( 2, iAddress->text() );
        item->setText( 3, iEMail->text() );
    }

    iFirstName->setText( "" );
    iLastName->setText( "" );
    iAddress->setText( "" );
    iEMail->setText( "" );
}

void ABCentralWidget::changeEntry()
{
    QListViewItem *item = listView->currentItem();

    if ( item &&
         ( !iFirstName->text().isEmpty() || !iLastName->text().isEmpty() ||
           !iAddress->text().isEmpty() || !iEMail->text().isEmpty() ) ) {
        item->setText( 0, iFirstName->text() );
        item->setText( 1, iLastName->text() );
        item->setText( 2, iAddress->text() );
        item->setText( 3, iEMail->text() );
    }
}

void ABCentralWidget::selectionChanged()
{
    iFirstName->setText( "" );
    iLastName->setText( "" );
    iAddress->setText( "" );
    iEMail->setText( "" );
}

void ABCentralWidget::itemSelected( QListViewItem *item )
{
    if ( !item )
        return;
    item->setSelected( TRUE );
    item->repaint();

    iFirstName->setText( item->text( 0 ) );
    iLastName->setText( item->text( 1 ) );
    iAddress->setText( item->text( 2 ) );
    iEMail->setText( item->text( 3 ) );
}

void ABCentralWidget::toggleFirstName()
{
    sFirstName->setText( "" );

    if ( cFirstName->isChecked() ) {
        sFirstName->setEnabled( TRUE );
        sFirstName->setFocus();
    }
    else
        sFirstName->setEnabled( FALSE );
}

void ABCentralWidget::toggleLastName()
{
    sLastName->setText( "" );

    if ( cLastName->isChecked() ) {
        sLastName->setEnabled( TRUE );
        sLastName->setFocus();
    }
    else
        sLastName->setEnabled( FALSE );
}

void ABCentralWidget::toggleAddress()
{
    sAddress->setText( "" );

    if ( cAddress->isChecked() ) {
        sAddress->setEnabled( TRUE );
        sAddress->setFocus();
    }
    else
        sAddress->setEnabled( FALSE );
}

void ABCentralWidget::toggleEMail()
{
    sEMail->setText( "" );

    if ( cEMail->isChecked() ) {
        sEMail->setEnabled( TRUE );
        sEMail->setFocus();
    }
    else
        sEMail->setEnabled( FALSE );
}

void ABCentralWidget::findEntries()
{
    if ( !cFirstName->isChecked() &&
         !cLastName->isChecked() &&
         !cAddress->isChecked() &&
         !cEMail->isChecked() ) {
        listView->clearSelection();
        return;
    }

    QListViewItemIterator it( listView );

    for ( ; it.current(); ++it ) {
        bool select = TRUE;

        if ( cFirstName->isChecked() ) {
            if ( select && it.current()->text( 0 ).contains( sFirstName->text() ) )
                select = TRUE;
            else
                select = FALSE;
        }
        if ( cLastName->isChecked() ) {
            if ( select && it.current()->text( 1 ).contains( sLastName->text() ) )
                select = TRUE;
            else
                select = FALSE;
        }
        if ( cAddress->isChecked() ) {
            if ( select && it.current()->text( 2 ).contains( sAddress->text() ) )
                select = TRUE;
            else
                select = FALSE;
        }
        if ( cEMail->isChecked() ) {
            if ( select && it.current()->text( 3 ).contains( sEMail->text() ) )
                select = TRUE;
            else
                select = FALSE;
        }

        if ( select )
            it.current()->setSelected( TRUE );
        else
            it.current()->setSelected( FALSE );
        it.current()->repaint();
    }
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>

#include "mainwindow.h"

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

    ABMainWindow *mw = new ABMainWindow();
    mw->setCaption( "Qt Example - Addressbook" );
    a.setMainWidget( mw );
    mw->show();

    a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
    int result = a.exec();
    delete mw;
    return result;
}

See also Examples.


Advanced Widgets

These classes provide more complex user interface controls (widgets).

QCheckListItem | Checkable list view items
QCheckTableItem | Checkboxes in QTables
QComboTableItem | Means of using comboboxes in QTables
QDateEdit | Date editor
QDateTimeEdit | Combines a QDateEdit and QTimeEdit widget into a single widget for editing datetimes
QDesktopWidget | Access to screen information on multi-head systems
QEditorFactory | Used to create editor widgets for QVariant data types
QHeader | Header row or column, e.g. for tables and listviews
QIconView | Area with movable labelled icons
QIconViewItem | Single item in a QIconView
QListBox | List of selectable, read-only items
QListBoxItem | The base class of all list box items
QListBoxPixmap | List box items with a pixmap and optional text
QListBoxText | List box items that display text
QListView | Implements a list/tree view
QListViewItem | Implements a list view item
QListViewItemIterator | Iterator for collections of QListViewItems
QMultiLineEdit | Simple editor for inputting text
QProgressBar | Horizontal progress bar
QTab | The structures in a QTabBar
QTabBar | Tab bar, e.g. for use in tabbed dialogs
QTable | Flexible editable table widget
QTableItem | The cell content for QTable cells
QTableSelection | Access to a selected area in a QTable
QTabWidget | Stack of tabbed widgets
QTextBrowser | Rich text browser with hypertext navigation
QTimeEdit | Time editor


Widget Appearance and Style

These classes are used to customize an application's appearance and style.

QBoxLayout | Lines up child widgets horizontally or vertically
QButtonGroup | Organizes QButton widgets in a group
QCDEStyle | CDE look and feel
QColor | Colors based on RGB or HSV values
QColorGroup | Group of widget colors
QCommonStyle | Encapsulates the common Look and Feel of a GUI
QCursor | Mouse cursor with an arbitrary shape
QFont | Font used for drawing text
QGLayoutIterator | Abstract base class of internal layout iterators
QGrid | Simple geometry management of its children
QGridLayout | Lays out widgets in a grid
QGroupBox | Group box frame with a title
QHBox | Horizontal geometry management for its child widgets
QHBoxLayout | Lines up widgets horizontally
QHButtonGroup | Organizes QButton widgets in a group with one horizontal row
QHGroupBox | Organizes widgets in a group with one horizontal row
QLayout | The base class of geometry managers
QLayoutItem | Abstract item that a QLayout manipulates
QLayoutIterator | Iterators over QLayoutItem
QMotifPlusStyle | More sophisticated Motif-ish look and feel
QMotifStyle | Motif look and feel
QPalette | Color groups for each widget state
QPlatinumStyle | Mac/Platinum look and feel
QSGIStyle | SGI/Irix look and feel
QSizeGrip | Corner-grip for resizing a top-level window
QSizePolicy | Layout attribute describing horizontal and vertical resizing policy
QSpacerItem | Blank space in a layout
QStyle | The look and feel of a GUI
QStyleOption | Optional parameters for QStyle functions
QVBox | Vertical geometry management of its child widgets
QVBoxLayout | Lines up widgets vertically
QVButtonGroup | Organizes QButton widgets in a vertical column
QVGroupBox | Organizes a group of widgets in a vertical column
QWidgetItem | Layout item that represents a widget
QWindowsStyle | Microsoft Windows-like look and feel


Setting the Application Icon

The application icon, typically displayed in the upper left corner of the application top-level windows, is set by calling the QWidget::setIcon() method on top-level widgets.

In order to change the icon of the executable application file itself, as it is presented on the desktop (i.e. prior to application execution), it is necessary to employ another, platform-dependent technique.

  • Setting the Application Icon on Windows
  • Setting the Application Icon on Mac OS X

Setting the Application Icon on Windows

First, create an ICO format bitmap file that contains the icon image. This can be done with e.g. Microsoft Visual C++: Select "File|New...", then select the "File" tab in the dialog that appears, and choose "Icon". (Note that you do not need to load your application into Visual C++; here we are only using its icon editor).

Store the ICO file in the source code directory of your application, for example, with the name, "myappico.ico". Then, create a text file called e.g. "myapp.rc" in which you put a single line of text:

IDI_ICON1               ICON    DISCARDABLE     "myappico.ico"

Lastly, assuming you are using qmake to generate your makefiles, add this line to your "myapp.pro" file:

RC_FILE = myapp.rc

Regenerate your makefile and your application. The .exe file will now be represented with your icon in e.g. Explorer.

If you do not use qmake, the necessary steps are: first, run the "rc" program on the .rc file, then link your application with the resulting .res file.

Setting the Application Icon on Mac OS X

The application icon, typically displayed in the application dock area, is set by calling QWidget::setIcon() on a top-level widget. It is possible that the program could appear in the application dock area before the function call, in which case a default icon will appear during the bouncing animation.

To ensure that the correct icon appears, both when the application is being launched, and in the finder, it is necessary to employ a platform-dependent technique.

Although many programs can create icon files (.icns), the recommended approach is to use the Icon Composer program supplied by Apple (in the Developer/Application folder). Icon Composer allows you to import several different sized icons (for use in different contexts) as well as the masks that go with them. Save the set of icons to a file in your project directory.

If you are using qmake to generate your make files, you only need to add a single line to your .pro project file. For example, if the name of your icon file is myapp.icns, and your project file is myapp.pro, add this line to myapp.pro:

RC_FILE = myapp.icns
This will ensure that qmake puts your icons in the proper place and creates a Info.plist entry for the icon.

If you do not use qmake, you must do the following manually:

  1. Create an Info.plist file for your application (using the PropertyListEditor, found in Developer/Applications).
  2. Associate your .icns record with the CFBundleIconFile record in the Info.plist file (again, using the PropertyListEditor).
  3. Copy both the icns and your Info.plist into your application bundle Resource directory.


Main Window and Related Classes

These classes provide everything you need for a typical modern main application window, like the main window itself, menu and tool bars, a statusbar, etc.

QAction | Abstract user interface action that can appear both in menus and tool bars
QActionGroup | Groups actions together
QApplication | Manages the GUI application's control flow and main settings
QDockArea | Manages and lays out QDockWindows
QDockWindow | Widget which can be docked inside a QDockArea or floated as a top level window on the desktop
QMainWindow | Main application window, with a menu bar, dock windows (e.g. for toolbars), and a status bar
QMenuBar | Horizontal menu bar
QPopupMenu | Popup menu widget
QSessionManager | Access to the session manager
QSizeGrip | Corner-grip for resizing a top-level window
QStatusBar | Horizontal bar suitable for presenting status information
QToolBar | Movable panel containing widgets such as tool buttons
QWorkspace | Workspace window that can contain decorated windows, e.g. for MDI


Basic Widgets

These basic controls (widgets) are designed for direct use. There are also some abstract widget classes, designed for subclassing, and some more complex widgets.

QAction | Abstract user interface action that can appear both in menus and tool bars
QActionGroup | Groups actions together
QCheckBox | Checkbox with a text label
QComboBox | Combined button and popup list
QDial | Rounded range control (like a speedometer or potentiometer)
QLabel | Text or image display
QLCDNumber | Displays a number with LCD-like digits
QLineEdit | One-line text editor
QPopupMenu | Popup menu widget
QPushButton | Command button
QRadioButton | Radio button with a text or pixmap label
QScrollBar | Vertical or horizontal scroll bar
QSizeGrip | Corner-grip for resizing a top-level window
QSlider | Vertical or horizontal slider
QSpinBox | Spin box widget (spin button)
QTextEdit | Powerful single-page rich text editor
QToolButton | Quick-access button to commands or options, usually used inside a QToolBar


Biff (UNIX only)

Biff is a simple graphical program to indicate whether there is new mail; it looks exactly like xbiff but is much shorter.

Header file:

/****************************************************************************
** $Id:  qt/biff.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef BIFF_H
#define BIFF_H

#include <qwidget.h>
#include <qdatetime.h>
#include <qpixmap.h>

class Biff : public QWidget
{
    Q_OBJECT
public:
    Biff( QWidget *parent=0, const char *name=0 );

protected:
    void        timerEvent( QTimerEvent * );
    void        paintEvent( QPaintEvent * );
    void        mousePressEvent( QMouseEvent * );

private:
    QDateTime   lastModified;
    QPixmap     hasNewMail;
    QPixmap     noNewMail;
    QString     mailbox;
    bool        gotMail;
};

#endif // BIFF_H

biff.cpp implements this custom widget. Note in particular how two images (hasmail_bmp_data and nomail_bmp_data, both from bmp.cpp) are included into the executable.

/****************************************************************************
** $Id:  qt/biff.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "biff.h"
#include <qstring.h>
#include <qfileinfo.h>
#include <qpainter.h>

#include <unistd.h>
#include <stdlib.h>

#include "bmp.cpp"

Biff::Biff( QWidget *parent, const char *name )
    : QWidget( parent, name, WType_Modal )
{
    QFileInfo fi = QString(getenv( "MAIL" ));
    if ( !fi.exists() ) {
        QString s( "/var/spool/mail/" );
        s += getlogin();
        fi.setFile( s );
    }

    if ( fi.exists() ) {
        mailbox = fi.absFilePath();
        startTimer( 1000 );
    }

    setMinimumSize( 48, 48 );
    setMaximumSize( 48, 48 );
    resize( 48, 48 );

    hasNewMail.loadFromData( hasmail_bmp_data, hasmail_bmp_len );
    noNewMail.loadFromData( nomail_bmp_data, nomail_bmp_len );

    gotMail = FALSE;
    lastModified = fi.lastModified();
}

void Biff::timerEvent( QTimerEvent * )
{
    QFileInfo fi( mailbox );
    bool newState = ( fi.lastModified() != lastModified &&
                      fi.lastModified() > fi.lastRead() );
    if ( newState != gotMail ) {
        if ( gotMail )
            lastModified = fi.lastModified();
        gotMail = newState;
        repaint( FALSE );
    }
}

void Biff::paintEvent( QPaintEvent * )
{
    if ( gotMail )
        bitBlt( this, 0, 0, &hasNewMail );
    else
        bitBlt( this, 0, 0, &noNewMail );
}

void Biff::mousePressEvent( QMouseEvent * )
{
    QFileInfo fi( mailbox );
    lastModified = fi.lastModified();
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "biff.h"

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );
    Biff b;
    a.setMainWidget( &b );
    b.show();
    return a.exec();
}

See also Examples.


如何生成大的稀疏QTable

本样例显示一个稀疏表格的实现，它使用QIntDict以跟踪实际使用的单元格的记录。

实现：

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qtable.h>

// Table size

const int numRows = 1000000;
const int numCols = 1000000;

class MyTable : public QTable
{
public:
    MyTable( int r, int c ) : QTable( r, c ) {
        items.setAutoDelete( TRUE );
        widgets.setAutoDelete( TRUE );
        setCaption( tr( "This is a big table with 1.000.000x1.000.000 cells..." ) );
        setLeftMargin( fontMetrics().width( "W999999W" ) );
    }

    void resizeData( int ) {}
    QTableItem *item( int r, int c ) const { return items.find( indexOf( r, c ) ); }
    void setItem( int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); }
    void clearCell( int r, int c ) { items.remove( indexOf( r, c ) ); }
    void insertWidget( int r, int c, QWidget *w ) { widgets.replace( indexOf( r, c ), w );  }
    QWidget *cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); }
    void clearCellWidget( int r, int c ) { widgets.remove( indexOf( r, c ) ); }

private:
    QIntDict<QTableItem> items;
    QIntDict<QWidget> widgets;

};

// The program starts here.

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

    MyTable table( numRows, numCols );
    app.setMainWidget( &table );
    table.show();
    return app.exec();
}

也参见表格例程。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


Buttons and Groupboxes

This example shows different types of groupboxes (buttongroups, etc.) and different kinds of buttons (checkboxes, radiobuttons, pushbuttons, etc.).

Header file:

/****************************************************************************
** $Id:  qt/buttongroups.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef BUTTONS_GROUPS_H
#define BUTTONS_GROUPS_H

#include <qwidget.h>

class QCheckBox;
class QRadioButton;

class ButtonsGroups : public QWidget
{
    Q_OBJECT

public:
    ButtonsGroups( QWidget *parent = 0, const char *name = 0 );

protected:
    QCheckBox *state;
    QRadioButton *rb21, *rb22, *rb23;

protected slots:
    void slotChangeGrp3State();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/buttongroups.cpp   3.0.5   edited Jun 4 09:54 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "buttongroups.h"

#include <qbuttongroup.h>
#include <qlayout.h>
#include <qradiobutton.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qpushbutton.h>

/*
 * Constructor
 *
 * Creates all child widgets of the ButtonGroups window
 */

ButtonsGroups::ButtonsGroups( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    // Create Widgets which allow easy layouting
    QVBoxLayout *vbox = new QVBoxLayout( this, 11, 6 );
    QHBoxLayout *box1 = new QHBoxLayout( vbox );
    QHBoxLayout *box2 = new QHBoxLayout( vbox );

    // ------- first group

    // Create an exclusive button group
    QButtonGroup *bgrp1 = new QButtonGroup( 1, QGroupBox::Horizontal, "Button Group &1 (exclusive)", this);
    box1->addWidget( bgrp1 );
    bgrp1->setExclusive( TRUE );

    // insert 3 radiobuttons
    QRadioButton *rb11 = new QRadioButton( "&Radiobutton 1", bgrp1 );
    rb11->setChecked( TRUE );
    (void)new QRadioButton( "R&adiobutton 2", bgrp1 );
    (void)new QRadioButton( "Ra&diobutton 3", bgrp1 );

    // ------- second group

    // Create a non-exclusive buttongroup
    QButtonGroup *bgrp2 = new QButtonGroup( 1, QGroupBox::Horizontal, "Button Group &2 (non-exclusive)", this );
    box1->addWidget( bgrp2 );
    bgrp2->setExclusive( FALSE );

    // insert 3 checkboxes
    (void)new QCheckBox( "&Checkbox 1", bgrp2 );
    QCheckBox *cb12 = new QCheckBox( "C&heckbox 2", bgrp2 );
    cb12->setChecked( TRUE );
    QCheckBox *cb13 = new QCheckBox( "Triple &State Button", bgrp2 );
    cb13->setTristate( TRUE );
    cb13->setChecked( TRUE );

    // ------------ third group

    // create a buttongroup which is exclusive for radiobuttons and non-exclusive for all other buttons
    QButtonGroup *bgrp3 = new QButtonGroup( 1, QGroupBox::Horizontal, "Button Group &3 (Radiobutton-exclusive)", this );
    box2->addWidget( bgrp3 );
    bgrp3->setRadioButtonExclusive( TRUE );

    // insert three radiobuttons
    rb21 = new QRadioButton( "Rad&iobutton 1", bgrp3 );
    rb22 = new QRadioButton( "Radi&obutton 2", bgrp3 );
    rb23 = new QRadioButton( "Radio&button 3", bgrp3 );
    rb23->setChecked( TRUE );

    // insert a checkbox...
    state = new QCheckBox( "E&nable Radiobuttons", bgrp3 );
    state->setChecked( TRUE );
    // ...and connect its SIGNAL clicked() with the SLOT slotChangeGrp3State()
    connect( state, SIGNAL( clicked() ), this, SLOT( slotChangeGrp3State() ) );

    // ------------ fourth group

    // create a groupbox which layouts its childs in a columns
    QGroupBox *bgrp4 = new QButtonGroup( 1, QGroupBox::Horizontal, "Groupbox with &normal buttons", this );
    box2->addWidget( bgrp4 );

    // insert three pushbuttons...
    (void)new QPushButton( "&Push Button", bgrp4 );
    QPushButton *tb2 = new QPushButton( "&Toggle Button", bgrp4 );
    QPushButton *tb3 = new QPushButton( "&Flat Button", bgrp4 );

    // ... and make the second one a toggle button
    tb2->setToggleButton( TRUE );
    tb2->setOn( TRUE );

    // ... and make the third one a flat button
    tb3->setFlat(TRUE);
}

/*
 * SLOT slotChangeGrp3State()
 *
 * enables/disables the radiobuttons of the third buttongroup
 */

void ButtonsGroups::slotChangeGrp3State()
{
    rb21->setEnabled( state->isChecked() );
    rb22->setEnabled( state->isChecked() );
    rb23->setEnabled( state->isChecked() );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "buttongroups.h"
#include <qapplication.h>

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

    ButtonsGroups buttonsgroups;
    buttonsgroups.resize( 500, 250 );
    buttonsgroups.setCaption( "Qt Example - Buttongroups" );
    a.setMainWidget( &buttonsgroups );
    buttonsgroups.show();

    return a.exec();
}

See also Examples.


A Complete Canvas Application

This is a complete example program with a main window, menus and toolbars. The main widget is a QCanvas, and this example demonstrates basic canvas usage.

Project file:

TEMPLATE = app
CONFIG  += warn_on

HEADERS +=  element.h \
            canvastext.h \
            canvasview.h \
            chartform.h \
            optionsform.h \
            setdataform.h
SOURCES +=  element.cpp \
            canvasview.cpp \
            chartform.cpp \
            chartform_canvas.cpp \
            chartform_files.cpp \
            optionsform.cpp \
            setdataform.cpp \
            main.cpp

Header files:

#ifndef ELEMENT_H
#define ELEMENT_H

#include <qcolor.h>
#include <qnamespace.h>
#include <qstring.h>
#include <qvaluevector.h>

class Element;

typedef QValueVector<Element> ElementVector;

/*
    Elements are valid if they have a value which is > EPSILON.
*/
const double EPSILON = 0.0000001; // Must be > INVALID.

class Element
{
public:
    enum { INVALID = -1 };
    enum { NO_PROPORTION = -1 };
    enum { MAX_PROPOINTS = 3 }; // One proportional point per chart type

    Element( double value = INVALID, QColor valueColor = Qt::gray,
             int valuePattern = Qt::SolidPattern,
             const QString& label = QString::null,
             QColor labelColor = Qt::black ) {
        init( value, valueColor, valuePattern, label, labelColor );
        for ( int i = 0; i < MAX_PROPOINTS * 2; ++i )
            m_propoints[i] = NO_PROPORTION;
    }
    ~Element() {}

    bool isValid() const { return m_value > EPSILON; }

    double value() const { return m_value; }
    QColor valueColor() const { return m_valueColor; }
    int valuePattern() const { return m_valuePattern; }
    QString label() const { return m_label; }
    QColor labelColor() const { return m_labelColor; }
    double proX( int index ) const;
    double proY( int index ) const;

    void set( double value = INVALID, QColor valueColor = Qt::gray,
              int valuePattern = Qt::SolidPattern,
              const QString& label = QString::null,
              QColor labelColor = Qt::black ) {
        init( value, valueColor, valuePattern, label, labelColor );
    }
    void setValue( double value ) { m_value = value; }
    void setValueColor( QColor valueColor ) { m_valueColor = valueColor; }
    void setValuePattern( int valuePattern );
    void setLabel( const QString& label ) { m_label = label; }
    void setLabelColor( QColor labelColor ) { m_labelColor = labelColor; }
    void setProX( int index, double value );
    void setProY( int index, double value );

private:
    void init( double value, QColor valueColor, int valuePattern,
               const QString& label, QColor labelColor );

    double m_value;
    QColor m_valueColor;
    int m_valuePattern;
    QString m_label;
    QColor m_labelColor;
    double m_propoints[2 * MAX_PROPOINTS];
};

Q_EXPORT QTextStream &operator<<( QTextStream&, const Element& );
Q_EXPORT QTextStream &operator>>( QTextStream&, Element& );

#endif

#ifndef CHARTFORM_H
#define CHARTFORM_H

#include "element.h"

#include <qmainwindow.h>
#include <qstringlist.h>

class CanvasView;

class QAction;
class QCanvas;
class QFont;
class QPrinter;
class QString;

class ChartForm: public QMainWindow
{
    Q_OBJECT
public:
    enum { MAX_ELEMENTS = 100 };
    enum { MAX_RECENTFILES = 9 }; // Must not exceed 9
    enum ChartType { PIE, VERTICAL_BAR, HORIZONTAL_BAR };
    enum AddValuesType { NO, YES, AS_PERCENTAGE };

    ChartForm( const QString& filename );
    ~ChartForm();

    int chartType() { return m_chartType; }
    void setChanged( bool changed = true ) { m_changed = changed; }
    void drawElements();

    QPopupMenu *optionsMenu; // Why public? See canvasview.cpp

private slots:
    void fileNew();
    void fileOpen();
    void fileOpenRecent( int index );
    void fileSave();
    void fileSaveAs();
    void fileSaveAsPixmap();
    void filePrint();
    void fileQuit();
    void optionsSetData();
    void updateChartType( QAction *action );
    void optionsSetFont();
    void optionsSetOptions();
    void helpHelp();
    void helpAbout();
    void helpAboutQt();
    void saveOptions();

private:
    void init();
    void load( const QString& filename );
    bool okToClear();
    void drawPieChart( const double scales[], double total, int count );
    void drawVerticalBarChart( const double scales[], double total, int count );
    void drawHorizontalBarChart( const double scales[], double total, int count );

    QString valueLabel( const QString& label, double value, double total );
    void updateRecentFiles( const QString& filename );
    void updateRecentFilesMenu();
    void setChartType( ChartType chartType );

    QPopupMenu *fileMenu;
    QAction *optionsPieChartAction;
    QAction *optionsHorizontalBarChartAction;
    QAction *optionsVerticalBarChartAction;

    QString m_filename;
    QStringList m_recentFiles;
    QCanvas *m_canvas;
    CanvasView *m_canvasView;
    bool m_changed;
    ElementVector m_elements;
    QPrinter *m_printer;
    ChartType m_chartType;
    AddValuesType m_addValues;
    int m_decimalPlaces;
    QFont m_font;
};

#endif

 Implementation:

#include "canvasview.h"
#include "chartform.h"
#include "optionsform.h"
#include "setdataform.h"

#include <qaction.h>
#include <qapplication.h>
#include <qcombobox.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qfont.h>
#include <qfontdialog.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qpixmap.h>
#include <qpopupmenu.h>
#include <qprinter.h>
#include <qradiobutton.h>
#include <qsettings.h>
#include <qspinbox.h>
#include <qstatusbar.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>

#include "images/file_new.xpm"
#include "images/file_open.xpm"
#include "images/file_save.xpm"
#include "images/file_print.xpm"
#include "images/options_setdata.xpm"
#include "images/options_setfont.xpm"
#include "images/options_setoptions.xpm"
#include "images/options_horizontalbarchart.xpm"
#include "images/options_piechart.xpm"
#include "images/options_verticalbarchart.xpm"

const QString WINDOWS_REGISTRY = "/QtExamples";
const QString APP_KEY = "/Chart/";

ChartForm::ChartForm( const QString& filename )
    : QMainWindow( 0, 0, WDestructiveClose )
{
    setIcon( QPixmap( options_piechart ) );

    QAction *fileNewAction;
    QAction *fileOpenAction;
    QAction *fileSaveAction;
    QAction *fileSaveAsAction;
    QAction *fileSaveAsPixmapAction;
    QAction *filePrintAction;
    QAction *fileQuitAction;
    QAction *optionsSetDataAction;
    QAction *optionsSetFontAction;
    QAction *optionsSetOptionsAction;

    fileNewAction = new QAction(
            "New Chart", QPixmap( file_new ),
            "&New", CTRL+Key_N, this, "new" );
    connect( fileNewAction, SIGNAL( activated() ), this, SLOT( fileNew() ) );

    fileOpenAction = new QAction(
            "Open Chart", QPixmap( file_open ),
            "&Open...", CTRL+Key_O, this, "open" );
    connect( fileOpenAction, SIGNAL( activated() ), this, SLOT( fileOpen() ) );

    fileSaveAction = new QAction(
            "Save Chart", QPixmap( file_save ),
            "&Save", CTRL+Key_S, this, "save" );
    connect( fileSaveAction, SIGNAL( activated() ), this, SLOT( fileSave() ) );

    fileSaveAsAction = new QAction(
            "Save Chart As", QPixmap( file_save ),
            "Save &As...", 0, this, "save as" );
    connect( fileSaveAsAction, SIGNAL( activated() ),
             this, SLOT( fileSaveAs() ) );

    fileSaveAsPixmapAction = new QAction(
            "Save Chart As Bitmap", QPixmap( file_save ),
            "Save As &Bitmap...", CTRL+Key_B, this, "save as bitmap" );
    connect( fileSaveAsPixmapAction, SIGNAL( activated() ),
             this, SLOT( fileSaveAsPixmap() ) );

    filePrintAction = new QAction(
            "Print Chart", QPixmap( file_print ),
            "&Print Chart...", CTRL+Key_P, this, "print chart" );
    connect( filePrintAction, SIGNAL( activated() ),
             this, SLOT( filePrint() ) );

    optionsSetDataAction = new QAction(
            "Set Data", QPixmap( options_setdata ),
            "Set &Data...", CTRL+Key_D, this, "set data" );
    connect( optionsSetDataAction, SIGNAL( activated() ),
             this, SLOT( optionsSetData() ) );

    QActionGroup *chartGroup = new QActionGroup( this ); // Connected later
    chartGroup->setExclusive( true );

    optionsPieChartAction = new QAction(
            "Pie Chart", QPixmap( options_piechart ),
            "&Pie Chart", CTRL+Key_I, chartGroup, "pie chart" );
    optionsPieChartAction->setToggleAction( true );

    optionsHorizontalBarChartAction = new QAction(
            "Horizontal Bar Chart", QPixmap( options_horizontalbarchart ),
            "&Horizontal Bar Chart", CTRL+Key_H, chartGroup,
            "horizontal bar chart" );
    optionsHorizontalBarChartAction->setToggleAction( true );

    optionsVerticalBarChartAction = new QAction(
            "Vertical Bar Chart", QPixmap( options_verticalbarchart ),
            "&Vertical Bar Chart", CTRL+Key_V, chartGroup, "Vertical bar chart" );
    optionsVerticalBarChartAction->setToggleAction( true );

    optionsSetFontAction = new QAction(
            "Set Font", QPixmap( options_setfont ),
            "Set &Font...", CTRL+Key_F, this, "set font" );
    connect( optionsSetFontAction, SIGNAL( activated() ),
             this, SLOT( optionsSetFont() ) );

    optionsSetOptionsAction = new QAction(
            "Set Options", QPixmap( options_setoptions ),
            "Set &Options...", 0, this, "set options" );
    connect( optionsSetOptionsAction, SIGNAL( activated() ),
             this, SLOT( optionsSetOptions() ) );

    fileQuitAction = new QAction( "Quit", "&Quit", CTRL+Key_Q, this, "quit" );
    connect( fileQuitAction, SIGNAL( activated() ), this, SLOT( fileQuit() ) );

    QToolBar* fileTools = new QToolBar( this, "file operations" );
    fileTools->setLabel( "File Operations" );
    fileNewAction->addTo( fileTools );
    fileOpenAction->addTo( fileTools );
    fileSaveAction->addTo( fileTools );
    fileTools->addSeparator();
    filePrintAction->addTo( fileTools );

    QToolBar *optionsTools = new QToolBar( this, "options operations" );
    optionsTools->setLabel( "Options Operations" );
    optionsSetDataAction->addTo( optionsTools );
    optionsTools->addSeparator();
    optionsPieChartAction->addTo( optionsTools );
    optionsHorizontalBarChartAction->addTo( optionsTools );
    optionsVerticalBarChartAction->addTo( optionsTools );
    optionsTools->addSeparator();
    optionsSetFontAction->addTo( optionsTools );
    optionsTools->addSeparator();
    optionsSetOptionsAction->addTo( optionsTools );

    fileMenu = new QPopupMenu( this );
    menuBar()->insertItem( "&File", fileMenu );
    fileNewAction->addTo( fileMenu );
    fileOpenAction->addTo( fileMenu );
    fileSaveAction->addTo( fileMenu );
    fileSaveAsAction->addTo( fileMenu );
    fileMenu->insertSeparator();
    fileSaveAsPixmapAction->addTo( fileMenu );
    fileMenu->insertSeparator();
    filePrintAction->addTo( fileMenu );
    fileMenu->insertSeparator();
    fileQuitAction->addTo( fileMenu );
    fileMenu->insertSeparator();

    optionsMenu = new QPopupMenu( this );
    menuBar()->insertItem( "&Options", optionsMenu );
    optionsSetDataAction->addTo( optionsMenu );
    optionsMenu->insertSeparator();
    optionsPieChartAction->addTo( optionsMenu );
    optionsHorizontalBarChartAction->addTo( optionsMenu );
    optionsVerticalBarChartAction->addTo( optionsMenu );
    optionsMenu->insertSeparator();
    optionsSetFontAction->addTo( optionsMenu );
    optionsMenu->insertSeparator();
    optionsSetOptionsAction->addTo( optionsMenu );

    menuBar()->insertSeparator();

    QPopupMenu *helpMenu = new QPopupMenu( this );
    menuBar()->insertItem( "&Help", helpMenu );
    helpMenu->insertItem( "&Help", this, SLOT(helpHelp()), Key_F1 );
    helpMenu->insertItem( "&About", this, SLOT(helpAbout()) );
    helpMenu->insertItem( "About &Qt", this, SLOT(helpAboutQt()) );

    m_printer = 0;
    m_elements.resize( MAX_ELEMENTS );

    QSettings settings;
    settings.insertSearchPath( QSettings::Windows, WINDOWS_REGISTRY );
    int windowWidth = settings.readNumEntry( APP_KEY + "WindowWidth", 460 );
    int windowHeight = settings.readNumEntry( APP_KEY + "WindowHeight", 530 );
    int windowX = settings.readNumEntry( APP_KEY + "WindowX", 0 );
    int windowY = settings.readNumEntry( APP_KEY + "WindowY", 0 );
    setChartType( ChartType(
            settings.readNumEntry( APP_KEY + "ChartType", int(PIE) ) ) );
    m_addValues = AddValuesType(
                    settings.readNumEntry( APP_KEY + "AddValues", int(NO) ));
    m_decimalPlaces = settings.readNumEntry( APP_KEY + "Decimals", 2 );
    m_font = QFont( "Helvetica", 18, QFont::Bold );
    m_font.fromString(
            settings.readEntry( APP_KEY + "Font", m_font.toString() ) );
    for ( int i = 0; i < MAX_RECENTFILES; ++i ) {
        QString filename = settings.readEntry( APP_KEY + "File" +
                                               QString::number( i + 1 ) );
        if ( !filename.isEmpty() )
            m_recentFiles.push_back( filename );
    }
    if ( m_recentFiles.count() )
        updateRecentFilesMenu();

    // Connect *after* we've set the chart type on so we don't call
    // drawElements() prematurely.
    connect( chartGroup, SIGNAL( selected(QAction*) ),
             this, SLOT( updateChartType(QAction*) ) );

    resize( windowWidth, windowHeight );
    move( windowX, windowY );

    m_canvas = new QCanvas( this );
    m_canvas->resize( width(), height() );
    m_canvasView = new CanvasView( m_canvas, &m_elements, this );
    setCentralWidget( m_canvasView );
    m_canvasView->show();

    if ( !filename.isEmpty() )
        load( filename );
    else {
        init();
        m_elements[0].set( 20, red,    14, "Red" );
        m_elements[1].set( 70, cyan,    2, "Cyan",   darkGreen );
        m_elements[2].set( 35, blue,   11, "Blue" );
        m_elements[3].set( 55, yellow,  1, "Yellow", darkBlue );
        m_elements[4].set( 80, magenta, 1, "Magenta" );
        drawElements();
    }

    statusBar()->message( "Ready", 2000 );
}

ChartForm::~ChartForm()
{
    delete m_printer;
}

void ChartForm::init()
{
    setCaption( "Chart" );
    m_filename = QString::null;
    m_changed = false;

    m_elements[0]  = Element( Element::INVALID, red );
    m_elements[1]  = Element( Element::INVALID, cyan );
    m_elements[2]  = Element( Element::INVALID, blue );
    m_elements[3]  = Element( Element::INVALID, yellow );
    m_elements[4]  = Element( Element::INVALID, green );
    m_elements[5]  = Element( Element::INVALID, magenta );
    m_elements[6]  = Element( Element::INVALID, darkYellow );
    m_elements[7]  = Element( Element::INVALID, darkRed );
    m_elements[8]  = Element( Element::INVALID, darkCyan );
    m_elements[9]  = Element( Element::INVALID, darkGreen );
    m_elements[10] = Element( Element::INVALID, darkMagenta );
    m_elements[11] = Element( Element::INVALID, darkBlue );
    for ( int i = 12; i < MAX_ELEMENTS; ++i ) {
        double x = (double(i) / MAX_ELEMENTS) * 360;
        int y = (int(x * 256) % 105) + 151;
        int z = ((i * 17) % 105) + 151;
        m_elements[i] = Element( Element::INVALID, QColor( int(x), y, z, QColor::Hsv ) );
    }
}

void ChartForm::fileNew()
{
    if ( okToClear() ) {
        init();
        drawElements();
    }
}

void ChartForm::fileOpen()
{
    if ( !okToClear() )
        return;

    QString filename = QFileDialog::getOpenFileName(
                            QString::null, "Charts (*.cht)", this,
                            "file open", "Chart -- File Open" );
    if ( !filename.isEmpty() )
        load( filename );
    else
        statusBar()->message( "File Open abandoned", 2000 );
}

void ChartForm::fileSaveAs()
{
    QString filename = QFileDialog::getSaveFileName(
                            QString::null, "Charts (*.cht)", this,
                            "file save as", "Chart -- File Save As" );
    if ( !filename.isEmpty() ) {
        int answer = 0;
        if ( QFile::exists( filename ) )
            answer = QMessageBox::warning(
                            this, "Chart -- Overwrite File",
                            QString( "Overwrite\n\'%1\'?" ).
                                arg( filename ),
                            "&Yes", "&No", QString::null, 1, 1 );
        if ( answer == 0 ) {
            m_filename = filename;
            updateRecentFiles( filename );
            fileSave();
            return;
        }
    }
    statusBar()->message( "Saving abandoned", 2000 );
}

void ChartForm::fileOpenRecent( int index )
{
    if ( !okToClear() )
        return;

    load( m_recentFiles[index] );
}

void ChartForm::updateRecentFiles( const QString& filename )
{
    if ( m_recentFiles.find( filename ) != m_recentFiles.end() )
        return;

    m_recentFiles.push_back( filename );
    if ( m_recentFiles.count() > MAX_RECENTFILES )
        m_recentFiles.pop_front();

    updateRecentFilesMenu();
}

void ChartForm::updateRecentFilesMenu()
{
    for ( int i = 0; i < MAX_RECENTFILES; ++i ) {
        if ( fileMenu->findItem( i ) )
            fileMenu->removeItem( i );
        if ( i < int(m_recentFiles.count()) )
            fileMenu->insertItem( QString( "&%1 %2" ).
                                    arg( i + 1 ).arg( m_recentFiles[i] ),
                                  this, SLOT( fileOpenRecent(int) ),
                                  0, i );
    }
}

void ChartForm::fileQuit()
{
    if ( okToClear() ) {
        saveOptions();
        qApp->exit( 0 );
    }
}

bool ChartForm::okToClear()
{
    if ( m_changed ) {
        QString msg;
        if ( m_filename.isEmpty() )
            msg = "Unnamed chart ";
        else
            msg = QString( "Chart '%1'\n" ).arg( m_filename );
        msg += "has been changed.";
        switch( QMessageBox::information( this, "Chart -- Unsaved Changes",
                                          msg, "&Save", "Cancel", "&Abandon",
                                          0, 1 ) ) {
            case 0:
                fileSave();
                break;
            case 1:
            default:
                return false;
                break;
            case 2:
                break;
        }
    }

    return true;
}

void ChartForm::saveOptions()
{
    QSettings settings;
    settings.insertSearchPath( QSettings::Windows, WINDOWS_REGISTRY );
    settings.writeEntry( APP_KEY + "WindowWidth", width() );
    settings.writeEntry( APP_KEY + "WindowHeight", height() );
    settings.writeEntry( APP_KEY + "WindowX", x() );
    settings.writeEntry( APP_KEY + "WindowY", y() );
    settings.writeEntry( APP_KEY + "ChartType", int(m_chartType) );
    settings.writeEntry( APP_KEY + "AddValues", int(m_addValues) );
    settings.writeEntry( APP_KEY + "Decimals", m_decimalPlaces );
    settings.writeEntry( APP_KEY + "Font", m_font.toString() );
    for ( int i = 0; i < int(m_recentFiles.count()); ++i )
        settings.writeEntry( APP_KEY + "File" + QString::number( i + 1 ),
                             m_recentFiles[i] );
}

void ChartForm::optionsSetData()
{
    SetDataForm *setDataForm = new SetDataForm( &m_elements, m_decimalPlaces, this );
    if ( setDataForm->exec() ) {
        m_changed = true;
        drawElements();
    }
    delete setDataForm;
}

void ChartForm::setChartType( ChartType chartType )
{
    m_chartType = chartType;
    switch ( m_chartType ) {
        case PIE:
            optionsPieChartAction->setOn( true );
            break;
        case VERTICAL_BAR:
            optionsVerticalBarChartAction->setOn( true );
            break;
        case HORIZONTAL_BAR:
            optionsHorizontalBarChartAction->setOn( true );
            break;
    }
}

void ChartForm::updateChartType( QAction *action )
{
    if ( action == optionsPieChartAction ) {
        m_chartType = PIE;
    }
    else if ( action == optionsHorizontalBarChartAction ) {
        m_chartType = HORIZONTAL_BAR;
    }
    else if ( action == optionsVerticalBarChartAction ) {
        m_chartType = VERTICAL_BAR;
    }

    drawElements();
}

void ChartForm::optionsSetFont()
{
    bool ok;
    QFont font = QFontDialog::getFont( &ok, m_font, this );
    if ( ok ) {
        m_font = font;
        drawElements();
    }
}

void ChartForm::optionsSetOptions()
{
    OptionsForm *optionsForm = new OptionsForm( this );
    optionsForm->chartTypeComboBox->setCurrentItem( m_chartType );
    optionsForm->setFont( m_font );
    switch ( m_addValues ) {
        case NO:
            optionsForm->noRadioButton->setChecked( true );
            break;
        case YES:
            optionsForm->yesRadioButton->setChecked( true );
            break;
        case AS_PERCENTAGE:
            optionsForm->asPercentageRadioButton->setChecked( true );
            break;
    }
    optionsForm->decimalPlacesSpinBox->setValue( m_decimalPlaces );
    if ( optionsForm->exec() ) {
        setChartType( ChartType(
                optionsForm->chartTypeComboBox->currentItem()) );
        m_font = optionsForm->font();
        if ( optionsForm->noRadioButton->isChecked() )
            m_addValues = NO;
        else if ( optionsForm->yesRadioButton->isChecked() )
            m_addValues = YES;
        else if ( optionsForm->asPercentageRadioButton->isChecked() )
            m_addValues = AS_PERCENTAGE;
        m_decimalPlaces = optionsForm->decimalPlacesSpinBox->value();
        drawElements();
    }
    delete optionsForm;
}

void ChartForm::helpHelp()
{
    statusBar()->message( "Help is not implemented yet", 2000 );
}

void ChartForm::helpAbout()
{
    QMessageBox::about( this, "Chart -- About",
                        "<center><h1><font color=blue>Chart<font></h1></center>"
                        "<p>Chart your data with <i>chart</i>.</p>"
                        );
}

void ChartForm::helpAboutQt()
{
    QMessageBox::aboutQt( this, "Chart -- About Qt" );
}

 Main:

#include <qapplication.h>
#include "chartform.h"

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

    QString filename;
    if ( app.argc() > 1 ) {
        filename = app.argv()[1];
        if ( !filename.endsWith( ".cht" ) )
            filename = QString::null;
    }

    ChartForm *cf = new ChartForm( filename );
    app.setMainWidget( cf );
    cf->show();
    app.connect( &app, SIGNAL(lastWindowClosed()), cf, SLOT(fileQuit()) );

    return app.exec();
}

See also Step-by-step Examples.

Copyright © 2002
TrolltechTrademarks

Qt version 3.0.5


Canvas Example

This example shows a QCanvas and some QCanvasItems in action. You can do a lot more with QCanvas than we show here, but the example provides a taste of what can be done.

Header file:

#ifndef EXAMPLE_H
#define EXAMPLE_H

#include <qpopupmenu.h>
#include <qmainwindow.h>
#include <qintdict.h>
#include <qcanvas.h>

class BouncyLogo : public QCanvasSprite {
    void initPos();
    void initSpeed();
public:
    BouncyLogo(QCanvas*);
    void advance(int);
    int rtti() const;
};

class FigureEditor : public QCanvasView {
    Q_OBJECT

public:
    FigureEditor(QCanvas&, QWidget* parent=0, const char* name=0, WFlags f=0);
    void clear();

protected:
    void contentsMousePressEvent(QMouseEvent*);
    void contentsMouseMoveEvent(QMouseEvent*);

signals:
    void status(const QString&);

private:
    QCanvasItem* moving;
    QPoint moving_start;
};

class Main : public QMainWindow {
    Q_OBJECT

public:
    Main(QCanvas&, QWidget* parent=0, const char* name=0, WFlags f=0);
    ~Main();

public slots:
    void help();

private slots:
    void aboutQt();
    void newView();
    void clear();
    void init();

    void addSprite();
    void addCircle();
    void addHexagon();
    void addPolygon();
    void addSpline();
    void addText();
    void addLine();
    void addRectangle();
    void addMesh();
    void addLogo();
    void addButterfly();

    void enlarge();
    void shrink();
    void rotateClockwise();
    void rotateCounterClockwise();
    void zoomIn();
    void zoomOut();
    void mirror();
    void moveL();
    void moveR();
    void moveU();
    void moveD();

    void print();

    void toggleDoubleBuffer();

private:
    QCanvas& canvas;
    FigureEditor *editor;

    QPopupMenu* options;
    QPrinter* printer;
    int dbf_id;
};

#endif

Implementation:

#include <qdatetime.h>
#include <qmainwindow.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qmenubar.h>
#include <qapplication.h>
#include <qpainter.h>
#include <qprinter.h>
#include <qlabel.h>
#include <qimage.h>
#include <qprogressdialog.h>
#include "canvas.h"

#include <stdlib.h>

// We use a global variable to save memory - all the brushes and pens in
// the mesh are shared.
static QBrush *tb = 0;
static QPen *tp = 0;

class EdgeItem;
class NodeItem;

class EdgeItem: public QCanvasLine
{
public:
    EdgeItem( NodeItem*, NodeItem*, QCanvas *canvas );
    void setFromPoint( int x, int y ) ;
    void setToPoint( int x, int y );
    static int count() { return c; }
    void moveBy(double dx, double dy);
private:
    static int c;
};

static const int imageRTTI = 984376;

class ImageItem: public QCanvasRectangle
{
public:
    ImageItem( QImage img, QCanvas *canvas );
    int rtti () const { return imageRTTI; }
    bool hit( const QPoint&) const;
protected:
    void drawShape( QPainter & );
private:
    QImage image;
    QPixmap pixmap;
};

ImageItem::ImageItem( QImage img, QCanvas *canvas )
    : QCanvasRectangle( canvas ), image(img)
{
    setSize( image.width(), image.height() );

#if !defined(Q_WS_QWS)
    pixmap.convertFromImage(image, OrderedAlphaDither);
#endif
}

void ImageItem::drawShape( QPainter &p )
{
// On Qt/Embedded, we can paint a QImage as fast as a QPixmap,
// but on other platforms, we need to use a QPixmap.
#if defined(Q_WS_QWS)
    p.drawImage( int(x()), int(y()), image, 0, 0, -1, -1, OrderedAlphaDither );
#else
    p.drawPixmap( int(x()), int(y()), pixmap );
#endif
}

bool ImageItem::hit( const QPoint &p ) const
{
    int ix = p.x()-int(x());
    int iy = p.y()-int(y());
    if ( !image.valid( ix , iy ) )
        return FALSE;
    QRgb pixel = image.pixel( ix, iy );
    return qAlpha( pixel ) != 0;
}

class NodeItem: public QCanvasEllipse
{
public:
    NodeItem( QCanvas *canvas );
    ~NodeItem() {}

    void addInEdge( EdgeItem *edge ) { inList.append( edge ); }
    void addOutEdge( EdgeItem *edge ) { outList.append( edge ); }

    void moveBy(double dx, double dy);

    //    QPoint center() { return boundingRect().center(); }
private:
    QPtrList<EdgeItem> inList;
    QPtrList<EdgeItem> outList;
};

int EdgeItem::c = 0;

void EdgeItem::moveBy(double, double)
{
    //nothing
}

EdgeItem::EdgeItem( NodeItem *from, NodeItem *to, QCanvas *canvas )
    : QCanvasLine( canvas )
{
    c++;
    setPen( *tp );
    setBrush( *tb );
    from->addOutEdge( this );
    to->addInEdge( this );
    setPoints( int(from->x()), int(from->y()), int(to->x()), int(to->y()) );
    setZ( 127 );
}

void EdgeItem::setFromPoint( int x, int y )
{
    setPoints( x,y, endPoint().x(), endPoint().y() );
}

void EdgeItem::setToPoint( int x, int y )
{
    setPoints( startPoint().x(), startPoint().y(), x, y );
}

void NodeItem::moveBy(double dx, double dy)
{
    QCanvasEllipse::moveBy( dx, dy );

    QPtrListIterator<EdgeItem> it1( inList );
    EdgeItem *edge;
    while (( edge = it1.current() )) {
        ++it1;
        edge->setToPoint( int(x()), int(y()) );
    }
    QPtrListIterator<EdgeItem> it2( outList );
    while (( edge = it2.current() )) {
        ++it2;
        edge->setFromPoint( int(x()), int(y()) );
    }
}

NodeItem::NodeItem( QCanvas *canvas )
    : QCanvasEllipse( 6, 6, canvas )
{
    setPen( *tp );
    setBrush( *tb );
    setZ( 128 );
}

FigureEditor::FigureEditor(
        QCanvas& c, QWidget* parent,
        const char* name, WFlags f) :
    QCanvasView(&c,parent,name,f)
{
}

void FigureEditor::contentsMousePressEvent(QMouseEvent* e)
{
    QPoint p = inverseWorldMatrix().map(e->pos());
    QCanvasItemList l=canvas()->collisions(p);
    for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
        if ( (*it)->rtti() == imageRTTI ) {
            ImageItem *item= (ImageItem*)(*it);
            if ( !item->hit( p ) )
                 continue;
        }
        moving = *it;
        moving_start = p;
        return;
    }
    moving = 0;
}

void FigureEditor::clear()
{
    QCanvasItemList list = canvas()->allItems();
    QCanvasItemList::Iterator it = list.begin();
    for (; it != list.end(); ++it) {
        if ( *it )
            delete *it;
    }
}

void FigureEditor::contentsMouseMoveEvent(QMouseEvent* e)
{
    if ( moving ) {
        QPoint p = inverseWorldMatrix().map(e->pos());
        moving->moveBy(p.x() - moving_start.x(),
                       p.y() - moving_start.y());
        moving_start = p;
        canvas()->update();
    }
}

BouncyLogo::BouncyLogo(QCanvas* canvas) :
    QCanvasSprite(0,canvas)
{
    static QCanvasPixmapArray logo("qt-trans.xpm");
    setSequence(&logo);
    setAnimated(TRUE);
    initPos();
}

const int logo_rtti = 1234;

int BouncyLogo::rtti() const
{
    return logo_rtti;
}

void BouncyLogo::initPos()
{
    initSpeed();
    int trial=1000;
    do {
        move(rand()%canvas()->width(),rand()%canvas()->height());
        advance(0);
    } while (trial-- && xVelocity()==0.0 && yVelocity()==0.0);
}

void BouncyLogo::initSpeed()
{
    const double speed = 4.0;
    double d = (double)(rand()%1024) / 1024.0;
    setVelocity( d*speed*2-speed, (1-d)*speed*2-speed );
}

void BouncyLogo::advance(int stage)
{
    switch ( stage ) {
      case 0: {
        double vx = xVelocity();
        double vy = yVelocity();

        if ( vx == 0.0 && vy == 0.0 ) {
            // stopped last turn
            initSpeed();
            vx = xVelocity();
            vy = yVelocity();
        }

        double nx = x() + vx;
        double ny = y() + vy;

        if ( nx < 0 || nx >= canvas()->width() )
            vx = -vx;
        if ( ny < 0 || ny >= canvas()->height() )
            vy = -vy;

        for (int bounce=0; bounce<4; bounce++) {
            QCanvasItemList l=collisions(FALSE);
            for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
                QCanvasItem *hit = *it;
                if ( hit->rtti()==logo_rtti && hit->collidesWith(this) ) {
                    switch ( bounce ) {
                      case 0:
                        vx = -vx;
                        break;
                      case 1:
                        vy = -vy;
                        vx = -vx;
                        break;
                      case 2:
                        vx = -vx;
                        break;
                      case 3:
                        // Stop for this turn
                        vx = 0;
                        vy = 0;
                        break;
                    }
                    setVelocity(vx,vy);
                    break;
                }
            }
        }

        if ( x()+vx < 0 || x()+vx >= canvas()->width() )
            vx = 0;
        if ( y()+vy < 0 || y()+vy >= canvas()->height() )
            vy = 0;

        setVelocity(vx,vy);
      } break;
      case 1:
        QCanvasItem::advance(stage);
        break;
    }
}

static uint mainCount = 0;
static QImage *butterflyimg;
static QImage *logoimg;

Main::Main(QCanvas& c, QWidget* parent, const char* name, WFlags f) :
    QMainWindow(parent,name,f),
    canvas(c)
{
    editor = new FigureEditor(canvas,this);
    QMenuBar* menu = menuBar();

    QPopupMenu* file = new QPopupMenu( menu );
    file->insertItem("&Fill canvas", this, SLOT(init()), CTRL+Key_F);
    file->insertItem("&Erase canvas", this, SLOT(clear()), CTRL+Key_E);
    file->insertItem("&New view", this, SLOT(newView()), CTRL+Key_N);
    file->insertSeparator();
    file->insertItem("&Print", this, SLOT(print()), CTRL+Key_P);
    file->insertSeparator();
    file->insertItem("E&xit", qApp, SLOT(quit()), CTRL+Key_Q);
    menu->insertItem("&File", file);

    QPopupMenu* edit = new QPopupMenu( menu );
    edit->insertItem("Add &Circle", this, SLOT(addCircle()), ALT+Key_C);
    edit->insertItem("Add &Hexagon", this, SLOT(addHexagon()), ALT+Key_H);
    edit->insertItem("Add &Polygon", this, SLOT(addPolygon()), ALT+Key_P);
    edit->insertItem("Add Spl&ine", this, SLOT(addSpline()), ALT+Key_I);
    edit->insertItem("Add &Text", this, SLOT(addText()), ALT+Key_T);
    edit->insertItem("Add &Line", this, SLOT(addLine()), ALT+Key_L);
    edit->insertItem("Add &Rectangle", this, SLOT(addRectangle()), ALT+Key_R);
    edit->insertItem("Add &Sprite", this, SLOT(addSprite()), ALT+Key_S);
    edit->insertItem("Create &Mesh", this, SLOT(addMesh()), ALT+Key_M );
    edit->insertItem("Add &Alpha-blended image", this, SLOT(addButterfly()), ALT+Key_A);
    menu->insertItem("&Edit", edit);

    QPopupMenu* view = new QPopupMenu( menu );
    view->insertItem("&Enlarge", this, SLOT(enlarge()), SHIFT+CTRL+Key_Plus);
    view->insertItem("Shr&ink", this, SLOT(shrink()), SHIFT+CTRL+Key_Minus);
    view->insertSeparator();
    view->insertItem("&Rotate clockwise", this, SLOT(rotateClockwise()), CTRL+Key_PageDown);
    view->insertItem("Rotate &counterclockwise", this, SLOT(rotateCounterClockwise()), CTRL+Key_PageUp);
    view->insertItem("&Zoom in", this, SLOT(zoomIn()), CTRL+Key_Plus);
    view->insertItem("Zoom &out", this, SLOT(zoomOut()), CTRL+Key_Minus);
    view->insertItem("Translate left", this, SLOT(moveL()), CTRL+Key_Left);
    view->insertItem("Translate right", this, SLOT(moveR()), CTRL+Key_Right);
    view->insertItem("Translate up", this, SLOT(moveU()), CTRL+Key_Up);
    view->insertItem("Translate down", this, SLOT(moveD()), CTRL+Key_Down);
    view->insertItem("&Mirror", this, SLOT(mirror()), CTRL+Key_Home);
    menu->insertItem("&View", view);

    options = new QPopupMenu( menu );
    dbf_id = options->insertItem("Double buffer", this, SLOT(toggleDoubleBuffer()));
    options->setItemChecked(dbf_id, TRUE);
    menu->insertItem("&Options",options);

    menu->insertSeparator();

    QPopupMenu* help = new QPopupMenu( menu );
    help->insertItem("&About", this, SLOT(help()), Key_F1);
    help->setItemChecked(dbf_id, TRUE);
    menu->insertItem("&Help",help);

    statusBar();

    setCentralWidget(editor);

    printer = 0;

    init();
}

void Main::init()
{
    clear();

    static int r=24;
    srand(++r);

    mainCount++;
    butterflyimg = 0;
    logoimg = 0;

    int i;
    for ( i=0; i<canvas.width() / 56; i++) {
        addButterfly();
    }
    for ( i=0; i<canvas.width() / 85; i++) {
        addHexagon();
    }
    for ( i=0; i<canvas.width() / 128; i++) {
        addLogo();
    }
}

Main::~Main()
{
    delete printer;
    if ( !--mainCount ) {
        delete[] butterflyimg;
        butterflyimg = 0;
        delete[] logoimg;
        logoimg = 0;
    }
}

void Main::newView()
{
    // Open a new view... have it delete when closed.
    Main *m = new Main(canvas, 0, 0, WDestructiveClose);
    qApp->setMainWidget(m);
    m->show();
    qApp->setMainWidget(0);
}

void Main::clear()
{
    editor->clear();
}

void Main::help()
{
    static QMessageBox* about = new QMessageBox( "Qt Canvas Example",
            "<h3>The QCanvas classes example</h3>"
            "<ul>"
                "<li> Press ALT-S for some sprites."
                "<li> Press ALT-C for some circles."
                "<li> Press ALT-L for some lines."
                "<li> Drag the objects around."
                "<li> Read the code!"
            "</ul>", QMessageBox::Information, 1, 0, 0, this, 0, FALSE );
    about->setButtonText( 1, "Dismiss" );
    about->show();
}

void Main::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Canvas Example" );
}

void Main::toggleDoubleBuffer()
{
    bool s = !options->isItemChecked(dbf_id);
    options->setItemChecked(dbf_id,s);
    canvas.setDoubleBuffering(s);
}

void Main::enlarge()
{
    canvas.resize(canvas.width()*4/3, canvas.height()*4/3);
}

void Main::shrink()
{
    canvas.resize(canvas.width()*3/4, canvas.height()*3/4);
}

void Main::rotateClockwise()
{
    QWMatrix m = editor->worldMatrix();
    m.rotate( 22.5 );
    editor->setWorldMatrix( m );
}

void Main::rotateCounterClockwise()
{
    QWMatrix m = editor->worldMatrix();
    m.rotate( -22.5 );
    editor->setWorldMatrix( m );
}

void Main::zoomIn()
{
    QWMatrix m = editor->worldMatrix();
    m.scale( 2.0, 2.0 );
    editor->setWorldMatrix( m );
}

void Main::zoomOut()
{
    QWMatrix m = editor->worldMatrix();
    m.scale( 0.5, 0.5 );
    editor->setWorldMatrix( m );
}

void Main::mirror()
{
    QWMatrix m = editor->worldMatrix();
    m.scale( -1, 1 );
    editor->setWorldMatrix( m );
}

void Main::moveL()
{
    QWMatrix m = editor->worldMatrix();
    m.translate( -16, 0 );
    editor->setWorldMatrix( m );
}

void Main::moveR()
{
    QWMatrix m = editor->worldMatrix();
    m.translate( +16, 0 );
    editor->setWorldMatrix( m );
}

void Main::moveU()
{
    QWMatrix m = editor->worldMatrix();
    m.translate( 0, -16 );
    editor->setWorldMatrix( m );
}

void Main::moveD()
{
    QWMatrix m = editor->worldMatrix();
    m.translate( 0, +16 );
    editor->setWorldMatrix( m );
}

void Main::print()
{
    if ( !printer ) printer = new QPrinter;
    if ( printer->setup(this) ) {
        QPainter pp(printer);
        canvas.drawArea(QRect(0,0,canvas.width(),canvas.height()),&pp,FALSE);
    }
}

void Main::addSprite()
{
    QCanvasItem* i = new BouncyLogo(&canvas);
    i->setZ(rand()%256);
    i->show();
}

QString butterfly_fn;
QString logo_fn;

void Main::addButterfly()
{
    if ( butterfly_fn.isEmpty() )
        return;
    if ( !butterflyimg ) {
        butterflyimg = new QImage[4];
        butterflyimg[0].load( butterfly_fn );
        butterflyimg[1] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.75),
                int(butterflyimg[0].height()*0.75) );
        butterflyimg[2] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.5),
                int(butterflyimg[0].height()*0.5) );
        butterflyimg[3] = butterflyimg[0].smoothScale( int(butterflyimg[0].width()*0.25),
                int(butterflyimg[0].height()*0.25) );
    }
    QCanvasPolygonalItem* i = new ImageItem(butterflyimg[rand()%4],&canvas);
    i->move(rand()%(canvas.width()-butterflyimg->width()),
            rand()%(canvas.height()-butterflyimg->height()));
    i->setZ(rand()%256+250);
    i->show();
}

void Main::addLogo()
{
    if ( logo_fn.isEmpty() )
        return;
    if ( !logoimg ) {
        logoimg = new QImage[4];
        logoimg[0].load( logo_fn );
        logoimg[1] = logoimg[0].smoothScale( int(logoimg[0].width()*0.75),
                int(logoimg[0].height()*0.75) );
        logoimg[2] = logoimg[0].smoothScale( int(logoimg[0].width()*0.5),
                int(logoimg[0].height()*0.5) );
        logoimg[3] = logoimg[0].smoothScale( int(logoimg[0].width()*0.25),
                int(logoimg[0].height()*0.25) );
    }
    QCanvasPolygonalItem* i = new ImageItem(logoimg[rand()%4],&canvas);
    i->move(rand()%(canvas.width()-logoimg->width()),
            rand()%(canvas.height()-logoimg->width()));
    i->setZ(rand()%256+256);
    i->show();
}

void Main::addCircle()
{
    QCanvasPolygonalItem* i = new QCanvasEllipse(50,50,&canvas);
    i->setBrush( QColor(rand()%32*8,rand()%32*8,rand()%32*8) );
    i->move(rand()%canvas.width(),rand()%canvas.height());
    i->setZ(rand()%256);
    i->show();
}

void Main::addHexagon()
{
    QCanvasPolygon* i = new QCanvasPolygon(&canvas);
    const int size = canvas.width() / 25;
    QPointArray pa(6);
    pa[0] = QPoint(2*size,0);
    pa[1] = QPoint(size,-size*173/100);
    pa[2] = QPoint(-size,-size*173/100);
    pa[3] = QPoint(-2*size,0);
    pa[4] = QPoint(-size,size*173/100);
    pa[5] = QPoint(size,size*173/100);
    i->setPoints(pa);
    i->setBrush( QColor(rand()%32*8,rand()%32*8,rand()%32*8) );
    i->move(rand()%canvas.width(),rand()%canvas.height());
    i->setZ(rand()%256);
    i->show();
}

void Main::addPolygon()
{
    QCanvasPolygon* i = new QCanvasPolygon(&canvas);
    const int size = canvas.width()/2;
    QPointArray pa(6);
    pa[0] = QPoint(0,0);
    pa[1] = QPoint(size,size/5);
    pa[2] = QPoint(size*4/5,size);
    pa[3] = QPoint(size/6,size*5/4);
    pa[4] = QPoint(size*3/4,size*3/4);
    pa[5] = QPoint(size*3/4,size/4);
    i->setPoints(pa);
    i->setBrush( QColor(rand()%32*8,rand()%32*8,rand()%32*8) );
    i->move(rand()%canvas.width(),rand()%canvas.height());
    i->setZ(rand()%256);
    i->show();
}

void Main::addSpline()
{
    QCanvasSpline* i = new QCanvasSpline(&canvas);
    const int size = canvas.width()/6;
    QPointArray pa(12);
    pa[0] = QPoint(0,0);
    pa[1] = QPoint(size/2,0);
    pa[2] = QPoint(size,size/2);
    pa[3] = QPoint(size,size);
    pa[4] = QPoint(size,size*3/2);
    pa[5] = QPoint(size/2,size*2);
    pa[6] = QPoint(0,size*2);
    pa[7] = QPoint(-size/2,size*2);
    pa[8] = QPoint(size/4,size*3/2);
    pa[9] = QPoint(0,size);
    pa[10]= QPoint(-size/4,size/2);
    pa[11]= QPoint(-size/2,0);
    i->setControlPoints(pa);
    i->setBrush( QColor(rand()%32*8,rand()%32*8,rand()%32*8) );
    i->move(rand()%canvas.width(),rand()%canvas.height());
    i->setZ(rand()%256);
    i->show();
}

void Main::addText()
{
    QCanvasText* i = new QCanvasText(&canvas);
    i->setText("QCanvasText");
    i->move(rand()%canvas.width(),rand()%canvas.height());
    i->setZ(rand()%256);
    i->show();
}

void Main::addLine()
{
    QCanvasLine* i = new QCanvasLine(&canvas);
    i->setPoints( rand()%canvas.width(), rand()%canvas.height(),
                  rand()%canvas.width(), rand()%canvas.height() );
    i->setPen( QPen(QColor(rand()%32*8,rand()%32*8,rand()%32*8), 6) );
    i->setZ(rand()%256);
    i->show();
}

void Main::addMesh()
{
    int x0 = 0;
    int y0 = 0;

    if ( !tb ) tb = new QBrush( Qt::red );
    if ( !tp ) tp = new QPen( Qt::black );

    int nodecount = 0;

    int w = canvas.width();
    int h = canvas.height();

    const int dist = 30;
    int rows = h / dist;
    int cols = w / dist;

#ifndef QT_NO_PROGRESSDIALOG
    QProgressDialog progress( "Creating mesh...", "Abort", rows,
                              this, "progress", TRUE );
#endif

    QMemArray<NodeItem*> lastRow(cols);
    for ( int j = 0; j < rows; j++ ) {
        int n = j%2 ? cols-1 : cols;
        NodeItem *prev = 0;
        for ( int i = 0; i < n; i++ ) {
            NodeItem *el = new NodeItem( &canvas );
            nodecount++;
            int r = rand();
            int xrand = r %20;
            int yrand = (r/20) %20;
            el->move( xrand + x0 + i*dist + (j%2 ? dist/2 : 0 ),
                      yrand + y0 + j*dist );

            if ( j > 0 ) {
                if ( i < cols-1 )
                    (new EdgeItem( lastRow[i], el, &canvas ))->show();
                if ( j%2 )
                    (new EdgeItem( lastRow[i+1], el, &canvas ))->show();
                else if ( i > 0 )
                    (new EdgeItem( lastRow[i-1], el, &canvas ))->show();
            }
            if ( prev ) {
                (new EdgeItem( prev, el, &canvas ))->show();
            }
            if ( i > 0 ) lastRow[i-1] = prev;
            prev = el;
            el->show();
        }
        lastRow[n-1]=prev;
#ifndef QT_NO_PROGRESSDIALOG
        progress.setProgress( j );
        if ( progress.wasCancelled() )
            break;
#endif
    }
#ifndef QT_NO_PROGRESSDIALOG
    progress.setProgress( rows );
#endif
    // qDebug( "%d nodes, %d edges", nodecount, EdgeItem::count() );
}

void Main::addRectangle()
{
    QCanvasPolygonalItem *i = new QCanvasRectangle( rand()%canvas.width(),rand()%canvas.height(),
                            canvas.width()/5,canvas.width()/5,&canvas);
    int z = rand()%256;
    i->setBrush( QColor(z,z,z) );
    i->setPen( QPen(QColor(rand()%32*8,rand()%32*8,rand()%32*8), 6) );
    i->setZ(z);
    i->show();
}

Main:

#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qmenubar.h>
#include <qapplication.h>
#include <qimage.h>

#include "canvas.h"

#include <stdlib.h>

extern QString butterfly_fn;
extern QString logo_fn;

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

    /*
    qDebug("sizeof(QCanvasPolygonalItem)=%d",sizeof(QCanvasPolygonalItem));
    qDebug("sizeof(QCanvasText)=%d",sizeof(QCanvasText));
    qDebug("sizeof(QWidget)=%d",sizeof(QWidget));
    qDebug("sizeof(QLabel)=%d",sizeof(QLabel));
    */

    if ( argc > 1 )
        butterfly_fn = argv[1];
    else
        butterfly_fn = "butterfly.png";

    if ( argc > 2 )
        logo_fn = argv[2];
    else
        logo_fn = "qtlogo.png";

    QCanvas canvas(800,600);
    canvas.setAdvancePeriod(30);
    Main m(canvas);
    m.resize(m.sizeHint());

    qApp->setMainWidget(&m);

    m.setCaption("Qt Example - Canvas");
    if ( QApplication::desktop()->width() > m.width() + 10
         && QApplication::desktop()->height() > m.height() +30 )
        m.show();
    else
        m.showMaximized();

    m.show();
    //    m.help();
    qApp->setMainWidget(0);

    QObject::connect( qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()) );

    return app.exec();
}

See also Examples.


Listviews with Checkable Items

This example program shows how to use listviews with different types of checkable items.

Header file:

/****************************************************************************
** $Id:  qt/checklists.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef CHECKLISTS_H
#define CHECKLISTS_H

#include <qwidget.h>

class QListView;
class QLabel;

class CheckLists : public QWidget
{
    Q_OBJECT

public:
    CheckLists( QWidget *parent = 0, const char *name = 0 );

protected:
    QListView *lv1, *lv2;
    QLabel *label;

protected slots:
    void copy1to2();
    void copy2to3();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/checklists.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "checklists.h"

#include <qlistview.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qvaluelist.h>
#include <qstring.h>
#include <qpushbutton.h>
#include <qlayout.h>

/*
 * Constructor
 *
 * Create all child widgets of the CheckList Widget
 */

CheckLists::CheckLists( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    QHBoxLayout *lay = new QHBoxLayout( this );
    lay->setMargin( 5 );

    // create a widget which layouts its childs in a column
    QVBoxLayout *vbox1 = new QVBoxLayout( lay );
    vbox1->setMargin( 5 );

    // First child: a Label
    vbox1->addWidget( new QLabel( "Check some items!", this ) );

    // Second child: the ListView
    lv1 = new QListView( this );
    vbox1->addWidget( lv1 );
    lv1->addColumn( "Items" );
    lv1->setRootIsDecorated( TRUE );

    // create a list with 4 ListViewItems which will be parent items of other ListViewItems
    QValueList<QListViewItem *> parentList;

    parentList.append( new QListViewItem( lv1, "Parent Item 1" ) );
    parentList.append( new QListViewItem( lv1, "Parent Item 2" ) );
    parentList.append( new QListViewItem( lv1, "Parent Item 3" ) );
    parentList.append( new QListViewItem( lv1, "Parent Item 4" ) );

    QListViewItem *item = 0;
    unsigned int num = 1;
    // go through the list of parent items...
    for ( QValueList<QListViewItem*>::Iterator it = parentList.begin(); it != parentList.end();
          ( *it )->setOpen( TRUE ), ++it, num++ ) {
        item = *it;
        // ...and create 5 checkable child ListViewItems for each parent item
        for ( unsigned int i = 1; i <= 5; i++ )
            (void)new QCheckListItem( item, QString( "%1. Child of Parent %2" ).arg( i ).arg( num ), QCheckListItem::CheckBox );
    }

    // Create another widget for layouting
    QVBoxLayout *tmp = new QVBoxLayout( lay );
    tmp->setMargin( 5 );

    // create a pushbutton
    QPushButton *copy1 = new QPushButton( "  ->  ", this );
    tmp->addWidget( copy1 );
    copy1->setMaximumWidth( copy1->sizeHint().width() );
    // connect the SIGNAL clicked() of the pushbutton with the SLOT copy1to2()
    connect( copy1, SIGNAL( clicked() ), this, SLOT( copy1to2() ) );

    // another widget for layouting
    QVBoxLayout *vbox2 = new QVBoxLayout( lay );
    vbox2->setMargin( 5 );

    // and another label
    vbox2->addWidget( new QLabel( "Check one item!", this ) );

    // create the second listview
    lv2 = new QListView( this );
    vbox2->addWidget( lv2 );
    lv2->addColumn( "Items" );
    lv2->setRootIsDecorated( TRUE );

    // another widget needed for layouting only
    tmp = new QVBoxLayout( lay );
    tmp->setMargin( 5 );

    // create another pushbutton...
    QPushButton *copy2 = new QPushButton( "  ->  ", this );
    lay->addWidget( copy2 );
    copy2->setMaximumWidth( copy2->sizeHint().width() );
    // ...and connect its clicked() SIGNAL to the copy2to3() SLOT
    connect( copy2, SIGNAL( clicked() ), this, SLOT( copy2to3() ) );

    tmp = new QVBoxLayout( lay );
    tmp->setMargin( 5 );

    // and create a label which will be at the right of the window
    label = new QLabel( "No Item yet...", this );
    tmp->addWidget( label );
}

/*
 * SLOT copy1to2()
 *
 * Copies all checked ListViewItems from the first ListView to
 * the second one, and inserts them as Radio-ListViewItem.
 */

void CheckLists::copy1to2()
{
    // create an iterator which operates on the first ListView
    QListViewItemIterator it( lv1 );

    lv2->clear();

    // Insert first a controller Item into the second ListView. Always if Radio-ListViewItems
    // are inserted into a Listview, the parent item of these MUST be a controller Item!
    QCheckListItem *item = new QCheckListItem( lv2, "Controller", QCheckListItem::Controller );
    item->setOpen( TRUE );

    // iterate through the first ListView...
    for ( ; it.current(); ++it )
        // ...check state of childs, and...
        if ( it.current()->parent() )
            // ...if the item is checked...
            if ( ( (QCheckListItem*)it.current() )->isOn() )
                // ...insert a Radio-ListViewItem with the same text into the second ListView
                (void)new QCheckListItem( item, it.current()->text( 0 ), QCheckListItem::RadioButton );

    if ( item->firstChild() )
        ( ( QCheckListItem* )item->firstChild() )->setOn( TRUE );
}

/*
 * SLOT copy2to3()
 *
 * Copies the checked item of the second ListView into the
 * Label at the right.
 */

void CheckLists::copy2to3()
{
    // create an iterator which operates on the second ListView
    QListViewItemIterator it( lv2 );

    label->setText( "No Item checked" );

    // iterate through the second ListView...
    for ( ; it.current(); ++it )
        // ...check state of childs, and...
        if ( it.current()->parent() )
            // ...if the item is checked...
            if ( ( (QCheckListItem*)it.current() )->isOn() )
                // ...set the text of the item to the label
                label->setText( it.current()->text( 0 ) );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "checklists.h"
#include <qapplication.h>

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

    CheckLists checklists;
    checklists.resize( 650, 350 );
    checklists.setCaption( "Qt Example - CheckLists" );
    a.setMainWidget( &checklists );
    checklists.show();

    return a.exec();
}

See also Examples.


A small client-server example

This example shows how two programs can communicate using sockets.

Two simple example programs are provided, a client program and a server program. Both use the QSocket class, and the server also uses QServerSocket class.

The server listens on port number 4242 and accepts incoming connections. It sends back every line it receives from the client, prepended with the line number.

The client tries to connect to the server on the host specified on the command line or to localhost if no command line arguments are specified. You can send single lines to the server.

Implementation server (server.cpp):

/****************************************************************************
** $Id:  qt/server.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qsocket.h>
#include <qserversocket.h>
#include <qapplication.h>
#include <qvbox.h>
#include <qtextview.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtextstream.h>

#include <stdlib.h>

/*
  The ClientSocket class provides a socket that is connected with a client.
  For every client that connects to the server, the server creates a new
  instance of this class.
*/
class ClientSocket : public QSocket
{
    Q_OBJECT
public:
    ClientSocket( int sock, QObject *parent=0, const char *name=0 ) :
        QSocket( parent, name )
    {
        line = 0;
        connect( this, SIGNAL(readyRead()), SLOT(readClient()) );
        connect( this, SIGNAL(connectionClosed()), SLOT(connectionClosed()) );
        setSocket( sock );
    }

    ~ClientSocket()
    {
    }

private slots:
    void readClient()
    {
        while ( canReadLine() ) {
            QTextStream os( this );
            os << line << ": " << readLine();
            line++;
        }
    }

    void connectionClosed()
    {
        delete this;
    }

private:
    int line;
};

/*
  The SimpleServer class handles new connections to the server. For every
  client that connects, it creates a new ClientSocket -- that instance is now
  responsible for the communication with that client.
*/
class SimpleServer : public QServerSocket
{
    Q_OBJECT
public:
    SimpleServer( QObject* parent=0 ) :
        QServerSocket( 4242, 1, parent )
    {
        if ( !ok() ) {
            qWarning("Failed to bind to port 4242");
            exit(1);
        }
    }

    ~SimpleServer()
    {
    }

    void newConnection( int socket )
    {
        (void)new ClientSocket( socket, this );
        emit newConnect();
    }

signals:
    void newConnect();
};

/*
  The ServerInfo class provides a small GUI for the server. It also creates the
  SimpleServer and as a result the server.
*/
class ServerInfo : public QVBox
{
    Q_OBJECT
public:
    ServerInfo()
    {
        SimpleServer *server = new SimpleServer( this );

        QString itext = QString(
                "This is a small server example.\n"
                "Connect with the client now."
                );
        QLabel *lb = new QLabel( itext, this );
        lb->setAlignment( AlignHCenter );
        infoText = new QTextView( this );
        QPushButton *quit = new QPushButton( "Quit" , this );

        connect( server, SIGNAL(newConnect()), SLOT(newConnect()) );
        connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
    }

    ~ServerInfo()
    {
    }

private slots:
    void newConnect()
    {
        infoText->append( "New connection\n" );
    }

private:
    QTextView *infoText;
};

int main( int argc, char** argv )
{
    QApplication app( argc, argv );
    ServerInfo info;
    app.setMainWidget( &info );
    info.show();
    return app.exec();
}

#include "server.moc"

Implementation client (client.cpp):

/****************************************************************************
** $Id:  qt/client.cpp   3.0.5   edited Nov 5 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qsocket.h>
#include <qapplication.h>
#include <qvbox.h>
#include <qhbox.h>
#include <qtextview.h>
#include <qlineedit.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtextstream.h>

class Client : public QVBox
{
    Q_OBJECT
public:
    Client( const QString &host, Q_UINT16 port )
    {
        // GUI layout
        infoText = new QTextView( this );
        QHBox *hb = new QHBox( this );
        inputText = new QLineEdit( hb );
        QPushButton *send = new QPushButton( tr("Send") , hb );
        QPushButton *close = new QPushButton( tr("Close connection") , this );
        QPushButton *quit = new QPushButton( tr("Quit") , this );

        connect( send, SIGNAL(clicked()), SLOT(sendToServer()) );
        connect( close, SIGNAL(clicked()), SLOT(closeConnection()) );
        connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

        // create the socket and connect various of its signals
        socket = new QSocket( this );
        connect( socket, SIGNAL(connected()),
                SLOT(socketConnected()) );
        connect( socket, SIGNAL(connectionClosed()),
                SLOT(socketConnectionClosed()) );
        connect( socket, SIGNAL(readyRead()),
                SLOT(socketReadyRead()) );
        connect( socket, SIGNAL(error(int)),
                SLOT(socketError(int)) );

        // connect to the server
        infoText->append( tr("Trying to connect to the server\n") );
        socket->connectToHost( host, port );
    }

    ~Client()
    {
    }

private slots:
    void closeConnection()
    {
        socket->close();
        if ( socket->state() == QSocket::Closing ) {
            // We have a delayed close.
            connect( socket, SIGNAL(delayedCloseFinished()),
                    SLOT(socketClosed()) );
        } else {
            // The socket is closed.
            socketClosed();
        }
    }

    void sendToServer()
    {
        // write to the server
        QTextStream os(socket);
        os << inputText->text() << "\n";
        inputText->setText( "" );
    }

    void socketReadyRead()
    {
        // read from the server
        while ( socket->canReadLine() ) {
            infoText->append( socket->readLine() );
        }
    }

    void socketConnected()
    {
        infoText->append( tr("Connected to server\n") );
    }

    void socketConnectionClosed()
    {
        infoText->append( tr("Connection closed by the server\n") );
    }

    void socketClosed()
    {
        infoText->append( tr("Connection closed\n") );
    }

    void socketError( int e )
    {
        infoText->append( tr("Error number %1 occurred\n").arg(e) );
    }

private:
    QSocket *socket;
    QTextView *infoText;
    QLineEdit *inputText;
};

int main( int argc, char** argv )
{
    QApplication app( argc, argv );
    Client client( argc<2 ? "localhost" : argv[1], 4242 );
    app.setMainWidget( &client );
    client.show();
    return app.exec();
}

#include "client.moc"

See also Network Examples.


Collection Classes

A collection class is a container which holds a number of items in a certain data structure and performs operations on the contained items; insert, remove, find etc.

Qt has several value-based and several pointer-based collection classes. The pointer-based collection classes work with pointers to items, while the value-based classes store copies of their items. The value-based collections are very similar to STL container classes, and can be used with STL algorithms and containers. See the Qt Template Library documentation for details.

The value-based collections are:

  • QValueList, a value-based list
  • QValueVector, a value-based vector structure
  • QValueStack, a value-based stack structure
  • QMap, a value-based dictionary structure

The pointer-based collections are:

  • QCache and QIntCache, LRU (least recently used) cache structures.
  • QDict, QIntDict and QPtrDict dictionary structures.
  • QPtrList, a double linked list structure.
  • QPtrQueue, a FIFO (first in, first out) queue structure.
  • QPtrStack, a LIFO (last in, first out) stack structure.
  • QPtrVector, a vector structure.

QMemArray is exceptional; it is neither pointer nor value based, but memory based. For maximum efficiency with the simple data types usually used in arrays, it uses bitwise operations to copy and compare array elements.

Some of these classes have corresponding iterators. An iterator is a class for traversing the items in a collection:

  • QCacheIterator and QIntCacheIterator
  • QDictIterator, QIntDictIterator, and QPtrDictIterator
  • QPtrListIterator
  • QValueListIterator, and QValueListConstIterator
  • QMapIterator, and QMapConstIterator

The value-based collections plus algorithms operating on them are grouped together in the Qt Template Library. See the respective documentation for details.

The rest of this page dicusses the pointer-based containers.

Architecture of the pointer-based containers

There are four internal base classes for the pointer-based containers (QGCache, QGDict, QGList and QGVector) that operate on void pointers. A thin template layer implements the actual collections by casting item pointers to and from void pointers.

This strategy allows Qt's templates to be very economical on space (instantiating one of these templates adds only inlinable calls to the base classes), while it does not hurt performance.

A QPtrList Example

This example shows how to store Employee items in a list and prints them out in the reverse order:

    #include <qptrlist.h>
    #include <qstring.h>
    #include <stdio.h>

    class Employee
    {
    public:
        Employee( const char *name, int salary ) { n=name; s=salary; }
        const char *name()   const               { return n; }
        int         salary() const               { return s; }
    private:
        QString     n;
        int         s;
    };

    int main()
    {
        QPtrList<Employee> list;                // list of pointers to Employee
        list.setAutoDelete( TRUE );     // delete items when they are removed

        list.append( new Employee("Bill", 50000) );
        list.append( new Employee("Steve",80000) );
        list.append( new Employee("Ron",  60000) );

        QPtrListIterator<Employee> it(list); // iterator for employee list
        for ( it.toLast(); it.current(); --it) ) {
            Employee *emp = it.current();
            printf( "%s earns %d\n", emp->name(), emp->salary() );
        }

        return 0;
    }

Program output:

    Ron earns 60000
    Steve earns 80000
    Bill earns 50000

Managing Collection Items

All pointer-based collections inherit the QPtrCollection base class. This class knows only the number of items in the collection and the delete strategy.

Items in a collection are by default not deleted when they are removed from the collection. The QPtrCollection::setAutoDelete() function specifies the delete strategy. In the list example, we enable auto-deletion to make the list delete the items when they are removed from the list.

When inserting an item into a collection, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the collection copy all of the item's data (known as a deep copy) when an item is inserted. All collection functions that insert an item call the virtual function QPtrCollection::newItem() for the item to be inserted. Inherit a collection and reimplement it if you want to have deep copies in your collection.

When removing an item from a list, the virtual function QPtrCollection::deleteItem() is called. The default implementation in all collection classes deletes the item if auto-deletion is enabled.

Usage

A pointer-based collection class, such as QPtrList<type>, defines a collection of pointers to type objects. The pointer (*) is implicit.

We discuss QPtrList here, but the same techniques apply for all pointer-based collection classes and all collection class iterators.

Template instantiation:

    QPtrList<Employee> list;            // wherever the list is used

The item's class or type, Employee in our example, must be defined prior to the list definition.

    // Does not work: Employee is not defined
    class Employee;
    QPtrList<Employee> list;

    // This works: Employee is defined before it is used
    class Employee {
        ...
    };
    QPtrList<Employee> list;

Iterators

Although QPtrList has member functions to traverse the list, it can often be better to make use of an iterator. QPtrListIterator is very safe and can traverse lists that are being modified at the same time. Multiple iterators can work independently on the same collection.

A QPtrList has an internal list of all iterators that are currently operating on the list. When a list entry is removed, the list updates all iterators to point to this entry.

The QDict and QCache collections have no traversal functions. To traverse these collections, you must use QDictIterator or QCacheIterator.

Predefined Collections

Qt has the following predefined collection classes:

  • String lists: QStrList, QStrIList (qstrlist.h) and QStringList (qstringlist.h)
  • String vectors: QStrVec and QStrIVec (qstrvec.h); these are obsolete

In almost all cases you would choose QStringList, a value list of implicitly shared QString unicode strings. QPtrStrList and QPtrStrIList store only char pointers, not the strings themselves.

List of Pointer-based Collection Classes and Related Iterator Classes

QAsciiCache | Template class that provides a cache based on char* keys
QAsciiCacheIterator | Iterator for QAsciiCache collections
QAsciiDict | Template class that provides a dictionary based on char* keys
QAsciiDictIterator | Iterator for QAsciiDict collections
QBitArray | Array of bits
QBitVal | Internal class, used with QBitArray
QBuffer | I/O device that operates on a QByteArray
QByteArray | Array of bytes
QCache | Template class that provides a cache based on QString keys
QCacheIterator | Iterator for QCache collections
QCString | Abstraction of the classic C zero-terminated char array (char *)
QDict | Template class that provides a dictionary based on QString keys
QDictIterator | Iterator for QDict collections
QIntCache | Template class that provides a cache based on long keys
QIntCacheIterator | Iterator for QIntCache collections
QIntDict | Template class that provides a dictionary based on long keys
QIntDictIterator | Iterator for QIntDict collections
QObjectList | QPtrList of QObjects
QObjectListIt | Iterator for QObjectLists
QPtrCollection | The base class of most pointer-based Qt collections
QPtrDict | Template class that provides a dictionary based on void* keys
QPtrDictIterator | Iterator for QPtrDict collections
QPtrList | Template class that provides doubly-linked lists
QPtrListIterator | Iterator for QPtrList collections
QPtrQueue | Template class that provides a queue
QStrIList | Doubly-linked list of char* with case-insensitive comparison
QStrList | Doubly-linked list of char*


坐标系统

在Qt中的一个绘画设备是一个可画的二维平面。QWidget、QPixmap、QPicture和QPrinter都是绘画设备。QPainter是一个可以在上面画的对象。

一个绘画设备的默认坐标系统的原点在左上角。X轴由左向右增加，Y轴由上向下增加。对于基于像素的设备单位是像素，对于打印机是点。

一个例子

下面这个图显示了一个绘画设备的左上角的高度放大的部分。

这个矩形和线段是由下面的代码画出来的（在这个图中添加了网格）：

    void MyWidget::paintEvent( QPaintEvent * )
    {
        QPainter p( this );
        p.setPen( darkGray );
        p.drawRect( 1,2, 5,4 );
        p.setPen( lightGray );
        p.drawLine( 9,2, 7,7 );
    }

applies to all the relevant functions in QPainter. 请注意drawRect()所画的所有像素是在指定的大小之内（5*4像素）。这一点和其它工具包不同；Qt中你指定的大小包括你所要画的像素。这一点适用于所有QPainter中相关的函数。

相似的，drawLine()调用画了这个线段的两个端点，而不仅仅是一个。

这里是一些和坐标系统关系很近的类：

  • QPoint是坐标系统中的单个二维点。Qt中处理点的绝大多数函数都可以接受QPoint参数或者两个整数参数，比如QPainter::drawPoint()。

  • QSize是单个二维矢量。在内部，QPoint和QSize是一样的，但是一个点和一个大小不同，所以这两个类都存在。同样，绝大多数函数都可以接受一个QSize或者两个整数，比如QWidget::resize()。

  • QRect是一个二维的矩形。绝大多数函数都可以接受一个QRect或者四个整数，比如QWidget::setGeometry()。

  • QRegion是点的一个任意组合，包括所有通常的组合操作，例如QRegion::intersect()，并且一些常用的函数返回一个矩形的列表，这个矩形的列表的集合等于一个区域。QRegion被例如QPainter::setClipRegion()、QWidget::repaint()和QPaintEvent::region()使用。

  • QPainter是一个绘图的类。它可以用同样的代码在任何一个设备上绘画。设备中是存在差异的，QPrinter::newPage()是一个很好的例子，但QPainter可以对所有的设备按同一种方式工作。

  • QPaintDevice是一个QPainter可以在上面绘画的设备。这里有两种都基于像素的内部的设备，和两种外部设备，QPrinter和QPicture（它把QPainter的命令都记录在一个文件或者其它的QIODevice，然后再运行它们）。其它的设备都可以被定义。

变换

尽管Qt默认的坐标系统像我们上面描述的那样工作，QPainter也支持任意的变换。

这个变换引擎是一个三步的管道，和下面的Foley & Van Dam and the OpenGL Programming Guide两本书中的模型非常接近。参考那些深度的内容，这里我们给出了一个简单的概述和一个例子。

第一步使用通用变换矩阵。使用这个矩阵来定位你的模型中的对象。Qt提供了像QPainter::rotate()、QPainter::scale()、QPainter::translate()等等方法来操作这个矩阵。

QPainter::save()和QPainter::restore()存储和恢复这个矩阵。你也可以使用QWMatrix对象、QPainter::worldMatrix()和QPainter::setWorldMatrix()来存储和使用指定的矩阵。

第二步使用窗口。这个窗口在模式坐标上说明视图的边界。矩阵定位对象并且QPainter::setWindow()定位这个窗口，决定哪个坐标系统是可见的。（如果你有三维的经验，这个窗口通常是被三维投影出来的。）

第三步使用视口。视口也描述视图的边界，但是是在设备坐标上。视口和窗口描述的是同一个矩形，但是在不同的坐标系统中。

在屏幕上，默认的是你所画的通常合适的整个QWidget或者QPixmap。对于打印这个功能是非常重要的，因为只有很少的打印机可以在真个物理页面上打印。

所以每一个要画的对象被使用QPainter::worldMatrix()变换到模式坐标中，然后被QPainter::window()剪辑，最后被使用QPainter::viewport()定位到所画的设备上。

没有上述一个或两个步骤也是可能做到的。举例来说，比如你的目标是画一些按比例缩放的东西，然后使用QPainter::scale()来达到理想的效果。如果你使用一个大小固定的坐标系统，QPainter::setWindow()是最好的。等等。

这里是一个使用所有这三个机制的一个简单的例子：这个函数在aclock/aclock.cpp例子中画了一个钟表面板。我们建议你在读任何代码之前先编译和运行这个例子。尤其是，试着把这个窗口改变成不同的形状。

    void AnalogClock::drawClock( QPainter *paint )
    {
        paint->save();

首先，我们保存绘画工具的状态，这样的调用函数就保证了不会将要使用的变换干扰。

        paint->setWindow( -500,-500, 1000,1000 );

我们设置一个1000*1000、原点（0，0)在中间的窗口的模式坐标系统。

        QRect v = paint->viewport();
        int d = QMIN( v.width(), v.height() );

这个设备也许不是正方形的，但我们希望钟表是正方形的，所以我们找到它当前的视口并计算它最短的边。

        paint->setViewport( v.left() + (v.width()-d)/2,
                            v.top() + (v.height()-d)/2, d, d );

然后我们设置一个新的正方形视口，把它放在原来的中间。

现在我们做完了我们的视图。从这点上来看，当我们在（0，0）点周围画一个1000*1000的区域，我们所画的东西将会在适合输出设备的最大可能的正方形区域中显示出来。

是我们开始绘图的时候了。

        // time = QTime::currentTime();
        QPointArray pts;

因为我们在画一个钟表，所以我们需要知道时间。pts刚好是一个用来存储一些点的有用的变量。

接下来我们画三个块，一个是时针，一个是分针，最后一个是钟表面板自己。首先我们来画时针：

        paint->save();
        paint->rotate( 30*(time.hour()%12-3) + time.minute()/2 );

我们保存绘画工具，然后根据时针转动的方向旋转它。

        pts.setPoints( 4, -20,0,  0,-20, 300,0, 0,20 );
        paint->drawConvexPolygon( pts );

我们把pts设置为一个四点的多边形，好像时针就在三点钟，然后画上它。因为这个旋转，时针被画到正确的位置。

        paint->restore();

我们恢复被存储哦绘图工具，取消旋转。我们也可以通过调用rotate( -30 )，但是那样也许会导致旋转错误，所以使用save()和restore()是更好的方法。接下来，按大致相同哦方式画分针：

        paint->save();
        paint->rotate( (time.minute()-15)*6 );
        pts.setPoints( 4, -10,0, 0,-10, 400,0, 0,10 );
        paint->drawConvexPolygon( pts );
        paint->restore();

唯一的不同是如何计算要旋转的角度和多边形的形状。

要画的最后一部分就是钟表面板自己。

        for ( int i=0; i<12; i++ ) {
            paint->drawLine( 440,0, 460,0 );
            paint->rotate( 30 );
        }

十二个短的时针刻度之间的间隔是三十度。最后，绘图工具被旋转不是一个非常有用的方法，但是我们已经画完了，所以这也没什么。

        paint->restore();
    }

最后一行的函数是恢复绘图工具，这样绘图工具的调用者就不用担心我们所做的所有变换会影响它。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Cursors

This example shows how to set a mouse cursor for a widget.

Implementation:

/****************************************************************************
** $Id:  qt/cursor.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qlabel.h>
#include <qbitmap.h>
#include <qapplication.h>
#include <qlayout.h>
#include <qcursor.h>

// cb_bits and cm_bits were generated by X bitmap program.

#define cb_width  32
#define cb_height 32

static unsigned char cb_bits[] = {              // cursor bitmap
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00,
   0x00, 0x06, 0x30, 0x00, 0x80, 0x01, 0xc0, 0x00, 0x40, 0x00, 0x00, 0x01,
   0x20, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x04, 0x08, 0x3e, 0x3e, 0x08,
   0x08, 0x03, 0xe0, 0x08, 0xc4, 0x00, 0x00, 0x11, 0x04, 0x1e, 0x78, 0x10,
   0x02, 0x0c, 0x30, 0x20, 0x02, 0x40, 0x00, 0x20, 0x02, 0x40, 0x00, 0x20,
   0x02, 0x40, 0x00, 0x20, 0x02, 0x20, 0x04, 0x20, 0x02, 0x20, 0x04, 0x20,
   0x02, 0x10, 0x08, 0x20, 0x02, 0x08, 0x08, 0x20, 0x02, 0xf0, 0x07, 0x20,
   0x04, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x10, 0x08, 0x00, 0xc0, 0x08,
   0x08, 0x3c, 0x30, 0x08, 0x10, 0xe6, 0x19, 0x04, 0x20, 0x00, 0x0f, 0x02,
   0x40, 0x00, 0x00, 0x01, 0x80, 0x01, 0xc0, 0x00, 0x00, 0x06, 0x30, 0x00,
   0x00, 0xf8, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00};

#define cm_width  32
#define cm_height 32

static unsigned char cm_bits[] = {              // cursor bitmap mask
   0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xfe, 0x3f, 0x00,
   0x80, 0x07, 0xf0, 0x00, 0xc0, 0x01, 0xc0, 0x01, 0x60, 0x00, 0x00, 0x03,
   0x30, 0x00, 0x00, 0x06, 0x18, 0x00, 0x00, 0x0c, 0x0c, 0x3e, 0x3e, 0x18,
   0x0e, 0x03, 0xe0, 0x18, 0xc6, 0x00, 0x00, 0x31, 0x07, 0x1e, 0x78, 0x30,
   0x03, 0x0c, 0x30, 0x60, 0x03, 0x40, 0x00, 0x60, 0x03, 0x40, 0x00, 0x60,
   0x03, 0x40, 0x00, 0x60, 0x03, 0x20, 0x04, 0x60, 0x03, 0x20, 0x04, 0x60,
   0x03, 0x10, 0x08, 0x60, 0x03, 0x08, 0x08, 0x60, 0x03, 0xf0, 0x07, 0x60,
   0x06, 0x00, 0x00, 0x30, 0x06, 0x00, 0x00, 0x30, 0x0c, 0x00, 0xc0, 0x18,
   0x0c, 0x3c, 0x30, 0x18, 0x18, 0xe6, 0x19, 0x0c, 0x30, 0x00, 0x0f, 0x06,
   0x60, 0x00, 0x00, 0x03, 0xc0, 0x01, 0xc0, 0x01, 0x80, 0x07, 0xf0, 0x00,
   0x00, 0xfe, 0x3f, 0x00, 0x00, 0xf8, 0x0f, 0x00};

//
// The CursorView contains many labels with different cursors.
//

class CursorView : public QWidget               // cursor view
{
public:
    CursorView();
};

//
// Constructs a cursor view.
//

CursorView::CursorView()                        // construct view
{
    struct List {
        CursorShape     shape;
        const char*     name;                   // cursor name
    };
    static List list[] = {
        { ArrowCursor,          "arrowCursor" },
        { UpArrowCursor,        "upArrowCursor" },
        { CrossCursor,          "crossCursor" },
        { WaitCursor,           "waitCursor" },
        { IbeamCursor,          "ibeamCursor" },
        { SizeVerCursor,        "sizeVerCursor" },
        { SizeHorCursor,        "sizeHorCursor" },
        { SizeBDiagCursor,      "sizeBDiagCursor" },
        { SizeFDiagCursor,      "sizeFDiagCursor" },
        { SizeAllCursor,        "sizeAllCursor" },
        { BlankCursor,          "blankCursor" },
        { SplitVCursor,         "splitVCursor" },
        { SplitHCursor,         "splitHCursor" },
        { PointingHandCursor,   "pointingHandCursor" },
        { ForbiddenCursor,      "forbiddenCursor" },
        { WhatsThisCursor,      "whatsThisCursor" }
    };

    setCaption( "CursorView" );                 // set window caption

    QGridLayout* grid = new QGridLayout( this, 5, 4, 20 );
    QLabel *label;

    int i=0;
    for ( int y=0; y<4; y++ ) {                 // create the small labels
        for ( int x=0; x<4; x++ ) {
            label = new QLabel( this );
            label->setCursor( QCursor( list[i].shape ) );
            label->setText( list[i].name );
            label->setAlignment( AlignCenter );
            label->setFrameStyle( QFrame::Box | QFrame::Raised );
            grid->addWidget( label, x, y );
            i++;
        }
    }

    QBitmap cb( cb_width, cb_height, cb_bits, TRUE );
    QBitmap cm( cm_width, cm_height, cm_bits, TRUE );
    QCursor custom( cb, cm );                   // create bitmap cursor

    label = new QLabel( this );                 // create the big label
    label->setCursor( custom );
    label->setText( "Custom bitmap cursor" );
    label->setAlignment( AlignCenter );
    label->setFrameStyle( QFrame::Box | QFrame::Sunken );
    grid->addMultiCellWidget( label, 4, 4, 0, 3 );

}

//
// Create and display a CursorView.
//

int main( int argc, char **argv )
{
    QApplication a( argc, argv );               // application object
    CursorView   v;                             // cursor view
    a.setMainWidget( &v );
    v.setCaption("Qt Example - Cursors");
    v.show();
    return a.exec();
}

See also Examples.


写你自己的布局管理器

这里我们提供了一个详细的例子。CardLayout类是从同名的Java布局管理器得到的灵感。它把项目（窗口部件或者嵌套的布局）布置到彼此的顶端，每个项目通过QLayout::spacing()偏移的。

要写自己的布局类，你必须像下面这样定义：

  • 一个用来存放被布局处理的项目的数据结构。每一个项目就是一个QLayoutItem。我们将在例子中使用一个QPtrList。
  • addItem()，如何向布局中添加一个项目。
  • setGeometry()，如何构成一个布局。
  • sizeHint()，布局优先选用的大小。
  • iterator()，如何迭代布局。

在绝大多数情况下，你也需要实现minimumSize()。

card.h

#ifndef CARD_H
#define CARD_H

#include <qlayout.h>
#include <qptrlist.h>

class CardLayout : public QLayout
{
public:
    CardLayout( QWidget *parent, int dist )
        : QLayout( parent, 0, dist ) { }
    CardLayout( QLayout* parent, int dist)
        : QLayout( parent, dist ) { }
    CardLayout( int dist )
        : QLayout( dist ) { }
    ~CardLayout();

    void addItem(QLayoutItem *item);
    QSize sizeHint() const;
    QSize minimumSize() const;
    QLayoutIterator iterator();
    void setGeometry(const QRect &rect);

private:
    QPtrList<QLayoutItem> list;
};

#endif

card.cpp

#include "card.h"

首先我们为布局定义一个迭代。布局迭代被布局系统用作内部处理图形窗口部件删除操作的。它们也可以被提供给应用程序员。

这里有两个两个不同的相关类：QLayoutIterator是一个可以提供给应用程序员可见的类，它是明确地被共享。QLayoutIterator包括一个可以做任何事情地QGLayoutIterator。我们必须生成一个知道如何迭代我们地布局类的QGLayoutIterator的子类。

在这种情况下，我们选择一个简单的实现：我们把一个整数索引和指针存储到一个列表中。每一个QGLayoutIterator的子类都必须实现current()、next()和takeCurrent()，还有一个构造函数。在我们的例子中我们不需要析构函数。

class CardLayoutIterator : public QGLayoutIterator
{
public:
    CardLayoutIterator( QPtrList<QLayoutItem> *l )
        : idx( 0 ), list( l ) { }

    QLayoutItem *current()
    { return idx < int(list->count()) ? list->at(idx) : 0;  }

    QLayoutItem *next()
    { idx++; return current(); }

    QLayoutItem *takeCurrent()
    { return list->take( idx ); }

private:
    int idx;
    QPtrList<QLayoutItem> *list;
};

我们必须实现QLayout:iterator()返回一个这个布局的QLayoutIterator。

QLayoutIterator CardLayout::iterator()
{
    return QLayoutIterator( new CardLayoutIterator(&list) );
}

addItem()实现了布局项目的默认布置策略。它必须被实现。它被QLayout::add()使用，被把一个布局作为父布局的QLayout的构造函数使用，并且它被用来实现自动添加这一特性。如果你的布局有需要参数的高级布置选项，你将必须提供像QGridLayout::addMultiCell()一样的额外的访问函数。

void CardLayout::addItem( QLayoutItem *item )
{
    list.append( item );
}

布局对项目的增加负有责任。因为QLayoutItem不继承QObject，我们必须人工地删除这些项目。QLayout::deleteAllItems()函数使用我们前面定义的迭代来删除布局中的所有项目。

CardLayout::~CardLayout()
{
    deleteAllItems();
}

setGeometry()函数实际上执行了这个布局。作为参数提供的矩形不包括margin()。如果相关的话，项目之间的距离请使用spacing()。

void CardLayout::setGeometry( const QRect &rect )
{
    QLayout::setGeometry( rect );

    QPtrListIterator<QLayoutItem> it( list );
    if (it.count() == 0)
        return;

    QLayoutItem *o;

    int i = 0;

    int w = rect.width() - ( list.count() - 1 ) * spacing();
    int h = rect.height() - ( list.count() - 1 ) * spacing();

    while ( (o = it.current()) != 0 ) {
        ++it;
        QRect geom( rect.x() + i * spacing(), rect.y() + i * spacing(),
                    w, h );
        o->setGeometry( geom );
        ++i;
    }
}

sizeHint()和minimumSize()通常情况下在实现中非常相似。这两个函数返回的大小应该包括spacing()，但不包括margin()。

QSize CardLayout::sizeHint() const
{
    QSize s( 0, 0 );
    int n = list.count();
    if ( n > 0 )
        s = QSize( 100, 70 ); // start with a nice default size
    QPtrListIterator<QLayoutItem> it( list );
    QLayoutItem *o;
    while ( (o = it.current()) != 0 ) {
        ++it;
        s = s.expandedTo( o->minimumSize() );
    }
    return s + n * QSize( spacing(), spacing() );
}

QSize CardLayout::minimumSize() const
{
    QSize s( 0, 0 );
    int n = list.count();
    QPtrListIterator<QLayoutItem> it( list );
    QLayoutItem *o;
    while ( (o = it.current()) != 0 ) {
        ++it;
        s = s.expandedTo( o->minimumSize() );
    }
    return s + n * QSize( spacing(), spacing() );
}

更多的注释

这个布局没有实现heightForWidth()。

我们忽略了QLayoutItem::isEmpty()，这也就是说这个布局将会把隐藏的窗口部件显示出来。

对于复杂的布局，通过存储计算结果可以使速度得到很大的提高。在这种情况下，实现QLayoutItem::invalidate()来把被存储的数据弄脏。

调用QLayoutItem::sizeHint()，其它的也许更浪费时间，如果你在同一个函数中再一次稍晚的情况下需要这个值，你应该把它存储成局部变量。

你不应该在同一个函数中对同一项目调用QLayoutItem::setGeometry()两次。如果这个项目有几个子窗口部件的话，它会很浪费时间，因为它将不得不每次都执行一个完整的布局。相反，计算几何位置并且设置它。（这不仅仅是应用于布局，如果你实现了你自己的resizeEvent()你应该做同样的事情。）

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Customized Layoutmanager

This examples demonstrates how to write customized layout (geometry) managers like card layouts, border layout and flow layouts.

See also: Documentation of Geometry Management.

Header file of the flow layout:

/****************************************************************************
** $Id:  qt/flow.h   3.0.5   edited Oct 12 2001 $
**
** Definition of simple flow layout for custom layout example
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef FLOW_H
#define FLOW_H

#include <qlayout.h>
#include <qptrlist.h>

class SimpleFlow : public QLayout
{
public:
    SimpleFlow( QWidget *parent, int border=0, int space=-1,
                const char *name=0 )
        : QLayout( parent, border, space, name ),
        cached_width(0) {}
    SimpleFlow( QLayout* parent, int space=-1, const char *name=0 )
        : QLayout( parent, space, name ),
        cached_width(0) {}
    SimpleFlow( int space=-1, const char *name=0 )
        : QLayout( space, name ),
        cached_width(0) {}

    ~SimpleFlow();

    void addItem( QLayoutItem *item);
    bool hasHeightForWidth() const;
    int heightForWidth( int ) const;
    QSize sizeHint() const;
    QSize minimumSize() const;
    QLayoutIterator iterator();
    QSizePolicy::ExpandData expanding() const;

protected:
    void setGeometry( const QRect& );

private:
    int doLayout( const QRect&, bool testonly = FALSE );
    QPtrList<QLayoutItem> list;
    int cached_width;
    int cached_hfw;

};

#endif

Implementation of the flow layout:

/****************************************************************************
** $Id:  qt/flow.cpp   3.0.5   edited Oct 12 2001 $
**
** Implementing your own layout: flow example
**
** Copyright (C) 1996 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "flow.h"

class SimpleFlowIterator :public QGLayoutIterator
{
public:
    SimpleFlowIterator( QPtrList<QLayoutItem> *l ) :idx(0), list(l)  {}
    uint count() const;
    QLayoutItem *current();
    QLayoutItem *next();
    QLayoutItem *takeCurrent();

private:
    int idx;
    QPtrList<QLayoutItem> *list;

};

uint SimpleFlowIterator::count() const
{
    return list->count();
}

QLayoutItem *SimpleFlowIterator::current()
{
    return idx < int(count()) ? list->at(idx) : 0;
}

QLayoutItem *SimpleFlowIterator::next()
{
    idx++; return current();
}

QLayoutItem *SimpleFlowIterator::takeCurrent()
{
    return idx < int(count()) ? list->take( idx ) : 0;
}

SimpleFlow::~SimpleFlow()
{
    deleteAllItems();
}

int SimpleFlow::heightForWidth( int w ) const
{
    if ( cached_width != w ) {
        //Not all C++ compilers support "mutable" yet:
        SimpleFlow * mthis = (SimpleFlow*)this;
        int h = mthis->doLayout( QRect(0,0,w,0), TRUE );
        mthis->cached_hfw = h;
        return h;
    }
    return cached_hfw;
}

void SimpleFlow::addItem( QLayoutItem *item)
{
    list.append( item );
}

bool SimpleFlow::hasHeightForWidth() const
{
    return TRUE;
}

QSize SimpleFlow::sizeHint() const
{
    return minimumSize();
}

QSizePolicy::ExpandData SimpleFlow::expanding() const
{
    return QSizePolicy::NoDirection;
}

QLayoutIterator SimpleFlow::iterator()
{
    return QLayoutIterator( new SimpleFlowIterator( &list ) );
}

void SimpleFlow::setGeometry( const QRect &r )
{
    QLayout::setGeometry( r );
    doLayout( r );
}

int SimpleFlow::doLayout( const QRect &r, bool testonly )
{
    int x = r.x();
    int y = r.y();
    int h = 0;          //height of this line so far.
    QPtrListIterator<QLayoutItem> it(list);
    QLayoutItem *o;
    while ( (o=it.current()) != 0 ) {
        ++it;
        int nextX = x + o->sizeHint().width() + spacing();
        if ( nextX - spacing() > r.right() && h > 0 ) {
            x = r.x();
            y = y + h + spacing();
            nextX = x + o->sizeHint().width() + spacing();
            h = 0;
        }
        if ( !testonly )
            o->setGeometry( QRect( QPoint( x, y ), o->sizeHint() ) );
        x = nextX;
        h = QMAX( h,  o->sizeHint().height() );
    }
    return y + h - r.y();
}

QSize SimpleFlow::minimumSize() const
{
    QSize s(0,0);
    QPtrListIterator<QLayoutItem> it(list);
    QLayoutItem *o;
    while ( (o=it.current()) != 0 ) {
        ++it;
        s = s.expandedTo( o->minimumSize() );
    }
    return s;
}

Header file of the border layout:

/****************************************************************************
** $Id:  qt/border.h   3.0.5   edited Oct 12 2001 $
**
** Definition of simple flow layout for custom layout example
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef BORDER_H
#define BORDER_H

#include <qlayout.h>
#include <qptrlist.h>

class BorderWidgetItem : public QWidgetItem
{
public:
    BorderWidgetItem( QWidget *w )
        : QWidgetItem( w )
    {}

    void setGeometry( const QRect &r )
    { widget()->setGeometry( r ); }

};

class BorderLayout : public QLayout
{
public:
    enum Position {
        West = 0,
        North,
        South,
        East,
        Center
    };

    struct BorderLayoutStruct
    {
        BorderLayoutStruct( QLayoutItem *i, Position p ) {
            item = i;
            pos = p;
        }

        QLayoutItem *item;
        Position pos;
    };

    enum SizeType {
        Minimum = 0,
        SizeHint
    };

    BorderLayout( QWidget *parent, int border = 0, int autoBorder = -1,
                  const char *name = 0 )
        : QLayout( parent, border, autoBorder, name ), cached( 0, 0 ), mcached( 0, 0 ),
          sizeDirty( TRUE ), msizeDirty( TRUE )
    {}

    BorderLayout( QLayout* parent, int autoBorder = -1, const char *name = 0 )
        : QLayout( parent, autoBorder, name  ), cached( 0, 0 ), mcached( 0, 0 ),
          sizeDirty( TRUE ), msizeDirty( TRUE )
    {}

    BorderLayout( int autoBorder = -1, const char *name = 0 )
        : QLayout( autoBorder, name ), cached( 0, 0 ), mcached( 0, 0 ),
          sizeDirty( TRUE ), msizeDirty( TRUE )
    {}

    ~BorderLayout();

    void addItem( QLayoutItem *item );

    void addWidget( QWidget *widget, Position pos );
    void add( QLayoutItem *item, Position pos );

    bool hasHeightForWidth() const;

    QSize sizeHint() const;
    QSize minimumSize() const;

    QLayoutIterator iterator();

    QSizePolicy::ExpandData expanding() const;

protected:
    void setGeometry( const QRect &rect );

private:
    void doLayout( const QRect &rect, bool testonly = FALSE );
    void calcSize( SizeType st );

    QPtrList<BorderLayoutStruct> list;
    QSize cached, mcached;
    bool sizeDirty, msizeDirty;

};

#endif

Implementation of the border layout:

/****************************************************************************
** $Id:  qt/border.cpp   3.0.5   edited Oct 12 2001 $
**
** Implementing your own layout: flow example
**
** Copyright (C) 1996 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "border.h"

class BorderLayoutIterator : public QGLayoutIterator
{
public:
    BorderLayoutIterator( const QPtrList<BorderLayout::BorderLayoutStruct> *l )
        : idx( 0 ) , list( (QPtrList<BorderLayout::BorderLayoutStruct>*)l )
    {}

    uint count() const;
    QLayoutItem *current();
    BorderLayout::BorderLayoutStruct *currentStruct();
    void toFirst();
    QLayoutItem *next();
    QLayoutItem *takeCurrent();
    BorderLayoutIterator &operator++();

private:
    int idx;
    QPtrList<BorderLayout::BorderLayoutStruct> *list;

};

uint BorderLayoutIterator::count() const
{
    return list->count();
}

QLayoutItem *BorderLayoutIterator::current()
{
    return idx < (int)count() ? list->at( idx )->item : 0;
}

BorderLayout::BorderLayoutStruct *BorderLayoutIterator::currentStruct()
{
    return idx < (int)count() ? list->at( idx ) : 0;
}

void BorderLayoutIterator::toFirst()
{
    idx = 0;
}

QLayoutItem *BorderLayoutIterator::next()
{
    idx++;
    return current();
}

QLayoutItem *BorderLayoutIterator::takeCurrent()
{
    BorderLayout::BorderLayoutStruct *b
        = idx < int( list->count() ) ? list->take(  idx  ) : 0;
    QLayoutItem *item =  b ? b->item : 0;
    delete b;
    return item;
}

BorderLayoutIterator &BorderLayoutIterator::operator++()
{
    next();
    return *this;
}

BorderLayout::~BorderLayout()
{
    deleteAllItems();
}

void BorderLayout::addItem( QLayoutItem *item )
{
    add( item, West );
}

void BorderLayout::addWidget( QWidget *widget, Position pos )
{
    add( new BorderWidgetItem( widget ), pos );
}

void BorderLayout::add( QLayoutItem *item, Position pos )
{
    list.append( new BorderLayoutStruct( item, pos ) );
    sizeDirty = TRUE; msizeDirty = TRUE;
    calcSize( SizeHint ); calcSize( Minimum );
}

bool BorderLayout::hasHeightForWidth() const
{
    return FALSE;
}

QSize BorderLayout::sizeHint() const
{
    return cached;
}

QSize BorderLayout::minimumSize() const
{
    return cached;
}

QSizePolicy::ExpandData BorderLayout::expanding() const

{
    return QSizePolicy::BothDirections;
}

QLayoutIterator BorderLayout::iterator()
{
    return QLayoutIterator( new BorderLayoutIterator( &list ) );
}

void BorderLayout::setGeometry( const QRect &rct )
{
    QLayout::setGeometry( rct );
    doLayout( rct );
}

void BorderLayout::doLayout( const QRect &rct, bool /*testonly*/ )
{
    int ew = 0, ww = 0, nh = 0, sh = 0;
    int h = 0;

    BorderLayoutIterator it( &list );
    BorderLayoutStruct *o;
    BorderLayoutStruct *center = 0;
    while ( ( o = it.currentStruct() ) != 0 ) {
        ++it;

        if ( o->pos == North ) {
            o->item->setGeometry( QRect( rct.x(), nh, rct.width(), o->item->sizeHint().height() ) );
            nh += o->item->geometry().height() + spacing();
        }
        if ( o->pos == South ) {
            o->item->setGeometry( QRect( o->item->geometry().x(), o->item->geometry().y(),
                                         rct.width(), o->item->sizeHint().height() ) );
            sh += o->item->geometry().height() + spacing();
            o->item->setGeometry( QRect( rct.x(), rct.y() + rct.height() - sh + spacing(),
                                         o->item->geometry().width(), o->item->geometry().height() ) );
        }
        if ( o->pos == Center )
            center = o;
    }

    h = rct.height() - nh - sh;

    it.toFirst();
    while ( ( o = it.currentStruct() ) != 0 ) {
        ++it;

        if ( o->pos == West ) {
            o->item->setGeometry( QRect( rct.x() + ww, nh, o->item->sizeHint().width(), h ) );
            ww += o->item->geometry().width() + spacing();
        }
        if ( o->pos == East ) {
            o->item->setGeometry( QRect( o->item->geometry().x(), o->item->geometry().y(),
                                         o->item->sizeHint().width(), h ) );
            ew += o->item->geometry().width() + spacing();
            o->item->setGeometry( QRect( rct.x() + rct.width() - ew + spacing(), nh,
                                         o->item->geometry().width(), o->item->geometry().height() ) );
        }
    }

    if ( center )
        center->item->setGeometry( QRect( ww, nh, rct.width() - ew - ww, h ) );
}

void BorderLayout::calcSize( SizeType st )
{
    if ( ( st == Minimum && !msizeDirty ) ||
         ( st == SizeHint && !sizeDirty ) )
        return;

    int w = 0, h = 0;

    BorderLayoutIterator it( &list );
    BorderLayoutStruct *o;
    while ( ( o = it.currentStruct() ) != 0 ) {
        ++it;
        if ( o->pos == North ||
             o->pos == South ) {
            if ( st == Minimum )
                h += o->item->minimumSize().height();
            else
                h += o->item->sizeHint().height();
        }
        else if ( o->pos == West ||
                  o->pos == East ) {
            if ( st == Minimum )
                w += o->item->minimumSize().width();
            else
                w += o->item->sizeHint().width();
        } else {
            if ( st == Minimum ) {
                h += o->item->minimumSize().height();
                w += o->item->minimumSize().width();
            }
            else {
                h += o->item->sizeHint().height();
                w += o->item->sizeHint().width();
            }
        }
    }

    if ( st == Minimum ) {
        msizeDirty = FALSE;
        mcached = QSize( w, h );
    } else {
        sizeDirty = FALSE;
        cached = QSize( w, h );
    }

    return;
}

Header file of the card layout:

/****************************************************************************
** $Id:  qt/card.h   3.0.5   edited Oct 12 2001 $
**
** Definition of simple flow layout for custom layout example
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef CARD_H
#define CARD_H

#include <qlayout.h>
#include <qptrlist.h>

class CardLayout : public QLayout
{
public:
    CardLayout( QWidget *parent, int dist )
        : QLayout( parent, 0, dist ) {}
    CardLayout( QLayout* parent, int dist)
        : QLayout( parent, dist ) {}
    CardLayout( int dist )
        : QLayout( dist ) {}
    ~CardLayout();

    void addItem( QLayoutItem *item );
    QSize sizeHint() const;
    QSize minimumSize() const;
    QLayoutIterator iterator();
    void setGeometry( const QRect &rect );

private:
    QPtrList<QLayoutItem> list;

};

#endif

Implementation of the card layout:

/****************************************************************************
** $Id:  qt/card.cpp   3.0.5   edited Oct 12 2001 $
**
** Implementing your own layout: flow example
**
** Copyright (C) 1996 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "card.h"

class CardLayoutIterator :public QGLayoutIterator
{
public:
    CardLayoutIterator( QPtrList<QLayoutItem> *l )
        : idx( 0 ), list( l )  {}

    QLayoutItem *current();
    QLayoutItem *next();
    QLayoutItem *takeCurrent();

private:
    int idx;
    QPtrList<QLayoutItem> *list;
};

QLayoutItem *CardLayoutIterator::current()
{
    return idx < int( list->count() ) ? list->at( idx ) : 0;
}

QLayoutItem *CardLayoutIterator::next()
{
    idx++; return current();
}

QLayoutItem *CardLayoutIterator::takeCurrent()
{
    return idx < int( list->count() ) ?list->take( idx ) : 0;
}

QLayoutIterator CardLayout::iterator()
{
    return QLayoutIterator(  new CardLayoutIterator( &list )  );
}

CardLayout::~CardLayout()
{
    deleteAllItems();
}

void CardLayout::addItem(  QLayoutItem *item  )
{
    list.append( item );
}

void CardLayout::setGeometry( const QRect &rct )
{
    QLayout::setGeometry( rct );

    QPtrListIterator<QLayoutItem> it( list );
    if ( it.count() == 0 )
        return;

    QLayoutItem *o;

    int i = 0;

    int w = rct.width() - ( list.count() - 1 ) * spacing();
    int h = rct.height() - ( list.count() - 1 ) * spacing();

    while ( ( o=it.current() ) != 0 ) {
        ++it;
        QRect geom( rct.x() + i * spacing(), rct.y() + i * spacing(),
                    w, h  );
        o->setGeometry(  geom  );
        ++i;
    }
}

QSize CardLayout::sizeHint() const
{
    QSize s(0,0);
    int n = list.count();
    if ( n > 0 )
        s = QSize(100,70); //start with a nice default size
    QPtrListIterator<QLayoutItem> it(list);
    QLayoutItem *o;
    while ( (o=it.current()) != 0 ) {
        ++it;
        s = s.expandedTo( o->minimumSize() );
    }
    return s + n*QSize(spacing(),spacing());
}

QSize CardLayout::minimumSize() const
{
    QSize s(0,0);
    int n = list.count();
    QPtrListIterator<QLayoutItem> it(list);
    QLayoutItem *o;
    while ( (o=it.current()) != 0 ) {
        ++it;
        s = s.expandedTo( o->minimumSize() );
    }
    return s + n*QSize(spacing(),spacing());
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Main for custom layout example
**
** Copyright (C) 1996 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "flow.h"
#include "border.h"
#include "card.h"

#include <qapplication.h>
#include <qlabel.h>
#include <qcolor.h>
#include <qgroupbox.h>
#include <qpushbutton.h>
#include <qmultilineedit.h>
#include <qcolor.h>

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

    QWidget *f = new QWidget;
    QBoxLayout *gm = new QVBoxLayout( f, 5 );

    SimpleFlow *b1 = new SimpleFlow( gm );

    b1->add( new QPushButton( "Short", f ) );
    b1->add( new QPushButton( "Longer", f ) );
    b1->add( new QPushButton( "Different text", f ) );
    b1->add( new QPushButton( "More text", f ) );
    b1->add( new QPushButton( "Even longer button text", f ) );
    QPushButton* qb = new QPushButton( "Quit", f );
    a.connect( qb, SIGNAL( clicked() ), SLOT( quit() ) );
    b1->add( qb );

    QWidget *wid = new QWidget( f );

    BorderLayout *large = new BorderLayout( wid );
    large->setSpacing( 5 );
    large->addWidget( new QPushButton( "North", wid ), BorderLayout::North );
    large->addWidget( new QPushButton( "West", wid ), BorderLayout::West );
    QMultiLineEdit* m = new QMultiLineEdit( wid );
    m->setText( "Central\nWidget" );
    large->addWidget( m, BorderLayout::Center );
    QWidget *east1 = new QPushButton( "East", wid );
    large->addWidget( east1, BorderLayout::East );
    QWidget *east2 = new QPushButton( "East 2", wid );
    large->addWidget( east2 , BorderLayout::East );
    large->addWidget( new QPushButton( "South", wid ), BorderLayout::South );
    //Left-to-right tab order looks better:
    QWidget::setTabOrder( east2, east1 );
    gm->addWidget( wid );

    wid = new QWidget( f );
    CardLayout *card = new CardLayout( wid, 10 );

    QWidget *crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::red );
    card->add( crd );
    crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::green );
    card->add( crd );
    crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::blue );
    card->add( crd );
    crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::white );
    card->add( crd );
    crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::black );
    card->add( crd );
    crd = new QWidget( wid );
    crd->setBackgroundColor( Qt::yellow );
    card->add( crd );

    gm->addWidget( wid );

    QLabel* s = new QLabel( f );
    s->setText( "outermost box" );
    s->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    s->setAlignment( Qt::AlignVCenter | Qt::AlignHCenter );
    gm->addWidget( s );
    a.setMainWidget( f );
    f->setCaption("Qt Example - Custom Layout");
    f->show();

    int result = a.exec();
    delete f;
    return result;
}

See also Examples.


Style overview

A style in Qt implements the look and feel found in GUIs on different platforms. For instance the Windows style used in Windows and the Motif style that are common on many Unix platforms.

This is a short guide that describes the steps that are necessary to get started creating and using custom styles with the style API in Qt 3.x. First, we go through the steps necessary to create a style: 1) picking a base style to inherit from and 2) re-implementing the necessary functions in the derived class. Then we show how to use the new style from within your own applications, or as a plugin together with existing Qt applications.

Creating a custom style

1. Pick a base style to inherit from.

The first step is to pick one of the base styles provided with Qt to build your custom style on. Which of the available styles to start from does of course depend on what look & feel you want. Basically you should choose from the QWindowsStyle derived classes or the QMotifStyle derived classes. These are the two base look & feel classes in the Qt style engine. Inheriting directly from QCommonStyle is also an option if you want to start almost from scratch when implementing your style. In this simple example we will inherit from QWindowsStyle.

2. Re-implement the necessary functions in your derived class.

Depending on which parts of the base style you want to change, you have to re-implement the functions that are used to draw those parts of the interface. If you take a look at the QStyle documentation, you will find a list of the different primitives, controls and complex controls. You will also find an illustration that shows where the different primitives, controls and complex controls are used. In this example we will first change the look of the standard arrows that are used in the QWindowsStyle. The arrows are PrimitiveElements that are drawn in the drawPrimitive() function, therefore we need to re-implement that function. We get the following class declaration:

#include <qwindowsstyle.h>

class CustomStyle : public QWindowsStyle {
    Q_OBJECT
public:
    CustomStyle();
    ~CustomStyle();

    void drawPrimitive( PrimitiveElement pe,
                        QPainter *p,
                        const QRect & r,
                        const QColorGroup & cg,
                        SFlags flags = Style_Default,
                        const QStyleOption & = QStyleOption::Default ) const;

private:
    // Disabled copy constructor and operator=
    CustomStyle( const CustomStyle & );
    CustomStyle& operator=( const CustomStyle & );
};

Note that we disable the copy constructor and the '=' operator for our style. QObject is the base class for all style classes in Qt, and a QObject inherently cannot be copied; there are some aspects of it that are not copyable.

From the QStyle docs we see that PE_ArrowUp, PE_ArrowDown, PE_ArrowLeft and PE_ArrowRight are the primitives we need to do something with. We get the following in our drawPrimitive() function:

CustomStyle::CustomStyle()
{
}

CustomStyle::~CustomStyle()
{
}

void CustomStyle::drawPrimitive( PrimitiveElement pe,
                                 QPainter * p,
                                 const QRect & r,
                                 const QColorGroup & cg,
                                 SFlags flags,
                                 const QStyleOption & opt ) const
{
    // we are only interested in the arrows
    if (pe >= PE_ArrowUp && pe <= PE_ArrowLeft) {
        QPointArray pa( 3 );
        // make the arrow cover half the area it is supposed to be
        // painted on
        int x = r.x();
        int y = r.y();
        int w = r.width() / 2;
        int h = r.height() / 2;
        x += (r.width() - w) / 2;
        y += (r.height() - h) /2;

        switch( pe ) {
        case PE_ArrowDown:
            pa.setPoint( 0, x, y );
            pa.setPoint( 1, x + w, y );
            pa.setPoint( 2, x + w / 2, y + h );
            break;
        case PE_ArrowUp:
            pa.setPoint( 0, x, y + h );
            pa.setPoint( 1, x + w, y + h );
            pa.setPoint( 2, x + w / 2, y );
            break;
        case PE_ArrowLeft:
            pa.setPoint( 0, x + w, y );
            pa.setPoint( 1, x + w, y + h );
            pa.setPoint( 2, x, y + h / 2 );
            break;
        case PE_ArrowRight:
            pa.setPoint( 0, x, y );
            pa.setPoint( 1, x, y + h );
            pa.setPoint( 2, x + w, y + h / 2 );
            break;
        default: break;

        }

        // use different colors to indicate that the arrow is
        // enabled/disabled
        if ( flags & Style_Enabled ) {
            p->setPen( cg.mid() );
            p->setBrush( cg.brush( QColorGroup::ButtonText ) );
        } else {
            p->setPen( cg.buttonText() );
            p->setBrush( cg.brush( QColorGroup::Mid ) );
        }
        p->drawPolygon( pa );
    } else {
        // let the base style handle the other primitives
        QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, data );
    }
}

Using a custom style

There are several ways of using a custom style in a Qt application. The easiest and most simple way is to include the following lines of code in the application's main() function:

#include "customstyle.h"

int main( int argc, char ** argv )
{
    QApplication::setStyle( new CustomStyle() );
    // do the usual routine on creating your QApplication object etc.
}

Note that you also have to include the customstyle.h and customstyle.cpp files in your project.

2. Creating and using a pluggable style

You may want to use your custom style in a Qt application that you don't want to, or have the opportunity to recompile. The Qt Plugin system makes it possible to create styles as plugins. Styles created as plugins are loaded as shared objects at runtime by Qt itself. Please refer to the Qt Plugin documentation for more information on how to go about creating a style plugin.

Compile your plugin and put it into $QTDIR/plugins/styles. We now have a pluggable style that Qt can load automatically. To use your new style with existing applications, simply start the application with the following argument:

./application -style custom

The application should appear with the look & feel from the custom style you implemented.


Database Classes

These classes provide access to SQL databases.

QDataBrowser | Data manipulation and navigation for data entry forms
QDataTable | Flexible SQL table widget that supports browsing and editing
QDataView | Read-only SQL forms
QSql | Namespace for Qt SQL identifiers that need to be global-like
QSqlCursor | Browsing and editing of SQL tables and views
QSqlDatabase | Used to create SQL database connections and provide transaction handling
QSqlDriver | Abstract base class for accessing SQL databases
QSqlEditorFactory | Used to create the editors used by QDataTable and QSqlForm
QSqlError | SQL database error information
QSqlField | Manipulates the fields in SQL database tables and views
QSqlFieldInfo | Stores meta data associated with a SQL field
QSqlForm | Creates and manages data entry forms tied to SQL databases
QSqlIndex | Functions to manipulate and describe QSqlCursor and QSqlDatabase indexes
QSqlPropertyMap | Used to map widgets to SQL fields
QSqlQuery | Means of executing and manipulating SQL statements
QSqlRecord | Encapsulates a database record, i.e. a set of database fields
QSqlRecordInfo | Encapsulates a set of database field meta data
QSqlResult | Abstract interface for accessing data from SQL databases


Format of the QDataStream Operators

The QDataStream allows you to serialize some of the Qt data types. The table below lists the data types that QDataStream can serialize and how they are represented.

  • Q_INT8
    • signed byte
  • Q_INT16
    • signed 16 bit integer
  • Q_INT32
    • signed 32 bit integer
  • Q_UINT8
    • unsigned byte
  • Q_UINT16
    • unsigned 16 bit integer
  • Q_UINT32
    • unsigned 32 bit integer
  • float
    • 32-bit floating point number using the standard IEEE-754 format
  • double
    • 64-bit floating point number using the standard IEEE-754 format
  • char *
    • The size of the string including the terminating 0 (Q_UINT32)
    • The string bytes including the terminating 0
    The null string is represented as (Q_UINT32) 0.
  • QBitArray
    • The array size (Q_UINT32)
    • The array bits, i.e. (size + 7)/8 bytes
  • QBrush
    • The brush style (Q_UINT8)
    • The brush color (QColor)
    • If style is CustomPattern, the brush pixmap (QPixmap)
  • QByteArray
    • The array size (Q_UINT32)
    • The array bytes, i.e. size bytes
  • QCString
    • The size of the string including the terminating 0 (Q_UINT32)
    • The string bytes including the terminating 0
    The null string is represented as (Q_UINT32) 0.
  • QColor
    • RGB value serialized as a Q_UINT32
  • QColorGroup
    • foreground (QBrush)
    • button (QBrush)
    • light (QBrush)
    • midLight (QBrush)
    • dark (QBrush)
    • mid (QBrush)
    • text (QBrush)
    • brightText (QBrush)
    • ButtonText (QBrush)
    • base (QBrush)
    • background (QBrush)
    • shadow (QBrush)
    • highlight (QBrush)
    • highlightedText (QBrush)
  • QCursor
    • Shape id (Q_INT16)
    • If shape is BitmapCursor: The bitmap (QPixmap), mask (QPixmap) and hot spot (QPoint)
  • QDate
    • Julian day (Q_UINT32)
  • QDateTime
    • Date (QDate)
    • Time (QTime)
  • QFont
    • The point size (Q_INT16)
    • The style hint (Q_UINT8)
    • The char set (Q_UINT8)
    • The weight (Q_UINT8)
    • The font bits (Q_UINT8)
  • QImage
    • Save it as a PNG image.
  • QMap
    • The number of items (Q_UINT32)
    • For all items, the key and value
  • QPalette
    • active (QColorGroup)
    • disabled (QColorGroup)
    • inactive (QColorGroup)
  • QPen
    • The pen styles (Q_UINT8)
    • The pen width (Q_UINT8)
    • The pen color (QColor)
  • QPicture
    • The size of the picture data (Q_UINT32)
    • The raw bytes of picture data (char)
  • QPixmap
    • Save it as a PNG image.
  • QPoint
    • The x coordinate (Q_INT32)
    • The y coordinate (Q_INT32)
  • QPointArray
    • The array size (Q_UINT32)
    • The array points (QPoint)
  • QRect
    • left (Q_INT32)
    • top (Q_INT32)
    • right (Q_INT32)
    • bottom (Q_INT32)
  • QRegion
    • The size of the data, i.e. 8 + 16 * (number of rectangles) (Q_UINT32)
    • QRGN_RECTS (Q_INT32)
    • The number of rectangles (Q_UINT32)
    • The rectangles in sequential order (QRect)
  • QSize
    • width (Q_INT32)
    • height (Q_INT32)
  • QString
    • If the string is null: 0xffffffff (Q_UINT32)
    • Otherwise: The string length (Q_UINT32) followed by the data in UTF-16
  • QTime
    • Milliseconds since midnight (Q_UINT32)
  • QValueList
    • The number of list elements (Q_UINT32)
    • All the elements in sequential order
  • QVariant
    • The type of the data (Q_UINT32)
    • The data of the specified type
  • QWMatrix
    • m11 (double)
    • m12 (double)
    • m21 (double)
    • m22 (double)
    • dx (double)
    • dy (double)


Digital Clock

This example displays a digital LCD clock that can switch between time and date.

Header file:

/****************************************************************************
** $Id:  qt/dclock.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef DCLOCK_H
#define DCLOCK_H

#include <qlcdnumber.h>

class DigitalClock : public QLCDNumber          // digital clock widget
{
    Q_OBJECT
public:
    DigitalClock( QWidget *parent=0, const char *name=0 );

protected:                                      // event handlers
    void        timerEvent( QTimerEvent * );
    void        mousePressEvent( QMouseEvent * );

private slots:                                  // internal slots
    void        stopDate();
    void        showTime();

private:                                        // internal data
    void        showDate();

    bool        showingColon;
    int         normalTimer;
    int         showDateTimer;
};

#endif // DCLOCK_H

Implementation:

/****************************************************************************
** $Id:  qt/dclock.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "dclock.h"
#include <qdatetime.h>

//
// Constructs a DigitalClock widget with a parent and a name.
//

DigitalClock::DigitalClock( QWidget *parent, const char *name )
    : QLCDNumber( parent, name )
{
    showingColon = FALSE;
    setFrameStyle( QFrame::Panel | QFrame::Raised );
    setLineWidth( 2 );                          // set frame line width
    showTime();                                 // display the current time
    normalTimer = startTimer( 500 );            // 1/2 second timer events
    showDateTimer = -1;                         // not showing date
}

//
// Handles timer events for the digital clock widget.
// There are two different timers; one timer for updating the clock
// and another one for switching back from date mode to time mode.
//

void DigitalClock::timerEvent( QTimerEvent *e )
{
    if ( e->timerId() == showDateTimer )        // stop showing date
        stopDate();
    else {                                      // normal timer
        if ( showDateTimer == -1 )              // not showing date
            showTime();
    }
}

//
// Enters date mode when the left mouse button is pressed.
//

void DigitalClock::mousePressEvent( QMouseEvent *e )
{
    if ( e->button() == QMouseEvent::LeftButton )               // left button pressed
        showDate();
}

//
// Shows the current date in the internal lcd widget.
// Fires a timer to stop showing the date.
//

void DigitalClock::showDate()
{
    if ( showDateTimer != -1 )                  // already showing date
        return;
    QDate date = QDate::currentDate();
    QString s;
    s.sprintf( "%2d %2d", date.month(), date.day() );
    display( s );                               // sets the LCD number/text
    showDateTimer = startTimer( 2000 );         // keep this state for 2 secs
}

//
// Stops showing the date.
//

void DigitalClock::stopDate()
{
    killTimer( showDateTimer );
    showDateTimer = -1;
    showTime();
}

//
// Shows the current time in the internal lcd widget.
//

void DigitalClock::showTime()
{
    showingColon = !showingColon;               // toggle/blink colon
    QString s = QTime::currentTime().toString().left(5);
    if ( !showingColon )
        s[2] = ' ';
    if ( s[0] == '0' )
        s[0] = ' ';
    display( s );                               // set LCD number/text
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "dclock.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    DigitalClock *clock = new DigitalClock;
    clock->resize( 170, 80 );
    a.setMainWidget( clock );
    clock->setCaption("Qt Example - Digital Clock");
    clock->show();
    return a.exec();
}

See also Examples.


Qt Demo

This program shows off some of Qt's widgets and functionality. It isn't intended as a code example, but rather as a single application that you can run to see many of Qt's features.

See $QTDIR/examples/demo for the source code.

See also Examples.


Painting on the Desktop

The desktop demo contains three routines, each of which draws something on the desktop. It does some nice stuff with QPainter, and also demonstrates how one can treat the desktop as a widget like any other.

Implementation:

/****************************************************************************
** $Id:  qt/desktop.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qimage.h>
#include <qbitmap.h>
#include <qpainter.h>
#include <qapplication.h>
#include <qdropsite.h>
#include <qdragobject.h>
#include <stdio.h>

static double seed = 0.353535353535;
static const int KINDA_RAND_MAX = 32767;

static int kindaRand()
{
    seed = seed*147;
    seed = seed - (double) ((int) seed);
    return (int) ( seed*(KINDA_RAND_MAX + 1) );
}

static int velocity( int i )                    // change velocity
{
    const int velmax = 15;
    const int velmin = 4;
    if ( i == 1 || i == 2 )
        i = (kindaRand()&0x7fff % velmax)/3 + velmin;
    else
        i = (kindaRand()&0x7fff % velmax) + velmin;
    return i;
}

//
// Draw polygon on desktop.
//

void poly()
{
    QWidget *d = QApplication::desktop();
    d->setBackgroundColor( Qt::white );         // white desktop

    const int maxpoints = 5;
    const int maxcurves = 8;
    static int xvel[maxpoints];
    static int yvel[maxpoints];
    int head = 0;
    int tail = -maxcurves + 2;
    QPointArray *a = new QPointArray[ maxcurves ];
    register QPointArray *p;
    QRect r = d->rect();                        // desktop rectangle

    int i;
    for ( i=0; i<maxcurves; i++ )
        a[i].resize( maxpoints );
    p = &a[0];
    for ( i=0; i<maxpoints; i++ ) {             // setup first polygon points
        p->setPoint( i, (kindaRand()&0x7fff) % r.width(),
                        (kindaRand()&0x7fff) % r.height() );
        xvel[i] = velocity(i);
        yvel[i] = velocity(i);
    }

    QPainter paint;
    paint.begin( d );                           // start painting desktop

    for ( int ntimes=0; ntimes<2000; ntimes++ ) {
        paint.setBrush( QColor(kindaRand()%360, 180, 255, QColor::Hsv) );
        paint.drawPolygon( a[head] );
        if ( ++tail >= maxcurves )
            tail = 0;

        int minx=r.left(), maxx=r.right();
        int miny=r.top(),  maxy=r.bottom();
        int x, y;
        p = &a[head];
        if ( ++head >= maxcurves )
            head = 0;
        for ( i=0; i<maxpoints; i++ ) {         // calc new curve
            p->point( i, &x, &y );
            x += xvel[i];
            y += yvel[i];
            if ( x >= maxx ) {
                x = maxx - (x - maxx + 1);
                xvel[i] = -velocity(i);
            }
            if ( x <= minx ) {
                x = minx + (minx - x + 1);
                xvel[i] = velocity(i);
            }
            if ( y >= maxy ) {
                y = maxy - (y - maxy + 1);
                yvel[i] = -velocity(i);
            }
            if ( y <= miny ) {
                y = miny + (miny - y + 1);
                yvel[i] = velocity(i);
            }
            a[head].setPoint( i, x, y );
        }
    }
    paint.end();                                // painting done
    delete[] a;
}

//
// Rotate pattern on desktop.
//

void rotate()
{
    int i;
    const int w = 64;
    const int h = 64;
    QImage image( w, h, 8, 128 );               // create image
    for ( i=0; i<128; i++ )                     // build color table
        image.setColor( i, qRgb(i,0,0) );
    for ( int y=0; y<h; y++ ) {                 // set image pixels
        uchar *p = image.scanLine(y);
        for ( int x=0; x<w; x++ )
            *p++ = (x+y)%128;
    }

    QPixmap pm;
    pm = image;                                 // convert image to pixmap
    pm.setOptimization( QPixmap::BestOptim );   // rotation will be faster

    QWidget *d = QApplication::desktop();       // w = desktop widget

    for ( i=0; i<=360; i += 2 ) {
        QWMatrix m;
        m.rotate( i );                          // rotate coordinate system
        QPixmap rpm = pm.xForm( m );            // rpm = rotated pixmap
        d->setBackgroundPixmap( rpm );          // set desktop pixmap
        d->update();                            // repaint desktop
    }
}

//
// Generates a marble-like pattern in pm.
//

void generateStone( QPixmap *pm,
                    const QColor &c1, const QColor &c2, const QColor &c3 )
{
    QPainter p;
    QPen p1 ( c1, 0 );
    QPen p2 ( c2, 0 );
    QPen p3 ( c3, 0 );

    p.begin( pm );
    for( int i = 0 ; i < pm->width() ; i++ )
        for( int j = 0 ; j < pm->height() ; j++ ) {
            int r = kindaRand();
            if ( r < KINDA_RAND_MAX / 3 )
                p.setPen( p1 );
            else if ( r < KINDA_RAND_MAX / 3 * 2 )
                p.setPen( p2 );
            else
                p.setPen( p3 );
            p.drawPoint( i,j );
        }
    p.end();
}

void drawShadeText( QPainter *p, int x, int y, const char *text,
                    const QColor &topColor, const QColor &bottomColor,
                    int sw = 2 )
{
    if ( !p->isActive() )
        return;

    p->setPen( bottomColor );
    p->drawText( x+sw, y+sw, text );
    p->setPen( topColor );
    p->drawText( x, y, text );
}

// NOTE: desktop drag/drop is experimental

class DesktopWidget : public QWidget, private QDropSite
{
public:
    DesktopWidget( const char *s, QWidget *parent=0, const char *name=0 );
   ~DesktopWidget();
    void paintEvent( QPaintEvent * );

    void dragEnterEvent( QDragEnterEvent *e )
    {
        if ( QImageDrag::canDecode(e) )
            e->accept();
    }

    void dragLeaveEvent( QDragLeaveEvent * )
    {
    }

    void dragMoveEvent( QDragMoveEvent *e )
    {
        e->accept();
    }

    void dropEvent( QDropEvent * e )
    {
        QPixmap pmp;
        if ( QImageDrag::decode( e, pmp ) ) {
            setBackgroundPixmap( pmp );
            update();
        }
    }

private:
    QPixmap *pm;
    QString text;
};

DesktopWidget::DesktopWidget( const char *s, QWidget *parent, const char *name )
    : QWidget( parent, name, WType_Desktop | WPaintDesktop),
        QDropSite(this)
{
    text = s;
    pm   = 0;
}

DesktopWidget::~DesktopWidget()
{
    delete pm;
}

void DesktopWidget::paintEvent( QPaintEvent * )
{
    QColor c1 = backgroundColor();
    QColor c2 = c1.light(104);
    QColor c3 = c1.dark(106);
    if ( !pm ) {
        pm = new QPixmap( 64, 64 );
        generateStone( pm, c1, c2, c3 );
        setBackgroundPixmap( *pm );
        update();
    }
    QRect br = fontMetrics().boundingRect( text );
    QPixmap offscreen( br.width(), br.height() );
    int x = width()/2  - br.width()/2;
    int y = height()/2 - br.height()/2;
    offscreen.fill( this, x, y );
    QPainter p;
    p.begin( &offscreen );
    drawShadeText( &p, -br.x(), -br.y(), text, c2, c3, 3 );
    p.end();
    bitBlt( this, x, y, &offscreen );
}

void desktopWidget( const char *s = "Trolltech" )
{
    DesktopWidget *t = new DesktopWidget(s);
    t->update();
    qApp->exec();
    delete t;
}

void desktopText( const char *s = "Trolltech" )
{
    const int border = 20;

    QColor c1 =  qApp->palette().inactive().background();
    QColor c2 = c1.light(104);
    QColor c3 = c1.dark(106);

    QPixmap pm(10,10);

    QPainter p;
    p.begin( &pm );
    QRect r = p.fontMetrics().boundingRect( s );
    p.end();

    int appWidth  =  qApp->desktop()->width();
    int appHeight =  qApp->desktop()->height();
    if ( r.width() > appWidth - border*2 )
        r.setWidth( appWidth - border*2 );
    if ( r.height() > appHeight - border*2 )
        r.setHeight( appHeight - border*2 );

    pm.resize( r.size() + QSize( border*2, border*2 ) );
    generateStone( &pm, c1, c2, c3 );
    p.begin( &pm );
    drawShadeText( &p, -r.x() + border, -r.y() + border, s, c2, c3 );
    p.end();

    qApp->desktop()->setBackgroundPixmap( pm );
}

//
// The program starts here.
//

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

    if ( argc > 1 ) {
        QFont f( "charter", 96, QFont::Black );
        f.setStyleHint( QFont::Times );
        app.setFont( f );
    }

    bool validOptions = FALSE;

    if ( argc == 2 ) {
        validOptions = TRUE;
        if ( strcmp(argv[1],"-poly") == 0 )
            poly();
        else if ( strcmp(argv[1],"-rotate") == 0 )
            rotate();
        else if ( strcmp(argv[1],"-troll") == 0 )
            desktopText();
        else if ( strcmp(argv[1],"-trollwidget") == 0 )
            desktopWidget();
        else
            validOptions = FALSE;
    }
    if ( argc == 3 ) {
        validOptions = TRUE;
        if ( strcmp(argv[1],"-shadetext") == 0 )
            desktopText( argv[2] );
        else if ( strcmp(argv[1],"-shadewidget") == 0 )
            desktopWidget( argv[2] );
        else
            validOptions = FALSE;
    }
    if ( !validOptions ) {
        fprintf( stderr, "Usage:\n\tdesktop -poly"
                               "\n\tdesktop -rotate"
                               "\n\tdesktop -troll"
                               "\n\tdesktop -trollwidget"
                               "\n\tdesktop -shadetext <text>"
                               "\n\tdesktop -shadewidget <text>\n" );
        rotate();
    }
    return 0;
}

See also Examples.


Dialog Classes

These classes are complex widgets, composed of simpler widgets; dialog boxes, generally.

QColorDialog | Dialog widget for specifying colors
QDialog | The base class of dialog windows
QErrorMessage | Error message display dialog
QFileDialog | Dialogs that allow users to select files or directories
QFontDialog | Dialog widget for selecting a font
QInputDialog | Simple convenience dialog to get a single value from the user
QMessageBox | Modal dialog with a short message, an icon, and some buttons
QProgressDialog | Feedback on the progress of a slow operation
QTabDialog | Stack of tabbed widgets
QWizard | Framework for wizard dialogs


A Directory Browser

This example program demonstrates how to use a listview and listview items to build a multi-column hierarchical, memory- and CPU-efficient directory browser. It also demonstrates how to use Drag&Drop in a listview.

Header file:

/****************************************************************************
** $Id:  qt/dirview.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef DIRVIEW_H
#define DIRVIEW_H

#include <qlistview.h>
#include <qstring.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qtimer.h>

class QWidget;
class QDragEnterEvent;
class QDragMoveEvent;
class QDragLeaveEvent;
class QDropEvent;

class FileItem : public QListViewItem
{
public:
    FileItem( QListViewItem *parent, const QString &s1, const QString &s2 )
        : QListViewItem( parent, s1, s2 ), pix( 0 ) {}

    const QPixmap *pixmap( int i ) const;
    void setPixmap( QPixmap *p );

private:
    QPixmap *pix;

};

class Directory : public QListViewItem
{
public:
    Directory( QListView * parent, const QString& filename );
    Directory( Directory * parent, const QString& filename, const QString &col2 )
        : QListViewItem( parent, filename, col2 ), pix( 0 ) {}
    Directory( Directory * parent, const QString& filename );

    QString text( int column ) const;

    QString fullName();

    void setOpen( bool );
    void setup();

    const QPixmap *pixmap( int i ) const;
    void setPixmap( QPixmap *p );

private:
    QFile f;
    Directory * p;
    bool readable;
    bool showDirsOnly;
    QPixmap *pix;

};

class DirectoryView : public QListView
{
    Q_OBJECT

public:
    DirectoryView( QWidget *parent = 0, const char *name = 0, bool sdo = FALSE );
    bool showDirsOnly() { return dirsOnly; }

public slots:
    void setDir( const QString & );

signals:
    void folderSelected( const QString & );

protected slots:
    void slotFolderSelected( QListViewItem * );
    void openFolder();

protected:
    void contentsDragEnterEvent( QDragEnterEvent *e );
    void contentsDragMoveEvent( QDragMoveEvent *e );
    void contentsDragLeaveEvent( QDragLeaveEvent *e );
    void contentsDropEvent( QDropEvent *e );
    void contentsMouseMoveEvent( QMouseEvent *e );
    void contentsMousePressEvent( QMouseEvent *e );
    void contentsMouseReleaseEvent( QMouseEvent *e );

private:
    QString fullPath(QListViewItem* item);
    bool dirsOnly;
    QListViewItem *oldCurrent;
    QListViewItem *dropItem;
    QTimer* autoopen_timer;
    QPoint presspos;
    bool mousePressed;

};

#endif

And here is the main implementation file. Note the way the program scans subdirectories only when it has to. This allows the program to handle very large file systems efficiently. The same technique can be used in any other trees.

/****************************************************************************
** $Id:  qt/dirview.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "dirview.h"

#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qpixmap.h>
#include <qevent.h>
#include <qpoint.h>
#include <qmessagebox.h>
#include <qdragobject.h>
#include <qmime.h>
#include <qstrlist.h>
#include <qstringlist.h>
#include <qapplication.h>
#include <qheader.h>

static const char* folder_closed_xpm[]={
    "16 16 9 1",
    "g c #808080",
    "b c #c0c000",
    "e c #c0c0c0",
    "# c #000000",
    "c c #ffff00",
    ". c None",
    "a c #585858",
    "f c #a0a0a4",
    "d c #ffffff",
    "..###...........",
    ".#abc##.........",
    ".#daabc#####....",
    ".#ddeaabbccc#...",
    ".#dedeeabbbba...",
    ".#edeeeeaaaab#..",
    ".#deeeeeeefe#ba.",
    ".#eeeeeeefef#ba.",
    ".#eeeeeefeff#ba.",
    ".#eeeeefefff#ba.",
    ".##geefeffff#ba.",
    "...##gefffff#ba.",
    ".....##fffff#ba.",
    ".......##fff#b##",
    ".........##f#b##",
    "...........####."};

static const char* folder_open_xpm[]={
    "16 16 11 1",
    "# c #000000",
    "g c #c0c0c0",
    "e c #303030",
    "a c #ffa858",
    "b c #808080",
    "d c #a0a0a4",
    "f c #585858",
    "c c #ffdca8",
    "h c #dcdcdc",
    "i c #ffffff",
    ". c None",
    "....###.........",
    "....#ab##.......",
    "....#acab####...",
    "###.#acccccca#..",
    "#ddefaaaccccca#.",
    "#bdddbaaaacccab#",
    ".eddddbbaaaacab#",
    ".#bddggdbbaaaab#",
    "..edgdggggbbaab#",
    "..#bgggghghdaab#",
    "...ebhggghicfab#",
    "....#edhhiiidab#",
    "......#egiiicfb#",
    "........#egiibb#",
    "..........#egib#",
    "............#ee#"};

static const char * folder_locked[]={
    "16 16 10 1",
    "h c #808080",
    "b c #ffa858",
    "f c #c0c0c0",
    "e c #c05800",
    "# c #000000",
    "c c #ffdca8",
    ". c None",
    "a c #585858",
    "g c #a0a0a4",
    "d c #ffffff",
    "..#a#...........",
    ".#abc####.......",
    ".#daa#eee#......",
    ".#ddf#e##b#.....",
    ".#dfd#e#bcb##...",
    ".#fdccc#daaab#..",
    ".#dfbbbccgfg#ba.",
    ".#ffb#ebbfgg#ba.",
    ".#ffbbe#bggg#ba.",
    ".#fffbbebggg#ba.",
    ".##hf#ebbggg#ba.",
    "...###e#gggg#ba.",
    ".....#e#gggg#ba.",
    "......###ggg#b##",
    ".........##g#b##",
    "...........####."};

static const char * pix_file []={
    "16 16 7 1",
    "# c #000000",
    "b c #ffffff",
    "e c #000000",
    "d c #404000",
    "c c #c0c000",
    "a c #ffffc0",
    ". c None",
    "................",
    ".........#......",
    "......#.#a##....",
    ".....#b#bbba##..",
    "....#b#bbbabbb#.",
    "...#b#bba##bb#..",
    "..#b#abb#bb##...",
    ".#a#aab#bbbab##.",
    "#a#aaa#bcbbbbbb#",
    "#ccdc#bcbbcbbb#.",
    ".##c#bcbbcabb#..",
    "...#acbacbbbe...",
    "..#aaaacaba#....",
    "...##aaaaa#.....",
    ".....##aa#......",
    ".......##......."};

QPixmap *folderLocked = 0;
QPixmap *folderClosed = 0;
QPixmap *folderOpen = 0;
QPixmap *fileNormal = 0;

/*****************************************************************************
 *
 * Class Directory
 *
 *****************************************************************************/

Directory::Directory( Directory * parent, const QString& filename )
    : QListViewItem( parent ), f(filename),
      showDirsOnly( parent->showDirsOnly ),
      pix( 0 )
{
    p = parent;
    readable = QDir( fullName() ).isReadable();

    if ( !readable )
        setPixmap( folderLocked );
    else
        setPixmap( folderClosed );
}

Directory::Directory( QListView * parent, const QString& filename )
    : QListViewItem( parent ), f(filename),
      showDirsOnly( ( (DirectoryView*)parent )->showDirsOnly() ),
      pix( 0 )
{
    p = 0;
    readable = QDir( fullName() ).isReadable();
}

void Directory::setPixmap( QPixmap *px )
{
    pix = px;
    setup();
    widthChanged( 0 );
    invalidateHeight();
    repaint();
}

const QPixmap *Directory::pixmap( int i ) const
{
    if ( i )
        return 0;
    return pix;
}

void Directory::setOpen( bool o )
{
    if ( o )
        setPixmap( folderOpen );
    else
        setPixmap( folderClosed );

    if ( o && !childCount() ) {
        QString s( fullName() );
        QDir thisDir( s );
        if ( !thisDir.isReadable() ) {
            readable = FALSE;
            setExpandable( FALSE );
            return;
        }

        listView()->setUpdatesEnabled( FALSE );
        const QFileInfoList * files = thisDir.entryInfoList();
        if ( files ) {
            QFileInfoListIterator it( *files );
            QFileInfo * fi;
            while( (fi=it.current()) != 0 ) {
                ++it;
                if ( fi->fileName() == "." || fi->fileName() == ".." )
                    ; // nothing
                else if ( fi->isSymLink() && !showDirsOnly ) {
                    FileItem *item = new FileItem( this, fi->fileName(),
                                                     "Symbolic Link" );
                    item->setPixmap( fileNormal );
                }
                else if ( fi->isDir() )
                    (void)new Directory( this, fi->fileName() );
                else if ( !showDirsOnly ) {
                    FileItem *item
                        = new FileItem( this, fi->fileName(),
                                             fi->isFile()?"File":"Special" );
                    item->setPixmap( fileNormal );
                }
            }
        }
        listView()->setUpdatesEnabled( TRUE );
    }
    QListViewItem::setOpen( o );
}

void Directory::setup()
{
    setExpandable( TRUE );
    QListViewItem::setup();
}

QString Directory::fullName()
{
    QString s;
    if ( p ) {
        s = p->fullName();
        s.append( f.name() );
        s.append( "/" );
    } else {
        s = f.name();
    }
    return s;
}

QString Directory::text( int column ) const
{
    if ( column == 0 )
        return f.name();
    else if ( readable )
        return "Directory";
    else
        return "Unreadable Directory";
}

/*****************************************************************************
 *
 * Class DirectoryView
 *
 *****************************************************************************/

DirectoryView::DirectoryView( QWidget *parent, const char *name, bool sdo )
    : QListView( parent, name ), dirsOnly( sdo ), oldCurrent( 0 ),
      dropItem( 0 ), mousePressed( FALSE )
{
    autoopen_timer = new QTimer( this );
    if ( !folderLocked ) {
        folderLocked = new QPixmap( folder_locked );
        folderClosed = new QPixmap( folder_closed_xpm );
        folderOpen = new QPixmap( folder_open_xpm );
        fileNormal = new QPixmap( pix_file );
    }

    connect( this, SIGNAL( doubleClicked( QListViewItem * ) ),
             this, SLOT( slotFolderSelected( QListViewItem * ) ) );
    connect( this, SIGNAL( returnPressed( QListViewItem * ) ),
             this, SLOT( slotFolderSelected( QListViewItem * ) ) );

    setAcceptDrops( TRUE );
    viewport()->setAcceptDrops( TRUE );

    connect( autoopen_timer, SIGNAL( timeout() ),
             this, SLOT( openFolder() ) );
}

void DirectoryView::slotFolderSelected( QListViewItem *i )
{
    if ( !i || !showDirsOnly() )
        return;

    Directory *dir = (Directory*)i;
    emit folderSelected( dir->fullName() );
}

void DirectoryView::openFolder()
{
    autoopen_timer->stop();
    if ( dropItem && !dropItem->isOpen() ) {
        dropItem->setOpen( TRUE );
        dropItem->repaint();
    }
}

static const int autoopenTime = 750;

void DirectoryView::contentsDragEnterEvent( QDragEnterEvent *e )
{
    if ( !QUriDrag::canDecode(e) ) {
        e->ignore();
        return;
    }

    oldCurrent = currentItem();

    QListViewItem *i = itemAt( contentsToViewport(e->pos()) );
    if ( i ) {
        dropItem = i;
        autoopen_timer->start( autoopenTime );
    }
}

void DirectoryView::contentsDragMoveEvent( QDragMoveEvent *e )
{
    if ( !QUriDrag::canDecode(e) ) {
        e->ignore();
        return;
    }

    QPoint vp = contentsToViewport( ( (QDragMoveEvent*)e )->pos() );
    QListViewItem *i = itemAt( vp );
    if ( i ) {
        setSelected( i, TRUE );
        e->accept();
        if ( i != dropItem ) {
            autoopen_timer->stop();
            dropItem = i;
            autoopen_timer->start( autoopenTime );
        }
        switch ( e->action() ) {
        case QDropEvent::Copy:
            break;
        case QDropEvent::Move:
            e->acceptAction();
            break;
        case QDropEvent::Link:
            e->acceptAction();
            break;
        default:
            ;
        }
    } else {
        e->ignore();
        autoopen_timer->stop();
        dropItem = 0;
    }
}

void DirectoryView::contentsDragLeaveEvent( QDragLeaveEvent * )
{
    autoopen_timer->stop();
    dropItem = 0;

    setCurrentItem( oldCurrent );
    setSelected( oldCurrent, TRUE );
}

void DirectoryView::contentsDropEvent( QDropEvent *e )
{
    autoopen_timer->stop();

    if ( !QUriDrag::canDecode(e) ) {
        e->ignore();
        return;
    }

    QListViewItem *item = itemAt( contentsToViewport(e->pos()) );
    if ( item ) {

        QStrList lst;

        QUriDrag::decode( e, lst );

        QString str;

        switch ( e->action() ) {
            case QDropEvent::Copy:
            str = "Copy";
            break;
            case QDropEvent::Move:
            str = "Move";
            e->acceptAction();
            break;
            case QDropEvent::Link:
            str = "Link";
            e->acceptAction();
            break;
            default:
            str = "Unknown";
        }

        str += "\n\n";

        e->accept();

        for ( uint i = 0; i < lst.count(); ++i ) {
            QString filename = lst.at( i );
            str += filename + "\n";
        }
        str += QString( "\nTo\n\n   %1" )
               .arg( fullPath(item) );

        QMessageBox::information( this, "Drop target", str, "Not implemented" );
    } else
        e->ignore();

}

QString DirectoryView::fullPath(QListViewItem* item)
{
    QString fullpath = item->text(0);
    while ( (item=item->parent()) ) {
        if ( item->parent() )
            fullpath = item->text(0) + "/" + fullpath;
        else
            fullpath = item->text(0) + fullpath;
    }
    return fullpath;
}

void DirectoryView::contentsMousePressEvent( QMouseEvent* e )
{
    QListView::contentsMousePressEvent(e);
    QPoint p( contentsToViewport( e->pos() ) );
    QListViewItem *i = itemAt( p );
    if ( i ) {
        // if the user clicked into the root decoration of the item, don't try to start a drag!
        if ( p.x() > header()->cellPos( header()->mapToActual( 0 ) ) +
             treeStepSize() * ( i->depth() + ( rootIsDecorated() ? 1 : 0) ) + itemMargin() ||
             p.x() < header()->cellPos( header()->mapToActual( 0 ) ) ) {
            presspos = e->pos();
            mousePressed = TRUE;
        }
    }
}

void DirectoryView::contentsMouseMoveEvent( QMouseEvent* e )
{
    if ( mousePressed && ( presspos - e->pos() ).manhattanLength() > QApplication::startDragDistance() ) {
        mousePressed = FALSE;
        QListViewItem *item = itemAt( contentsToViewport(presspos) );
        if ( item ) {
            QString source = fullPath(item);
            if ( QFile::exists(source) ) {
                QUriDrag* ud = new QUriDrag(viewport());
                ud->setUnicodeUris( source );
                if ( ud->drag() )
                    QMessageBox::information( this, "Drag source",
                                              QString("Delete ")+source, "Not implemented" );
            }
        }
    }
}

void DirectoryView::contentsMouseReleaseEvent( QMouseEvent * )
{
    mousePressed = FALSE;
}

void DirectoryView::setDir( const QString &s )
{
    QListViewItemIterator it( this );
    ++it;
    for ( ; it.current(); ++it ) {
        it.current()->setOpen( FALSE );
    }

    QStringList lst( QStringList::split( "/", s ) );
    QListViewItem *item = firstChild();
    QStringList::Iterator it2 = lst.begin();
    for ( ; it2 != lst.end(); ++it2 ) {
        while ( item ) {
            if ( item->text( 0 ) == *it2 ) {
                item->setOpen( TRUE );
                break;
            }
            item = item->itemBelow();
        }
    }

    if ( item )
        setCurrentItem( item );
}

void FileItem::setPixmap( QPixmap *p )
{
    pix = p;
    setup();
    widthChanged( 0 );
    invalidateHeight();
    repaint();
}

const QPixmap *FileItem::pixmap( int i ) const
{
    if ( i )
        return 0;
    return pix;
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qfileinfo.h>
#include <qdir.h>
#include "dirview.h"

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

    DirectoryView mw;

    mw.addColumn( "Name" );
    mw.addColumn( "Type" );
    mw.setTreeStepSize( 20 );

    const QFileInfoList* roots = QDir::drives();
    QPtrListIterator<QFileInfo> i(*roots);
    QFileInfo* fi;
    while ( (fi = *i) ) {
        ++i;
        Directory * root = new Directory( &mw, fi->filePath() );
        if ( roots->count() <= 1 )
            root->setOpen( TRUE ); // be interesting
    }

    mw.resize( 400, 400 );
    mw.setCaption( "Qt Example - Directory Browser" );
    mw.setAllColumnsShowFocus( TRUE );
    a.setMainWidget( &mw );
    mw.show();

    return a.exec();
}

See also Examples.


拖放

拖放提供了一种用户可以在应用程序之间或之内传递信息的一种简单视觉效果机制。（在术语中，这被称为“直接操作模型”。）拖放和剪贴板的剪切和粘贴的机制相似。

  • 拖动
  • 放下
  • 剪贴板
  • 拖放操作
  • 添加新的拖放类型
  • 增强的拖放
  • 和其它应用程序之间的操作

对于拖放的实例，请参考（随着复杂度的增加的顺序）：qt/examples/iconview/simple_dd、qt/examples/dragdrop和qt/examples/fileiconview。也可以参考QMultiLineEdit窗口部件的源码。

拖动

开始一个拖动，比如是在鼠标移动事件，创建一个适合你的媒体的QDragObject的子类的对象，比如对于文本使用QTextDrag，对于图片使用QImageDrag。然后调用drag()方法。这就是我们对现有类型简单的拖动所要做的一切。

例如，从一个窗口部件中开始拖动一些文本：

  void MyWidget::startDrag()
  {
    QDragObject *d = new QTextDrag( myHighlightedText(), this );
    d->dragCopy();
    // 不要删除d。
  }

注意在拖动之后，QDragObject没有被删除。这个QDragObject需要被保存直到拖放明显完成——它也许还要和其它进程通讯。最后Qt会删除这个对象。如果拥有拖动对象的窗口部件在这之前被删除，任何没有完成的放下将会被取消并且拖动对象会被删除。因为这个原因，你应该注意对象引用的是什么。

放下

为了能在一个窗口部件中接收被放下的媒体，在这个窗口部件中调用setAcceptDrops(TRUE)（比如在它的构造函数中），并且重载事件处理方法dragEnterEvent()和dropEvent()。对于更复杂的应用程序，重载dragMoveEvent()和dragLeaveEvent()也是必需的。

例如，为了接受被放下的文本和图片：

  MyWidget::MyWidget(...) :
    QWidget(...)
  {
    ...
    setAcceptDrops(TRUE);
  }

  void MyWidget::dragEnterEvent(QDragEnterEvent* event)
  {
    event->accept(
        QTextDrag::canDecode(event) ||
        QImageDrag::canDecode(event)
    );
  }

  void MyWidget::dropEvent(QDropEvent* event)
  {
    QImage image;
    QString text;

    if ( QImageDrag::decode(event, image) ) {
      insertImageAt(image, event->pos());
    } else if ( QTextDrag::decode(event, text) ) {
      insertTextAt(text, event->pos());
    }
  }

剪贴板

QDragObject、QDragEnterEvent、QDragMoveEvent和QDropEvent类都是QMimeSource（提供类型信息的类）的子类。如果你在QDragObject中基于你的数据进行传递，你不仅要使用拖放，而且要使用使用传统的剪切和粘贴——QClipboard有两个函数：

      setData(QMimeSource*)
      QMimeSource* data()const
使用这些函数，你就可以很容易地把你的拖放初始信息放到剪贴板中：
  void MyWidget::copy()
  {
    QApplication::clipboard()->setData(
        new QTextDrag(myHighlightedText())
    );
  }

  void MyWidget::paste()
  {
    QString text;
    if ( QTextDrag::decode(QApplication::clipboard()->data(), text) )
        insertText( text );
  }
你甚至可以使用QDragObject的子类作为文件输入输出的部分。例如，如果你的程序有一个QDragObject的子类来把CAD设计编码为DXF格式，你的保存和载入代码也许可以是：
  void MyWidget::save()
  {
    QFile out(current_file_name);
    out.open(IO_WriteOnly);
    MyCadDrag tmp(current_design);
    out.writeBlock( tmp->encodedData( "image/x-dxf" ) );
  }

  void MyWidget::load()
  {
    QFile in(current_file_name);
    in.open(IO_ReadOnly);
    if ( !MyCadDrag::decode(in.readAll(), current_design) ) {
        QMessageBox::warning( this, "Format error",
            tr("The file \"%1\" is not in any supported format")
             .arg(current_file_name)
        );
    }
  }
注意QDragObject的子类叫做“MyCadDrag”，而不是“MyDxfDrag”——因为以后也许你要把它扩展为DXF、DWG、SVF、WMF，或者甚至是QPicture数据到其它应用程序中。

拖放操作

在一些简单的情况下，拖放的目标接收一个被拖动的数据的复制并且由源来决定是否删除初始的拖动对象。这就是QDropEvent中的“Copy”操作。目标也可以选择理解其它操作，特别是“Move”和“Link”操作。如果目标理解了“Move”操作，目标就会对复制和删除操作负责并且源自己不会再试图删除数据。如果目标理解了“Link”操作，它存储它自己的初始信息的引用，并且源也不会删除初始信息的。最通用的拖放操作是在同一个窗口部件中执行一个“Move”——请参考下面的增强的拖放一节。

拖动操作的另一个主要用法是当使用一个引用类型，比如text/uri-list，实际被拖动的数据引用了文件或对象。

添加新的拖放类型

就像上面的DXF例子中建议的一样，拖放不仅仅局限于文本和图片。任何信息都可以被拖放。在应用程序之间拖放信息，两个应用程序必须使用它们都能接受和产生的数据格式。这个可以使用MIME类型来达到——拖动的源提供一个它能缠身的MIME类型的类标（按从最常用的到比较少用到的顺序排列），并且拖动目标选择一种它能接受的。例如，QTextDrag提供了“text/plain”MIME类型（普通的没有格式的文本）和并且Unicode格式是“text/utf16”和“text/utf8”的支持，QImageDrag提供了“image/*”的支持，*是QImageIO支持的任何一种图片格式，并且QUriDrag子类提供了“text/uri-list”的支持，一个文件（或URL）的列表传输的标准格式。

为了实现QDragObject子类中没有支持的拖放信息的类型，首先和最重要的步骤是查找一下现存的格式中哪个是适合的——IANA（Internet Assigned Numbers Authority）在ISI（Information Sciences Institute）提供了一个MIME媒体类型的分级列表。使用标准的MIME类型将会使你的应用程序和现在以及未来的其它软件在互相操作中能够最优化。

为了支持另外的媒体类型，继承QDragObject或QStoredDrag。当你需要提供对多类型进行支持，继承QDragObject。当一个类型就足够的时候，继承更加简单的QStoredDrag。

QDragObject的子类将会重载const char* format(int i) const和QByteArray encodedData(const char* mimetype) const成员，并且提供对媒体数据进行编码和静态成员canDecode()和对进入的数据进行解码的decode()一套方法，和QImageDrag的bool canDecode(QMimeSource*) const和QByteArray decode(QMimeSource*) const很相似。当然，你也可以通过省略其中的一些方法对一种媒体数据只支持拖或只支持放。

QStoredDrag的子类提供了对媒体数据进行编码和静态成员canDecode()和对进入的数据进行解码的decode()一套方法。

增强的拖放

在剪贴板模式中，用户可以剪切或复制源信息，然后粘贴它。相似地，在拖放模式中，用户可以拖动信息的复制或者它们能够自己拖动信息到一个新的位置（移动它）。拖放模式无论如何对于程序员来说都是额外的复杂：程序直到放下（粘贴）完成才会知道用户是想剪切还是复制！在应用程序之间拖动，这个没有什么影响，但是在一个应用程序之内进行拖动，应用程序必须多加注意以免踩到自己的脚。例如，在文档中拖动文本，拖动的开始点和放下事件也许是这样：

  void MyEditor::startDrag()
  {
    QDragObject *d = new QTextDrag(myHighlightedText(), this);
    if ( d->drag() && d->target() != this )
      cutMyHighlightedText();
  }

  void MyEditor::dropEvent(QDropEvent* event)
  {
    QString text;

    if ( QTextDrag::decode(event, text) ) {
      if ( event->source() == this && event->action() == QDropEvent::Move ) {
        // 注意不要踩到自己的脚
        event->acceptAction();
        moveMyHighlightedTextTo(event->pos());
      } else {
        pasteTextAt(text, event->pos());
      }
    }
  }

一些窗口部件在数据被拖动到它们上面时会问一个“是”或“否”的细节。比如，一个CAD程序也许只接收在视图中的文本对象上放下的文本。在这种情况下，dragMoveEvent()被使用并且给定一个区域是接受或者忽略拖动：

  void MyWidget::dragMoveEvent(QDragMoveEvent* event)
  {
    if ( QTextDrag::canDecode(event) ) {
      MyCadItem* item = findMyItemAt(event->pos());
      if ( item )
        event->accept();
    }
  }
如果搜索对象的计算指令特别地慢，如果你告诉系统你允许那些区域接受请求的话，你也许可以达到更好的效果：
  void MyWidget::dragMoveEvent(QDragMoveEvent* event)
  {
    if ( QTextDrag::canDecode(event) ) {
      MyCadItem* item = findMyItemAt(event->pos());
      if ( item ) {
        QRect r = item->areaRelativeToMeClippedByAnythingInTheWay();
        if ( item->type() == MyTextType )
          event->accept( r );
        else
          event->ignore( r );
      }
    }
  }

如果你需要在拖动进程开始定时器、开始滚动窗口或者合适的情况（但是不要忘记在dragMoveEvent()中停止滚动和定时器）中给出视觉效果，dragMoveEvent()也可以被使用。

和其它应用程序之间的操作

在X11上，公有的XDND协议被使用，而Qt在Windows上使用OLE标准，并且Qt在Mac上使用Carbon拖动管理器。在X11上，XDND使用MIME，所以不需要转换。Qt的应用编程接口与平台无关。在Windows上，可以识别MIME的应用程序可以通过使用MIME类型命名的剪贴板格式进行通讯。一些Windows引用程序已经在它们的剪贴板格式中使用MIME命名约定了。在内部，Qt也有在专有的剪贴板格式和MIME类型之间转换的能力。在适当时候，这个接口应该被公开，但是如果你现在需要这样的转换，请和你的Qt技术支持服务进行联系。

在X11上，Qt也支持使用Motif拖放协议的拖动。重新实现中合并了由Daniel Dardailler写的一些代码，并且由Qt的Matt Koss <koss@napri.sk>和Trolltech修改过。这里是初始版权通告：

Copyright 1996 Daniel Dardailler。

允许任何目的地使用、复制、修改、发布和销售这个软件并且允许没有任何费用，上面的版权通告必须出现在所有的复制当中并且版权通告和这个允许通告要在支持文档中出现，并且Daniel Dardailler的姓名在没有被特定允许的情况下不能出现在和所发布的软件相关的广告和宣传中。Daniel Dardailler对于这个软件的任何目的的适用性都没有任何责任。它仅仅提供的是“它自己”，而没有明确或暗示任何责任。

Copyright 1999 Matt Koss修改，和上面的协议相同。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Drag And Drop Classes

These classes deal with drag and drop and the necessary mime type encoding and decoding. See also Drag and Drop with Qt.

QColorDrag | Drag and drop object for transferring colors
QDragEnterEvent | Event which is sent to the widget when a drag and drop first drags onto the widget
QDragLeaveEvent | Event which is sent to the widget when a drag and drop leaves the widget
QDragMoveEvent | Event which is sent while a drag and drop is in progress
QDragObject | Encapsulates MIME-based data transfer
QDropEvent | Event which is sent when a drag and drop is completed
QIconDrag | Supports drag and drop operations within a QIconView
QIconDragItem | Encapsulates a drag item
QImageDrag | Drag and drop object for transferring images
QMimeSource | Abstraction of objects which provide formatted data of a certain MIME type
QStoredDrag | Simple stored-value drag object for arbitrary MIME data
QTextDrag | Drag and drop object for transferring plain and Unicode text
QUriDrag | Drag object for a list of URI references
QWindowsMime | Maps open-standard MIME to Window Clipboard formats


Drag and Drop

This program demonstrates Qt's drag and drop functionality.

See $QTDIR/examples/dragdrop for the source code.

See also Examples.


Draw Demo

This example demonstrates several drawing functions and printer output. You can easily add you own drawing functions.

Implementation:

/****************************************************************************
** $Id:  qt/drawdemo.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qwidget.h>
#include <qpainter.h>
#include <qprinter.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qapplication.h>
#include <math.h>

//
// First we define the functionality our demo should present
// to the user. You might add different demo-modes if you wish so.
//

//
// This function draws a color wheel.
// The coordinate system x=(0..500), y=(0..500) spans the paint device.
//

void drawColorWheel( QPainter *p )
{
    QFont f( "times", 18, QFont::Bold );
    p->setFont( f );
    p->setPen( Qt::black );
    p->setWindow( 0, 0, 500, 500 );             // defines coordinate system

    for ( int i=0; i<36; i++ ) {                // draws 36 rotated rectangles

        QWMatrix matrix;
        matrix.translate( 250.0F, 250.0F );     // move to center
        matrix.shear( 0.0F, 0.3F );             // twist it
        matrix.rotate( (float)i*10 );           // rotate 0,10,20,.. degrees
        p->setWorldMatrix( matrix );            // use this world matrix

        QColor c;
        c.setHsv( i*10, 255, 255 );             // rainbow effect
        p->setBrush( c );                       // solid fill with color c
        p->drawRect( 70, -10, 80, 10 );         // draw the rectangle

        QString n;
        n.sprintf( "H=%d", i*10 );
        p->drawText( 80+70+5, 0, n );           // draw the hue number
    }
}

//
// This function draws a few lines of text using different fonts.
//

void drawFonts( QPainter *p )
{
    static const char *fonts[] = { "Helvetica", "Courier", "Times", 0 };
    static int   sizes[] = { 10, 12, 18, 24, 36, 0 };
    int f = 0;
    int y = 0;
    while ( fonts[f] ) {
        int s = 0;
        while ( sizes[s] ) {
            QFont font( fonts[f], sizes[s] );
            p->setFont( font );
            QFontMetrics fm = p->fontMetrics();
            y += fm.ascent();
            p->drawText( 10, y, "Quartz Glyph Job Vex'd Cwm Finks" );
            y += fm.descent();
            s++;
        }
        f++;
    }
}

//
// This function draws some shapes
//

void drawShapes( QPainter *p )
{
    QBrush b1( Qt::blue );
    QBrush b2( Qt::green, Qt::Dense6Pattern );          // green 12% fill
    QBrush b3( Qt::NoBrush );                           // void brush
    QBrush b4( Qt::CrossPattern );                      // black cross pattern

    p->setPen( Qt::red );
    p->setBrush( b1 );
    p->drawRect( 10, 10, 200, 100 );
    p->setBrush( b2 );
    p->drawRoundRect( 10, 150, 200, 100, 20, 20 );
    p->setBrush( b3 );
    p->drawEllipse( 250, 10, 200, 100 );
    p->setBrush( b4 );
    p->drawPie( 250, 150, 200, 100, 45*16, 90*16 );
}

typedef void (*draw_func)(QPainter*);

struct DrawThing {
    draw_func    f;
    const char  *name;
};

//
// All previously implemented functions are collected
// in the following "table".
// If you implement different functionality, your new draw
// function must be assigned here with a function pointer and
// description.
// Leave the zeros at the end, they will be used
// as markers referring to the end of the array.
//

DrawThing ourDrawFunctions[] = {
// name of the function, title presented to the user
    { drawColorWheel,   "Draw color wheel" },
    { drawFonts,        "Draw fonts" },
    { drawShapes,       "Draw shapes" },
    { 0,                0 } };

class DrawView : public QWidget
{
    Q_OBJECT
public:
    DrawView();
    ~DrawView();
public slots:
    void   updateIt( int );
    void   printIt();
protected:
    void   drawIt( QPainter * );
    void   paintEvent( QPaintEvent * );
    void   resizeEvent( QResizeEvent * );
private:
    QPrinter     *printer;
    QButtonGroup *bgroup;
    QPushButton  *print;
    int           drawindex;
    int           maxindex;
};

//
// Construct the DrawView with buttons.
//

DrawView::DrawView()
{
    setCaption( "Qt Draw Demo Application" );
    setBackgroundColor( white );

    // Create a button group to contain all buttons
    bgroup = new QButtonGroup( this );
    bgroup->resize( 200, 200 );
    connect( bgroup, SIGNAL(clicked(int)), SLOT(updateIt(int)) );

    // Calculate the size for the radio buttons
    int maxwidth = 80;
    int maxheight = 10;
    int i;
    const char *n;
    QFontMetrics fm = bgroup->fontMetrics();

    // Find out the longest function description.
    // Here we make use of the last "0,0"-entry in the
    // ourDrawFunctions-array.
    for ( i=0; (n=ourDrawFunctions[i].name) != 0; i++ ) {
        int w = fm.width( n );
        maxwidth = QMAX(w,maxwidth); // QMAX is a macro defined in qglobal.h
                                     // and returns the biggest of to values.
        // Due to its macro nature one should use it with care and with
        // constant parameters only.
    }

    maxwidth = maxwidth + 30;                   // allow 30 pixels for radiobuttons

    for ( i=0; (n=ourDrawFunctions[i].name) != 0; i++ ) {
        QRadioButton *rb = new QRadioButton( n, bgroup );
        rb->setGeometry( 10, i*30+10, maxwidth, 30 );

        maxheight += 30;

        if ( i == 0 )
            rb->setChecked( TRUE );
    }

    maxheight += 10;                            // maxheight is now 10 pixels upper margin
                                                // plus number_of_drawfunctions * 30
                                                // plus 10 pixels lower margin

    drawindex = 0;                              // draw first thing
    maxindex  = i;

    maxwidth += 20;                             // add some margin, this results in the
                                                // final width of bgroup

    bgroup->resize( maxwidth, maxheight );      // resize bgroup to its final size
                                                // when no printersupport is provided

// If -- at compile time -- printer support will be disabled,
// we won't set up printing functionality.

#ifndef QT_NO_PRINTER

    printer = new QPrinter;

    // Create and setup the print button
    print = new QPushButton( "Print...", bgroup );
    print->resize( 80, 30 );
    print->move( maxwidth/2 - print->width()/2, maxindex*30+20 );
    connect( print, SIGNAL(clicked()), SLOT(printIt()) );

    // Resize bgroup to its final size when printersupport is given.
    bgroup->resize( maxwidth, print->y()+print->height()+10 );

#endif

    resize( 640,300 );
}

//
// Clean up.
//
DrawView::~DrawView()
{
#ifndef QT_NO_PRINTER
    delete printer;
#endif
}

//
// Called when a radio button is clicked.
//

void DrawView::updateIt( int index )
{
    if ( index < maxindex ) {
        drawindex = index;
        update();
    }
}

//
// Calls the drawing function as specified by the radio buttons.
//

void DrawView::drawIt( QPainter *p )
{
    (*ourDrawFunctions[drawindex].f)(p);
}

//
// Called when the print button is clicked.
//

void DrawView::printIt()
{
    if ( printer->setup( this ) ) {
        QPainter paint( printer );
        drawIt( &paint );
    }
}

//
// Called when the widget needs to be updated.
//

void DrawView::paintEvent( QPaintEvent * )
{
    QPainter paint( this );
    drawIt( &paint );
}

//
// Called when the widget has been resized.
// Moves the button group to the upper right corner
// of the widget.

void DrawView::resizeEvent( QResizeEvent * )
{
    bgroup->move( width()-bgroup->width(), 0 );
}

//
// Create and display our widget.
//

#include "drawdemo.moc"

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    DrawView   draw;
    app.setMainWidget( &draw );
    draw.setCaption("Qt Example - Drawdemo");
    draw.show();
    return app.exec();
}

See also Examples.


Connect the Points

This example shows very simple mouse-based user interaction and painting without any world transform matrix or other advanced features. Run the program, click the button, move the mouse, release the button, and watch the lines get drawn.

Implementation:

/****************************************************************************
** $Id:  qt/connect.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qwidget.h>
#include <qpainter.h>
#include <qapplication.h>
#include <stdlib.h>

const int MAXPOINTS = 2000;                     // maximum number of points
const int MAXCOLORS = 40;

//
// ConnectWidget - draws connected lines
//

class ConnectWidget : public QWidget
{
public:
    ConnectWidget( QWidget *parent=0, const char *name=0 );
   ~ConnectWidget();
protected:
    void        paintEvent( QPaintEvent * );
    void        mousePressEvent( QMouseEvent *);
    void        mouseReleaseEvent( QMouseEvent *);
    void        mouseMoveEvent( QMouseEvent *);
private:
    QPoint     *points;                         // point array
    QColor     *colors;                         // color array
    int         count;                          // count = number of points
    bool        down;                           // TRUE if mouse down
};

//
// Constructs a ConnectWidget.
//

ConnectWidget::ConnectWidget( QWidget *parent, const char *name )
    : QWidget( parent, name, WStaticContents )
{
    setBackgroundColor( white );                // white background
    count = 0;
    down = FALSE;
    points = new QPoint[MAXPOINTS];
    colors = new QColor[MAXCOLORS];
    for ( int i=0; i<MAXCOLORS; i++ )           // init color array
        colors[i] = QColor( rand()&255, rand()&255, rand()&255 );
}

ConnectWidget::~ConnectWidget()
{
    delete[] points;                            // cleanup
    delete[] colors;
}

//
// Handles paint events for the connect widget.
//

void ConnectWidget::paintEvent( QPaintEvent * )
{
    QPainter paint( this );
    for ( int i=0; i<count-1; i++ ) {           // connect all points
        for ( int j=i+1; j<count; j++ ) {
            paint.setPen( colors[rand()%MAXCOLORS] ); // set random pen color
            paint.drawLine( points[i], points[j] ); // draw line
        }
    }
}

//
// Handles mouse press events for the connect widget.
//

void ConnectWidget::mousePressEvent( QMouseEvent * )
{
    down = TRUE;
    count = 0;                                  // start recording points
    erase();                                    // erase widget contents
}

//
// Handles mouse release events for the connect widget.
//

void ConnectWidget::mouseReleaseEvent( QMouseEvent * )
{
    down = FALSE;                               // done recording points
    update();                                   // draw the lines
}

//
// Handles mouse move events for the connect widget.
//

void ConnectWidget::mouseMoveEvent( QMouseEvent *e )
{
    if ( down && count < MAXPOINTS ) {
        QPainter paint( this );
        points[count++] = e->pos();             // add point
        paint.drawPoint( e->pos() );            // plot point
    }
}

//
// Create and display a ConnectWidget.
//

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    ConnectWidget connect;
#ifndef QT_NO_WIDGET_TOPEXTRA   // for Qt/Embedded minimal build
    connect.setCaption( "Qt Example - Draw lines");
#endif
    a.setMainWidget( &connect );
    connect.show();
    return a.exec();
}

See also Examples.


Adding an accelerated graphics driver to Qt/Embedded

Qt/Embedded has the capacity to make use of hardware accelerators. To use a hardware accelerator for a PCI or AGP driver, you need to perform the following steps:

  1. Define an accelerated descendant of QLinuxFbScreen.

    This should implement QVoodooScreen::connect() to map its registers. Use qt_probe_bus to get a pointer to the PCI config space. This is where you should check that you're being pointed to the right device (using the PCI device/manufacturer ID information). Then use PCI config space to locate your device's accelerator registers in physical memory and mmap the appropriate region from /dev/mem. There is no need to map the framebuffer, QLinuxFbScreen will do this for you. Return FALSE if a problem occurs at any point. QVoodooScreen::initDevice() will be called only by the QWS server and is guaranteed to be called before any drawing is done (and so is a good place to set registers to known states). connect() will be called by every connecting client.

  2. Define an accelerated descendant of QGfxRaster.

    This is where the actual drawing code goes. Anything not implemented in hardware can be passed back to QGfxRaster to do in software. Use the optype variable to make sure that accelerated and unaccelerated operations are synchronised (if you start drawing via software into an area where the hardware accelerator is still drawing then your drawing operations will appear to be in the wrong order). optype is stored in shared memory and is set to 0 by unaccelerated operations; accelerated operations should set it to 1. When a software graphics operation is requested and optype is 1, QGfxRaster::sync() is called; you should provide your own implementation of this that waits for the graphics engine to go idle. lastop is also available for optimisation and is stored in the shared space - this will not be set by the software-only QGfx and can be used to store the type of your last operation (e.g. drawing a rectangle) so that part of the setup for the next operation can be avoided when many of the same operations are performed in sequence.

    All drawing operations should be protected via a QWSDisplay::grab() before any registers, lastop or optype are accessed, and ungrabbed() at the end. This prevents two applications trying to access the accelerator at once and possibly locking up the machine. It's possible that your source data is not on the graphics card so you should check in such cases and fall back to software if necessary. Note that QGfxRaster supports some features not directly supported by QPainter (for instance, alpha channels in 32-bit data and stretchBlt's). These features are used by Qt; stretchBlt speeds up QPixmap::xForm() and drawPixmap() into a transformed QPainter, alpha channel acceleration is supported for 32-bit pixmaps.

  3. If you wish, define an accelerated descendant of QScreenCursor. restoreUnder(), saveUnder(), drawCursor() and draw() should be defined as null operations. Implement set(), move(), show() and hide(). 4k is left for your cursor at the end of the visible part of the framebuffer (i.e. at (width*height*depth)/8 )

  4. Implement initCursor() and createGfx() in your QScreen descendant. Implement useOffscreen() and return TRUE if you can make use of offscreen graphics memory.

  5. Implement a small function qt_get_screen_mychip(), which simply returns a new QMychipScreen

  6. Add your driver to the DriverTable table in qgfxraster_qws.cpp, e.g.
    { "MyChip", qt_get_screen_mychip,1 },

    The first parameter is the name used with QWS_DISPLAY to request your accelerated driver.

  7. To run with your new driver,
    export QWS_DISPLAY=MyChip
    (optionally MyChip:/dev/fb<n> to request a different Linux framebuffer than /dev/fb0), then run the program

If your driver is not PCI or AGP you'll need to inherit QScreen instead of QLinuxFbScreen and implement similar functionality to QLinuxFbScreen, but otherwise the process should be similar. The most complete example driver is qgfxmach64_qws.cpp; qgfxvoodoo_qws.cpp may provide a smaller and easier-to-understand driver.


Qt/Embedded Case Study - Cassiopeia E-100

Introduction

This document describes the steps involved in installing Linux on an embedded device and building a Qt/Embedded application. The target device is the Cassiopeia E-100/E-105. The device has a MIPS Vr4121 processor, 16MB RAM (32MB in the E-105), a Compact Flash slot and a 240x320 16 bit per pixel LCD display.

The only part of this document that is specific to the Cassiopeia is the installation of Linux and the development tools. The example application can be compiled and run on your desktop machine.

Installing Linux

All the information and software required to get Linux running on the VR series of processors is available from the Linux VR web site. In Summary:

Install the tools

Follow the instructions at http://www.linux-vr.org/tools.html.

Build the kernel

Get a sample root ramdisk from ftp://ftp.ltc.com/pub/linux/mips/ramdisk/ramdisk.

Follow the instructions at http://www.linux-vr.org/ramdisk.html to create a ramdisk.o file.

Now build your kernel http://www.linux-vr.org/kernel.html using this ramdisk object. Make sure you have at least the following configuration:

  • Development/incomplete drivers
  • Casio E105 Platform
  • Network and System V IPC
  • RAM disk and Initial RAM disk support
  • Support for console on virtual terminal (so that you can see boot messages)
  • /proc and ext2 filesystem support
  • Simple Frame Buffer with HPC device control

Booting Linux

Follow the instructions at http://www.linux-vr.org/booting.html.

You should see the linux boot messages on the LCD display.

A Qt/Embedded Application

Usually a device such as the Cassiopeia would have a shell, configured as the Qt/Embedded server, that allows client applications to be launched. For the purposes of this tutorial, we will write a simple application that serves as the Qt/Embedded server and client. A more complete Qt/Embbeded server can be found in $QTDIR/examples/compact.

The application that we will write is a simple note pad. It will allow notes to be created, viewed and deleted. Since the Cassiopeia doesn't have a keyboard, we will include a simple on-screen keyboard for input.

Note Pad

Our note pad user interface is very simple. It consists of a toolbar with "New" and "Delete" buttons, a combo box to select the note to view and an editing area.

Take a moment to browse the source code for Note Pad in $QTDIR/examples/notepad/. The code is quite simple, but there are some things worth noting:

  1. Two fonts are set - helvetica 10 point as the application's default font, and helvetica 12 point for the editor. Since we will use prerendered fonts these fonts must be prepared as described here.
  2. The QApplication is constructed with the QApplication::GuiServer type specified. This makes the note pad a Qt/Embedded server. One server must be running for Qt/Embedded clients to run. In this case our application is both server and client because it is the only application we wish to run on our device.
  3. The Cassiopeia (usually) has no keyboard so we must provide some means of character input with the pen. The simplest method is to display a small keyboard. The compact example includes a keyboard, so we use this code. Key and pointer input is Qt/Embedded specific, so it is surrounded by #ifdef Q_WS_QWS ... #endif so that we can compile the example with Qt/X11 or Qt/Windows if we wish.
  4. The touch panel needs to be calibrated. There is a calibration module included in the compact demo, so we use this.

Creating a suitable Qt/Embedded Library

Since our application is quite simple we can remove some unnecessary features from Qt/Embedded. Edit $QTDIR/src/tools/qconfig.h and disable the following features:

    #define QT_NO_IMAGEIO_BMP
    #define QT_NO_IMAGEIO_PPM
    #define QT_NO_IMAGEIO_XBM
    #define QT_NO_IMAGEIO_PNG
    #define QT_NO_ASYNC_IO
    #define QT_NO_ASYNC_IMAGE_IO
    #define QT_NO_TRUETYPE
    #define QT_NO_BDF
    #define QT_NO_FONTDATABASE
    #define QT_NO_MIME
    #define QT_NO_SOUND
    #define QT_NO_PROPERTIES
    #define QT_NO_CURSOR
    #define QT_NO_NETWORKPROTOCOL
    #define QT_NO_COLORNAMES
    #define QT_NO_TRANSFORMATIONS
    #define QT_NO_PSPRINTER
    #define QT_NO_PICTURE
    #define QT_NO_LISTVIEW
    #define QT_NO_CANVAS
    #define QT_NO_DIAL
    #define QT_NO_WORKSPACE
    #define QT_NO_TABLE
    #define QT_NO_LCDNUMBER
    #define QT_NO_STYLE_MOTIF
    #define QT_NO_STYLE_PLATINUM
    #define QT_NO_COLORDIALOG
    #define QT_NO_PROGRESSDIALOG
    #define QT_NO_TABDIALOG
    #define QT_NO_WIZARD
    #define QT_NO_EFFECTS

See Qt Features for a description of the features that can be disabled. This leaves us with a small set of widgets and dialogs necessary for our application. Cross-compile the library for the mips target on the x86 platform:

    cd $QTDIR
    ./configure -xplatform linux-mips-g++ -platform linux-x86-g++
    make
    mipsel-linux-strip $QTDIR/lib/libqt.so.2.2.0

The library is stripped to conserve ramdisk space.

Installation

Compile the application:

    cd examples/notepad
    make
    mipsel-linux-strip notepad

We have chosen to link the application dynamically. While this is important if we plan to run multiple applications, it is a waste of space in an application such as notepad that is supposed to be the only application running. You can link statically by configuring with:

    ./configure -static -xplatform linux-mips-g++ -platform linux-x86-g++

We must install our application and its support files in the ramdisk. Mount the ramdisk using loopback device (you will need loopback device support in your kernel):

    mkdir /mnt/ramdisk
    mount -o loop ~/ramdisk /mnt/ramdisk

Copy the Qt/Embedded library to the ramdisk /lib directory and make the necessary links:

    cd /mnt/ramdisk/lib
    cp $QTDIR/lib/libqt.so.2.2.0 .
    ln -s libqt.so.2.2.0 libqt.so.2.2
    ln -s libqt.so.2.2.0 libqt.so.2

The fonts must be installed in /usr/local/qt-embedded/etc/fonts:

    cd /mnt/ramdisk
    mkdir usr/local
    mkdir usr/local/qt-embedded
    mkdir usr/local/qt-embedded/etc
    mkdir usr/local/qt-embedded/etc/fonts
    cp helvetica_100_50.qlf helvetica_120_50.qlf usr/local/qt-embedded/etc/fonts

When the kernel boots it looks for several files to run. In order to have our application run when the kernel boots, we change its name to /bin/sh. A /tmp directory is also used by Qt/Embedded:

    cp $QTDIR/examples/notepad/notepad /mnt/ramdisk/bin/sh
    mkdir /mnt/ramdisk/tmp
    umount /mnt/ramdisk

Create a ramdisk object, link it with the kernel, copy it to the compact flash and boot Linux. You should see the calibration screen appear on the LCD display.


Character input in Qt/Embedded

Internally in the client/server protocol, each key press and key release is sent as a QWSKeyEvent. A QWSKeyEvent contains the following fields:

  • unicode

    Unicode value

  • keycode

    Qt keycode value as defined in qnamespace.h

  • modifier

    A bitfield consisting of some of Qt::ShiftButton, Qt::ControlButton, and Qt::AltButton.

  • is_press

    TRUE if this is a key press, FALSE if it is a key release.

  • is_auto_repeat

    TRUE if this event is caused by auto repeat.

When the server receives a key event, it is sent to each client process, which is responsible for processing the key event and sending it to the right window, if any. Key events may come from several different sources.

Keyboard drivers

A keyboard driver reads data from a device and gives key events to the server.

Keyboard drivers are currently compiled into the library. They are defined in the file src/kernel/qkeyboard_qws.cpp. At the time of writing, the following drivers are defined:

QWSTtyKeyboardHandler | Input from the system console (tty)
QWSVr41xxButtonsHandler | Input handler for the buttons on Cassiopeia-style PDAs
QWSVFbKeyboardHandler | Virtual framebuffer key input

The keyboard drivers all follow the same pattern. They read keyboard data from a device, find out which keys were pressed, and then call the static function QWSServer::processKeyEvent() with the key information.

At present, the console keyboard driver also handles console switching (Ctrl+Alt-F1...Ctrl+Alt+F10) and termination (Ctrl+Alt+Backspace).

To add a keyboard driver for a new device, make a subclass of QWSKeyboardHandler and instantiate it in QWSServer::newKeyboardHandler() (in qkeyboard_qws.cpp).

Key event filters (input methods)

When the server receives a key event from a keyboard driver, it first passes it through a filter.

This can be used to implement input methods, providing input of characters that are not on the keyboard.

To make an input method, subclass QWSServer::KeyboardFilter (in src/kernel/qwindowsystem_qws.h) and implement the virtual function filter(). If filter() returns FALSE, the event will be sent to the clients (using QWSServer::sendKeyEvent()). If filter() returns TRUE, the event will be stopped. To generate new key events, use QWSServer::sendKeyEvent(). (Do not use processKeyEvent(), since this will lead to infinite recursion.)

To install a keyboard event filter, use QWSServer::setKeyboardFilter(). Currently, only one filter can be installed at a time.

Filtering must be done in the server process.

The launcher example contains an example of a simple input method, SimpleIM which reads a substitution table from a file.

Pen input

Key events do not need to come from a keyboard device. The server process may call QWSServer::sendKeyEvent() at any time.

Typically, this is done by popping up a widget, and letting the user specify characters with the pointer device.

Note: the key input widget should not take focus, since the server would then just send the key events back to the input widget. One way to make sure that the input widget never takes focus is to set the WStyle_Customize and WStyle_Tool widget flags in the QWidget constructor.

The Qt Palmtop environment contains various input widgets such as Handwriting Recognition and Virtual Keyboard.


The Qt/Embedded-specific classes

Qt/Embedded classes fall into two classes - the majority are used by every Qt/Embedded program, some are used only by the Qt/Embedded server. The Qt/Embedded server program can be a client as well, as in the case of a single-process installation. All Qt/Embedded specific source files live in src/kernel and are suffixed _qws. --> indicates inheritance.

  • QFontManager
  • QDiskFont
  • QRenderedFont
  • QFontFactory (and descendants QFontFactoryBDF, QFontFactoryTtf)
  • QGlyph
  • QMemoryManagerPixmap/QMemoryManager
  • QScreen-->QLinuxFbScreen-->accelerated screens, QTransformedScreen-->QVfbScreen
  • QScreenCursor-->accelerated cursor-->QVfbCursor
  • QGfx-->RasterBase-->Raster-->accelerated driver--> QGfxVfb-->QGfxTransformedRaster
  • QLock, QLockHolder
  • QDirectPainter
  • QWSSoundServer, Client
  • QWSWindow
  • QWSKeyboardHandler-->subtypes
  • QWSMouseHandler-->QCalibratedMouseHandler-->mouse types
  • QWSDisplay
  • QWSServer
  • QWSClient
  • QWSDisplayData
  • QWSCommands
  • QCopChannel
  • QWSManager
  • QWSDecoration
  • QWSPropertyManager
  • QWSRegionManager
  • QWSSocket, QWSServerSocket

QFontManager

There is one of these per application. At application startup time it reads the font definition file from $QTDIR/etc/fonts/fontdir (or /usr/local/etc/qt-embedded/fonts/fontdir if QTDIR is undefined). It keeps track of all font information and maintains a cache of rendered fonts. It also creates the font factories - QFontManager::QFontManager is the place to add constructors for new factories. It provides a high-level interface for requesting a particular font and calls QFontFactories to load fonts from disk on demand. Note that this only applies to BDF and TrueType fonts; Qt/Embedded's optimised .qpf font file format bypasses the QFontManager mechanism altogether.

There should be no need to modify this class unless you wish to change font matching or cacheing behaviour.

QDiskFont

This contains information about a single on-disk font file (e.g. /usr/local/etc/qt-embedded/times.ttf). It holds the file path, information about whether the font is scalable, its weight, size, Qt/Embedded name, etc. This information is used so that QFontManager can find the closest matching disk font (it uses a scoring mechanism weighted towards matching names, then whether the font's italic, then weight).

There should be no reason to modify this class.

QRenderedFont

There is one and only one QRenderedFont for every unique font currently loaded by the system (that is, each unique combination of name, size, weight, italic or not, anti-aliased or not). QRenderedFonts are reference counted; once no one is using the QRenderedFont it is deleted along with its cache of glyph bitmaps. The QDiskFont it was loaded from remains opened by its QFontFactory.

There should be no reason to modify this class, unless you wish to change the way in which glyphs are cached.

QFontFactory (and descendants QFontFactoryBDF, QFontFactoryTtf)

These provide support for particular font formats, for instance the scalable Truetype and Type1 formats (both supported in QFontFactoryTtf, which uses Freetype 2) and the bitmap BDF format used by X. It's called to open an on-disk font; once a font is opened it remains opened so that the creation of new font instances from the disk font is fast. It can also create a QRenderedFont and convert from Unicode values to an index into the font file. For compactness, glyphs are stored in the order and indexes they are defined in the font rather than in Unicode order.

There should be no need to modify this class, but it should be inherited if you wish to add a different type of font renderer (e.g. for a custom vector font format).

QGlyph

This describes a particular image of a character from a QRenderedFont - for example, the letter 'A' at 10 points in Times New Roman, bold italic, anti-aliased. It contains pointers to a QGlyphMetrics structure with information about the character and to the raw data for the glyph - this is either a 1-bit mask or an 8-bit alpha channel. Each QRenderedFont creates these on demand and caches them once created (note that this is not currently implemented for TrueType fonts).

You would only need to modify this class if you were, for example, modifying Qt/Embedded to support textured fonts, in which case you would also need to modify QGfxRaster.

QMemoryManagerPixmap/QMemoryManager

This handles requests for space for pixmaps and also keeps track of QPF format fonts (these are small 'state dumps' of QRenderedFonts, typically 2-20K in size; they can be mmap'd direct from disk in order to save memory). If a QPF font is found which matches a font request no new QRenderedFont need be created for it. It's possible to strip out all QFontFactory support and simply use QPFs if your font needs are modest (for instance, if you only require a few fixed point sizes). Note that no best-match loading is performed with QPFs, as opposed to those loaded via QFontManager, so if you don't have the correct QPF for a point size text in that size will simply not be displayed.

There should be no need to modify this class.

QScreen-->QLinuxFbScreen-->accelerated screens, QTransformedScreen-->QVfbScreen

These encapsulate the framebuffer Qt/Embedded is drawing to, provide support for mapping of coordinates for rotating framebuffers, allow manipulation of the colour palette and provide access to offscreen graphics memory for devices with separate framebuffer memories.

This is used for cacheing pixmaps and allowing accelerated pixmap->screen blt's. QLinuxFbScreen and the accelerated screens use the Linux /dev/fb interface to get access to graphics memory and information about the characteristics of the device. The framebuffer device to open is specified by QWS_DISPLAY. Only QTransformedScreen implements the support for rotated framebuffers. QVfbScreen provides an X window containing an emulated framebuffer (a chunk of shared memory is set aside as the 'framebuffer' and blt'd into the X window) - this is intended as a debugging device allowing users to debug their applications under Qt/Embedded without leaving X. The accelerated screen drivers check to see if they can drive the device specified by QWS_CARD_SLOT (which defaults to the usual position of an AGP slot if not specified) and mmap its on-chip registers from /dev/mem. They may also do chip-specific setup (initialising registers to known values and so on). Finally, QScreen's are used to create new QScreenCursors and QGfxes.

If you wish to modify the way pixmaps are allocated in memory, subclass or modify QLinuxFbScreen. If you're writing an accelerated driver you will need to subclass QScreen or QLinuxFbScreen.

QScreenCursor-->accelerated cursor-->QVfbCursor

This handles drawing the on-screen mouse cursor, and saving and restoring the screen under it for the non-accelerated cursor types.

Subclassing QScreenCursor is optional in an accelerated driver (you would only want to do so if the hardware supports a hardware cursor).

QGfx-->RasterBase-->Raster-->accelerated driver--> QGfxVfb-->QGfxTransformedRaster

This class encapsulates drawing operations, a little like a low-level QPainter. QGfxRaster and its descendants are specifically intended for drawing into a raw framebuffer. They can take an offset for drawing operations and a clipping region in order to support drawing into windows. You will need to subclass the QGfxRaster template in order to implement an accelerated driver.

If you're brave, modifying QGfxRaster would allow you to customise how drawing is done or add support for a new bit depth/pixel format.

QLock, QLockHolder

This encapsulates a System V semaphore, used for synchronising access to memory shared between Qt/Embedded clients. QLockHolder is a utility class to make managing and destroying QLocks easier.

There should be no need to modify this class unless porting Qt/Embedded to an operating system without System V IPC.

QDirectPainter

This is a QPainter which also gives you a pointer to the framebuffer of the window it's pointing to, the window's clip region and so on. It's intended to easily allow you to do your own pixel-level manipulation of window contents.

There should be no reason to modify this class.

QWSSoundServer, Client

The Qt/Embedded server contains a simple sound player and mixer. Clients can request the server play sounds specified as files.

There should be no need to modify this class unless porting Qt/Embedded to an operating system without a Linux-style /dev/dsp.

QWSWindow

This contains the server's notion of an individual top level window - the region of the framebuffer it's allocated, the client that created it and so forth.

There should be no reason to modify this class.

QWSKeyboardHandler-->subtypes

This handles keyboard/button input. QWSKeyboardHandler is subclassed to provide for reading /dev/tty, an arbitrary low-level USB event device (for USB keyboards) and some PDA button devices.

Modifying QWSKeyboardHandler would allow you to support different types of keyboard (currently only a fairly standard US PC style keyboard is supported); subclassing it is the preferred way to handle non-pointer input devices.

QWSMouseHandler-->QCalibratedMouseHandler-->mouse types

This handles mouse/touchpanel input. Descendants of QCalibratedMouseHandler make use of filtering code which prevents 'jittering' of the pointer on touchscreens; some embedded devices do this filtering in the kernel in which case the driver doesn't need to inherit from QCalibratedMouseHandler.

Subclassing QCalibratedMouseHandler is preferred for touchpanels without kernel filtering; inheriting QWSMouseHandler is the way to add any other type of pointing device (pen tablets, touchscreens, mice, trackballs and so forth).

QWSDisplay

This class exists only in the Qt/Embedded server and keeps track of all the top-level windows in the system, as well as the keyboard and mouse.

You would only want to modify this if making deep and drastic modifications to Qt/Embedded window behaviour (alpha blended windows for example).

QWSServer

This manages the Qt/Embedded server's Unix-domain socket connections to clients. It sends and receives QWS protocol events and calls QWSDisplay in order to do such things as change the allocation region of windows.

The only reason to modify this would be to use something other than some sort of socket-like mechanism to communicate between Qt/Embedded applications (in which case modify QWSClient too). If you have something like Unix domain sockets, modify QWSSocket/QWSServerSocket instead. Don't add extra QWS events to communicate between applications, use QCOP instead.

QWSClient

This encapsulates the client side of a Qt/Embedded connection and can marshal and demarshal events.

There should be no reason to modify this except to use something radically different from Unix domain sockets to communicate between Qt/Embedded applications.

QWSDisplayData

This manages a client's QWSClient, reading and interpreting events from the QWS server. It connects to the QWS server on application startup, getting information about the framebuffer and creating the memory manager. Other information about the framebuffer comes directly from /dev/fb in QLinuxFbScreen.

There should be no reason to modify this.

QWSCommands

These encapsulate the data sent to and from the QWS server.

There should be no reason to modify them.

QCopChannel

QCop is a simple IPC mechanism for communication between Qt/Embedded applications. String messages with optional binary data can be sent to different channels.

The mechanism itself is designed to be bare-bones in order for users to build whatever mechanism they like on top of it.

QWSManager

This provides Qt/Embedded window management, drawing a title bar and handling user requests to move, resize the window and so on.

There should be no reason to modify it but you should subclass it if you want to modify window behaviour (point to click versus focus follows mouse, for instance).

QWSDecoration

Descendants of this class are different styles for the Qt/Embedded window manager, for instance QWSWindowsDecoration draws Qt/Embedded window frames in the style of Windows CE.

Subclass it in order to provide a new window manager appearance (the equivalent of a Windows XP or Enlightenment theme).

QWSPropertyManager

This provides the QWS client's interface to the QWS property system (a simpler version of the X property system, it allows you to attach arbitrary data to top-level windows, keyed by an integer).

There should be no reason to modify it.

QWSRegionManager

Used by both client and server to help manage top-level window regions.

There should be no reason to modify it.

QWSSocket, QWSServerSocket

Provides Unix-domain sockets.

Modify this if you're porting to a non-Unix OS but have something analogous to Unix-domain sockets (a byte-oriented, reliable, ordered transmission mechanism, although you can probably implement it with something like a message queue as well).


Qt/Embedded environment variables

Variable | Notes
QWS_SW_CURSOR | If defined, always use a software mouse cursor even when using an accelerated driver that supports a hardware cursor
QWS_DISPLAY | Defines display type and framebuffer, e.g. Voodoo3 Mach64:/dev/fb1 Defaults to unaccelerated Linux framebuffer driver on /dev/fb0. Valid drivers are QVfb, VGA16, LinuxFb (unaccelerated Linux framebuffer), Mach64 (accelerated for ATI Mach64 cards such as the Rage Pro), Voodoo3 (accelerated for the 3dfx Voodoo 3, should also work on Voodoo Banshee), Matrox (should work on all Matrox graphics cards since the Matrox Millennium), Transformed(for rotated displays), SVGALIB and VNC. Transformed displays have a special format - within the specification should be a multiple of 90 degrees rotation specified as Rot<x>, for instance Transformed:Rot90.
QTDIR | If defined tells Qt/Embedded to where to find its fonts - fontdir should be in $QTDIR/etc/fonts/. If undefined it's assumed to be /usr/local/qt-embedded
QWS_SIZE | If defined forces Qt/Embedded into a window of <width> x <height> size centred within the screen, e.g. 320x200
QWS_NOMTRR | If defined, don't use Memory Type Range Registers to define the framebuffer as write-combined on x86. Write-combining speeds up graphics output.
QWS_CARD_SLOT | Tells the accelerated drivers which card to attempt to accelerate. This should be a path in /proc/bus/pci. It defaults to /proc/bus/pci/01/00.0 - the first device on the second PCI bus in the system, which is normally the AGP card.
QWS_USB_KEYBOARD | If defined, instead of opening /dev/tty open the USB low-level event device defined in QWS_USB_KEYBOARD (e.g. /dev/input/event0) - this is useful if you wish to run X and Qt/Embedded side by side on different framebuffers.
QWS_MOUSE_PROTO | Defined as <type>:<device>, e.g. Microsoft:/dev/ttyS0. If you want to use a USB mouse directly (separate from X) use MouseMan:/dev/input/mouse0 or similar. Valid mouse protocls are Auto (automatically sense protocol), MouseMan, IntelliMouse, Microsoft, QVfbMouse (only useful with QVfb) and TPanel, a sample touch panel driver.
QWS_KEYBOARD | Defines the keyboard type. Multiple keyboards can be handled at once, input will be read from all of them. Valid values: Buttons (an iPaq button device if QT_QWS_IPAQ is compiled, otherwise one for the Cassiopeia), QVfbKeyboard (only useful with QVfb), and TTY (either a USB keyboard or /dev/tty depending if QWS_USB_KEYBOARD is defined)


The Feature Definition File

The file src/tools/qfeatures.h includes the file src/tools/qconfig.h. By modifying qconfig.h, you can define a subset of the full Qt functionality that you wish to have available on your installation.

Note that such modification is only supported on Qt/Embedded platforms, where reducing the size of Qt is important and the application-set is often fixed.

The config.h definition file simply defines macros to disable features. Some features are dependent on other features and these dependencies are expressed in qfeatures.h.

The available options are:

Macro | Disables | Set automatically by
Images (QImageIO)
QT_NO_IMAGEIO_BMP | The Microsoft Bitmap image file format. |
QT_NO_IMAGEIO_PPM | The Portable Pixmap image file format. |
QT_NO_IMAGEIO_XBM | The X11 Bitmap image file format. |
QT_NO_IMAGEIO_XPM | The X11 Pixmap image file format. |
QT_NO_IMAGEIO_PNG | The Portable Network Graphics image file format. |
Animation
QT_NO_ASYNC_IO | Asynchronous I/O (QAsyncIO) |
QT_NO_ASYNC_IMAGE_IO | Asynchronous Image I/O and GIF image support (QImageDecoder, ...) |
QT_NO_MOVIE | Animation support (QMovie) | QT_NO_ASYNC_IO, QT_NO_ASYNC_IMAGE_IO
Fonts
QT_NO_TRUETYPE | TrueType (TTF and TTC) font file format, only used by Qt/Embedded. |
QT_NO_BDF | Bitmap Distribution Format (BDF) font file format, only used by Qt/Embedded. |
QT_NO_FONTDATABASE | Font database. |
Internationalization
QT_NO_I18N | Conversions between Unicode and 8-bit encodings. |
QT_NO_UNICODETABLES | Large tables defining such things as upper and lowercase conversions for all Unicode characters. |
MIME
QT_NO_MIME | Multipurpose Internet Mail Extensions, an internet standard for encoding and tagging typed data (eg. text, images, colors) (QMimeSource) |
QT_NO_RICHTEXT | HTML-like text (QStyleSheet, QLabel) | QT_NO_MIME
QT_NO_DRAGANDDROP | Drag-and-drop data between applications (QDragObject) | QT_NO_MIME
QT_NO_CLIPBOARD | Cut-and-paste data between applications (QClipboard) | QT_NO_MIME
Sound
QT_NO_SOUND | Playing audio files (QSound) |
Scipting
QT_NO_PROPERTIES | Scripting of Qt-based applications. |
Qt/Embedded-specific
QT_NO_QWS_CURSOR | The cursor sprite on Qt/Embedded. Pen-operated devices would not normally need this feature. |
QT_NO_QWS_DEPTH_8GRAYSCALE | 8 bits per pixel: 256 levels of gray. Incompatible with QWS_DEPTH_8. |
QT_NO_QWS_DEPTH_8 | 8 bits per pixel: 216-color cube with 40 auxiliary colors. Incompatible with QWS_DEPTH_8GRAYSCALE. |
QT_NO_QWS_DEPTH_15 | 15 bits per pixel: 32 levels for each of red, green and blue. |
QT_NO_QWS_DEPTH_16 | 16 bits per pixel: 64 levels of green, 32 levels for red and for blue. |
QT_NO_QWS_DEPTH_32 | 32 bits per pixel: 256 levels for each of red, green and blue. |
QT_NO_QWS_MACH64 | Mach64 accelerated driver (demonstration only). |
QT_NO_QWS_VFB | Virtual framebuffer running on X11 (see reference documentation). |
Networking
QT_NO_NETWORKPROTOCOL | Abstract multi-protocol data retrieval, with local file retrieval included (QNetworkProtocol) |
QT_NO_NETWORKPROTOCOL_FTP | FTP-protocol data retrieval. | QT_NO_NETWORKPROTOCOL
QT_NO_NETWORKPROTOCOL_HTTP | HTTP-protocol data retrieval. | QT_NO_NETWORKPROTOCOL
Painting/drawing
QT_NO_COLORNAMES | Color names such as "red", used by some QColor constructors and by some HTML documents (QColor, QStyleSheet) |
QT_NO_TRANSFORMATIONS | Used by a number of classes in Qt. With this, rotation and scaling are possible. Without it, only co-ordinate translation (QWMatrix) |
QT_NO_PSPRINTER | PostScript printer support. |
QT_NO_PRINTER | Printer support (QPrinter) | QT_NO_PSPRINTER (Unix only)
QT_NO_PICTURE | Save Qt drawing commands to a files (QPicture) |
Widgets
QT_NO_WIDGETS | Disabling this disables all widgets except QWidget. |
QT_NO_TEXTVIEW | HTML document viewing (QTextView) | QT_NO_WIDGETS, QT_NO_RICHTEXT
QT_NO_TEXTBROWSER | HTML document browsing (QTextBrowser) | QT_NO_TEXTVIEW
QT_NO_ICONVIEW | Labelled icons (QIconView) | QT_NO_WIDGETS, QT_NO_DRAGANDDROP
QT_NO_LISTVIEW | Lists of information (QListView) | QT_NO_WIDGETS
QT_NO_CANVAS | Object canvas (QCanvas) | QT_NO_WIDGETS
QT_NO_DIAL | Value control (QDial) | QT_NO_WIDGETS
QT_NO_WORKSPACE | Multi-document interface (QWorkspace) | QT_NO_WIDGETS
QT_NO_LCDNUMBER | LCD-like number display (QLCDNumber) | QT_NO_WIDGETS
GUI Styles
QT_NO_STYLE_WINDOWS | Microsoft Windows style (QWindowsStyle) | QT_NO_WIDGETS
QT_NO_STYLE_MOTIF | OSF Motif style (QMotifStyle) | QT_NO_WIDGETS
QT_NO_STYLE_CDE | Open Group CDE style (QCDEStyle) | QT_NO_STYLE_MOTIF
QT_NO_STYLE_AQUA | MacOS X style (QAquaStyle)
QT_NO_STYLE_PLATINUM | MacOS 9 style (QPlatinumStyle) | QT_NO_WIDGETS
QT_NO_STYLE_SGI | SGI style (QSGIStyle) | QT_NO_STYLE_MOTIF
Dialogs
QT_NO_DIALOGS | Disabling this disables all common dialogs QWidget. | QT_NO_WIDGETS
QT_NO_FILEDIALOG | The file selection dialog (QFileDialog) | QT_NO_DIALOGS, QT_NO_NETWORKPROTOCOL, QT_NO_LISTVIEW
QT_NO_FONTDIALOG | The font selection dialog (QFontDialog) | QT_NO_DIALOGS, QT_NO_FONTDATABASE
QT_NO_COLORDIALOG | The color selection dialog (QColorDialog) | QT_NO_DIALOGS
QT_NO_INPUTDIALOG | Text input dialog (QInputDialog) | QT_NO_DIALOGS
QT_NO_MESSAGEBOX | Message/prompting dialog (QMessageBox) | QT_NO_DIALOGS
QT_NO_PROGRESSDIALOG | Long-computation progress dialog (QProgressDialog) | QT_NO_DIALOGS
QT_NO_TABDIALOG | Tabbed-pages dialog (QTabDialog) | QT_NO_DIALOGS
QT_NO_WIZARD | Multi-step dialog (QWizard) | QT_NO_DIALOGS


Fonts in Qt/Embedded

Supported Formats

Qt/Embedded supports four font formats:

  • TrueType (TTF) - the scalable font technology now standard on MS-Windows and Apple Macintosh, and becoming popular on X11.
  • Postscript Type1 (PFA/PFB) - scalable fonts often used by printers, also popular on X11. These are similar in functionality to TTF fonts and are not discussed further in this document.
  • Bitmap Distribution Format fonts (BDF) - a standard format for non-scalable fonts. A large number of BDF fonts are supplied as part of standard X11 distributions - most of these can be used with Qt/Embedded. You should not use these in a production system: they are very slow to load and take up a lot of storage space. Instead, render the BDF to a QPF.
  • Qt Prerendered Font (QPF) - a light-weight non-scalable font format specific to Qt/Embedded.

Support for each of these font formats, except QPF which is always enabled, can be enabled or disabled independently by using the Qt/Embedded Features Definition. There is support in Qt/Embedded for writing a QPF font file from any font, thus you can initially enable TTF and BDF formats, save QPF files for the fonts and sizes you need, then remove TTF and BDF support.

See tools/makeqpf for a tool that helps produce QPF files from the TTF and BDF, or just run your application with the -savefonts option.

Memory Requirements

With TTF fonts, each character in the font at a given point size is only rendered when first used in a drawing or metrics operation. With BDF fonts all characters are rendered when the font is used. With QPF fonts, the characters are stored in the same format as Qt uses when drawing.

For example, a 10-point Times font containing the ASCII characters uses around 1300 bytes when stored in QPF format.

Taking advantage of the way the QPF format is structured, Qt/Embedded memory-maps the data rather than reading and parsing it. This reduces RAM consumption even further.

Scalable fonts use a larger amount of memory per font, but these fonts provide a memory saving if many different sizes of each font are needed.

Smooth Fonts

TTF, PFA, and QPF fonts can be rendered as smooth anti-aliased fonts to give superior readability, especially on low-resolution devices. The difference between smooth and non-smooth fonts is illustrated below (you may need to change your display to low resolution to see the difference):

In Qt/Embedded 2.2.1, smooth fonts use 8 times as much memory as non-smooth fonts. This multiplier will be reduced to a configurable 2 or 4 (ie. 4-level and 16-level shading rather than the current excessive 256-level shading).

Unicode

All fonts used by Qt/Embedded use the Unicode character encoding. Most fonts available today use this encoding, but they usually don't contain all the Unicode characters. A complete 16-point Unicode font uses over 1 MB of memory.

The font definition file

When Qt/Embedded applications run, they look for a file called $QTDIR/lib/fonts/fontdir or /usr/local/qt-embedded/lib/fonts/fontdir. This file defines the fonts available to the application. It has the following format:

name file renderer italic weight size flags
where

Field | Value
name | Helvetica, Times, etc.
file | helvR0810.bdf, verdana.ttf, etc.
renderer | BDF or FT
italic | y or n
weight | 50 is normal, 75 is bold, etc.
size | 0 for scalable or pointsize times 10 (e.g., 120 for 12pt)
flags
  • s: smooth (anti-aliased)
  • u: unicode range when saving (default is Latin-1)
  • a: ascii range when saving (default is Latin-1)

The font definition file does not specify QPF fonts; these are loaded directly from the directory containing the fontdir file, and must be named name_size_weightitalicflag.qpf, where

Field | Value
name | helvetica, times, etc. (in lowercase)
size | pointsize times 10 (e.g., 120 for 12pt)
italicflag | i for italic, otherwise nothing.
weight | 50 is normal, 75 is bold, etc.

If an application is run with the -savefonts command-line option, then whenever a font other than a QPF font is used, a corresponding QPF file is saved. This allows you to easily find the font usage of your applications and to generate QPF files so that you can eventually reduce the memory usage of your applications by disabling TTF and BDF support from Qt/Embedded, or by modifying the initialization of qws_savefonts in kernel/qapplication_qws.cpp of the Qt/Embedded library source code. In extreme cases of memory-saving, it is possible to save partially-rendered fonts (eg. only the characters in "Product NameTM") if you are certain that these are the only characters you will need from the font. See QMemoryManager::savePrerenderedFont() for this functionality.

Notes

The font definition file, naming conventions for font files, and the format of QPF files may change in versions of Qt/Embedded after 2.2.1.

When enabled, Qt/Embedded uses the powerful FreeType2 library to implement TrueType and Type1 support.


Enabling the Linux Framebuffer

This is only a short guide. See /usr/src/linux/README and /usr/src/linux/Documentation/fb/ for detailed information. There is also a detailed explanation at http://www.linuxdoc.org/HOWTO/Framebuffer-HOWTO.html.

  1. Make sure that you have the Linux kernel source code in /usr/src/linux/.

  2. Log in as root and cd /usr/src/linux

  3. Configure the kernel:

    Run:

        make menuconfig

    Select "Code maturity level options" and set "Prompt for development and/or incomplete code/drivers".

    Then select "Console drivers" and set "Support for frame buffer devices" to built-in (even if it says EXPERIMENTAL). Then configure the driver. Most modern graphics cards can use the "VESA VGA graphics console"; use that or a driver that specifically matches your video card. Finally, enable "Advanced low level driver options" and make sure that 16 and 32 bpp packed pixel support are enabled.

    When you are finished, chose exit and save.

  4. Compile the kernel

    First do:

        make dep
    then:
        make bzImage

    The new kernel should now be in arch/i386/boot/bzImage.

  5. Copy the kernel to the boot directory:
        cp arch/i386/boot/bzImage /boot/linux.vesafb

  6. Edit /etc/lilo.conf.

    Warning: Keep a backup of /etc/lilo.conf, and have a rescue disk available. If you make a mistake, the machine may not boot.

    The file /etc/lilo.conf specifies how the system boots. The precise contents of the file varies from system to system. Here is an example:

    # LILO configuration file
boot = /dev/hda3
delay = 30
image = /boot/vmlinuz
  root = /dev/hda3
  label = Linux
  read-only # Non-UMSDOS filesystems should be mounted read-only for checking
other=/dev/hda1
        label=nt
        table=/dev/hda

    Make a new "image" section that is a copy of the first one, but with

      image = /boot/linux.vesafb
    and
      label = Linux-vesafb
endcode
  Place it just above the first image section.

  Add a line before the image section saying \c{vga = 791}. (Meaning
  1024x768, 16 bpp.)

  With the above example, lilo.conf would now be:
\code
# LILO configuration file
boot = /dev/hda3
delay = 30
vga = 791
image = /boot/linux.vesafb
  root = /dev/hda3
  label = Linux-vesafb
  read-only # Non-UMSDOS filesystems should be mounted read-only for checking
image = /boot/vmlinuz
  root = /dev/hda3
  label = Linux
  read-only # Non-UMSDOS filesystems should be mounted read-only for checking
other=/dev/hda1
        label=nt
        table=/dev/hda

    Do not change any existing lines in the file; just add new ones.

  7. To make the new changes take effect, run the lilo program:
        lilo

  8. Reboot the system. You should now see a penguin logo while the system is booting. (Or more than one on a multi-processor machine.)

  9. If it does not boot properly with the new kernel, you can boot with the old kernel by entering the label of the old image section at the LILO prompt. (with the example lilo.conf file, the old label is Linux.)

    If that does not work (probably because of an error in lilo.conf), boot the machine using your rescue disk, restore /etc/lilo.conf from backup and re-run lilo.

  10. Testing: Here's a short program that opens the frame buffer and draws a gradient-filled red square.

    #include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>

int main()
{
    int fbfd = 0;
    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;
    long int screensize = 0;
    char *fbp = 0;
    int x = 0, y = 0;
    long int location = 0;

    // Open the file for reading and writing
    fbfd = open("/dev/fb0", O_RDWR);
    if (!fbfd) {
        printf("Error: cannot open framebuffer device.\n");
        exit(1);
    }
    printf("The framebuffer device was opened successfully.\n");

    // Get fixed screen information
    if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) {
        printf("Error reading fixed information.\n");
        exit(2);
    }

    // Get variable screen information
    if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) {
        printf("Error reading variable information.\n");
        exit(3);
    }

    printf("%dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel );

    // Figure out the size of the screen in bytes
    screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;

    // Map the device to memory
    fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED,
                       fbfd, 0);
    if ((int)fbp == -1) {
        printf("Error: failed to map framebuffer device to memory.\n");
        exit(4);
    }
    printf("The framebuffer device was mapped to memory successfully.\n");

    x = 100; y = 100;       // Where we are going to put the pixel

    // Figure out where in memory to put the pixel
    for ( y = 100; y < 300; y++ )
        for ( x = 100; x < 300; x++ ) {

            location = (x+vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
                       (y+vinfo.yoffset) * finfo.line_length;

            if ( vinfo.bits_per_pixel == 32 ) {
                *(fbp + location) = 100;        // Some blue
                *(fbp + location + 1) = 15+(x-100)/2;     // A little green
                *(fbp + location + 2) = 200-(y-100)/5;    // A lot of red
                *(fbp + location + 3) = 0;      // No transparency
            } else  { //assume 16bpp
                int b = 10;
                int g = (x-100)/6;     // A little green
                int r = 31-(y-100)/16;    // A lot of red
                unsigned short int t = r<<11 | g << 5 | b;
                *((unsigned short int*)(fbp + location)) = t;
            }

        }
    munmap(fbp, screensize);
    close(fbfd);
    return 0;
}


Qt/Embedded Performance Tuning

When building embedded applications on low-powered devices, a number of options are available that would not be considered in a desktop application environment. These options reduce the memory and/or CPU requirements at the cost of other factors.

  • Tuning the functionality of Qt
  • General programming style
  • Static vs. Dynamic linking
  • Alternative memory allocation

General programming style

The following guidelines will improve CPU performance:

  • Create dialogs and widgets once, then QWidget::hide() and QWidget::show() them, rather than creating them and deleting them every time they are needed. This will use a little more memory, but will be much faster. Try to create them the first time "lazily" to avoid slow startup (only create the Find dialog the first time the user invokes it).

Static vs. Dynamic linking

Much CPU and memory is used by the ELF linking process. You can make significant savings by using a static build of your application suite. This means that rather than having a dynamic library (libqte.so) and a collection of executables which link dynamically to that library, you build all the applications into a single executable and statically link that with a static library (libqt.a). This improves start-up time, and reduces memory usage, at the expense of flexibility (to add a new application, you must recompile the single executable) and robustness (if one application has a bug, it might harm other applications). If you need to install end-user applications, this may not be an option, but if you are building a single application suite for a device with limited CPU power and memory, this option could be very beneficial.

To compile Qt as a static library, add the -static options when you run configure.

To build your application suite as an all-in-one application, design each application as a stand-alone widget or set of widgets, with only minimal code in the main() function. Then, write an application that gives some way to switch between the applications (eg. a QIconView). The QPE is an example of this. It can be built either as a set of dynamically-linked executables, or as a single static application.

Note that you should generally still link dynamically against the standard C library and any other libraries which might be used by other applications on your device.

Alternative memory allocation

We have found that the libraries shipped with some C++ compilers on some platforms have poor performance in the built-in "new" and "delete" operators. You might gain performance by re-implementing these functions. For example, you can switch to the plain C allocators by adding the following to your code:

    void* operator new[]( size_t size )
    {
        return malloc( size );
    }

    void* operator new( size_t size )
    {
        return malloc( size );
    }

    void operator delete[]( void *p )
    {
        free( p );
    }

    void operator delete[]( void *p, size_t size )
    {
        free( p );
    }

    void operator delete( void *p )
    {
        free( p );
    }

    void operator delete( void *p, size_t size )
    {
        free( p );
    }


Qt/Embedded Pointer Handling

Pointer handling in Qt/Embedded works for any mouse or mouse-like device such as touchpanels and trackballs.

Usually only one pointer device is supported in an embedded device, but for demonstration purposes, Qt/Embedded includes a large number of supported devices.

Mouse Protocols

Qt/Embedded normally auto-detects the mouse type and device if it is one of the supported types on /dev/psaux or one of the /dev/ttyS? serial lines. If multiple mice are detected, all may be used simultaneously.

Alternatively, you may set the environment variable QWS_MOUSE_PROTO to determine which mouse to use. This environment variable may be set to:

<protocol>:<device>
where <protocol> is one of:
  • MouseMan
  • IntelliMouse
  • Microsoft
and <device> is the mouse device, often /dev/mouse. If no such variable is specified, the built-in default is Auto, which enables auto-detection of the mouse protocol and device.

To add another protocol, new subclasses of QAutoMouseSubHandler or QMouseHandler can be written in kernel/qwsmouse_qws.cpp.

Touch Panels

Qt/Embedded ships with support for the NEC Vr41XX touchpanel and the iPAQ touchpanel. These are subclasses of QCalibratedMouseHandler which is in turn a subclass of QMouseHandler in kernel/qwsmouse_qws.cpp.


Porting your applications to Qt/Embedded

Existing Qt applications should require no porting provided there is no platform dependent code. Platform dependent code includes system calls, calls to the underlying window system (Windows or X11), and Qt platform specific methods such as QApplication::x11EventFilter().

For cases where it is necessary to use platform dependent code there are macros defined that can be used to enable/disable code for each platform using #ifdef directives:

Platform | Macro
Qt/X11 | Q_WS_X11
Qt/Windows | Q_WS_WIN
Qt/Embedded | Q_WS_QWS


Qt/嵌入式的虚拟帧缓冲

虚拟帧缓冲允许在你的桌面机器上开发Qt/嵌入式程序，而不用在命令台和X11之间来回切换。

The virtual framebuffer is located in $QTDIR/tools/qvfb.

使用虚拟帧缓冲

  1. 确认$QTDIR/src/tools/qconfig.h中的QT_NO_QWS_VFB是没有被定义的，并且编译Qt/Embedded库。
  2. 把qvfb作为一个普通的Qt/X11应用程序来编译并且运行它。不要把它作为一个Qt/嵌入式应用程序来编译。
  3. 启动一个Qt/嵌入式主程序（比如，使用QApplication::GuiServer标志来构造一个QApplication或者在命令行下使用-qws参数）。你将会需要指定你所要使用虚拟帧缓冲驱动的服务器，例如：
        widgets -qws -display QVFb:0
  4. 你也可以设置QWS_DISPLAY环境变量为QVFb:0。

qvfb支持下列命令行参数：

  • -width width

    虚拟帧缓冲的宽度（默认：240）。

  • -height height

    虚拟帧缓冲的高度（默认：320）。

  • -depth depth

    虚拟帧缓冲的色深（1、8或者32，默认：8）。

  • -nocursor

    在帧缓冲窗口不显示X11光标。

  • -qwsdisplay :id

    提供的Qt/嵌入式显示id（默认：0）。

虚拟帧缓冲设计

虚拟帧缓冲使用了共享存储区域（虚拟的帧缓冲）来模拟帧缓冲并且在一个窗口中（qvfb）模拟一个应用来显示帧缓冲。显示的区域被周期性的改变和更新，所以你会看到帧缓冲的不连续的快照，而不是每一个单独的绘画操作。因为这个原因的绘画问题，比如闪烁，知道程序在使用真正的帧缓冲而运行的时候就不会再出现了。

目标刷新速度可以通过View|Refresh Rate菜单项来设置。这将会倒置qvfb更加频繁地检查要被刷新的区域。速度仅仅是一个目标。如果一个小的绘画操作完成了，帧缓冲将不会在绘画事件之间显示任何更新。如果一个应用程序正在显示一个动画，更新将会更频繁，并且应用程序和qvfb将会争夺处理器时间。

鼠标和键盘事件通过命名管道传递给Qt/嵌入式主程序处理。

虚拟帧缓冲只是一个开发工具。在虚拟帧缓冲设计中没有考虑任何安全问题。在产品环境中应该避免这个问题，QT_NO_QWS_VFB在产品库中应该是被定义的。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Running Qt/Embedded applications

A Qt/Embedded application requires a master application to be running or to be a master application itself. The master application is primarily responsible for managing top-level window regions, and pointer and keyboard input.

Any Qt/Embedded application can be a master application by constructing the QApplication object with the QApplication::GuiServer type, or running the application with the -qws command line option.

This document assumes you have the Linux framebuffer configured correctly and no master process is running. If you do not have a working Linux framebuffer you can use the Qt/Embedded virtual framebuffer, or you can run Qt/Embedded as a VNC server.

Change to a Linux console and select an example to run, e.g. examples/widgets. Make sure $QTDIR is set to the directory where you installed Qt/Embedded and add the $QTDIR/lib directory to $LD_LIBRARY_PATH, e.g.:

export QTDIR=$HOME/qt-VERSION
export LD_LIBRARY_PATH=$QTDIR/lib:$LD_LIBRARY_PATH

Run the application with the -qws option:

cd $QTDIR/examples/widgets
./widgets -qws

You should see the widgets example appear. If your mouse doesn't work correctly you need to specify the type of mouse to use. You can exit the master application at any time using Ctrl+Alt+Backspace.

If you wish to run additional applications you should run them as clients i.e. without the -qws option.

Displays

Qt/Embedded allows multiple displays to be used simultaneously by running multiple Qt/Embedded master processes. This is achieved using the -display command line parameter or the $QWS_DISPLAY environment variable.

The -display parameter's syntax is:

    [gfx driver][:driver specific options][:display number]
for example if you want to use the mach64 driver on fb1 as display 2:
    $ ./launcher -display Mach64:/dev/fb1:2

To try this functionality you can do the following:

  1. Change to VC 1 and run the launcher:

        $ cd examples/launcher
    $ ./launcher

  2. Switch to VC 2 and run another one:

        $ cd examples/launcher
    $ ./launcher -display :1

    Another launcher will be started. Start an application in this launcher.

  3. Press Ctrl+Alt+F1 - back to display 0. You can also start additional applications on a particular display by specifying the display id. Change to VC 3:

        $ cd examples/widgets
    $ ./widgets -display :1

    will display the widgets example on dislpay :1 (VC 2).

Only the master process needs to specify the driver/device part explicitly. The clients get the information they need from the master when they connect. So once you have a master server running using a particular driver, you can just use "client -display :n" to use display n.

Mouse Input

At the time of writing Qt/Embedded supports MouseMan (default), Microsoft, IntelliMouse and some other devices specific to certain hardware (e.g. Vr touch panel). To specify the mouse to use set the $QWS_MOUSE_PROTO environment variable, e.g.:

export QWS_MOUSE_PROTO=IntelliMouse

See also Qt/Embedded Pointer Handling.


Qt/Embedded as a VNC Server

The VNC protocol allows you to view and interact with the computer's display from anywhere on the network.

To use Qt/Embedded in this way, configure Qt with the -vnc option, and ensure you also enable 16-bit display support. Run your application via:

    application -display VNC:0
then, run a VNC client pointed at the machine that is running your application. For example, using the X11 VNC client to view the application from the same machine:
    vncviewer localhost:0

By default, Qt/Embedded will create a 640 by 480 pixel display. You can change this by setting the QWS_SIZE environment variable to another size, e.g. QWS_SIZE=240x320.

VNC clients are available for a vast array of display systems - X11, Windows, Amiga, DOS, VMS, and dozens of others.

The Qt Virtual Framebuffer is an alternative technique. It uses shared memory and thus is much faster and smoother, but it does not operate over a network.


Environment Classes

These classes providing various global services to your application such as event handling, access to system settings, internationalization, etc.

QClipboard | Access to the window system clipboard
QDesktopWidget | Access to screen information on multi-head systems
QEvent | The base class of all event classes. Event objects contain event parameters
QFontDatabase | Information about the fonts available in the underlying window system
QMimeSourceFactory | Extensible provider of mime-typed data
QMutex | Access serialization between threads
QPixmapCache | Application-global cache for pixmaps
QSemaphore | Robust integer semaphore
QSessionManager | Access to the session manager
QThread | Platform-independent threads
QTranslator | Internationalization support for text output
QTranslatorMessage | Translator message and its properties
QWaitCondition | Allows waiting/waking for conditions between threads


Event Classes

These classes are used to create and handle events.

For more information see the Object model and Signals and Slots.

QChildEvent | Event parameters for child object events
QCloseEvent | Parameters that describe a close event
QContextMenuEvent | Parameters that describe a context menu event
QCustomEvent | Support for custom events
QDragEnterEvent | Event which is sent to the widget when a drag and drop first drags onto the widget
QDragLeaveEvent | Event which is sent to the widget when a drag and drop leaves the widget
QDragMoveEvent | Event which is sent while a drag and drop is in progress
QDropEvent | Event which is sent when a drag and drop is completed
QEvent | The base class of all event classes. Event objects contain event parameters
QFocusEvent | Event parameters for widget focus events
QHideEvent | Event which is sent after a widget is hidden
QIMEvent | Parameters for input method events
QKeyEvent | Describes a key event
QMouseEvent | Parameters that describe a mouse event
QMoveEvent | Event parameters for move events
QPaintEvent | Event parameters for paint events
QResizeEvent | Event parameters for resize events
QShowEvent | Event which is sent when a widget is shown
QTabletEvent | Parameters that describe a Tablet event
QTimer | Timer signals and single-shot timers
QTimerEvent | Parameters that describe a timer event
QWheelEvent | Parameters that describe a wheel event


Simple Filemanager

This example implements a simple and not fully functional file manager using a widget derived from QIconView to display the current directory. To display the directory tree the widget written in the dirview example is used.

Header file of the file icon view:

/****************************************************************************
** $Id:  qt/qfileiconview.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef QTFILEICONVIEW_H
#define QTFILEICONVIEW_H

#include <qiconset.h>
#include <qstring.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <qtimer.h>
#include <qiconview.h>

class QtFileIconView;
class QDragObject;
class QResizeEvent;

/*****************************************************************************
 *
 * Class QtFileIconDrag
 *
 *****************************************************************************/

class QtFileIconDrag : public QIconDrag
{
    Q_OBJECT

public:
    QtFileIconDrag( QWidget * dragSource, const char* name = 0 );

    const char* format( int i ) const;
    QByteArray encodedData( const char* mime ) const;
    static bool canDecode( QMimeSource* e );
    void append( const QIconDragItem &item, const QRect &pr, const QRect &tr, const QString &url );

private:
    QStringList urls;

};

/*****************************************************************************
 *
 * Class QtFileIconView
 *
 *****************************************************************************/
class QtFileIconViewItem;
class QtFileIconView : public QIconView
{
    Q_OBJECT

public:
    QtFileIconView( const QString &dir, QWidget *parent = 0, const char *name = 0 );

    enum ViewMode { Large, Small };

    void setViewMode( ViewMode m );
    ViewMode viewMode() const { return vm; }
    void setOpenItem( QtFileIconViewItem *i ) {
        openItem = i;
    }

public slots:
    void setDirectory( const QString &dir );
    void setDirectory( const QDir &dir );
    void newDirectory();
    QDir currentDir();

signals:
    void directoryChanged( const QString & );
    void startReadDir( int dirs );
    void readNextDir();
    void readDirDone();
    void enableUp();
    void disableUp();
    void enableMkdir();
    void disableMkdir();

protected slots:
    void itemDoubleClicked( QIconViewItem *i );
    void slotDropped( QDropEvent *e, const QValueList<QIconDragItem> & );

    void viewLarge();
    void viewSmall();
    void viewBottom();
    void viewRight();
    void flowEast();
    void flowSouth();
    void itemTextTruncate();
    void itemTextWordWrap();
    void sortAscending();
    void sortDescending();
    void arrangeItemsInGrid() {
        QIconView::arrangeItemsInGrid( TRUE );
    }

    void slotRightPressed( QIconViewItem *item );
    void openFolder();

protected:
    void readDir( const QDir &dir );
    virtual QDragObject *dragObject();

    virtual void keyPressEvent( QKeyEvent *e );

    QDir viewDir;
    int newFolderNum;
    QSize sz;
    QPixmap pix;
    ViewMode vm;
    QtFileIconViewItem *openItem;

};

/*****************************************************************************
 *
 * Class QtFileIconViewItem
 *
 *****************************************************************************/

class QtFileIconViewItem : public QIconViewItem
{
    friend class QtFileIconView;

public:
    enum ItemType {
        File = 0,
        Dir,
        Link
    };

    QtFileIconViewItem( QtFileIconView *parent, QFileInfo *fi );

    virtual ~QtFileIconViewItem();

    ItemType type() const
    { return itemType; }
    QString filename() const { return itemFileName; }

    virtual bool acceptDrop( const QMimeSource *e ) const;

    virtual void setText( const QString &text );
    virtual QPixmap *pixmap() const;

    virtual void dragEntered();
    virtual void dragLeft();

    void viewModeChanged( QtFileIconView::ViewMode m );
    void paintItem( QPainter *p, const QColorGroup &cg );

protected:
    virtual void dropped( QDropEvent *e, const QValueList<QIconDragItem> & );

    QString itemFileName;
    QFileInfo *itemFileInfo;
    ItemType itemType;
    bool checkSetText;
    QTimer timer;
    QtFileIconView::ViewMode vm;

};

#endif

Implementation of the file icon view:

/****************************************************************************
** $Id:  qt/qfileiconview.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "qfileiconview.h"
#include <qpainter.h>
#include <qstringlist.h>
#include <qpixmap.h>
#include <qmime.h>
#include <qstrlist.h>
#include <qdragobject.h>
#include <qmessagebox.h>
#include <qevent.h>
#include <qpopupmenu.h>
#include <qcursor.h>
#include <qapplication.h>
#include <qwmatrix.h>

#include <stdlib.h>

static const char * file_icon[]={
    "32 32 17 1",
    "# c #000000",
    "a c #ffffff",
    "j c #808080",
    "n c #a0a0a4",
    "g c #c0c0c0",
    "m c #004000",
    "o c #000000",
    "l c #004040",
    "k c #404000",
    "i c #c0c000",
    "h c #ffff00",
    "b c #ffffc0",
    "e c #ff8000",
    "f c #c05800",
    "c c #ffa858",
    "d c #ffdca8",
    ". c None",
    "................................",
    "................................",
    "................................",
    "................................",
    ".............#....###...........",
    "...###......#a##.#aba##.........",
    "..#cdb#....#aaaa#aaaaaa##.......",
    "..#ecdb#..#aaaa#aaaaaaaba##.....",
    "..#fecdb##aaaa#aaaaaaaaaaab##...",
    "...#fecdb#aaa#aaaaaaabaabaaaa##.",
    "....#fecdb#a#baaaaa#baaaaaabaaa#",
    ".....#fecdb#aaaaab#a##baaaaaaa#.",
    ".....##fecdb#bbba#aaaa##baaab#..",
    "....#bb#fecdb#ba#aaaaaaa##aa#...",
    "...#bbbb#fecdb##aaabaaaaaa##....",
    "..#bbbb#b#fecdb#aaaaaaabaaaa##..",
    ".#bbbb#bbb#fecdg#aaaaaaaaaaaba#.",
    "#hhbb#bbbbb#fegg#iiaaaaaaaaaaaa#",
    "#jhhhklibbbk#ggj#aaiiaaaaaaaaa#j",
    ".#mjhhhkmikab####aaabiiaaaaaa#j.",
    "...##jhhhmaaibbaaiibaaaiiaab#n..",
    ".....##j#baaaiiabaaiibaabaa#n...",
    "......##baibaabiibaaaiiabb#j....",
    "......#bbbbiiaabbiiaaaaabon.....",
    ".....#bbbbbbbiiabbaiiaab#n......",
    ".....#jbbbbbbbbiibaabba#n.......",
    "......##jbbbbbbbbiiaabmj........",
    "........##jbbbbbbbbbb#j.........",
    "..........##nbbbbbbbmj..........",
    "............##jbbbb#j...........",
    "..............#mjj#n............",
    "................##n............."};

static const char * folder_icon[]={
    "32 32 11 1",
    "# c #000000",
    "b c #c0c000",
    "d c #585858",
    "a c #ffff00",
    "i c #400000",
    "h c #a0a0a4",
    "e c #000000",
    "c c #ffffff",
    "f c #303030",
    "g c #c0c0c0",
    ". c None",
    "...###..........................",
    "...#aa##........................",
    ".###baaa##......................",
    ".#cde#baaa##....................",
    ".#cccdeebaaa##..##f.............",
    ".#cccccdeebaaa##aaa##...........",
    ".#cccccccdeebaaaaaaaa##.........",
    ".#cccccccccdeebababaaa#.........",
    ".#cccccgcgghhebbbbbbbaa#........",
    ".#ccccccgcgggdebbbbbbba#........",
    ".#cccgcgcgcgghdeebiebbba#.......",
    ".#ccccgcggggggghdeddeeba#.......",
    ".#cgcgcgcggggggggghghdebb#......",
    ".#ccgcggggggggghghghghd#b#......",
    ".#cgcgcggggggggghghghhd#b#......",
    ".#gcggggggggghghghhhhhd#b#......",
    ".#cgcggggggggghghghhhhd#b#......",
    ".#ggggggggghghghhhhhhhdib#......",
    ".#gggggggggghghghhhhhhd#b#......",
    ".#hhggggghghghhhhhhhhhd#b#......",
    ".#ddhhgggghghghhhhhhhhd#b#......",
    "..##ddhhghghhhhhhhhhhhdeb#......",
    "....##ddhhhghhhhhhhhhhd#b#......",
    "......##ddhhhhhhhhhhhhd#b#......",
    "........##ddhhhhhhhhhhd#b#......",
    "..........##ddhhhhhhhhd#b#......",
    "............##ddhhhhhhd#b###....",
    "..............##ddhhhhd#b#####..",
    "................##ddhhd#b######.",
    "..................##dddeb#####..",
    "....................##d#b###....",
    "......................####......"};

static const char * link_icon[]={
    "32 32 12 1",
    "# c #000000",
    "h c #a0a0a4",
    "b c #c00000",
    "d c #585858",
    "i c #400000",
    "c c #ffffff",
    "e c #000000",
    "g c #c0c0c0",
    "a c #ff0000",
    "f c #303030",
    "n c white",
    ". c None",
    "...###..........................",
    "...#aa##........................",
    ".###baaa##......................",
    ".#cde#baaa##....................",
    ".#cccdeebaaa##..##f.............",
    ".#cccccdeebaaa##aaa##...........",
    ".#cccccccdeebaaaaaaaa##.........",
    ".#cccccccccdeebababaaa#.........",
    ".#cccccgcgghhebbbbbbbaa#........",
    ".#ccccccgcgggdebbbbbbba#........",
    ".#cccgcgcgcgghdeebiebbba#.......",
    ".#ccccgcggggggghdeddeeba#.......",
    ".#cgcgcgcggggggggghghdebb#......",
    ".#ccgcggggggggghghghghd#b#......",
    ".#cgcgcggggggggghghghhd#b#......",
    ".#gcggggggggghghghhhhhd#b#......",
    ".#cgcggggggggghghghhhhd#b#......",
    ".#ggggggggghghghhhhhhhdib#......",
    ".#gggggggggghghghhhhhhd#b#......",
    ".#hhggggghghghhhhhhhhhd#b#......",
    ".#ddhhgggghghghhhhhhhhd#b#......",
    "..##ddhhghghhhhhhhhhhhdeb#......",
    "############hhhhhhhhhhd#b#......",
    "#nnnnnnnnnn#hhhhhhhhhhd#b#......",
    "#nnnnnnnnnn#hhhhhhhhhhd#b#......",
    "#nn#nn#nnnn#ddhhhhhhhhd#b#......",
    "#nn##n##nnn###ddhhhhhhd#b###....",
    "#nnn#####nn#..##ddhhhhd#b#####..",
    "#nnnnn##nnn#....##ddhhd#b######.",
    "#nnnnn#nnnn#......##dddeb#####..",
    "#nnnnnnnnnn#........##d#b###....",
    "############..........####......"};

static const char * folder_locked_icon[]={
    "32 32 12 1",
    "# c #000000",
    "g c #808080",
    "h c #c0c0c0",
    "f c #c05800",
    "c c #ffffff",
    "d c #585858",
    "b c #ffa858",
    "a c #ffdca8",
    "e c #000000",
    "i c #a0a0a4",
    "j c #c0c0c0",
    ". c None",
    "...###..........................",
    "...#aa##........................",
    ".###baaa##......................",
    ".#cde#baaa##....................",
    ".#cccdeeba#######...............",
    ".#cccccde##fffff##..............",
    ".#cccccc##fffgggg#..............",
    ".#ccccccc#ffg####a##............",
    ".#ccccchc#ffg#eebbaa##..........",
    ".#ccccccc#ffg#ddeebbba##........",
    ".#ccchccc#ffg#ihddeebbba##......",
    ".#cccccaa#ffg#ihhhddeeba##......",
    ".#chchhbbaafg#ihhhihidebb#......",
    ".#cchccbbbbaa#ihhihihid#b#......",
    ".#chchhbb#bbbaaiihihiid#b#......",
    ".#hchhcbb#fbbbafhiiiiid#b#......",
    ".#chchhbb#ffgbbfihiiiid#b#......",
    ".#hhhhhbb#ffg#bfiiiiiid#b#......",
    ".#hhhhhbbaffg#bfiiiiiid#b#......",
    ".#iihhhjbbaab#bfiiiiiid#b#......",
    ".#ddiihhh#bbbabfiiiiiid#b#......",
    "..##ddiih#ffbbbfiiiiiid#b#......",
    "....##ddi#ffg#biiiiiiid#b#......",
    "......##d#ffg#iiiiiiiid#b#......",
    "........##ffg#iiiiiiiid#b#......",
    ".........#ffg#iiiiiiiid#b#......",
    ".........#ffg#ddiiiiiid#b###....",
    ".........##fg###ddiiiid#b#####..",
    "...........####.##ddiid#b######.",
    "..................##dddeb#####..",
    "....................##d#b###....",
    "......................####......"};

static QPixmap *iconFolderLockedLarge = 0;
static QPixmap *iconFolderLarge = 0;
static QPixmap *iconFileLarge = 0;
static QPixmap *iconLinkLarge = 0;
static QPixmap *iconFolderLockedSmall = 0;
static QPixmap *iconFolderSmall = 0;
static QPixmap *iconFileSmall = 0;
static QPixmap *iconLinkSmall = 0;

static void cleanup()
{
    delete iconFolderLockedLarge;
    iconFolderLockedLarge = 0;
    delete iconFolderLarge;
    iconFolderLarge = 0;
    delete iconFileLarge;
    iconFileLarge = 0;
    delete iconLinkLarge;
    iconLinkLarge = 0;
    delete iconFolderLockedSmall;
    iconFolderLockedSmall = 0;
    delete iconFolderSmall;
    iconFolderSmall = 0;
    delete iconFileSmall;
    iconFileSmall = 0;
    delete iconLinkSmall;
    iconLinkSmall = 0;
}

/*****************************************************************************
 *
 * Class QtFileIconDrag
 *
 *****************************************************************************/

QtFileIconDrag::QtFileIconDrag( QWidget * dragSource, const char* name )
    : QIconDrag( dragSource, name )
{
}

const char* QtFileIconDrag::format( int i ) const
{
    if ( i == 0 )
        return "application/x-qiconlist";
    else if ( i == 1 )
        return "text/uri-list";
    else
        return 0;
}

QByteArray QtFileIconDrag::encodedData( const char* mime ) const
{
    QByteArray a;
    if ( QString( mime ) == "application/x-qiconlist" ) {
        a = QIconDrag::encodedData( mime );
    } else if ( QString( mime ) == "text/uri-list" ) {
        QString s = urls.join( "\r\n" );
        a.resize( s.length() );
        memcpy( a.data(), s.latin1(), s.length() );
    }
    return a;
}

bool QtFileIconDrag::canDecode( QMimeSource* e )
{
    return e->provides( "application/x-qiconlist" ) ||
        e->provides( "text/uri-list" );
}

void QtFileIconDrag::append( const QIconDragItem &item, const QRect &pr,
                             const QRect &tr, const QString &url )
{
    QIconDrag::append( item, pr, tr );
    urls << url;
}

/*****************************************************************************
 *
 * Class QtFileIconViewItem
 *
 *****************************************************************************/

QtFileIconViewItem::QtFileIconViewItem( QtFileIconView *parent, QFileInfo *fi )
    : QIconViewItem( parent, fi->fileName() ), itemFileName( fi->filePath() ),
      itemFileInfo( fi ), checkSetText( FALSE )
{
    vm = QtFileIconView::Large;

    if ( itemFileInfo->isDir() )
        itemType = Dir;
    else if ( itemFileInfo->isFile() )
        itemType = File;
    if ( itemFileInfo->isSymLink() )
        itemType = Link;

    viewModeChanged( ( (QtFileIconView*)iconView() )->viewMode() );

    if ( itemFileInfo->fileName() == "." ||
         itemFileInfo->fileName() == ".." )
        setRenameEnabled( FALSE );

    checkSetText = TRUE;

    QObject::connect( &timer, SIGNAL( timeout() ),
                      iconView(), SLOT( openFolder() ) );
}

void QtFileIconViewItem::paintItem( QPainter *p, const QColorGroup &cg )
{
    if ( itemFileInfo->isSymLink() ) {
        QFont f( p->font() );
        f.setItalic( TRUE );
        p->setFont( f );
    }

    QIconViewItem::paintItem( p, cg );
}

void QtFileIconViewItem::viewModeChanged( QtFileIconView::ViewMode m )
{
    vm = m;
    setDropEnabled( itemType == Dir && QDir( itemFileName ).isReadable() );
    calcRect();
}

QPixmap *QtFileIconViewItem::pixmap() const
{
    switch ( itemType ) {
    case Dir:
        {
            if ( !QDir( itemFileName ).isReadable() ) {
                if ( vm == QtFileIconView::Small )
                    return iconFolderLockedSmall;
                else
                    return iconFolderLockedLarge;
            } else {
                if ( vm == QtFileIconView::Small )
                    return iconFolderSmall;
                else
                    return iconFolderLarge;
            }
        }
    case Link:
        {
            if ( vm == QtFileIconView::Small )
                return iconLinkSmall;
            else
                return iconLinkLarge;
        }
    default:
        {
            if ( vm == QtFileIconView::Small )
                return iconFileSmall;
            else
                return iconFileLarge;
        }
    }
}

QtFileIconViewItem::~QtFileIconViewItem()
{
    delete itemFileInfo;
}

void QtFileIconViewItem::setText( const QString &text )
{
    if ( checkSetText ) {
        if ( text == "." || text == "." || text.isEmpty() )
            return;
        QDir dir( itemFileInfo->dir() );
        if ( dir.rename( itemFileInfo->fileName(), text ) ) {
            itemFileName = itemFileInfo->dirPath( TRUE ) + "/" + text;
            delete itemFileInfo;
            itemFileInfo = new QFileInfo( itemFileName );
            QIconViewItem::setText( text );
        }
    } else {
        QIconViewItem::setText( text );
    }
}

bool QtFileIconViewItem::acceptDrop( const QMimeSource *e ) const
{
    if ( type() == Dir && e->provides( "text/uri-list" ) &&
         dropEnabled() )
        return TRUE;

    return FALSE;
}

void QtFileIconViewItem::dropped( QDropEvent *e, const QValueList<QIconDragItem> & )
{
    timer.stop();

    if ( !QUriDrag::canDecode( e ) ) {
        e->ignore();
        return;
    }

    QStrList lst;
    QUriDrag::decode( e, lst );

    QString str;
    if ( e->action() == QDropEvent::Copy )
        str = "Copy\n\n";
    else
        str = "Move\n\n";
    for ( uint i = 0; i < lst.count(); ++i )
        str += QString( "   %1\n" ).arg( lst.at( i ) );
    str += QString( "\n"
                    "To\n\n"
                    "   %1" ).arg( filename() );

    QMessageBox::information( iconView(), e->action() == QDropEvent::Copy ? "Copy" : "Move" , str, "Not Implemented" );
    if ( e->action() == QDropEvent::Move )
        QMessageBox::information( iconView(), "Remove" , str, "Not Implemented" );
    e->acceptAction();
}

void QtFileIconViewItem::dragEntered()
{
    if ( type() != Dir ||
         type() == Dir && !QDir( itemFileName ).isReadable() )
        return;

    ( (QtFileIconView*)iconView() )->setOpenItem( this );
    timer.start( 1500 );
}

void QtFileIconViewItem::dragLeft()
{
    if ( type() != Dir ||
         type() == Dir && !QDir( itemFileName ).isReadable() )
        return;

    timer.stop();
}

/*****************************************************************************
 *
 * Class QtFileIconView
 *
 *****************************************************************************/

QtFileIconView::QtFileIconView( const QString &dir, QWidget *parent, const char *name )
    : QIconView( parent, name ), viewDir( dir ), newFolderNum( 0 )
{
    if ( !iconFolderLockedLarge ) {
        qAddPostRoutine( cleanup );
        QWMatrix m;
        m.scale( 0.6, 0.6 );
        QPixmap iconpix( folder_locked_icon );
        iconFolderLockedLarge = new QPixmap( folder_locked_icon );
        iconpix = iconpix.xForm( m );
        iconFolderLockedSmall = new QPixmap( iconpix );
        iconpix = QPixmap( folder_icon );
        iconFolderLarge = new QPixmap( folder_icon );
        iconpix = iconpix.xForm( m );
        iconFolderSmall = new QPixmap( iconpix );
        iconpix = QPixmap( file_icon );
        iconFileLarge = new QPixmap( file_icon );
        iconpix = iconpix.xForm( m );
        iconFileSmall = new QPixmap( iconpix );
        iconpix = QPixmap( link_icon );
        iconLinkLarge = new QPixmap( link_icon );
        iconpix = iconpix.xForm( m );
        iconLinkSmall = new QPixmap( iconpix );
    }

    vm = Large;

    setGridX( 75 );
    setResizeMode( Adjust );
    setWordWrapIconText( FALSE );

    connect( this, SIGNAL( doubleClicked( QIconViewItem * ) ),
             this, SLOT( itemDoubleClicked( QIconViewItem * ) ) );
    connect( this, SIGNAL( returnPressed( QIconViewItem * ) ),
             this, SLOT( itemDoubleClicked( QIconViewItem * ) ) );
    connect( this, SIGNAL( dropped( QDropEvent *, const QValueList<QIconDragItem> & ) ),
             this, SLOT( slotDropped( QDropEvent *, const QValueList<QIconDragItem> & ) ) );
    connect( this, SIGNAL( contextMenuRequested( QIconViewItem *, const QPoint & ) ),
             this, SLOT( slotRightPressed( QIconViewItem * ) ) );

    setHScrollBarMode( AlwaysOff );
    setVScrollBarMode( Auto );

    setAutoArrange( TRUE );
    setSorting( TRUE );
    openItem = 0;
}

void QtFileIconView::openFolder()
{
    if ( !openItem )
        return;
    if ( openItem->type() != QtFileIconViewItem::Dir ||
         openItem->type() == QtFileIconViewItem::Dir &&
         !QDir( openItem->itemFileName ).isReadable() )
        return;

    openItem->timer.stop();
    setDirectory( openItem->itemFileName );
}

void QtFileIconView::setDirectory( const QString &dir )
{
    viewDir = QDir( dir );
    readDir( viewDir );
}

void QtFileIconView::setDirectory( const QDir &dir )
{
    viewDir = dir;
    readDir( viewDir );
}

void QtFileIconView::newDirectory()
{
    setAutoArrange( FALSE );
    selectAll( FALSE );
    if ( viewDir.mkdir( QString( "New Folder %1" ).arg( ++newFolderNum ) ) ) {
        QFileInfo *fi = new QFileInfo( viewDir, QString( "New Folder %1" ).arg( newFolderNum ) );
        QtFileIconViewItem *item = new QtFileIconViewItem( this, new QFileInfo( *fi ) );
        item->setKey( QString( "000000%1" ).arg( fi->fileName() ) );
        delete fi;
        repaintContents( contentsX(), contentsY(), contentsWidth(), contentsHeight(), FALSE );
        ensureItemVisible( item );
        item->setSelected( TRUE, TRUE );
        setCurrentItem( item );
        repaintItem( item );
        qApp->processEvents();
        item->rename();
    }
    setAutoArrange( TRUE );
}

QDir QtFileIconView::currentDir()
{
    return viewDir;
}

static bool isRoot( const QString &s )
{
#if defined(Q_OS_UNIX)
    if ( s == "/" )
        return TRUE;
#elif defined(Q_OS_WIN32)
    QString p = s;
    if ( p.length() == 3 &&
         p.right( 2 ) == ":/" )
        return TRUE;
    if ( p[ 0 ] == '/' && p[ 1 ] == '/' ) {
        int slashes = p.contains( '/' );
        if ( slashes <= 3 )
            return TRUE;
        if ( slashes == 4 && p[ (int)p.length() - 1 ] == '/' )
            return TRUE;
    }
#endif

    return FALSE;
}

void QtFileIconView::readDir( const QDir &dir )
{
    if ( !dir.isReadable() )
        return;

    if ( isRoot( dir.absPath() ) )
        emit disableUp();
    else
        emit enableUp();

    clear();

    emit directoryChanged( dir.absPath() );

    const QFileInfoList *filist = dir.entryInfoList( QDir::DefaultFilter, QDir::DirsFirst | QDir::Name );

    emit startReadDir( filist->count() );

    QFileInfoListIterator it( *filist );
    QFileInfo *fi;
    bool allowRename = FALSE, allowRenameSet = FALSE;
    while ( ( fi = it.current() ) != 0 ) {
        ++it;
        if ( fi && fi->fileName() == ".." && ( fi->dirPath() == "/" || fi->dirPath().isEmpty() ) )
            continue;
        emit readNextDir();
        QtFileIconViewItem *item = new QtFileIconViewItem( this, new QFileInfo( *fi ) );
        if ( fi->isDir() )
            item->setKey( QString( "000000%1" ).arg( fi->fileName() ) );
        else
            item->setKey( fi->fileName() );
        if ( !allowRenameSet ) {
            if ( !QFileInfo( fi->absFilePath() ).isWritable() ||
                 item->text() == "." || item->text() == ".." )
                allowRename = FALSE;
            else
                allowRename = TRUE;
            if ( item->text() == "." || item->text() == ".." )
                allowRenameSet = FALSE;
            else
                allowRenameSet = TRUE;
        }
        item->setRenameEnabled( allowRename );
    }

    if ( !QFileInfo( dir.absPath() ).isWritable() )
        emit disableMkdir();
    else
        emit enableMkdir();

    emit readDirDone();
}

void QtFileIconView::itemDoubleClicked( QIconViewItem *i )
{
    QtFileIconViewItem *item = ( QtFileIconViewItem* )i;

    if ( item->type() == QtFileIconViewItem::Dir ) {
        viewDir = QDir( item->filename() );
        readDir( viewDir );
    } else if ( item->type() == QtFileIconViewItem::Link &&
                QFileInfo( QFileInfo( item->filename() ).readLink() ).isDir() ) {
        viewDir = QDir( QFileInfo( item->filename() ).readLink() );
        readDir( viewDir );
    }
}

QDragObject *QtFileIconView::dragObject()
{
    if ( !currentItem() )
        return 0;

    QPoint orig = viewportToContents( viewport()->mapFromGlobal( QCursor::pos() ) );
    QtFileIconDrag *drag = new QtFileIconDrag( viewport() );
    drag->setPixmap( *currentItem()->pixmap(),
                     QPoint( currentItem()->pixmapRect().width() / 2, currentItem()->pixmapRect().height() / 2 ) );
    for ( QtFileIconViewItem *item = (QtFileIconViewItem*)firstItem(); item;
          item = (QtFileIconViewItem*)item->nextItem() ) {
        if ( item->isSelected() ) {
            QIconDragItem id;
            id.setData( QCString( item->filename() ) );
            drag->append( id,
                          QRect( item->pixmapRect( FALSE ).x() - orig.x(),
                                 item->pixmapRect( FALSE ).y() - orig.y(),
                                 item->pixmapRect().width(), item->pixmapRect().height() ),
                          QRect( item->textRect( FALSE ).x() - orig.x(),
                                 item->textRect( FALSE ).y() - orig.y(),
                                 item->textRect().width(), item->textRect().height() ),
                          QString( item->filename() ) );
        }
    }

    return drag;
}

void QtFileIconView::keyPressEvent( QKeyEvent *e )
{
    if ( e->key() == Key_N &&
         ( e->state() & ControlButton ) )
        newDirectory();
    else
        QIconView::keyPressEvent( e );
}

void QtFileIconView::slotDropped( QDropEvent *e, const QValueList<QIconDragItem> & )
{
    if ( openItem )
        openItem->timer.stop();
    if ( !QUriDrag::canDecode( e ) ) {
        e->ignore();
        return;
    }

    QStrList lst;
    QUriDrag::decode( e, lst );

    QString str;
    if ( e->action() == QDropEvent::Copy )
        str = "Copy\n\n";
    else
        str = "Move\n\n";
    for ( uint i = 0; i < lst.count(); ++i )
        str += QString( "   %1\n" ).arg( lst.at( i ) );
    str += QString( "\n"
                    "To\n\n"
                    "   %1" ).arg( viewDir.absPath() );

    QMessageBox::information( this, e->action() == QDropEvent::Copy ? "Copy" : "Move" , str, "Not Implemented" );
    if ( e->action() == QDropEvent::Move )
        QMessageBox::information( this, "Remove" , str, "Not Implemented" );
    e->acceptAction();
    openItem = 0;
}

void QtFileIconView::viewLarge()
{
    setViewMode( Large );
}

void QtFileIconView::viewSmall()
{
    setViewMode( Small );
}

void QtFileIconView::viewBottom()
{
    setItemTextPos( Bottom );
}

void QtFileIconView::viewRight()
{
    setItemTextPos( Right );
}

void QtFileIconView::flowEast()
{
    setHScrollBarMode( AlwaysOff );
    setVScrollBarMode( Auto );
    setArrangement( LeftToRight );
}

void QtFileIconView::flowSouth()
{
    setVScrollBarMode( AlwaysOff );
    setHScrollBarMode( Auto );
    setArrangement( TopToBottom );
}

void QtFileIconView::sortAscending()
{
    sort( TRUE );
}

void QtFileIconView::sortDescending()
{
    sort( FALSE );
}

void QtFileIconView::itemTextTruncate()
{
    setWordWrapIconText( FALSE );
}

void QtFileIconView::itemTextWordWrap()
{
    setWordWrapIconText( TRUE );
}

void QtFileIconView::slotRightPressed( QIconViewItem *item )
{
    if ( !item ) { // right pressed on viewport
        QPopupMenu menu( this );

        menu.insertItem( "&Large view", this, SLOT( viewLarge() ) );
        menu.insertItem( "&Small view", this, SLOT( viewSmall() ) );
        menu.insertSeparator();
        menu.insertItem( "Text at the &bottom", this, SLOT( viewBottom() ) );
        menu.insertItem( "Text at the &right", this, SLOT( viewRight() ) );
        menu.insertSeparator();
        menu.insertItem( "Arrange l&eft to right", this, SLOT( flowEast() ) );
        menu.insertItem( "Arrange t&op to bottom", this, SLOT( flowSouth() ) );
        menu.insertSeparator();
        menu.insertItem( "&Truncate item text", this, SLOT( itemTextTruncate() ) );
        menu.insertItem( "&Wordwrap item text", this, SLOT( itemTextWordWrap() ) );
        menu.insertSeparator();
        menu.insertItem( "Arrange items in &grid", this, SLOT( arrangeItemsInGrid() ) );
        menu.insertSeparator();
        menu.insertItem( "Sort &ascending", this, SLOT( sortAscending() ) );
        menu.insertItem( "Sort &descending", this, SLOT( sortDescending() ) );

        menu.setMouseTracking( TRUE );
        menu.exec( QCursor::pos() );
    } else { // on item
        QPopupMenu menu( this );

        int RENAME_ITEM = menu.insertItem( "Rename Item" );
        int REMOVE_ITEM = menu.insertItem( "Remove Item" );

        menu.setMouseTracking( TRUE );
        int id = menu.exec( QCursor::pos() );

        if ( id == -1 )
            return;

        if ( id == RENAME_ITEM && item->renameEnabled() ) {
            item->rename();
        } else if ( id == REMOVE_ITEM ) {
            delete item;
            QMessageBox::information( this, "Not implemented!", "Deleting files not implemented yet,\n"
                                      "The item has only been removed from the view! " );
        }
    }
}

void QtFileIconView::setViewMode( ViewMode m )
{
    if ( m == vm )
        return;

    vm = m;
    QtFileIconViewItem *item = (QtFileIconViewItem*)firstItem();
    for ( ; item; item = (QtFileIconViewItem*)item->nextItem() )
        item->viewModeChanged( vm );

    arrangeItemsInGrid();
}

Header file of the main window:

/****************************************************************************
** $Id:  qt/mainwindow.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef MAINWIN_H
#define MAINWIN_H

#include <qmainwindow.h>

class QtFileIconView;
class DirectoryView;
class QProgressBar;
class QLabel;
class QComboBox;
class QToolButton;

class FileMainWindow : public QMainWindow
{
    Q_OBJECT

public:
    FileMainWindow();

    QtFileIconView *fileView() { return fileview; }
    DirectoryView *dirList() { return dirlist; }

    void show();

protected:
    void setup();
    void setPathCombo();

    QtFileIconView *fileview;
    DirectoryView *dirlist;
    QProgressBar *progress;
    QLabel *label;
    QComboBox *pathCombo;
    QToolButton *upButton, *mkdirButton;

protected slots:
    void directoryChanged( const QString & );
    void slotStartReadDir( int dirs );
    void slotReadNextDir();
    void slotReadDirDone();
    void cdUp();
    void newFolder();
    void changePath( const QString &path );
    void enableUp();
    void disableUp();
    void enableMkdir();
    void disableMkdir();

};

#endif

Implementation of the main window:

/****************************************************************************
** $Id:  qt/mainwindow.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "mainwindow.h"
#include "qfileiconview.h"
#include "../dirview/dirview.h"

#include <qsplitter.h>
#include <qprogressbar.h>
#include <qlabel.h>
#include <qstatusbar.h>
#include <qtoolbar.h>
#include <qcombobox.h>
#include <qpixmap.h>
#include <qtoolbutton.h>
#include <qdir.h>
#include <qfileinfo.h>

static const char* cdtoparent_xpm[]={
    "15 13 3 1",
    ". c None",
    "* c #000000",
    "a c #ffff99",
    "..*****........",
    ".*aaaaa*.......",
    "***************",
    "*aaaaaaaaaaaaa*",
    "*aaaa*aaaaaaaa*",
    "*aaa***aaaaaaa*",
    "*aa*****aaaaaa*",
    "*aaaa*aaaaaaaa*",
    "*aaaa*aaaaaaaa*",
    "*aaaa******aaa*",
    "*aaaaaaaaaaaaa*",
    "*aaaaaaaaaaaaa*",
    "***************"};

static const char* newfolder_xpm[] = {
    "15 14 4 1",
    "   c None",
    ".  c #000000",
    "+  c #FFFF00",
    "@  c #FFFFFF",
    "          .    ",
    "               ",
    "          .    ",
    "       .     . ",
    "  ....  . . .  ",
    " .+@+@.  . .   ",
    "..........  . .",
    ".@+@+@+@+@..   ",
    ".+@+@+@+@+. .  ",
    ".@+@+@+@+@.  . ",
    ".+@+@+@+@+.    ",
    ".@+@+@+@+@.    ",
    ".+@+@+@+@+.    ",
    "...........    "};

FileMainWindow::FileMainWindow()
    : QMainWindow()
{
    setup();
}

void FileMainWindow::show()
{
    QMainWindow::show();
}

void FileMainWindow::setup()
{
    QSplitter *splitter = new QSplitter( this );

    dirlist = new DirectoryView( splitter, "dirlist", TRUE );
    dirlist->addColumn( "Name" );
    dirlist->addColumn( "Type" );
    Directory *root = new Directory( dirlist, "/" );
    root->setOpen( TRUE );
    splitter->setResizeMode( dirlist, QSplitter::KeepSize );

    fileview = new QtFileIconView( "/", splitter );
    fileview->setSelectionMode( QIconView::Extended );

    setCentralWidget( splitter );

    QToolBar *toolbar = new QToolBar( this, "toolbar" );
    setRightJustification( TRUE );

    (void)new QLabel( tr( " Path: " ), toolbar );

    pathCombo = new QComboBox( TRUE, toolbar );
    pathCombo->setAutoCompletion( TRUE );
    toolbar->setStretchableWidget( pathCombo );
    connect( pathCombo, SIGNAL( activated( const QString & ) ),
             this, SLOT ( changePath( const QString & ) ) );

    toolbar->addSeparator();

    QPixmap pix;

    pix = QPixmap( cdtoparent_xpm );
    upButton = new QToolButton( pix, "One directory up", QString::null,
                                this, SLOT( cdUp() ), toolbar, "cd up" );

    pix = QPixmap( newfolder_xpm );
    mkdirButton = new QToolButton( pix, "New Folder", QString::null,
                                   this, SLOT( newFolder() ), toolbar, "new folder" );

    connect( dirlist, SIGNAL( folderSelected( const QString & ) ),
             fileview, SLOT ( setDirectory( const QString & ) ) );
    connect( fileview, SIGNAL( directoryChanged( const QString & ) ),
             this, SLOT( directoryChanged( const QString & ) ) );
    connect( fileview, SIGNAL( startReadDir( int ) ),
             this, SLOT( slotStartReadDir( int ) ) );
    connect( fileview, SIGNAL( readNextDir() ),
             this, SLOT( slotReadNextDir() ) );
    connect( fileview, SIGNAL( readDirDone() ),
             this, SLOT( slotReadDirDone() ) );

    setDockEnabled( DockLeft, FALSE );
    setDockEnabled( DockRight, FALSE );

    label = new QLabel( statusBar() );
    statusBar()->addWidget( label, 2, TRUE );
    progress = new QProgressBar( statusBar() );
    statusBar()->addWidget( progress, 1, TRUE );

    connect( fileview, SIGNAL( enableUp() ),
             this, SLOT( enableUp() ) );
    connect( fileview, SIGNAL( disableUp() ),
             this, SLOT( disableUp() ) );
    connect( fileview, SIGNAL( enableMkdir() ),
             this, SLOT( enableMkdir() ) );
    connect( fileview, SIGNAL( disableMkdir() ),
             this, SLOT( disableMkdir() ) );
}

void FileMainWindow::setPathCombo()
{
    QString dir = caption();
    int i = 0;
    bool found = FALSE;
    for ( i = 0; i < pathCombo->count(); ++i ) {
        if ( pathCombo->text( i ) == dir) {
            found = TRUE;
            break;
        }
    }

    if ( found )
        pathCombo->setCurrentItem( i );
    else {
        pathCombo->insertItem( dir );
        pathCombo->setCurrentItem( pathCombo->count() - 1 );
    }

}

void FileMainWindow::directoryChanged( const QString &dir )
{
    setCaption( dir );
    setPathCombo();
}

void FileMainWindow::slotStartReadDir( int dirs )
{
    label->setText( tr( " Reading Directory..." ) );
    progress->reset();
    progress->setTotalSteps( dirs );
}

void FileMainWindow::slotReadNextDir()
{
    int p = progress->progress();
    progress->setProgress( ++p );
}

void FileMainWindow::slotReadDirDone()
{
    label->setText( tr( " Reading Directory Done." ) );
    progress->setProgress( progress->totalSteps() );
}

void FileMainWindow::cdUp()
{
    QDir dir = fileview->currentDir();
    dir.cd( ".." );
    fileview->setDirectory( dir );
}

void FileMainWindow::newFolder()
{
    fileview->newDirectory();
}

void FileMainWindow::changePath( const QString &path )
{
    if ( QFileInfo( path ).exists() )
        fileview->setDirectory( path );
    else
        setPathCombo();
}

void FileMainWindow::enableUp()
{
    upButton->setEnabled( TRUE );
}

void FileMainWindow::disableUp()
{
    upButton->setEnabled( FALSE );
}

void FileMainWindow::enableMkdir()
{
    mkdirButton->setEnabled( TRUE );
}

void FileMainWindow::disableMkdir()
{
    mkdirButton->setEnabled( FALSE );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "mainwindow.h"
#include "qfileiconview.h"

#include <qapplication.h>

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

    FileMainWindow mw;
    mw.resize( 680, 480 );
    a.setMainWidget( &mw );
    mw.fileView()->setDirectory( "/" );
    mw.show();
    return a.exec();
}

See also Examples.


键盘焦点概述

Qt的窗口部件使用图形用户界面中已经非常通用的方式来处理键盘焦点。

基本观点是用户的击键会定向到屏幕上的窗口中，和计划中的窗口的窗口部件中。当用户按下一个键，他们希望它能够到达正确的位置，并且软件必须尽量满足这种希望。系统必须决定哪一个应用程序、应用程序中的哪一个窗口和窗口中的哪一个窗口部件被击键，

焦点移动

为了把焦点移到特殊的窗口部件的已经解决的方式有：

  1. 用户按下Tab键（或者Shift键+Tab键）（或者有时是Enter键）。

  2. 用户点击一个窗口部件。

  3. 用户按下一个键盘快捷键。

  4. 用户使用鼠标滚轮。

  5. 用户移动焦点到一个窗口，并且应用程序可以决定窗口中的哪个窗口部件应该得到焦点。

每一个移动机制都是不同的，并且不同类型的窗口部件只接收它们中的一些。我们将逐个介绍它们中的每一个。

Tab或者Shift+Tab.

按Tab键是到目前为止使用键盘来移动焦点的最普通的方法。有时在输入数据的应用程序中Enter键和Tab键的作用是一样的。我们暂时忽略这一点。

按Tab键，是今天所有窗口系统中的普通使用方法，把键盘焦点移到一个每个窗口中的循环列表中的下一个窗口部件。Tab键按照循环列表的顺序的一个方向移动，Shift键+Tab键是另一个方向。使用按Tab键从一个窗口部件到下一个窗口部件移动焦点的顺序叫做Tab键控制次序。

在Qt中，这个列表存放在QFocusData列表中。在每一个窗口中都有一个QFocusData对象，并且当QWidget::setFocusPolicy()使用适当的QWidget::FocusPolicy被调用的时候，窗口部件自动把它们自己添加到列表的最后。你可以使用QWidget::setTabOrder()来自定义Tab键控制次序。（如果你没有自定义，那么Tab键会按照窗口部件构造的顺序移动焦点。）Qt设计器提供了一个可视化的改变Tab键控制次序的方法。

因为按Tab键是如此的普通，绝大多数含有焦点的窗口部件都应该支持Tab焦点。主要的例外情况是一些很少使用的窗口部件，和一些使用一些键盘快捷键或者错误处理来移动焦点的窗口部件。

举个例子，在一个数据输入对话框中，也许一个字段只有在百分之一的情况下是必须的。在这样的一个对话框中，Tab键可能忽略这个区域，并且对话框可以使用下面的机制之一：

  1. 如果程序能够决定哪个字段是需要的，它可以当用户完成输入并且按下OK时，或者当用户在完成其它字段后按下Enter键时，移动焦点到那里。另一种方法是，把这个字段包含到Tab键控制次序中，但使这个字段失效。然后当用户在其它字段中输入后的适当条件下，再使它生效。

  2. 这个字段的标签可以包含一个可以使焦点移动到这个字段的键盘快捷键。

还有一种对Tab键支持的例外情况是那些必须支持Tab键的文本输入窗口部件，几乎所有的文本编辑器都属于这一类。Qt把Control键+Tab键作为Tab键来对待，把Control键+Shift键+Tab键作为Shift键+Tab键来对待，并且这样的窗口部件都重新实现了QWidget::event()并且在调用QWidget::event()获得对于所有其它键的处理之前处理Tab键。无论如何，因为一些系统中把Control键+Tab键用于其它用途，并且一些用户无论如何也不知道Control键+Tab键这种方法，所以这不是一个完全的解决方案。

用户点击一个窗口部件。

在使用鼠标或者其它指示器的计算机中，这可能是一种比按Tab键更普通的方法。

点击来移动焦点比Tab键稍微强大一些。当它把焦点移到一个窗口部件时，对于编辑器窗口部件，它也会移动文本光标（窗口部件的内部焦点）到鼠标被点击的点。

因为它是如此的普通，绝大多数窗口部件都支持它是一个不错的主意。人们已经很习惯使用它了。无论如何，还有一个重要的原因要避免它：你可能不想从它所在地窗口部件中移去焦点。

举个例子，在一个字处理程序中，当用户点击“B”（粗体）工具按钮，键盘焦点会发生什么呢？应该保留它原来的位置，几乎所有的编辑器窗口部件都是这样的，或者把焦点移到“B”按钮？

我们建议支持文本输入的窗口部件支持点击到焦点，并且为了避免它对于绝大多数窗口部件中的鼠标点击有一个不同的效果。（对于按钮，我们也推荐加入键盘快捷键－QButton和它的子类都使这个变得很容易。）

在Qt中，只有QWidget::setFocusPolicy()函数影响点击到焦点。

用户按下一个键盘快捷键。

使用键盘快捷键来移动焦点不是很常用。这种情况可能会隐含地发生在打开的模式对话框中，但是也会明显地使用键盘焦点，比如在QLabel::setBuddy()、QGroupBox和QTabBar。

我们建议用户如果想在窗口部件中实现跳最好支持快捷键焦点。举个例子，一个Tab对话框为它的每一个页提供键盘快捷键，所以用户可以按下比如Alt+P来跳到打印（P）页面。但不要做得太过分－只需要少量的快捷键，并且为命令提供键盘快捷键也是很重要的。举个例子，Alt+P也可以用来粘贴、播放、打印和打印这里，请参考标准快捷键列表。

用户使用鼠标滚轮。

在Microsoft Windows上，鼠标滚轮的用法是一直由有键盘焦点的窗口部件处理。在Mac OS X和X11上，它是由可以获得其它鼠标事件的窗口部件处理。

Qt处理这种与平台相关的方法是当滚轮被用到的时候，让窗口部件移动键盘焦点。每个窗口部件上使用正确的焦点策略，应用程序就可以在Windows、Mac OS X和X11上按照习惯正确地工作了。

用户移动焦点到这个窗口。

在这种情况下，应用程序不得不决定窗口中的哪一个窗口部件应该接收焦点。

这样也许会简单些：如果以前焦点在这个窗口中，那么上次获得焦点的最后一个窗口部件将会重新得到它。Qt自动地就是这样做的。

如果以前焦点就从来没有来到过这个窗口，并且你知道焦点应该从哪里开始，就在你调用QWidget::show()显示它之前，在这个接收焦点的窗口部件上调用QWidget::setFocus()。如果你不知道，Qt也许会选择一些合适的窗口部件。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


A Rectangle Draw "Benchmark"

This example continuously draws rectangles in a window and has another widget that counts the number of rectangles that are drawn per second.

Header file:

/****************************************************************************
** $Id:  qt/forever.h   3.0.5   edited Oct 12 2001 $
**
** Definition of something or other
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef FOREVER_H
#define FOREVER_H

#include <qwidget.h>

const int numColors = 120;

class Forever : public QWidget
{
    Q_OBJECT
public:
    Forever( QWidget *parent=0, const char *name=0 );
protected:
    void        paintEvent( QPaintEvent * );
    void        timerEvent( QTimerEvent * );
private slots:
    void        updateCaption();
private:
    int         rectangles;
    QColor      colors[numColors];
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/forever.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qtimer.h>
#include <qpainter.h>
#include <qapplication.h>
#include <stdlib.h>                             // defines rand() function

#include "forever.h"

//
// Forever - a widget that draws rectangles forever.
//

//
// Constructs a Forever widget.
//

Forever::Forever( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    for (int a=0; a<numColors; a++) {
        colors[a] = QColor( rand()&255,
                            rand()&255,
                            rand()&255 );
    }
    rectangles = 0;
    startTimer( 0 );                            // run continuous timer
    QTimer * counter = new QTimer( this );
    connect( counter, SIGNAL(timeout()),
             this, SLOT(updateCaption()) );
    counter->start( 1000 );
}

void Forever::updateCaption()
{
    QString s;
    s.sprintf( "Qt Example - Forever - %d rectangles/second", rectangles );
    rectangles = 0;
    setCaption( s );
}

//
// Handles paint events for the Forever widget.
//

void Forever::paintEvent( QPaintEvent * )
{
    QPainter paint( this );                     // painter object
    int w = width();
    int h = height();
    if(w <= 0 || h <= 0)
        return;
    paint.setPen( NoPen );                      // do not draw outline
    paint.setBrush( colors[rand() % numColors]);// set random brush color

    QPoint p1( rand()%w, rand()%h );    // p1 = top left
    QPoint p2( rand()%w, rand()%h );    // p2 = bottom right

    QRect r( p1, p2 );
    paint.drawRect( r );                        // draw filled rectangle
}

//
// Handles timer events for the Forever widget.
//

void Forever::timerEvent( QTimerEvent * )
{
    for ( int i=0; i<100; i++ ) {
        repaint( FALSE );                       // repaint, don't erase
        rectangles++;
    }
}

//
// Create and display Forever widget.
//

int main( int argc, char **argv )
{
    QApplication a( argc, argv );               // create application object
    Forever always;                             // create widget
    a.setMainWidget( &always );                 // set as main widget
    always.setCaption("Qt Example - Forever");
    always.show();                              // show widget
    return a.exec();                            // run event loop
}

See also Examples.


An FTP client

This example implements a FTP client. It uses QUrlOperator (which in turn uses QFtp) to perform its FTP commands.

The API of the FtpMainWindow class (ftpmainwindow.h):

/****************************************************************************
** $Id:  qt/ftpmainwindow.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef FTPMAINWINDOW_H
#define FTPMAINWINDOW_H

#include <qmainwindow.h>
#include <qurloperator.h>

class FtpView;
class QSplitter;
class QVBox;
class QSpinBox;
class QComboBox;
class QLineEdit;
class QNetworkOperation;
class QLabel;
class QProgressBar;

class FtpMainWindow : public QMainWindow
{
    Q_OBJECT

public:
    FtpMainWindow();

    QSplitter *mainSplitter() const {
        return splitter;
    }

private:
    void setupLeftSide();
    void setupRightSide();
    void setupCenterCommandBar();
    void setup();

private slots:
    void slotLocalDirChanged( const QString &path );
    void slotLocalDirChanged( const QUrlInfo &info );
    void slotRemoteDirChanged( const QString &path );
    void slotRemoteDirChanged( const QUrlInfo &info );
    void slotConnect();
    void slotUpload();
    void slotDownload();
    void slotLocalStart( QNetworkOperation * );
    void slotLocalFinished( QNetworkOperation * );
    void slotRemoteStart( QNetworkOperation * );
    void slotRemoteFinished( QNetworkOperation * );
    void slotLocalDataTransferProgress( int, int, QNetworkOperation * );
    void slotRemoteDataTransferProgress( int, int, QNetworkOperation * );
    void slotLocalMkDir();
    void slotLocalRemove();
    void slotRemoteMkDir();
    void slotRemoteRemove();
    void slotConnectionStateChanged( int, const QString &msg );

private:
    QSplitter *splitter;
    QVBox *mainWidget;
    FtpView *leftView, *rightView;
    QComboBox *localCombo, *remoteHostCombo, *remotePathCombo, *userCombo;
    QLineEdit *passLined;
    QSpinBox *portSpin;
    QUrlOperator localOperator, remoteOperator, oldLocal, oldRemote;
    QLabel *progressLabel1, *progressLabel2;
    QProgressBar *progressBar1, *progressBar2;

};

#endif

The Implementation of the FtpMainWindow class (ftpmainwindow.cpp):

/****************************************************************************
** $Id:  qt/ftpmainwindow.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "ftpmainwindow.h"
#include "ftpview.h"

#include <qvbox.h>
#include <qhbox.h>
#include <qsplitter.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qspinbox.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <qprogressbar.h>
#include <qdir.h>
#include <qinputdialog.h>
#include <qapplication.h>
#include <qstatusbar.h>

FtpMainWindow::FtpMainWindow()
    : QMainWindow(),
      localOperator( "/" )
{
    setup();

    // connect to the signals of the local QUrlOperator - this will be used to
    // work on the local file system (listing dirs, etc.) and to copy files
    // TO the local filesystem (downloading)
    connect( &localOperator, SIGNAL( newChildren( const QValueList<QUrlInfo> &, QNetworkOperation * ) ),
             leftView, SLOT( slotInsertEntries( const QValueList<QUrlInfo> & ) ) );
    connect( &localOperator, SIGNAL( start( QNetworkOperation * ) ),
             this, SLOT( slotLocalStart( QNetworkOperation *) ) );
    connect( &localOperator, SIGNAL( finished( QNetworkOperation * ) ),
             this, SLOT( slotLocalFinished( QNetworkOperation *) ) );
    connect( leftView, SIGNAL( itemSelected( const QUrlInfo & ) ),
             this, SLOT( slotLocalDirChanged( const QUrlInfo & ) ) );
    connect( &localOperator, SIGNAL( dataTransferProgress( int, int, QNetworkOperation * ) ),
             this, SLOT( slotLocalDataTransferProgress( int, int, QNetworkOperation * ) ) );

    // connect to the signals of the remote QUrlOperator - this will be used to
    // work on the remote file system (on the FTP Server) and to copy files
    // TO the ftp server (uploading)
    connect( &remoteOperator, SIGNAL( newChildren( const QValueList<QUrlInfo> &, QNetworkOperation * ) ),
             rightView, SLOT( slotInsertEntries( const QValueList<QUrlInfo> & ) ) );
    connect( &remoteOperator, SIGNAL( start( QNetworkOperation * ) ),
             this, SLOT( slotRemoteStart( QNetworkOperation *) ) );
    connect( &remoteOperator, SIGNAL( finished( QNetworkOperation * ) ),
             this, SLOT( slotRemoteFinished( QNetworkOperation *) ) );
    connect( rightView, SIGNAL( itemSelected( const QUrlInfo & ) ),
             this, SLOT( slotRemoteDirChanged( const QUrlInfo & ) ) );
    connect( &remoteOperator, SIGNAL( dataTransferProgress( int, int, QNetworkOperation * ) ),
             this, SLOT( slotRemoteDataTransferProgress( int, int, QNetworkOperation * ) ) );
    connect( &remoteOperator, SIGNAL( connectionStateChanged( int, const QString & ) ),
             this, SLOT( slotConnectionStateChanged( int, const QString & ) ) );

    // read the local filesystem at the beginning once
    localOperator.listChildren();

    // create status bar
    (void)statusBar();
}

void FtpMainWindow::setupLeftSide()
{
    // Setup the left side of the GUI, this is the listview
    // of the local filesystem

    QVBox *layout = new QVBox( splitter );
    layout->setSpacing( 5 );
    layout->setMargin( 5 );

    QHBox *h = new QHBox( layout );
    h->setSpacing( 5 );
    QLabel *l = new QLabel( tr( "Local Path:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    localCombo = new QComboBox( TRUE, h );
    localCombo->insertItem( "/" );

    connect( localCombo, SIGNAL( activated( const QString & ) ),
             this, SLOT( slotLocalDirChanged( const QString & ) ) );

    leftView = new FtpView( layout );

    QHBox *bottom = new QHBox( layout );
    bottom->setSpacing( 5 );
    QPushButton *bMkDir = new QPushButton( tr( "New Directory" ), bottom );
    QPushButton *bRemove = new QPushButton( tr( "Remove" ), bottom );
    connect( bMkDir, SIGNAL( clicked() ),
             this, SLOT( slotLocalMkDir() ) );
    connect( bRemove, SIGNAL( clicked() ),
             this, SLOT( slotLocalRemove() ) );

    splitter->setResizeMode( layout, QSplitter::Stretch );
}

void FtpMainWindow::setupRightSide()
{
    // Setup the right side of the GUI, this is the listview
    // of the remote filesystem (FTP), needs also lineedits/combos
    // for username, password, etc.

    QVBox *layout = new QVBox( splitter );
    layout->setSpacing( 5 );
    layout->setMargin( 5 );

    QHBox *h = new QHBox( layout );
    h->setSpacing( 5 );
    QLabel *l = new QLabel( tr( "Remote Host:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    remoteHostCombo = new QComboBox( TRUE, h );

    l = new QLabel( tr( "Port:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    portSpin = new QSpinBox( 0, 32767, 1, h );
    portSpin->setValue( 21 );
    portSpin->setFixedWidth( portSpin->sizeHint().width() );
    remoteOperator.setPort( portSpin->value() );

    h = new QHBox( layout );
    h->setSpacing( 5 );
    l = new QLabel( tr( "Remote Path:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    remotePathCombo = new QComboBox( TRUE, h );

    h = new QHBox( layout );
    h->setSpacing( 5 );
    l = new QLabel( tr( "Username:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    userCombo = new QComboBox( TRUE, h );

    l = new QLabel( tr( "Password:" ), h );
    l->setFixedWidth( l->sizeHint().width() );
    passLined = new QLineEdit( h );
    passLined->setEchoMode( QLineEdit::Password );

    rightView = new FtpView( layout );

    QHBox *bottom = new QHBox( layout );
    bottom->setSpacing( 5 );
    QPushButton *bMkDir = new QPushButton( tr( "New Directory" ), bottom );
    QPushButton *bRemove = new QPushButton( tr( "Remove" ), bottom );
    connect( bMkDir, SIGNAL( clicked() ),
             this, SLOT( slotRemoteMkDir() ) );
    connect( bRemove, SIGNAL( clicked() ),
             this, SLOT( slotRemoteRemove() ) );

    splitter->setResizeMode( layout, QSplitter::Stretch );

    connect( remotePathCombo, SIGNAL( activated( const QString & ) ),
             this, SLOT( slotRemoteDirChanged( const QString & ) ) );
}

void FtpMainWindow::setupCenterCommandBar()
{
    // Setup the command bar in the middle between the two views

    QVBox *w = new QVBox( splitter );
    splitter->setResizeMode( w, QSplitter::FollowSizeHint );
    w->setSpacing( 5 );
    w->setMargin( 5 );

    QPushButton *bConnect = new QPushButton( tr( "&Connect" ), w );
    (void)new QWidget( w );
    QPushButton *bUpload = new QPushButton( tr( "== &Upload ==>" ), w );
    QPushButton *bDownload = new QPushButton( tr( "<== &Download ==" ), w );
    (void)new QWidget( w );

    connect( bConnect, SIGNAL( clicked() ),
             this, SLOT( slotConnect() ) );
    connect( bUpload, SIGNAL( clicked() ),
             this, SLOT( slotUpload() ) );
    connect( bDownload, SIGNAL( clicked() ),
             this, SLOT( slotDownload() ) );
}

void FtpMainWindow::setup()
{
    // Setup the GUI

    mainWidget = new QVBox( this );
    splitter = new QSplitter( mainWidget );
    setupLeftSide();
    setupCenterCommandBar();
    setupRightSide();

    progressLabel1 = new QLabel( tr( "No Operation in Progress" ), mainWidget );
    progressBar1 = new QProgressBar( mainWidget );
    progressLabel2 = new QLabel( tr( "No Operation in Progress" ), mainWidget );
    progressBar2 = new QProgressBar( mainWidget );

    progressLabel1->hide();
    progressBar1->hide();
    progressLabel2->hide();
    progressBar2->hide();

    setCentralWidget( mainWidget );
}

void FtpMainWindow::slotLocalDirChanged( const QString &path )
{
    // The user changed the path on the left side

    oldLocal = localOperator;
    localOperator.setPath( path );
    localOperator.listChildren();
}

void FtpMainWindow::slotLocalDirChanged( const QUrlInfo &info )
{
    // The user changed the path on the left side

    oldLocal = localOperator;
    localOperator.addPath( info.name() );
    localOperator.listChildren();
    localCombo->insertItem( localOperator.path(), 0 );
    localCombo->setCurrentItem( 0 );
}

void FtpMainWindow::slotRemoteDirChanged( const QString &path )
{
    // The user changed the path on the right side

    if ( !remoteOperator.isValid() )
        return;
    oldRemote = remoteOperator;
    remoteOperator.setPath( path );
    remoteOperator.listChildren();
}

void FtpMainWindow::slotRemoteDirChanged( const QUrlInfo &info )
{
    // The user changed the path on the right side

    oldRemote = remoteOperator;
    remoteOperator.addPath( info.name() );
    remoteOperator.listChildren();
    remotePathCombo->insertItem( remoteOperator.path(), 0 );
    remotePathCombo->setCurrentItem( 0 );
}

void FtpMainWindow::slotConnect()
{
    // The user pressed the connect button, so let's connect to the
    // FTP server
    // First we need to set stuff (host, path, etc.) which the user
    // entered on the right side to the remote QUrlOperator

    // protocol + hostname
    QString s = "ftp://" + remoteHostCombo->currentText();
    oldRemote = remoteOperator;
    remoteOperator = s;

    // path on the server
    if ( !remotePathCombo->currentText().isEmpty() )
        remoteOperator.setPath( remotePathCombo->currentText() );
    else
        remoteOperator.setPath( "/" );

    // if nothing or "ftp" or "anonymous" has been entered into the username combo,
    // let's connect anonymous, else private with password
    if ( !userCombo->currentText().isEmpty() &&
         userCombo->currentText().lower() != "anonymous" &&
         userCombo->currentText().lower() != "ftp" ) {
        remoteOperator.setUser( userCombo->currentText() );
        remoteOperator.setPassword( passLined->text() );
    }

    // set the port
    remoteOperator.setPort( portSpin->value() );

    // finally read the directory on the ftp server
    remoteOperator.listChildren();
}

void FtpMainWindow::slotUpload()
{
    // the user pressed the upload button

    // if files have been selected on the left side (local filesystem)
    QValueList<QUrlInfo> files = leftView->selectedItems();
    if ( files.isEmpty() )
        return;

    // create a list of the URLs which should be copied
    QStringList lst;
    QValueList<QUrlInfo>::Iterator it = files.begin();
    for ( ; it != files.end(); ++it )
        lst << QUrl( localOperator, ( *it ).name() );

    // copy the list of selected files to the directory in which the
    // remoteOperator currently is (upload)
    remoteOperator.copy( lst, remoteOperator, FALSE );
}

void FtpMainWindow::slotDownload()
{
    // if the user pressed the download button

    // if files have been selected on the right side (remote filesystem)
    QValueList<QUrlInfo> files = rightView->selectedItems();
    if ( files.isEmpty() )
        return;

    // create a list of the URLs which should be downloaded
    QStringList lst;
    QValueList<QUrlInfo>::Iterator it = files.begin();
    for ( ; it != files.end(); ++it )
        lst << QUrl( remoteOperator, ( *it ).name() );

    // copy the list of selected files to the directory in which the
    // localOperator currently is (download)
    localOperator.copy( lst, localOperator, FALSE );
}

void FtpMainWindow::slotLocalStart( QNetworkOperation *op )
{
    // this slot is always called if the local QUrlOperator starts
    // listing a directory or dowloading a file

    if ( !op )
        return;

    if ( op->operation() == QNetworkProtocol::OpListChildren ) {
        // start listing a dir? clear the left view!
        leftView->clear();
    } else if ( op->operation() == QNetworkProtocol::OpGet ) {
        // start downloading a file? reset the progress bar!
        progressBar1->setTotalSteps( 0 );
        progressBar1->reset();
    }
}

void FtpMainWindow::slotLocalFinished( QNetworkOperation *op )
{
    // this slot is always called if the local QUrlOperator finished
    // an operation

    if ( !op )
        return;

    if ( op && op->state() == QNetworkProtocol::StFailed ) {
        // an error happend, let the user know that
        QMessageBox::critical( this, tr( "ERROR" ), op->protocolDetail() );

        // do something depending in the error code
        int ecode = op->errorCode();
        if ( ecode == QNetworkProtocol::ErrListChildren || ecode == QNetworkProtocol::ErrParse ||
             ecode == QNetworkProtocol::ErrUnknownProtocol || ecode == QNetworkProtocol::ErrLoginIncorrect ||
             ecode == QNetworkProtocol::ErrValid || ecode == QNetworkProtocol::ErrHostNotFound ||
             ecode == QNetworkProtocol::ErrFileNotExisting ) {
            localOperator = oldLocal;
            localCombo->setEditText( localOperator.path() );
            localOperator.listChildren();
        }
    } else if ( op->operation() == QNetworkProtocol::OpPut ) {
        // finished saving the downloaded file? reread the dir and hide the progress bar
        localOperator.listChildren();
        progressLabel1->hide();
        progressBar1->hide();
    } else if ( op->operation() == QNetworkProtocol::OpGet ) {
        // finished reading a file from the ftp server? reset the progress bar
        progressBar1->setTotalSteps( 0 );
        progressBar1->reset();
    }

}

void FtpMainWindow::slotRemoteStart( QNetworkOperation *op )
{
    // this slot is always called if the remote QUrlOperator starts
    // listing a directory or uploading a file

    if ( !op )
        return;

    if ( op->operation() == QNetworkProtocol::OpListChildren ) {
        // start listing a dir? clear the right view!
        rightView->clear();
    } else if ( op->operation() == QNetworkProtocol::OpGet ) {
        // start downloading a file? reset the progress bar!
        progressBar2->setTotalSteps( 0 );
        progressBar2->reset();
    }
}

void FtpMainWindow::slotRemoteFinished( QNetworkOperation *op )
{
    // this slot is always called if the remote QUrlOperator finished
    // an operation

    if ( !op )
        return;

    if ( op && op->state() == QNetworkProtocol::StFailed ) {
        // an error happend, let the user know that
        QMessageBox::critical( this, tr( "ERROR" ), op->protocolDetail() );

        // do something depending in the error code
        int ecode = op->errorCode();
        if ( ecode == QNetworkProtocol::ErrListChildren || ecode == QNetworkProtocol::ErrParse ||
             ecode == QNetworkProtocol::ErrUnknownProtocol || ecode == QNetworkProtocol::ErrLoginIncorrect ||
             ecode == QNetworkProtocol::ErrValid || ecode == QNetworkProtocol::ErrHostNotFound ||
             ecode == QNetworkProtocol::ErrFileNotExisting ) {
            remoteOperator = oldRemote;
            remoteHostCombo->setEditText( remoteOperator.host() );
            remotePathCombo->setEditText( remoteOperator.path() );
            passLined->setText( remoteOperator.password() );
            userCombo->setEditText( remoteOperator.user() );
            portSpin->setValue( remoteOperator.port() );
            remoteOperator.listChildren();
        }
    } else if ( op->operation() == QNetworkProtocol::OpListChildren ) {
        // finished reading a dir? set the correct path to the pth combo of the right view
        remotePathCombo->setEditText( remoteOperator.path() );
    } else if ( op->operation() == QNetworkProtocol::OpPut ) {
        // finished saving the uploaded file? reread the dir and hide the progress bar
        remoteOperator.listChildren();
        progressLabel2->hide();
        progressBar2->hide();
    } else if ( op->operation() == QNetworkProtocol::OpGet ) {
        // finished reading a file from the local filesystem? reset the progress bar
        progressBar2->setTotalSteps( 0 );
        progressBar2->reset();
    }
}

void FtpMainWindow::slotLocalDataTransferProgress( int bytesDone, int bytesTotal,
                                                   QNetworkOperation *op )
{
    // Show the progress here of the local QUrlOperator reads or writes data

    if ( !op )
        return;

    if ( !progressBar1->isVisible() ) {
        if ( bytesDone < bytesTotal) {
            progressLabel1->show();
            progressBar1->show();
            progressBar1->setTotalSteps( bytesTotal );
            progressBar1->setProgress( 0 );
            progressBar1->reset();
        } else
            return;
    }

    if ( progressBar1->totalSteps() == bytesTotal )
        progressBar1->setTotalSteps( bytesTotal );

    if ( op->operation() == QNetworkProtocol::OpGet )
        progressLabel1->setText( tr( "Read: %1" ).arg( op->arg( 0 ) ) );
    else if ( op->operation() == QNetworkProtocol::OpPut )
        progressLabel1->setText( tr( "Write: %1" ).arg( op->arg( 0 ) ) );
    else
        return;

    progressBar1->setProgress( bytesDone );
}

void FtpMainWindow::slotRemoteDataTransferProgress( int bytesDone, int bytesTotal,
                                                    QNetworkOperation *op )
{
    // Show the progress here of the remote QUrlOperator reads or writes data

    if ( !op )
        return;

    if ( !progressBar2->isVisible() ) {
        if ( bytesDone < bytesTotal) {
            progressLabel2->show();
            progressBar2->show();
            progressBar2->setTotalSteps( bytesTotal );
            progressBar2->setProgress( 0 );
            progressBar2->reset();
        } else
            return;
    }

    if ( progressBar2->totalSteps() != bytesTotal )
        progressBar2->setTotalSteps( bytesTotal );

    if ( op->operation() == QNetworkProtocol::OpGet )
        progressLabel2->setText( tr( "Read: %1" ).arg( op->arg( 0 ) ) );
    else if ( op->operation() == QNetworkProtocol::OpPut )
        progressLabel2->setText( tr( "Write: %1" ).arg( op->arg( 0 ) ) );
    else
        return;

    progressBar2->setProgress( bytesDone );
}

void FtpMainWindow::slotLocalMkDir()
{
    // create a dir on the local filesystem

    bool ok = FALSE;
    QString name = QInputDialog::getText( tr( "Directory Name:" ), QString::null, QLineEdit::Normal, QString::null, &ok, this );

    if ( !name.isEmpty() && ok )
        localOperator.mkdir( name );
}

void FtpMainWindow::slotLocalRemove()
{
}

void FtpMainWindow::slotRemoteMkDir()
{
    // create a dir on the remote filesystem (FTP server)

    bool ok = FALSE;
    QString name = QInputDialog::getText( tr( "Directory Name:" ), QString::null, QLineEdit::Normal, QString::null, &ok, this );

    if ( !name.isEmpty() && ok )
        remoteOperator.mkdir( name );
}

void FtpMainWindow::slotRemoteRemove()
{
}

void FtpMainWindow::slotConnectionStateChanged( int, const QString &msg )
{
    statusBar()->message( msg );
}

The API of the FtpViewItem and FtpView classes (ftpview.h):

/****************************************************************************
** $Id:  qt/ftpview.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef FTPVIEW_H
#define FTPVIEW_H

#include <qlistview.h>
#include <qvaluelist.h>
#include <qurlinfo.h>

class FtpViewItem : public QListViewItem
{
public:
    FtpViewItem( QListView *parent, const QUrlInfo &i );

    int compare( QListViewItem * i, int col, bool ascending ) const;
    QString text( int c ) const;
    const QPixmap* pixmap( int c ) const;

    QUrlInfo entryInfo() {
        return info;
    }

private:
    QUrlInfo info;

};

class FtpView : public QListView
{
    Q_OBJECT

public:
    FtpView( QWidget *parent );
    QValueList<QUrlInfo> selectedItems() const;

public slots:
    void slotInsertEntries( const QValueList<QUrlInfo> &info );

signals:
    void itemSelected( const QUrlInfo &info );

private slots:
    void slotSelected( QListViewItem *item );

};

#endif

Their Implementation (ftpview.cpp):

/****************************************************************************
** $Id:  qt/ftpview.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "ftpview.h"

#include <qpixmap.h>
#include <qvaluelist.h>

/* XPM */
static const char* closed_xpm[]={
    "15 15 6 1",
    ". c None",
    "b c #ffff00",
    "d c #000000",
    "* c #999999",
    "a c #cccccc",
    "c c #ffffff",
    "...............",
    "..*****........",
    ".*ababa*.......",
    "*abababa******.",
    "*cccccccccccc*d",
    "*cbababababab*d",
    "*cabababababa*d",
    "*cbababababab*d",
    "*cabababababa*d",
    "*cbababababab*d",
    "*cabababababa*d",
    "*cbababababab*d",
    "**************d",
    ".dddddddddddddd",
    "..............."};

/* XPM */
static const char* file_xpm[]={
    "13 15 5 1",
    ". c #7f7f7f",
    "# c None",
    "c c #000000",
    "b c #bfbfbf",
    "a c #ffffff",
    "..........###",
    ".aaaaaaaab.##",
    ".aaaaaaaaba.#",
    ".aaaaaaaacccc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".aaaaaaaaaabc",
    ".bbbbbbbbbbbc",
    "ccccccccccccc"};

QPixmap *folderIcon = 0;
QPixmap *fileIcon = 0;

FtpViewItem::FtpViewItem( QListView *parent, const QUrlInfo &i )
    : QListViewItem( parent, i.name() ), info( i )
{
}

int FtpViewItem::compare( QListViewItem * i, int col, bool ascending ) const
{
    FtpViewItem *other = (FtpViewItem*)i;
    switch ( col ) {
    case 1:
        if ( info.size() == other->info.size() )
            return 0;
        else
            return info.size() < other->info.size() ? -1 : 1;
    case 2:
        if ( info.lastModified() == other->info.lastModified() )
            return 0;
        else
            return info.lastModified() < other->info.lastModified() ? -1 : 1;
    default:
        // use default method for colum 0 and others added in the future
        return QListViewItem::compare( i, col, ascending );
    };
}

QString FtpViewItem::text( int c ) const
{
    switch ( c ) {
    case 0:
        return info.name();
    case 1:
        return QString::number( info.size() );
    case 2:
        return info.lastModified().toString();
    }

    return "????";
}

const QPixmap *FtpViewItem::pixmap( int c ) const
{
    if ( !folderIcon )
        folderIcon = new QPixmap( closed_xpm );
    if ( !fileIcon )
        fileIcon = new QPixmap( file_xpm );
    if ( info.isDir() && c == 0 )
        return folderIcon;
    else if ( info.isFile() && c == 0 )
        return fileIcon;
    return 0;
}

FtpView::FtpView( QWidget *parent )
    : QListView( parent )
{
    addColumn( tr( "Name" ) );
    addColumn( tr( "Size" ) );
    addColumn( tr( "Last Modified" ) );
    setColumnAlignment( 1, Qt::AlignRight );
    setShowSortIndicator( TRUE );
    setAllColumnsShowFocus( TRUE );
    setSelectionMode( Extended );

    connect( this, SIGNAL( doubleClicked( QListViewItem * ) ),
             this, SLOT( slotSelected( QListViewItem * ) ) );
    connect( this, SIGNAL( returnPressed( QListViewItem * ) ),
             this, SLOT( slotSelected( QListViewItem * ) ) );
}

void FtpView::slotInsertEntries( const QValueList<QUrlInfo> &info )
{
    QValueList<QUrlInfo>::ConstIterator it;
    for( it = info.begin(); it != info.end(); ++it ) {
        if ( (*it).name() != ".." && (*it).name() != "." && (*it).name()[ 0 ] == '.' )
            continue;
        FtpViewItem *item = new FtpViewItem( this, (*it) );
        if ( (*it).isDir() )
            item->setSelectable( FALSE );
    }
}

void FtpView::slotSelected( QListViewItem *item )
{
    if ( !item )
        return;

    FtpViewItem *i = (FtpViewItem*)item;
    if ( i->entryInfo().isDir() )
        emit itemSelected( i->entryInfo() );
}

QValueList<QUrlInfo> FtpView::selectedItems() const
{
    QValueList<QUrlInfo> lst;
    QListViewItemIterator it( (QListView*)this );
    for ( ; it.current(); ++it ) {
        if ( it.current()->isSelected() ) {
            lst << ( (FtpViewItem*)it.current() )->entryInfo();
        }
    }

    return lst;
}

Main (main.cpp):

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Nov 6 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qnetwork.h>
#include <qsplitter.h>

#include "ftpmainwindow.h"

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

    // call this to register the built-in network protocols, e.g. FTP
    // and HTTP.
    qInitNetworkProtocols();

    FtpMainWindow m;
    a.setMainWidget( &m );
    QValueList<int> sizes;
    sizes << 300 << 70 << 300;
    m.mainSplitter()->setSizes( sizes );
    m.resize( 800, 600 );
    m.show();
    return a.exec();
}

See also Network Examples.


Layout Management

These classes provide automatic geometry (layout) management of widgets.

QBoxLayout | Lines up child widgets horizontally or vertically
QButtonGroup | Organizes QButton widgets in a group
QGLayoutIterator | Abstract base class of internal layout iterators
QGrid | Simple geometry management of its children
QGridLayout | Lays out widgets in a grid
QGroupBox | Group box frame with a title
QHBox | Horizontal geometry management for its child widgets
QHBoxLayout | Lines up widgets horizontally
QHButtonGroup | Organizes QButton widgets in a group with one horizontal row
QHGroupBox | Organizes widgets in a group with one horizontal row
QLayout | The base class of geometry managers
QLayoutItem | Abstract item that a QLayout manipulates
QLayoutIterator | Iterators over QLayoutItem
QSizePolicy | Layout attribute describing horizontal and vertical resizing policy
QSpacerItem | Blank space in a layout
QVBox | Vertical geometry management of its child widgets
QVBoxLayout | Lines up widgets vertically
QVButtonGroup | Organizes QButton widgets in a vertical column
QVGroupBox | Organizes a group of widgets in a vertical column
QWidgetItem | Layout item that represents a widget


Grapher Plugin

This example graphs data from a simple text file. It demonstrates the use of the QNPInstance::writeReady() and QNPInstance::write() functions.

To build the example, you must first build the Qt Netscape Plugin Extension library. Then type make in extensions/nsplugin/examples/grapher/ and copy the resulting grapher.so or npgrapher.dll to the Plugins directory of your WWW browser.

The text file it accepts as input has a title line, then a sequence of lines with a number, then a string. The plugin displays a pie chart of the numbers, each segment labelled by the associated string. The user can select a bar chart view of the same data by selecting from the menu that appears when they point at the plugin.

The HTML tag used to embed the graph is:

  <EMBED
    SRC=graph.g1n
    ALIGN=LEFT
    WIDTH=49% HEIGHT=300
    graphstyle=pie fontfamily=times
    fontsize=18>

Note that some HTML arguments (which we have capitalized here) are interpreted by the browser, while others are used by the plugin.

With the simplicity and cross-platform nature of Qt-based plugins, pages like Netcraft's Server Graphs can be provided much more efficiently for both the service provider and consumer. Data need not be converted to an image at the server.

Implementation:

// Include Qt Netscape Plugin classes.
#include "qnp.h"

// Include other Qt classes.
#include <qpainter.h>
#include <qtextstream.h>
#include <qbuffer.h>
#include <qpixmap.h>
#include <qmenubar.h>
#include <qpushbutton.h>
#include <qptrlist.h>
#include <qmessagebox.h>

// Include some C library functions.
#include <math.h>
#include <stdlib.h>

#ifndef M_PI // Some math.h don't include this.
#define M_PI 3.14159265358979323846264338327950288
#endif

//
// GraphModel is a simple abstract class that describes
// a table of numeric and text data.
//

class GraphModel {
public:
    enum ColType { Numeric, Label };

    union Datum {
        double dbl;
        QString* str;
    };

    virtual QPtrList<Datum>& graphData()=0;
    virtual ColType colType(int col) const=0;
    virtual int nCols() const=0;
};

//
// Graph is a widget subclass that displays a GraphModel.
// Since the widget is a QNPWidget, it can be used as a plugin window,
// returned by Grapher::newWindow() below.
//

class Graph : public QNPWidget {
    Q_OBJECT
public:
    // Constructs a Graph to display a GraphModel
    //
    Graph(GraphModel&);
    ~Graph();

    // Two styles are available - Pie and Bar graph
    //
    enum Style { Pie, Bar };
    static const char* styleName[];
    void setStyle(Style);
    void setStyle(const char*);

    // Timer event processing rotates the pie graph
    //
    void timerEvent(QTimerEvent*);

    // These functions are provided by QNPWidget - we override
    // them to hide and show the plugin menubar.
    //
    void enterInstance();
    void leaveInstance();

    // Paint the graph...
    //
    void paintEvent(QPaintEvent*);
    //
    // ... as either a "Loading" message, a Bar graph, a Pie graph,
    // or an error message.
    //
    void paintWait(QPaintEvent*);
    void paintBar(QPaintEvent*);
    void paintPie(QPaintEvent*);
    void paintError(const char*);

signals:
    // Signals emitted when the Help menus are selected.
    void aboutPlugin();
    void aboutData();

private:
    GraphModel& model;
    QMenuBar *menubar;
    Style style;
    QPopupMenu* stylemenu;
    int pieRotationTimer;
    int pieRotation;
    QPixmap pm;

private slots:
    void setStyleFromMenu(int id);
};

Graph::Graph( GraphModel& mdl ) :
    model(mdl),
    style(Bar),
    pieRotationTimer(0),
    pieRotation(0)
{
    // Create a menubar for the widget
    //
    menubar = new QMenuBar( this );
    stylemenu = new QPopupMenu;
    stylemenu->setCheckable(TRUE);
    for ( Style s = Pie; styleName[s]; s = Style(s+1)) {
        stylemenu->insertItem(styleName[s], s+100);
    }
    connect(stylemenu, SIGNAL(activated(int)),
        this, SLOT(setStyleFromMenu(int)));
    setStyle(Pie);

    menubar->insertItem("Style", stylemenu);
    menubar->insertSeparator();

    QPopupMenu* help = new QPopupMenu;
    help->insertItem( "About plugin...", this, SIGNAL(aboutPlugin()) );
    help->insertItem( "About data...", this, SIGNAL(aboutData()) );
    menubar->insertItem("Help", help);
}

Graph::~Graph()
{
}

void Graph::setStyle(Style s)
{
    if (style != s) {
        if (pieRotationTimer)
            killTimer(pieRotationTimer);
        stylemenu->setItemChecked(100+style, FALSE);
        style = s;
        if ( style == Pie )
            pieRotationTimer = startTimer( 80 );
        else
            pieRotationTimer = 0;
        stylemenu->setItemChecked(100+style, TRUE);
        update();
    }
}

void Graph::timerEvent(QTimerEvent*)
{
    pieRotation = ( pieRotation + 6 ) % 360; repaint(FALSE);
}

void Graph::setStyle(const char* stext)
{
    for ( Style s = Pie; styleName[s]; s = Style(s+1) ) {
        if ( qstricmp(stext,styleName[s])==0 ) {
            setStyle(s);
            return;
        }
    }
}

void Graph::enterInstance()
{
    menubar->show();
}

void Graph::leaveInstance()
{
    menubar->hide();
}

void Graph::paintError(const char* e)
{
    QPainter p(this);
    int w = width();
    p.drawText(w/8, 0, w-w/4, height(), AlignCenter|WordBreak, e);
}

void Graph::paintBar(QPaintEvent* event)
{
    if ( model.colType(0) != GraphModel::Numeric ) {
        paintError("First column not numeric, cannot draw bar graph\n");
        return;
    }

    QPtrList<GraphModel::Datum>& data = model.graphData();

    double max = 0.0;

    for (GraphModel::Datum* rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        if (rowdata[0].dbl > max) max = rowdata[0].dbl;
    }

    const uint w = width();
    const uint h = height();

    QPainter p(this);

    p.setClipRect(event->rect());

    if ( w > data.count() ) {
        // More pixels than data
        int x = 0;
        int i = 0;
        QFontMetrics fm=fontMetrics();
        int fh = fm.height();

        for (GraphModel::Datum* rowdata = data.first();
            rowdata; rowdata = data.next())
        {
            QColor c;
            c.setHsv( (i * 255)/data.count(), 255, 255 );// rainbow effect
            p.setBrush(c);
            int bw = (w-w/4-x)/(data.count()-i);
            int bh = int((h-h/4-1)*rowdata[0].dbl/max);
            p.drawRect( w/8+x, h-h/8-1-bh, bw, bh );

            i++;
            x+=bw;
        }
    } else {
        // More data than pixels
        int x = 0;
        int i = 0;
        double av = 0.0;
        int n = 0;
        for (GraphModel::Datum* rowdata = data.first(); rowdata;
            rowdata = data.next())
        {
            int bx = i*w/data.count();

            if (bx > x) {
                QColor c;
                c.setHsv( (x * 255)/w, 255, 255 );// rainbow effect
                p.setPen(c);
                int bh = int(h*av/n/max);

                p.drawLine(x,h-1,x,h-bh);

                av = 0.0;
                n = 0;
                x = bx;
            }

            av += rowdata[0].dbl;
            n++;

            i++;
        }
    }
}

void Graph::paintPie(QPaintEvent* event)
{
    if ( model.colType(0) != GraphModel::Numeric ) {
        paintError("First column not numeric, cannot draw pie graph\n");
        return;
    }

    QPtrList<GraphModel::Datum>& data = model.graphData();

    double total = 0.0;

    GraphModel::Datum* rowdata;

    for (rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        total += rowdata[0].dbl;
    }

    // Only use first column for pie chart
    if ( !total ) return;

    int apos = (pieRotation-90)*16;

    const int w = width();
    const int h = height();

    const int xd = w - w/5;
    const int yd = h - h/5;

    pm.resize(width(),height());
    pm.fill(backgroundColor());
    QPainter p(&pm);
    p.setFont(font());

    p.setClipRect(event->rect());

    int i = 0;

    for (rowdata = data.first();
        rowdata; rowdata = data.next())
    {
        QColor c;

        c.setHsv( ( i * 255)/data.count(), 255, 255 );// rainbow effect
        p.setBrush( c );                        // solid fill with color c

        int a = int(( rowdata[0].dbl * 360.0 ) / total * 16.0 + 0.5);
        p.drawPie( w/10, h/10, xd, yd, -apos, -a );
        apos += a;
        i++;
    }

    if (model.colType(1) == GraphModel::Label) {
        double apos = (pieRotation-90)*M_PI/180;

        for (rowdata = data.first();
            rowdata; rowdata = data.next())
        {
            double a = rowdata[0].dbl * 360 / total * M_PI / 180;
            int x = int(cos(apos+a/2)*w*5/16 + w/2 + 0.5);
            int y = int(sin(apos+a/2)*h*5/16 + h/2 + 0.5);

            // ### This causes a crash, so comment out for now
            /*p.drawText(x-w/8, y-h/8, w/4, h/4,
                WordBreak|AlignCenter,
                *rowdata[1].str);*/
            apos += a;
        }
    }

    QPainter p2(this);
    p2.setClipRect(event->rect());
    p2.drawPixmap(0,0,pm);
}

void Graph::paintWait(QPaintEvent*)
{
    QPainter p(this);
    p.drawText(rect(), AlignCenter, "Loading...");
}

void Graph::paintEvent(QPaintEvent* event)
{
    if (!model.nCols()) {
        paintWait(event);
    } else {
        switch (style) {
          case Pie:
            paintPie(event);
            break;
          case Bar:
            paintBar(event);
            break;
        }
    }
}

void Graph::setStyleFromMenu(int id)
{
    setStyle(Style(id-100));
}

const char* Graph::styleName[] = { "Pie", "Bar", 0 };

//
// Grapher is a subclass of QNPInstance, and so it can be returned
// by GrapherPlugin::newInstance().  A QNPInstance represents the
// plugin, distinctly from the plugin window.
//
// Grapher is also a GraphModel, because it loads graph data from
// the net.  When Grapher creates a window in newWindow(), it creates
// a Graph widget to display the GraphModel that is the Grapher itself.
//

class Grapher : public QNPInstance, GraphModel {
    Q_OBJECT
public:
    // Create a Grapher - all Grapher plugins are created
    // by one GrapherPlugin object.
    //
    Grapher();
    ~Grapher();

    // We override this QNPInstance function to create our
    // own subclass of QNPWidget, a Graph widget.
    //
    QNPWidget* newWindow();

    // We override this QNPInstance function to process the
    // incoming graph data.
    //
    int write(QNPStream* /*str*/, int /*offset*/, int len, void* buffer);

private:
    // Grapher is a GraphModel, so it implements the pure virtual
    // functions of that class.
    //
    QPtrList<Datum>& graphData();
    ColType colType(int col) const;
    int nCols() const;

    void consumeLine();
    QPtrList<Datum> data;
    QBuffer line;
    bool firstline;
    int ncols;
    ColType *coltype;

private slots:
    // Slots that are connected to the Graph menu items.
    //
    void aboutPlugin();
    void aboutData();
};

Grapher::Grapher()
{
    data.setAutoDelete(TRUE);
    firstline = TRUE;
    ncols = 0;
    line.open(IO_WriteOnly|IO_Truncate);
}

Grapher::~Grapher()
{
}

QPtrList<GraphModel::Datum>& Grapher::graphData()
{
    return data;
}

GraphModel::ColType Grapher::colType(int col) const
{
    return coltype[col];
}

int Grapher::nCols() const
{
    return ncols;
}

QNPWidget* Grapher::newWindow()
{
    // Create a Graph - our subclass of QNPWidget.
    Graph *graph = new Graph(*this);

    // Look at the arguments from the EMBED tag.
    //   GRAPHSTYLE chooses pie or bar
    //   FONTFAMILY and FONTSIZE choose the font
    //
    const char* style = arg("GRAPHSTYLE");
    if ( style ) graph->setStyle(style);

    const char* fontfamily = arg("FONTFAMILY");
    const char* fontsize = arg("FONTSIZE");
    int ptsize = fontsize ? atoi(fontsize) : graph->font().pointSize();
    if (fontfamily) graph->setFont(QFont(fontfamily, ptsize));

    connect(graph, SIGNAL(aboutPlugin()), this, SLOT(aboutPlugin()));
    connect(graph, SIGNAL(aboutData()), this, SLOT(aboutData()));

    return graph;
}

void Grapher::consumeLine()
{
    line.close();
    line.open(IO_ReadOnly);

    QTextStream ts( &line );

    if (firstline) {
        firstline = FALSE;
        ncols=0;
        QPtrList<ColType> typelist;
        typelist.setAutoDelete(TRUE);
        do {
            QString typestr;
            ts >> typestr >> ws;
            ColType* t = 0;
            if ( typestr == "num" ) {
                t = new ColType(Numeric);
            } else if ( typestr == "label" ) {
                t = new ColType(Label);
            }
            if (t) typelist.append(t);
        } while (!ts.atEnd());
        coltype = new ColType[ncols];
        for (ColType* t = typelist.first(); t; t = typelist.next()) {
            coltype[ncols++] = *t;
        }
    } else {
        int col=0;
        Datum *rowdata = new Datum[ncols];
        while ( col < ncols && !ts.atEnd() ) {
            switch (coltype[col]) {
              case Numeric: {
                double value;
                ts >> value >> ws;
                rowdata[col].dbl = value;
                break;
              }
              case Label: {
                QString* value = new QString;
                ts >> *value >> ws;
                rowdata[col].str = value;
                break;
              }
            }
            col++;
        }

        data.append(rowdata);
    }

    line.close();
    line.open(IO_WriteOnly|IO_Truncate);
}

int Grapher::write(QNPStream* /*str*/, int /*offset*/, int len, void* buffer)
{
    // The browser calls this function when data is available on one
    // of the streams the plugin has requested.  Since we are only
    // processing one stream - the URL in the SRC argument of the EMBED
    // tag, we assume the QNPStream is that one.  Also, since we do not
    // override QNPInstance::writeReady(), we must accepts ALL the data
    // that is sent to this function.
    //
    char* txt = (char*)buffer;
    for (int i=0; i<len; i++) {
        char ch = txt[i];
        switch ( ch ) {
          case '\n':
            consumeLine();
            break;
          case '\r': // ignore;
            break;
          default:
            line.putch(ch);
        }
    }

    if ( widget() ) {
        widget()->update();
    }

    return len;
}

void Grapher::aboutPlugin()
{
    getURL( "http://www.trolltech.com/nsplugin/", "_blank" );
}

void Grapher::aboutData()
{
    const char* page = arg("DATAPAGE");
    if (page)
        getURL( page, "_blank" );
    else
        QMessageBox::message("Help", "No help for this data");
}

//
// GrapherPlugin is the start of everything.  It is a QNPlugin subclass,
// and it is responsible for describing the plugin to the browser, and
// creating instances of the plugin when it appears in web page.
//

class GrapherPlugin : public QNPlugin {
public:
    GrapherPlugin()
    {
    }

    QNPInstance* newInstance()
    {
        // Make a new Grapher, our subclass of QNPInstance.
        return new Grapher;
    }

    const char* getMIMEDescription() const
    {
        // Describe the MIME types which this plugin can
        // process.  Just the concocted "application/x-graphable"
        // type, with the "g1n" filename extension.
        //
        return "application/x-graphable:g1n:Graphable ASCII numeric data";
    }

    const char * getPluginNameString() const
    {
        // The name of the plugin.  This is the title string used in
        // the "About Plugins" page of the browser.
        //
        return "Qt-based Graph Plugin";
    }

    const char * getPluginDescriptionString() const
    {
        // A longer description of the plugin.
        //
        return "A Qt-based LiveConnected plug-in that graphs numeric data";
    }

};

//
// Finally, we provide the implementation of QNPlugin::create(), to
// provide our subclass of QNPlugin.
//

QNPlugin* QNPlugin::create()
{
    return new GrapherPlugin;
}

#include "grapher.moc"

See also LiveConnect Examples.


Graphics Classes

These classes provide powerful graphics drawing primitives for both 2D and (with OpenGL) 3D.

See also this introduction to the Qt coordinate system.

QBitmap | Monochrome (1-bit depth) pixmaps
QBrush | Defines the fill pattern of shapes drawn by a QPainter
QCanvas | 2D area that can contain QCanvasItem objects
QCanvasEllipse | Ellipse or ellipse segment on a QCanvas
QCanvasItem | Abstract graphic object on a QCanvas
QCanvasItemList | List of QCanvasItems
QCanvasLine | Line on a QCanvas
QCanvasPixmap | Pixmaps for QCanvasSprites
QCanvasPixmapArray | Array of QCanvasPixmaps
QCanvasPolygon | Polygon on a QCanvas
QCanvasPolygonalItem | Polygonal canvas item on a QCanvas
QCanvasRectangle | Rectangle on a QCanvas
QCanvasSpline | Multi-bezier splines on a QCanvas
QCanvasSprite | Animated canvas item on a QCanvas
QCanvasText | Text object on a QCanvas
QCanvasView | On-screen view of a QCanvas
QColor | Colors based on RGB or HSV values
QColorDialog | Dialog widget for specifying colors
QColorGroup | Group of widget colors
QDirectPainter | Direct access to the video hardware
QFont | Font used for drawing text
QFontDatabase | Information about the fonts available in the underlying window system
QFontInfo | General information about fonts
QFontMetrics | Font metrics information
QGL | Namespace for miscellaneous identifiers in the Qt OpenGL module
QGLColormap | Used for installing custom colormaps into QGLWidgets
QGLContext | Encapsulates an OpenGL rendering context
QGLFormat | The display format of an OpenGL rendering context
QGLWidget | Widget for rendering OpenGL graphics
QIconSet | Set of icons with different styles and sizes
QImage | Hardware-independent pixmap representation with direct access to the pixel data
QImageConsumer | Abstraction used by QImageDecoder
QImageDecoder | Incremental image decoder for all supported image formats
QImageFormat | Incremental image decoder for a specific image format
QImageFormatType | Factory that makes QImageFormat objects
QImageIO | Parameters for loading and saving images
QMovie | Incremental loading of animations or images, signalling as it progresses
QPaintDevice | The base class of objects that can be painted
QPaintDeviceMetrics | Information about a paint device
QPainter | Does low-level painting e.g. on widgets
QPalette | Color groups for each widget state
QPen | Defines how a QPainter should draw lines and outlines of shapes
QPicture | Paint device that records and replays QPainter commands
QPixmap | Off-screen, pixel-based paint device
QPixmapCache | Application-global cache for pixmaps
QPNGImagePacker | Creates well-compressed PNG animations
QPoint | Defines a point in the plane
QPointArray | Array of points
QPrinter | Paint device that paints on a printer
QRect | Defines a rectangle in the plane
QRegion | Clip region for a painter
QSize | Defines the size of a two-dimensional object
QStyleSheet | Collection of styles for rich text rendering and a generator of tags
QWMatrix | 2D transformations of a coordinate system


Books about GUI

This is not a comprehensive list of books, there are many other books worth buying. This is just a few GUI/UI books that don't gather dust in our shelves.

Programming with Qt by Kalle Dalheimer, ISBN 1-56592-588-2 is a simple introduction to programming with Qt. For those wanting something more than our short tutorial, this is it. (Read more or buy it.)

The Design of Everyday Things by Donald Norman, ISBN 0-38526774-6, is one of the classics of human interface design. Norman shows how badly something as simple as a kitchen stove can be designed, and everyone should read it who will design a dialog box, write an error message, or design just about anything else humans are supposed to use. (Read more or buy it.)

GUI Design Handbook by Susan Fowler, ISBN 0-07-059274-8, is an alphabetical dictionary of widgets and other user interface elements, with comprehensive coverage of each. Each chapter covers one widget or other element, contains the most important recommendation from the Macintosh, Windows and Motif style guides, notes about common problems, comparison with other widgets that can serve some of the same roles as this one, etc.

(Read more or buy it.)

Macintosh Human Interface Guidelines, second edition, ISBN 0-201-62216-5, is worth buying for the don'ts alone. Even though you're not writing Macintosh software, avoiding most of what it advises against will produce more easily comprehensible software. Doing what it tells you to do helps, too. (Read more or buy it.)

This book is now available on the web and there is a Mac OS 8 addendum.

The Microsoft Windows User Experience, ISBN 1-55615-679-0, is Microsoft's look and feel Bible. Indispensable for everyone who has customers that worship Microsoft, and it's quite good, too. (Read more or buy it.)

Microsoft's guidelines are often available on the web, but have occasionally been hidden in an impenetrable maze of javascript. Try and see.

The Icon Book by William Horton, ISBN 0-471-59900-X, is a perhaps the only thorough coverage of icons and icon use in software. In order for icons to be successful, people must be able to do four things with them: decode, recognize, find and activate them. This book explains these goals from scratch and how to reach them, both with single icons and icon families. Some 500 examples are scattered throughout the text, generally in groups of four or five. (Read more or buy it.)

Buying these books from Amazon.com.

These books are made available in association with Amazon.com, our favorite on-line bookstore. Here is more information about Amazon.com's shipping options and its customer service. When you buy a book by following one of these links, Amazon.com gives about 15% of the purchase price to Amnesty International.


Hello, World

This example brings up the words "Hello, World" moving up and down, and in different colors.

Header file:

/****************************************************************************
** $Id:  qt/hello.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef HELLO_H
#define HELLO_H

#include <qwidget.h>

class Hello : public QWidget
{
    Q_OBJECT
public:
    Hello( const char *text, QWidget *parent=0, const char *name=0 );
signals:
    void clicked();
protected:
    void mouseReleaseEvent( QMouseEvent * );
    void paintEvent( QPaintEvent * );
private slots:
    void animate();
private:
    QString t;
    int     b;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/hello.cpp   3.0.5   edited May 7 17:30 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "hello.h"
#include <qpushbutton.h>
#include <qtimer.h>
#include <qpainter.h>
#include <qpixmap.h>

/*
  Constructs a Hello widget. Starts a 40 ms animation timer.
*/

Hello::Hello( const char *text, QWidget *parent, const char *name )
    : QWidget(parent,name), t(text), b(0)
{
    QTimer *timer = new QTimer(this);
    connect( timer, SIGNAL(timeout()), SLOT(animate()) );
    timer->start( 40 );

    resize( 260, 130 );
}

/*
  This private slot is called each time the timer fires.
*/

void Hello::animate()
{
    b = (b + 1) & 15;
    repaint( FALSE );
}

/*
  Handles mouse button release events for the Hello widget.

  We emit the clicked() signal when the mouse is released inside
  the widget.
*/

void Hello::mouseReleaseEvent( QMouseEvent *e )
{
    if ( rect().contains( e->pos() ) )
        emit clicked();
}

/*
  Handles paint events for the Hello widget.

  Flicker-free update. The text is first drawn in the pixmap and the
  pixmap is then blt'ed to the screen.
*/

void Hello::paintEvent( QPaintEvent * )
{
    static int sin_tbl[16] = {
        0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38};

    if ( t.isEmpty() )
        return;

    // 1: Compute some sizes, positions etc.
    QFontMetrics fm = fontMetrics();
    int w = fm.width(t) + 20;
    int h = fm.height() * 2;
    int pmx = width()/2 - w/2;
    int pmy = height()/2 - h/2;

    // 2: Create the pixmap and fill it with the widget's background
    QPixmap pm( w, h );
    pm.fill( this, pmx, pmy );

    // 3: Paint the pixmap. Cool wave effect
    QPainter p;
    int x = 10;
    int y = h/2 + fm.descent();
    int i = 0;
    p.begin( &pm );
    p.setFont( font() );
    while ( !t[i].isNull() ) {
        int i16 = (b+i) & 15;
        p.setPen( QColor((15-i16)*16,255,255,QColor::Hsv) );
        p.drawText( x, y-sin_tbl[i16]*h/800, t.mid(i,1), 1 );
        x += fm.width( t[i] );
        i++;
    }
    p.end();

    // 4: Copy the pixmap to the Hello widget
    bitBlt( this, pmx, pmy, &pm );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "hello.h"
#include <qapplication.h>

/*
  The program starts here. It parses the command line and builds a message
  string to be displayed by the Hello widget.
*/

int main( int argc, char **argv )
{
    QApplication a(argc,argv);
    QString s;
    for ( int i=1; i<argc; i++ ) {
        s += argv[i];
        if ( i<argc-1 )
            s += " ";
    }
    if ( s.isEmpty() )
        s = "Hello, World";
    Hello h( s );
#ifndef QT_NO_WIDGET_TOPEXTRA   // for Qt/Embedded minimal build
    h.setCaption( "Qt says hello" );
#endif
    QObject::connect( &h, SIGNAL(clicked()), &a, SLOT(quit()) );
    h.setFont( QFont("times",32,QFont::Bold) );         // default font
    h.setBackgroundColor( Qt::white );                  // default bg color
    a.setMainWidget( &h );
    h.show();
    return a.exec();
}

See also Examples.


Simple HTML Help Browser

This example implements a simple HTML help browser using Qt's richtext capabilities.

Header file:

/****************************************************************************
** $Id:  qt/helpwindow.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef HELPWINDOW_H
#define HELPWINDOW_H

#include <qmainwindow.h>
#include <qtextbrowser.h>
#include <qstringlist.h>
#include <qmap.h>
#include <qdir.h>

class QComboBox;
class QPopupMenu;

class HelpWindow : public QMainWindow
{
    Q_OBJECT
public:
    HelpWindow( const QString& home_,  const QString& path, QWidget* parent = 0, const char *name=0 );
    ~HelpWindow();

private slots:
    void setBackwardAvailable( bool );
    void setForwardAvailable( bool );

    void textChanged();
    void about();
    void aboutQt();
    void openFile();
    void newWindow();
    void print();

    void pathSelected( const QString & );
    void histChosen( int );
    void bookmChosen( int );
    void addBookmark();

private:
    void readHistory();
    void readBookmarks();

    QTextBrowser* browser;
    QComboBox *pathCombo;
    int backwardId, forwardId;
    QString selectedURL;
    QStringList history, bookmarks;
    QMap<int, QString> mHistory, mBookmarks;
    QPopupMenu *hist, *bookm;

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/helpwindow.cpp   3.0.5   edited May 27 19:35 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "helpwindow.h"
#include <qstatusbar.h>
#include <qpixmap.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qiconset.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qstylesheet.h>
#include <qmessagebox.h>
#include <qfiledialog.h>
#include <qapplication.h>
#include <qcombobox.h>
#include <qevent.h>
#include <qlineedit.h>
#include <qobjectlist.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qdatastream.h>
#include <qprinter.h>
#include <qsimplerichtext.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>

#include <ctype.h>

HelpWindow::HelpWindow( const QString& home_, const QString& _path,
                        QWidget* parent, const char *name )
    : QMainWindow( parent, name, WDestructiveClose ),
      pathCombo( 0 ), selectedURL()
{
    readHistory();
    readBookmarks();

    browser = new QTextBrowser( this );

    browser->mimeSourceFactory()->setFilePath( _path );
    browser->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    connect( browser, SIGNAL( textChanged() ),
             this, SLOT( textChanged() ) );

    setCentralWidget( browser );

    if ( !home_.isEmpty() )
        browser->setSource( home_ );

    connect( browser, SIGNAL( highlighted( const QString&) ),
             statusBar(), SLOT( message( const QString&)) );

    resize( 640,700 );

    QPopupMenu* file = new QPopupMenu( this );
    file->insertItem( tr("&New Window"), this, SLOT( newWindow() ), CTRL+Key_N );
    file->insertItem( tr("&Open File"), this, SLOT( openFile() ), CTRL+Key_O );
    file->insertItem( tr("&Print"), this, SLOT( print() ), CTRL+Key_P );
    file->insertSeparator();
    file->insertItem( tr("&Close"), this, SLOT( close() ), CTRL+Key_Q );
    file->insertItem( tr("E&xit"), qApp, SLOT( closeAllWindows() ), CTRL+Key_X );

    // The same three icons are used twice each.
    QIconSet icon_back( QPixmap("back.xpm") );
    QIconSet icon_forward( QPixmap("forward.xpm") );
    QIconSet icon_home( QPixmap("home.xpm") );

    QPopupMenu* go = new QPopupMenu( this );
    backwardId = go->insertItem( icon_back,
                                 tr("&Backward"), browser, SLOT( backward() ),
                                 CTRL+Key_Left );
    forwardId = go->insertItem( icon_forward,
                                tr("&Forward"), browser, SLOT( forward() ),
                                CTRL+Key_Right );
    go->insertItem( icon_home, tr("&Home"), browser, SLOT( home() ) );

    QPopupMenu* help = new QPopupMenu( this );
    help->insertItem( tr("&About ..."), this, SLOT( about() ) );
    help->insertItem( tr("About &Qt ..."), this, SLOT( aboutQt() ) );

    hist = new QPopupMenu( this );
    QStringList::Iterator it = history.begin();
    for ( ; it != history.end(); ++it )
        mHistory[ hist->insertItem( *it ) ] = *it;
    connect( hist, SIGNAL( activated( int ) ),
             this, SLOT( histChosen( int ) ) );

    bookm = new QPopupMenu( this );
    bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) );
    bookm->insertSeparator();

    QStringList::Iterator it2 = bookmarks.begin();
    for ( ; it2 != bookmarks.end(); ++it2 )
        mBookmarks[ bookm->insertItem( *it2 ) ] = *it2;
    connect( bookm, SIGNAL( activated( int ) ),
             this, SLOT( bookmChosen( int ) ) );

    menuBar()->insertItem( tr("&File"), file );
    menuBar()->insertItem( tr("&Go"), go );
    menuBar()->insertItem( tr( "History" ), hist );
    menuBar()->insertItem( tr( "Bookmarks" ), bookm );
    menuBar()->insertSeparator();
    menuBar()->insertItem( tr("&Help"), help );

    menuBar()->setItemEnabled( forwardId, FALSE);
    menuBar()->setItemEnabled( backwardId, FALSE);
    connect( browser, SIGNAL( backwardAvailable( bool ) ),
             this, SLOT( setBackwardAvailable( bool ) ) );
    connect( browser, SIGNAL( forwardAvailable( bool ) ),
             this, SLOT( setForwardAvailable( bool ) ) );

    QToolBar* toolbar = new QToolBar( this );
    addToolBar( toolbar, "Toolbar");
    QToolButton* button;

    button = new QToolButton( icon_back, tr("Backward"), "", browser, SLOT(backward()), toolbar );
    connect( browser, SIGNAL( backwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) );
    button->setEnabled( FALSE );
    button = new QToolButton( icon_forward, tr("Forward"), "", browser, SLOT(forward()), toolbar );
    connect( browser, SIGNAL( forwardAvailable(bool) ), button, SLOT( setEnabled(bool) ) );
    button->setEnabled( FALSE );
    button = new QToolButton( icon_home, tr("Home"), "", browser, SLOT(home()), toolbar );

    toolbar->addSeparator();

    pathCombo = new QComboBox( TRUE, toolbar );
    connect( pathCombo, SIGNAL( activated( const QString & ) ),
             this, SLOT( pathSelected( const QString & ) ) );
    toolbar->setStretchableWidget( pathCombo );
    setRightJustification( TRUE );
    setDockEnabled( DockLeft, FALSE );
    setDockEnabled( DockRight, FALSE );

    pathCombo->insertItem( home_ );
    browser->setFocus();

}

void HelpWindow::setBackwardAvailable( bool b)
{
    menuBar()->setItemEnabled( backwardId, b);
}

void HelpWindow::setForwardAvailable( bool b)
{
    menuBar()->setItemEnabled( forwardId, b);
}

void HelpWindow::textChanged()
{
    if ( browser->documentTitle().isNull() )
        setCaption( "Qt Example - Helpviewer - " + browser->context() );
    else
        setCaption( "Qt Example - Helpviewer - " + browser->documentTitle() ) ;

    selectedURL = browser->context();

    if ( !selectedURL.isEmpty() && pathCombo ) {
        bool exists = FALSE;
        int i;
        for ( i = 0; i < pathCombo->count(); ++i ) {
            if ( pathCombo->text( i ) == selectedURL ) {
                exists = TRUE;
                break;
            }
        }
        if ( !exists ) {
            pathCombo->insertItem( selectedURL, 0 );
            pathCombo->setCurrentItem( 0 );
            mHistory[ hist->insertItem( selectedURL ) ] = selectedURL;
        } else
            pathCombo->setCurrentItem( i );
        selectedURL = QString::null;
    }
}

HelpWindow::~HelpWindow()
{
    history.clear();
    QMap<int, QString>::Iterator it = mHistory.begin();
    for ( ; it != mHistory.end(); ++it )
        history.append( *it );

    QFile f( QDir::currentDirPath() + "/.history" );
    f.open( IO_WriteOnly );
    QDataStream s( &f );
    s << history;
    f.close();

    bookmarks.clear();
    QMap<int, QString>::Iterator it2 = mBookmarks.begin();
    for ( ; it2 != mBookmarks.end(); ++it2 )
        bookmarks.append( *it2 );

    QFile f2( QDir::currentDirPath() + "/.bookmarks" );
    f2.open( IO_WriteOnly );
    QDataStream s2( &f2 );
    s2 << bookmarks;
    f2.close();
}

void HelpWindow::about()
{
    QMessageBox::about( this, "HelpViewer Example",
                        "<p>This example implements a simple HTML help viewer "
                        "using Qt's rich text capabilities</p>"
                        "<p>It's just about 100 lines of C++ code, so don't expect too much :-)</p>"
                        );
}

void HelpWindow::aboutQt()
{
    QMessageBox::aboutQt( this, "QBrowser" );
}

void HelpWindow::openFile()
{
#ifndef QT_NO_FILEDIALOG
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() )
        browser->setSource( fn );
#endif
}

void HelpWindow::newWindow()
{
    ( new HelpWindow(browser->source(), "qbrowser") )->show();
}

void HelpWindow::print()
{
#ifndef QT_NO_PRINTER
    QPrinter printer;
    printer.setFullPage(TRUE);
    if ( printer.setup( this ) ) {
        QPainter p( &printer );
        QPaintDeviceMetrics metrics(p.device());
        int dpix = metrics.logicalDpiX();
        int dpiy = metrics.logicalDpiY();
        const int margin = 72; // pt
        QRect body(margin*dpix/72, margin*dpiy/72,
                   metrics.width()-margin*dpix/72*2,
                   metrics.height()-margin*dpiy/72*2 );
        QFont font( "times", 10 );
        QSimpleRichText richText( browser->text(), font,
                                  browser->context(),
                                  browser->styleSheet(),
                                  browser->mimeSourceFactory(),
                                  body.height() );
        richText.setWidth( &p, body.width() );
        QRect view( body );
        int page = 1;
        do {
            richText.draw( &p, body.left(), body.top(), view, colorGroup() );
            view.moveBy( 0, body.height() );
            p.translate( 0 , -body.height() );
            p.setFont( font );
            p.drawText( view.right() - p.fontMetrics().width( QString::number(page) ),
                        view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page) );
            if ( view.top()  >= body.top() + richText.height() )
                break;
            printer.newPage();
            page++;
        } while (TRUE);
    }
#endif
}

void HelpWindow::pathSelected( const QString &_path )
{
    browser->setSource( _path );
    QMap<int, QString>::Iterator it = mHistory.begin();
    bool exists = FALSE;
    for ( ; it != mHistory.end(); ++it ) {
        if ( *it == _path ) {
            exists = TRUE;
            break;
        }
    }
    if ( !exists )
        mHistory[ hist->insertItem( _path ) ] = _path;
}

void HelpWindow::readHistory()
{
    if ( QFile::exists( QDir::currentDirPath() + "/.history" ) ) {
        QFile f( QDir::currentDirPath() + "/.history" );
        f.open( IO_ReadOnly );
        QDataStream s( &f );
        s >> history;
        f.close();
        while ( history.count() > 20 )
            history.remove( history.begin() );
    }
}

void HelpWindow::readBookmarks()
{
    if ( QFile::exists( QDir::currentDirPath() + "/.bookmarks" ) ) {
        QFile f( QDir::currentDirPath() + "/.bookmarks" );
        f.open( IO_ReadOnly );
        QDataStream s( &f );
        s >> bookmarks;
        f.close();
    }
}

void HelpWindow::histChosen( int i )
{
    if ( mHistory.contains( i ) )
        browser->setSource( mHistory[ i ] );
}

void HelpWindow::bookmChosen( int i )
{
    if ( mBookmarks.contains( i ) )
        browser->setSource( mBookmarks[ i ] );
}

void HelpWindow::addBookmark()
{
    mBookmarks[ bookm->insertItem( caption() ) ] = browser->context();
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "helpwindow.h"
#include <qapplication.h>
#include <qwindowsstyle.h>
#include <qstylesheet.h>
#include <stdlib.h>

int main( int argc, char ** argv )
{
    QApplication::setColorSpec( QApplication::ManyColor );
    QApplication a(argc, argv);

    QString home;
    if (argc > 1)
        home = argv[1];
    else
        home = QString(getenv("QTDIR")) + "/doc/html/index.html";

    HelpWindow *help = new HelpWindow(home, ".", 0, "help viewer");
    help->setCaption("Qt Example - Helpviewer");
    if ( QApplication::desktop()->width() > 400
         && QApplication::desktop()->height() > 500 )
        help->show();
    else
        help->showMaximized();

    QObject::connect( &a, SIGNAL(lastWindowClosed()),
                      &a, SLOT(quit()) );

    return a.exec();
}

See also Examples.


A simple HTTP daemon

This example shows how to use the QServerSocket class. It is a very simple implementation of a HTTP daemon that listens on port 8080 and sends back a simple HTML page back for every GET request it gets. After sending the page, it closes the connection.

Implementation (httpd.cpp):

/****************************************************************************
** $Id:  qt/httpd.cpp   3.0.5   edited Nov 6 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include <stdlib.h>
#include <qsocket.h>
#include <qregexp.h>
#include <qserversocket.h>
#include <qapplication.h>
#include <qmainwindow.h>
#include <qtextstream.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qtextview.h>
#include <qpushbutton.h>

// HttpDaemon is the the class that implements the simple HTTP server.
class HttpDaemon : public QServerSocket
{
    Q_OBJECT
public:
    HttpDaemon( QObject* parent=0 ) :
        QServerSocket(8080,1,parent)
    {
        if ( !ok() ) {
            qWarning("Failed to bind to port 8080");
            exit( 1 );
        }
    }

    void newConnection( int socket )
    {
        // When a new client connects, the server constructs a QSocket and all
        // communication with the client is done over this QSocket. QSocket
        // works asynchronouslyl, this means that all the communication is done
        // in the two slots readClient() and discardClient().
        QSocket* s = new QSocket( this );
        connect( s, SIGNAL(readyRead()), this, SLOT(readClient()) );
        connect( s, SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
        s->setSocket( socket );
        emit newConnect();
    }

signals:
    void newConnect();
    void endConnect();
    void wroteToClient();

private slots:
    void readClient()
    {
        // This slot is called when the client sent data to the server. The
        // server looks if it was a get request and sends a very simple HTML
        // document back.
        QSocket* socket = (QSocket*)sender();
        if ( socket->canReadLine() ) {
            QStringList tokens = QStringList::split( QRegExp("[ \n\r][ \n\r]*"), socket->readLine() );
            if ( tokens[0] == "GET" ) {
                QTextStream os( socket );
                os.setEncoding( QTextStream::UnicodeUTF8 );
                os << "HTTP/1.0 200 Ok\n\r"
                    "Content-Type: text/html; charset=\"utf-8\"\n\r"
                    "\n\r"
                    "<h1>Nothing to see here</h1>\n";
                socket->close();
                emit wroteToClient();
            }
        }
    }
    void discardClient()
    {
        QSocket* socket = (QSocket*)sender();
        delete socket;
        emit endConnect();
    }
};

// HttpInfo provides a simple graphical user interface to the server and shows
// the actions of the server.
class HttpInfo : public QVBox
{
    Q_OBJECT
public:
    HttpInfo()
    {
        HttpDaemon *httpd = new HttpDaemon( this );

        QString itext = QString(
                "This is a small httpd example.\n"
                "You can connect with your\n"
                "web browser to port %1"
            ).arg( httpd->port() );
        QLabel *lb = new QLabel( itext, this );
        lb->setAlignment( AlignHCenter );
        infoText = new QTextView( this );
        QPushButton *quit = new QPushButton( "quit" , this );

        connect( httpd, SIGNAL(newConnect()), SLOT(newConnect()) );
        connect( httpd, SIGNAL(endConnect()), SLOT(endConnect()) );
        connect( httpd, SIGNAL(wroteToClient()), SLOT(wroteToClient()) );
        connect( quit, SIGNAL(pressed()), qApp, SLOT(quit()) );
    }

    ~HttpInfo()
    {
    }

private slots:
    void newConnect()
    {
        infoText->append( "New connection" );
    }
    void endConnect()
    {
        infoText->append( "Connection closed\n\n" );
    }
    void wroteToClient()
    {
        infoText->append( "Wrote to client" );
    }

private:
    QTextView *infoText;
};

int main( int argc, char** argv )
{
    QApplication app( argc, argv );
    HttpInfo info;
    app.setMainWidget( &info );
    info.show();
    return app.exec();
}

#include "httpd.moc"

See also Network Examples.


Internationalization

This example shows how to internationalize applications. Start it with

# i18n de

to get a german version and with

# i18n en

to get the english version.

Refer also to the internationalization documentation.

Header file:

/****************************************************************************
** $Id:  qt/mywidget.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <qmainwindow.h>
#include <qstring.h>

class MyWidget : public QMainWindow
{
    Q_OBJECT

public:
    MyWidget( QWidget* parent=0, const char* name = 0 );

signals:
    void closed();

protected:
    void closeEvent(QCloseEvent*);

private:
    static void initChoices(QWidget* parent);
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/mywidget.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qlabel.h>
#include <qlistbox.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qaccel.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qstatusbar.h>
#include <qapplication.h>

#include "mywidget.h"

MyWidget::MyWidget( QWidget* parent, const char* name )
        : QMainWindow( parent, name )
{
    QVBox* central = new QVBox(this);
    central->setMargin( 5 );
    central->setSpacing( 5 );
    setCentralWidget(central);

    QPopupMenu* file = new QPopupMenu(this);
    file->insertItem( tr("E&xit"), qApp, SLOT(quit()),
            QAccel::stringToKey(tr("Ctrl+Q")) );
    menuBar()->insertItem( tr("&File"), file );

    setCaption( tr( "Internationalization Example" ) );

    QString l;
    statusBar()->message( tr("Language: English") );

    ( void )new QLabel( tr( "The Main Window" ), central );

    QButtonGroup* gbox = new QButtonGroup( 1, QGroupBox::Horizontal,
                                      tr( "View" ), central );
    (void)new QRadioButton( tr( "Perspective" ), gbox );
    (void)new QRadioButton( tr( "Isometric" ), gbox );
    (void)new QRadioButton( tr( "Oblique" ), gbox );

    initChoices(central);
}

static const char* choices[] = {
    QT_TRANSLATE_NOOP( "MyWidget", "First" ),
    QT_TRANSLATE_NOOP( "MyWidget", "Second" ),
    QT_TRANSLATE_NOOP( "MyWidget", "Third" ),
    0
};

void MyWidget::initChoices(QWidget* parent)
{
    QListBox* lb = new QListBox( parent );
    for ( int i = 0; choices[i]; i++ )
        lb->insertItem( tr( choices[i] ) );
}

void MyWidget::closeEvent(QCloseEvent* e)
{
    QWidget::closeEvent(e);
    emit closed();
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Dec 6 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qtranslator.h>
#include <qfileinfo.h>
#include <qmessagebox.h>
#include <qcheckbox.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qbuttongroup.h>
#include <qpushbutton.h>
#include <qsignalmapper.h>
#include <qtextcodec.h>
#include <stdlib.h>

#if defined(Q_OS_UNIX)
#include <unistd.h>
#endif

#include "mywidget.h"

//#define USE_I18N_FONT

class QVDialog : public QDialog {
public:
    QVDialog(QWidget *parent=0, const char *name=0, bool modal=FALSE,
             WFlags f=0) : QDialog(parent,name,modal,f)
    {
        QVBoxLayout* vb = new QVBoxLayout(this,8);
        vb->setAutoAdd(TRUE);
        hb = 0;
        sm = new QSignalMapper(this);
        connect(sm,SIGNAL(mapped(int)),this,SLOT(done(int)));
    }
    void addButtons( const QString& cancel=QString::null,
                    const QString& ok=QString::null,
                    const QString& mid1=QString::null,
                    const QString& mid2=QString::null,
                    const QString& mid3=QString::null)
    {
        addButton(ok.isNull() ? tr("OK") : ok, 1);
        if ( !mid1.isNull() ) addButton(mid1,2);
        if ( !mid2.isNull() ) addButton(mid2,3);
        if ( !mid3.isNull() ) addButton(mid3,4);
        addButton(cancel.isNull() ? tr("Cancel") : cancel, 0);
    }

    void addButton( const QString& text, int result )
    {
        if ( !hb )
            hb = new QHBox(this);
        QPushButton *c = new QPushButton(text, hb);
        sm->setMapping(c,result);
        connect(c,SIGNAL(clicked()),sm,SLOT(map()));
    }

private:
    QSignalMapper *sm;
    QHBox *hb;
};

MyWidget* showLang(QString lang)
{

    static QTranslator *translator = 0;

    qApp->setPalette(QPalette(QColor(220-rand()%64,220-rand()%64,220-rand()%64)));

    lang = "mywidget_" + lang + ".qm";
    QFileInfo fi( lang );

    if ( !fi.exists() ) {
        QMessageBox::warning( 0, "File error",
                              QString("Cannot find translation for language: "+lang+
                                      "\n(try eg. 'de', 'ko' or 'no')") );
        return 0;
    }
    if ( translator ) {
        qApp->removeTranslator( translator );
        delete translator;
    }
    translator = new QTranslator( 0 );
    translator->load( lang, "." );
    qApp->installTranslator( translator );
    MyWidget *m = new MyWidget;
    m->setCaption("Qt Example - i18n - " + m->caption() );
    return m;
}

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

    const char* qm[]=
        { "cs", "de", "el", "en", "eo", "fr", "it", "jp", "ko", "no", "ru", "zh", 0 };

#if defined(Q_OS_UNIX)
    srand( getpid() << 2 );
#endif

    QString lang;
    if ( argc == 2 )
        lang = argv[1];

    if ( argc != 2 || lang == "all" ) {
        QVDialog dlg(0,0,TRUE);
        QCheckBox* qmb[sizeof(qm)/sizeof(qm[0])];
        int r;
        if ( lang == "all" ) {
            r = 2;
        } else {
            QButtonGroup *bg = new QButtonGroup(4,Qt::Vertical,"Choose Locales",&dlg);
            QString loc = QTextCodec::locale();
            for ( int i=0; qm[i]; i++ ) {
                qmb[i] = new QCheckBox((const char*)qm[i],bg);
                qmb[i]->setChecked( loc == qm[i] );
            }
            dlg.addButtons("Cancel","OK","All");
            r = dlg.exec();
        }
        if ( r ) {
            bool tight = qApp->desktop()->screen()->width() < 1024;
            int x=5;
            int y=25;
            for ( int i=0; qm[i]; i++ ) {
                if ( r == 2 || qmb[i]->isChecked() ) {
                    MyWidget* w = showLang((const char*)qm[i]);

                    if( w == 0 ) exit( 0 );
                    QObject::connect(w, SIGNAL(closed()), qApp, SLOT(quit()));
                    w->setGeometry(x,y,197,356);
                    w->show();
                    if ( tight ) {
                        x += 8;
                        y += 8;
                    } else {
                        x += 205;
                        if ( x > 1000 ) {
                            x = 5;
                            y += 384;
                        }
                    }
                }
            }
        } else {
            exit( 0 );
        }
    } else {
        QString lang = argv[1];
        QWidget* m = showLang(lang);
        app.setMainWidget( m );
        m->setCaption("Qt Example - i18n");
        m->show();
    }

#ifdef USE_I18N_FONT
    memorymanager->savePrerenderedFont(font.handle(),FALSE);
#endif

    // While we run "all", kill them all
    return app.exec();

}

See also Examples.


Iconview

This example implements a flexible icon view which can store lots of icon items. It supports Drag&Drop, different selection modes, view modes, rubberband selection, etc.

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Nov 13 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qiconview.h>
#include <qapplication.h>
#include <qdragobject.h>
#include <qpixmap.h>
#include <qiconset.h>

#include <qmime.h>
#include <stdio.h>

class ListenDND : public QObject
{
    Q_OBJECT

public:
    ListenDND( QWidget *w )
        : view( w )
    {}

public slots:
    void dropped( QDropEvent *mime ) {
        qDebug( "Dropped Mimesource %p into the view %p", mime, view );
        qDebug( "  Formats:" );
        int i = 0;
        const char *str = mime->format( i );
        qDebug( "    %s", str );
        while ( str ) {
            qDebug( "    %s", str );
            str = mime->format( ++i );
        }
    };
    void moved() {
        qDebug( "All selected items were moved to another widget" );
    }

protected:
    QWidget *view;

};

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

    QIconView qiconview;
    qiconview.setSelectionMode( QIconView::Extended );

    for ( unsigned int i = 0; i < 3000; i++ ) {
        QIconViewItem *item = new QIconViewItem( &qiconview, QString( "Item %1" ).arg( i + 1 ) );
        item->setRenameEnabled( TRUE );
    }

    qiconview.setCaption( "Qt Example - Iconview" );

    ListenDND listen_dnd( &qiconview );
    QObject::connect( &qiconview, SIGNAL( dropped( QDropEvent *, const QValueList<QIconDragItem> & ) ),
                      &listen_dnd, SLOT( dropped( QDropEvent * ) ) );
    QObject::connect( &qiconview, SIGNAL( moved() ), &listen_dnd, SLOT( moved() ) );

    a.setMainWidget( &qiconview );
    qiconview.show();
    qiconview.resize( qiconview.sizeHint() );

    return a.exec();
}

#include "main.moc"

See also Examples.


iconview/simple_dd/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"

const char* red_icon[]={
"16 16 2 1",
"r c red",
". c None",
"................",
"................",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"................",
"................"};

const char* blue_icon[]={
"16 16 2 1",
"b c blue",
". c None",
"................",
"................",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"................",
"................"};

const char* green_icon[]={
"16 16 2 1",
"g c green",
". c None",
"................",
"................",
"..gggggggggggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"................",
"................"};

// ListBox -- low level drag and drop

DDListBox::DDListBox( QWidget * parent, const char * name, WFlags f ) :
    QListBox( parent, name, f )
{
    setAcceptDrops( TRUE );
    dragging = FALSE;
}

void DDListBox::dragEnterEvent( QDragEnterEvent *evt )
{
    if ( QTextDrag::canDecode( evt ) )
        evt->accept();
}

void DDListBox::dropEvent( QDropEvent *evt )
{
    QString text;

    if ( QTextDrag::decode( evt, text ) )
        insertItem( text );
}

void DDListBox::mousePressEvent( QMouseEvent *evt )
{
    QListBox::mousePressEvent( evt );
    dragging = TRUE;
}

void DDListBox::mouseMoveEvent( QMouseEvent * )
{
    if ( dragging ) {
        QDragObject *d = new QTextDrag( currentText(), this );
        d->dragCopy(); // do NOT delete d.
        dragging = FALSE;
    }
}

// IconViewIcon -- high level drag and drop

bool DDIconViewItem::acceptDrop( const QMimeSource *mime ) const
{
    if ( mime->provides( "text/plain" ) )
        return TRUE;
    return FALSE;
}

void DDIconViewItem::dropped( QDropEvent *evt, const QValueList<QIconDragItem>& )
{
    QString label;

    if ( QTextDrag::decode( evt, label ) )
        setText( label );
}

// IconView -- high level drag and drop

QDragObject *DDIconView::dragObject()
{
  return new QTextDrag( currentItem()->text(), this );
}

void DDIconView::slotNewItem( QDropEvent *evt, const QValueList<QIconDragItem>& )
{
    QString label;

    if ( QTextDrag::decode( evt, label ) ) {
        DDIconViewItem *item = new DDIconViewItem( this, label );
        item->setRenameEnabled( TRUE );
    }
}

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

    // Create and show the widgets
    QSplitter *split = new QSplitter();
    DDIconView *iv   = new DDIconView( split );
    (void)             new DDListBox( split );
    app.setMainWidget( split );
    split->resize( 600, 400 );
    split->show();

    // Set up the connection so that we can drop items into the icon view
    QObject::connect(
        iv, SIGNAL(dropped(QDropEvent*, const QValueList<QIconDragItem>&)),
        iv, SLOT(slotNewItem(QDropEvent*, const QValueList<QIconDragItem>&)));

    // Populate the QIconView with icons
    DDIconViewItem *item;
    item = new DDIconViewItem( iv, "Red",   QPixmap( red_icon ) );
    item->setRenameEnabled( TRUE );
    item = new DDIconViewItem( iv, "Green", QPixmap( green_icon ) );
    item->setRenameEnabled( TRUE );
    item = new DDIconViewItem( iv, "Blue",  QPixmap( blue_icon ) );
    item->setRenameEnabled( TRUE );

    return app.exec();
}


iconview/simple_dd/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qcursor.h>
#include <qsplitter.h>
#include <qlistbox.h>
#include <qiconview.h>
#include <qpixmap.h>

class QDragEnterEvent;
class QDragDropEvent;

class DDListBox : public QListBox
{
    Q_OBJECT
public:
    DDListBox( QWidget * parent = 0, const char * name = 0, WFlags f = 0 );
    // Low-level drag and drop
    void dragEnterEvent( QDragEnterEvent *evt );
    void dropEvent( QDropEvent *evt );
    void mousePressEvent( QMouseEvent *evt );
    void mouseMoveEvent( QMouseEvent * );
private:
    int dragging;
};

class DDIconViewItem : public QIconViewItem
{
public:
    DDIconViewItem( QIconView *parent, const QString& text, const QPixmap& icon ) :
        QIconViewItem( parent, text, icon ) {}
    DDIconViewItem( QIconView *parent, const QString &text ) :
        QIconViewItem( parent, text ) {}
    // High-level drag and drop
    bool acceptDrop( const QMimeSource *mime ) const;
    void dropped( QDropEvent *evt, const QValueList<QIconDragItem>& );
};

class DDIconView : public QIconView
{
    Q_OBJECT
public:
    DDIconView( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) :
        QIconView( parent, name, f ) {}
    // High-level drag and drop
    QDragObject *dragObject();
public slots:
    void slotNewItem( QDropEvent *evt, const QValueList<QIconDragItem>& list );
};


Image Processing Classes

These classes are used for manipulating images.

QBitmap | Monochrome (1-bit depth) pixmaps
QBrush | Defines the fill pattern of shapes drawn by a QPainter
QCanvas | 2D area that can contain QCanvasItem objects
QCanvasEllipse | Ellipse or ellipse segment on a QCanvas
QCanvasItem | Abstract graphic object on a QCanvas
QCanvasItemList | List of QCanvasItems
QCanvasLine | Line on a QCanvas
QCanvasPixmap | Pixmaps for QCanvasSprites
QCanvasPixmapArray | Array of QCanvasPixmaps
QCanvasPolygon | Polygon on a QCanvas
QCanvasPolygonalItem | Polygonal canvas item on a QCanvas
QCanvasRectangle | Rectangle on a QCanvas
QCanvasSpline | Multi-bezier splines on a QCanvas
QCanvasSprite | Animated canvas item on a QCanvas
QCanvasText | Text object on a QCanvas
QCanvasView | On-screen view of a QCanvas
QColor | Colors based on RGB or HSV values
QColorGroup | Group of widget colors
QGL | Namespace for miscellaneous identifiers in the Qt OpenGL module
QGLColormap | Used for installing custom colormaps into QGLWidgets
QGLContext | Encapsulates an OpenGL rendering context
QGLFormat | The display format of an OpenGL rendering context
QGLWidget | Widget for rendering OpenGL graphics
QIconSet | Set of icons with different styles and sizes
QImage | Hardware-independent pixmap representation with direct access to the pixel data
QImageConsumer | Abstraction used by QImageDecoder
QImageDecoder | Incremental image decoder for all supported image formats
QImageFormat | Incremental image decoder for a specific image format
QImageFormatType | Factory that makes QImageFormat objects
QImageIO | Parameters for loading and saving images
QMovie | Incremental loading of animations or images, signalling as it progresses
QPaintDevice | The base class of objects that can be painted
QPaintDeviceMetrics | Information about a paint device
QPainter | Does low-level painting e.g. on widgets
QPalette | Color groups for each widget state
QPen | Defines how a QPainter should draw lines and outlines of shapes
QPicture | Paint device that records and replays QPainter commands
QPixmap | Off-screen, pixel-based paint device
QPixmapCache | Application-global cache for pixmaps
QPNGImagePacker | Creates well-compressed PNG animations
QPoint | Defines a point in the plane
QPointArray | Array of points
QPrinter | Paint device that paints on a printer
QRect | Defines a rectangle in the plane
QRegion | Clip region for a painter
QSize | Defines the size of a two-dimensional object
QWMatrix | 2D transformations of a coordinate system


Input/Output and Networking

These classes are used to handle input and output to and from external devices, processes, files etc. as well as manipulating files and directories.

QBuffer | I/O device that operates on a QByteArray
QClipboard | Access to the window system clipboard
QDataStream | Serialization of binary data to a QIODevice
QDir | Access to directory structures and their contents in a platform-independent way
QDns | Asynchronous DNS lookups
QFile | I/O device that operates on files
QFileInfo | System-independent file information
QFtp | Implementation of the FTP protocol
QHostAddress | IP address
QHttp | Implementation of the HTTP protocol
QImageIO | Parameters for loading and saving images
QIODevice | The base class of I/O devices
QLocalFs | Implementation of a QNetworkProtocol that works on the local file system
QLock | Wrapper for a System V shared semaphore
QMimeSource | Abstraction of objects which provide formatted data of a certain MIME type
QMimeSourceFactory | Extensible provider of mime-typed data
QNetworkOperation | Common operations for network protocols
QNetworkProtocol | Common API for network protocols
QProcess | Used to start external programs and to communicate with them
QServerSocket | TCP-based server
QSettings | Persistent platform-independent application settings
QSignal | Can be used to send signals for classes that don't inherit QObject
QSignalMapper | Bundles signals from identifiable senders
QSocket | Buffered TCP connection
QSocketDevice | Platform-independent low-level socket API
QSocketNotifier | Support for socket callbacks
QTextIStream | Convenience class for input streams
QTextOStream | Convenience class for output streams
QTextStream | Basic functions for reading and writing text using a QIODevice
QUrl | URL parser and simplifies working with URLs
QUrlInfo | Stores information about URLs
QUrlOperator | Common operations on URLs
QWindowsMime | Maps open-standard MIME to Window Clipboard formats


布局类

Qt的布局系统提供了一个规定子窗口部件布局的简单的和强有力的方式。

当你一旦规定了合理的布局，你就会获得如下利益：

  • 布置子窗口部件。
  • 最高层窗口部件可感知的默认大小。
  • 最高层窗口部件可感知的最小大小。
  • 调整大小的处理。
  • 当内容改变的时候自动更新：
    • 字体大小、文本或者子窗口部件的其它内容。
    • 隐藏或者显示子窗口部件。
    • 移去一些子窗口部件。

Qt的布局类使用手写的C++代码设计的，所以它们很容易被理解和使用。

手写的布局代码的不利是当你在试验设计一个视窗并且你不得不为每一个改变进行编译、连接和运行这样一个循环的时候它不是非常方便的。我们的解决方案是Qt设计器，一种可以快速建立和很容易地试验布局和为你生成C++布局代码地图形用户界面可视化设计工具。

布局窗口部件

给你的窗口部件一个好的布局的最好的方法是使用这些布局窗口部件：QHBox，QVBox和QGrid。一个布局窗口部件自已自动地把它们的子窗口部件按照它们被构造地顺序进行布局。为了生成更复杂的布局，你可以嵌入一个布局窗口部件到其它的。

  • 一个QHBox把它的子窗口部件从左到右排列在一个水平的行中。

    Horizontal box with five child widgets

  • 一个QVBox把它的子窗口部件从上到下排列在一个竖直的列中。

    Vertical box with five child widgets

  • 一个QGrid把它的子窗口部件排列在一个二维的网格中。 你可以规定网格可以有多少列，当前面的一行已经排满，它将会从左到右填充新的一行。网格是被确定的，当这个窗口部件被改变大小的时候，它的子窗口部件不会跑到其它的行。

Two-column grid with five child widgets

上述演示的表格是由下面这些代码生成的：

    QGrid *mainGrid = new QGrid( 2 ); // 一个2*n的网格
    new QLabel( "One", mainGrid );
    new QLabel( "Two", mainGrid );
    new QLabel( "Three", mainGrid );
    new QLabel( "Four", mainGrid );
    new QLabel( "Five", mainGrid );

你可以通过对子窗口部件调用QWidget::setMinimumSize()或QWidget::setFixedSize()来调节布局。

QLayout

当你添加一个窗口部件到一个布局中，布局过程工作如下：

  1. 所有的窗口部件将最初根据它们的QWidget::sizePolicy()而被分配到一定空间中。
  2. 如果任何一个窗口部件有一个伸展因素设置，而且数值大于零，那么它们就会被根据它们的伸展因素的比例分配空间。
  3. 如果任何一个窗口部件有一个伸展因素设置而且数值为零，那么只有当其它窗口部件不再需要空间的时候才会得到更多的空间。在这当中，空间会首先被根据延展大小策略分配给窗口部件。
  4. 任何窗口部件被分配的空间的大小如果小于它们的最小大小（或者是在没有规定最小大小时的最小大小的提示），它们就会被按它们所需要的最小大小分配空间。（如果窗口部件的伸展因素是它们的决定因素的情况下，它们不必有最小大小或者最小大小的提示。）
  5. 任何窗口部件被分配的空间的大小如果大于它们的最大大小，它们就会被按它们所需要的最大大小分配空间。（如果窗口部件的伸展因素是它们的决定因素的情况下，它们不必有最大大小。）

伸展因素

窗口部件通常是在没有伸展因素设置的情况下被生成的。当它们被布置到一个布局中时，窗口部件会被根据它们的QWidget::sizePolicy()或者它们的最小大小的提示中大的那一个分配给整个空间的一部分。伸展因素是用来根据窗口部件互相的比例来改变它们所被分配的空间。

如果你使用一个QHBox来布置没有伸展参数设置的三个窗口部件，我们就会得到像下面这样的布局：

3 widgets in a row

如果我们给每个窗口部件设置一个伸展因素，它们就会被按比例布置（但是不能小于最小大小的提示），举例来说：

3 stretch factored widgets in a row

QLayout

如果你需要控制布局，可以使用QLayout的子类。Qt中包括的布局类有QGridLayout和QBoxLayout。（QHBoxLayout和QVBoxLayout是QBoxLayout很简单的子类，它们可以更简单地使用并且使得代码更容易阅读。）

当你使用一个布局，你将不得不把每个子窗口部件不仅放到它们的父窗口部件中（这个已经在构造函数中完成），而且要把它们放到它们的布局中（典型地通过调用addWidget()完成）。这个方法中，你可以对每个窗口部件给出布局参数，规定像对齐方式、伸展因素和位置这样的属性。

下面的代码生成一个和上面的那个网格类似，但有一些改进的网格：

    QWidget *main = new QWidget;

    // 生成一个1*1的网格；它可以自动展开
    QGridLayout *grid = new QGridLayout( main, 1, 1 );

    // 根据(行, 列)编址来添加前四个窗口部件
    grid->addWidget( new QLabel( "One", main ), 0, 0 );
    grid->addWidget( new QLabel( "Two", main ), 0, 1 );
    grid->addWidget( new QLabel( "Three", main ), 1, 0 );
    grid->addWidget( new QLabel( "Four", main ), 1, 1 );

    // 添加最后一个窗口部件到第2行，并占用第0列和第1列，中间对齐
    grid->addMultiCellWidget( new QLabel( "Five", main ), 2, 2, 0, 1,
                              Qt::AlignCenter );

    // 设置第0列和第1列的宽度比例为2:3
    grid->setColStretch( 0, 2 );
    grid->setColStretch( 1, 3 );

你可以通过把父布局作为子布局构造函数的一个参数来把布局添加到另一个布局中。

    QWidget *main = new QWidget;
    QLineEdit *field = new QLineEdit( main );
    QPushButton *ok = new QPushButton( "OK", main );
    QPushButton *cancel = new QPushButton( "Cancel", main );
    QLabel *label = new QLabel( "Write once, compile everywhere.", main );

    // 一个窗口部件中的布局
    QVBoxLayout *vbox = new QVBoxLayout( main );
    vbox->addWidget( label );
    vbox->addWidget( field );

    // 一个布局中的布局
    QHBoxLayout *buttons = new QHBoxLayout( vbox );
    buttons->addWidget( ok );
    buttons->addWidget( cancel );
如果你对默认位置感到不满意，你可以不使用父布局参数来生成一个布局然后通过调用addLayout()把这个布局插入到其它布局中。

自定义布局

如果内置的布局类不够充分的话，你可以定义你自己的布局类。你必须创建QLayout的一个子类来处理重新定义大小和大小的计算，也可以使用QGLayoutIterator的子类来迭代你的布局类。

如果需要更深的描述，请看Custom Layout页。

在布局中自定义窗口部件

当你创建自己的窗口部件类的时候，你也应该传递它的布局属性。如果这个窗口部件有一个QLayout，这样的话就已经被处理了。如果这个窗口部件不包括任何子窗口部件，或者使用自定义布局，你需要重新实现下面这些QWidget的成员函数：

  • QWidget::sizeHint()返回窗口部件的优先选用的大小。
  • QWidget::minimumSizeHint()返回窗口部件所能有的最小大小。
  • QWidget::sizePolicy()返回一个QSizePolicy；这个值描述的是这个窗口部件所需要的空间。

只要大小提示、最小大小提示或者大小策略发生改变，都要调用QWidget::updateGeometry()。这会引起布局的重新计算。对updateGeometry()的多重调用只会引起一次重新计算。

如果你的窗口部件的优先选用的高度依赖于它的实际宽度（比如一个自动断词的标签），在sizePolicy()中设置hasHeightForWidth()标记，并且重新实现QWidget::heightForWidth()。

即使你实现了heightForWidth()，提供一个好的sizeHint()仍然是必需的。sizeHint()提供了窗口部件的优先选用的宽度，并且它经常被不支持heightForWidth()的QLayout的子类使用（QGridLayout和QBoxLayout都支持）。

当你实现这些函数并想获得更多的制导的时候，请查看和你的新窗口部件所需要的布局存在于Qt类中最接近的布局的实现。

人工布局

如果你要生成一种特殊的布局，你也可以按上面的描述来生成一个自定义窗口部件。重新实现QWidget::resizeEvent()来计算所需要分配的大小并且给每一个子窗口部件调用setGeometry()。

当布局需要重新计算的时候，窗口部件会得到一个类型是LayoutHint的事件。重新实现被通知LayoutHint事件的QWidget::event()。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Layout Managers

This example shows simple and intermediate use of Qt's layout classes, QGridLayout, QBoxLayout etc.

Implementation:

/****************************************************************************
** $Id:  qt/layout.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qlabel.h>
#include <qcolor.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qmultilineedit.h>
#include <qmenubar.h>
#include <qpopupmenu.h>

class ExampleWidget : public QWidget
{
public:
    ExampleWidget( QWidget *parent = 0, const char *name = 0 );
    ~ExampleWidget();
};

ExampleWidget::ExampleWidget( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    // Make the top-level layout; a vertical box to contain all widgets
    // and sub-layouts.
    QBoxLayout *topLayout = new QVBoxLayout( this, 5 );

    // Create a menubar...
    QMenuBar *menubar = new QMenuBar( this );
    menubar->setSeparator( QMenuBar::InWindowsStyle );
    QPopupMenu* popup;
    popup = new QPopupMenu( this );
    popup->insertItem( "&Quit", qApp, SLOT(quit()) );
    menubar->insertItem( "&File", popup );

    // ...and tell the layout about it.
    topLayout->setMenuBar( menubar );

    // Make an hbox that will hold a row of buttons.
    QBoxLayout *buttons = new QHBoxLayout( topLayout );
    int i;
    for ( i = 1; i <= 4; i++ ) {
        QPushButton* but = new QPushButton( this );
        QString s;
        s.sprintf( "Button %d", i );
        but->setText( s );

        // Set horizontal stretch factor to 10 to let the buttons
        // stretch horizontally. The buttons will not stretch
        // vertically, since bigWidget below will take up vertical
        // stretch.
        buttons->addWidget( but, 10 );
        // (Actually, the result would have been the same with a
        // stretch factor of 0; if no items in a layout have non-zero
        // stretch, the space is divided equally between members.)
    }

    // Make another hbox that will hold a left-justified row of buttons.
    QBoxLayout *buttons2 = new QHBoxLayout( topLayout );

    QPushButton* but = new QPushButton( "Button five", this );
    buttons2->addWidget( but );

    but = new QPushButton( "Button 6", this );
    buttons2->addWidget( but );

    // Fill up the rest of the hbox with stretchable space, so that
    // the buttons get their minimum width and are pushed to the left.
    buttons2->addStretch( 10 );

    // Make  a big widget that will grab all space in the middle.
    QMultiLineEdit *bigWidget = new QMultiLineEdit( this );
    bigWidget->setText( "This widget will get all the remaining space" );
    bigWidget->setFrameStyle( QFrame::Panel | QFrame::Plain );

    // Set vertical stretch factor to 10 to let the bigWidget stretch
    // vertically. It will stretch horizontally because there are no
    // widgets beside it to take up horizontal stretch.
    //    topLayout->addWidget( bigWidget, 10 );
    topLayout->addWidget( bigWidget );

    // Make a grid that will hold a vertical table of QLabel/QLineEdit
    // pairs next to a large QMultiLineEdit.

    // Don't use hard-coded row/column numbers in QGridLayout, you'll
    // regret it when you have to change the layout.
    const int numRows = 3;
    const int labelCol = 0;
    const int linedCol = 1;
    const int multiCol = 2;

    // Let the grid-layout have a spacing of 10 pixels between
    // widgets, overriding the default from topLayout.
    QGridLayout *grid = new QGridLayout( topLayout, 0, 0, 10 );
    int row;

    for ( row = 0; row < numRows; row++ ) {
        QLineEdit *ed = new QLineEdit( this );
        // The line edit goes in the second column
        grid->addWidget( ed, row, linedCol );

        // Make a label that is a buddy of the line edit
        QString s;
        s.sprintf( "Line &%d", row+1 );
        QLabel *label = new QLabel( ed, s, this );
        // The label goes in the first column.
        grid->addWidget( label, row, labelCol );
    }

    // The multiline edit will cover the entire vertical range of the
    // grid (rows 0 to numRows) and stay in column 2.

    QMultiLineEdit *med = new QMultiLineEdit( this );
    grid->addMultiCellWidget( med, 0, -1, multiCol, multiCol );

    // The labels will take the space they need. Let the remaining
    // horizontal space be shared so that the multiline edit gets
    // twice as much as the line edit.
    grid->setColStretch( linedCol, 10 );
    grid->setColStretch( multiCol, 20 );

    // Add a widget at the bottom.
    QLabel* sb = new QLabel( this );
    sb->setText( "Let's pretend this is a status bar" );
    sb->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    // This widget will use all horizontal space, and have a fixed height.

    // we should have made a subclass and implemented sizePolicy there...
    sb->setFixedHeight( sb->sizeHint().height() );

    sb->setAlignment( AlignVCenter | AlignLeft );
    topLayout->addWidget( sb );

    topLayout->activate();
}

ExampleWidget::~ExampleWidget()
{
    // All child widgets are deleted by Qt.
    // The top-level layout and all its sub-layouts are deleted by Qt.
}

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

    ExampleWidget f;
    a.setMainWidget(&f);
    f.setCaption("Qt Example - Caption");
    f.show();

    return a.exec();
}

See also Examples.


Conway's Game of Life

Header file:

/****************************************************************************
** $Id:  qt/life.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef LIFE_H
#define LIFE_H

#include <qframe.h>

class LifeWidget : public QFrame
{
    Q_OBJECT
public:
    LifeWidget( int s = 10, QWidget *parent = 0, const char *name = 0 );

    void        setPoint( int i, int j );

    int         maxCol() { return maxi; }
    int         maxRow() { return maxj; }

public slots:
    void        nextGeneration();
    void        clear();

protected:
    virtual void paintEvent( QPaintEvent * );
    virtual void mouseMoveEvent( QMouseEvent * );
    virtual void mousePressEvent( QMouseEvent * );
    virtual void resizeEvent( QResizeEvent * );
    void         mouseHandle( const QPoint &pos );

private:
    enum { MAXSIZE = 50, MINSIZE = 10, BORDER = 5 };

    bool        cells[2][MAXSIZE + 2][MAXSIZE + 2];
    int         current;
    int         maxi, maxj;

    int pos2index( int x )
    {
        return ( x - BORDER ) / SCALE + 1;
    }
    int index2pos( int i )
    {
        return  ( i - 1 ) * SCALE + BORDER;
    }

    int SCALE;
};

#endif // LIFE_H

Implementation:

/****************************************************************************
** $Id:  qt/life.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "life.h"

#include <qpainter.h>
#include <qdrawutil.h>
#include <qcheckbox.h>
#include <qevent.h>
#include <qapplication.h>

// The main game of life widget

LifeWidget::LifeWidget( int s, QWidget *parent, const char *name )
    : QFrame( parent, name )
{
    SCALE = s;

    maxi = maxj = 50;
    setMinimumSize( MINSIZE * SCALE + 2 * BORDER,
                   MINSIZE * SCALE + 2 * BORDER );
    setMaximumSize( MAXSIZE * SCALE + 2 * BORDER,
                   MAXSIZE * SCALE + 2 * BORDER );
    setSizeIncrement( SCALE, SCALE);

    clear();
    resize( maxi * SCALE + 2 * BORDER , maxj * SCALE + 2 * BORDER );

}

void LifeWidget::clear()
{
    current = 0;
    for ( int t = 0; t < 2; t++ )
        for ( int i = 0; i < MAXSIZE + 2; i++ )
            for ( int j = 0; j < MAXSIZE + 2; j++ )
                cells[t][i][j] = FALSE;

    repaint();
}

// We assume that the size will never be beyond the maximum size set
// this is not in general TRUE, but in practice it's good enough for
// this program

void LifeWidget::resizeEvent( QResizeEvent * e )
{
    maxi = (e->size().width()  - 2 * BORDER) / SCALE;
    maxj = (e->size().height() - 2 * BORDER) / SCALE;
}

void LifeWidget::setPoint( int i, int j )
{
    if ( i < 1 || i > maxi || j < 1 || j > maxi )
        return;
    cells[current][i][j] = TRUE;
    repaint( index2pos(i), index2pos(j), SCALE, SCALE, FALSE );
}

void LifeWidget::mouseHandle( const QPoint &pos )
{
    int i = pos2index( pos.x() );
    int j = pos2index( pos.y() );
    setPoint( i, j );
}

void LifeWidget::mouseMoveEvent( QMouseEvent *e )
{
    mouseHandle( e->pos() );
}

void LifeWidget::mousePressEvent( QMouseEvent *e )
{
    if ( e->button() == QMouseEvent::LeftButton )
        mouseHandle( e->pos() );
}

void LifeWidget::nextGeneration()
{
    for ( int i = 1; i <= MAXSIZE; i++ ) {
        for ( int j = 1; j <= MAXSIZE; j++ ) {
            int t = cells[current][i - 1][j - 1]
            + cells[current][i - 1][j]
            + cells[current][i - 1][j + 1]
            + cells[current][i][j - 1]
            + cells[current][i][j + 1]
            + cells[current][i + 1][j - 1]
            + cells[current][i + 1][j]
            + cells[current][i + 1][j + 1];

            cells[!current][i][j] = ( t == 3 ||
                                      t == 2 && cells[current][i][j] );
        }
    }
    current = !current;
    repaint( FALSE );           // repaint without erase
}

void LifeWidget::paintEvent( QPaintEvent * e )
{
    int starti = pos2index( e->rect().left() );
    int stopi  = pos2index( e->rect().right() );
    int startj = pos2index( e->rect().top() );
    int stopj  = pos2index( e->rect().bottom() );

    if (stopi > maxi)
        stopi = maxi;
    if (stopj > maxj)
        stopj = maxj;

    QPainter paint( this );
    for ( int i = starti; i <= stopi; i++ ) {
        for ( int j = startj; j <= stopj; j++ ) {
            if ( cells[current][i][j] )
                qDrawShadePanel( &paint, index2pos( i ), index2pos( j ),
                                 SCALE - 1, SCALE - 1, colorGroup() );
            else if ( cells[!current][i][j] )
                erase(index2pos( i ), index2pos( j ), SCALE - 1, SCALE - 1);
        }
    }
    drawFrame( &paint );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "lifedlg.h"
#include <qapplication.h>
#include <stdlib.h>

void usage()
{
    qWarning( "Usage: life [-scale scale]" );
}

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

    int scale = 10;

    for ( int i = 1; i < argc; i++ ){
        QString arg = argv[i];
        if ( arg == "-scale" )
            scale = atoi( argv[++i] );
        else {
            usage();
            exit(1);
        }
    }

    if ( scale < 2 )
        scale = 2;

    LifeDialog *life = new LifeDialog( scale );
    a.setMainWidget( life );
    life->setCaption("Qt Example - Life");
    life->show();

    return a.exec();
}

See also Examples.


Line Edits

This example shows how to work with single lineedit widgets, and how to use different echo modes and validators.

Header file:

/****************************************************************************
** $Id:  qt/lineedits.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef LINEDITS_H
#define LINEDITS_H

#include <qgroupbox.h>

class QLineEdit;
class QComboBox;

class LineEdits : public QGroupBox
{
    Q_OBJECT

public:
    LineEdits( QWidget *parent = 0, const char *name = 0 );

protected:
    QLineEdit *lined1, *lined2, *lined3, *lined4;
    QComboBox *combo1, *combo2, *combo3, *combo4;

protected slots:
    void slotEchoChanged( int );
    void slotValidatorChanged( int );
    void slotAlignmentChanged( int );
    void slotReadOnlyChanged( int );
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/lineedits.cpp   3.0.5   edited May 7 17:30 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "lineedits.h"

#include <qlineedit.h>
#include <qcombobox.h>
#include <qframe.h>
#include <qvalidator.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qhbox.h>

/*
 * Constructor
 *
 * Creates child widgets of the LineEdits widget
 */

LineEdits::LineEdits( QWidget *parent, const char *name )
    : QGroupBox( 0, Horizontal, "Line edits", parent, name )
{
    setMargin( 10 );

    QVBoxLayout* box = new QVBoxLayout( layout() );

    QHBoxLayout *row1 = new QHBoxLayout( box );
    row1->setMargin( 5 );

    // Create a Label
    QLabel* label = new QLabel( "Echo Mode: ", this);
    row1->addWidget( label );

    // Create a Combobox with three items...
    combo1 = new QComboBox( FALSE, this );
    row1->addWidget( combo1 );
    combo1->insertItem( "Normal", -1 );
    combo1->insertItem( "Password", -1 );
    combo1->insertItem( "No Echo", -1 );
    // ...and connect the activated() SIGNAL with the slotEchoChanged() SLOT to be able
    // to react when an item is selected
    connect( combo1, SIGNAL( activated( int ) ), this, SLOT( slotEchoChanged( int ) ) );

    // insert the first LineEdit
    lined1 = new QLineEdit( this );
    box->addWidget( lined1 );

    // another widget which is used for layouting
    QHBoxLayout *row2 = new QHBoxLayout( box );
    row2->setMargin( 5 );

    // and the second label
    label = new QLabel( "Validator: ", this );
    row2->addWidget( label );

    // A second Combobox with again three items...
    combo2 = new QComboBox( FALSE, this );
    row2->addWidget( combo2 );
    combo2->insertItem( "No Validator", -1 );
    combo2->insertItem( "Integer Validator", -1 );
    combo2->insertItem( "Double Validator", -1 );
    // ...and again the activated() SIGNAL gets connected with a SLOT
    connect( combo2, SIGNAL( activated( int ) ), this, SLOT( slotValidatorChanged( int ) ) );

    // and the second LineEdit
    lined2 = new QLineEdit( this );
    box->addWidget( lined2 );

    // yet another widget which is used for layouting
    QHBoxLayout *row3 = new QHBoxLayout( box );
    row3->setMargin( 5 );

    // we need a label for this too
    label = new QLabel( "Alignment: ", this );
    row3->addWidget( label );

    // A combo box for setting alignment
    combo3 = new QComboBox( FALSE, this );
    row3->addWidget( combo3 );
    combo3->insertItem( "Left", -1 );
    combo3->insertItem( "Centered", -1 );
    combo3->insertItem( "Right", -1 );
    // ...and again the activated() SIGNAL gets connected with a SLOT
    connect( combo3, SIGNAL( activated( int ) ), this, SLOT( slotAlignmentChanged( int ) ) );

    // and the third lineedit
    lined3 = new QLineEdit( this );
    box->addWidget( lined3 );

    // last widget used for layouting
    QHBox *row4 = new QHBox( this );
    box->addWidget( row4 );
    row4->setMargin( 5 );

    // last label
    (void)new QLabel( "Read-Only: ", row4 );

    // A combo box for setting alignment
    combo4 = new QComboBox( FALSE, row4 );
    combo4->insertItem( "False", -1 );
    combo4->insertItem( "True", -1 );
    // ...and again the activated() SIGNAL gets connected with a SLOT
    connect( combo4, SIGNAL( activated( int ) ), this, SLOT( slotReadOnlyChanged( int ) ) );

    // and the last lineedit
    lined4 = new QLineEdit( this );
    box->addWidget( lined4 );

    // give the first LineEdit the focus at the beginning
    lined1->setFocus();
}

/*
 * SLOT slotEchoChanged( int i )
 *
 * i contains the number of the item which the user has been chosen in the
 * first Combobox. According to this value, we set the Echo-Mode for the
 * first LineEdit.
 */

void LineEdits::slotEchoChanged( int i )
{
    switch ( i ) {
    case 0:
        lined1->setEchoMode( QLineEdit::Normal );
        break;
    case 1:
        lined1->setEchoMode( QLineEdit::Password );
        break;
    case 2:
        lined1->setEchoMode( QLineEdit::NoEcho );
        break;
    }

    lined1->setFocus();
}

/*
 * SLOT slotValidatorChanged( int i )
 *
 * i contains the number of the item which the user has been chosen in the
 * second Combobox. According to this value, we set a validator for the
 * second LineEdit. A validator checks in a LineEdit each character which
 * the user enters and accepts it if it is valid, else the character gets
 * ignored and not inserted into the lineedit.
 */

void LineEdits::slotValidatorChanged( int i )
{
    switch ( i ) {
    case 0:
        lined2->setValidator( 0 );
        break;
    case 1:
        lined2->setValidator( new QIntValidator( lined2 ) );
        break;
    case 2:
        lined2->setValidator( new QDoubleValidator( -999.0, 999.0, 2,
                                                    lined2 ) );
        break;
    }

    lined2->setText( "" );
    lined2->setFocus();
}

/*
 * SLOT slotAlignmentChanged( int i )
 *
 * i contains the number of the item which the user has been chosen in
 * the third Combobox.  According to this value, we set an alignment
 * third LineEdit.
 */

void LineEdits::slotAlignmentChanged( int i )
{
    switch ( i ) {
    case 0:
        lined3->setAlignment( QLineEdit::AlignLeft );
        break;
    case 1:
        lined3->setAlignment( QLineEdit::AlignCenter );
        break;
    case 2:
        lined3->setAlignment( QLineEdit::AlignRight );
        break;
    }

    lined3->setFocus();
}

/*
 * SLOT slotReadOnlyChanged( int i )
 *
 * i contains the number of the item which the user has been chosen in
 * the fourth Combobox.  According to this value, we toggle read-only.
 */

void LineEdits::slotReadOnlyChanged( int i )
{
    switch ( i ) {
    case 0:
        lined4->setReadOnly( FALSE );
        break;
    case 1:
        lined4->setReadOnly( TRUE );
        break;
    }

    lined4->setFocus();
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "lineedits.h"
#include <qapplication.h>

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

    LineEdits lineedits;
    lineedits.setCaption( "Qt Example - Lineedits" );
    a.setMainWidget( &lineedits );
    lineedits.show();

    return a.exec();
}

See also Examples.


Listboxes and Comboboxes

This example program demonstrates how to use listboxes (with single selection and multi selection) and comboboxes (editable and non-editable).

Header file:

/****************************************************************************
** $Id:  qt/listboxcombo.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef LISTBOX_COMBO_H
#define LISTBOX_COMBO_H

#include <qvbox.h>

class QListBox;
class QLabel;

class ListBoxCombo : public QVBox
{
    Q_OBJECT

public:
    ListBoxCombo( QWidget *parent = 0, const char *name = 0 );

protected:
    QListBox *lb1, *lb2;
    QLabel *label1, *label2;

protected slots:
    void slotLeft2Right();
    void slotCombo1Activated( const QString &s );
    void slotCombo2Activated( const QString &s );

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/listboxcombo.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listboxcombo.h"

#include <qcombobox.h>
#include <qlistbox.h>
#include <qhbox.h>
#include <qpushbutton.h>
#include <qstring.h>
#include <qpixmap.h>
#include <qlabel.h>
#include <qimage.h>
#include <qpainter.h>
#include <qstyle.h>

class MyListBoxItem : public QListBoxItem
{
public:
    MyListBoxItem()
        : QListBoxItem()
    {
        setCustomHighlighting( TRUE );
    }

protected:
    virtual void paint( QPainter * );
    virtual int width( const QListBox* ) const { return 100; }
    virtual int height( const QListBox* ) const { return 16; }

};

void MyListBoxItem::paint( QPainter *painter )
{
    // evil trick: find out whether we are painted onto our listbox
    bool in_list_box = listBox() && listBox()->viewport() == painter->device();

    QRect r ( 0, 0, width( listBox() ), height( listBox() ) );
    if ( in_list_box && isSelected() )
        painter->eraseRect( r );
    painter->fillRect( 5, 5, width( listBox() ) - 10, height( listBox() ) - 10, Qt::red );
    if ( in_list_box && isCurrent() )
        listBox()->style().drawPrimitive( QStyle::PE_FocusRect, painter, r, listBox()->colorGroup() );
}

/*
 * Constructor
 *
 * Creates child widgets of the ListBoxCombo widget
 */

ListBoxCombo::ListBoxCombo( QWidget *parent, const char *name )
    : QVBox( parent, name )
{
    setMargin( 5 );
    setSpacing( 5 );

    unsigned int i;
    QString str;

    QHBox *row1 = new QHBox( this );
    row1->setSpacing( 5 );

    // Create a multi-selection ListBox...
    lb1 = new QListBox( row1 );
    lb1->setSelectionMode( QListBox::Multi );

    // ...insert a pixmap item...
    lb1->insertItem( QPixmap( "qtlogo.png" ) );
    // ...and 100 text items
    for ( i = 0; i < 100; i++ ) {
        str = QString( "Listbox Item %1" ).arg( i );
        if ( !( i % 4 ) )
            lb1->insertItem( QPixmap( "fileopen.xpm" ), str );
        else
            lb1->insertItem( str );
    }

    // Create a pushbutton...
    QPushButton *arrow1 = new QPushButton( " -> ", row1 );
    // ...and connect the clicked SIGNAL with the SLOT slotLeft2Right
    connect( arrow1, SIGNAL( clicked() ), this, SLOT( slotLeft2Right() ) );

    // create an empty single-selection ListBox
    lb2 = new QListBox( row1 );

    QHBox *row2 = new QHBox( this );
    row2->setSpacing( 5 );

    QVBox *box1 = new QVBox( row2 );
    box1->setSpacing( 5 );

    // Create a non-editable Combobox and a label below...
    QComboBox *cb1 = new QComboBox( FALSE, box1 );
    label1 = new QLabel( "Current Item: Combobox Item 0", box1 );
    label1->setMaximumHeight( label1->sizeHint().height() * 2 );
    label1->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    //...and insert 50 items into the Combobox
    for ( i = 0; i < 50; i++ ) {
        str = QString( "Combobox Item %1" ).arg( i );
        if ( i % 9 )
            cb1->insertItem( str );
        else
            cb1->listBox()->insertItem( new MyListBoxItem );
    }

    QVBox *box2 = new QVBox( row2 );
    box2->setSpacing( 5 );

    // Create an editable Combobox and a label below...
    QComboBox *cb2 = new QComboBox( TRUE, box2 );
    label2 = new QLabel( "Current Item: Combobox Item 0", box2 );
    label2->setMaximumHeight( label2->sizeHint().height() * 2 );
    label2->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    // ... and insert 50 items into the Combobox
    for ( i = 0; i < 50; i++ ) {
        str = QString( "Combobox Item %1" ).arg( i );
        if ( !( i % 4 ) )
            cb2->insertItem( QPixmap( "fileopen.xpm" ), str );
        else
            cb2->insertItem( str );
    }

    // Connect the activated SIGNALs of the Comboboxes with SLOTs
    connect( cb1, SIGNAL( activated( const QString & ) ), this, SLOT( slotCombo1Activated( const QString & ) ) );
    connect( cb2, SIGNAL( activated( const QString & ) ), this, SLOT( slotCombo2Activated( const QString & ) ) );
}

/*
 * SLOT slotLeft2Right
 *
 * Copies all selected items of the first ListBox into the
 * second ListBox
 */

void ListBoxCombo::slotLeft2Right()
{
    // Go through all items of the first ListBox
    for ( unsigned int i = 0; i < lb1->count(); i++ ) {
        QListBoxItem *item = lb1->item( i );
        // if the item is selected...
        if ( item->isSelected() ) {
            // ...and it is a text item...
            if ( item->pixmap() && !item->text().isEmpty() )
                lb2->insertItem( *item->pixmap(), item->text() );
            else if ( !item->pixmap() )
                lb2->insertItem( item->text() );
            else if ( item->text().isEmpty() )
                lb2->insertItem( *item->pixmap() );
        }
    }
}

/*
 * SLOT slotCombo1Activated( const QString &s )
 *
 * Sets the text of the item which the user just selected
 * in the first Combobox (and is now the value of s) to
 * the first Label.
 */

void ListBoxCombo::slotCombo1Activated( const QString &s )
{
    label1->setText( QString( "Current Item: %1" ).arg( s ) );
}

/*
 * SLOT slotCombo2Activated( const QString &s )
 *
 * Sets the text of the item which the user just selected
 * in the second Combobox (and is now the value of s) to
 * the second Label.
 */

void ListBoxCombo::slotCombo2Activated( const QString &s )
{
    label2->setText( QString( "Current Item: %1" ).arg( s ) );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listboxcombo.h"
#include <qapplication.h>

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

    ListBoxCombo listboxcombo;
    listboxcombo.resize( 400, 270 );
    listboxcombo.setCaption( "Qt Example - Listboxes and Comboboxes" );
    a.setMainWidget( &listboxcombo );
    listboxcombo.show();

    return a.exec();
}

See also Examples.


Listviews

This examples shows how to work with listviews (hierarchical and multi-column). It also shows how to subclass listview items for special reasons. It looks and works like the main window of a mail client.

Header file:

/****************************************************************************
** $Id:  qt/listviews.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef LISTVIEWS_H
#define LISTVIEWS_H

#include <qsplitter.h>
#include <qstring.h>
#include <qobject.h>
#include <qdatetime.h>
#include <qptrlist.h>
#include <qlistview.h>

class QListView;
class QLabel;
class QPainter;
class QColorGroup;
class QObjectList;
class QPopupMenu;

// -----------------------------------------------------------------

class MessageHeader
{
public:
    MessageHeader( const QString &_sender, const QString &_subject, const QDateTime &_datetime )
        : msender( _sender ), msubject( _subject ), mdatetime( _datetime )
    {}

    MessageHeader( const MessageHeader &mh );
    MessageHeader &operator=( const MessageHeader &mh );

    QString sender() { return msender; }
    QString subject() { return msubject; }
    QDateTime datetime() { return mdatetime; }

protected:
    QString msender, msubject;
    QDateTime mdatetime;

};

// -----------------------------------------------------------------

class Message
{
public:
    enum State { Read = 0,
                 Unread};

    Message( const MessageHeader &mh, const QString &_body )
        : mheader( mh ), mbody( _body ), mstate( Unread )
    {}

    Message( const Message &m )
        : mheader( m.mheader ), mbody( m.mbody ), mstate( m.mstate )
    {}

    MessageHeader header() { return mheader; }
    QString body() { return mbody; }

    void setState( const State &s ) { mstate = s; }
    State state() { return mstate; }

protected:
    MessageHeader mheader;
    QString mbody;
    State mstate;

};

// -----------------------------------------------------------------

class Folder : public QObject
{
    Q_OBJECT

public:
    Folder( Folder *parent, const QString &name );
    ~Folder()
    {}

    void addMessage( Message *m )
    { lstMessages.append( m ); }

    QString folderName() { return fName; }

    Message *firstMessage() { return lstMessages.first(); }
    Message *nextMessage() { return lstMessages.next(); }

protected:
    QString fName;
    QPtrList<Message> lstMessages;

};

// -----------------------------------------------------------------

class FolderListItem : public QListViewItem
{
public:
    FolderListItem( QListView *parent, Folder *f );
    FolderListItem( FolderListItem *parent, Folder *f );

    void insertSubFolders( const QObjectList *lst );

    Folder *folder() { return myFolder; }

protected:
    Folder *myFolder;

};

// -----------------------------------------------------------------

class MessageListItem : public QListViewItem
{
public:
    MessageListItem( QListView *parent, Message *m );

    virtual void paintCell( QPainter *p, const QColorGroup &cg,
                            int column, int width, int alignment );

    Message *message() { return myMessage; }

protected:
    Message *myMessage;

};

// -----------------------------------------------------------------

class ListViews : public QSplitter
{
    Q_OBJECT

public:
    ListViews( QWidget *parent = 0, const char *name = 0 );
    ~ListViews()
    {}

protected:
    void initFolders();
    void initFolder( Folder *folder, unsigned int &count );
    void setupFolders();

    QListView *messages, *folders;
    QLabel *message;
    QPopupMenu* menu;

    QPtrList<Folder> lstFolders;

protected slots:
    void slotFolderChanged( QListViewItem* );
    void slotMessageChanged();
    void slotRMB( QListViewItem*, const QPoint &, int );

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/listviews.cpp   3.0.5   edited Feb 11 15:31 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listviews.h"

#include <qlabel.h>
#include <qpainter.h>
#include <qpalette.h>
#include <qobjectlist.h>
#include <qpopupmenu.h>
#include <qheader.h>
#include <qregexp.h>

// -----------------------------------------------------------------

MessageHeader::MessageHeader( const MessageHeader &mh )
{
    msender = mh.msender;
    msubject = mh.msubject;
    mdatetime = mh.mdatetime;
}

MessageHeader &MessageHeader::operator=( const MessageHeader &mh )
{
    msender = mh.msender;
    msubject = mh.msubject;
    mdatetime = mh.mdatetime;

    return *this;
}

// -----------------------------------------------------------------

Folder::Folder( Folder *parent, const QString &name )
    : QObject( parent, name ), fName( name )
{
    lstMessages.setAutoDelete( TRUE );
}

// -----------------------------------------------------------------

FolderListItem::FolderListItem( QListView *parent, Folder *f )
    : QListViewItem( parent )
{
    myFolder = f;
    setText( 0, f->folderName() );

    if ( myFolder->children() )
        insertSubFolders( myFolder->children() );
}

FolderListItem::FolderListItem( FolderListItem *parent, Folder *f )
    : QListViewItem( parent )
{
    myFolder = f;

    setText( 0, f->folderName() );

    if ( myFolder->children() )
        insertSubFolders( myFolder->children() );
}

void FolderListItem::insertSubFolders( const QObjectList *lst )
{
    Folder *f;
    for ( f = ( Folder* )( ( QObjectList* )lst )->first(); f; f = ( Folder* )( ( QObjectList* )lst )->next() )
        (void)new FolderListItem( this, f );
}

// -----------------------------------------------------------------

MessageListItem::MessageListItem( QListView *parent, Message *m )
    : QListViewItem( parent )
{
    myMessage = m;
    setText( 0, myMessage->header().sender() );
    setText( 1, myMessage->header().subject() );
    setText( 2, myMessage->header().datetime().toString() );
}

void MessageListItem::paintCell( QPainter *p, const QColorGroup &cg,
                                 int column, int width, int alignment )
{
    QColorGroup _cg( cg );
    QColor c = _cg.text();

    if ( myMessage->state() == Message::Unread )
        _cg.setColor( QColorGroup::Text, Qt::red );

    QListViewItem::paintCell( p, _cg, column, width, alignment );

    _cg.setColor( QColorGroup::Text, c );
}

// -----------------------------------------------------------------

ListViews::ListViews( QWidget *parent, const char *name )
    : QSplitter( Qt::Horizontal, parent, name )
{
    lstFolders.setAutoDelete( TRUE );

    folders = new QListView( this );
    folders->header()->setClickEnabled( FALSE );
    folders->addColumn( "Folder" );

    initFolders();
    setupFolders();

    folders->setRootIsDecorated( TRUE );
    setResizeMode( folders, QSplitter::KeepSize );

    QSplitter *vsplitter = new QSplitter( Qt::Vertical, this );

    messages = new QListView( vsplitter );
    messages->addColumn( "Sender" );
    messages->addColumn( "Subject" );
    messages->addColumn( "Date" );
    messages->setColumnAlignment( 1, Qt::AlignRight );
    messages->setAllColumnsShowFocus( TRUE );
    messages->setShowSortIndicator( TRUE );
    menu = new QPopupMenu( messages );
    for( int i = 1; i <= 10; i++ )
        menu->insertItem( QString( "Context Item %1" ).arg( i ) );
    connect(messages, SIGNAL( contextMenuRequested( QListViewItem *, const QPoint& , int ) ),
            this, SLOT( slotRMB( QListViewItem *, const QPoint &, int ) ) );
    vsplitter->setResizeMode( messages, QSplitter::KeepSize );

    message = new QLabel( vsplitter );
    message->setAlignment( Qt::AlignTop );
    message->setBackgroundMode( PaletteBase );

    connect( folders, SIGNAL( selectionChanged( QListViewItem* ) ),
             this, SLOT( slotFolderChanged( QListViewItem* ) ) );
    connect( messages, SIGNAL( selectionChanged() ),
             this, SLOT( slotMessageChanged() ) );
    connect( messages, SIGNAL( currentChanged( QListViewItem * ) ),
             this, SLOT( slotMessageChanged() ) );

    messages->setSelectionMode( QListView::Extended );
    // some preperationes
    folders->firstChild()->setOpen( TRUE );
    folders->firstChild()->firstChild()->setOpen( TRUE );
    folders->setCurrentItem( folders->firstChild()->firstChild()->firstChild() );
    folders->setSelected( folders->firstChild()->firstChild()->firstChild(), TRUE );

    messages->setSelected( messages->firstChild(), TRUE );
    messages->setCurrentItem( messages->firstChild() );
    message->setMargin( 5 );

    QValueList<int> lst;
    lst.append( 170 );
    setSizes( lst );
}

void ListViews::initFolders()
{
    unsigned int mcount = 1;

    for ( unsigned int i = 1; i < 20; i++ ) {
        QString str;
        str = QString( "Folder %1" ).arg( i );
        Folder *f = new Folder( 0, str );
        for ( unsigned int j = 1; j < 5; j++ ) {
            QString str2;
            str2 = QString( "Sub Folder %1" ).arg( j );
            Folder *f2 = new Folder( f, str2 );
            for ( unsigned int k = 1; k < 3; k++ ) {
                QString str3;
                str3 = QString( "Sub Sub Folder %1" ).arg( k );
                Folder *f3 = new Folder( f2, str3 );
                initFolder( f3, mcount );
            }
        }
        lstFolders.append( f );
    }
}

void ListViews::initFolder( Folder *folder, unsigned int &count )
{
    for ( unsigned int i = 0; i < 15; i++, count++ ) {
        QString str;
        str = QString( "Message %1  " ).arg( count );
        QDateTime dt = QDateTime::currentDateTime();
        dt = dt.addSecs( 60 * count );
        MessageHeader mh( "Trolltech <info@trolltech.com>  ", str, dt );

        QString body;
        body = QString( "This is the message number %1 of this application, \n"
                        "which shows how to use QListViews, QListViewItems, \n"
                        "QSplitters and so on. The code should show how easy\n"
                        "this can be done in Qt." ).arg( count );
        Message *msg = new Message( mh, body );
        folder->addMessage( msg );
    }
}

void ListViews::setupFolders()
{
    folders->clear();

    for ( Folder* f = lstFolders.first(); f; f = lstFolders.next() )
        (void)new FolderListItem( folders, f );
}

void ListViews::slotRMB( QListViewItem* Item, const QPoint & point, int )
{
    if( Item )
        menu->popup( point );
}

void ListViews::slotFolderChanged( QListViewItem *i )
{
    if ( !i )
        return;
    messages->clear();
    message->setText( "" );

    FolderListItem *item = ( FolderListItem* )i;

    for ( Message* msg = item->folder()->firstMessage(); msg;
          msg = item->folder()->nextMessage() )
        (void)new MessageListItem( messages, msg );
}

void ListViews::slotMessageChanged()
{
    QListViewItem *i = messages->currentItem();
    if ( !i )
        return;

    if ( !i->isSelected() ) {
        message->setText( "" );
        return;
    }

    MessageListItem *item = ( MessageListItem* )i;
    Message *msg = item->message();

    QString text;
    QString tmp = msg->header().sender();
    tmp = tmp.replace( QRegExp( "<" ), "&lt;" );
    tmp = tmp.replace( QRegExp( ">" ), "&gt;" );
    text = QString( "<b><i>From:</i></b> <a href=\"mailto:info@trolltech.com\">%1</a><br>"
                    "<b><i>Subject:</i></b> <big><big><b>%2</b></big></big><br>"
                    "<b><i>Date:</i></b> %3<br><br>"
                    "%4" ).
           arg( tmp ).arg( msg->header().subject() ).
           arg( msg->header().datetime().toString() ).arg( msg->body() );

    message->setText( text );

    msg->setState( Message::Read );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "listviews.h"
#include <qapplication.h>

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

    ListViews listViews;
    listViews.resize( 640, 480 );
    listViews.setCaption( "Qt Example - Listview" );
    a.setMainWidget( &listViews );
    listViews.show();

    return a.exec();
}

See also Examples.


A simple mail client

This example shows how to use the QSocket class. The client can only be used to send mails. The interesting part is the implementation of the SMTP protocol.

Header file (smtp.h):

/****************************************************************************
** $Id:  qt/smtp.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef SMTP_H
#define SMTP_H

#include <qobject.h>
#include <qstring.h>

class QSocket;
class QTextStream;
class QDns;

class Smtp : public QObject
{
    Q_OBJECT

public:
    Smtp( const QString &from, const QString &to,
          const QString &subject, const QString &body );
    ~Smtp();

signals:
    void status( const QString & );

private slots:
    void dnsLookupHelper();
    void readyRead();
    void connected();

private:
    enum State {
        Init,
        Mail,
        Rcpt,
        Data,
        Body,
        Quit,
        Close
    };

    QString message;
    QString from;
    QString rcpt;
    QSocket *socket;
    QTextStream * t;
    int state;
    QString response;
    QDns * mxLookup;
};

#endif

Implementation (smtp.cpp):

/****************************************************************************
** $Id:  qt/smtp.cpp   3.0.5   edited Apr 18 14:18 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "smtp.h"

#include <qtextstream.h>
#include <qsocket.h>
#include <qdns.h>
#include <qtimer.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qregexp.h>

Smtp::Smtp( const QString &from, const QString &to,
            const QString &subject,
            const QString &body )
{
    socket = new QSocket( this );
    connect ( socket, SIGNAL( readyRead() ),
              this, SLOT( readyRead() ) );
    connect ( socket, SIGNAL( connected() ),
              this, SLOT( connected() ) );

    mxLookup = new QDns( to.mid( to.find( '@' )+1 ), QDns::Mx );
    connect( mxLookup, SIGNAL(resultsReady()),
             this, SLOT(dnsLookupHelper()) );

    message = QString::fromLatin1( "From: " ) + from +
              QString::fromLatin1( "\nTo: " ) + to +
              QString::fromLatin1( "\nSubject: " ) + subject +
              QString::fromLatin1( "\n\n" ) + body + "\n";
    message.replace( QRegExp( QString::fromLatin1( "\n" ) ),
                     QString::fromLatin1( "\r\n" ) );
    message.replace( QRegExp( QString::fromLatin1( "\r\n.\r\n" ) ),
                     QString::fromLatin1( "\r\n..\r\n" ) );

    this->from = from;
    rcpt = to;

    state = Init;
}

Smtp::~Smtp()
{
    delete t;
    delete socket;
}

void Smtp::dnsLookupHelper()
{
    QValueList<QDns::MailServer> s = mxLookup->mailServers();
    if ( s.isEmpty() && mxLookup->isWorking() )
        return;

    emit status( tr( "Connecting to %1" ).arg( s.first().name ) );

    socket->connectToHost( s.first().name, 25 );
    t = new QTextStream( socket );
}

void Smtp::connected()
{
    emit status( tr( "Connected to %1" ).arg( socket->peerName() ) );
}

void Smtp::readyRead()
{
    // SMTP is line-oriented
    if ( !socket->canReadLine() )
        return;

    QString responseLine;
    do {
        responseLine = socket->readLine();
        response += responseLine;
    } while( socket->canReadLine() && responseLine[3] != ' ' );
    responseLine.truncate( 3 );

    if ( state == Init && responseLine[0] == '2' ) {
        // banner was okay, let's go on
        *t << "HELO there\r\n";
        state = Mail;
    } else if ( state == Mail && responseLine[0] == '2' ) {
        // HELO response was okay (well, it has to be)
        *t << "MAIL FROM: <" << from << ">\r\n";
        state = Rcpt;
    } else if ( state == Rcpt && responseLine[0] == '2' ) {
        *t << "RCPT TO: <" << rcpt << ">\r\n";
        state = Data;
    } else if ( state == Data && responseLine[0] == '2' ) {
        *t << "DATA\r\n";
        state = Body;
    } else if ( state == Body && responseLine[0] == '3' ) {
        *t << message << ".\r\n";
        state = Quit;
    } else if ( state == Quit && responseLine[0] == '2' ) {
        *t << "QUIT\r\n";
        // here, we just close.
        state = Close;
        emit status( tr( "Message sent" ) );
    } else if ( state == Close ) {
        delete this;
        return;
    } else {
        // something broke.
        QMessageBox::warning( qApp->activeWindow(),
                              tr( "Qt Mail Example" ),
                              tr( "Unexpected reply from SMTP server:\n\n" ) +
                              response );
        state = Close;
    }

    response = "";
}

See also Network Examples.


Editors in a Motif form

This example shows two simple text editors, with most of the program written in Motif. One editor is a Qt QMultiLineEdit, the other is a Motif text widget. They are bound together in a Motif form widget.

Implementation:

#include "qxt.h"
#include <qmultilineedit.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <X11/Shell.h>
#include <X11/StringDefs.h>
#include <Xm/Form.h>
#include <Xm/Text.h>

static const char* QTEDMSG =
    "This is a Qt widget.\nIt is a QMultiLineEdit.";

static const char* XTEDMSG =
    "This is an Xt widget.\nIt is an xmTextWidgetClass.";

class EncapsulatedQtWidget : public QXtWidget {
    QMultiLineEdit* mle;
public:
    EncapsulatedQtWidget(Widget parent) :
        QXtWidget("editor", parent, TRUE)
    {
        mle = new QMultiLineEdit(this);
        mle->setText(QTEDMSG);
    }

    void resizeEvent(QResizeEvent*)
    {
        mle->resize(width(),height());
    }
};

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

    Widget toplevel = XtAppInitialize(
        &app, "Editors",
        0, 0, &argc, argv, 0, 0, 0);
    QXtApplication qapp(XtDisplay(toplevel));

    Widget form = XtVaCreateManagedWidget("form",
                    xmFormWidgetClass, toplevel, 0);

    EncapsulatedQtWidget qtchild(form);

    const int marg=10;

    Arg args[20];
    Cardinal nargs=0;
    XtSetArg(args[nargs], XmNwidth, 200);                      nargs++;
    XtSetArg(args[nargs], XmNheight, 200);                     nargs++;
    XtSetArg(args[nargs], XmNleftOffset, marg);                nargs++;
    XtSetArg(args[nargs], XmNtopOffset, marg);                 nargs++;
    XtSetArg(args[nargs], XmNbottomOffset, marg);              nargs++;
    XtSetArg(args[nargs], XmNtopAttachment, XmATTACH_FORM);    nargs++;
    XtSetArg(args[nargs], XmNbottomAttachment, XmATTACH_FORM); nargs++;
    XtSetArg(args[nargs], XmNleftAttachment, XmATTACH_FORM);   nargs++;
    XtSetValues(qtchild.xtWidget(), args, nargs);

    nargs=0;
    XtSetArg(args[nargs], XmNeditMode, XmMULTI_LINE_EDIT);     nargs++;
    XtSetArg(args[nargs], XmNvalue, XTEDMSG);                  nargs++;
    XtSetArg(args[nargs], XmNwidth, 200);                      nargs++;
    XtSetArg(args[nargs], XmNheight, 200);                     nargs++;
    XtSetArg(args[nargs], XmNtopOffset, marg);                 nargs++;
    XtSetArg(args[nargs], XmNbottomOffset, marg);              nargs++;
    XtSetArg(args[nargs], XmNrightOffset, marg);               nargs++;
    XtSetArg(args[nargs], XmNtopAttachment, XmATTACH_FORM);    nargs++;
    XtSetArg(args[nargs], XmNbottomAttachment, XmATTACH_FORM); nargs++;
    XtSetArg(args[nargs], XmNrightAttachment, XmATTACH_FORM);  nargs++;
    XtSetArg(args[nargs], XmNleftAttachment, XmATTACH_WIDGET); nargs++;
    XtSetArg(args[nargs], XmNleftWidget, qtchild.xtWidget());  nargs++;
    Widget xtchild = XtCreateManagedWidget("editor", xmTextWidgetClass,
        form, args, nargs);

    XtRealizeWidget(toplevel);
    XtAppMainLoop(app);
}

See also Qt Xt/Motif Support Extension.


Editors in a Qt main window

This example shows two simple text editors, with most of the program written in Qt. One editor is a Qt QMultiLineEdit, the other is an Athena Widgets text widget. They are bound together in a Qt main window.

Implementation:

#include <qmainwindow.h>
#include <qmultilineedit.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qsplitter.h>
#include "qxt.h"
#include <X11/IntrinsicP.h>
#include <X11/Shell.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/AsciiText.h>

static const char* QTEDMSG =
    "This is a Qt widget.\nIt is a QMultiLineEdit.";

static const char* XTEDMSG =
    "This is an Xt widget.\nIt is an asciiTextWidgetClass.";

class EncapsulatedXtWidget : public QXtWidget {
    Widget editor;
public:
    EncapsulatedXtWidget(QWidget* parent) :
        QXtWidget( "shell", topLevelShellWidgetClass, parent )
    {
        Arg args[20];
        Cardinal nargs=0;
        XtSetArg(args[nargs], XtNeditType, XawtextEdit); nargs++;
        XtSetArg(args[nargs], XtNstring, XTEDMSG);       nargs++;
        editor = XtCreateWidget( "editor", asciiTextWidgetClass, xtWidget(), args, nargs);
        XtRealizeWidget( editor );
        XtMapWidget( editor );
    }
    void resizeEvent( QResizeEvent* e )
    {
        QXtWidget::resizeEvent( e );
        XtResizeWidget( editor, width(), height(), 2 );
    }
};

class TwoEditors : public QMainWindow {
    QMultiLineEdit* qtchild;
    EncapsulatedXtWidget* xtchild;

public:
    TwoEditors() :
        QMainWindow( 0, "mainWindow")
    {
        QPopupMenu* file = new QPopupMenu( this );
        file->insertItem("E&xit", qApp, SLOT( quit() ) );
        menuBar()->insertItem( "&File", file );
        statusBar();
        QSplitter* splitter = new QSplitter( this );
        splitter->setOpaqueResize( TRUE );
        setCentralWidget( splitter );
        xtchild = new EncapsulatedXtWidget( splitter );
        qtchild = new QMultiLineEdit( splitter );
        qtchild->setText(QTEDMSG);
    }

};

int main(int argc, char** argv)
{
    QXtApplication app(argc, argv, "TwoEditors");
    TwoEditors m;
    app.setMainWidget(&m);
    m.show();
    return app.exec();
}

See also Qt Xt/Motif Support Extension.


Editors in an Xt form

This example shows two simple text editors, with most of the program written in Xt. One editor is a Qt QMultiLineEdit, the other is an Athena Widgets text widget. They are bound together in an Xt form widget.

Implementation:

#include "qxt.h"
#include <qmultilineedit.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <X11/Shell.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/Form.h>
#include <X11/Xaw/AsciiText.h>

static const char* QTEDMSG =
    "This is a Qt widget.\nIt is a QMultiLineEdit.";

static const char* XTEDMSG =
    "This is an Xt widget.\nIt is an asciiTextWidgetClass.";

class EncapsulatedQtWidget : public QXtWidget {
public:
    QMultiLineEdit* mle;
    EncapsulatedQtWidget(Widget parent) :
        QXtWidget("editor", parent, TRUE)
    {
        mle = new QMultiLineEdit(this);
        mle->setText(QTEDMSG);
    }

    void resizeEvent(QResizeEvent* e )
    {
        QXtWidget::resizeEvent( e );
        mle->resize(width(),height());
    }
};

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

    Widget toplevel = XtAppInitialize(
        &app, "Editors",
        0, 0, &argc, argv, 0, 0, 0);
    QXtApplication qapp(XtDisplay(toplevel));

    Widget form = XtVaCreateManagedWidget("form", formWidgetClass, toplevel, 0);

    EncapsulatedQtWidget qtchild(form);

    Arg args[20];
    Cardinal nargs=0;
    XtSetArg(args[nargs], XtNwidth, 200);                    nargs++;
    XtSetArg(args[nargs], XtNheight, 200);                   nargs++;
    XtSetValues(qtchild.xtWidget(), args, nargs);
    nargs=0;
    XtSetArg(args[nargs], XtNeditType, XawtextEdit);         nargs++;
    XtSetArg(args[nargs], XtNstring, XTEDMSG);               nargs++;
    XtSetArg(args[nargs], XtNwidth, 200);                    nargs++;
    XtSetArg(args[nargs], XtNheight, 200);                   nargs++;
    XtSetArg(args[nargs], XtNfromHoriz, qtchild.xtWidget()); nargs++;
    Widget xtchild = XtCreateManagedWidget("editor", asciiTextWidgetClass,
        form, args, nargs);

    XtRealizeWidget(toplevel);

//     XSetInputFocus( qt_xdisplay(), qtchild.mle->winId(), RevertToParent, CurrentTime );

    //XtAppMainLoop(app);

    // or the equivalent:

    XEvent xe;
    while (1)
    {
        XtAppNextEvent(app, &xe);
        XtDispatchEvent(&xe);
    }
}

See also Qt Xt/Motif Support Extension.


makeqpf

Saves QPF font files by rendering and saving fonts.

Usage

makeqpf [-A] [-f spec-file] [font ...]

  • -A - Render and save all fonts in fontdir
  • -f - File of lines: fontname character-ranges e.g. "smoothtimes 0-ff,20a0-20af"
  • font - Font to render and save


A MDI Application

This example program is just like the application example, but designed as Multiple Document Interface (MDI).

Header file:

/****************************************************************************
** $Id:  qt/application.h   3.0.5   edited Jun 5 14:11 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef APPLICATION_H
#define APPLICATION_H

#include <qmainwindow.h>
#include <qptrlist.h>

class QMultiLineEdit;
class QToolBar;
class QPopupMenu;
class QWorkspace;
class QPopupMenu;
class QMovie;

class MDIWindow: public QMainWindow
{
    Q_OBJECT
public:
    MDIWindow( QWidget* parent, const char* name, int wflags );
    ~MDIWindow();

    void load( const QString& fn );
    void save();
    void saveAs();
    void print( QPrinter* );

signals:
    void message(const QString&, int );

private:
    QMultiLineEdit* medit;
    QMovie * mmovie;
    QString filename;
};

class ApplicationWindow: public QMainWindow
{
    Q_OBJECT
public:
    ApplicationWindow();
    ~ApplicationWindow();

private slots:
    MDIWindow* newDoc();
    void load();
    void save();
    void saveAs();
    void print();
    void closeWindow();
    void tileHorizontal();

    void about();
    void aboutQt();

    void windowsMenuAboutToShow();
    void windowsMenuActivated( int id );

private:
    QPrinter *printer;
    QWorkspace* ws;
    QToolBar *fileTools;
    QPopupMenu* windowsMenu;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/application.cpp   3.0.5   edited Jun 5 14:13 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "application.h"
#include <qworkspace.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qmovie.h>
#include <qmultilineedit.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qlabel.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qprinter.h>
#include <qapplication.h>
#include <qpushbutton.h>
#include <qaccel.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qwhatsthis.h>
#include <qobjectlist.h>
#include <qvbox.h>

#include "filesave.xpm"
#include "fileopen.xpm"
#include "fileprint.xpm"

const char * fileOpenText = "Click this button to open a <em>new file</em>. <br><br>"
"You can also select the <b>Open command</b> from the File menu.";
const char * fileSaveText = "Click this button to save the file you are "
"editing.  You will be prompted for a file name.\n\n"
"You can also select the Save command from the File menu.\n\n"
"Note that implementing this function is left as an exercise for the reader.";
const char * filePrintText = "Click this button to print the file you "
"are editing.\n\n"
"You can also select the Print command from the File menu.";

ApplicationWindow::ApplicationWindow()
    : QMainWindow( 0, "example application main window", WDestructiveClose )
{
    int id;

    QPixmap openIcon, saveIcon;

    fileTools = new QToolBar( this, "file operations" );
    addToolBar( fileTools, tr( "File Operations" ), DockTop, TRUE );

    openIcon = QPixmap( fileopen );
    QToolButton * fileOpen
        = new QToolButton( openIcon, "Open File", QString::null,
                           this, SLOT(load()), fileTools, "open file" );

    saveIcon = QPixmap( filesave );
    QToolButton * fileSave
        = new QToolButton( saveIcon, "Save File", QString::null,
                           this, SLOT(save()), fileTools, "save file" );

#ifndef QT_NO_PRINTER
    printer = new QPrinter;
    QPixmap printIcon;

    printIcon = QPixmap( fileprint );
    QToolButton * filePrint
        = new QToolButton( printIcon, "Print File", QString::null,
                           this, SLOT(print()), fileTools, "print file" );
    QWhatsThis::add( filePrint, filePrintText );
#endif

    (void)QWhatsThis::whatsThisButton( fileTools );

    QWhatsThis::add( fileOpen, fileOpenText );
    QWhatsThis::add( fileSave, fileSaveText );

    QPopupMenu * file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );

    file->insertItem( "&New", this, SLOT(newDoc()), CTRL+Key_N );

    id = file->insertItem( openIcon, "&Open...",
                           this, SLOT(load()), CTRL+Key_O );
    file->setWhatsThis( id, fileOpenText );

    id = file->insertItem( saveIcon, "&Save",
                           this, SLOT(save()), CTRL+Key_S );
    file->setWhatsThis( id, fileSaveText );
    id = file->insertItem( "Save &As...", this, SLOT(saveAs()) );
    file->setWhatsThis( id, fileSaveText );
#ifndef QT_NO_PRINTER
    file->insertSeparator();
    id = file->insertItem( printIcon, "&Print...",
                           this, SLOT(print()), CTRL+Key_P );
    file->setWhatsThis( id, filePrintText );
#endif
    file->insertSeparator();
    file->insertItem( "&Close", this, SLOT(closeWindow()), CTRL+Key_W );
    file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );

    windowsMenu = new QPopupMenu( this );
    windowsMenu->setCheckable( TRUE );
    connect( windowsMenu, SIGNAL( aboutToShow() ),
             this, SLOT( windowsMenuAboutToShow() ) );
    menuBar()->insertItem( "&Windows", windowsMenu );

    menuBar()->insertSeparator();
    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertItem( "&Help", help );

    help->insertItem( "&About", this, SLOT(about()), Key_F1);
    help->insertItem( "About &Qt", this, SLOT(aboutQt()));
    help->insertSeparator();
    help->insertItem( "What's &This", this, SLOT(whatsThis()), SHIFT+Key_F1);

    QVBox* vb = new QVBox( this );
    vb->setFrameStyle( QFrame::StyledPanel | QFrame::Sunken );
    ws = new QWorkspace( vb );
    ws->setScrollBarsEnabled( TRUE );
    setCentralWidget( vb );

    statusBar()->message( "Ready", 2000 );
}

ApplicationWindow::~ApplicationWindow()
{
#ifndef QT_NO_PRINTER
    delete printer;
#endif
}

MDIWindow* ApplicationWindow::newDoc()
{
    MDIWindow* w = new MDIWindow( ws, 0, WDestructiveClose );
    connect( w, SIGNAL( message(const QString&, int) ), statusBar(), SLOT( message(const QString&, int )) );
    w->setCaption("unnamed document");
    w->setIcon( QPixmap("document.xpm") );
    // show the very first window in maximized mode
    if ( ws->windowList().isEmpty() )
        w->showMaximized();
    else
        w->show();
    return w;
}

void ApplicationWindow::load()
{
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() ) {
        MDIWindow* w = newDoc();
        w->load( fn );
    }  else {
        statusBar()->message( "Loading aborted", 2000 );
    }
}

void ApplicationWindow::save()
{
    MDIWindow* m = (MDIWindow*)ws->activeWindow();
    if ( m )
        m->save();
}

void ApplicationWindow::saveAs()
{
    MDIWindow* m = (MDIWindow*)ws->activeWindow();
    if ( m )
        m->saveAs();
}

void ApplicationWindow::print()
{
#ifndef QT_NO_PRINTER
    MDIWindow* m = (MDIWindow*)ws->activeWindow();
    if ( m )
        m->print( printer );
#endif
}

void ApplicationWindow::closeWindow()
{
    MDIWindow* m = (MDIWindow*)ws->activeWindow();
    if ( m )
        m->close();
}

void ApplicationWindow::about()
{
    QMessageBox::about( this, "Qt Application Example",
                        "This example demonstrates simple use of\n "
                        "Qt's Multiple Document Interface (MDI).");
}

void ApplicationWindow::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Application Example" );
}

void ApplicationWindow::windowsMenuAboutToShow()
{
    windowsMenu->clear();
    int cascadeId = windowsMenu->insertItem("&Cascade", ws, SLOT(cascade() ) );
    int tileId = windowsMenu->insertItem("&Tile", ws, SLOT(tile() ) );
    int horTileId = windowsMenu->insertItem("Tile &Horizontally", this, SLOT(tileHorizontal() ) );
    if ( ws->windowList().isEmpty() ) {
        windowsMenu->setItemEnabled( cascadeId, FALSE );
        windowsMenu->setItemEnabled( tileId, FALSE );
        windowsMenu->setItemEnabled( horTileId, FALSE );
    }
    windowsMenu->insertSeparator();
    QWidgetList windows = ws->windowList();
    for ( int i = 0; i < int(windows.count()); ++i ) {
        int id = windowsMenu->insertItem(windows.at(i)->caption(),
                                         this, SLOT( windowsMenuActivated( int ) ) );
        windowsMenu->setItemParameter( id, i );
        windowsMenu->setItemChecked( id, ws->activeWindow() == windows.at(i) );
    }
}

void ApplicationWindow::windowsMenuActivated( int id )
{
    QWidget* w = ws->windowList().at( id );
    if ( w )
        w->showNormal();
    w->setFocus();
}

void ApplicationWindow::tileHorizontal()
{
    // primitive horizontal tiling
    QWidgetList windows = ws->windowList();
    if ( !windows.count() )
        return;

    int heightForEach = ws->height() / windows.count();
    int y = 0;
    for ( int i = 0; i < int(windows.count()); ++i ) {
        QWidget *window = windows.at(i);
        if ( window->testWState( WState_Maximized ) ) {
            // prevent flicker
            window->hide();
            window->showNormal();
        }
        int preferredHeight = window->minimumHeight()+window->parentWidget()->baseSize().height();
        int actHeight = QMAX(heightForEach, preferredHeight);

        window->parentWidget()->setGeometry( 0, y, ws->width(), actHeight );
        y += actHeight;
    }
}

MDIWindow::MDIWindow( QWidget* parent, const char* name, int wflags )
    : QMainWindow( parent, name, wflags )
{
    mmovie = 0;
    medit = new QMultiLineEdit( this );
    setFocusProxy( medit );
    setCentralWidget( medit );
}

MDIWindow::~MDIWindow()
{
    delete mmovie;
}

void MDIWindow::load( const QString& fn )
{
    filename  = fn;
    QFile f( filename );
    if ( !f.open( IO_ReadOnly ) )
        return;

    if(fn.contains(".gif")) {
        QWidget * tmp=new QWidget(this);
        setFocusProxy(tmp);
        setCentralWidget(tmp);
        medit->hide();
        delete medit;
        QMovie * qm=new QMovie(fn);
#ifdef Q_WS_QWS // temporary speed-test hack
        qm->setDisplayWidget(tmp);
#endif
        tmp->setBackgroundMode(QWidget::NoBackground);
        tmp->show();
        mmovie=qm;
    } else {
        mmovie = 0;

        QTextStream t(&f);
        QString s = t.read();
        medit->setText( s );
        f.close();

    }
    setCaption( filename );
    emit message( QString("Loaded document %1").arg(filename), 2000 );
}

void MDIWindow::save()
{
    if ( filename.isEmpty() ) {
        saveAs();
        return;
    }

    QString text = medit->text();
    QFile f( filename );
    if ( !f.open( IO_WriteOnly ) ) {
        emit message( QString("Could not write to %1").arg(filename),
                      2000 );
        return;
    }

    QTextStream t( &f );
    t << text;
    f.close();

    setCaption( filename );

    emit message( QString( "File %1 saved" ).arg( filename ), 2000 );
}

void MDIWindow::saveAs()
{
    QString fn = QFileDialog::getSaveFileName( filename, QString::null, this );
    if ( !fn.isEmpty() ) {
        filename = fn;
        save();
    } else {
        emit message( "Saving aborted", 2000 );
    }
}

void MDIWindow::print( QPrinter* printer)
{
#ifndef QT_NO_PRINTER
    const int Margin = 10;
    int pageNo = 1;

    if ( printer->setup(this) ) {               // printer dialog
        emit message( "Printing...", 0 );
        QPainter p;
        if ( !p.begin( printer ) )
            return;                             // paint on printer
        p.setFont( medit->font() );
        int yPos        = 0;                    // y position for each line
        QFontMetrics fm = p.fontMetrics();
        QPaintDeviceMetrics metrics( printer ); // need width/height
        // of printer surface
        for( int i = 0 ; i < medit->numLines() ; i++ ) {
            if ( Margin + yPos > metrics.height() - Margin ) {
                QString msg( "Printing (page " );
                msg += QString::number( ++pageNo );
                msg += ")...";
                emit message( msg, 0 );
                printer->newPage();             // no more room on this page
                yPos = 0;                       // back to top of page
            }
            p.drawText( Margin, Margin + yPos,
                        metrics.width(), fm.lineSpacing(),
                        ExpandTabs | DontClip,
                        medit->textLine( i ) );
            yPos = yPos + fm.lineSpacing();
        }
        p.end();                                // send job to printer
        emit message( "Printing completed", 2000 );
    } else {
        emit message( "Printing aborted", 2000 );
    }
#endif
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "application.h"

int main( int argc, char ** argv ) {
    QApplication a( argc, argv );
    ApplicationWindow * mw = new ApplicationWindow();
    mw->setCaption( "Qt Example - Multiple Documents Interface (MDI)" );
    mw->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    int res = a.exec();
    return res;
}

See also Examples.


Using menus

This example demonstrates simple use of menus (a menu bar and pull-down menus). Qt also supports popup menus, although this example doesn't contain any.

Header file:

/****************************************************************************
** $Id:  qt/menu.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef MENU_H
#define MENU_H

#include <qwidget.h>
#include <qmenubar.h>
#include <qlabel.h>

class MenuExample : public QWidget
{
    Q_OBJECT
public:
    MenuExample( QWidget *parent=0, const char *name=0 );

public slots:
    void open();
    void news();
    void save();
    void closeDoc();
    void undo();
    void redo();
    void normal();
    void bold();
    void underline();
    void about();
    void aboutQt();
    void printer();
    void file();
    void fax();
    void printerSetup();

protected:
    void    resizeEvent( QResizeEvent * );

signals:
    void    explain( const QString& );

private:
    QMenuBar *menu;
    QLabel   *label;
    bool isBold;
    bool isUnderline;
    int boldID, underlineID;
};

#endif // MENU_H

Implementation:

/****************************************************************************
** $Id:  qt/menu.cpp   3.0.5   edited Jan 29 19:01 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "menu.h"
#include <qpopupmenu.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qpixmap.h>
#include <qpainter.h>

/* XPM */
static const char * p1_xpm[] = {
"16 16 3 1",
"       c None",
".      c #000000000000",
"X      c #FFFFFFFF0000",
"                ",
"                ",
"         ....   ",
"        .XXXX.  ",
" .............. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .XXXXXXXXXXXX. ",
" .............. ",
"                "};

/* XPM */
static const char * p2_xpm[] = {
"16 16 3 1",
"       c None",
".      c #000000000000",
"X      c #FFFFFFFFFFFF",
"                ",
"   ......       ",
"   .XXX.X.      ",
"   .XXX.XX.     ",
"   .XXX.XXX.    ",
"   .XXX.....    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .XXXXXXX.    ",
"   .........    ",
"                ",
"                "};

/* XPM */
static const char * p3_xpm[] = {
"16 16 3 1",
"       c None",
".      c #000000000000",
"X      c #FFFFFFFFFFFF",
"                ",
"                ",
"   .........    ",
"  ...........   ",
"  ........ ..   ",
"  ...........   ",
"  ...........   ",
"  ...........   ",
"  ...........   ",
"  ...XXXXX...   ",
"  ...XXXXX...   ",
"  ...XXXXX...   ",
"  ...XXXXX...   ",
"   .........    ",
"                ",
"                "};

/*
  Auxiliary class to provide fancy menu items with different
  fonts. Used for the "bold" and "underline" menu items in the options
  menu.
 */
class MyMenuItem : public QCustomMenuItem
{
public:
    MyMenuItem( const QString& s, const QFont& f )
        : string( s ), font( f ){};
    ~MyMenuItem(){}

    void paint( QPainter* p, const QColorGroup& /*cg*/, bool /*act*/, bool /*enabled*/, int x, int y, int w, int h )
    {
        p->setFont ( font );
        p->drawText( x, y, w, h, AlignLeft | AlignVCenter | DontClip, string );
    }

    QSize sizeHint()
    {
        return QFontMetrics( font ).size( AlignLeft | AlignVCenter | ShowPrefix | DontClip,  string );
    }
private:
    QString string;
    QFont font;
};

MenuExample::MenuExample( QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    QPixmap p1( p1_xpm );
    QPixmap p2( p2_xpm );
    QPixmap p3( p3_xpm );

    QPopupMenu *print = new QPopupMenu( this );
    Q_CHECK_PTR( print );
    print->insertTearOffHandle();
    print->insertItem( "&Print to printer", this, SLOT(printer()) );
    print->insertItem( "Print to &file", this, SLOT(file()) );
    print->insertItem( "Print to fa&x", this, SLOT(fax()) );
    print->insertSeparator();
    print->insertItem( "Printer &Setup", this, SLOT(printerSetup()) );

    QPopupMenu *file = new QPopupMenu( this );
    Q_CHECK_PTR( file );
    file->insertItem( p1, "&Open",  this, SLOT(open()), CTRL+Key_O );
    file->insertItem( p2, "&New", this, SLOT(news()), CTRL+Key_N );
    file->insertItem( p3, "&Save", this, SLOT(save()), CTRL+Key_S );
    file->insertItem( "&Close", this, SLOT(closeDoc()), CTRL+Key_W );
    file->insertSeparator();
    file->insertItem( "&Print", print, CTRL+Key_P );
    file->insertSeparator();
    file->insertItem( "E&xit",  qApp, SLOT(quit()), CTRL+Key_Q );

    QPopupMenu *edit = new QPopupMenu( this );
    Q_CHECK_PTR( edit );
    int undoID = edit->insertItem( "&Undo", this, SLOT(undo()) );
    int redoID = edit->insertItem( "&Redo", this, SLOT(redo()) );
    edit->setItemEnabled( undoID, FALSE );
    edit->setItemEnabled( redoID, FALSE );

    QPopupMenu* options = new QPopupMenu( this );
    Q_CHECK_PTR( options );
    options->insertTearOffHandle();
    options->setCaption("Options");
    options->insertItem( "&Normal Font", this, SLOT(normal()) );
    options->insertSeparator();

    options->polish(); // adjust system settings
    QFont f = options->font();
    f.setBold( TRUE );
    boldID = options->insertItem( new MyMenuItem( "Bold", f ) );
    options->setAccel( CTRL+Key_B, boldID );
    options->connectItem( boldID, this, SLOT(bold()) );
    f = font();
    f.setUnderline( TRUE );
    underlineID = options->insertItem( new MyMenuItem( "Underline", f ) );
    options->setAccel( CTRL+Key_U, underlineID );
    options->connectItem( underlineID, this, SLOT(underline()) );

    isBold = FALSE;
    isUnderline = FALSE;
    options->setCheckable( TRUE );

    QPopupMenu *help = new QPopupMenu( this );
    Q_CHECK_PTR( help );
    help->insertItem( "&About", this, SLOT(about()), CTRL+Key_H );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );

    menu = new QMenuBar( this );
    Q_CHECK_PTR( menu );
    menu->insertItem( "&File", file );
    menu->insertItem( "&Edit", edit );
    menu->insertItem( "&Options", options );
    menu->insertSeparator();
    menu->insertItem( "&Help", help );
    menu->setSeparator( QMenuBar::InWindowsStyle );

    label = new QLabel( this );
    Q_CHECK_PTR( label );
    label->setGeometry( 20, rect().center().y()-20, width()-40, 40 );
    label->setFrameStyle( QFrame::Box | QFrame::Raised );
    label->setLineWidth( 1 );
    label->setAlignment( AlignCenter );

    connect( this,  SIGNAL(explain(const QString&)),
             label, SLOT(setText(const QString&)) );

    setMinimumSize( 100, 80 );
}

void MenuExample::open()
{
    emit explain( "File/Open selected" );
}

void MenuExample::news()
{
    emit explain( "File/New selected" );
}

void MenuExample::save()
{
    emit explain( "File/Save selected" );
}

void MenuExample::closeDoc()
{
    emit explain( "File/Close selected" );
}

void MenuExample::undo()
{
    emit explain( "Edit/Undo selected" );
}

void MenuExample::redo()
{
    emit explain( "Edit/Redo selected" );
}

void MenuExample::normal()
{
    isBold = FALSE;
    isUnderline = FALSE;
    menu->setItemChecked( boldID, isBold );
    menu->setItemChecked( underlineID, isUnderline );
    emit explain( "Options/Normal selected" );
}

void MenuExample::bold()
{
    isBold = !isBold;
    menu->setItemChecked( boldID, isBold );
    emit explain( "Options/Bold selected" );
}

void MenuExample::underline()
{
    isUnderline = !isUnderline;
    menu->setItemChecked( underlineID, isUnderline );
    emit explain( "Options/Underline selected" );
}

void MenuExample::about()
{
    QMessageBox::about( this, "Qt Menu Example",
                        "This example demonstrates simple use of Qt menus.\n"
                        "You can cut and paste lines from it to your own\n"
                        "programs." );
}

void MenuExample::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Menu Example" );
}

void MenuExample::printer()
{
    emit explain( "File/Printer/Print selected" );
}

void MenuExample::file()
{
    emit explain( "File/Printer/Print To File selected" );
}

void MenuExample::fax()
{
    emit explain( "File/Printer/Print To Fax selected" );
}

void MenuExample::printerSetup()
{
    emit explain( "File/Printer/Printer Setup selected" );
}

void MenuExample::resizeEvent( QResizeEvent * )
{
    label->setGeometry( 20, rect().center().y()-20, width()-40, 40 );
}

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );
    MenuExample m;
    m.setCaption("Qt Examples - Menus");
    a.setMainWidget( &m );
    m.show();
    return a.exec();
}

See also Examples.


元对象系统

Qt中的元对象系统是用来处理对象间通讯的信号/槽机制、运行时的类型信息和 动态属性系统。

它基于下列三类：

  1. QObject类；
  2. 类声明中的私有段中的Q_OBJECT宏；
  3. 元对象编译器（moc）。

moc读取C++源文件。如果它发现其中包 含一个或多个类的声明中含有Q_OBJECT宏，它就会给含有Q_OBJECT宏的类生成另一个 含有元对象代码的C++源文件。这个生成的源文件可以被类的源文件包含（#include） 到或者和这个类的实现一起编译和连接。

除了提供对象间通讯的信号和槽机制之 外（介绍这个系统的主要原因），QObject中的元对象代码实现其它特征：

  • className()函数在运行的时候以 字符串返回类的名称，不需要C++编译器中的本地运行类型信息（RTTI）的支持。

  • inherits()函数返回这个对象是否 是一个继承于QObject继承树中一个特定类的类的实例。

  • tr()和trUtf8() 两个函数是用于国际化中的字符串翻译。

  • setProperty()和property()两个函数是用来通过名称动态设置和 获得对象属性的。

  • metaObject()函数返回这个类 所关联的元对象。

虽然你使用QObject作为一个基类而不使用Q_OBJECT宏和元对象代码是可以的， 但是如果Q_OBJECT宏没有被使用，那么这里的信号和槽以及其它特征描述都不会被 提供。根据元对象系统的观点，一个没有元代码的QObject的子类和它含有元对象代 码的最近的祖先相同。举例来说就是，className()将不会返回你的类的实际名称， 返回的是它的这个祖先的名称。我们强烈建议QObject 的所有子类使用Q_OBJECT宏，而不管它们是否实际使用了信号、槽和属性。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Miscellaneous Classes

These classes are useful classes not fitting into any other category.

QAccel | Handles keyboard accelerator and shortcut keys
QAccessible | Enums and static functions relating to accessibility
QAccessibleInterface | Defines an interface that exposes information about accessible objects
QAccessibleObject | Implements parts of the QAccessibleInterface for QObjects
QCustomMenuItem | Abstract base class for custom menu items in popup menus
QDoubleValidator | Range checking of floating-point numbers
QErrorMessage | Error message display dialog
QFileIconProvider | Icons for QFileDialog to use
QFilePreview | File previewing in QFileDialog
QFocusData | Maintains the list of widgets in the focus chain
QIntValidator | Validator which ensures that a string contains a valid integer within a specified range
QKeySequence | Encapsulates a key sequence as used by accelerators
QMenuData | Base class for QMenuBar and QPopupMenu
QMimeSource | Abstraction of objects which provide formatted data of a certain MIME type
QProcess | Used to start external programs and to communicate with them
QRangeControl | Integer value within a range
QRegExp | Pattern matching using regular expressions
QRegExpValidator | Used to check a string against a regular expression
QSettings | Persistent platform-independent application settings
QSignal | Can be used to send signals for classes that don't inherit QObject
Qt | Namespace for miscellaneous identifiers that need to be global-like
QUrl | URL parser and simplifies working with URLs
QUrlInfo | Stores information about URLs
QUrlOperator | Common operations on URLs
QValidator | Validation of input text
QVariant | Acts like a union for the most common Qt data types
QWindowsMime | Maps open-standard MIME to Window Clipboard formats


Movies or the Story of the Animated GIF file

The Movies example displays animated GIF files using the QMovie and QLabel classes.

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Dec 18 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qfiledialog.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <qmovie.h>
#include <qvbox.h>

class MovieScreen : public QFrame {
    Q_OBJECT
    QMovie movie;
    QString filename;
    QSize sh;

public:
    MovieScreen(const char* fname, QMovie m, QWidget* p=0, const char* name=0, WFlags f=0) :
        QFrame(p, name, f),
        sh(100,100)
    {
        setCaption(fname);
        filename = fname;
        movie = m;

        // Set a frame around the movie.
        setFrameStyle(QFrame::WinPanel|QFrame::Sunken);

        // No background needed, since we draw on the whole widget.
        movie.setBackgroundColor(backgroundColor());
        setBackgroundMode(NoBackground);

        // Get the movie to tell use when interesting things happen.
        movie.connectUpdate(this, SLOT(movieUpdated(const QRect&)));
        movie.connectResize(this, SLOT(movieResized(const QSize&)));
        movie.connectStatus(this, SLOT(movieStatus(int)));

        setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
    }

    QSize sizeHint() const
    {
        return sh;
    }

protected:

    // Draw the contents of the QFrame - the movie and on-screen-display
    void drawContents(QPainter* p)
    {
        // Get the current movie frame.
        QPixmap pm = movie.framePixmap();

        // Get the area we have to draw in.
        QRect r = contentsRect();

        if ( !pm.isNull() ) {
            // Only rescale is we need to - it can take CPU!
            if ( r.size() != pm.size() ) {
                QWMatrix m;
                m.scale((double)r.width()/pm.width(),
                        (double)r.height()/pm.height());
                pm = pm.xForm(m);
            }

            // Draw the [possibly scaled] frame.  movieUpdated() below calls
            // repaint with only the changed area, so clipping will ensure we
            // only do the minimum amount of rendering.
            //
            p->drawPixmap(r.x(), r.y(), pm);
        }

        // The on-screen display

        const char* message = 0;

        if (movie.paused()) {
            message = "PAUSED";
        } else if (movie.finished()) {
            message = "THE END";
        } else if (movie.steps() > 0) {
            message = "FF >>";
        }

        if (message) {
            // Find a good font size...
            p->setFont(QFont("Helvetica", 24));

            QFontMetrics fm = p->fontMetrics();
            if ( fm.width(message) > r.width()-10 )
                p->setFont(QFont("Helvetica", 18));

            fm = p->fontMetrics();
            if ( fm.width(message) > r.width()-10 )
                p->setFont(QFont("Helvetica", 14));

            fm = p->fontMetrics();
            if ( fm.width(message) > r.width()-10 )
                p->setFont(QFont("Helvetica", 12));

            fm = p->fontMetrics();
            if ( fm.width(message) > r.width()-10 )
                p->setFont(QFont("Helvetica", 10));

            // "Shadow" effect.
            p->setPen(black);
            p->drawText(1, 1, width()-1, height()-1, AlignCenter, message);
            p->setPen(white);
            p->drawText(0, 0, width()-1, height()-1, AlignCenter, message);
        }
    }

public slots:
    void restart()
    {
        movie.restart();
        repaint();
    }

    void togglePause()
    {
        if ( movie.paused() )
            movie.unpause();
        else
            movie.pause();
        repaint();
    }

    void step()
    {
        movie.step();
        repaint();
    }

    void step10()
    {
        movie.step(10);
        repaint();
    }

private slots:
    void movieUpdated(const QRect& area)
    {
        if (!isVisible())
            show();

        // The given area of the movie has changed.

        QRect r = contentsRect();

        if ( r.size() != movie.framePixmap().size() ) {
            // Need to scale - redraw whole frame.
            repaint( r );
        } else {
            // Only redraw the changed area of the frame
            repaint( area.x()+r.x(), area.y()+r.x(),
                     area.width(), area.height() );
        }
    }

    void movieResized(const QSize& size)
    {
        // The movie changed size, probably from its initial zero size.

        int fw = frameWidth();
        sh = QSize( size.width() + fw*2, size.height() + fw*2 );
        updateGeometry();
        if ( parentWidget() && parentWidget()->isHidden() )
            parentWidget()->show();
    }

    void movieStatus(int status)
    {
        // The movie has sent us a status message.

        if (status < 0) {
            QString msg;
            msg.sprintf("Could not play movie \"%s\"", (const char*)filename);
            QMessageBox::warning(this, "movies", msg);
            parentWidget()->close();
        } else if (status == QMovie::Paused || status == QMovie::EndOfMovie) {
            repaint(); // Ensure status text is displayed
        }
    }
};

class MoviePlayer : public QVBox {
    MovieScreen* movie;
public:
    MoviePlayer(const char* fname, QMovie m, QWidget* p=0, const char* name=0, WFlags f=0) :
        QVBox(p,name,f)
    {
        movie = new MovieScreen(fname, m, this);
        QHBox* hb = new QHBox(this);
        QPushButton* btn;
        btn = new QPushButton("<<", hb);
        connect(btn, SIGNAL(clicked()), movie, SLOT(restart()));
        btn = new QPushButton("||", hb);
        connect(btn, SIGNAL(clicked()), movie, SLOT(togglePause()));
        btn = new QPushButton(">|", hb);
        connect(btn, SIGNAL(clicked()), movie, SLOT(step()));
        btn = new QPushButton(">>|", hb);
        connect(btn, SIGNAL(clicked()), movie, SLOT(step10()));
    }
};

// A QFileDialog that chooses movies.
//
class MovieStarter: public QFileDialog {
    Q_OBJECT
public:
    MovieStarter(const char *dir);

public slots:
    void startMovie(const QString& filename);
    // QDialog's method - normally closes the file dialog.
    // We want it left open, and we want Cancel to quit everything.
    void done( int r );
};

MovieStarter::MovieStarter(const char *dir)
    : QFileDialog(dir, "*.gif *.mng")
{
    //behave as in getOpenFilename
    setMode( ExistingFile );
    // When a file is selected, show it as a movie.
    connect(this, SIGNAL(fileSelected(const QString&)),
            this, SLOT(startMovie(const QString&)));
}

void MovieStarter::startMovie(const QString& filename)
{
    if ( filename ) // Start a new movie - have it delete when closed.
        (new MoviePlayer( filename, QMovie(filename), 0, 0,
                               WDestructiveClose))->show();
}

void MovieStarter::done( int r )
{
    if (r != Accepted)
        qApp->quit(); // end on Cancel
    setResult( r );

    // And don't hide.
}

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

    if (argc > 1) {
        // Commandline mode - show movies given on the command line
        //
        bool gui=TRUE;
        for (int arg=1; arg<argc; arg++) {
            if ( QString(argv[arg]) == "-i" )
                gui = !gui;
            else if ( gui )
                (void)new MoviePlayer(argv[arg], QMovie(argv[arg]), 0, 0,
                                      Qt::WDestructiveClose);
            else
                (void)new MovieScreen(argv[arg], QMovie(argv[arg]), 0, 0,
                                      Qt::WDestructiveClose);
        }
        QObject::connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));
    } else {
        // "GUI" mode - open a chooser for movies
        //
        MovieStarter* fd = new MovieStarter(".");
        fd->show();
    }

    // Go!
    return a.exec();
}

#include "main.moc"

See also Examples.


Multimedia Classes

These classes provide support for graphics, sound, animation etc.

QImageConsumer | Abstraction used by QImageDecoder
QImageDecoder | Incremental image decoder for all supported image formats
QImageFormat | Incremental image decoder for a specific image format
QImageFormatType | Factory that makes QImageFormat objects
QMovie | Incremental loading of animations or images, signalling as it progresses
QSound | Access to the platform audio facilities


Network Examples

The following example programs demonstrate the use of the Qt network module.

A small client-server example
An FTP client
A simple HTTP daemon
A simple mail client
A simple NNTP implementation

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


A simple NNTP implementation

This example shows how to implement your own QNetworkProtocol. The protocol that was chosen for this example is NTTP. Please note that this implementation is very simple since it is designed to be an example. It should not be used as a real NNTP implemention.

Header file (nntp.h):

/****************************************************************************
** $Id:  qt/nntp.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef NNTP_H
#define NNTP_H

#include <qsocket.h>
#include <qnetworkprotocol.h>

class Nntp : public QNetworkProtocol
{
    Q_OBJECT

public:
    Nntp();
    virtual ~Nntp();
    virtual int supportedOperations() const;

protected:
    virtual void operationListChildren( QNetworkOperation *op );
    virtual void operationGet( QNetworkOperation *op );

    QSocket *commandSocket;
    bool connectionReady;
    bool readGroups;
    bool readArticle;

private:
    bool checkConnection( QNetworkOperation *op );
    void close();
    void parseGroups();
    void parseArticle();

protected slots:
    void hostFound();
    void connected();
    void closed();
    void readyRead();
    void error( int );

};

#endif

Implementation (nntp.cpp):

/****************************************************************************
** $Id:  qt/nntp.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "nntp.h"
#include <qurlinfo.h>
#include <stdlib.h>
#include <qurloperator.h>
#include <qstringlist.h>
#include <qregexp.h>

Nntp::Nntp()
    : QNetworkProtocol(), connectionReady( FALSE ),
      readGroups( FALSE ), readArticle( FALSE )
{
    // create the command socket and connect to its signals
    commandSocket = new QSocket( this );
    connect( commandSocket, SIGNAL( hostFound() ),
             this, SLOT( hostFound() ) );
    connect( commandSocket, SIGNAL( connected() ),
             this, SLOT( connected() ) );
    connect( commandSocket, SIGNAL( connectionClosed() ),
             this, SLOT( closed() ) );
    connect( commandSocket, SIGNAL( readyRead() ),
             this, SLOT( readyRead() ) );
    connect( commandSocket, SIGNAL( error( int ) ),
             this, SLOT( error( int ) ) );
}

Nntp::~Nntp()
{
    close();
    delete commandSocket;
}

void Nntp::operationListChildren( QNetworkOperation * )
{
    // create a command
    QString path = url()->path(), cmd;
    if ( path.isEmpty() || path == "/" ) {
        // if the path is empty or we are in the root dir,
        // we want to read the list of available newsgroups
        cmd = "list newsgroups\r\n";
    } else if ( url()->isDir() ) {
        // if the path is a directory (in our case a news group)
        // we want to list the articles of this group
        path = path.replace( QRegExp( "/" ), "" );
        cmd = "listgroup " + path + "\r\n";
    } else
        return;

    // write the command to the socket
    commandSocket->writeBlock( cmd.latin1(), cmd.length() );
    readGroups = TRUE;
}

void Nntp::operationGet( QNetworkOperation *op )
{
    // get the dirPath of the URL (this is our news group)
    // and the filename (which is the article we want to read)
    QUrl u( op->arg( 0 ) );
    QString dirPath = u.dirPath(), file = u.fileName();
    dirPath = dirPath.replace( QRegExp( "/" ), "" );

    // go to the group in which the article is
    QString cmd;
    cmd = "group " + dirPath + "\r\n";
    commandSocket->writeBlock( cmd.latin1(), cmd.length() );

    // read the head of the article
    cmd = "article " + file + "\r\n";
    commandSocket->writeBlock( cmd.latin1(), cmd.length() );
    readArticle = TRUE;
}

bool Nntp::checkConnection( QNetworkOperation * )
{
    // we are connected, return TRUE
    if ( commandSocket->isOpen() && connectionReady )
        return TRUE;

    // seems that there is no chance to connect
    if ( commandSocket->isOpen() )
        return FALSE;

    // don't call connectToHost() if we are already trying to connect
    if ( commandSocket->state() == QSocket::Connecting )
        return FALSE;

    // start connecting
    connectionReady = FALSE;
    commandSocket->connectToHost( url()->host(),
                                  url()->port() != -1 ? url()->port() : 119 );
    return FALSE;
}

void Nntp::close()
{
    // close the command socket
    if ( commandSocket->isOpen() ) {
        commandSocket->writeBlock( "quit\r\n", strlen( "quit\r\n" ) );
        commandSocket->close();
    }
}

int Nntp::supportedOperations() const
{
    // we only support listing children and getting data
    return OpListChildren | OpGet;
}

void Nntp::hostFound()
{
    if ( url() )
        emit connectionStateChanged( ConHostFound, tr( "Host %1 found" ).arg( url()->host() ) );
    else
        emit connectionStateChanged( ConHostFound, tr( "Host found" ) );
}

void Nntp::connected()
{
    if ( url() )
        emit connectionStateChanged( ConConnected, tr( "Connected to host %1" ).arg( url()->host() ) );
    else
        emit connectionStateChanged( ConConnected, tr( "Connected to host" ) );
}

void Nntp::closed()
{
    if ( url() )
        emit connectionStateChanged( ConClosed, tr( "Connection to %1 closed" ).arg( url()->host() ) );
    else
        emit connectionStateChanged( ConClosed, tr( "Connection closed" ) );
}

void Nntp::readyRead()
{
    // new data arrived on the command socket

    // of we should read the list of available groups, let's do so
    if ( readGroups ) {
        parseGroups();
        return;
    }

    // of we should read an article, let's do so
    if ( readArticle ) {
        parseArticle();
        return;
    }

    // read the new data from the socket
    QCString s;
    s.resize( commandSocket->bytesAvailable() );
    commandSocket->readBlock( s.data(), commandSocket->bytesAvailable() );

    if ( !url() )
        return;

    // of the code of the server response was 200, we know that the
    // server is ready to get commands from us now
    if ( s.left( 3 ) == "200" )
        connectionReady = TRUE;
}

void Nntp::parseGroups()
{
    if ( !commandSocket->canReadLine() )
        return;

    // read one line after the other
    while ( commandSocket->canReadLine() ) {
        QString s = commandSocket->readLine();

        // if the  line starts with a dot, all groups or articles have been listed,
        // so we finished processing the listChildren() command
        if ( s[ 0 ] == '.' ) {
            readGroups = FALSE;
            operationInProgress()->setState( StDone );
            emit finished( operationInProgress() );
            return;
        }

        // if the code of the server response is 215 or 211
        // the next line will be the first group or article (depending on what we read).
        // So let others know that we start reading now...
        if ( s.left( 3 ) == "215" || s.left( 3 ) == "211" ) {
            operationInProgress()->setState( StInProgress );
            emit start( operationInProgress() );
            continue;
        }

        // parse the line and create a QUrlInfo object
        // which describes the child (group or article)
        bool tab = s.find( '\t' ) != -1;
        QString group = s.mid( 0, s.find( tab ? '\t' : ' ' ) );
        QUrlInfo inf;
        inf.setName( group );
        QString path = url()->path();
        inf.setDir( path.isEmpty() || path == "/" );
        inf.setSymLink( FALSE );
        inf.setFile( !inf.isDir() );
        inf.setWritable( FALSE );
        inf.setReadable( TRUE );

        // let others know about our new child
        emit newChild( inf, operationInProgress() );
    }

}

void Nntp::parseArticle()
{
    if ( !commandSocket->canReadLine() )
        return;

    // read an article one line after the other
    while ( commandSocket->canReadLine() ) {
        QString s = commandSocket->readLine();

        // if the  line starts with a dot, we finished reading something
        if ( s[ 0 ] == '.' ) {
            readArticle = FALSE;
            operationInProgress()->setState( StDone );
            emit finished( operationInProgress() );
            return;
        }

        if ( s.right( 1 ) == "\n" )
            s.remove( s.length() - 1, 1 );

        // emit the new data of the article which we read
        emit data( QCString( s.ascii() ), operationInProgress() );
    }
}

void Nntp::error( int code )
{
    if ( code == QSocket::ErrHostNotFound ||
         code == QSocket::ErrConnectionRefused ) {
        // this signal is called if connecting to the server failed
        if ( operationInProgress() ) {
            QString msg = tr( "Host not found or couldn't connect to: \n" + url()->host() );
            operationInProgress()->setState( StFailed );
            operationInProgress()->setProtocolDetail( msg );
            operationInProgress()->setErrorCode( (int)ErrHostNotFound );
            clearOperationQueue();
            emit finished( operationInProgress() );
        }
    }
}

See also Network Examples.


Qt-based LiveConnect Plugins

The Qt-based Netscape Plugin software makes it easy to write plugins that can be used on both Unix/Linux and Windows/95/NT, in Netscape and Internet Explorer, and any other web browser supporting the same protocol.

How-to

  1. Download the Plugin SDK from Netscape, and copy the following files from there to $QTDIR/extensions/nsplugin/src
    • common/npwin.cpp
    • common/npunix.c
    • include/npapi.h
    • include/npupp.h
    • include/jri.h
    • include/jri_md.h
    • include/jritypes.h
  2. Build the Netscape Plugin extension library, found in the extensions/nsplugin/src directory of your Qt distribution. This produces a static library to be linked with your plugin code.
  3. Read the plugin class documentation, and examine the example plugins.
  4. Do most of your development as a stand-alone Qt application - debugging Netscape Plugins is cumbersome. You may want to use signal(2) in your plugin to enable core-dumps if your browser disables them.
  5. Note the platform-specific build steps below.
  6. Read about the raw plugin interface in Netscape's handbook.
  7. If files viewed by a plugin are provided by an HTTP server (using a http://... URL) then the server must be configured to send the correct MIME type for the file, e.g. by editing Apache's mime.types file. If the files are viewed via a //... URL, then the browser will use the filename extension to decide the file type (and hence the plugin to load) - the user may need to set the filename extension in the Helpers or Applications section of their browser preferences.

Building under X11

  • The Makefiles in the examples are appropriate for UNIX/X11.
  • The user must install the resulting Shared Object in the Plugins directory of the browser.

Building under Windows

  • Qt needs to be built as a static library when building Netscape plugins.
  • Plugins must be named np name.dll, or the browser will ignore them.
  • The link step must include:
    • /def:name.def
    • /dll
    • a compiled resource file defining the file/MIME types accepted by the plugin.
  • The user must install the resulting DLL in the Plugins directory of the browser.

Known Bugs

The Qt-based LiveConnect Plugin binding code has a number of minor bugs, but is sufficiently stable for many production applications.

  • MSIE 4.0 support is poor.
  • Crashes on X11 if window is closed via window manager.
  • Keyboard problems on Windows.


LiveConnect Examples

The following example programs show how to write plugins that can be used with web browsers supporting the LiveConnect protocol.

For more information see the Plugin Howto.

Grapher Plugin
Display Images in Qt-supported Formats
Trivial Example

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


Object Model

These classes form the basis of the Qt Object Model.

QGuardedPtr | Template class that provides guarded pointers to QObjects
QMetaObject | Meta information about Qt objects
QMetaProperty | Stores meta data about a property
QObject | The base class of all Qt objects
QObjectCleanupHandler | Watches the lifetime of multiple QObjects
QVariant | Acts like a union for the most common Qt data types


对象树和对象所有权

QObject在对象树中组织它们自己。当你以另外一个对象作为 父对象来创建一个QObject时，它就被添加到父对象的children() 列表中，并且当父对象被删除的时候，它也会被删除。这种机制很好的适合了图形用户 界面应用对象的需要。例如，一个QAccel(键盘快捷键)是相关窗口的子对象，当用户 关闭该窗口的时候，这个快捷键也被删除了。

静态函数QObject::objectTrees()提供了访问当前存在的所有跟对象的方法。

QWidget，在屏幕上显示的任何东西的基类，扩展着父-子对象关系。一个子 对象通常就是一个子窗口部件，也就是说，它被显示在父对象的坐标系统中并且 在图象上由父对象的边界夹住。例如，当一个应用程序在一个消息框被关闭之后 删除这个消息框时，消息框的按钮和标签正如我们所想要的也被删除了，因为这些 按钮和标签都是消息框的子对象。

你也可以自己删除子对象，这样它们就会把它们自己从它们的父对象中移除。例如， 当用户移除工具条可以导致应用程序删除它的一个QToolBar对象，在这种情况 工具条的QMainWindow父对象会检测到这种变化并因此而重新构成屏幕空间。

当一个应用程序的看起来或者运行起来有些奇怪的时候，调试函数QObject::dumpObjectTree() 和QObject::dumpObjectInfo()是经常有用的。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


OpenGL Box Example

This example demonstrates how to use OpenGL in Qt.

Essentially, all you do is put your OpenGL code in a class inherited from QGLWidget. This class may then be used like any other Qt widget, including the use of signals and slots and geometry management.

See $QTDIR/examples/opengl/box for the source code.

See also OpenGL Examples.


OpenGL Examples

The following example programs demonstrate the use of the Qt OpenGL module.

OpenGL Box Example
OpenGL Gear Example
OpenGL Overlay Example
OpenGL Overlay X11 Example
OpenGL Pixmap Example
OpenGL Shared Box Example
OpenGL Texture Example

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


OpenGL Gear Example

This example demonstrates how to use OpenGL display lists.

See $QTDIR/examples/opengl/gear for the source code.

See also OpenGL Examples.


OpenGL Overlay Example

This example demonstrates how to use OpenGL overlays with the Qt OpenGL Extension. It features a QGLWidget with a relatively expensive redrawing operation, and rubber-band drawing in the overlay plane. Using the overlay has the advantage that the rubber-band may be drawn and erased without damaging the image in the main plane, so costly redraws are avoided.

See $QTDIR/examples/opengl/overlay for the source code.

See also OpenGL Examples.


OpenGL Overlay X11 Example

Warning: From version 5.0 onwards, the Qt OpenGL Extension includes direct support for use of OpenGL overlays. For many uses of overlays, this makes the technique described below redundant. See the overlay example program. The following is a discussion on how to use non-QGL widgets in overlay planes.

Overlayrubber: An example program showing how to use Qt and Qt OpenGL Extension with X11 overlay visuals.

See $QTDIR/examples/opengl/overlay_x11 for the source code.

Background information for this example can be found in the information on overlays.

The example program has three main parts:

  1. GearWidget - a normal, simple QGLWidget. This renders the usual gears. It has been modified to print a debug message every time it redraws (renders) itself. Thus, you can easily confirm that drawing in the overlay plane does not cause redrawings in the main plane where the QGLWidget resides.

  2. RubberbandWidget - Very simple standard (non-GL) Qt widget that implements rubberband drawing. Designed for use in an overlay plane. It takes the plane's transparent color as a constructor argument and uses that for its background color. Thus, the widget itself will be invisible, only the rubberbands it draws will be visible.

  3. main.cpp Creates a GearWidget and a Rubberbandwidget and puts the latter on top of the former. Contains a routine that checks that the default visual is in an overlay plane, and returns the transparent color of that plane.

Running the Example

Start the overlayrubber executable. Click and drag with the left mouse button to see rubberband drawing. Observe that the QGLWidget does not redraw itself (no redraw debug messages are output), and yet the image is not destroyed. Marvel at the coolness of X11 overlays!

Using this technique in a real application

For clarity, this example program has been kept very simple. Here are some hints for real application usage:

  • All normal widgets are in the overlay plane. This means that you can put all kinds of Qt widgets (your own or standard Qt widgets) on top of the OpenGL image (widget), e.g. pushbuttons etc., and they can be moved, resized, or removed without destroying the OpenGL image.

  • Using with geometry management. The QLayout classes don't permit putting one widget (the overlay) on top of another (the OpenGL widget); that would defy the whole purpose of the automatic layout. The solution is to add just one of them to the QLayout object. Have it keep a pointer to the other (i.e. the QGLWidget knows about its overlay widget or vice versa). Implement the resizeEvent() method of the widget you put in the layout, and make it call setGeometry() on the other widget with its own geometry as parameters, thus keeping the two widgets' geometries synchronized.

  • Using together with QPalette and QColorGroup. Instead of the simplistic setBackgroundColor( transparentColor ), you can use Qt's QPalette system to make your overlay widgets use transparent color for what you want. This way, the normal Qt widgets can be used as overlays for fancy effects. Just create a palette for them with the transparent color for the relevant color roles, e.g. Background and Base, in the Normal and/or Active modes. This way, you can create see-through QPushButtons etc.

See also OpenGL Examples.


OpenGL Pixmap Example

This example program is an extension of the OpenGL Box example.

It demonstrates how to render OpenGL into a QPixmap.

See $QTDIR/examples/opengl/glpixmap for the source code.

See also OpenGL Examples.


OpenGL Shared Box Example

This example program is an extension of the Box example.

It demonstrates how to use OpenGL display list sharing with QGLWidgets.

See $QTDIR/examples/opengl/sharedbox for the source code.

See also OpenGL Examples.


OpenGL Texture Example

This example program demonstrates how to use OpenGL 2D textures.

See $QTDIR/examples/opengl/texture for the source code.

See also OpenGL Examples.


How to use X11 overlays with the Qt OpenGL extension

X11 overlays are a powerful mechanism for drawing annotations etc., on top of an image without destroying it, thus saving a great deal of image rendering time. For more information, consult the highly recommended book OpenGL Programming for the X Window System (Mark Kilgard, Addison Wesley Developers Press 1996).

Warning: From version 5.0 onwards, the Qt OpenGL Extension includes direct support for the use of OpenGL overlays. For many uses of overlays, this makes the technique described below redundant. See the overlay example program. The following is a discussion on how to use non-QGL widgets in overlay planes.

In the typical case, X11 overlays can easily be used together with the current version of Qt and the Qt OpenGL Extension. The following requirements apply:

  1. Your X server and graphics card/hardware must support overlays. For many X servers, overlay support can be turned on with a configuration option; consult your X server installation documentation.

  2. Your X server must (be configured to) use an overlay visual as the default visual. Most modern X servers do this, since this has the added advantage that pop-up menus, overlapping windows etc., will not destroy underlying images in the main plane, thereby avoiding expensive redraws.

  3. The best (deepest) visual for OpenGL rendering is in the main plane. This is the normal case. Typically, X servers that support overlays provide a 24 bit deep TrueColor visual in the main plane, and an 8 bit PseudoColor (default) visual in the overlay plane.

The provided example program X11 overlay will check for these and report if anything is wrong. See About X11 Visuals, below for more information.

How it works

Given the above, a QGLWidget will by default use the main plane visual, while all other widgets will use the overlay visual. Thus, we can place a normal widget on top of the QGLWidget, and do drawing on it, without destroying the image in the OpenGL window. In other words, we can use all the drawing capabilities of QPainter to draw the annotations, rubberbands, etc. For the typical use of overlays, this is much easier than using OpenGL for rendering the annotations.

An overlay plane has a specific color called the transparent color. Pixels drawn in this color will not be visible; instead the underlying OpenGL image will show through. In the example program X11 overlay, the file main.cpp contains a routine that returns a QColor containing the transparent color. For the overlay widget, you will typically want to set the background color to the transparent color, so that the OpenGL image shows through except where explicitly overpainted.

Note: to use this technique, you must not use the "ManyColor" or "TrueColor" ColorSpec for QApplication, because this will force the normal Qt widgets to use a TrueColor visual, which will typically be in the main plane, not in the overlay plane as desired.

About X11 visuals

The utilities directory contains two small programs that can help you determine the capabilities of your X server. These programs are from the OpenGL book mentioned above, see utilities/NOTICE for copyright information. The full set of example programs from this book is available at ftp://ftp.sgi.com/pub/opengl/opengl_for_x/.

glxvisuals will list all the GL-capable visuals the X server provides, together with the depth and other GL-specific information for each. Note especially the column "lvl"; a number in this column means the visual is in an overlay plane.

sovinfo will list all available visuals, and provides special transparency information for overlay visuals.

The X11 overlay example program will output what visual is used for the normal Qt widgets, and what visual is used by the QGLWidget.


Organizers

These classes are used to organize and group GUI primitives into more complex applications or dialogs.

QButtonGroup | Organizes QButton widgets in a group
QGroupBox | Group box frame with a title
QHBox | Horizontal geometry management for its child widgets
QHButtonGroup | Organizes QButton widgets in a group with one horizontal row
QHGroupBox | Organizes widgets in a group with one horizontal row
QSplitter | Implements a splitter widget
QTabWidget | Stack of tabbed widgets
QVBox | Vertical geometry management of its child widgets
QVButtonGroup | Organizes QButton widgets in a vertical column
QVGroupBox | Organizes a group of widgets in a vertical column
QWidgetStack | Stack of widgets of which only the top widget is user-visible
QWizard | Framework for wizard dialogs
QWorkspace | Workspace window that can contain decorated windows, e.g. for MDI


Outliner to show use of DOM

This example presents a small outliner program to show the basic usage of the DOM classes. The format of the outlines is the OPML format as described in http://www.opml.org/spec.

This example shows how to load a DOM tree from an XML file and how to traverse it.

Sample XML file (todos.opml):

<?xml version="1.0" encoding="ISO-8859-1"?>
<opml version="1.0">
    <head>
        <title>Todo List</title>
        <dateCreated>Tue, 31 Oct 2000 17:00:17 CET</dateCreated>
        <dateModified>Tue, 31 Oct 2000 17:00:17 CET</dateModified>
        <ownerName>Arthur Dent</ownerName>
        <ownerEmail>info@trolltech.com</ownerEmail>
    </head>
    <body>
        <outline text="Background">
            <outline text="This is an example todo list."/>
        </outline>
        <outline text="Books to read">
            <outline text="Science Fiction">
                <outline text="Philip K. Dick">
                    <outline text="Do Androids Dream of Electical Sheep?"/>
                    <outline text="The Three Stigmata of Palmer Eldritch"/>
                </outline>
                <outline text="Robert A. Heinlein">
                    <outline text="Stranger in a Strange Land"/>
                </outline>
                <outline text="Isaac Asimov">
                    <outline text="Foundation and Empire"/>
                </outline>
            </outline>
            <outline text="Qt Books (in English)">
                <outline text="Dalheimer: Programming with Qt"/>
                <outline text="Griffith: KDE 2/Qt Programming Bible"/>
                <outline text="Hughes: Linux Rapid Application Development"/>
                <outline text="Solin: Qt Programming in 24 hours"/>
                <outline text="Ward: Qt 2 Programming for Linux and Windows 2000"/>
            </outline>
        </outline>
        <outline text="Shopping list">
            <outline text="General">
                <outline text="Towel"/>
                <outline text="Hair dryer"/>
                <outline text="Underpants"/>
            </outline>
            <outline text="For Sunday">
                <outline text="Beef"/>
                <outline text="Rice"/>
                <outline text="Carrots"/>
                <outline text="Beans"/>
                <outline text="Beer"/>
                <outline text="Wine"/>
                <outline text="Orange juice"/>
            </outline>
        </outline>
        <outline text="Write a letter to Ford">
        </outline>
    </body>
</opml>

Header file (outlinetree.h):

/****************************************************************************
** $Id:  qt/outlinetree.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef OUTLINETREE_H
#define OUTLINETREE_H

#include <qlistview.h>
#include <qdom.h>

class OutlineTree : public QListView
{
    Q_OBJECT

public:
    OutlineTree( const QString fileName, QWidget *parent = 0, const char *name = 0 );
    ~OutlineTree();

private:
    QDomDocument domTree;
    void getHeaderInformation( const QDomElement &header );
    void buildTree( QListViewItem *parentItem, const QDomElement &parentElement );
};

#endif // OUTLINETREE_H

Implementation (outlinetree.cpp):

/****************************************************************************
** $Id:  qt/outlinetree.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "outlinetree.h"
#include <qfile.h>
#include <qmessagebox.h>

OutlineTree::OutlineTree( const QString fileName, QWidget *parent, const char *name )
    : QListView( parent, name )
{
    // div. configuration of the list view
    addColumn( "Outlines" );
    setSorting( -1 );
    setRootIsDecorated( TRUE );

    // read the XML file and create DOM tree
    QFile opmlFile( fileName );
    if ( !opmlFile.open( IO_ReadOnly ) ) {
        QMessageBox::critical( 0,
                tr( "Critical Error" ),
                tr( "Cannot open file %1" ).arg( fileName ) );
        return;
    }
    if ( !domTree.setContent( &opmlFile ) ) {
        QMessageBox::critical( 0,
                tr( "Critical Error" ),
                tr( "Parsing error for file %1" ).arg( fileName ) );
        opmlFile.close();
        return;
    }
    opmlFile.close();

    // get the header information from the DOM
    QDomElement root = domTree.documentElement();
    QDomNode node;
    node = root.firstChild();
    while ( !node.isNull() ) {
        if ( node.isElement() && node.nodeName() == "head" ) {
            QDomElement header = node.toElement();
            getHeaderInformation( header );
            break;
        }
        node = node.nextSibling();
    }
    // create the tree view out of the DOM
    node = root.firstChild();
    while ( !node.isNull() ) {
        if ( node.isElement() && node.nodeName() == "body" ) {
            QDomElement body = node.toElement();
            buildTree( 0, body );
            break;
        }
        node = node.nextSibling();
    }
}

OutlineTree::~OutlineTree()
{
}

void OutlineTree::getHeaderInformation( const QDomElement &header )
{
    // visit all children of the header element and look if you can make
    // something with it
    QDomNode node = header.firstChild();
    while ( !node.isNull() ) {
        if ( node.isElement() ) {
            // case for the different header entries
            if ( node.nodeName() == "title" ) {
                QDomText textChild = node.firstChild().toText();
                if ( !textChild.isNull() ) {
                    setColumnText( 0, textChild.nodeValue() );
                }
            }
        }
        node = node.nextSibling();
    }
}

void OutlineTree::buildTree( QListViewItem *parentItem, const QDomElement &parentElement )
{
    QListViewItem *thisItem = 0;
    QDomNode node = parentElement.firstChild();
    while ( !node.isNull() ) {
        if ( node.isElement() && node.nodeName() == "outline" ) {
            // add a new list view item for the outline
            if ( parentItem == 0 )
                thisItem = new QListViewItem( this, thisItem );
            else
                thisItem = new QListViewItem( parentItem, thisItem );
            thisItem->setText( 0, node.toElement().attribute( "text" ) );
            // recursive build of the tree
            buildTree( thisItem, node.toElement() );
        }
        node = node.nextSibling();
    }
}

Main (main.cpp):

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "outlinetree.h"

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

    OutlineTree outline( "todos.opml" );
    a.setMainWidget( &outline );
    outline.show();

    return a.exec();
}

See also Qt XML Examples.


Picture

This example shows how to make a picture, store it to a file, and read it as a set of drawing commands.

Implementation:

/****************************************************************************
** $Id:  qt/picture.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qpainter.h>
#include <qpicture.h>
#include <qpixmap.h>
#include <qwidget.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <ctype.h>

void paintCar( QPainter *p )                    // paint a car
{
    QPointArray a;
    QBrush brush( Qt::yellow, Qt::SolidPattern );
    p->setBrush( brush );                       // use solid, yellow brush

    a.setPoints( 5, 50,50, 350,50, 450,120, 450,250, 50,250 );
    p->drawPolygon( a );                        // draw car body

    QFont f( "courier", 12, QFont::Bold );
    p->setFont( f );

    QColor windowColor( 120, 120, 255 );        // a light blue color
    brush.setColor( windowColor );              // set this brush color
    p->setBrush( brush );                       // set brush
    p->drawRect( 80, 80, 250, 70 );             // car window
    p->drawText( 180, 80, 150, 70, Qt::AlignCenter, "--  Qt  --\nTrolltech AS" );

    QPixmap pixmap;
    if ( pixmap.load("flag.bmp") )              // load and draw image
        p->drawPixmap( 100, 85, pixmap );

    p->setBackgroundMode( Qt::OpaqueMode );     // set opaque mode
    p->setBrush( Qt::DiagCrossPattern );        // black diagonal cross pattern
    p->drawEllipse( 90, 210, 80, 80 );          // back wheel
    p->setBrush( Qt::CrossPattern );            // black cross fill pattern
    p->drawEllipse( 310, 210, 80, 80 );         // front wheel
}

class PictureDisplay : public QWidget           // picture display widget
{
public:
    PictureDisplay( const char *fileName );
   ~PictureDisplay();
protected:
    void        paintEvent( QPaintEvent * );
    void        keyPressEvent( QKeyEvent * );
private:
    QPicture   *pict;
    QString     name;
};

PictureDisplay::PictureDisplay( const char *fileName )
{
    pict = new QPicture;
    name = fileName;
    if ( !pict->load(fileName) ) {              // cannot load picture
        delete pict;
        pict = 0;
        name.sprintf( "Not able to load picture: %s", fileName );
    }
}

PictureDisplay::~PictureDisplay()
{
    delete pict;
}

void PictureDisplay::paintEvent( QPaintEvent * )
{
    QPainter paint( this );                     // paint widget
    if ( pict )
        paint.drawPicture( *pict );             // draw picture
    else
        paint.drawText( rect(), AlignCenter, name );
}

void PictureDisplay::keyPressEvent( QKeyEvent *k )
{
    switch ( tolower(k->ascii()) ) {
        case 'r':                               // reload
            pict->load( name );
            update();
            break;
        case 'q':                               // quit
            QApplication::exit();
            break;
    }
}

int main( int argc, char **argv )
{
    QApplication a( argc, argv );               // QApplication required!

    const char *fileName = "car.pic";           // default picture file name

    if ( argc == 2 )                            // use argument as file name
        fileName = argv[1];

    if ( !QFile::exists(fileName) ) {
        QPicture pict;                          // our picture
        QPainter paint;                         // our painter

        paint.begin( &pict );                   // begin painting onto picture
        paintCar( &paint );                     // paint!
        paint.end();                            // painting done

        pict.save( fileName );                  // save picture
        QMessageBox::information(0, "Qt Example - Picture", "Saved.  Run me again!");
        return 0;
    } else {
        PictureDisplay test( fileName );        // create picture display
        a.setMainWidget( &test);                // set main widget
        test.setCaption("Qt Example - Picture");
        test.show();                            // show it

        return a.exec();                        // start event loop
    }
}

See also Examples.


Plugins

These classes are used with Qt plugins. See the plugins documentation.

QImageFormatPlugin | Abstract base for custom image format plugins
QSqlDriverPlugin | Abstract base for custom QSqlDriver plugins
QStylePlugin | Abstract base for custom QStyle plugins
QTextCodecPlugin | Abstract base for custom QTextCodec plugins
QWidgetPlugin | Abstract base for custom QWidget plugins


Popup Widgets

This example shows how to implement widgets that should pop up.

Header file:

/****************************************************************************
** $Id:  qt/popup.h   3.0.5   edited Oct 12 2001 $
**
** Definition of something or other
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef POPUP_H
#define POPUP_H
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlineedit.h>

class FancyPopup : public QLabel
{
    Q_OBJECT
public:
    FancyPopup( QWidget* parent = 0, const char*  name=0);

    void popup( QWidget* parent = 0);
protected:
    virtual void mouseMoveEvent( QMouseEvent * );
    virtual void mouseReleaseEvent( QMouseEvent * );
    virtual void closeEvent( QCloseEvent * );

private:
    QWidget* popupParent;
    int moves;
};

 class Frame : public QFrame
 {
     Q_OBJECT
 public:
     Frame( QWidget *parent=0, const char*  name=0);

 protected:

 private slots:
     void button1Clicked();
     void button2Pressed();

 private:
     QPushButton *button1;
     QPushButton *button2;

     QFrame* popup1;
     FancyPopup* popup2;
 };

#endif

Implementation:

/****************************************************************************
** $Id:  qt/popup.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "popup.h"
#include <qapplication.h>
#include <qlayout.h>

FancyPopup::FancyPopup( QWidget* parent, const char*  name ):
    QLabel( parent, name, WType_Popup ){
        setFrameStyle( WinPanel|Raised );
        setAlignment( AlignCenter );
        resize(150,100);
        moves = 0;
        setMouseTracking( TRUE );
}

void FancyPopup::mouseMoveEvent( QMouseEvent * e){
    moves++;
    QString s;
    s.sprintf("%d/%d", e->pos().x(), e->pos().y());
    if (e->state() & QMouseEvent::LeftButton)
        s += " (down)";
    setText(s);
}

void FancyPopup::mouseReleaseEvent( QMouseEvent * e){
    if  (rect().contains( e->pos() ) || moves > 5)
        close();
}

void FancyPopup::closeEvent( QCloseEvent *e ){
    e->accept();
    moves = 0;
    if (!popupParent)
        return;

    // remember that we (as a popup) might recieve the mouse release
    // event instead of the popupParent. This is due to the fact that
    // the popupParent popped us up in its mousePressEvent handler. To
    // avoid the button remaining in pressed state we simply send a
    // faked mouse button release event to it.
    QMouseEvent me( QEvent::MouseButtonRelease, QPoint(0,0), QPoint(0,0), QMouseEvent::LeftButton, QMouseEvent::NoButton);
    QApplication::sendEvent( popupParent, &me );
}

void FancyPopup::popup( QWidget* parent) {
    popupParent = parent;
    setText("Move the mouse!");
    if (popupParent)
        move( popupParent->mapToGlobal( popupParent->rect().bottomLeft() ) );
    show();
}

Frame::Frame(QWidget* parent, const char* name): QFrame(parent, name){
    button1 = new QPushButton("Simple Popup", this);
    connect ( button1, SIGNAL( clicked() ), SLOT( button1Clicked() ) );
    button2 = new QPushButton("Fancy Popup", this);
    connect ( button2, SIGNAL( pressed() ), SLOT( button2Pressed() ) );

    QBoxLayout * l = new QHBoxLayout( this );
    button1->setMaximumSize(button1->sizeHint());
    button2->setMaximumSize(button2->sizeHint());
    l->addWidget( button1 );
    l->addWidget( button2 );
    l->activate();

//     button1->setGeometry(20,20,100,30);
//     button2->setGeometry(140,20,100,30);
    resize(270, 70);

    //create a very simple popup: it is just composed with other
    //widget and will be shown after clicking on button1

    popup1 = new QFrame( this ,0, WType_Popup);
    popup1->setFrameStyle( WinPanel|Raised );
    popup1->resize(150,100);
    QLineEdit *tmpE = new QLineEdit( popup1 );
    connect( tmpE, SIGNAL( returnPressed() ), popup1, SLOT( hide() ) );
    tmpE->setGeometry(10,10, 130, 30);
    tmpE->setFocus();
    QPushButton *tmpB = new QPushButton("Click me!", popup1);
    connect( tmpB, SIGNAL( clicked() ), popup1, SLOT( close() ) );
    tmpB->setGeometry(10, 50, 130, 30);

    // the fancier version uses its own class. It will be shown when
    // pressing button2, so they behavior is more like a modern menu
    // or toolbar.

    popup2 = new FancyPopup( this );

    // you might also add new widgets to the popup, just like you do
    // it with any other widget.  The next four lines (if not
    // commented out) will for instance add a line edit widget.

//     tmpE = new QLineEdit( popup2 );
//     tmpE->setFocus();
//     connect( tmpE, SIGNAL( returnPressed() ), popup2, SLOT( close() ) );
//     tmpE->setGeometry(10, 10, 130, 30);
}

void Frame::button1Clicked(){
    popup1->move( mapToGlobal( button1->geometry().bottomLeft() ) );
    popup1->show();
}

void Frame::button2Pressed(){
    popup2->popup(button2);
}

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

    Frame frame;
    frame.setCaption("Qt Example - Custom Popups");
    a.setMainWidget(&frame);
    frame.show();
    return a.exec();
}

See also Examples.


Starting processes with IO redirection

This example shows you how to start other processes with Qt and how IO redirection is done. The example tries to start the uic (a tool that comes with the Qt Designer) on a certain ui file and displays the output of the command.

Implementation (process.cpp):

/****************************************************************************
** $Id:  qt/process.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qobject.h>
#include <qprocess.h>
#include <qvbox.h>
#include <qtextview.h>
#include <qpushbutton.h>
#include <qapplication.h>
#include <qmessagebox.h>

#include <stdlib.h>

class UicManager : public QVBox
{
    Q_OBJECT

public:
    UicManager();
    ~UicManager() {}

public slots:
    void readFromStdout();
    void scrollToTop();

private:
    QProcess *proc;
    QTextView *output;
    QPushButton *quitButton;
};

UicManager::UicManager()
{
    // Layout
    output = new QTextView( this );
    quitButton = new QPushButton( tr("Quit"), this );
    connect( quitButton, SIGNAL(clicked()),
            qApp, SLOT(quit()) );
    resize( 500, 500 );

    // QProcess related code
    proc = new QProcess( this );

    // Set up the command and arguments.
    // On the command line you would do:
    //   uic -tr i18n "small_dialog.ui"
    proc->addArgument( "uic" );
    proc->addArgument( "-tr" );
    proc->addArgument( "i18n" );
    proc->addArgument( "small_dialog.ui" );

    connect( proc, SIGNAL(readyReadStdout()),
            this, SLOT(readFromStdout()) );
    connect( proc, SIGNAL(processExited()),
            this, SLOT(scrollToTop()) );

    if ( !proc->start() ) {
        // error handling
        QMessageBox::critical( 0,
                tr("Fatal error"),
                tr("Could not start the uic command."),
                tr("Quit") );
        exit( -1 );
    }
}

void UicManager::readFromStdout()
{
    // Read and process the data.
    // Bear in mind that the data might be output in chunks.
    output->append( proc->readStdout() );
}

void UicManager::scrollToTop()
{
    output->setContentsPos( 0, 0 );
}

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    UicManager manager;
    a.setMainWidget( &manager );
    manager.show();
    return a.exec();
}

#include "process.moc"

See also QProcess Examples.


Progress Bar and Dialog Example

This example displays either a simple (text-only) or a custom-labelled (user-supplied widget) progress dialog. It also demonstrates simple use of menus.

Implementation:

/****************************************************************************
** $Id:  qt/progress.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qprogressdialog.h>
#include <qapplication.h>
#include <qmenubar.h>
#include <qpopupmenu.h>
#include <qpainter.h>
#include <stdlib.h>

class AnimatedThingy : public QLabel {
public:
    AnimatedThingy( QWidget* parent, const QString& s ) :
        QLabel(parent),
        label(s),
        step(0)
    {
        label+="\n... and wasting CPU\nwith this animation!\n";

        for (int i=0; i<nqix; i++)
            ox[0][i] = oy[0][i] = ox[1][i] = oy[1][i] = 0;
        x0 = y0 = x1 = y1 = 0;
        dx0 = rand()%8+2;
        dy0 = rand()%8+2;
        dx1 = rand()%8+2;
        dy1 = rand()%8+2;
    }

    void show()
    {
        if (!isVisible()) startTimer(100);
        QWidget::show();
    }

    void hide()
    {
        QWidget::hide();
        killTimers();
    }

    QSize sizeHint() const
    {
        return QSize(120,100);
    }

protected:
    void timerEvent(QTimerEvent*)
    {
        QPainter p(this);
        QPen pn=p.pen();
        pn.setWidth(2);
        pn.setColor(backgroundColor());
        p.setPen(pn);

        step = (step + 1) % nqix;

        p.drawLine(ox[0][step], oy[0][step], ox[1][step], oy[1][step]);

        inc(x0, dx0, width());
        inc(y0, dy0, height());
        inc(x1, dx1, width());
        inc(y1, dy1, height());
        ox[0][step] = x0;
        oy[0][step] = y0;
        ox[1][step] = x1;
        oy[1][step] = y1;

        QColor c;
        c.setHsv( (step*255)/nqix, 255, 255 ); // rainbow effect
        pn.setColor(c);
        p.setPen(pn);
        p.drawLine(ox[0][step], oy[0][step], ox[1][step], oy[1][step]);
        p.setPen(colorGroup().text());
        p.drawText(rect(), AlignCenter, label);
    }

    void paintEvent(QPaintEvent* event)
    {
        QPainter p(this);
        QPen pn=p.pen();
        pn.setWidth(2);
        p.setPen(pn);
        p.setClipRect(event->rect());
        for (int i=0; i<nqix; i++) {
            QColor c;
            c.setHsv( (i*255)/nqix, 255, 255 ); // rainbow effect
            pn.setColor(c);
            p.setPen(pn);
            p.drawLine(ox[0][i], oy[0][i], ox[1][i], oy[1][i]);
        }
        p.setPen(colorGroup().text());
        p.drawText(rect(), AlignCenter, label);
    }

private:
    void inc(int& x, int& dx, int b)
    {
        x+=dx;
        if (x<0) { x=0; dx=rand()%8+2; }
        else if (x>=b) { x=b-1; dx=-(rand()%8+2); }
    }

    enum {nqix=10};
    int ox[2][nqix];
    int oy[2][nqix];
    int x0,y0,x1,y1;
    int dx0,dy0,dx1,dy1;
    QString label;
    int step;
};

class CPUWaster : public QWidget
{
    Q_OBJECT

    enum { first_draw_item = 1000, last_draw_item = 1006 };

    int drawItemRects(int id)
    {
        int n = id - first_draw_item;
        int r = 100;
        while (n--) r*=(n%3 ? 5 : 4);
        return r;
    }
    QString drawItemText(int id)
    {
        QString str;
        str.sprintf("%d Rectangles", drawItemRects(id));
        return str;
    }

public:
    CPUWaster() :
        pb(0)
    {
        menubar = new QMenuBar( this, "menu" );
        Q_CHECK_PTR( menubar );

        QPopupMenu* file = new QPopupMenu();
        Q_CHECK_PTR( file );
        menubar->insertItem( "&File", file );
        for (int i=first_draw_item; i<=last_draw_item; i++)
            file->insertItem( drawItemText(i), i );
        connect( menubar, SIGNAL(activated(int)), this, SLOT(doMenuItem(int)) );
        file->insertSeparator();
        file->insertItem( "Quit", qApp,  SLOT(quit()) );

        options = new QPopupMenu();
        Q_CHECK_PTR( options );
        menubar->insertItem( "&Options", options );
        td_id = options->insertItem( "Timer driven", this, SLOT(timerDriven()) );
        ld_id = options->insertItem( "Loop driven", this, SLOT(loopDriven()) );
        options->insertSeparator();
        dl_id = options->insertItem( "Default label", this, SLOT(defaultLabel()) );
        cl_id = options->insertItem( "Custom label", this, SLOT(customLabel()) );
        options->insertSeparator();
        md_id = options->insertItem( "No minimum duration", this, SLOT(toggleMinimumDuration()) );
        options->setCheckable( TRUE );
        loopDriven();
        defaultLabel();

        setFixedSize( 400, 300 );

        setBackgroundColor( black );
    }

public slots:
    void doMenuItem(int id)
    {
        if (id >= first_draw_item && id <= last_draw_item)
            draw(drawItemRects(id));
    }

    void stopDrawing() { got_stop = TRUE; }

    void timerDriven()
    {
        timer_driven = TRUE;
        options->setItemChecked( td_id, TRUE );
        options->setItemChecked( ld_id, FALSE );
    }

    void loopDriven()
    {
        timer_driven = FALSE;
        options->setItemChecked( ld_id, TRUE );
        options->setItemChecked( td_id, FALSE );
    }

    void defaultLabel()
    {
        default_label = TRUE;
        options->setItemChecked( dl_id, TRUE );
        options->setItemChecked( cl_id, FALSE );
    }

    void customLabel()
    {
        default_label = FALSE;
        options->setItemChecked( dl_id, FALSE );
        options->setItemChecked( cl_id, TRUE );
    }

    void toggleMinimumDuration()
    {
        options->setItemChecked( md_id,
           !options->isItemChecked( md_id ) );
    }

private:
    void timerEvent( QTimerEvent* )
    {
        pb->setProgress( pb->totalSteps() - rects );
        rects--;

        {
            QPainter p(this);

            int ww = width();
            int wh = height();

            if ( ww > 8 && wh > 8 ) {
                QColor c(rand()%255, rand()%255, rand()%255);
                int x = rand() % (ww-8);
                int y = rand() % (wh-8);
                int w = rand() % (ww-x);
                int h = rand() % (wh-y);
                p.fillRect( x, y, w, h, c );
            }
        }

        if (!rects || got_stop) {
            pb->setProgress( pb->totalSteps() );
            QPainter p(this);
            p.fillRect(0, 0, width(), height(), backgroundColor());
            enableDrawingItems(TRUE);
            killTimers();
            delete pb;
            pb = 0;
        }
    }

    QProgressDialog* newProgressDialog( const char* label, int steps, bool modal )
    {
        QProgressDialog *d = new QProgressDialog(label, "Cancel", steps, this,
                                                 "progress", modal);
        if ( options->isItemChecked( md_id ) )
            d->setMinimumDuration(0);
        if ( !default_label )
            d->setLabel( new AnimatedThingy(d,label) );
        return d;
    }

    void enableDrawingItems(bool yes)
    {
        for (int i=first_draw_item; i<=last_draw_item; i++) {
            menubar->setItemEnabled(i, yes);
        }
    }

    void draw(int n)
    {
        if ( timer_driven ) {
            if ( pb ) {
                qWarning("This cannot happen!");
                return;
            }
            rects = n;
            pb = newProgressDialog("Drawing rectangles.\n"
                                   "Using timer event.", n, FALSE);
            pb->setCaption("Please Wait");
            connect(pb, SIGNAL(cancelled()), this, SLOT(stopDrawing()));
            enableDrawingItems(FALSE);
            startTimer(0);
            got_stop = FALSE;
        } else {
            QProgressDialog* lpb = newProgressDialog(
                        "Drawing rectangles.\nUsing loop.", n, TRUE);
            lpb->setCaption("Please Wait");

            QPainter p(this);
            for (int i=0; i<n; i++) {
                lpb->setProgress(i);
                if ( lpb->wasCancelled() )
                    break;

                QColor c(rand()%255, rand()%255, rand()%255);
                int x = rand()%(width()-8);
                int y = rand()%(height()-8);
                int w = rand()%(width()-x);
                int h = rand()%(height()-y);
                p.fillRect(x,y,w,h,c);
            }

            p.fillRect(0, 0, width(), height(), backgroundColor());

            delete lpb;
        }
    }

    QMenuBar* menubar;
    QProgressDialog* pb;
    QPopupMenu* options;
    int td_id, ld_id;
    int dl_id, cl_id;
    int md_id;
    int rects;
    bool timer_driven;
    bool default_label;
    bool got_stop;
};

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

    int wincount = argc > 1 ? atoi(argv[1]) : 1;

    for ( int i=0; i<wincount; i++ ) {
        CPUWaster* cpuw = new CPUWaster;
        if ( i == 0 ) a.setMainWidget(cpuw);
        cpuw->show();
    }
    return a.exec();
}

#include "progress.moc"

See also Examples.


Progress Bar

This example shows how to use a progress bar.

Header file:

/****************************************************************************
** $Id:  qt/progressbar.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef PROGRESSBAR_H
#define PROGRESSBAR_H

#include <qbuttongroup.h>
#include <qtimer.h>

class QRadioButton;
class QPushButton;
class QProgressBar;

class ProgressBar : public QButtonGroup
{
    Q_OBJECT

public:
    ProgressBar( QWidget *parent = 0, const char *name = 0 );

protected:
    QRadioButton *slow, *normal, *fast;
    QPushButton *start, *pause, *reset;
    QProgressBar *progress;
    QTimer timer;

protected slots:
    void slotStart();
    void slotReset();
    void slotTimeout();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/progressbar.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "progressbar.h"

#include <qradiobutton.h>
#include <qpushbutton.h>
#include <qprogressbar.h>
#include <qlayout.h>

#include <qmotifstyle.h>

/*
 * Constructor
 *
 * Creates child widgets of the ProgressBar widget
 */

ProgressBar::ProgressBar( QWidget *parent, const char *name )
    : QButtonGroup( 0, Horizontal, "Progress Bar", parent, name ), timer()
{
    setMargin( 10 );

    QGridLayout* toplayout = new QGridLayout( layout(), 2, 2, 5);

    setRadioButtonExclusive( TRUE );

    // insert three radiobuttons which the user can use
    // to set the speed of the progress and two pushbuttons
    // to start/pause/continue and reset the progress
    slow = new QRadioButton( "&Slow", this );
    normal = new QRadioButton( "&Normal", this );
    fast = new QRadioButton( "&Fast", this );
    QVBoxLayout* vb1 = new QVBoxLayout;
    toplayout->addLayout( vb1, 0, 0 );
    vb1->addWidget( slow );
    vb1->addWidget( normal );
    vb1->addWidget( fast );

    // two push buttons, one for start, for for reset.
    start = new QPushButton( "&Start", this );
    reset = new QPushButton( "&Reset", this );
    QVBoxLayout* vb2 = new QVBoxLayout;
    toplayout->addLayout( vb2, 0, 1 );
    vb2->addWidget( start );
    vb2->addWidget( reset );

    // Create the progressbar
    progress = new QProgressBar( 100, this );
    //    progress->setStyle( new QMotifStyle() );
    toplayout->addMultiCellWidget( progress, 1, 1, 0, 1 );

    // connect the clicked() SIGNALs of the pushbuttons to SLOTs
    connect( start, SIGNAL( clicked() ), this, SLOT( slotStart() ) );
    connect( reset, SIGNAL( clicked() ), this, SLOT( slotReset() ) );

    // connect the timeout() SIGNAL of the progress-timer to a SLOT
    connect( &timer, SIGNAL( timeout() ), this, SLOT( slotTimeout() ) );

    // Let's start with normal speed...
    normal->setChecked( TRUE );

    // some contraints
    start->setFixedWidth( 80 );
    setMinimumWidth( 300 );
}

/*
 * SLOT slotStart
 *
 * This SLOT is called if the user clicks start/pause/continue
 * button
 */

void ProgressBar::slotStart()
{
    // If the progress bar is at the beginning...
    if ( progress->progress() == -1 ) {
        // ...set according to the checked speed-radiobutton
        // the number of steps which are needed to complete the process
        if ( slow->isChecked() )
            progress->setTotalSteps( 10000 );
        else if ( normal->isChecked() )
            progress->setTotalSteps( 1000 );
        else
            progress->setTotalSteps( 50 );

        // disable the speed-radiobuttons
        slow->setEnabled( FALSE );
        normal->setEnabled( FALSE );
        fast->setEnabled( FALSE );
    }

    // If the progress is not running...
    if ( !timer.isActive() ) {
        // ...start the timer (and so the progress) with a interval of 1 ms...
        timer.start( 1 );
        // ...and rename the start/pause/continue button to Pause
        start->setText( "&Pause" );
    } else { // if the prgress is running...
        // ...stop the timer (and so the prgress)...
        timer.stop();
        // ...and rename the start/pause/continue button to Continue
        start->setText( "&Continue" );
    }
}

/*
 * SLOT slotReset
 *
 * This SLOT is called when the user clicks the reset button
 */

void ProgressBar::slotReset()
{
    // stop the timer and progress
    timer.stop();

    // rename the start/pause/continue button to Start...
    start->setText( "&Start" );
    // ...and enable this button
    start->setEnabled( TRUE );

    // enable the speed-radiobuttons
    slow->setEnabled( TRUE );
    normal->setEnabled( TRUE );
    fast->setEnabled( TRUE );

    // reset the progressbar
    progress->reset();
}

/*
 * SLOT slotTimeout
 *
 * This SLOT is called each ms when the timer is
 * active (== progress is running)
 */

void ProgressBar::slotTimeout()
{
    int p = progress->progress();

#if 1
    // If the progress is complete...
    if ( p == progress->totalSteps() )  {
        // ...rename the start/pause/continue button to Start...
        start->setText( "&Start" );
        // ...and disable it...
        start->setEnabled( FALSE );
        // ...and return
        return;
    }
#endif

    // If the process is not complete increase it
    progress->setProgress( ++p );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "progressbar.h"
#include <qapplication.h>

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

    ProgressBar progressbar;
    progressbar.setCaption("Qt Example - ProgressBar");
    a.setMainWidget(&progressbar);
    progressbar.show();

    return a.exec();
}

See also Examples.


属性

Qt提供了一套和一些编译器提供商也提供的属性系统类似的完善的属性系统。然而，作为一个不依赖编译器和平台的库，Qt不能依赖像__property或者[property]那样的非标准编译器特征。我们的解决方案可以在我们支持的每一个平台上和任何标准的C++编译器一起工作。它基于元对象系统，元对象系统也通过信号和槽提供对象通讯。

在类声明中的Q_PROPERTY宏声明了一个属性。属性只能在继承于QObject的子类中声明。第二个宏，Q_OVERRIDE，可以用来覆盖一些子类中由继承得到的属性。

对于外面的世界，属性看起来和一个数据成员非常类似。然而，属性和普通的数据成员还是有一下一些不同点：

  • 一个读函数。这是一直存在的。

  • 一个写函数。这个是可选的：像QWidget::isDesktop()这样的只读的属性就没有写函数。

  • “存储”特征需要说明持续性。绝大多数属性是被存储的，但是有一小部分的虚拟属性却不用。举个例子，QWidget::minimumWidth()是不用存储的，因为它只是QWidget::minimumSize()的一种查看，没有自己的数据。

  • 一个复位函数用来把属性设置回它根据上下文的特定缺省值。这个用法还是比较罕见的，但是举个例子，QWidget::font()需要这个函数，因为没有调用QWidget::setFont()意味着“复位到根据上下文特定的字体”。

  • “可设计”特征说明它是否可以被一个图形用户界面生成器（例如Qt设计器）设置属性。对于大多数属性都有这个特征，但不是所有，例如QButton::isDown()。用户可以按按钮，并且应用程序设计人员可以让程序来按它自己的按钮，但是一个图形用户界面设计工具不能按按钮。

读、写和复位函数就像任何成员函数一样，继承或不继承，虚或不虚。只有一个例外就是，在多重继承的情况下，成员函数必须从第一个被继承类继承。

属性可以在不知道被使用的类的任何情况的时候通过QObject中的一般函数进行读写。下面两个函数调用是等效的：

    // QButton *b和QObject *o指向同一个按钮
    b->setDown( TRUE );
    o->setProperty( "down", TRUE );

等效的是指，除了第一个函数要快一些，在编译的时候提供了更好的诊断信息。在实际应用中，第一个函数更好些。然而，因为我们可以通过QMetaObject获得任何一个QObject的所有有用属性的一个列表，QObject::setProperty()可以让你控制类中那些在编译时不可用的属性。

像QObject::setProperty()一样，还有一个相应的QObject::property()函数。QMetaObject::propertyNames()返回所有可用属性的名称。QMetaObject::property()返回一个指定属性的属性数据：一个QMetaProperty对象。

这里有一个简单的例子说明了可以应用的绝大多数重要属性函数：

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        MyClass( QObject * parent=0, const char * name=0 );
        ~MyClass();

        enum Priority { High, Low, VeryHigh, VeryLow };
        void setPriority( Priority );
        Priority priority() const;
    };

这个类有一个名为“priority”的还不被元对象系统所知的属性。为了让这个属性被元对象系统知道，你必须用Q_PROPERTY宏来声明它。声明语法如下：

Q_PROPERTY( type name READ getFunction [WRITE setFunction]
            [RESET resetFunction] [DESIGNABLE bool]
            [SCRIPTABLE bool] [STORED bool] )

为了声明是有效的，读函数必须是常量函数并且返回值的类型是它本身或者是指向它的指针，或者是它的一个引用。可选的写函数必须返回void并且必须带有一个正确的参数，类型必须是它本身或者是指向它的指针，或者是它的一个常量引用。元对象编译器强迫这样的。

属性的类型可以是任何一个QVariant支持的类型或者是一个自己在类中已经定义的枚举类型。因为MyClass中的属性使用了枚举类型Priority，这个类型必须也向属性系统注册。这样的话，像如下方式通过名称来设置值是可行的：

    obj->setProperty( "priority", "VeryHigh" );

枚举类型必须使用Q_ENUMS宏来进行注册。这里是一个包含属性相关声明的最终的类声明：

    class MyClass : public QObject
    {
        Q_OBJECT
        Q_PROPERTY( Priority priority READ priority WRITE setPriority )
        Q_ENUMS( Priority )
    public:
        MyClass( QObject * parent=0, const char * name=0 );
        ~MyClass();

        enum Priority { High, Low, VeryHigh, VeryLow };
        void setPriority( Priority );
        Priority priority() const;
    };

另外一个类似的宏是Q_SETS。像Q_ENUMS一样，它注册了一个枚举类型，但是它额外的加了一个“set”的标记，也就是说，这个枚举数据可以被一起读或写。一个输入输出类也许有枚举数据“读”和“写”和接收“读|写”：这时最好用Q_SETS来声明一个枚举类型，而不是Q_ENUMS。

Q_PROPERTY段剩余的关键字是RESET、DESIGNABLE、SCRIPTABLE和STORED。

RESET指定一个函数可以设置属性到缺省状态（这个缺省状态可能和初始状态不同）。这个函数必须返回void并且不带有参数。

DESIGNABLE声明这个属性是否适合被一个图形用户界名设计工具修改。缺省的TRUE是说这个属性可写，否则就是FALSE说明不能。你可以定义一个布尔成员函数来替代TRUE或FALSE。

SCRIPTABLE声明这个属性是否适合被一个脚本引擎访问。缺省是TRUE，可以。你可以定义一个布尔成员函数来替代TRUE或FALSE。

STORED声明这个属性的值是否必须作为一个存储的对象状态而被记得。STORED只对可写的属性有意义。缺省是TRUE。技术上多余的属性（比如，如果QRect的geometry已经是一个属性了的QPoint的pos）定义为FALSE。

连接到属性系统是一个附加宏，“Q_CLASSINFO”，它可以用来把名称/值这样一套的属性添加到一个类的元对象中，例如：

    Q_CLASSINFO( "Version", "3.0.0" )

和其它元数据一样，类信息在运行时是可以通过元对象访问的，具体请看QMetaObject::classInfo()。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QAccel类

QAccel类参考

QAccel类用来处理键盘的加速键和快捷键。 详情请见……

#include <qaccel.h>

继承了QObject。

所有成员函数的列表。

公有成员

  • QAccel ( QWidget * parent, const char * name = 0 )
  • QAccel ( QWidget * watch, QObject * parent, const char * name = 0 )
  • ~QAccel ()
  • bool isEnabled () const
  • void setEnabled ( bool enable )
  • uint count () const
  • int insertItem ( const QKeySequence & key, int id = -1 )
  • void removeItem ( int id )
  • void clear ()
  • QKeySequence key ( int id )
  • int findKey ( const QKeySequence & key ) const
  • bool isItemEnabled ( int id ) const
  • void setItemEnabled ( int id, bool enable )
  • bool connectItem ( int id, const QObject * receiver, const char * member )
  • bool disconnectItem ( int id, const QObject * receiver, const char * member )
  • void repairEventFilter ()
  • void setWhatsThis ( int id, const QString & text )
  • QString whatsThis ( int id ) const

信号

  • void activated ( int id )

静态公有成员

  • QKeySequence shortcutKey ( const QString & str )
  • QString keyToString ( QKeySequence k ) (obsolete)
  • QKeySequence stringToKey ( const QString & s ) (obsolete)

保护成员

  • virtual bool eventFilter ( QObject * o, QEvent * e )

详细描

QAccel类用来处理键盘的加速键和快捷键。

键盘加速键是在某个组合键按下的时候出发一个动作，加速键可以处理窗口部件和它子部件里所有的键盘动作所以它不会被键盘焦点所影响。

在大多数情况下，你不需要直接使用这个类。使用QAction类建立的具有加速键的动作可以同时在菜单和工具栏里使用。如果你的兴趣只是在菜单里使用QMenuData::insertItem()或者QMenuData::setAccel()建立只作用在菜单里的加速键。那么许多窗口部件可以自动的生成加速键，比如QButton、QGroupBox、QLabel（使用QLabel::setBuddy()）、QMenuBar和QTabBar。实例：

        QPushButton p( "&Exit", parent ); // 自动使用快捷键ALT+Key_E
        QPopupMenu *fileMenu = new fileMenu( parent );
        fileMenu->insertItem( "Undo", parent, SLOT(undo()), CTRL+Key_Z );

QAccel包括一个加速键的列表，这个列表里的项目可以使用insertItem()、removeItem()、clear()、key()和findKey()。

每一个加速键项目是由一个标示符和 QKeySequence组成。一个单独的键组是由一个键盘码组合上改变符形成的(SHIFT，CTRL，ALT 或者 UNICODE_ACCEL)。例如，CTRL + Key_p可以作为文本打印的快捷键。这个键的键盘码在qnamespace.h里列出。还有，使用UNICODE_ACCEL可以使字符以统一码（unicode）的形式表现出来。例如 UNICODE_ACCEL + 'A' 所给出的加速键和Key_A是一样的。

当一个加速键被按下的时候，信号 activated()会伴随着这个加速键项目的标示被发出。加速键项目也可以单独的被连接，所以两个不同的键可以在两个不同的槽里被激活(参考 connectItem() 和 disconnectItem())。

使用 setEnabled() 可以允许或禁止所有的的加速键的项目，setItemEnabled() 则可以允许或禁止单独的项目。只有QAccel和这个项目本身被允许的时候，这个项目才可以被激活。

当用户在What's This模式的情况下按下加速键的时候，函数 setWhatsThis() 会提供一个帮助文本。

QAccel对象把键事件发送给包含有parent的 QWidget::topLevelWidget() ，并由此发给这个窗口里的所有子部件。当parent被删除的时候，所有的加速键也同时被删除，然后销毁所有的相关的键事件。

实例：

        QAccel *a = new QAccel( myWindow );        // 在myWindow里建立加速键
        a->connectItem( a->insertItem(Key_P+CTRL), // 添加Ctrl+P加速键
                        myWindow,                  // 连接到myWindow的
                        SLOT(printDoc()) );        // printDoc()槽

也可以参考QKeyEvent、QWidget::keyPressEvent()、QMenuData::setAccel()、QButton::accel、QLabel::setBuddy()、QKeySequence、GUI Design Handbook: Keyboard Shortcuts和杂项类。

成员函数文档

QAccel::QAccel ( QWidget * parent, const char * name = 0 )

通过name和parent构造QAccel的对象。加速键是在parent上操作的。

QAccel::QAccel ( QWidget * watch, QObject * parent, const char * name = 0 )

构造QAccel对象，这个对象是通过调用name构造的，作用在watch上，是parent的子。

对于一般的程序，这个构造函数是不需要的。

QAccel::~QAccel ()

析构加速键对象并释放所有分配的资源。

void QAccel::activated ( int id ) [信号]

当加速键被按下的时候这个信号产生。id 是个数字，用来表明某个特定的加速键项目。

void QAccel::clear ()

清空所有的加速键项目。

bool QAccel::connectItem ( int id, const QObject * receiver, const char * member )

把加速键项目的id连接到receiver的member槽里。

        a->connectItem( 201, mainView, SLOT(quit()) );

当然，你也可以发送一个信号作为 member。

也可以参考disconnectItem()。

例子: t14/gamebrd.cpp。

uint QAccel::count () const

返回在这个加速键对象里所有加速键项目的数目。

bool QAccel::disconnectItem ( int id, const QObject * receiver, const char * member )

通过调用member把使用id标示的加速键项目从receiver里断开。

参考 connectItem()。

bool QAccel::eventFilter ( QObject * o, QEvent * e ) [虚拟 保护]

处理用于顶级部件的加速键事件。e 是产生在对象 o 上的事件。

由 QObject 继承并执行。

int QAccel::findKey ( const QKeySequence & key ) const

返回由键码 key制定的加速键项目的标示，-1表明这个项目没有被找到。

int QAccel::insertItem ( const QKeySequence & key, int id = -1 )

插入加速键项目并返回这个项目的标示符。

key 是键码和混合了SHIFT，CTRL 和 ALT的选项。id 是加速键项目标示符。

如果 id 是负的，那么这个项目就被会被分配一个唯一的小于-1的负标示符。

        QAccel *a = new QAccel( myWindow )；        // 在myWindow里建立accels
        a->insertItem( CTRL + Key_p, 200 )；        // Ctrl+p, 打印文本
        a->insertItem( ALT + Key_X, 201 )；         // Alt+X, 退出
        a->insertItem( UNICODE_ACCEL + 'q', 202 )； // 统一码 'q', 退出
        a->insertItem( Key_D )；                    // 得到小于－1的唯一负标示符
        a->insertItem( CTRL + SHIFT + Key_p )；     // 得到小于－1的唯一负标示符

例子： t14/gamebrd.cpp。

bool QAccel::isEnabled () const

如果加速键被允许激活，返回TRUE，否则FALSE。

参考 setEnabled() 和 isItemEnabled()。

bool QAccel::isItemEnabled ( int id ) const

如果以id表明的这个加速键项目是被允许激活的，返回TRUE，如果是被禁止的或没有找到这个项目，返回FALSE。

参考 setItemEnabled() 和 isEnabled()。

QKeySequence QAccel::key ( int id )

返回以标示符id指明的加速键项目的键组，如果这个标示符没有被找到，返回无效的键组(0)。

QString QAccel::keyToString ( QKeySequence k ) [静态]

这个函数已经不再使用了。 它存在的目的是使以前的源代码还可以工作。我们强烈建议，在新的代码里不要使用它。

建立一个针对于键 k 的加速键字符串。比如，CTRL+Key_O就给出"Ctrl+O"。"Ctrl"等等这一些的字符串（使用 QObject::tr()) 在"QAccel"上下文里被翻译。

这个函数是多余的。把QKeySequence k 进行类型转换成 QString 也可以达到同样的效果。

void QAccel::removeItem ( int id )

去除标示符 id 所标示的加速键项目。

void QAccel::repairEventFilter ()

确信加速键获得正确的事件过滤器。这个函数是自动被调用的，你不应该在应用程序里调用它。

void QAccel::setEnabled ( bool enable )

如果 enable 是TRUE，就把加速键设为允许被激活，如果 enable 是FALSE就禁止它。

单独的键可以通过使用 setItemEnabled() 设置允许或禁止被激活。如果要操作某个键，那么这个键必须在被允许的QAccel里并切实是被允许激活的。

参考 isEnabled() 和 setItemEnabled()。

void QAccel::setItemEnabled ( int id, bool enable )

如果 enable 是TRUE，允许标示符 id 所标示的加速键项目可以被激活。

如果 enable 是FALSE，就禁止这个 id 标示的项目。

如果要操作某项目，那么这个项目必须是被允许的并且存在于一个被运行的QAccel里。

参考 isItemEnabled() 和 isEnabled()。

void QAccel::setWhatsThis ( int id, const QString & text )

为 id 标示的加速键项目设定What's This帮助文本，这个文本设定给 text 。

当应用程序处于What's This模式并在用户按下加速键的时候，这个文本显示。

如果要在菜单里设置What's This帮助（不管有没有加速键），使用QMenuData::setWhatsThis().

参考 whatsThis()，QWhatsThis::inWhatsThisMode()，QMenuData::setWhatsThis() 和 QAction::whatsThis。

QKeySequence QAccel::shortcutKey ( const QString & str ) [静态]

返回 str 里的快捷键组，如果 str 没有快捷键组，返回无效的键组(0)。

比如，shortcutKey("E&xit") 返回ALT+Key_X, shortcutKey("&Quit") 返回 ALT+Key_Q 和 shortcutKey("Quit") 返回 0。(在没有继承Qt名字空间类的代码里，你必须像这样写Qt::ALT+Qt::Key_Q.)

我们用英语提供了一个通用加速键列表。在发布这个列表的时候，Microsofu和Open Group并没有表示要推出针对于其他语言的版本

QKeySequence QAccel::stringToKey ( const QString & s ) [静态]

这个函数已不再使用了。 它存在的目的是使以前的源代码还可以工作。我们强烈建议，在新的代码里不要使用它。

返回字符串 s 里里加速键码。例如"Ctrl+O" 给出CTRL+UNICODE_ACCEL+'O'。这些字符串"Ctrl"，"Shift"，"Alt"都是被识别的，如同它们在"QAccel"上下文里（使用( QObject::tr())）被翻译过来的意思一样。如果 s 不是被识别的，返回0。

这个函数的典型是使用方法是伴随着 tr()的使用，这样，加速键就可以直接通过翻译被取代。

          QpopupMenu *file = new QpopupMenu( this )；
        file->insertItem( p1, tr("&Open..."), this, SLOT(open())，
        QAccel::stringToKey(tr("Ctrl+O", "File|Open")) )；

注意"File|Open"的翻译注释，它实际上没有任何的意思，它只是为人工的翻译提供了一个上下文的帮助。

这个函数是多余的，从字符串 s 里构造一个QKeySequence可以达到同样的效果。

参考QObject::tr() 和 Internationalization with Qt。

例子：i18n/mywidget.cpp。

QString QAccel::whatsThis ( int id ) const

返回某个特定项目 id 的What's This 帮助文本或者如果没有文本被提供的时候，返回 QString::null

参考setWhatsThis()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:allexit
Qt 3.0.5版


qaccel.h包含文件

qaccel.h

这里是qaccel.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qaccel.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QAccel class
**
** Created : 950419
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QACCEL_H
#define QACCEL_H

#ifndef QT_H
#include "qobject.h"
#include "qkeysequence.h"
#endif // QT_H

#ifndef QT_NO_ACCEL

class QAccelPrivate;

class Q_EXPORT QAccel : public QObject			// accelerator class
{
    Q_OBJECT
public:
    QAccel( QWidget *parent, const char *name=0 );
    QAccel( QWidget* watch, QObject *parent, const char *name=0 );
    ~QAccel();

    bool isEnabled() const;
    void setEnabled( bool );

    uint count() const;

    int insertItem( const QKeySequence& key, int id=-1);
    void removeItem( int id );
    void clear();

    QKeySequence key( int id );
    int findKey( const QKeySequence& key ) const;

    bool isItemEnabled( int id ) const;
    void setItemEnabled( int id, bool enable );

    bool connectItem( int id,  const QObject *receiver, const char* member );
    bool disconnectItem( int id,  const QObject *receiver, const char* member );

    void repairEventFilter();

    void setWhatsThis( int id, const QString& );
    QString whatsThis( int id ) const;
    void setIgnoreWhatsThis( bool );
    bool ignoreWhatsThis() const;

    static QKeySequence shortcutKey( const QString & );
    static QString keyToString(QKeySequence k );
    static QKeySequence stringToKey( const QString & );

signals:
    void activated( int id );

protected:
    bool eventFilter( QObject *, QEvent * );

private:
    QAccelPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QAccel( const QAccel & );
    QAccel &operator=( const QAccel & );
#endif
};

#endif // QT_NO_ACCEL
#endif // QACCEL_H

Copyright © 2002 Trolltech Trademarks 译者:allexit
Qt 3.0.5版


QAccel成员列表

完整的QAccel成员列表

这里是QAccel成员函数的完整列表，包括继承的成员。

  • QAccel()
  • ~QAccel()
  • activated()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clear()
  • connect()
  • connectItem()
  • connectNotify()
  • count()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectItem()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • findKey()
  • highPriority()
  • inherits()
  • insertChild()
  • insertItem()
  • installEventFilter()
  • isA()
  • isEnabled()
  • isItemEnabled()
  • isWidgetType()
  • key()
  • keyToString()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • removeItem()
  • repairEventFilter()
  • sender()
  • setEnabled()
  • setItemEnabled()
  • setName()
  • setProperty()
  • setWhatsThis()
  • shortcutKey()
  • signalsBlocked()
  • startTimer()
  • stringToKey()
  • timerEvent()
  • tr()
  • trUtf8()
  • whatsThis()

Copyright © 2002 Trolltech Trademarks 译者:allexit
Qt 3.0.5版


QAccessible Class

QAccessible Class Reference

The QAccessible class provides enums and static functions relating to accessibility. More...

#include <qaccessible.h>

Inherited by QAccessibleInterface.

List of all member functions.

Public Members

  • enum Event { SoundPlayed = 0x0001, Alert = 0x0002, ForegroundChanged = 0x0003, MenuStart = 0x0004, MenuEnd = 0x0005, PopupMenuStart = 0x0006, PopupMenuEnd = 0x0007, ContextHelpStart = 0x000C, ContextHelpEnd = 0x000D, DragDropStart = 0x000E, DragDropEnd = 0x000F, DialogStart = 0x0010, DialogEnd = 0x0011, ScrollingStart = 0x0012, ScrollingEnd = 0x0013, MenuCommand = 0x0018, ObjectCreated = 0x8000, ObjectDestroyed = 0x8001, ObjectShow = 0x8002, ObjectHide = 0x8003, ObjectReorder = 0x8004, Focus = 0x8005, Selection = 0x8006, SelectionAdd = 0x8007, SelectionRemove = 0x8008, SelectionWithin = 0x8009, StateChanged = 0x800A, LocationChanged = 0x800B, NameChanged = 0x800C, DescriptionChanged = 0x800D, ValueChanged = 0x800E, ParentChanged = 0x800F, HelpChanged = 0x80A0, DefaultActionChanged = 0x80B0, AcceleratorChanged = 0x80C0 }
  • enum State { Normal = 0x00000000, Unavailable = 0x00000001, Selected = 0x00000002, Focused = 0x00000004, Pressed = 0x00000008, Checked = 0x00000010, Mixed = 0x00000020, ReadOnly = 0x00000040, HotTracked = 0x00000080, Default = 0x00000100, Expanded = 0x00000200, Collapsed = 0x00000400, Busy = 0x00000800, Floating = 0x00001000, Marqueed = 0x00002000, Animated = 0x00004000, Invisible = 0x00008000, Offscreen = 0x00010000, Sizeable = 0x00020000, Moveable = 0x00040000, SelfVoicing = 0x00080000, Focusable = 0x00100000, Selectable = 0x00200000, Linked = 0x00400000, Traversed = 0x00800000, MultiSelectable = 0x01000000, ExtSelectable = 0x02000000, AlertLow = 0x04000000, AlertMedium = 0x08000000, AlertHigh = 0x10000000, Protected = 0x20000000, Valid = 0x3fffffff }
  • enum Role { NoRole = 0x00000000, TitleBar = 0x00000001, MenuBar = 0x00000002, ScrollBar = 0x00000003, Grip = 0x00000004, Sound = 0x00000005, Cursor = 0x00000006, Caret = 0x00000007, AlertMessage = 0x00000008, Window = 0x00000009, Client = 0x0000000A, PopupMenu = 0x0000000B, MenuItem = 0x0000000C, ToolTip = 0x0000000D, Application = 0x0000000E, Document = 0x0000000F, Pane = 0x00000010, Chart = 0x00000011, Dialog = 0x00000012, Border = 0x00000013, Grouping = 0x00000014, Separator = 0x00000015, ToolBar = 0x00000016, StatusBar = 0x00000017, Table = 0x00000018, ColumnHeader = 0x00000019, RowHeader = 0x0000001A, Column = 0x0000001B, Row = 0x0000001C, Cell = 0x0000001D, Link = 0x0000001E, HelpBalloon = 0x0000001F, Character = 0x00000020, List = 0x00000021, ListItem = 0x00000022, Outline = 0x00000023, OutlineItem = 0x00000024, PageTab = 0x00000025, PropertyPage = 0x00000026, Indicator = 0x00000027, Graphic = 0x00000028, StaticText = 0x00000029, EditableText = 0x0000002A, PushButton = 0x0000002B, CheckBox = 0x0000002C, RadioButton = 0x0000002D, ComboBox = 0x0000002E, DropLest = 0x0000002F, ProgressBar = 0x00000030, Dial = 0x00000031, HotkeyField = 0x00000032, Slider = 0x00000033, SpinBox = 0x00000034, Diagram = 0x00000035, Animation = 0x00000036, Equation = 0x00000037, ButtonDropDown = 0x00000038, ButtonMenu = 0x00000039, ButtonDropGrid = 0x0000003A, Whitespace = 0x0000003B, PageTabList = 0x0000003C, Clock = 0x0000003D }
  • enum NavDirection { NavUp = 0x00000001, NavDown = 0x00000002, NavLeft = 0x00000003, NavRight = 0x00000004, NavNext = 0x00000005, NavPrevious = 0x00000006, NavFirstChild = 0x00000007, NavLastChild = 0x00000008, NavFocusChild = 0x00000009 }
  • enum Text { Name = 0, Description, Value, Help, Accelerator, DefaultAction }

Static Public Members

  • QRESULT queryAccessibleInterface ( QObject * object, QAccessibleInterface ** iface )
  • void updateAccessibility ( QObject * object, int control, Event reason )

Detailed Description

The QAccessible class provides enums and static functions relating to accessibility.

Accessibility clients use implementations of the QAccessibleInterface to read the information an accessible object exposes, or to call functions to manipulate the accessible object.

See the plugin documentation for more details about how to redistribute Qt plugins.

See also Miscellaneous Classes.

Member Type Documentation

QAccessible::Event

This enum type defines event types when the state of the accessible object has changed. The event types are:

  • QAccessible::SoundPlayed
  • QAccessible::Alert
  • QAccessible::ForegroundChanged
  • QAccessible::MenuStart
  • QAccessible::MenuEnd
  • QAccessible::PopupMenuStart
  • QAccessible::PopupMenuEnd
  • QAccessible::ContextHelpStart
  • QAccessible::ContextHelpEnd
  • QAccessible::DragDropStart
  • QAccessible::DragDropEnd
  • QAccessible::DialogStart
  • QAccessible::DialogEnd
  • QAccessible::ScrollingStart
  • QAccessible::ScrollingEnd
  • QAccessible::ObjectCreated
  • QAccessible::ObjectDestroyed
  • QAccessible::ObjectShow
  • QAccessible::ObjectHide
  • QAccessible::ObjectReorder
  • QAccessible::Focus
  • QAccessible::Selection
  • QAccessible::SelectionAdd
  • QAccessible::SelectionRemove
  • QAccessible::SelectionWithin
  • QAccessible::StateChanged
  • QAccessible::LocationChanged
  • QAccessible::NameChanged
  • QAccessible::DescriptionChanged
  • QAccessible::ValueChanged
  • QAccessible::ParentChanged
  • QAccessible::HelpChanged
  • QAccessible::DefaultActionChanged
  • QAccessible::AcceleratorChanged
  • QAccessible::MenuCommand

QAccessible::NavDirection

This enum specifies which item to move to when navigating.

  • QAccessible::NavUp - sibling above
  • QAccessible::NavDown - sibling below
  • QAccessible::NavLeft - left sibling
  • QAccessible::NavRight - right sibling
  • QAccessible::NavNext - next sibling
  • QAccessible::NavPrevious - previous sibling
  • QAccessible::NavFirstChild - first child
  • QAccessible::NavLastChild - last child
  • QAccessible::NavFocusChild - child with focus

QAccessible::Role

This enum defines a number of roles an accessible object can have. The roles are:

  • QAccessible::NoRole
  • QAccessible::TitleBar
  • QAccessible::MenuBar
  • QAccessible::ScrollBar
  • QAccessible::Grip
  • QAccessible::Sound
  • QAccessible::Cursor
  • QAccessible::Caret
  • QAccessible::AlertMessage
  • QAccessible::Window
  • QAccessible::Client
  • QAccessible::PopupMenu
  • QAccessible::MenuItem
  • QAccessible::ToolTip
  • QAccessible::Application
  • QAccessible::Document
  • QAccessible::Pane
  • QAccessible::Chart
  • QAccessible::Dialog
  • QAccessible::Border
  • QAccessible::Grouping
  • QAccessible::Separator
  • QAccessible::ToolBar
  • QAccessible::StatusBar
  • QAccessible::Table
  • QAccessible::ColumnHeader
  • QAccessible::RowHeader
  • QAccessible::Column
  • QAccessible::Row
  • QAccessible::Cell
  • QAccessible::Link
  • QAccessible::HelpBalloon
  • QAccessible::Character
  • QAccessible::List
  • QAccessible::ListItem
  • QAccessible::Outline
  • QAccessible::OutlineItem
  • QAccessible::PageTab
  • QAccessible::PropertyPage
  • QAccessible::Indicator
  • QAccessible::Graphic
  • QAccessible::StaticText
  • QAccessible::EditableText
  • QAccessible::PushButton
  • QAccessible::CheckBox
  • QAccessible::RadioButton
  • QAccessible::ComboBox
  • QAccessible::DropLest
  • QAccessible::ProgressBar
  • QAccessible::Dial
  • QAccessible::HotkeyField
  • QAccessible::Slider
  • QAccessible::SpinBox
  • QAccessible::Diagram
  • QAccessible::Animation
  • QAccessible::Equation
  • QAccessible::ButtonDropDown
  • QAccessible::ButtonMenu
  • QAccessible::ButtonDropGrid
  • QAccessible::Whitespace
  • QAccessible::PageTabList
  • QAccessible::Clock

QAccessible::State

This enum type defines bitflags that can be combined to indicate the state of the accessible object. The values are:

  • QAccessible::Normal
  • QAccessible::Unavailable
  • QAccessible::Selected
  • QAccessible::Focused
  • QAccessible::Pressed
  • QAccessible::Checked
  • QAccessible::Mixed
  • QAccessible::ReadOnly
  • QAccessible::HotTracked
  • QAccessible::Default
  • QAccessible::Expanded
  • QAccessible::Collapsed
  • QAccessible::Busy
  • QAccessible::Floating
  • QAccessible::Marqueed
  • QAccessible::Animated
  • QAccessible::Invisible
  • QAccessible::Offscreen
  • QAccessible::Sizeable
  • QAccessible::Moveable
  • QAccessible::SelfVoicing
  • QAccessible::Focusable
  • QAccessible::Selectable
  • QAccessible::Linked
  • QAccessible::Traversed
  • QAccessible::MultiSelectable
  • QAccessible::ExtSelectable
  • QAccessible::AlertLow
  • QAccessible::AlertMedium
  • QAccessible::AlertHigh
  • QAccessible::Protected
  • QAccessible::Valid

QAccessible::Text

This enum specifies string information that an accessible object returns.

  • QAccessible::Name - The name of the object
  • QAccessible::Description - A short text describing the object
  • QAccessible::Value - The value of the object
  • QAccessible::Help - A longer text giving information about how to use the object
  • QAccessible::DefaultAction - The default method to interact with the object
  • QAccessible::Accelerator - The keyboard shortcut that executes the default action

Member Function Documentation

QRESULT QAccessible::queryAccessibleInterface ( QObject * object, QAccessibleInterface ** iface ) [static]

Sets iface to point to the implementation of the QAccessibleInterface for object, and returns QS_OK if successfull, or sets iface to 0 and returns QE_NOCOMPONENT if no accessibility implementation for object exists.

The function uses the classname of object to find a suitable implementation. If no implementation for the object's class is available the function tries to find an implementation for the object's parent class.

This function is called to answer an accessibility client's request for object information. You should never need to call this function yourself.

void QAccessible::updateAccessibility ( QObject * object, int control, Event reason ) [static]

Notifies accessibility clients about a change in object's accessibility information.

reason specifies the cause of the change, for example, ValueChange when the position of a slider has been changed. control is the ID of the child element that has changed. When control is 0, the object itself has changed.

Call this function whenever the state of your accessible object or one of it's sub-elements has been changed either programmatically (e.g. by calling QLabel::setText()) or by user interaction.

If there are no accessibility tools listening to this event, the performance penalty for calling this function is minor.

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


qaccessible.h Include File

qaccessible.h

This is the verbatim text of the qaccessible.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QAccessible and QAccessibleObject classes
**
** Copyright (C) 2000-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QACCESSIBLE_H
#define QACCESSIBLE_H

#ifndef QT_H
#include "qobject.h"
#include <private/qcom_p.h>
#include "qrect.h"
#include "qguardedptr.h"
#include "qmemarray.h"
#endif // QT_H

#if defined(QT_ACCESSIBILITY_SUPPORT)

struct QAccessibleInterface;

class Q_EXPORT QAccessible
{
public:
    enum Event {
    SoundPlayed	    = 0x0001,
    Alert		    = 0x0002,
    ForegroundChanged   = 0x0003,
    MenuStart	    = 0x0004,
    MenuEnd		    = 0x0005,
    PopupMenuStart	    = 0x0006,
    PopupMenuEnd	    = 0x0007,
    ContextHelpStart    = 0x000C,
    ContextHelpEnd	    = 0x000D,
    DragDropStart	    = 0x000E,
    DragDropEnd	    = 0x000F,
    DialogStart	    = 0x0010,
    DialogEnd	    = 0x0011,
    ScrollingStart	    = 0x0012,
    ScrollingEnd	    = 0x0013,

    MenuCommand	    = 0x0018,

    ObjectCreated	    = 0x8000,
    ObjectDestroyed	    = 0x8001,
    ObjectShow	    = 0x8002,
    ObjectHide	    = 0x8003,
    ObjectReorder	    = 0x8004,
    Focus		    = 0x8005,
    Selection	    = 0x8006,
    SelectionAdd	    = 0x8007,
    SelectionRemove	    = 0x8008,
    SelectionWithin	    = 0x8009,
    StateChanged	    = 0x800A,
    LocationChanged	    = 0x800B,
    NameChanged	    = 0x800C,
    DescriptionChanged  = 0x800D,
    ValueChanged	    = 0x800E,
    ParentChanged	    = 0x800F,
    HelpChanged	    = 0x80A0,
    DefaultActionChanged= 0x80B0,
    AcceleratorChanged  = 0x80C0
    };

    enum State {
    Normal		= 0x00000000,
    Unavailable	= 0x00000001,
    Selected	= 0x00000002,
    Focused		= 0x00000004,
    Pressed		= 0x00000008,
    Checked		= 0x00000010,
    Mixed		= 0x00000020,
    ReadOnly	= 0x00000040,
    HotTracked	= 0x00000080,
    Default		= 0x00000100,
    Expanded	= 0x00000200,
    Collapsed	= 0x00000400,
    Busy		= 0x00000800,
    Floating	= 0x00001000,
    Marqueed	= 0x00002000,
    Animated	= 0x00004000,
    Invisible	= 0x00008000,
    Offscreen	= 0x00010000,
    Sizeable	= 0x00020000,
    Moveable	= 0x00040000,
    SelfVoicing	= 0x00080000,
    Focusable	= 0x00100000,
    Selectable	= 0x00200000,
    Linked		= 0x00400000,
    Traversed	= 0x00800000,
    MultiSelectable	= 0x01000000,
    ExtSelectable	= 0x02000000,
    AlertLow	= 0x04000000,
    AlertMedium	= 0x08000000,
    AlertHigh	= 0x10000000,
    Protected	= 0x20000000,
    Valid		= 0x3fffffff
    };

    enum Role {
    NoRole		= 0x00000000,
    TitleBar	= 0x00000001,
    MenuBar		= 0x00000002,
    ScrollBar	= 0x00000003,
    Grip		= 0x00000004,
    Sound		= 0x00000005,
    Cursor		= 0x00000006,
    Caret		= 0x00000007,
    AlertMessage	= 0x00000008,
    Window		= 0x00000009,
    Client		= 0x0000000A,
    PopupMenu	= 0x0000000B,
    MenuItem	= 0x0000000C,
    ToolTip		= 0x0000000D,
    Application	= 0x0000000E,
    Document	= 0x0000000F,
    Pane		= 0x00000010,
    Chart		= 0x00000011,
    Dialog		= 0x00000012,
    Border		= 0x00000013,
    Grouping	= 0x00000014,
    Separator	= 0x00000015,
    ToolBar		= 0x00000016,
    StatusBar	= 0x00000017,
    Table		= 0x00000018,
    ColumnHeader	= 0x00000019,
    RowHeader	= 0x0000001A,
    Column		= 0x0000001B,
    Row		= 0x0000001C,
    Cell		= 0x0000001D,
    Link		= 0x0000001E,
    HelpBalloon	= 0x0000001F,
    Character	= 0x00000020,
    List		= 0x00000021,
    ListItem	= 0x00000022,
    Outline		= 0x00000023,
    OutlineItem	= 0x00000024,
    PageTab		= 0x00000025,
    PropertyPage	= 0x00000026,
    Indicator	= 0x00000027,
    Graphic		= 0x00000028,
    StaticText	= 0x00000029,
    EditableText	= 0x0000002A,  // Editable, selectable, etc.
    PushButton	= 0x0000002B,
    CheckBox	= 0x0000002C,
    RadioButton	= 0x0000002D,
    ComboBox	= 0x0000002E,
    DropLest	= 0x0000002F,
    ProgressBar	= 0x00000030,
    Dial		= 0x00000031,
    HotkeyField	= 0x00000032,
    Slider		= 0x00000033,
    SpinBox		= 0x00000034,
    Diagram		= 0x00000035,
    Animation	= 0x00000036,
    Equation	= 0x00000037,
    ButtonDropDown	= 0x00000038,
    ButtonMenu	= 0x00000039,
    ButtonDropGrid	= 0x0000003A,
    Whitespace	= 0x0000003B,
    PageTabList	= 0x0000003C,
    Clock		= 0x0000003D
    };

    enum NavDirection {
    NavUp		= 0x00000001,
    NavDown		= 0x00000002,
    NavLeft		= 0x00000003,
    NavRight	= 0x00000004,
    NavNext		= 0x00000005,
    NavPrevious	= 0x00000006,
    NavFirstChild	= 0x00000007,
    NavLastChild	= 0x00000008,
    NavFocusChild	= 0x00000009
    };

    enum Text {
    Name		= 0,
    Description,
    Value,
    Help,
    Accelerator,
    DefaultAction
    };

    static QRESULT queryAccessibleInterface( QObject *, QAccessibleInterface ** );
    static void updateAccessibility( QObject *, int who, Event reason );
};

// {EC86CB9C-5DA0-4c43-A739-13EBDF1C6B14}
#define IID_QAccessible QUuid( 0xec86cb9c, 0x5da0, 0x4c43, 0xa7, 0x39, 0x13, 0xeb, 0xdf, 0x1c, 0x6b, 0x14 )

struct Q_EXPORT QAccessibleInterface : public QAccessible, public QUnknownInterface
{
    // check for valid pointers
    virtual bool	isValid() const = 0;

    // hierarchy
    virtual int		childCount() const = 0;
    virtual QRESULT	queryChild( int control, QAccessibleInterface** ) const = 0;
    virtual QRESULT	queryParent( QAccessibleInterface** ) const = 0;

    // navigation
    virtual int		controlAt( int x, int y ) const = 0;
    virtual QRect	rect( int control ) const = 0;
    virtual int		navigate( NavDirection direction, int startControl ) const = 0;

    // properties and state
    virtual QString	text( Text t, int control ) const = 0;
    virtual void	setText( Text t, int control, const QString &text ) = 0;
    virtual Role	role( int control ) const = 0;
    virtual State	state( int control ) const = 0;
    virtual QMemArray<int> selection() const = 0;

    // methods
    virtual bool	doDefaultAction( int control ) = 0;
    virtual bool	setFocus( int control ) = 0;
    virtual bool	setSelected( int control, bool on, bool extend ) = 0;
    virtual void	clearSelection() = 0;
};

// {49F4C6A7-412F-41DE-9E24-648843421FD3}
#ifndef IID_QAccessibleFactory
#define IID_QAccessibleFactory QUuid( 0x49f4c6a7, 0x412f, 0x41de, 0x9e, 0x24, 0x64, 0x88, 0x43, 0x42, 0x1f, 0xd3 )
#endif

struct Q_EXPORT QAccessibleFactoryInterface : public QAccessible, public QFeatureListInterface
{
    virtual QRESULT createAccessibleInterface( const QString &, QObject *, QAccessibleInterface** ) = 0;
};

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QGuardedPtr<QObject>;
// MOC_SKIP_END
#endif

class Q_EXPORT QAccessibleObject : public QObject, public QAccessibleInterface
{
public:
    QAccessibleObject( QObject *object );
    virtual ~QAccessibleObject();

    QRESULT	queryInterface( const QUuid &, QUnknownInterface** );
    Q_REFCOUNT

    bool	isValid() const;

protected:
    QObject *object() const;

private:
    QGuardedPtr<QObject> object_;
};

#endif //QT_ACCESSIBILITY_SUPPORT

#endif //QACCESSIBLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QAccessible Member List

Complete Member List for QAccessible

This is the complete list of member functions for QAccessible, including inherited members.

  • queryAccessibleInterface()
  • updateAccessibility()


QAccessibleInterface Class

QAccessibleInterface Class Reference

The QAccessibleInterface class defines an interface that exposes information about accessible objects. More...

#include <qaccessible.h>

Inherits QAccessible.

Inherited by QAccessibleObject.

List of all member functions.

Public Members

  • virtual bool isValid () const = 0
  • virtual int childCount () const = 0
  • virtual QRESULT queryChild ( int control, QAccessibleInterface ** iface ) const = 0
  • virtual QRESULT queryParent ( QAccessibleInterface ** iface ) const = 0
  • virtual int controlAt ( int x, int y ) const = 0
  • virtual QRect rect ( int control ) const = 0
  • virtual int navigate ( NavDirection direction, int startControl ) const = 0
  • virtual QString text ( Text t, int control ) const = 0
  • virtual void setText ( Text t, int control, const QString & text ) = 0
  • virtual Role role ( int control ) const = 0
  • virtual State state ( int control ) const = 0
  • virtual QMemArray<int> selection () const = 0
  • virtual bool doDefaultAction ( int control ) = 0
  • virtual bool setFocus ( int control ) = 0
  • virtual bool setSelected ( int control, bool on, bool extend ) = 0
  • virtual void clearSelection () = 0

Detailed Description

The QAccessibleInterface class defines an interface that exposes information about accessible objects.

See also Miscellaneous Classes.

Member Function Documentation

int QAccessibleInterface::childCount () const [pure virtual]

Returns the number of children that belong to this object. A child can provide accessibility information on it's own (e.g. a child widget), or be a sub-element of this accessible object.

All objects provide this information.

See also queryChild().

void QAccessibleInterface::clearSelection () [pure virtual]

Removes any selection from the object.

See also setSelected().

int QAccessibleInterface::controlAt ( int x, int y ) const [pure virtual]

Returns the ID of the child that contains the screen coordinates (x, y). This function returns 0 if the point is positioned on the object itself. If the tested point is outside the boundaries of the object this function returns -1.

All visual objects provide this information.

bool QAccessibleInterface::doDefaultAction ( int control ) [pure virtual]

Calling this function performs the default action of the child object specified by control, or the default action of the object itself if control is 0.

bool QAccessibleInterface::isValid () const [pure virtual]

Returns TRUE if all the data necessary to use this interface implementation is valid (e.g. all pointers are non-null), otherwise returns FALSE.

int QAccessibleInterface::navigate ( NavDirection direction, int startControl ) const [pure virtual]

This function traverses to another object, or to a sub-element of the current object. direction specifies in which direction to navigate, and startControl specifies the start point of the navigation, which is either 0 if the navigation starts at the object itself, or an ID of one of the object's sub-elements.

The function returns the ID of the sub-element located in the direction specified. If there is nothing in the navigated direction, this function returns -1.

All objects support navigation.

QRESULT QAccessibleInterface::queryChild ( int control, QAccessibleInterface ** iface ) const [pure virtual]

Sets iface to point to the implementation of the QAccessibleInterface for the child specified with control. If the child doesn't provide accessibility information on it's own, the value of iface is set to 0. For those elements, this object is responsible for exposing the child's properties.

All objects provide this information.

See also childCount() and queryParent().

QRESULT QAccessibleInterface::queryParent ( QAccessibleInterface ** iface ) const [pure virtual]

Sets iface to point to the implementation of the QAccessibleInterface for the parent object, or to 0 if there is no such implementation or object.

All objects provide this information.

See also queryChild().

QRect QAccessibleInterface::rect ( int control ) const [pure virtual]

Returns the location of the child specified with control in screen coordinates. This function returns the location of the object itself if control is 0.

All visual objects provide this information.

Role QAccessibleInterface::role ( int control ) const [pure virtual]

Returns the role of the object if control is 0, or the role of the object's sub-element with ID control. The role of an object is usually static. All accessible objects have a role.

See also text(), state() and selection().

QMemArray<int> QAccessibleInterface::selection () const [pure virtual]

Returns the list of all the element IDs that are selected.

See also text(), role() and state().

bool QAccessibleInterface::setFocus ( int control ) [pure virtual]

Gives the focus to the child object specified by control, or to the object itself if control is 0.

Returns TRUE if the focus could be set; otherwise returns FALSE.

bool QAccessibleInterface::setSelected ( int control, bool on, bool extend ) [pure virtual]

Sets the selection of the child object with ID control to on. If extend is TRUE, all child elements between the focused item and the specified child object have their selection set to on.

Returns TRUE if the selection could be set; otherwise returns FALSE.

See also setFocus() and clearSelection().

void QAccessibleInterface::setText ( Text t, int control, const QString & text ) [pure virtual]

Sets the text property t of the child object control to text. If control is 0, the text property of the object itself is set.

State QAccessibleInterface::state ( int control ) const [pure virtual]

Returns the current state of the object if control is 0, or the state of the object's sub-element element with ID control. All objects have a state.

See also text(), role() and selection().

QString QAccessibleInterface::text ( Text t, int control ) const [pure virtual]

Returns a string property t of the child object specified by control, or the string property of the object itself if control is 0.

The Name is a string used by clients to identify, find or announce an accessible object for the user. All objects must have a name that is unique within their container.

An accessible object's Description provides textual information about an object's visual appearance. The description is primarily used to provide greater context for low-vision or blind users, but is also used for context searching or other applications. Not all objects have a description. An "OK" button would not need a description, but a toolbutton that shows a picture of a smiley would.

The Value of an accessible object represents visual information contained by the object, e.g. the text in a line edit. Usually, the value can be modified by the user. Not all objects have a value, e.g. static text labels don't, and some objects have a state that already is the value, e.g. toggle buttons.

The Help text provides information about the function and usage of an accessible object. Not all objects provide this information.

An accessible object's DefaultAction describes the object's primary method of manipulation, and should be a verb or a short phrase, e.g. "Press" for a button.

The accelerator is a keyboard shortcut that activates the default action of the object. A keyboard shortcut is the underlined character in the text of a menu, menu item or control, and is either the character itself, or a combination of this character and a modifier key like ALT, CTRL or SHIFT. Command controls like tool buttons also have shortcut keys and usually display them in their tooltip.

See also role(), state() and selection().

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


QAccessibleInterface Member List

Complete Member List for QAccessibleInterface

This is the complete list of member functions for QAccessibleInterface, including inherited members.

  • childCount()
  • clearSelection()
  • controlAt()
  • doDefaultAction()
  • isValid()
  • navigate()
  • queryAccessibleInterface()
  • queryChild()
  • queryParent()
  • rect()
  • role()
  • selection()
  • setFocus()
  • setSelected()
  • setText()
  • state()
  • text()
  • updateAccessibility()


QAccessibleObject Class

QAccessibleObject Class Reference

The QAccessibleObject class implements parts of the QAccessibleInterface for QObjects. More...

#include <qaccessible.h>

Inherits QObject and QAccessibleInterface.

List of all member functions.

Public Members

  • QAccessibleObject ( QObject * object )
  • virtual ~QAccessibleObject ()

Protected Members

  • QObject * object () const

Detailed Description

The QAccessibleObject class implements parts of the QAccessibleInterface for QObjects.

This class is mainly provided for convenience. All subclasses of the QAccessibleInterface should use this class as the base class.

See also Miscellaneous Classes.

Member Function Documentation

QAccessibleObject::QAccessibleObject ( QObject * object )

Creates a QAccessibleObject for object.

QAccessibleObject::~QAccessibleObject () [virtual]

Destroys the QAccessibleObject.

This only happens when a call to release() decrements the internal reference counter to zero.

QObject * QAccessibleObject::object () const [protected]

Returns the QObject for which this QAccessibleInterface implementation provides information. Use isValid() to make sure the object pointer is safe to use.

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


QAccessibleObject Member List

Complete Member List for QAccessibleObject

This is the complete list of member functions for QAccessibleObject, including inherited members.

  • QAccessibleObject()
  • ~QAccessibleObject()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childCount()
  • childEvent()
  • children()
  • className()
  • clearSelection()
  • connect()
  • connectNotify()
  • controlAt()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doDefaultAction()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isValid()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • navigate()
  • normalizeSignalSlot()
  • object()
  • objectTrees()
  • parent()
  • property()
  • queryAccessibleInterface()
  • queryChild()
  • queryList()
  • queryParent()
  • rect()
  • removeChild()
  • removeEventFilter()
  • role()
  • selection()
  • sender()
  • setFocus()
  • setName()
  • setProperty()
  • setSelected()
  • setText()
  • signalsBlocked()
  • startTimer()
  • state()
  • text()
  • timerEvent()
  • tr()
  • trUtf8()
  • updateAccessibility()


QAction类

QAction类参考

QAction类提供了一个可以同时出现在菜单和工具条上的抽象用户界面操作。 详情请见……

#include <qaction.h>

Inherits QObject。

Inherited by QActionGroup。

所有成员函数的列表。

公有成员

  • QAction ( QObject * parent, const char * name = 0, bool toggle = FALSE )
  • QAction ( const QString & text, const QIconSet & icon, const QString & menuText, QKeySequence accel, QObject * parent, const char * name = 0, bool toggle = FALSE )
  • QAction ( const QString & text, const QString & menuText, QKeySequence accel, QObject * parent, const char * name = 0, bool toggle = FALSE )
  • ~QAction ()
  • virtual void setIconSet ( const QIconSet & )
  • QIconSet iconSet () const
  • virtual void setText ( const QString & )
  • QString text () const
  • virtual void setMenuText ( const QString & )
  • QString menuText () const
  • virtual void setToolTip ( const QString & )
  • QString toolTip () const
  • virtual void setStatusTip ( const QString & )
  • QString statusTip () const
  • virtual void setWhatsThis ( const QString & )
  • QString whatsThis () const
  • virtual void setAccel ( const QKeySequence & key )
  • QKeySequence accel () const
  • virtual void setToggleAction ( bool )
  • bool isToggleAction () const
  • bool isOn () const
  • bool isEnabled () const
  • virtual bool addTo ( QWidget * w )
  • virtual bool removeFrom ( QWidget * w )

公有槽

  • void toggle ()
  • virtual void setOn ( bool )
  • virtual void setEnabled ( bool )

信号

  • void activated ()
  • void toggled ( bool )

属性

  • QKeySequence accel - 操作快捷键
  • bool enabled - 操作是否生效
  • QIconSet iconSet - 操作的图标
  • QString menuText - 操作的菜单文本
  • bool on - 切换操作是否打开
  • QString statusTip - 操作的状态提示
  • QString text - 操作的描述文本
  • bool toggleAction - 操作是否是切换操作
  • QString toolTip - 操作的工具提示
  • QString whatsThis - 操作的“这是什么？”帮助文本

保护成员

  • virtual void addedTo ( QWidget * actionWidget, QWidget * container )
  • virtual void addedTo ( int index, QPopupMenu * menu )

详细描述

QAction类提供了一个可以同时出现在菜单和工具条上的抽象用户界面操作。

在图形用户界面应用程序中很多命令可以通过菜单选项、工具条按钮和键盘快捷键调用。因为同一个操作将会被执行，而与它的调用方法无关，并且因为菜单和工具条必须保持同步，所以提供一个操作这样的命令很有用。一个操作可以被添加到菜单和工具条中并且将会自动使它们同步。例如，如果用户按下“加粗”工具条按钮，“加粗”菜单项将会自动被选中。

QAction可以包含图标、菜单文本、快捷键、状态条文本、这是什么文本和工具提示。它们可以分别通过setIconSet()、setText()、setMenuText()、setToolTip()、setStatusTip()、setWhatsThis()和setAccel()来设置。

操作可以是一个切换操作，例如，一个“加粗”工具条按钮，或者一个命令操作，例如“打开文件”来调用打开文件对话框。当切换操作的状态改变了，它发射toggled()信号。当命令操作和切换按钮被调用时，它们都发射activated()信号。使用setToggleAction()来设置操作的切换状态。如果要看操作是否是切换操作，请使用isToggleAction()。切换操作可以是“开”，isOn()返回真，或者“关”，isOn()返回假。

操作可以使用addTo()被添加到窗口部件（菜单或者工具条）中，并且使用removeFrom()来移除。

一旦QAction已经被创建，它应该被添加到相应的菜单或者工具条重并且然后连接到执行这个操作的槽。例如：

        fileSaveAction = new QAction( "Save File", QPixmap( filesave ),
                                      "&Save", CTRL+Key_S, this, "save" );
        connect( fileSaveAction, SIGNAL( activated() ) , this, SLOT( save() ) );

我们创建一个菜单文本为“保存(&S)”并且Ctrl+S为键盘快捷键的“文件保存”操作。我们连接fileSaveAction的activated()信号到我自己的save()槽。注意在这时还没有菜单或者工具条操作，接下来我们将添加它们：

        QToolBar * fileTools = new QToolBar( this, "file operations" );

        fileSaveAction->addTo( fileTools );

        QPopupMenu * file = new QPopupMenu( this );
        menuBar()->insertItem( "&File", file );

        fileSaveAction->addTo( file );

我们创建了一个工具条并把我们的fileSaveAction添加进去。类似的，我们创建一个菜单，添加一个顶级菜单项并且把我们的fileSaveAction添加进去。

（对于一个更详细的实例请参考有QAction特征的简单应用程序排演。）

我们建议把操作为它所在的窗口的子对象来创建。在绝大多数情况下操作是应用程序主窗口的子对象。

为了防止循环，不要在一个稍后要添加操作的窗口部件的子对象中创建操作。

也可以参考主窗口和相关类和基本窗口部件。

成员函数文档

QAction::QAction ( QObject * parent, const char * name = 0, bool toggle = FALSE )

构造一个父对象为parent并且名称为name的操作。

如果toggle为真，操作将是切换操作，否则它就是命令操作。

如果parent是QActionGroup，新的操作会把自己插入到parent中。

为了使快捷键和状态提示能够工作，parent必须是一个窗口部件或者一个父对象为窗口部件的操作组。

QAction::QAction ( const QString & text, const QIconSet & icon, const QString & menuText, QKeySequence accel, QObject * parent, const char * name = 0, bool toggle = FALSE )

构造一个有如下属性的操作：描述为text、图标为icon、菜单文本为menuText并且键盘快捷键为accel。它是parent的子对象并且名称为name。如果toggle为真，操作将是切换操作，否则它就是命令操作。

如果parent是QActionGroup，新的操作会把自己插入到parent中。

为了使快捷键和状态提示能够工作，parent必须是一个窗口部件或者一个父对象为窗口部件的操作组。

text和accel将会用于工具提示和状态提示，除非你使用setToolTip()和setStatusTip()为它们提供特定文本。

QAction::QAction ( const QString & text, const QString & menuText, QKeySequence accel, QObject * parent, const char * name = 0, bool toggle = FALSE )

这个构造函数的结果是没有图标的操作：描述为text、菜单文本为menuText并且键盘快捷键为accel。它是parent的子对象并且名称为name。如果toggle为真，操作将是切换操作，否则它就是命令操作。

如果parent是QActionGroup，新的操作会把自己插入到parent中。

为了使快捷键和状态提示能够工作，parent必须是一个窗口部件或者一个父对象为窗口部件的操作组。

text和accel将会用于工具提示和状态提示，除非你使用setToolTip()和setStatusTip()为它们提供特定文本。

QAction::~QAction ()

销毁这个对象并且释放已经分配的资源。

QKeySequence QAction::accel () const

返回操作的快捷键。详细情况请参考“accel”属性。

void QAction::activated () [信号]

当操作被用户激活时，也就是说当用户点击菜单选项或者工具条按钮或者按下操作的快捷键组合时，这个信号被发射。

对于命令操作连接这个信号。对于切换按钮连接toggled()信号。

例如：action/application.cpp、chart/chartform.cpp和themes/themes.cpp。

bool QAction::addTo ( QWidget * w ) [虚]

把这个这个操作添加到窗口部件w。

现在操作可以被添加到QToolBar和QPopupMenu窗口部件中。

被添加到菜单条中的操作会自动被显示为一个按钮，被添加到弹出菜单中的操作会自动显示为一个菜单项。

如果操作被添加成功，addTo()返回真，否则返回假。（如果w不是QToolBar或者QPopupMenu，操作将不会被添加并且将返回假。）

也可以参考removeFrom()。

例如：action/application.cpp、action/toggleaction/toggleaction.cpp、chart/chartform.cpp和textedit/textedit.cpp。

在QActionGroup中被重新实现。

void QAction::addedTo ( QWidget * actionWidget, QWidget * container ) [虚 保护]

当它在container中为这个操作创建一个窗口部件时（actionWidget），这个函数被addTo()调用。

void QAction::addedTo ( int index, QPopupMenu * menu ) [虚 保护]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

当它在弹出菜单menu中为这个操作创建一个索引为index的菜单项时，这个函数被addTo()调用。

QIconSet QAction::iconSet () const

返回操作的图标。详细情况请参考“iconSet”属性。

bool QAction::isEnabled () const

如果操作生效，返回真，否则返回假。详细情况请参考“enabled”属性。

bool QAction::isOn () const

如果切换操作是开的，返回真，否则返回假。详细情况请参考“on”属性。

bool QAction::isToggleAction () const

如果操作是切换操作，返回真，否则返回假。详细情况请参考“toggleAction”属性。

QString QAction::menuText () const

返回操作的菜单文本。详细情况请参考“menuText”属性。

bool QAction::removeFrom ( QWidget * w ) [虚]

从窗口部件w中移除操作。

如果操作被成功移除，返回真，否则返回假。

也可以参考addTo()。

void QAction::setAccel ( const QKeySequence & key ) [虚]

设置操作的快捷键为key。详细情况请参考“accel”属性。

void QAction::setEnabled ( bool ) [虚 槽]

设置操作是否生效。详细情况请参考“enabled”属性。

void QAction::setIconSet ( const QIconSet & ) [虚]

设置操作的图标。详细情况请参考“iconSet”属性。

void QAction::setMenuText ( const QString & ) [虚]

设置操作的菜单文本。详细情况请参考“menuText”属性。

void QAction::setOn ( bool ) [虚 槽]

设置切换按钮为开。详细情况请参考“on”属性。

void QAction::setStatusTip ( const QString & ) [虚]

设置操作的状态提示。详细情况请参考“statusTip”属性。

void QAction::setText ( const QString & ) [虚]

设置操作的描述文本。详细情况请参考“text”属性。

void QAction::setToggleAction ( bool ) [虚]

设置操作是否是切换按钮。详细情况请参考“toggleAction”属性。

void QAction::setToolTip ( const QString & ) [虚]

设置操作的工具提示。详细情况请参考“toolTip”属性。

void QAction::setWhatsThis ( const QString & ) [虚]

设置操作的“这是什么？”帮助文本。详细情况请参考“whatsThis”属性。

QString QAction::statusTip () const

返回操作的状态提示。详细情况请参考“statusTip”属性。

QString QAction::text () const

返回操作的描述文本。详细情况请参考“text”属性。

void QAction::toggle () [槽]

切换切换按钮的状态。

也可以参考on、toggled()和toggleAction。

void QAction::toggled ( bool ) [信号]

当切换按钮改变状态时，这个信号被发射，命令操作和QActionGroups不发射toggled()。

参数表示新的状态，也就是如果切换按钮被打开，为真，或者如果它被关闭，为假。

依赖切换按钮是否被打开或者关闭来触发用户命令要把它连接到一个可以得到bool变量来识别状态的槽，例如：

        QMainWindow * window = new QMainWindow;

        QAction * labelonoffaction = new QAction( window, "labelonoff", TRUE );

        QObject::connect( labelonoffaction, SIGNAL( toggled( bool ) ),
                          window, SLOT( setUsesTextLabel( bool ) ) );

也可以参考activated()、toggleAction和on。

实例：action/toggleaction/toggleaction.cpp。

QString QAction::toolTip () const

返回操作的工具提示。详细情况请参考“toolTip”属性。

QString QAction::whatsThis () const

返回操作的“这是什么？”帮助文本。详细情况请参考“whatsThis”属性。

属性文档

QKeySequence accel

这个属性保存的是操作的快捷键。

键代码可以在Qt::Key和Qt::Modifier中找到。这里没有默认快捷键。

通过setAccel()设置属性值并且通过accel()来获得属性值。

bool enabled

这个属性保存的是操作是否生效。

失效的操作不能被用户选择。它们不从菜单/工具条上消失，但是会以某种方式表面它们不可用，例如，它们也许被变灰。

失效操作上的“这是什么？”帮助还是由被设置的QAction::whatsThis属性提供。

通过setEnabled()设置属性值并且通过isEnabled()来获得到属性值。

QIconSet iconSet

这个属性保存的是操作的图标。

这个图标会用在工具条按钮和菜单中菜单文本的左面。这里没有默认图标。

（请参考action/toggleaction/toggleaction.cpp实例。）

通过setIconSet()设置属性值并且通过iconSet()来获得属性值。

QString menuText

这个属性保存的是操作的菜单文本。

如果操作备添加为菜单中的一个菜单选项将会由图标（如果有的话）、菜单文本和快捷键（如果有的话）组成。如果没有菜单文本在构造函数或者使用setMenuText()中明确设置，操作的描述文本将用来作为菜单文本。这里没有默认菜单文本。

也可以参考text。

通过setMenuText()设置属性值并且通过menuText()来获得属性值。

bool on

这个属性保存的是切换按钮是否为开。

对于命令操作和QActionGroup这个属性总是开的（真），setOn()对于它们没有效果。对于为真的操作，这个属性的默认值是关（假）。

也可以参考toggleAction。

通过setOn()设置属性值并且通过isOn()来获得属性值。

QString statusTip

这个属性保存的是操作的状态提示。

这个状态提示将会被显示在操作的顶级父窗口部件提供的所有状态条上。

如果没有状态提示被定义，操作使用工具条提示文本。

这里没有默认的状态提示。

也可以参考statusTip和toolTip。

通过setStatusTip()设置属性值并且通过statusTip()来获得属性值。

QString text

这个属性保存的是操作的描述文本。

如果QMainWindow::usesTextLabel为真，文本将会作为相应工具按钮上的文本。如果没有菜单文本和工具条提示被定义，它也可以作为相应的默认文本。这里没有默认的文本。

也可以参考menuText、toolTip和statusTip。

通过setText()设置属性值并且通过text()来获得属性值。

bool toggleAction

这个属性保存的是操作是否是切换操作。

切换操作的状态为开/关中的一种。例如，“加粗”工具条按钮是开或者是开。不是切换操作的操作是命令操作，命令操作被简单执行。这个属性默认为假。

在一些情况下，切换操作的状态依赖于其它切换操作状态。例如，“左对齐”、“中间对齐”和“右对齐”切换操作是互斥的。为了达到互斥切换，把相关切换操作添加到QActionGroup中，并且把QActionGroup::exclusive属性设置为真。

通过setToggleAction()设置属性值并且通过isToggleAction()来获得属性值。

QString toolTip

这个属性保存得失操作的工具提示。

这个文本用于工具提示。如果没有状态提示被设置，工具提示会被用作状态提示。

如果没有指定工具提示，那么操作的文本被使用并且如果没有指定操作的文本没有被指定，那么描述文本将被用作工具提示。

这里没有默认工具提示文本。

也可以参考statusTip和accel。

通过setToolTip()设置属性值并且通过toolTip()来获得属性值。

QString whatsThis

这个属性保存的是操作的“这是什么？”帮助文本。

“这是什么？”文本被用来提供操作的简要描述。这个文本中可以使用多信息文本（比如HTML标记——对于支持的标记得列表请参考QStyleSheet）。这里没有默认的“这是什么？”文本。

也可以参考QWhatsThis。

通过setWhatsThis()设置属性值并且通过whatsThis()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


A Complete Application Window with Actions

This example program is just like the application example, but uses QAction to build the menu and the toolbar.

The QAction related part of the program is covered in detail by the QAction application walkthrough whilst the Simple application walkthrough deals with the rest.

Header file:

/****************************************************************************
** $Id:  qt/application.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef APPLICATION_H
#define APPLICATION_H

#include <qmainwindow.h>

class QTextEdit;

class ApplicationWindow: public QMainWindow
{
    Q_OBJECT

public:
    ApplicationWindow();
    ~ApplicationWindow();

protected:
    void closeEvent( QCloseEvent* );

private slots:
    void newDoc();
    void choose();
    void load( const QString &fileName );
    void save();
    void saveAs();
    void print();

    void about();
    void aboutQt();

private:
    QPrinter *printer;
    QTextEdit *e;
    QString filename;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/application.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "application.h"

#include <qimage.h>
#include <qpixmap.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qtextedit.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qprinter.h>
#include <qapplication.h>
#include <qaccel.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qwhatsthis.h>
#include <qaction.h>

#include "filesave.xpm"
#include "fileopen.xpm"
#include "fileprint.xpm"

ApplicationWindow::ApplicationWindow()
    : QMainWindow( 0, "example application main window", WDestructiveClose )
{
    printer = new QPrinter;

    QAction * fileNewAction;
    QAction * fileOpenAction;
    QAction * fileSaveAction, * fileSaveAsAction, * filePrintAction;
    QAction * fileCloseAction, * fileQuitAction;

    fileNewAction = new QAction( "New", "&New", CTRL+Key_N, this, "new" );
    connect( fileNewAction, SIGNAL( activated() ) , this,
             SLOT( newDoc() ) );

    fileOpenAction = new QAction( "Open File", QPixmap( fileopen ), "&Open",
                                  CTRL+Key_O, this, "open" );
    connect( fileOpenAction, SIGNAL( activated() ) , this, SLOT( choose() ) );

    const char * fileOpenText = "<p><img source=\"fileopen\"> "
                     "Click this button to open a <em>new file</em>. <br>"
                     "You can also select the <b>Open</b> command "
                     "from the <b>File</b> menu.</p>";
    QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen",
                          fileOpenAction->iconSet().pixmap() );
    fileOpenAction->setWhatsThis( fileOpenText );

    fileSaveAction = new QAction( "Save File", QPixmap( filesave ),
                                  "&Save", CTRL+Key_S, this, "save" );
    connect( fileSaveAction, SIGNAL( activated() ) , this, SLOT( save() ) );

    const char * fileSaveText = "<p>Click this button to save the file you "
                     "are editing. You will be prompted for a file name.\n"
                     "You can also select the <b>Save</b> command "
                     "from the <b>File</b> menu.</p>";
    fileSaveAction->setWhatsThis( fileSaveText );

    fileSaveAsAction = new QAction( "Save File As", "Save &as", 0,  this,
                                    "save as" );
    connect( fileSaveAsAction, SIGNAL( activated() ) , this,
             SLOT( saveAs() ) );
    fileSaveAsAction->setWhatsThis( fileSaveText );

    filePrintAction = new QAction( "Print File", QPixmap( fileprint ),
                                   "&Print", CTRL+Key_P, this, "print" );
    connect( filePrintAction, SIGNAL( activated() ) , this,
             SLOT( print() ) );

    const char * filePrintText = "Click this button to print the file you "
                     "are editing.\n You can also select the Print "
                     "command from the File menu.";
    filePrintAction->setWhatsThis( filePrintText );

    fileCloseAction = new QAction( "Close", "&Close", CTRL+Key_W, this,
                                   "close" );
    connect( fileCloseAction, SIGNAL( activated() ) , this,
             SLOT( close() ) );

    fileQuitAction = new QAction( "Quit", "&Quit", CTRL+Key_Q, this,
                                  "quit" );
    connect( fileQuitAction, SIGNAL( activated() ) , qApp,
             SLOT( closeAllWindows() ) );

    // populate a tool bar with some actions

    QToolBar * fileTools = new QToolBar( this, "file operations" );
    fileTools->setLabel( "File Operations" );
    fileOpenAction->addTo( fileTools );
    fileSaveAction->addTo( fileTools );
    filePrintAction->addTo( fileTools );
    (void)QWhatsThis::whatsThisButton( fileTools );

    // populate a menu with all actions

    QPopupMenu * file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );
    fileNewAction->addTo( file );
    fileOpenAction->addTo( file );
    fileSaveAction->addTo( file );
    fileSaveAsAction->addTo( file );
    file->insertSeparator();
    filePrintAction->addTo( file );
    file->insertSeparator();
    fileCloseAction->addTo( file );
    fileQuitAction->addTo( file );

    menuBar()->insertSeparator();

    // add a help menu

    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertItem( "&Help", help );
    help->insertItem( "&About", this, SLOT(about()), Key_F1 );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
    help->insertSeparator();
    help->insertItem( "What's &This", this, SLOT(whatsThis()),
                      SHIFT+Key_F1 );

    // create and define the central widget

    e = new QTextEdit( this, "editor" );
    e->setFocus();
    setCentralWidget( e );
    statusBar()->message( "Ready", 2000 );

    resize( 450, 600 );
}

ApplicationWindow::~ApplicationWindow()
{
    delete printer;
}

void ApplicationWindow::newDoc()
{
    ApplicationWindow *ed = new ApplicationWindow;
    ed->show();
}

void ApplicationWindow::choose()
{
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null,
                                               this);
    if ( !fn.isEmpty() )
        load( fn );
    else
        statusBar()->message( "Loading aborted", 2000 );
}

void ApplicationWindow::load( const QString &fileName )
{
    QFile f( fileName );
    if ( !f.open( IO_ReadOnly ) )
        return;

    QTextStream ts( &f );
    e->setText( ts.read() );
    e->setModified( FALSE );
    setCaption( fileName );
    statusBar()->message( "Loaded document " + fileName, 2000 );
}

void ApplicationWindow::save()
{
    if ( filename.isEmpty() ) {
        saveAs();
        return;
    }

    QString text = e->text();
    QFile f( filename );
    if ( !f.open( IO_WriteOnly ) ) {
        statusBar()->message( QString("Could not write to %1").arg(filename),
                              2000 );
        return;
    }

    QTextStream t( &f );
    t << text;
    f.close();

    e->setModified( FALSE );

    setCaption( filename );

    statusBar()->message( QString( "File %1 saved" ).arg( filename ), 2000 );
}

void ApplicationWindow::saveAs()
{
    QString fn = QFileDialog::getSaveFileName( QString::null, QString::null,
                                               this );
    if ( !fn.isEmpty() ) {
        filename = fn;
        save();
    } else {
        statusBar()->message( "Saving aborted", 2000 );
    }
}

void ApplicationWindow::print()
{
    const int Margin = 10;
    int pageNo = 1;

    if ( printer->setup(this) ) {               // printer dialog
        statusBar()->message( "Printing..." );
        QPainter p;
        if( !p.begin( printer ) )              // paint on printer
            return;

        p.setFont( e->font() );
        int yPos        = 0;                    // y-position for each line
        QFontMetrics fm = p.fontMetrics();
        QPaintDeviceMetrics metrics( printer ); // need width/height
                                                // of printer surface
        for( int i = 0 ; i < e->lines() ; i++ ) {
            if ( Margin + yPos > metrics.height() - Margin ) {
                QString msg( "Printing (page " );
                msg += QString::number( ++pageNo );
                msg += ")...";
                statusBar()->message( msg );
                printer->newPage();             // no more room on this page
                yPos = 0;                       // back to top of page
            }
            p.drawText( Margin, Margin + yPos,
                        metrics.width(), fm.lineSpacing(),
                        ExpandTabs | DontClip,
                        e->text( i ) );
            yPos = yPos + fm.lineSpacing();
        }
        p.end();                                // send job to printer
        statusBar()->message( "Printing completed", 2000 );
    } else {
        statusBar()->message( "Printing aborted", 2000 );
    }
}

void ApplicationWindow::closeEvent( QCloseEvent* ce )
{
    if ( !e->isModified() ) {
        ce->accept();
        return;
    }

    switch( QMessageBox::information( this, "Qt Application Example",
                                      "The document has been changed since "
                                      "the last save.",
                                      "Save Now", "Cancel", "Leave Anyway",
                                      0, 1 ) ) {
    case 0:
        save();
        ce->accept();
        break;
    case 1:
    default: // just for sanity
        ce->ignore();
        break;
    case 2:
        ce->accept();
        break;
    }
}

void ApplicationWindow::about()
{
    QMessageBox::about( this, "Qt Application Example",
                        "This example demonstrates simple use of "
                        "QMainWindow,\nQMenuBar and QToolBar.");
}

void ApplicationWindow::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Application Example" );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "application.h"

int main( int argc, char ** argv ) {
    QApplication a( argc, argv );
    ApplicationWindow * mw = new ApplicationWindow();
    mw->setCaption( "Document 1" );
    mw->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    return a.exec();
}

See also QAction Examples.


QAction Examples

The following example programs show how to use the QAction and QActionGroup classes.

A Tiny Example Featuring QActionGroup
A Complete Application Window with Actions
A Tiny Example Featuring a Toggle Action

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


qaction.h包含文件

qaction.h

这里是qaction.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qaction.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QAction class
**
** Created : 000000
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QACTION_H
#define QACTION_H

#ifndef QT_H
#include "qobject.h"
#include "qiconset.h"
#include "qstring.h"
#include "qkeysequence.h"
#endif // QT_H

#ifndef QT_NO_ACTION

class QActionPrivate;
class QActionGroupPrivate;
class QStatusBar;
class QPopupMenu;

class Q_EXPORT QAction : public QObject
{
    Q_OBJECT
    Q_PROPERTY( bool toggleAction READ isToggleAction WRITE setToggleAction)
    Q_PROPERTY( bool on READ isOn WRITE setOn )
    Q_PROPERTY( bool enabled READ isEnabled WRITE setEnabled )
    Q_PROPERTY( QIconSet iconSet READ iconSet WRITE setIconSet )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( QString menuText READ menuText WRITE setMenuText )
    Q_PROPERTY( QString toolTip READ toolTip WRITE setToolTip )
    Q_PROPERTY( QString statusTip READ statusTip WRITE setStatusTip )
    Q_PROPERTY( QString whatsThis READ whatsThis WRITE setWhatsThis )
    Q_PROPERTY( QKeySequence accel READ accel WRITE setAccel )

public:
    QAction( QObject* parent, const char* name = 0, bool toggle = FALSE  );
    QAction( const QString& text, const QIconSet& icon, const QString& menuText, QKeySequence accel,
         QObject* parent, const char* name = 0, bool toggle = FALSE );
    QAction( const QString& text, const QString& menuText, QKeySequence accel, QObject* parent,
         const char* name = 0, bool toggle = FALSE );
    ~QAction();

    virtual void setIconSet( const QIconSet& );
    QIconSet iconSet() const;
    virtual void setText( const QString& );
    QString text() const;
    virtual void setMenuText( const QString& );
    QString menuText() const;
    virtual void setToolTip( const QString& );
    QString toolTip() const;
    virtual void setStatusTip( const QString& );
    QString statusTip() const;
    virtual void setWhatsThis( const QString& );
    QString whatsThis() const;
    virtual void setAccel( const QKeySequence& key );
    QKeySequence accel() const;
    virtual void setToggleAction( bool );
    bool isToggleAction() const;
    bool isOn() const;
    bool isEnabled() const;
    virtual bool addTo( QWidget* );
    virtual bool removeFrom( QWidget* );

protected:
    virtual void addedTo( QWidget *actionWidget, QWidget *container );
    virtual void addedTo( int index, QPopupMenu *menu );

public slots:
    void toggle();
    virtual void setOn( bool );
    virtual void setEnabled( bool );

signals:
    void activated();
    void toggled( bool );

private slots:
    void internalActivation();
    void toolButtonToggled( bool );
    void objectDestroyed();
    void menuStatusText( int id );
    void showStatusText( const QString& );
    void clearStatusText();

private:
    void init();

    QActionPrivate* d;

};

class Q_EXPORT QActionGroup : public QAction
{
    Q_OBJECT
    Q_PROPERTY( bool exclusive READ isExclusive WRITE setExclusive )
    Q_PROPERTY( bool usesDropDown READ usesDropDown WRITE setUsesDropDown )

public:
    QActionGroup( QObject* parent, const char* name = 0, bool exclusive = TRUE );
    ~QActionGroup();
    void setExclusive( bool );
    bool isExclusive() const;
    void add( QAction* a);
    void addSeparator();
    bool addTo( QWidget* );
    bool removeFrom( QWidget* );
    void setEnabled( bool );

    void setUsesDropDown( bool enable );
    bool usesDropDown() const;

    void setIconSet( const QIconSet& );
    void setText( const QString& );
    void setMenuText( const QString& );
    void setToolTip( const QString& );
    void setWhatsThis( const QString& );

protected:
    void childEvent( QChildEvent* );
    virtual void addedTo( QWidget *actionWidget, QWidget *container, QAction *a );
    virtual void addedTo( int index, QPopupMenu *menu, QAction *a );
    virtual void addedTo( QWidget *actionWidget, QWidget *container );
    virtual void addedTo( int index, QPopupMenu *menu );

signals:
    void selected( QAction* );

private slots:
    void childToggled( bool );
    void childDestroyed();
    void internalComboBoxActivated( int );
    void internalToggle( QAction* );
    void objectDestroyed();

private:
    QActionGroupPrivate* d;

#ifndef QT_NO_COMPAT
public:
    void insert( QAction* a ) { add( a ); }
#endif

};

#endif

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QAction成员列表

完整的QAction成员列表

这里是QAction成员函数的完整列表，包括继承的成员。

  • QAction()
  • ~QAction()
  • accel()
  • activated()
  • addTo()
  • addedTo()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • iconSet()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isEnabled()
  • isOn()
  • isToggleAction()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • menuText()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • removeFrom()
  • sender()
  • setAccel()
  • setEnabled()
  • setIconSet()
  • setMenuText()
  • setName()
  • setOn()
  • setProperty()
  • setStatusTip()
  • setText()
  • setToggleAction()
  • setToolTip()
  • setWhatsThis()
  • signalsBlocked()
  • startTimer()
  • statusTip()
  • text()
  • timerEvent()
  • toggle()
  • toggled()
  • toolTip()
  • tr()
  • trUtf8()
  • whatsThis()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QActionGroup类

QActionGroup类参考

QActionGroup类把操作组合在一起。 详情请见……

#include <qaction.h>

继承了QAction。

所有成员函数的列表。

公有成员

  • QActionGroup ( QObject * parent, const char * name = 0, bool exclusive = TRUE )
  • ~QActionGroup ()
  • void setExclusive ( bool )
  • bool isExclusive () const
  • void add ( QAction * action )
  • void addSeparator ()
  • virtual bool addTo ( QWidget * w )
  • void setUsesDropDown ( bool enable )
  • bool usesDropDown () const
  • void insert ( QAction * a ) (obsolete)

信号

  • void selected ( QAction * )

属性

  • bool exclusive - 操作组是否是排它切换的
  • bool usesDropDown - 组的操作是否被显示到操作组所被添加到的窗口部件的子窗口部件中

保护成员

  • virtual void addedTo ( QWidget * actionWidget, QWidget * container, QAction * a )
  • virtual void addedTo ( int index, QPopupMenu * menu, QAction * a )

详细描述

QActionGroup类把操作组合在一起。

在一些情况下，把操作组合在一起是很有用的。例如，你有一个左对齐操作、右对齐操作和中间对齐操作，任何一个时间内只能有一个操作是被激活的，并且达到这一点的简单方法就是把这些操作组合在一个操作组中并且调用setExclusive(TRUE)。

操作组也可以像单一的单元那样被添加到菜单或者工具条中，操作组中的所有操作都被分别显示为菜单选项和工具条按钮。

这里是来自examples/textedit的实例：

        QActionGroup *grp = new QActionGroup( this );
        grp->setExclusive( TRUE );
        connect( grp, SIGNAL( selected( QAction* ) ), this, SLOT( textAlign( QAction* ) ) );

我们创建一个新的操作组并且调用setExclusive()来确保任何一个时间内组中只有一个操作可以被激活。然后我们把组的selected()信号连接到我们的textAlign()槽。

        actionAlignLeft = new QAction( tr( "Left" ), QPixmap( "textleft.xpm" ), tr( "&Left" ), CTRL + Key_L, grp, "textLeft" );
        actionAlignLeft->addTo( tb );
        actionAlignLeft->addTo( menu );
        actionAlignLeft->setToggleAction( TRUE );

我们创建一个左对齐操作，把它添加到工具条和菜单中并且使它成为切换操作。我们也用同样的方式创建中间对齐操作和右对齐操作。

在操作组中的操作像通常一样发射它们的activated()信号（对于切换操作是toggled()）。

setExclusive()函数用来确保任何一个时间内只用一个操作被激活，它应该被用在toggleAction被设置为真的操作中。

操作组中的操作分别出现在菜单选项合工具条按钮中。对于排它操作组使用setUsesDropDown()可以把这些操作显示到操作组所被添加到的窗口部件的子窗口部件中。例如，这些操作可以出现在工具条中的组合框中或者菜单的子菜单中。

操作可以使用add()被添加到操作组汇总，但通常它们把操作组作为父对象来创建就可以了。操作可以使用addSeparator()来分割。操作组可以使用addTo()被添加到窗口部件中。

也可以参考主窗口和相关类和基本窗口部件。

成员函数文档

QActionGroup::QActionGroup ( QObject * parent, const char * name = 0, bool exclusive = TRUE )

构造一个父对象为parent并且名称为name的操作组。

如果exclusive为真，组中只有一个切换操作可以被激活。

QActionGroup::~QActionGroup ()

销毁这个对象并且释放已经分配的资源。

void QActionGroup::add ( QAction * action )

把操作action添加到组中。

通常把这个组作为父对象创建的操作被添加到组中，所以这个函数通常不被用到。

也可以参考addTo()。

void QActionGroup::addSeparator ()

把分隔符添加到组中。

bool QActionGroup::addTo ( QWidget * w ) [virtual]

把这个操作组添加到窗口部件w中。

如果usesDropDown()为真并且exclusive为真（请参考setExclusive()），如果w是一个工具条的话，这些操作就会出现在一个组合框中或者w是一个菜单的话，它们就会作为一个子菜单出现。否则（默认）组中的操作将会分别被加入到窗口部件中。例如，如果窗口部件是菜单，这些操作将分别被显示为菜单选项，如果窗口部件是工具条的话，它们被分别显示为工具条按钮。

在操作组中的操作，特别是usesDropDown()为真的，建议设置它们的menuText()或text()属性。

应该在操作组被添加到窗口部件之前，所有的操作被添加到操作组中。如果在操作组被添加到窗口部件之后，被添加到操作组中的操作将不会被显示。

也可以参考exclusive、usesDropDown和removeFrom()。

实例：action/actiongroup/editor.cpp和themes/themes.cpp。

从QAction中重新实现的。

void QActionGroup::addedTo ( QWidget * actionWidget, QWidget * container, QAction * a ) [虚 保护]

当它在container中为这个子操作a创建一个窗口部件时（actionWidget），这个函数被addTo()调用。

void QActionGroup::addedTo ( int index, QPopupMenu * menu, QAction * a ) [虚 保护]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

当它在弹出菜单menu中为这个子操作创建一个索引为index的菜单项时，这个函数被addTo()调用。

void QActionGroup::insert ( QAction * a )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用add()来替代，或者使用操作组作为父对象来创建操作更好。

bool QActionGroup::isExclusive () const

如果操作组是排它切换的，返回真，否则返回假。详细情况请参考“exclusive”属性。

void QActionGroup::selected ( QAction * ) [信号]

当切换操作改变状态时，这个信号从排它组中被发射。

参数是状态变为“开”的操作。

        QActionGroup * colors = new QActionGroup( this, "colors", TRUE );

        QObject::connect( colors, SIGNAL( selected( QAction * ) ),
                          this, SLOT( setFontColor( QAction * ) ) );

在这个实例中，我们把selected()信号连接到我们自己的setFontColor()槽，传递QAction所以我们可以直到哪个操作被用户选择。

（请参考QActionGroup排演。）

也可以参考exclusive和on。

实例：action/actiongroup/editor.cpp、chart/chartform.cpp和textedit/textedit.cpp。

void QActionGroup::setExclusive ( bool )

设置操作组是否排它切换。详细情况请参考“exclusive”属性。

void QActionGroup::setUsesDropDown ( bool enable )

设置组中的操作是否被显示为操作组所被添加到的窗口部件的子窗口部件为enable。详细情况请参考“usesDropDown”属性。

bool QActionGroup::usesDropDown () const

如果组的操作被显示为操作组所被添加到的窗口部件的子窗口部件，返回真，否则返回假。详细情况请参考“usesDropDown”属性。

属性文档

bool exclusive

这个属性保存的是操作组是否是排它切换。

如果exclusive为真，则任何一个时间内操作组中只有一个切换操作可以被激活。如果用户选择组中的其它切换操作，那么被用户选择的被激活，其它的变为非活动的。默认情况下这个属性为假。

也可以参考QAction::toggleAction。

通过setExclusive()设置属性值并且通过isExclusive()来获得属性值。

bool usesDropDown

这个属性保存的是组的操作是否被显示到操作组所被添加到的窗口部件的子窗口部件中。

被添加到工具条中的排它操作组会在组合框中显示它们的操作，操作的QAction::text和QAction::iconSet属性被显示。非排它组会被分别显示为工具按钮，显示它们的QAction::iconSet，并且——依赖于QMainWindow::usesTextLabel()——来显示text()属性。

在弹出菜单中，成员操作会被显示在子菜单中。

改变usersDropDown只影响subsequent调用addTo()。

这个属性的默认值为假。

通过setUsesDropDown()设置属性值并且通过usesDropDown()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QActionGroup成员列表

完整的QActionGroup成员列表

这里是QActionGroup成员函数的完整列表，包括继承的成员。

  • QActionGroup()
  • ~QActionGroup()
  • accel()
  • activated()
  • add()
  • addSeparator()
  • addTo()
  • addedTo()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • iconSet()
  • inherits()
  • insert()
  • insertChild()
  • installEventFilter()
  • isA()
  • isEnabled()
  • isExclusive()
  • isOn()
  • isToggleAction()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • menuText()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • removeFrom()
  • selected()
  • sender()
  • setAccel()
  • setEnabled()
  • setExclusive()
  • setIconSet()
  • setMenuText()
  • setName()
  • setOn()
  • setProperty()
  • setStatusTip()
  • setText()
  • setToggleAction()
  • setToolTip()
  • setUsesDropDown()
  • setWhatsThis()
  • signalsBlocked()
  • startTimer()
  • statusTip()
  • text()
  • timerEvent()
  • toggle()
  • toggled()
  • toolTip()
  • tr()
  • trUtf8()
  • usesDropDown()
  • whatsThis()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QApplication类

QApplication类参考

QApplication类管理图形用户界面应用程序的控制流和主要设置。 详情请见……

#include <qapplication.h>

继承了QObject。

被QXtApplication继承。

所有成员函数的列表。

公有成员

  • QApplication ( int & argc, char ** argv )
  • QApplication ( int & argc, char ** argv, bool GUIenabled )
  • enum Type { Tty, GuiClient, GuiServer }
  • QApplication ( int & argc, char ** argv, Type type )
  • QApplication ( Display * dpy, HANDLE visual = 0, HANDLE colormap = 0 )
  • QApplication ( Display * dpy, int argc, char ** argv, HANDLE visual = 0, HANDLE colormap = 0 )
  • virtual ~QApplication ()
  • int argc () const
  • char ** argv () const
  • Type type () const
  • enum ColorSpec { NormalColor = 0, CustomColor = 1, ManyColor = 2 }
  • QWidget * mainWidget () const
  • virtual void setMainWidget ( QWidget * mainWidget )
  • virtual void polish ( QWidget * w )
  • QWidget * focusWidget () const
  • QWidget * activeWindow () const
  • int exec ()
  • void processEvents ()
  • void processEvents ( int maxtime )
  • void processOneEvent ()
  • bool hasPendingEvents ()
  • int enter_loop ()
  • void exit_loop ()
  • int loopLevel () const
  • virtual bool notify ( QObject * receiver, QEvent * e )
  • void setDefaultCodec ( QTextCodec * codec )
  • QTextCodec * defaultCodec () const
  • void installTranslator ( QTranslator * mf )
  • void removeTranslator ( QTranslator * mf )
  • enum Encoding { DefaultCodec, UnicodeUTF8 }
  • QString translate ( const char * context, const char * sourceText, const char * comment = 0, Encoding encoding = DefaultCodec ) const
  • virtual bool macEventFilter ( EventRef )
  • virtual bool winEventFilter ( MSG * )
  • virtual bool x11EventFilter ( XEvent * )
  • int x11ProcessEvent ( XEvent * event )
  • virtual bool qwsEventFilter ( QWSEvent * )
  • void qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )
  • void winFocus ( QWidget * widget, bool gotFocus )
  • bool isSessionRestored () const
  • QString sessionId () const
  • virtual void commitData ( QSessionManager & sm )
  • virtual void saveState ( QSessionManager & sm )
  • void wakeUpGuiThread ()
  • void lock ()
  • void unlock ( bool wakeUpGui = TRUE )
  • bool locked ()
  • bool tryLock ()

公有槽

  • void quit ()
  • void closeAllWindows ()

信号

  • void lastWindowClosed ()
  • void aboutToQuit ()
  • void guiThreadAwake ()

静态公有成员

  • QStyle & style ()
  • void setStyle ( QStyle * style )
  • QStyle * setStyle ( const QString & style )
  • int colorSpec ()
  • void setColorSpec ( int spec )
  • QCursor * overrideCursor ()
  • void setOverrideCursor ( const QCursor & cursor, bool replace = FALSE )
  • void restoreOverrideCursor ()
  • bool hasGlobalMouseTracking ()
  • void setGlobalMouseTracking ( bool enable )
  • QPalette palette ( const QWidget * w = 0 )
  • void setPalette ( const QPalette & palette, bool informWidgets = FALSE, const char * className = 0 )
  • QFont font ( const QWidget * w = 0 )
  • void setFont ( const QFont & font, bool informWidgets = FALSE, const char * className = 0 )
  • QFontMetrics fontMetrics ()
  • QWidgetList * allWidgets ()
  • QWidgetList * topLevelWidgets ()
  • QDesktopWidget * desktop ()
  • QWidget * activePopupWidget ()
  • QWidget * activeModalWidget ()
  • QClipboard * clipboard ()
  • QWidget * widgetAt ( int x, int y, bool child = FALSE )
  • QWidget * widgetAt ( const QPoint & pos, bool child = FALSE )
  • void exit ( int retcode = 0 )
  • bool sendEvent ( QObject * receiver, QEvent * event )
  • void postEvent ( QObject * receiver, QEvent * event )
  • void sendPostedEvents ( QObject * receiver, int event_type )
  • void sendPostedEvents ()
  • void removePostedEvents ( QObject * receiver )
  • bool startingUp ()
  • bool closingDown ()
  • void flushX ()
  • void flush ()
  • void syncX ()
  • void beep ()
  • void setWinStyleHighlightColor ( const QColor & c ) (obsolete)
  • const QColor & winStyleHighlightColor () (obsolete)
  • void setDesktopSettingsAware ( bool on )
  • bool desktopSettingsAware ()
  • void setCursorFlashTime ( int msecs )
  • int cursorFlashTime ()
  • void setDoubleClickInterval ( int ms )
  • int doubleClickInterval ()
  • void setWheelScrollLines ( int n )
  • int wheelScrollLines ()
  • void setGlobalStrut ( const QSize & strut )
  • QSize globalStrut ()
  • void setLibraryPaths ( const QStringList & paths )
  • QStringList libraryPaths ()
  • void addLibraryPath ( const QString & path )
  • void removeLibraryPath ( const QString & path )
  • void setStartDragTime ( int ms )
  • int startDragTime ()
  • void setStartDragDistance ( int l )
  • int startDragDistance ()
  • void setReverseLayout ( bool b )
  • bool reverseLayout ()
  • int horizontalAlignment ( int align )
  • bool isEffectEnabled ( Qt::UIEffect effect )
  • void setEffectEnabled ( Qt::UIEffect effect, bool enable = TRUE )
  • QWSDecoration & qwsDecoration ()
  • void qwsSetDecoration ( QWSDecoration * d )
  • WindowsVersion winVersion ()

相关函数

  • void qAddPostRoutine ( QtCleanUpFunction p )
  • const char * qVersion ()
  • bool qSysInfo ( int * wordSize, bool * bigEndian )
  • void qDebug ( const char * msg, ... )
  • void qWarning ( const char * msg, ... )
  • void qFatal ( const char * msg, ... )
  • void qSystemWarning ( const char * msg, int code )
  • void Q_ASSERT ( bool test )
  • void Q_CHECK_PTR ( void * p )
  • QtMsgHandler qInstallMsgHandler ( QtMsgHandler h )

详细描述

QApplication类管理图形用户界面应用程序的控制流和主要设置。

它包含主事件循环，在其中来自窗口系统和其它资源的所有事件被处理和调度。它也处理应用程序的初始化和结束，并且提供对话管理。它也处理绝大多数系统范围和应用程序范围的设置。

对于任何一个使用Qt的图形用户界面应用程序，都正好存在一个QApplication对象，而不论这个应用程序在同一时间内是不是有0、1、2或更多个窗口。

QApplication对象是可以通过全局变量qApp访问。它的负责的主要范围有：

  • 它使用用户的桌面设置，例如palette()、font()和doubleClickInterval()来初始化应用程序。如果用户改变全局桌面，例如通过一些控制面板，它会对这些属性保持跟踪。

  • 它执行事件处理，也就是说它从低下的窗口系统接收事件并且把它们分派给相关的窗口部件。通过使用sendEvent()和postEvent()，你可以发送你自己的事件到窗口部件。

  • 它分析命令行参数并且根据它们设置内部状态。关于这点的详细情况请参考下面的构造函数文档。

  • 它定义了由QStyle对象封装的应用程序的观感。在运行状态下，可以通过setStyle()来改变。

  • 它指定了应用程序如何分配颜色。详细情况请参考setColorSpec()。

  • 它定义了默认文本编码（请参考setDefaultCodec()）并且提供了通过translate()用户可见的本地化字符串。

  • 它提供了一些像desktop()和clipboard()这样的魔术般的对象。

  • 它知道应用程序的窗口。你可以使用widgetAt()来询问在一个确定点上存在哪个窗口部件，得到一个topLevelWidgets()（顶级窗口部件）的列表和通过closeAllWindows()来关闭所有窗口，等等。

  • 它管理应用程序的鼠标光标处理，请参考setOverrideCursor()和setGlobalMouseTracking()。

  • 在X窗口系统上，它提供刷新和同步通讯流的函数，请参考flushX()和syncX()。

  • 它提供复杂的对话管理支持。这使得当用户注销时，它可以让应用程序很好地结束，如果无法终止，撤消关闭进程并且甚至为未来的对话保留整个应用程序的状态。详细情况请参考isSessionRestored()、sessionId()、commitData()和saveState()。

应用程序排演实例包含了一个QApplication通常用法的典型完整的main()。

因为QApplication对象做了如此多的初始化，它必须在所有与用户界面相关的其它类被创建之前被创建。

因为它也处理命令行参数，在应用程序中对argv解释和修改之前创建它通常是一个好主意。（注意，也对于X11，setMainWidget()可以根据-geometry选项来改变主窗口部件。为了保持这个功能，你必须在setMainWidget()和它的任何重载之前设置你的默认。）

函数分组
系统设置 | desktopSettingsAware()、setDesktopSettingsAware()、cursorFlashTime()、setCursorFlashTime()、doubleClickInterval()、setDoubleClickInterval()、wheelScrollLines()、setWheelScrollLines()、palette()、setPalette()、font()、setFont()、fontMetrics()。
事件处理 | exec()、processEvents()、enter_loop()、exit_loop()、exit()、quit()。 sendEvent()、postEvent()、sendPostedEvents()、removePostedEvents()、hasPendingEvents()、notify()、macEventFilter()、qwsEventFilter()、x11EventFilter()、x11ProcessEvent()、winEventFilter()。
图形用户界面风格 | style()、setStyle()、polish()。
颜色使用 | colorSpec()、setColorSpec()、qwsSetCustomColors()。
文本处理 | setDefaultCodec()、installTranslator()、removeTranslator()、translate()。
窗口部件 | mainWidget()、setMainWidget()、allWidgets()、topLevelWidgets()、desktop()、activePopupWidget()、activeModalWidget()、clipboard()、focusWidget()、winFocus()、activeWindow()、widgetAt()。
高级光标处理 | hasGlobalMouseTracking()、setGlobalMouseTracking()、overrideCursor()、setOverrideCursor()、restoreOverrideCursor()。
X窗口系统同步 | flushX()、syncX()。
对话管理 | isSessionRestored()、sessionId()、commitData()、saveState()。
线程 | lock()、unlock()、locked()、tryLock()、wakeUpGuiThread()。
杂项 | closeAllWindows()、startingUp()、closingDown()、type()。

非图形用户界面程序：虽然Qt没有为写非图形用户界面程序而优化设计，不创建QApplication也可以使用它的一些类。如果你想在一个非图形用户界面服务器和一个图形用户界面客户端之间共享代码，这点很有用。

也可以参考主窗口和相关类。

成员类型文档

QApplication::ColorSpec

这个枚举变量定义了应用程序的颜色分配策略：

  • QApplication::NormalColor - 默认的颜色分配策略
  • QApplication::CustomColor - 在X11下和NormalColor一样，在Windows下根据需要为调色板分配颜色
  • QApplication::ManyColor - 使用上千种颜色的应用程序的正确选择

完整细节请参考setColorSpec()。

QApplication::Encoding

这个枚举变量为translate()定义了字符串参数的8位编码。

  • QApplication::DefaultCodec - defaultCodec()的编码（如果没有被设置就是Latin-1）
  • QApplication::UnicodeUTF8 - UTF-8

也可以参考QObject::tr()、QObject::trUtf8()和QString::fromUtf8()。

QApplication::Type

这个枚举变量定义了QApplication的类型：

  • QApplication::Tty - 控制台应用程序
  • QApplication::GuiClient - 图形用户界面客户端应用程序
  • QApplication::GuiServer - 图形用户界面服务器应用程序

成员函数文档

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

初始化窗口系统并且使用在argv中的argc个命令行参数构造一个应用程序对象。

全局指针qApp指向这个应用程序对象。应该只有一个应用程序对象被创建。

这个应用程序对象必须在任何绘制设备（包括窗口部件、像素映射、位图等等）之前被构造。

注意argc和argv也可以被改变。Qt会移除它能够识别的命令行参数。原来的argc和argv稍后可以通过qApp->argc()和qApp->argv()来访问。argv()的文档中包含如何处理命令行参数的详细描述。

Qt调试选项（如果Qt被使用被定义的QT_NO_DEBUG标记进行编译，这些选项就是不可用的）：

  • -nograb，告诉Qt永远不要捕获鼠标或者键盘。
  • -dograb （只有在X11下），在调试器下运行可能导致和-nograb冲突，使用-dograb来覆盖。
  • -sync （只有在X11下），为了调试切换为同步模式。

更详细的解释请参考调试技术。

所有的Qt程序自动支持下面这些命令行选项：

  • -style= style，设置应用程序图形用户界面风格。可能的值有motif、windows和platinum。如果你使用其它风格编译Qt或者有作为插件编译了其它风格，那么它们都可以被用作-style命令行选项。
  • -style style，这个和上面的一样。
  • -session= session，从以前的对话中重新载入应用程序。
  • -session session，这个和上面的一样。

X11版本的Qt也支持传统的X11命令行选项：

  • -display display，设置X显示（默认为$DISPLAY）。
  • -geometry geometry，设置主窗口部件的客户端位置和大小。
  • -fn或者-font font，定义应用程序的字体。这个字体必须使用X逻辑字体描述来北指定。
  • -bg或者-background color，设置默认背景色和应用程序调色板（亮的和暗的阴影将被计算出来）。
  • -fg或者-foreground color，设置默认前景色。
  • -btn或者-button color，设置默认按钮颜色。
  • -name name，设置应用程序名称。
  • -title title，设置应用程序标题。
  • -visual TrueColor，强制应用程序在8位显示上使用真彩图像。
  • -ncols count，如果应用程序使用QApplication::ManyColor颜色规格，在8位显示中限制颜色立方体重分配的颜色。如果count为216，那么一个6x6x6的颜色立方体将被使用（也就是说6级红色，6级绿色和6级蓝色），对于其它值，与2x3x1立方体成比例的立方体将被使用。
  • -cmap，导致应用程序在8位显示上安装一个私有的颜色映射。

也可以参考argc()和argv()。

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

构造一个使用argv中argc个命令行参数的应用程序对象。如果GUIenabled为真，图形用户界面应用程序被构造，否则非图形用户界面（命令行）应用程序被创建。

对于没有图形用户界面的程序，设置GUIenabled为假可以在没有窗口系统的情况下运行。

在X11下，如果GUIenabled为真，窗口系统被初始化。如果GUIenabled为假，应用程序不连接X服务器。在Windows和Macintosh，现在窗口系统总是被初始化，而不管GUIenabled的值。在Qt未来的版本这也许会改变。

对于线程配置（也就是说当Qt已经被作为线程库建立），应用程序全局互斥量在构造函数中将被锁定并且当使用exec()进入事件循环中时解锁。如果你不调用exec()，你必须明显地对这个互斥量解锁，否则你将会在应用程序退出时得到警告。

下面这个例子显示如何创建在可能情况下使用图形界面的应用程序。

  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 ) {
       //开始图形用户界面版本
       ...
    } else {
       //开始非图形用户界面版本
       ...
    }
    return app.exec();
  }

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

构造一个使用argv中argc个命令行参数的应用程序对象。

对于Qt/Embedded，在type传递QApplication::GuiServer参数将会使这个应用程序变为服务器（相当于使用-qws参数运行）。

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

创建一个应用程序，给定一个已经打开显示的dpy。如果visual和colormap非零，应用程序将使用它们作为默认的Visual和Colormap上下文。

这个只在X11上有效。

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

创建使用argv中argc个命令行参数的一个应用程序，给定一个已经打开显示的dpy。如果visual和colormap非零，应用程序将使用它们作为默认的Visual和Colormap上下文

这个只在X11上有效。

QApplication::~QApplication () [虚]

清空由这个应用程序分配的任何窗口系统资源。设置全局变量qApp为0。

void QApplication::aboutToQuit () [信号]

当应用程序要退出主事件循环时，这个信号被发射。这也许发生在应用程序中调用quit()之后，或者当用户关闭整个桌面对话时。

如果你的应用程序在清空的最后一刻要做些什么，这个信号特别重要。注意在这种状态下没有任何用户交互。

也可以参考quit()。

QWidget * QApplication::activeModalWidget () [静态]

返回激活的模式窗口部件。

模式对话框是特殊的顶级窗口部件，它是QDialog的子类，在构造函数中把模式参数设置为真。用户只有在关闭了模式窗口部件之后才能继续这个程序的其它部分。

模式窗口部件被组织在一个栈中。这个函数返回栈顶的激活窗口部件。

也可以参考activePopupWidget()和topLevelWidgets()。

QWidget * QApplication::activePopupWidget () [静态]

返回激活弹出窗口部件。

弹出窗口部件是特殊的顶级窗口部件，它设置了窗口部件标记WType_Popup，例如QPopupMenu窗口部件。当应用程序打开一个弹出窗口部件，所有的事件都被发送给弹出窗口部件。在弹出窗口部件被关闭之前，普通窗口部件和模式对话框都不能被访问。

当弹出窗口部件被显示时，只有其它弹出窗口部件可以被打开。弹出窗口部件被组织在一个栈中。这个函数返回栈顶的弹出窗口部件。

也可以参考activeModalWidget()和topLevelWidgets()。

QWidget * QApplication::activeWindow () const

返回拥有键盘输入焦点的应用程序顶级窗口，或者如果没有应用程序窗口拥有焦点，返回0。注意尽管可能没有focusWidget()，仍然有可能activeWindow()，例如如果在窗口中没有窗口部件接收键盘事件。

也可以参考QWidget::setFocus()、QWidget::focus和focusWidget()。

实例：network/mail/smtp.cpp。

void QApplication::addLibraryPath ( const QString & path ) [静态]

把path添加到库路径列表的末尾。如果path为空或者已经在路径列表中，路径列表不会被改变。默认路径列表包含一个单一的条目$QTDIR/plugins。

也可以参考removeLibraryPath()、libraryPaths()和setLibraryPaths()。

QWidgetList * QApplication::allWidgets () [静态]

返回应用程序中所有窗口部件的列表。

这个列表必须使用new来被创建并且必须被调用者删除。

如果没有窗口部件，这个列表为空（QPtrList::isEmpty()）。

注意一些窗口部件也许被隐藏。

更新所有窗口部件的实例：

    QWidgetList  *list = QApplication::allWidgets();
    QWidgetListIt it( *list );         // 遍历窗口部件
    QWidget * w;
    while ( (w=it.current()) != 0 ) {  // 对于每一个窗口部件……
        ++it;
        w->update();
    }
    delete list;                      // 删除这个列表，不是这个窗口部件

QWidgetList类在qwidgetlist.h头文件中被定义。

警告：一旦你用完了这个列表，就删除它。列表中的窗口部件也许会在任何时候被其它删除。

也可以参考topLevelWidgets()、QWidget::visible和QPtrList::isEmpty()。

int QApplication::argc () const

返回命令行参数的数量。

argv()的文档描述了如何处理命令行参数。

也可以参考argv()和QApplication::QApplication()。

实例：chart/main.cpp和scribble/scribble.cpp。

char ** QApplication::argv () const

返回命令行参数矢量。

argv()[0]是程序名称，argv()[1]是第一个参数并且argv()[argc()-1]是最后一个参数。

QApplication对象是通过从main()函数传递的argc和argv被构造的。一些参数被作为Qt选项识别并且从参数矢量中移除。例如，X11版本的Qt知道-display、-font和其它一些选项。

实例：

    // showargs.cpp - 在列表框中显示程序参数

    #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();
    }

如果你在X11下运行showargs -display unix:0 -font 9x15bold hello world，列表框中包含三个字符串“showargs”、“hello”和“world”。

也可以参考argc()和QApplication::QApplication()。

实例：chart/main.cpp和scribble/scribble.cpp。

void QApplication::beep () [静态]

使铃发声，使用默认音量和声音。

QClipboard * QApplication::clipboard () [静态]

返回应用程序全局剪贴板的指针。

实例：showimg/showimg.cpp。

void QApplication::closeAllWindows () [槽]

关闭所有顶级窗口。

这个函数对于有很多顶级窗口部件的应用程序相当有用。例如，它可以被和文件菜单中的“Quit”条目连接，正如下面的代码实例：

    // “Quit”菜单条目应该试图关闭所有窗口
    QPopupMenu* file = new QPopupMenu( this );
    file->insertItem( "&Quit", qApp, SLOT(closeAllWindows()), CTRL+Key_Q );

    // 当最后一个窗口被关闭，应用程序应该退出
    connect( qApp, SIGNAL( lastWindowClosed() ), qApp, SLOT( quit() ) );

窗口是被按随机顺序关闭的，直到一个窗口不接受关闭事件。

也可以参考QWidget::close()、QWidget::closeEvent()、lastWindowClosed()、quit()、topLevelWidgets()和QWidget::isTopLevel。

实例：action/application.cpp、application/application.cpp、helpviewer/helpwindow.cpp、mdi/application.cpp和qwerty/qwerty.cpp。

bool QApplication::closingDown () [静态]

如果应用程序对象正在被销毁，返回真，否则返回假。

也可以参考startingUp()。

int QApplication::colorSpec () [静态]

返回颜色规格。

也可以参考QApplication::setColorSpec()。

实例：showimg/showimg.cpp。

void QApplication::commitData ( QSessionManager & sm ) [虚]

这个函数处理对话管理。当QSessionManager想让应用程序提交它的所有数据时，它被调用。

通常这意味着在得到用户的许可之后保存所有打开的文件。此外你可能想提供让用户可以撤销这个关闭的选择。

注意你不应该在这个函数中退出这个应用程序。相反，对话管理器在这之后也许会，也许不会这样做，依赖上下文。

警告：在这个函数中，不能有任何用户交互，除非你请求对话管理器sm明确的允许。详细情况和使用实例请参考QSessionManager::allowsInteraction()和QSessionManager::allowsErrorInteraction()。

默认实现请求交互并且发送一个关闭事件给所有可视的顶级窗口部件。如果任何一个事件被拒绝，那么关闭被撤销。

也可以参考isSessionRestored()、sessionId()和saveState()。

int QApplication::cursorFlashTime () [静态]

返回文本关标闪烁（闪亮）的时间，以毫秒为单位。闪烁时间是显示、转化和恢复脱字符显示所使用的时间。

在X11上的默认值是1000毫秒。在Windows上，使用控制面板的值。

窗口部件不应该存储这个值，因为它可能在任何时候被用户改变全局桌面设置而改变。

也可以参考setCursorFlashTime()。

QTextCodec * QApplication::defaultCodec () const

返回默认的编解码器（请参考setDefaultCodec()）。默认返回0（没有编解码器）。

QDesktopWidget * QApplication::desktop () [静态]

返回桌面窗口部件（也调用根窗口）。

桌面窗口部件对于获得屏幕大小很有用。在桌面上绘制也是可能的。我们建议不要假设可以在桌面上绘制，因为它不能在所有的操作系统上工作。

    QDesktopWidget *d = QApplication::desktop();
    int w = d->width();     // 返回桌面宽度
    int h = d->height();    // 返回桌面高度

实例：canvas/main.cpp、desktop/desktop.cpp、helpviewer/main.cpp、i18n/main.cpp、qmag/qmag.cpp、qwerty/main.cpp和scribble/main.cpp。

bool QApplication::desktopSettingsAware () [静态]

返回由setDesktopSettingsAware()设置的值，默认返回真。

也可以参考setDesktopSettingsAware()。

int QApplication::doubleClickInterval () [静态]

返回双击的最大持续时间。

在X11上默认值为400毫秒。在Windows上，使用控制面板的值。

也可以参考setDoubleClickInterval()。

int QApplication::enter_loop ()

这个函数进入主事件循环（递归地）。除非你真的直到你正在做什么，否则请不要调用它。

也可以参考exit_loop()和loopLevel()。

int QApplication::exec ()

进入主事件循环并且等待，直到exit()被调用或者主窗口部件被销毁，并且返回值被设置为exit()（如果通过quit()，exit()被调用，为0）。

需要调用这个函数来开始事件处理。主事件循环从窗口系统中接收事件并且把它们分派给应用程序窗口部件。

通常来说，在调用exec()之前，没有用户交互可以发生。作为一个特例，像QMessageBox这样的模式对话框可以在调用exec()之前使用，因为模式对话框调用exec()来开始本地事件循环。

为了使你的应用程序执行空闲处理，例如，只要没有未处理地事件，执行一个特殊的函数，使用QTimer，0超时。更高级的空闲处理方案可以使用processEvents()来完成。

也可以参考quit()、exit()、processEvents()和setMainWidget()。

实例：biff/main.cpp、chart/main.cpp、fonts/simple-qfont-demo/simple-qfont-demo.cpp、life/main.cpp、t1/main.cpp、t4/main.cpp和xml/outliner/main.cpp。

void QApplication::exit ( int retcode = 0 ) [静态]

告诉应用程序退出，伴随一个返回代码。

在这个函数被调用之后，应用程序离开主事件循环并且从exec()调用之后返回。exec()函数返回retcode。

根据习惯，为0的retcode意味着成功，并且任何非零的值意味着错误。

注意与同名的C库函数不同，这个函数返回到调用者——它的事件处理结束。

也可以参考quit()和exec()。

实例：chart/chartform.cpp和picture/picture.cpp。

void QApplication::exit_loop ()

这个函数从到主事件循环的递归调用中退出。不要调用它，除非你是一个专家。

也可以参考enter_loop()和loopLevel()。

void QApplication::flush () [静态]

刷新窗口系统指定事件队列。

如果在异步的窗口系统，例如X11，或者双缓存的窗口系统，例如Mac OS X的不返回事件循环的循环中正在做图形变化，并且你想立即显现这些变化（比如，Splash Screen），请调用这个函数。

也可以参考flushX()、sendPostedEvents()和QPainter::flush()。

void QApplication::flushX () [静态]

在X11实现中刷新X事件队列。这通常会立即返回。在其它平台上不会做任何事。

也可以参考syncX()。

实例：xform/xform.cpp。

QWidget * QApplication::focusWidget () const

返回拥有键盘输入焦点的应用程序窗口部件，或者在这个应用程序中没有窗口部件拥有焦点，返回0。

也可以参考QWidget::setFocus()、QWidget::focus和activeWindow()。

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

返回窗口部件w的默认字体，或者如果w为0，返回默认应用程序字体。

也可以参考setFont()、fontMetrics()和QWidget::font。

实例：qfd/fontdisplayer.cpp、themes/metal.cpp和themes/themes.cpp。

QFontMetrics QApplication::fontMetrics () [静态]

返回应用程序字体的显示（屏幕）字体规格。

也可以参考font()、setFont()、QWidget::fontMetrics()和QPainter::fontMetrics()。

QSize QApplication::globalStrut () [静态]

返回应用程序的全局strut。

strut是任何用户可以交互的图形交互界面元素的最小维数的大小对象。例如，没有按钮应该被重新定义大小小于全局strut大小。

也可以参考setGlobalStrut()。

void QApplication::guiThreadAwake () [信号]

当图形用户界面线程要处理一个事件循环的周期，这个信号被发射。

也可以参考wakeUpGuiThread()。

bool QApplication::hasGlobalMouseTracking () [静态]

如果全局鼠标跟踪生效，返回真，否则返回假。

也可以参考setGlobalMouseTracking()。

bool QApplication::hasPendingEvents ()

如果有未处理的事件，这个函数返回真，否则返回假。未处理的事件可以是来自于窗口系统，也可以是使用QApplication::postEvent()发送的事件。

int QApplication::horizontalAlignment ( int align ) [静态]

去掉垂直对齐标记并且根据使用的语言把AlignAuto的对齐方式align转换为AlignLeft或者AlignRight。其它水平对齐标记不被改变而留下。

void QApplication::installTranslator ( QTranslator * mf )

添加消息文件mf到翻译所用的消息文件列表。

可以安装多种消息文件。翻译会在最后安装的消息文件中搜索，然后是紧接着最后的，并且继续，一直到最先安装的。一旦找到匹配的翻译，搜索就停止。

也可以参考removeTranslator()、translate()和QTranslator::load()。

实例：i18n/main.cpp。

bool QApplication::isEffectEnabled ( Qt::UIEffect effect ) [静态]

如果effect生效，返回真，否则返回假。

默认，Qt将视图使用桌面设置。调用setDesktopSettingsAware(FALSE)可以防止这一点。

也可以参考setEffectEnabled()和Qt::UIEffect。

bool QApplication::isSessionRestored () const

如果应用程序已经从以前的对方中恢复，返回真，否则返回假。

也可以参考sessionId()、commitData()和saveState()。

void QApplication::lastWindowClosed () [信号]

当用户关闭最后一个顶级窗口时，这个信号被发射。

当你的应用程序有很多顶级窗口部件，而没有主窗口部件时，这个信号很有用。你可以把它和quit()槽连接起来。

为了方便，对于短暂的顶级窗口部件，例如弹出菜单和对话框，这个信号不被发射。

也可以参考mainWidget()、topLevelWidgets()、QWidget::isTopLevel和QWidget::close()。

实例：action/main.cpp、addressbook/main.cpp、chart/main.cpp、helpviewer/main.cpp、qwerty/main.cpp和showimg/main.cpp。

QStringList QApplication::libraryPaths () [静态]

返回当动态载入库的时候，应用程序将搜索的路径列表。如果没有路径被设置，$QTDIR/plugins将作为唯一的条目被返回。

如果你想遍历这个列表，你应该遍历一个复制，例如：

    QStringList list = app.libraryPaths();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

关于如何使用库路径的详细情况请参考插件文档。

也可以参考setLibraryPaths()、addLibraryPath()、removeLibraryPath()和QLibrary。

void QApplication::lock ()

锁住Qt库互斥量。如果另外一个线程已经锁住这个互斥量，那么这个调用线程将会阻塞，直到其它线程对这个互斥量解锁。

也可以参考unlock()、locked()和Qt中的线程支持。

bool QApplication::locked ()

如果Qt库互斥量被不同的线程锁住，返回真，否则返回假。

警告：由于在被支持的平台上，递归互斥量的实现不同，在以前锁住互斥量的同一个线程中调用这个函数将会给出不确定的结果。

也可以参考lock()、unlock()和Qt中的线程支持。

int QApplication::loopLevel () const

返回当前循环水平。

也可以参考enter_loop()和exit_loop()。

bool QApplication::macEventFilter ( EventRef ) [虚]

这个虚函数只在Macintosh下被实现。

如果你创建一个继承QApplication并且重新实现这个函数的应用程序，你可以直接访问从Mac OS接收的所有Carbon事件。

如果你想停止正在处理的事件，返回真。对于普通事件分派，返回假。

QWidget * QApplication::mainWidget () const

返回主应用程序窗口部件，如果没有主窗口部件，返回0。

也可以参考setMainWidget()。

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

把事件e发送给receiver：receiver->event(e)。返回接收者的事件处理器返回值。

对于确定类型的事件（例如鼠标和键盘事件），如果接收者对这个事件没有兴趣（也就是说它返回假），事件将被传播给接收者的父对象一直到顶级对象。

这里有事件被处理的五种不同方法，重新实现这个函数是其中的一个。所有这五种途径如下：

  1. 重新实现这个函数。这是一个非常强大，提供了完整控制，但只能是qApp的子类。

  2. 在qApp上安装事件过滤器。这样的事件过滤器可以为所有窗口部件处理所有的事件，所以它和重新实现notify()一样强大；此外，可以有超过一个的应用程序全局事件过滤器。全局事件过滤器甚至可以看到失效的窗口部件的鼠标事件，并且如果全局鼠标跟踪生效，它可以见到所有窗口部件的鼠标移动事件。

  3. 重新实现QObject::event()（就像QWidget做的那样）。如果你这样做来得到Tab键按下，并且你会在任何窗口部件特定的事件过滤器之前看到这个事件。

  4. 在一个对象中安装事件过滤器。这样的事件过滤器可以得到除了Tab和Shift-Tab键按下之外的所有事件。

  5. 重新实现paintEvent()、mousePressEvent()和其它。这是最普通、最容易并且最不强大的方式。

也可以参考QObject::event()和installEventFilter()。

QCursor * QApplication::overrideCursor () [静态]

返回激活的应用程序强制光标。

如果没有应用程序关标被指定（也就是说内部光标栈为空），这个函数返回0。

也可以参考setOverrideCursor()和restoreOverrideCursor()。

QPalette QApplication::palette ( const QWidget * w = 0 ) [静态]

返回默认应用程序调色板的指针。这个一直是应用程序的调色板，也就是说返回的指针被保证为非零。

如果被传递的窗口部件w，返回这个窗口部件的默认调色板。这个可能是，也可能不是应用程序调色板。在绝大多数情况下，普通类型的窗口部件没有特殊调色板，但是一个需要注意的例外是在Windows下的弹出菜单，如果用户在显示设置中为菜单定义了特定背景色。

也可以参考setPalette()和QWidget::palette。

实例：desktop/desktop.cpp、themes/metal.cpp和themes/wood.cpp。

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

在窗口部件w被显示之前，初始化它的外观。

通常当窗口部件被抛光时，它们会自动调用这个函数。它也可以被用来做窗口部件的基于风格的主要定制。

注意你不会被QWidget的公有函数限制。相反，基于像QObject::className()这些元信息，你可以对任何种类的窗口部件进行定制。

也可以参考QStyle::polish()、QWidget::polish()、setPalette()和setFont()。

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

把事件event添加为对象receiver的接收对象，把它添加到事件队列中并且立即返回。

这个时间必须在堆中被分配，因为递送事件队列将会得到事件的所有权并且一旦它被递送就删除它。

当控制返回主事件循环，存储在队列中的所有事件将被使用notify()函数发送。

也可以参考sendEvent()、QThread::postEvent()和notify()。

void QApplication::processEvents ()

处理未处理的事件，在3秒内或者直到没有没有更多的事件要处理，看哪一个更短。

偶尔当你的程序很忙来处理一个长期操作（例如，复制文件），你可以调用这个函数。

也可以参考exec()和QTimer。

实例：fileiconview/qfileiconview.cpp。

void QApplication::processEvents ( int maxtime )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

处理未处理的事件，在maxtime毫秒内或者直到没有没有更多的事件要处理，看哪一个更短。

偶尔当你的程序很忙来处理一个长期操作（例如，复制文件），你可以调用这个函数。

也可以参考exec()和QTimer。

void QApplication::processOneEvent ()

等待一个事件的发生，处理它，然后返回。

这个函数对于使Qt能够适应事件处理必须移植到已经存在的程序循环中很有用处。

在新的应用程序中使用这个函数可能意味着设计的问题。

也可以参考processEvents()、exec()和QTimer。

void QApplication::quit () [槽]

告诉应用程序退出，并且返回代码为0（成功）。相当于调用QApplication::exit( 0 )。

把lastWindowClosed()信号和quit()连接起来是很普通的，并且你也可以经常把比如QButton::clicked()或者QAction、QPopupMenu或QMenuBar中的信号和它连接起来。

实例：

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

也可以参考exit()、aboutToQuit()、lastWindowClosed()和QAction。

实例：addressbook/main.cpp、helpviewer/main.cpp、qwerty/main.cpp、showimg/main.cpp、t2/main.cpp、t4/main.cpp和t6/main.cpp。

QWSDecoration & QApplication::qwsDecoration () [静态]

返回装饰窗口所使用的QWSDecoration。

这个方法是不可移植的。它只在Qt/Embedded中有效。

也可以参考QWSDecoration。

bool QApplication::qwsEventFilter ( QWSEvent * ) [虚]

这个虚函数只在Qt/Embedded下实现。

如果你创建一个继承QApplication并且重新实现这个函数的一个应用程序，你可以直接处理从QWS（Q窗口系统）进程接收的说有QWS事件。

如果你想停止要处理的事件，返回真。对于普通事件分派，返回假。

void QApplication::qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )

设置Qt/Embedded定制颜色表。

Qt/Embedded在8位显示时分配一个标准的216颜色立方体。它保留了40个颜色可以用来在任何客户端连接之前由QWS主进程设置一个自定义颜色表。

colorTable是任何最多为40的自定义颜色数组。start是开始索引（0－39），并且numColors是要设置的颜色数量（1－40）。

这个方法是不可移植的。它只在Qt/Embedded有效。

void QApplication::qwsSetDecoration ( QWSDecoration * d ) [静态]

设置用来装饰Qt/Embedded窗口的QWSDecoration的继承类为d。

这个方法是不可移植的。它只在Qt/Embedded有效。

也可以参考QWSDecoration。

void QApplication::removeLibraryPath ( const QString & path ) [静态]

从库路径列表中移除path。如果path为空或者它不在列表中，列表不被改变。

也可以参考addLibraryPath()、libraryPaths()和setLibraryPaths()。

void QApplication::removePostedEvents ( QObject * receiver ) [静态]

移除所有使用postEvent()递送给receiver的事件。

这些事件不被分派，相反它们会从队列中被移除。你应该永远不需要调用这个函数。如果你调用了，要直到杀掉事件可能导致receiver破坏一个或多个变量。

void QApplication::removeTranslator ( QTranslator * mf )

从这个应用程序所使用的消息文件的列表中移除消息文件mf。（它不会从文件系统中删除这个消息文件。）

也可以参考installTranslator()、translate()和QObject::tr()。

实例：i18n/main.cpp。

void QApplication::restoreOverrideCursor () [静态]

撤销最近一次的setOverrideCursor()。

如果setOverrideCursor()已经被调用两次，调用restoreOverrideCursor()会激活第一个光标设置。第二次调用这个函数会恢复初始窗口部件的光标。

也可以参考setOverrideCursor()和overrideCursor()。

实例：showimg/showimg.cpp。

bool QApplication::reverseLayout () [静态]

如果所有的对话框和窗口部件都将会被按镜像的方式被放置（从右到左），返回真。如果是按从左到右的方式，返回假。

也可以参考setReverseLayout()。

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

这个函数处理对话管理。当对话管理器想让应用程序为未来的对话保存它的状态时，它被调用。

例如，文本编辑器将会创建一个包含编辑缓存的当前内容的临时文件，光标的位置和当前编辑对话的其它特征。

注意你不应该在这个函数中退出这个应用程序。相反，对话管理器在这之后也许会，也许不会这样做，依赖上下文。此外，绝大多数对话管理器将会在应用程序已经被开始之后立即请求一个状态保存。这允许对话管理器来知道应用程序的重启策略。

警告：在这个函数中，不能有任何用户交互，除非你请求对话管理器sm明确的允许。详细情况和使用实例请参考QSessionManager::allowsInteraction()和QSessionManager::allowsErrorInteraction()。

也可以参考isSessionRestored()、sessionId()和commitData()。

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

使用notify()函数直接发送事件event给接受者receiver。返回由事件处理器返回的值。

这个事件在它被发送时，不能被删除。通常的访问方式是在栈中创建这个事件，例如：

    QMouseEvent me( QEvent::MouseButtonPress, pos, 0, 0 );
    QApplication::sendEvent( mainWindow, &me );
如果你在堆中创建这个事件，你就必须删除它。

也可以参考postEvent()和notify()。

实例：popup/popup.cpp。

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

立即分派由QApplication::postEvent()以前已经排队的并且是发给对象receiver，事件类型是event_type的所有事件。

注意来自窗口系统的事件不能被这个函数分派，但是可以用processEvents()。

void QApplication::sendPostedEvents () [静态]

分派所有递送事件，也就是清空事件队列。这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

QString QApplication::sessionId () const

返回当前对话的标识符。

如果应用程序已经从一个较早的对话中恢复，这个标识符就和那个先前的对话一样。

对话标识符已经被保证对于不同的应用程序和同一个应用程序的不同实例都是唯一的。

也可以参考isSessionRestored()、commitData()和saveState()。

void QApplication::setColorSpec ( int spec ) [静态]

设置应用程序的颜色策略为spec。

颜色策略控制着当在一个显示颜色总数有限制的情况下运行应用程序如何分配颜色，例如8位/256色显示。

颜色策略必须在你创建QApplication对象之前设置。

选项有：

  • QApplication::NormalColor。这是默认颜色分配策略。如果你的应用程序使用按钮、菜单、文本和少量颜色的像素映射，请使用这个选项。在这个选项中，应用程序使用系统全局颜色。这对于X11下的绝大多数应用程序都工作得很好，但是在Windows机器上，它也许会导致非标准颜色的抖动。
  • QApplication::CustomColor。如果你的应用程序需要少量的自定义颜色，请使用这个选项。在X11下，这个选项和NormalColor一样。在Windows下，Qt创建一个Windows调色板并且在根据需要在上面分配颜色。
  • QApplication::ManyColor。如果你的应用程序使用非常大量的颜色（例如，它需要几千种颜色），请使用这个选项。在X11下，效果是：
    • 对于最多256色真彩色视的256色显示，默认视被显示，并且颜色被分配到一个颜色立方体重。颜色立方体是6*6*6（216色）“网页调色板”*，但是颜色的数量可以通过-ncols选项改变。用户可以通过-visual选项强制应用程序使用真彩色视。
    • 对于超过256色的真彩色视的256色显示，就是用这个视。例如，Silicon Graphics的X服务器具有这个特征。它们提供8位视作为默认，但是可以当请求的时候可以递送真彩色。
    在Windows下，Qt创建一个Windows调色板并且用一个颜色立方体填充它。

要知道CustomColor和ManyColor选择也许会导致颜色映射闪烁：当背景窗口将看起来不够吸引人的时候，前景应用程序得到（绝大多数）可用的颜色。

实例：

  int main( int argc, char **argv )
  {
      QApplication::setColorSpec( QApplication::ManyColor );
      QApplication a( argc, argv );
      ...
  }

QColor提供对于控制颜色分配合释放某一种颜色的更多功能。详细信息请参考QColor::enterAllocContext()。

为了检查你以什么模式结束，当QApplication对象存在的时候，调用QColor::numBitPlanes()。一个大于8的值（通常是16、24或32）意味着真彩色。

* 0x00, 0x33, 0x66, 0x99, 0xCC, or 0xFF. * Qt使用的颜色立方体有216色，它的红、绿和蓝组成部分总是下面的值之一：0x00、0x33、0x66、0x99、0xCC或0xFF。

也可以参考colorSpec()、QColor::numBitPlanes()和QColor::enterAllocContext()。

实例：helpviewer/main.cpp、showimg/main.cpp、t9/main.cpp、tetrix/tetrix.cpp和themes/main.cpp。

void QApplication::setCursorFlashTime ( int msecs ) [静态]

设置文本光标闪烁（闪亮）时间为msecs毫秒。闪烁时间是显示、转化和恢复脱字符显示所使用的时间。通常文本光标是显示msecs/2毫秒，然后隐藏msecs/2毫秒，但是这可能会变化。

注意在Microsoft Windows上，调用这个函数会设置所有窗口的光标闪烁时间。

也可以参考cursorFlashTime()。

void QApplication::setDefaultCodec ( QTextCodec * codec )

设置应用程序的默认编解码器为codec。

如果程序中的文字引用文本不是Latin1编码，这个函数可以用来设置合适的编码。例如，韩国程序员开发的软件在程序中对所有文本可以使用eucKR，这种情况下，main()函数可能看起来像这样：

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

注意，这不是用户来选择编码的方式。例如，把一个包含英语字符串的应用程序转换为韩语，所需要做的一切就是对于所有的英语字符串通过tr()传递并且载入翻译文件。有关国际化的详细情况，请参考Qt国际化文档。

注意也有一些Qt内置类为不同的字符串调用tr()。这些字符串使用英语，所以对于完整的翻译，编解码器将被这些字符串需要。

void QApplication::setDesktopSettingsAware ( bool on ) [静态]

默认情况下，Qt将试图使用底下的窗口系统的桌面设置中当前标准颜色、字体等等并且对于所有相关窗口部件使用它们。这种行为可以通过把on设置为假，调用这个函数来关闭。

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

  int main( int argc, char** argv ) {
    QApplication::setDesktopSettingsAware( FALSE ); // 我知道什么比用户的更好
    QApplication myApp( argc, argv ); // 使用默认字体&颜色
    ...
  }

也可以参考desktopSettingsAware()。

void QApplication::setDoubleClickInterval ( int ms ) [静态]

设置区别一个双击和两次单击的时间限度为ms毫秒。

注意在Microsoft Windows上，调用这个函数会设置所有窗口的双击间隔。

也可以参考doubleClickInterval()。

void QApplication::setEffectEnabled ( Qt::UIEffect effect, bool enable = TRUE ) [静态]

如果enable为真，使用户界面效果effect生效，否则这个效果将不被使用。

也可以参考isEffectEnabled()、Qt::UIEffect和setDesktopSettingsAware()。

void QApplication::setFont ( const QFont & font, bool informWidgets = FALSE, const char * className = 0 ) [静态]

改变应用程序默认字体为font。如果informWidgets为真，那么存在的窗口部件将会被通知有关这个变化并且也许会根据新的应用程序设置来调整它们自己。如果informWidgets为假，改变只对新创建的窗口部件生效。如果className被传递，那么改变只对继承className的类适用（由QObject::inherits()报告的）。

当应用程序启动时，默认字体依赖于窗口系统。它非常依赖于窗口系统的版本和本地设置。这个函数让我们不顾默认字体，但是这种不顾也许是一个坏主意，因为，例如，一些本地设置需要支持它的一些特殊字符需要特大字体。

也可以参考font()、fontMetrics()和QWidget::font。

实例：desktop/desktop.cpp、qfd/qfd.cpp、showimg/main.cpp、themes/metal.cpp和themes/themes.cpp。

void QApplication::setGlobalMouseTracking ( bool enable ) [静态]

如果enable为真，使全局鼠标跟踪生效，或者如果enable为假，使它失效。

使全局鼠标跟踪生效将使窗口部件时间过滤器或者应用程序事件过滤器能够获得所有的鼠标移动事件，尽管当没有按键被按下的时候。这对于特殊图形用户界面元件，比如工具提示，是很有用的。

全局鼠标跟踪不会影响窗口部件和它们的mouseMoveEvent()。对于一个要在按键不被按下时得到鼠标移动事件的窗口部件，它必须做QWidget::setMouseTracking(TRUE)。

这个函数使用内部计数器。每一个setGlobalMouseTracking(TRUE)都必须有一个相对应的setGlobalMouseTracking(FALSE)：

        // 在这点，全局鼠标跟踪是关闭的
        QApplication::setGlobalMouseTracking( TRUE );
        QApplication::setGlobalMouseTracking( TRUE );
        QApplication::setGlobalMouseTracking( FALSE );
        // 在这点，它仍然是打开的
        QApplication::setGlobalMouseTracking( FALSE );
        // 但是现在它是关的

也可以参考hasGlobalMouseTracking()和QWidget::mouseTracking。

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

设置应用程序全局strut为strut。

strut是任何用户可以交互的图形交互界面元素的最小维数的大小对象。例如，没有按钮应该被重新定义大小小于全局strut大小。

当重新实现用于在触摸屏或者类似输入输出设备的图形用户界面控制时，strut的大小应该被考虑。

实例：

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

也可以参考globalStrut()。

void QApplication::setLibraryPaths ( const QStringList & paths ) [静态]

设置当载入库的时候搜索的目录列表为paths。如果paths为空，搜索列表不会被改变，否则所有的存在的路径将被删除并且路径列表将由paths中给定的路径组成。

也可以参考libraryPaths()、addLibraryPath()、removeLibraryPath()和QLibrary。

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

设置应用程序的主窗口部件为mainWidget。

主窗口部件的绝大部分责任和任何其它窗口部件一样，除了如果它被删除，应用程序就退出。

你也可以不需要主窗口部件，把lastWindowClosed()连接到quit()是一个替换方法。

对于X11，这个函数也可以根据-geometry命令行参数来移动和改变主窗口部件的大小，所以你应该在调用setMainWidget()之前设置默认几何形状（使用QWidget::setGeometry()）。

也可以参考mainWidget()、exec()和quit()。

实例：canvas/main.cpp、chart/main.cpp、fonts/simple-qfont-demo/simple-qfont-demo.cpp、life/main.cpp、t1/main.cpp、t4/main.cpp和xml/outliner/main.cpp。

void QApplication::setOverrideCursor ( const QCursor & cursor, bool replace = FALSE ) [静态]

设置应用程序强制光标为cursor。

应用程序强制光标是为了显示应用程序是在特定状态下，例如在一个操作期间也许会占用一些时间。

这个光标将在所有应用程序的窗口部件中被显示，直到restoreOverrideCursor()或者另一个setOverrideCursor()被调用。

应用程序光标被存储到内部栈中。setOverrideCursor()把光标压到栈中，并且restoreOverrideCursor()把激活的光标从栈中弹出。每一个setOverrideCursor()都必须最后有一个对应的restoreOverrideCursor()跟着，否则栈将永远不会被清空。

如果replace为真，新的光标将替换最近一个强制光标（栈将保持它的深度）。如果replace为假，新的光标将被要到栈顶。

实例：

        QApplication::setOverrideCursor( Qt::WaitCursor );
        calculateHugeMandelbrot();              // 消耗时间……
        QApplication::restoreOverrideCursor();

也可以参考overrideCursor()、restoreOverrideCursor()和QWidget::cursor。

实例：showimg/showimg.cpp。

void QApplication::setPalette ( const QPalette & palette, bool informWidgets = FALSE, const char * className = 0 ) [静态]

改变应用程序默认调色板为palette。如果informWidgets为真，那么存在的窗口部件将会被通知有关这个变化并且也许会根据新的应用程序设置来调整它们自己。如果informWidgets为假，改变只对新创建的窗口部件生效。

如果className被传递，那么改变只对继承className的类适用（由QObject::inherits()报告的）。如果className为0，变化将影响所有窗口部件，这样会强制覆盖以前任何类的特定调色板。

这个调色板会根据QStyle::polish()中当前的图形用户界面风格而被改变。

也可以参考QWidget::palette、palette()和QStyle::polish()。

实例：i18n/main.cpp、themes/metal.cpp、themes/themes.cpp和themes/wood.cpp。

void QApplication::setReverseLayout ( bool b ) [静态]

如果b为真，所有的对话框和窗口部件可以按镜像方式布置，这是阿拉伯语和希伯来语等从右到左的语言需要的。如果b为假，对话框和窗口部件被按从左到右布置。

也可以参考reverseLayout()。

void QApplication::setStartDragDistance ( int l ) [静态]

设置拖动开始之后的距离为l像素。

也可以参考startDragDistance()。

void QApplication::setStartDragTime ( int ms ) [静态]

设置拖动开始之后的时间为ms毫秒。

也可以参考startDragTime()。

void QApplication::setStyle ( QStyle * style ) [静态]

设置应用程序的图形用户界面风格为style。风格对象的所有权被移交给QApplication，所以当应用程序退出时或者当新的风格被设置时QApplication会删除这个风格对象。

用法实例：

    QApplication::setStyle( new QWindowStyle );

当切换应用程序风格时，颜色调色板被设置回初始颜色或者系统默认。这是因为某一种风格不得不让颜色调色板完全适应风格的指导的需要。

也可以参考style()、QStyle、setPalette()和desktopSettingsAware()。

实例：themes/themes.cpp。

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

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用QStyleFactory来为style创建一个QStyle对象。

这个字符串必须是QStyleFactory::keys()之一，通常是“windows”、“motif”、“cde”、“motifplus”、“platinum”、“sgi”和“compact”。根据平台，“windowsxp”、“aqua”或“macintosh”也是可以用的。

如果一个未知的style被传递，返回0。

void QApplication::setWheelScrollLines ( int n ) [静态]

设置当鼠标滚轮旋转时滚动的行数为n。

如果这个数字超过某一个窗口部件中可视的行数，窗口部件应该把这个滚动操作解释为单一的上/下翻页的操作来替代。

也可以参考wheelScrollLines()。

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

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

在窗口风格中，为了应用程序中的所有窗口部件，设置颜色用来遮蔽选择。如果这个颜色被改变了，所有的窗口部件都将被重新绘制。

默认颜色是darkBlue。

也可以参考winStyleHighlightColor()。

int QApplication::startDragDistance () [静态]

如果你在你的应用程序中支持拖放并且一个拖动应该在一个鼠标点击并且移动鼠标一定距离之后才开始，你应该使用这个方法返回的值作为那个距离。

例如，如果鼠标点击的位置被存储在startPos并且当前位置（例如，在鼠标移动事件中）是currPos，你可以发现拖动是否开始的代码如下：

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

Qt内部使用这个值，例如在QFileDialog中。

这个值默认是4像素。

也可以参考setStartDragDistance()、startDragTime()和QPoint::manhattanLength()。

int QApplication::startDragTime () [静态]

如果你在你的应用程序中支持拖放并且一个拖动应该在一个鼠标点击并且经过一段时间之后才开始，你应该使用这个方法返回的值作为那个拖延（以毫秒为单位）。

Qt也是在内部使用这个拖延，例如在QTextView和QLineEdit中来开始一个拖动。

默认值是500毫秒。

也可以参考setStartDragTime()和startDragDistance()。

bool QApplication::startingUp () [静态]

如果应用程序对象还没有被创建，返回真，否则返回假。

也可以参考closingDown()。

QStyle & QApplication::style () [静态]

返回应用程序的风格对象。

也可以参考setStyle()和QStyle。

void QApplication::syncX () [静态]

在X11中实现与X服务器的同步。这通常会占用一些时间。在其它平台上不做任何事。

也可以参考flushX()。

QWidgetList * QApplication::topLevelWidgets () [静态]

返回应用程序中顶级窗口部件的列表。

这个列表是使用new创建的并且必须由调用者删除。

如果没有顶级窗口部件，这个列表是空的（QPtrList::isEmpty()）。

注意一些顶级窗口部件也许被隐藏了，例如如果当前没有工具提示被显示的工具提示。

实例：

    // 显示所有隐藏的顶级窗口部件。
    QWidgetList  *list = QApplication::topLevelWidgets();
    QWidgetListIt it( *list );  // 遍历窗口部件
    QWidget * w;
    while ( (w=it.current()) != 0 ) {   // 对每一个顶级窗口部件
        ++it;
        if ( !w->isVisible() )
            w->show();
    }
    delete list;                // 删除这个列表，而不是窗口部件

警告： 只要你用完了这个列表，就删除它。列表中的窗口部件也许会在任何时候被其他人删除。

也可以参考allWidgets()、QWidget::isTopLevel、QWidget::visible和QPtrList::isEmpty()。

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

通过查询安装的消息文件，返回sourceText的翻译文本。消息文件被搜索的顺序是从最近安装的开始到最先安装的。

QObject::tr()和QObject::trUtf8()提供了更方便的这种功能。

context通常是一个类名（例如，“MyDialog”）并且sourceText是英语文本或者一个短的标识文本，如果输出文本很长（就像帮助文本那样的）。

comment是消除歧义的注释，当相同的sourceText在同样的上下文情况下被用在不同的规则中。默认情况下，它是零。encoding表明字符串的8位编码方式。

关于上下文和注释的更多信息请参考QTranslator文档。

如果消息文件中没有包含context中sourceText的翻译，这个函数返回一个和sourceText相等的QString。sourceText的编码方式由encoding指定，它默认为DefaultCodec。

这个函数不是虚的。你可以使用继承QTranslator这样的替代翻译技术。

也可以参考QObject::tr()、installTranslator()和defaultCodec()。

bool QApplication::tryLock ()

试图锁定Qt库互斥量，并且立即返回。如果锁已经被获得，这个函数返回真。如果另外一个线程已经锁定了这个互斥量，这个函数返回假，而不是等待这个互斥量什么时候可用。

在另外一个线程能够成功地锁定它之前，这个互斥量必须使用unlock()解锁。

也可以参考lock()、unlock()和Qt中的线程支持。

Type QApplication::type () const

返回应用程序的类型，Tty、GuiClient或GuiServer。

void QApplication::unlock ( bool wakeUpGui = TRUE )

对Qt库互斥量解锁。如果wakeUpGui为真（默认），那么图形用户界面线程将被QApplication::wakeUpGuiThread()唤醒。

也可以参考lock()、locked()和Qt中的线程支持。

void QApplication::wakeUpGuiThread ()

唤醒图形用户界面线程。

也可以参考guiThreadAwake()和Qt中的线程支持。

int QApplication::wheelScrollLines () [静态]

返回当鼠标滚轮被旋转时，滚动的行数。

也可以参考setWheelScrollLines()。

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

返回在全局屏幕位置(x, y)处的窗口部件的指针，或者如果没有Qt窗口部件在那里返回0。

如果child为假并且在位置(x, y)处有一个子窗口部件，包含它的顶级窗口部件将被返回。如果child为真，则在位置(x, y)处的子窗口部件被返回。

这个函数通常是相当慢的。

也可以参考QCursor::pos()、QWidget::grabMouse()和QWidget::grabKeyboard()。

QWidget * QApplication::widgetAt ( const QPoint & pos, bool child = FALSE ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 返回在全局屏幕位置pos处的窗口部件的指针，或者如果没有Qt窗口部件在那里返回0。

如果child为假并且在位置pos处有一个子窗口部件，包含它的顶级窗口部件将被返回。如果child为真，则在位置pos处的子窗口部件被返回。

bool QApplication::winEventFilter ( MSG * ) [虚]

消息程序在每次接受到消息时调用这个函数。如果你想处理Qt不处理的窗口消息msg，请重新实现这个函数。

void QApplication::winFocus ( QWidget * widget, bool gotFocus )

如果gotFocus为真，widget将变为激活窗口。否则这个激活窗口将被重新设置为NULL。

const QColor & QApplication::winStyleHighlightColor () [静态]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

返回在窗口风格中用来遮蔽选择的颜色。

也可以参考setWinStyleHighlightColor()。

WindowsVersion QApplication::winVersion () [静态]

返回当前运行的Windows操作系统的版本：

  • Qt::WV_95 - Windows 95
  • Qt::WV_98 - Windows 98
  • Qt::WV_Me - Windows Me
  • Qt::WV_NT - Windows NT 4.x
  • Qt::WV_2000 - Windows 2000 （NT5）
  • Qt::WV_XP - Windows XP

注意这个函数只对Qt的Windows版本实现了。

bool QApplication::x11EventFilter ( XEvent * ) [虚]

这个虚函数只在X11下实现了。

如果你创建一个继承QApplication的应用程序并且重新实现这个函数，你可以直接访问从X服务器接收的所有X事件。

如果你想停止正在处理的事件，返回真，否则对于普通事件分派返回假。

也可以参考x11ProcessEvent()。

int QApplication::x11ProcessEvent ( XEvent * event )

这个函数做不同的Xevent的核心处理，通常把Qt事件分派到正确的目的地。

如果这个时间被特殊处理消耗，返回1，如果event被普通处理消耗，返回0，并且如果event是针对不可识别的窗口部件，返回-1。

也可以参考x11EventFilter()。

相关函数

void Q_ASSERT ( bool test )

如果test为假，打印一个包含源代码文件名和行号的警告信息。

这是一个qglobal.h中定义的宏。

Q_ASSERT对于在你的程序中测试所需条件是很有用的。

实例：

    //
    // File: div.cpp
    //

    #include <qglobal.h>

    int divide( int a, int b )
    {
        Q_ASSERT( b != 0 );                     // 这是第9行
        return a/b;
    }

如果b为0，Q_ASSERT语句将会使用qWarning()函数输出下面的消息：

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

也可以参考qWarning()和调试。

void Q_CHECK_PTR ( void * p )

如果p为零，一个致命的消息说程序用完了内存并且退出。如果p为非零，什么也不发生。

这是一个qglobal.h中定义的宏。

实例：

    int *a;
    Q_CHECK_PTR( a = new int[80] );     // 不要这样做！
      // 应该这样做：
    a = new int[80];
    Q_CHECK_PTR( a );                   // 这是正确的

也可以参考qFatal()和调试。

void qAddPostRoutine ( QtCleanUpFunction p )

添加一个将被QApplication析构函数中调用的全局日常事务。这个函数通常用来添加在整个程序范围的功能的清理的日常事务。

这个由p给定的函数不应该有任何参数并且什么也不返回，就像这样：

    static int *global_ptr = 0;

    static void cleanup_ptr()
    {
        delete [] global_ptr;
        global_ptr = 0;
    }

    void init_ptr()
    {
        global_ptr = new int[100];      // 分配数据
        qAddPostRoutine( cleanup_ptr ); // 稍后删除
    }

注意对于一个应用程序范围或者模块范围的清理，qAddPostRoutine()通常是不适合的。人们倾向于使用动态模块加载，并且在例如QApplication析构函数被调用的很早之前就卸载那些模块。

对于模块和库，使用引用计数的初始化管理器或者Qt的父子对象删除机制也许更好。这里是一个使用父子对象机制，在正确时间调用清理函数的私有类的实例：

    class MyPrivateInitStuff: public QObject {
    private:
        MyPrivateInitStuff( QObject * parent ): QObject( parent) {
            // 这里是初始化
        }
        MyPrivateInitStuff * p;

    public:
        static MyPrivateInitStuff * initStuff( QObject * parent ) {
            if ( !p )
                p = new MyPrivateInitStuff( parent );
            return p;
        }

        ~MyPrivateInitStuff() {
            // 在这里清理（“后面的日常事务”）
        }
    }

通过选择正确的父窗口部件/对象，这会在非常正确的时候完成清理模块数据的任务。

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

打印调试消息msg，或者调用消息处理器（如果它已经被安装）。

这个函数使用一个格式化字符串和参数列表，和C中的printf()函数很相似。

实例：

    qDebug( "my window handle = %x", myWidget->id() );

在X11下，这个文本被打印到标准错误输出。在Windows下，这个文本被打印到调试器。

警告：内部缓存被限制为8196字节（包括0结束符）。

也可以参考qWarning()、qFatal()、qInstallMsgHandler()和Debugging。

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

打印致命消息msg，或者调用消息处理器（如果它已经被安装）。

这个函数使用一个格式化字符串和参数列表，和C中的printf()函数很相似。

实例：

    int divide( int a, int b )
    {
        if ( b == 0 )                           // 程序错误
            qFatal( "divide: cannot divide by zero" );
        return a/b;
    }

在X11下，这个文本被打印到标准错误输出。在Windows下，这个文本被打印到调试器。

警告：内部缓存被限制为8196字节（包括0结束符）。

也可以参考qDebug()、qWarning()、qInstallMsgHandler()和Debugging。

QtMsgHandler qInstallMsgHandler ( QtMsgHandler h )

安装Qt消息处理器h。返回以前定义的的消息处理器的指针。

消息处理器是一个打印调试消息、警告和致命错误消息的函数。Qt库（调试版）包含在发生内部错误（通常是无效函数参数）时要打印的数百条警告消息。如果你实现了你自己的消息处理器，你就得到这些消息的完全控制。

默认消息处理器在X11下把消息打印到标准输出，在Windows下打印到调试器。如果是一个致命消息，应用程序立即异常中断。

只能有一个消息处理器被定义，因为它通常在应用程序范围基础上控制调试输出。

恢复消息处理器，调用qInstallMsgHandler(0)。

实例：

    #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, "警告： %s\n", msg );
                break;
            case QtFatalMsg:
                fprintf( stderr, "Fatal: %s\n", msg );
                abort();                        // 决定把核心倒出
        }
    }

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

也可以参考qDebug()、qWarning()、qFatal()和调试。

bool qSysInfo ( int * wordSize, bool * bigEndian )

获取有关系统的信息。

在wordSize中以位为单位返回系统字大小（通常位32）。如果这是一个以高位在前的机器，bigEndian被设置为真，或者如果这是一个以低位在前的机器，被设置为假。

在调试模式下，如果计算机是真正的怪异（例如对于16位和32位整数是不同的在前方式）这个函数调用qFatal()输出一个信息，在发布模式下，它返回假。

void qSystemWarning ( const char * msg, int code )

打印消息msg并且使用code来获得系统特定错误消息。当code为-1（默认），如果可能系统最后一个错误代码将被使用。使用这个方法来处理平台特定应用编程接口调用的失败。

当Qt在QT_NO_DEBUG被定义的情况下，这个函数什么都不做。

const char * qVersion ()

返回Qt库的版本号，通常为“1.44”或“2.3.0”等。

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

打印警告消息msg，或者调用消息处理器（如果它已经被安装）。

这个函数使用一个格式化字符串和参数列表，和C中的printf()函数很相似。

实例：

    void f( int c )
    {
        if ( c > 200 )
            qWarning( "f: bad argument, c == %d", c );
    }

在X11下，这个文本被打印到标准错误输出。在Windows下，这个文本被打印到调试器。

警告：内部缓存被限制为8196字节（包括0结束符）。

也可以参考qDebug()、qFatal()、qInstallMsgHandler()和Debugging。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qapplication.h包含文件

qapplication.h

这里是qapplication.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qapplication.h   3.0.5   edited May 28 11:20 $
**
** Definition of QApplication class
**
** Created : 931107
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QAPPLICATION_H
#define QAPPLICATION_H

#ifndef QT_H
#include "qdesktopwidget.h"
#include "qasciidict.h"
#include "qpalette.h"
#include "qtranslator.h"
#include "qstrlist.h"
#include "qstringlist.h"
#endif // QT_H

class QSessionManager;
class QStyle;
class QTranslator;
#if defined(Q_WS_QWS)
class QWSDecoration;
#endif

template <class type> class QPtrList;

class QApplication;
extern Q_EXPORT QApplication *qApp;		// global application object

#if defined(QT_THREAD_SUPPORT)
class QMutex;
#endif

class Q_EXPORT QApplication : public QObject
{
    Q_OBJECT
public:
    QApplication( int &argc, char **argv);
    QApplication( int &argc, char **argv, bool GUIenabled );
    enum Type { Tty, GuiClient, GuiServer };
    QApplication( int &argc, char **argv, Type );
#if defined(Q_WS_X11)
    QApplication( Display* dpy, HANDLE visual = 0, HANDLE cmap = 0 );
    QApplication( Display *dpy, int argc, char **argv,
          HANDLE visual = 0, HANDLE cmap= 0 );
#endif
    virtual ~QApplication();

    int		    argc()	const;
    char	  **argv()	const;

    Type type() const;

#ifndef QT_NO_STYLE
    static QStyle  &style();
    static void	    setStyle( QStyle* );
    static QStyle*  setStyle( const QString& );
#endif
#ifndef Q_QDOC
    enum ColorMode { NormalColors, CustomColors };
    static ColorMode colorMode();
    static void      setColorMode( QApplication::ColorMode );
#endif

    enum ColorSpec { NormalColor=0, CustomColor=1, ManyColor=2 };
    static int	     colorSpec();
    static void      setColorSpec( int );
#ifndef QT_NO_CURSOR
    static QCursor  *overrideCursor();
    static void	     setOverrideCursor( const QCursor &, bool replace=FALSE );
    static void	     restoreOverrideCursor();
#endif
    static bool	     hasGlobalMouseTracking();
    static void	     setGlobalMouseTracking( bool enable );
#ifndef QT_NO_PALETTE
    static QPalette  palette( const QWidget* = 0 );
    static void	     setPalette( const QPalette &, bool informWidgets=FALSE,
                 const char* className = 0 );
#endif
    static QFont     font( const QWidget* = 0 );
    static void	     setFont( const QFont &, bool informWidgets=FALSE,
                  const char* className = 0 );
    static QFontMetrics fontMetrics();

    QWidget	    *mainWidget()  const;
    virtual void     setMainWidget( QWidget * );
    virtual void     polish( QWidget * );

    static QWidgetList *allWidgets();
    static QWidgetList *topLevelWidgets();

    static QDesktopWidget   *desktop();

    static QWidget     *activePopupWidget();
    static QWidget     *activeModalWidget();
#ifndef QT_NO_CLIPBOARD
    static QClipboard  *clipboard();
#endif
    QWidget	       *focusWidget() const;
    QWidget	       *activeWindow() const;

    static QWidget  *widgetAt( int x, int y, bool child=FALSE );
    static QWidget  *widgetAt( const QPoint &, bool child=FALSE );

    int		     exec();
    void	     processEvents();
    void	     processEvents( int maxtime );
    void	     processOneEvent();
    bool	     hasPendingEvents();
    int		     enter_loop();
    void	     exit_loop();
    int		     loopLevel() const;
    static void	     exit( int retcode=0 );

    static bool	     sendEvent( QObject *receiver, QEvent *event );
    static void	     postEvent( QObject *receiver, QEvent *event );
    static void	     sendPostedEvents( QObject *receiver, int event_type );
    static void	     sendPostedEvents();

    static void      removePostedEvents( QObject *receiver );

    virtual bool     notify( QObject *, QEvent * );

    static bool	     startingUp();
    static bool	     closingDown();

    static void	     flushX();
    static void flush();
    static void	     syncX();

    static void	     beep();

#ifndef QT_NO_TRANSLATION
    void	     setDefaultCodec( QTextCodec * );
    QTextCodec*	     defaultCodec() const;
    void	     installTranslator( QTranslator * );
    void	     removeTranslator( QTranslator * );
#endif
    enum Encoding { DefaultCodec, UnicodeUTF8 };
    QString	     translate( const char * context,
                const char * key,
                const char * comment = 0,
                Encoding encoding = DefaultCodec ) const;
#ifndef QT_NO_PALETTE
    // obsolete functions
    static void      setWinStyleHighlightColor( const QColor &c ) {
    QPalette p( palette() );
    p.setColor( QColorGroup::Highlight, c );
    setPalette( p, TRUE);
    }
    static const QColor &winStyleHighlightColor() {
    return palette().active().highlight();
    }
#endif
    static void      setDesktopSettingsAware( bool );
    static bool      desktopSettingsAware();

    static void      setCursorFlashTime( int );
    static int       cursorFlashTime();

    static void      setDoubleClickInterval( int );
    static int       doubleClickInterval();
#ifndef QT_NO_WHEELEVENT
    static void      setWheelScrollLines( int );
    static int       wheelScrollLines();
#endif
    static void	     setGlobalStrut( const QSize & );
    static QSize     globalStrut();

#ifndef QT_NO_COMPONENT
    static void      setLibraryPaths(const QStringList &);
    static QStringList libraryPaths();
    static void      addLibraryPath(const QString &);
    static void      removeLibraryPath(const QString &);
#endif //QT_NO_COMPONENT
    static void setStartDragTime( int ms );
    static int startDragTime();
    static void setStartDragDistance( int l );
    static int startDragDistance();

    static void setReverseLayout( bool b );
    static bool reverseLayout();

    static int horizontalAlignment( int align );

    static bool	    isEffectEnabled( Qt::UIEffect );
    static void	    setEffectEnabled( Qt::UIEffect, bool enable = TRUE );

#if defined(Q_WS_MAC)
    virtual bool     macEventFilter( EventRef );
#endif
#if defined(Q_WS_WIN)
    virtual bool     winEventFilter( MSG * );
#endif
#if defined(Q_WS_X11)
    virtual bool     x11EventFilter( XEvent * );
    virtual int	     x11ClientMessage( QWidget*, XEvent*, bool passive_only);
    int              x11ProcessEvent( XEvent* );
#endif
#if defined(Q_WS_QWS)
    virtual bool     qwsEventFilter( QWSEvent * );
    int              qwsProcessEvent( QWSEvent* );
    void             qwsSetCustomColors( QRgb *colortable, int start, int numColors );
#ifndef QT_NO_QWS_MANAGER
    static QWSDecoration &qwsDecoration();
    static void      qwsSetDecoration( QWSDecoration *);
#endif
#endif

#if defined(Q_WS_WIN)
    static WindowsVersion winVersion();
    void	     winFocus( QWidget *, bool );
    static void	     winMouseButtonUp();
#endif

#ifndef QT_NO_SESSIONMANAGER
    // session management
    bool	     isSessionRestored() const;
    QString	     sessionId() const;
    virtual void     commitData( QSessionManager& sm );
    virtual void     saveState( QSessionManager& sm );
#endif
#if defined(Q_WS_X11)
    static void create_xim();
    static void close_xim();
    static bool x11_apply_settings();
#endif
    void	     wakeUpGuiThread();
#if defined(QT_THREAD_SUPPORT)
    void	     lock();
    void	     unlock(bool wakeUpGui = TRUE);
    bool	     locked();
    bool             tryLock();
#endif

signals:
    void	     lastWindowClosed();
    void	     aboutToQuit();
    void	     guiThreadAwake();

public slots:
    void	     quit();
    void	     closeAllWindows();

private:
    void	     construct( int &argc, char **argv, Type );
    bool	     processNextEvent( bool );
    void	     initialize( int, char ** );
    void	     init_precmdline();
    void	     process_cmdline( int* argcptr, char ** argv );
    bool	     internalNotify( QObject *, QEvent * );
#if defined(Q_WS_QWS)
    static QWidget *findChildWidget( const QWidget *p, const QPoint &pos );
    static QWidget *findWidget( const QObjectList&, const QPoint &, bool rec );
#endif

#if defined(Q_WS_MAC)
    bool	     do_mouse_down(Point *);
    static QMAC_PASCAL OSStatus globalEventProcessor(EventHandlerCallRef,  EventRef, void *);
    static QMAC_PASCAL void qt_context_timer_callbk(EventLoopTimerRef, void *);
    static QMAC_PASCAL void qt_select_timer_callbk(EventLoopTimerRef, void *);
    static bool qt_mac_apply_settings();
    friend class QMacInputMethod;
    friend bool qt_set_socket_handler( int, int, QObject *, bool);
    friend void qt_mac_destroy_widget(QWidget *);
    friend void qt_init(int *, char **, QApplication::Type);
#endif

#if defined(QT_THREAD_SUPPORT)
    static QMutex * qt_mutex;
#endif

    int		     app_argc;
    char	   **app_argv;
    bool	     quit_now;
    int		     quit_code;
    static QStyle   *app_style;
    static int	     app_cspec;
#ifndef QT_NO_PALETTE
    static QPalette *app_pal;
#endif
    static QFont    *app_font;
#ifndef QT_NO_CURSOR
    static QCursor  *app_cursor;
#endif
    static int	     app_tracking;
    static bool	     is_app_running;
    static bool	     is_app_closing;
    static bool	     app_exit_loop;
    static int	     loop_level;
    static QWidget  *main_widget;
    static QWidget  *focus_widget;
    static QWidget  *active_window;
    static bool	     obey_desktop_settings;
    static int	     cursor_flash_time;
    static int	     mouse_double_click_time;
    static int	     wheel_scroll_lines;

    static bool	     animate_ui;
    static bool	     animate_menu;
    static bool	     animate_tooltip;
    static bool	     animate_combo;
    static bool	     fade_menu;
    static bool	     fade_tooltip;

    QPtrList<QTranslator> *translators;
#ifndef QT_NO_SESSIONMANAGER
    QSessionManager *session_manager;
    QString	     session_id;
    bool	     is_session_restored;
#endif
#if defined(Q_WS_X11) && !defined (QT_NO_STYLE )
    static void x11_initialize_style();
#endif

    static QSize     app_strut;

    static QStringList *app_libpaths;

    static QAsciiDict<QPalette> *app_palettes;
    static QAsciiDict<QFont>    *app_fonts;

    static QWidgetList *popupWidgets;
    bool	     inPopupMode() const;
    void	     closePopup( QWidget *popup );
    void	     openPopup( QWidget *popup );
    void	     setActiveWindow( QWidget* act );

    static bool      sendSpontaneousEvent( QObject *receiver, QEvent *event );
    static void      removePostedEvent( QEvent * );

    friend class QWidget;
    friend class QETWidget;
    friend class QEvent;
    friend Q_EXPORT void qt_ucm_initialize( QApplication * );
#if defined(Q_WS_WIN)
    friend bool qt_sendSpontaneousEvent( QObject*, QEvent* );
#endif

private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QApplication( const QApplication & );
    QApplication &operator=( const QApplication & );
#endif
};

inline int QApplication::argc() const
{
    return app_argc;
}

inline char **QApplication::argv() const
{
    return app_argv;
}
#ifndef QT_NO_CURSOR
inline QCursor *QApplication::overrideCursor()
{
    return app_cursor;
}
#endif
inline bool QApplication::hasGlobalMouseTracking()
{
    return app_tracking > 0;
}

inline QWidget *QApplication::mainWidget() const
{
    return main_widget;
}

inline QWidget *QApplication::focusWidget() const
{
    return focus_widget;
}

inline QWidget *QApplication::activeWindow() const
{
    return active_window;
}

inline QWidget *QApplication::widgetAt( const QPoint &p, bool child )
{
    return widgetAt( p.x(), p.y(), child );
}

inline bool QApplication::inPopupMode() const
{
    return popupWidgets != 0;
}
#ifndef QT_NO_SESSIONMANAGER
inline bool QApplication::isSessionRestored() const
{
    return is_session_restored;
}

inline QString QApplication::sessionId() const
{
    return session_id;
}
#endif
inline QSize QApplication::globalStrut()
{
    return app_strut;
}

inline bool QApplication::sendEvent( QObject *receiver, QEvent *event )
{ return qApp ? qApp->notify( receiver, event ) : FALSE; }

inline bool QApplication::sendSpontaneousEvent( QObject *receiver, QEvent *event )
{ if ( event ) event->spont = TRUE; return qApp ? qApp->notify( receiver, event ) : FALSE; }

#ifdef QT_NO_TRANSLATION
// Simple versions
inline QString QApplication::translate( const char *, const char *sourceText,
                    const char *, Encoding encoding ) const
{
#ifndef QT_NO_TEXTCODEC
    if ( encoding == UnicodeUTF8 )
    return QString::fromUtf8( sourceText );
    else
#endif
    return QString::fromLatin1( sourceText );
}
#endif

inline int QApplication::horizontalAlignment( int align )
{
    align &= AlignHorizontal_Mask;
    if ( align == AlignAuto ) {
    if ( reverseLayout() )
        align = AlignRight;
    else
        align = AlignLeft;
    }
    return align;
}

#endif // QAPPLICATION_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QApplication成员列表

完整的QApplication成员列表

这里是QApplication成员函数的完整列表，包括继承的成员。

  • QApplication()
  • ~QApplication()
  • aboutToQuit()
  • activeModalWidget()
  • activePopupWidget()
  • activeWindow()
  • addLibraryPath()
  • allWidgets()
  • argc()
  • argv()
  • beep()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clipboard()
  • closeAllWindows()
  • closingDown()
  • colorSpec()
  • commitData()
  • connect()
  • connectNotify()
  • cursorFlashTime()
  • customEvent()
  • defaultCodec()
  • deleteLater()
  • desktop()
  • desktopSettingsAware()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doubleClickInterval()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enter_loop()
  • event()
  • eventFilter()
  • exec()
  • exit()
  • exit_loop()
  • flush()
  • flushX()
  • focusWidget()
  • font()
  • fontMetrics()
  • globalStrut()
  • guiThreadAwake()
  • hasGlobalMouseTracking()
  • hasPendingEvents()
  • highPriority()
  • horizontalAlignment()
  • inherits()
  • insertChild()
  • installEventFilter()
  • installTranslator()
  • isA()
  • isEffectEnabled()
  • isSessionRestored()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • lastWindowClosed()
  • libraryPaths()
  • lock()
  • locked()
  • loopLevel()
  • macEventFilter()
  • mainWidget()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • notify()
  • objectTrees()
  • overrideCursor()
  • palette()
  • parent()
  • polish()
  • postEvent()
  • processEvents()
  • processOneEvent()
  • property()
  • queryList()
  • quit()
  • qwsDecoration()
  • qwsEventFilter()
  • qwsSetCustomColors()
  • qwsSetDecoration()
  • removeChild()
  • removeEventFilter()
  • removeLibraryPath()
  • removePostedEvents()
  • removeTranslator()
  • restoreOverrideCursor()
  • reverseLayout()
  • saveState()
  • sendEvent()
  • sendPostedEvents()
  • sender()
  • sessionId()
  • setColorSpec()
  • setCursorFlashTime()
  • setDefaultCodec()
  • setDesktopSettingsAware()
  • setDoubleClickInterval()
  • setEffectEnabled()
  • setFont()
  • setGlobalMouseTracking()
  • setGlobalStrut()
  • setLibraryPaths()
  • setMainWidget()
  • setName()
  • setOverrideCursor()
  • setPalette()
  • setProperty()
  • setReverseLayout()
  • setStartDragDistance()
  • setStartDragTime()
  • setStyle()
  • setWheelScrollLines()
  • setWinStyleHighlightColor()
  • signalsBlocked()
  • startDragDistance()
  • startDragTime()
  • startTimer()
  • startingUp()
  • style()
  • syncX()
  • timerEvent()
  • topLevelWidgets()
  • tr()
  • trUtf8()
  • translate()
  • tryLock()
  • type()
  • unlock()
  • wakeUpGuiThread()
  • wheelScrollLines()
  • widgetAt()
  • winEventFilter()
  • winFocus()
  • winStyleHighlightColor()
  • winVersion()
  • x11EventFilter()
  • x11ProcessEvent()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QAsciiCache Class

QAsciiCache Class Reference

The QAsciiCache class is a template class that provides a cache based on char* keys. More...

#include <qasciicache.h>

List of all member functions.

Public Members

  • QAsciiCache ( int maxCost = 100, int size = 17, bool caseSensitive = TRUE, bool copyKeys = TRUE )
  • ~QAsciiCache ()
  • int maxCost () const
  • int totalCost () const
  • void setMaxCost ( int m )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • virtual void clear ()
  • bool insert ( const char * k, const type * d, int c = 1, int p = 0 )
  • bool remove ( const char * k )
  • type * take ( const char * k )
  • type * find ( const char * k, bool ref = TRUE ) const
  • type * operator[] ( const char * k ) const
  • void statistics () const

Detailed Description

The QAsciiCache class is a template class that provides a cache based on char* keys.

QAsciiCache is implemented as a template class. Define a template instance QAsciiCache<X> to create a cache that operates on pointers to X (X*).

A cache is a least recently used (LRU) list of cache items. The cache items are accessed via char* keys. For Unicode keys use the QCache template instead, which uses QString keys. A QCache has the same performace as a QAsciiCache.

Each cache item has a cost. The sum of item costs, totalCost(), will not exceed the maximum cache cost, maxCost(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed.

Apart from insert(), by far the most important function is find() (which also exists as operator[]()). This function looks up an item, returns it, and by default marks it as being the most recently used item.

There are also methods to remove() or take() an object from the cache. Calling setAutoDelete(TRUE) tells the cache to delete items that are removed. The default is to not delete items when then are removed (i.e., remove() and take() are equivalent).

When inserting an item into the cache, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the cache copy all of the item's data (known as a deep copy) when an item is inserted. insert() calls the virtual function QPtrCollection::newItem() for the item to be inserted. Inherit a cache and reimplement it if you want deep copies.

When removing a cache item the virtual function QPtrCollection::deleteItem() is called. Its default implementation in QAsciiCache is to delete the item if auto-deletion is enabled.

There is a QAsciiCacheIterator which may be used to traverse the items in the cache in arbitrary order.

See also QAsciiCacheIterator, QCache, QIntCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QAsciiCache::QAsciiCache ( int maxCost = 100, int size = 17, bool caseSensitive = TRUE, bool copyKeys = TRUE )

Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items.

size is actually the size of an internal hash array; it's usually best to make it prime and at least 50% bigger than the largest expected number of items in the cache.

Each inserted item has an associated cost. When inserting a new item, if the total cost of all items in the cache will exceed maxCost, the cache will start throwing out the older (least recently used) items until there is enough room for the new item to be inserted.

If caseSensitive is TRUE (the default), the cache keys are case sensitive; if it is FALSE, they are case-insensitive. Case-insensitive comparison includes only the 26 letters in US-ASCII. If copyKeys is TRUE (the default), QAsciiCache makes a copy of the cache keys, otherwise it copies just the const char * pointer - slightly faster if you can guarantee that the keys will never change, but very risky.

QAsciiCache::~QAsciiCache ()

Removes all items from the cache and destroys it. All iterators that access this cache will be reset.

void QAsciiCache::clear () [virtual]

Removes all items from the cache, and deletes them if auto-deletion has been enabled.

All cache iterators that operate on this cache are reset.

See also remove() and take().

uint QAsciiCache::count () const [virtual]

Returns the number of items in the cache.

See also totalCost() and size().

type * QAsciiCache::find ( const char * k, bool ref = TRUE ) const

Returns the item with key k, or null if the key does not exist in the cache. If ref is TRUE (the default), the item is moved to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

bool QAsciiCache::insert ( const char * k, const type * d, int c = 1, int p = 0 )

Inserts the item d into the cache using key k, and with a cost of c. Returns TRUE if the item is successfully inserted. Returns FALSE if the item is not inserted, for example, if the cost of the item exceeds maxCost().

The cache's size is limited, and if the total cost is too high, QAsciiCache will remove old, least recently used items until there is room for this new item.

Items with duplicate keys may be inserted.

The parameter p is internal and should be left at the default value (0).

Warning: If this function returns FALSE, you must delete d yourself. Additionally, be very careful about using d after calling this function, because any other insertions into the cache, from anywhere in the application or within Qt itself, could cause the object to be discarded from the cache and the pointer to become invalid.

bool QAsciiCache::isEmpty () const

Returns TRUE if the cache is empty; otherwise returns FALSE.

int QAsciiCache::maxCost () const

Returns the maximum allowed total cost of the cache.

See also setMaxCost() and totalCost().

type * QAsciiCache::operator[] ( const char * k ) const

Returns the item with key k, or null if k does not exist in the cache, and moves the item to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

This is the same as find( k, TRUE ).

See also find().

bool QAsciiCache::remove ( const char * k )

Removes the item with key k and returns TRUE if the item was present in the cache; otherwise returns FALSE.

The item is deleted if auto-deletion has been enabled, i.e., if you have called setAutoDelete(TRUE).

If there are two or more items with equal keys, the one that was inserted last is removed.

All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.

See also take() and clear().

void QAsciiCache::setMaxCost ( int m )

Sets the maximum allowed total cost of the cache to m. If the current total cost is greater than m, some items are removed immediately.

See also maxCost() and totalCost().

uint QAsciiCache::size () const

Returns the size of the hash array used to implement the cache. This should be a bit bigger than count() is likely to be.

void QAsciiCache::statistics () const

A debug-only utility function. Prints out cache usage, hit/miss, and distribution information using qDebug(). This function does nothing in the release library.

type * QAsciiCache::take ( const char * k )

Takes the item associated with k out of the cache without deleting it and returns a pointer to the item taken out, or null if the key does not exist in the cache.

If there are two or more items with equal keys, the one that was inserted last is taken.

All iterators that refer to the taken item are set to point to the next item in the cache's traversal order.

See also remove() and clear().

int QAsciiCache::totalCost () const

Returns the total cost of the items in the cache. This is an integer in the range 0 to maxCost().

See also setMaxCost().

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


qasciicache.h Include File

qasciicache.h

This is the verbatim text of the qasciicache.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QAsciiCache template/macro class
**
** Created : 950209
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QASCIICACHE_H
#define QASCIICACHE_H

#ifndef QT_H
#include "qgcache.h"
#endif // QT_H

template<class type>
class QAsciiCache
: public QGCache
{
public:
    QAsciiCache( const QAsciiCache<type> &c ) : QGCache(c) {}
    QAsciiCache( int maxCost=100, int size=17, bool caseSensitive=TRUE,
         bool copyKeys=TRUE )
    : QGCache( maxCost, size, AsciiKey, caseSensitive, copyKeys ) {}
   ~QAsciiCache()			{ clear(); }
    QAsciiCache<type> &operator=( const QAsciiCache<type> &c )
            { return (QAsciiCache<type>&)QGCache::operator=(c); }
    int	  maxCost()   const		{ return QGCache::maxCost(); }
    int	  totalCost() const		{ return QGCache::totalCost(); }
    void  setMaxCost( int m )		{ QGCache::setMaxCost(m); }
    uint  count()     const		{ return QGCache::count(); }
    uint  size()      const		{ return QGCache::size(); }
    bool  isEmpty()   const		{ return QGCache::count() == 0; }
    void  clear()			{ QGCache::clear(); }
    bool  insert( const char *k, const type *d, int c=1, int p=0 )
            { return QGCache::insert_other(k,(Item)d,c,p);}
    bool  remove( const char *k )
            { return QGCache::remove_other(k); }
    type *take( const char *k )
            { return (type *)QGCache::take_other(k); }
    type *find( const char *k, bool ref=TRUE ) const
            { return (type *)QGCache::find_other(k,ref);}
    type *operator[]( const char *k ) const
            { return (type *)QGCache::find_other(k);}
    void  statistics() const	      { QGCache::statistics(); }
private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QAsciiCache<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QAsciiCache<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QAsciiCacheIterator
: public QGCacheIterator
{
public:
    QAsciiCacheIterator( const QAsciiCache<type> &c ):QGCacheIterator((QGCache &)c) {}
    QAsciiCacheIterator( const QAsciiCacheIterator<type> &ci)
                : QGCacheIterator( (QGCacheIterator &)ci ) {}
    QAsciiCacheIterator<type> &operator=(const QAsciiCacheIterator<type>&ci)
    { return ( QAsciiCacheIterator<type>&)QGCacheIterator::operator=( ci ); }
    uint  count()   const     { return QGCacheIterator::count(); }
    bool  isEmpty() const     { return QGCacheIterator::count() == 0; }
    bool  atFirst() const     { return QGCacheIterator::atFirst(); }
    bool  atLast()  const     { return QGCacheIterator::atLast(); }
    type *toFirst()	      { return (type *)QGCacheIterator::toFirst(); }
    type *toLast()	      { return (type *)QGCacheIterator::toLast(); }
    operator type *() const   { return (type *)QGCacheIterator::get(); }
    type *current()   const   { return (type *)QGCacheIterator::get(); }
    const char *currentKey() const { return QGCacheIterator::getKeyAscii(); }
    type *operator()()	      { return (type *)QGCacheIterator::operator()();}
    type *operator++()	      { return (type *)QGCacheIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGCacheIterator::operator+=(j);}
    type *operator--()	      { return (type *)QGCacheIterator::operator--(); }
    type *operator-=(uint j)  { return (type *)QGCacheIterator::operator-=(j);}
};

#endif // QASCIICACHE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QAsciiCache Member List

Complete Member List for QAsciiCache

This is the complete list of member functions for QAsciiCache, including inherited members.

  • ~QAsciiCache()
  • clear()
  • count()
  • find()
  • insert()
  • isEmpty()
  • maxCost()
  • operator[]()
  • remove()
  • setMaxCost()
  • size()
  • statistics()
  • take()
  • totalCost()


QAsciiCacheIterator Class

QAsciiCacheIterator Class Reference

The QAsciiCacheIterator class provides an iterator for QAsciiCache collections. More...

#include <qasciicache.h>

List of all member functions.

Public Members

  • QAsciiCacheIterator ( const QAsciiCache<type> & cache )
  • QAsciiCacheIterator ( const QAsciiCacheIterator<type> & ci )
  • QAsciiCacheIterator<type> & operator= ( const QAsciiCacheIterator<type> & ci )
  • uint count () const
  • bool isEmpty () const
  • bool atFirst () const
  • bool atLast () const
  • type * toFirst ()
  • type * toLast ()
  • operator type * () const
  • type * current () const
  • const char * currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )
  • type * operator-- ()
  • type * operator-= ( uint jump )

Detailed Description

The QAsciiCacheIterator class provides an iterator for QAsciiCache collections.

Note that the traversal order is arbitrary; you are not guaranteed any particular order. If new objects are inserted into the cache while the iterator is active, the iterator may or may not see them.

Multiple iterators are completely independent, even when they operate on the same QAsciiCache. QAsciiCache updates all iterators that refer an item when that item is removed.

QAsciiCacheIterator provides an operator++() and an operator+=() to traverse the cache; current() and currentKey() to access the current cache item and its key. It also provides atFirst() and atLast(), which return TRUE if the iterator points to the first or last item in the cache respectively. The isEmpty() function returns TRUE if the cache is empty; and count() returns the number of items in the cache.

Note that atFirst() and atLast() refer to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also QAsciiCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QAsciiCacheIterator::QAsciiCacheIterator ( const QAsciiCache<type> & cache )

Constructs an iterator for cache. The current iterator item is set to point to the first item in the cache.

QAsciiCacheIterator::QAsciiCacheIterator ( const QAsciiCacheIterator<type> & ci )

Constructs an iterator for the same cache as ci. The new iterator starts at the same item as ci.current() but moves independently from there on.

bool QAsciiCacheIterator::atFirst () const

Returns TRUE if the iterator points to the first item in the cache. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also toFirst() and atLast().

bool QAsciiCacheIterator::atLast () const

Returns TRUE if the iterator points to the last item in the cache. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also toLast() and atFirst().

uint QAsciiCacheIterator::count () const

Returns the number of items in the cache over which this iterator operates.

See also isEmpty().

type * QAsciiCacheIterator::current () const

Returns a pointer to the current iterator item.

const char * QAsciiCacheIterator::currentKey () const

Returns the key for the current iterator item.

bool QAsciiCacheIterator::isEmpty () const

Returns TRUE if the cache is empty, i.e. count() == 0; otherwise returns FALSE.

See also count().

QAsciiCacheIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QAsciiCacheIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the cache or if it was null, null is returned.

type * QAsciiCacheIterator::operator++ ()

Prefix ++ makes the iterator point to the item just after current(), and makes that the new current item for the iterator. If current() was the last item, operator++() returns 0.

type * QAsciiCacheIterator::operator+= ( uint jump )

Returns the item jump positions after the current item, or null if it is beyond the last item. Makes this the current item.

type * QAsciiCacheIterator::operator-- ()

Prefix -- makes the iterator point to the item just before current(), and makes that the new current item for the iterator. If current() was the first item, operator--() returns 0.

type * QAsciiCacheIterator::operator-= ( uint jump )

Returns the item jump positions before the current item, or null if it is before the first item. Makes this the current item.

QAsciiCacheIterator<type> & QAsciiCacheIterator::operator= ( const QAsciiCacheIterator<type> & ci )

Makes this an iterator for the same cache as ci. The new iterator starts at the same item as ci.current(), but moves independently thereafter.

type * QAsciiCacheIterator::toFirst ()

Sets the iterator to point to the first item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if the cache is empty.

See also toLast() and isEmpty().

type * QAsciiCacheIterator::toLast ()

Sets the iterator to point to the last item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if the cache is empty.

See also isEmpty().

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


QAsciiCacheIterator Member List

Complete Member List for QAsciiCacheIterator

This is the complete list of member functions for QAsciiCacheIterator, including inherited members.

  • QAsciiCacheIterator()
  • atFirst()
  • atLast()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()


QAsciiDict Class

QAsciiDict Class Reference

The QAsciiDict class is a template class that provides a dictionary based on char* keys. More...

#include <qasciidict.h>

Inherits QPtrCollection.

List of all member functions.

Public Members

  • QAsciiDict ( int size = 17, bool caseSensitive = TRUE, bool copyKeys = TRUE )
  • QAsciiDict ( const QAsciiDict<type> & dict )
  • ~QAsciiDict ()
  • QAsciiDict<type> & operator= ( const QAsciiDict<type> & dict )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • void insert ( const char * key, const type * item )
  • void replace ( const char * key, const type * item )
  • bool remove ( const char * key )
  • type * take ( const char * key )
  • type * find ( const char * key ) const
  • type * operator[] ( const char * key ) const
  • virtual void clear ()
  • void resize ( uint newsize )
  • void statistics () const

Important Inherited Members

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

Protected Members

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item ) const

Detailed Description

The QAsciiDict class is a template class that provides a dictionary based on char* keys.

QAsciiDict is implemented as a template class. Define a template instance QAsciiDict<X> to create a dictionary that operates on pointers to X (X*).

A dictionary is a collection of key-value pairs. The key is a char* used for insertion, removal and lookup. The value is a pointer. Dictionaries provide very fast insertion and lookup.

QAsciiDict cannot handle Unicode keys; use the QDict template instead, which uses QString keys. A QDict has the same performace as a QAsciiDict.

Example:

    QAsciiDict<QLineEdit> fields;
    fields.insert( "forename", new QLineEdit( this ) );
    fields.insert( "surname", new QLineEdit( this ) );

    fields["forename"]->setText( "Homer" );
    fields["surname"]->setText( "Simpson" );

    QAsciiDictIterator<QLineEdit> it( fields ); // See QAsciiDictIterator
    for( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;
    cout << endl;

    if ( fields["forename"] && fields["surname"] )
        cout << fields["forename"]->text() << " "
            << fields["surname"]->text() << endl;  // Prints "Homer Simpson"

    fields.remove( "forename" ); // Does not delete the line edit
    if ( ! fields["forename"] )
        cout << "forename is not in the dictionary" << endl;
In this example we use a dictionary to keep track of the line edits we're using. We insert each line edit into the dictionary with a unique name and then access the line edits via the dictionary. See QPtrDict, QIntDict and QDict.

See QDict for full details, including the choice of dictionary size, and how deletions are handled.

See also QAsciiDictIterator, QDict, QIntDict, QPtrDict, Collection Classes, Collection Classes and Non-GUI Classes.

Member Function Documentation

QAsciiDict::QAsciiDict ( int size = 17, bool caseSensitive = TRUE, bool copyKeys = TRUE )

Constructs a dictionary optimized for less than size entries.

We recommend setting size to a suitably large prime number (a bit larger than the expected number of entries). This makes the hash distribution better and hence the lookup faster.

When caseSensitive is TRUE (the default) QAsciiDict treats "abc" and "Abc" as different keys; when it is FALSE "abc" and "Abc" are the same. Case-insensitive comparison includes only the 26 letters in US-ASCII.

If copyKeys is TRUE (the default), the dictionary copies keys using strcpy; if it is FALSE, the dictionary just copies the pointers.

QAsciiDict::QAsciiDict ( const QAsciiDict<type> & dict )

Constructs a copy of dict.

Each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy).

QAsciiDict::~QAsciiDict ()

Removes all items from the dictionary and destroys it.

The items are deleted if auto-delete is enabled.

All iterators that access this dictionary will be reset.

See also setAutoDelete().

bool QPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is FALSE.

See also setAutoDelete().

void QAsciiDict::clear () [virtual]

Removes all items from the dictionary.

The removed items are deleted if auto-deletion is enabled.

All dictionary iterators that operate on dictionary are reset.

See also remove(), take() and setAutoDelete().

Reimplemented from QPtrCollection.

uint QAsciiDict::count () const [virtual]

Returns the number of items in the dictionary.

See also isEmpty().

Reimplemented from QPtrCollection.

type * QAsciiDict::find ( const char * key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the item that was most recently inserted will be found.

Equivalent to the [] operator.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also operator[]().

void QAsciiDict::insert ( const char * key, const type * item )

Inserts the key with the item into the dictionary.

The key does not have to be a unique dictionary key. If multiple items are inserted with the same key, only the last item will be visible.

Null items are not allowed.

See also replace().

bool QAsciiDict::isEmpty () const

Returns TRUE if the dictionary is empty, i.e. count() == 0; otherwise it returns FALSE.

See also count().

QAsciiDict<type> & QAsciiDict::operator= ( const QAsciiDict<type> & dict )

Assigns dict to this dictionary and returns a reference to this dictionary.

This dictionary is first cleared and then each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy) unless newItem() has been reimplemented().

type * QAsciiDict::operator[] ( const char * key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the item that was most recently inserted will be found.

Equivalent to the find() function.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also find().

QDataStream & QAsciiDict::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

Reads a dictionary item from the stream s and returns a reference to the stream.

The default implementation sets item to 0.

See also write().

bool QAsciiDict::remove ( const char * key )

Removes the item associated with key from the dictionary. Returns TRUE if successful, or FALSE if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last inserted of these will be removed.

The removed item is deleted if auto-deletion is enabled.

All dictionary iterators that refer to the removed item will be set to point to the next item in the dictionary traversal order.

See also take(), clear() and setAutoDelete().

void QAsciiDict::replace ( const char * key, const type * item )

Replaces an item that has a key equal to key with item.

If the item does not already exist, it will be inserted.

Null items are not allowed.

Equivalent to:

    QAsciiDict<char> dict;
        ...
    if ( dict.find(key) )
        dict.remove( key );
    dict.insert( key, item );

If there are two or more items with equal keys, then the last inserted of these will be replaced.

See also insert().

void QAsciiDict::resize ( uint newsize )

Changes the size of the hashtable to newsize. The contents of the dictionary are preserved but all iterators on the dictionary become invalid.

void QPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is TRUE and to never delete them if enable is FALSE.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is FALSE, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp and table/bigtable/main.cpp.

uint QAsciiDict::size () const

Returns the size of the internal hash array (as specified in the constructor).

See also count().

void QAsciiDict::statistics () const

Debugging-only function that prints out the dictionary distribution using qDebug().

type * QAsciiDict::take ( const char * key )

Takes the item associated with key out of the dictionary without deleting it (even if auto-deletion is enabled).

If there are two or more items with equal keys, then the last inserted of these will be taken.

Returns a pointer to the item taken out, or null if the key does not exist in the dictionary.

All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary traversal order.

See also remove(), clear() and setAutoDelete().

QDataStream & QAsciiDict::write ( QDataStream & s, QPtrCollection::Item ) const [virtual protected]

Writes a dictionary item to the stream s and returns a reference to the stream.

See also read().

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


qasciidict.h Include File

qasciidict.h

This is the verbatim text of the qasciidict.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QAsciiDict template class
**
** Created : 920821
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QASCIIDICT_H
#define QASCIIDICT_H

#ifndef QT_H
#include "qgdict.h"
#endif // QT_H

template<class type>
class QAsciiDict
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGDict
#endif
{
public:
    QAsciiDict(int size=17, bool caseSensitive=TRUE, bool copyKeys=TRUE )
    : QGDict(size,AsciiKey,caseSensitive,copyKeys) {}
    QAsciiDict( const QAsciiDict<type> &d ) : QGDict(d) {}
   ~QAsciiDict()			{ clear(); }
    QAsciiDict<type> &operator=(const QAsciiDict<type> &d)
            { return (QAsciiDict<type>&)QGDict::operator=(d); }
    uint  count()   const		{ return QGDict::count(); }
    uint  size()    const		{ return QGDict::size(); }
    bool  isEmpty() const		{ return QGDict::count() == 0; }

    void  insert( const char *k, const type *d )
                    { QGDict::look_ascii(k,(Item)d,1); }
    void  replace( const char *k, const type *d )
                    { QGDict::look_ascii(k,(Item)d,2); }
    bool  remove( const char *k )	{ return QGDict::remove_ascii(k); }
    type *take( const char *k )		{ return (type *)QGDict::take_ascii(k); }
    type *find( const char *k ) const
        { return (type *)((QGDict*)this)->QGDict::look_ascii(k,0,0); }
    type *operator[]( const char *k ) const
        { return (type *)((QGDict*)this)->QGDict::look_ascii(k,0,0); }

    void  clear()			{ QGDict::clear(); }
    void  resize( uint n )		{ QGDict::resize(n); }
    void  statistics() const		{ QGDict::statistics(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream &, QPtrCollection::Item & );
    virtual QDataStream& write( QDataStream &, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QAsciiDict<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QAsciiDict<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QAsciiDictIterator
: public QGDictIterator
{
public:
    QAsciiDictIterator(const QAsciiDict<type> &d)
    : QGDictIterator((QGDict &)d) {}
   ~QAsciiDictIterator()      {}
    uint  count()   const     { return dict->count(); }
    bool  isEmpty() const     { return dict->count() == 0; }
    type *toFirst()	      { return (type *)QGDictIterator::toFirst(); }
    operator type *() const   { return (type *)QGDictIterator::get(); }
    type   *current() const   { return (type *)QGDictIterator::get(); }
    const char *currentKey() const { return QGDictIterator::getKeyAscii(); }
    type *operator()()	      { return (type *)QGDictIterator::operator()(); }
    type *operator++()	      { return (type *)QGDictIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGDictIterator::operator+=(j);}
};

#endif // QASCIIDICT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QAsciiDict Member List

Complete Member List for QAsciiDict

This is the complete list of member functions for QAsciiDict, including inherited members.

  • QAsciiDict()
  • ~QAsciiDict()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • find()
  • insert()
  • isEmpty()
  • newItem()
  • operator=()
  • operator[]()
  • read()
  • remove()
  • replace()
  • resize()
  • setAutoDelete()
  • size()
  • statistics()
  • take()
  • write()


QAsciiDictIterator Class

QAsciiDictIterator Class Reference

The QAsciiDictIterator class provides an iterator for QAsciiDict collections. More...

#include <qasciidict.h>

List of all member functions.

Public Members

  • QAsciiDictIterator ( const QAsciiDict<type> & dict )
  • ~QAsciiDictIterator ()
  • uint count () const
  • bool isEmpty () const
  • type * toFirst ()
  • operator type * () const
  • type * current () const
  • const char * currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )

Detailed Description

The QAsciiDictIterator class provides an iterator for QAsciiDict collections.

QAsciiDictIterator is implemented as a template class. Define a template instance QAsciiDictIterator<X> to create a dictionary iterator that operates on QAsciiDict<X> (dictionary of X*).

Example:

    QAsciiDict<QLineEdit> fields;
    fields.insert( "forename", new QLineEdit( this ) );
    fields.insert( "surname", new QLineEdit( this ) );
    fields.insert( "age", new QLineEdit( this ) );

    fields["forename"]->setText( "Homer" );
    fields["surname"]->setText( "Simpson" );
    fields["age"]->setText( "45" );

    QAsciiDictIterator<QLineEdit> it( fields );
    for( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;
    cout << endl;

    // Output (random order):
    //  age: 45
    //  surname: Simpson
    //  forename: Homer
In the example we insert some line edits into a dictionary, then iterate over the dictionary printing the strings associated with those line edits.

Note that the traversal order is arbitrary; you are not guaranteed any particular order.

Multiple iterators may independently traverse the same dictionary. A QAsciiDict knows about all the iterators that are operating on the dictionary. When an item is removed from the dictionary, QAsciiDict updates all the iterators that are referring the removed item to point to the next item in the (arbitrary) traversal order.

See also QAsciiDict, Collection Classes and Non-GUI Classes.

Member Function Documentation

QAsciiDictIterator::QAsciiDictIterator ( const QAsciiDict<type> & dict )

Constructs an iterator for dict. The current iterator item is set to point on the first item in the dict.

QAsciiDictIterator::~QAsciiDictIterator ()

Destroys the iterator.

uint QAsciiDictIterator::count () const

Returns the number of items in the dictionary this iterator operates over.

See also isEmpty().

type * QAsciiDictIterator::current () const

Returns a pointer to the current iterator item.

const char * QAsciiDictIterator::currentKey () const

Returns a pointer to the key for the current iterator item.

bool QAsciiDictIterator::isEmpty () const

Returns TRUE if the dictionary is empty, i.e. count() == 0, otherwise returns FALSE.

See also count().

QAsciiDictIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QAsciiDictIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QAsciiDictIterator::operator++ ()

Prefix ++ makes the succeeding item current and returns the new current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QAsciiDictIterator::operator+= ( uint jump )

Sets the current item to the item jump positions after the current item, and returns a pointer to that item.

If that item is beyond the last item or if the dictionary is empty, it sets the current item to null and returns null.

type * QAsciiDictIterator::toFirst ()

Sets the current iterator item to point to the first item in the dictionary and returns a pointer to the item. If the dictionary is empty it sets the current item to null and returns null.

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


QAsciiDictIterator Member List

Complete Member List for QAsciiDictIterator

This is the complete list of member functions for QAsciiDictIterator, including inherited members.

  • QAsciiDictIterator()
  • ~QAsciiDictIterator()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • toFirst()


qasyncimageio.h Include File

qasyncimageio.h

This is the verbatim text of the qasyncimageio.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qasyncimageio.h   3.0.5   edited Oct 12 2001 $
**
** Definition of asynchronous image/movie loading classes
**
** Created : 970617
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QASYNCIMAGEIO_H
#define QASYNCIMAGEIO_H

#ifndef QT_H
#include "qimage.h"
#endif // QT_H

#ifndef QT_NO_ASYNC_IMAGE_IO

class Q_EXPORT QImageConsumer {
public:
    virtual void end()=0;

    // Change transfer type 1.
    virtual void changed( const QRect& ) = 0;
    virtual void frameDone() = 0;

    // Change transfer type 2.
    virtual void frameDone( const QPoint&, const QRect& ) = 0;

    virtual void setLooping( int ) = 0;
    virtual void setFramePeriod( int ) = 0;
    virtual void setSize( int, int ) = 0;
};

class Q_EXPORT QImageFormat {
public:
    virtual ~QImageFormat();
    virtual int decode( QImage& img, QImageConsumer* consumer,
            const uchar* buffer, int length ) = 0;
};

class Q_EXPORT QImageFormatType {
public:
    virtual ~QImageFormatType();
    virtual QImageFormat* decoderFor( const uchar* buffer, int length ) = 0;
    virtual const char* formatName() const = 0;
protected:
    QImageFormatType();
};

class QImageDecoderPrivate;
class Q_EXPORT QImageDecoder {
public:
    QImageDecoder( QImageConsumer* c );
    ~QImageDecoder();

    const QImage& image() { return img; }
    int decode( const uchar* buffer, int length );

    static const char* formatName( const uchar* buffer, int length );
    static QImageFormatType* format( const char* name ); // direct use - no decode()

    static QStrList inputFormats();
    static void registerDecoderFactory( QImageFormatType* );
    static void unregisterDecoderFactory( QImageFormatType* );

private:
    QImageFormat* actual_decoder;
    QImageConsumer* consumer;
    QImage img;
    QImageDecoderPrivate *d;
};

#endif // QT_NO_ASYNC_IMAGE_IO

#endif // QASYNCIMAGEIO_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QAsyncIO Class

QAsyncIO Class Reference
[obsolete]

The QAsyncIO class encapsulates I/O asynchronicity. More...

#include <qasyncio.h>

Inherited by QDataSink and QDataSource.

List of all member functions.

Public Members

  • virtual ~QAsyncIO ()
  • void connect ( QObject * obj, const char * member )

Protected Members

  • void ready ()

Detailed Description

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

The QAsyncIO class encapsulates I/O asynchronicity.

The Qt classes for asynchronous input/output provide a simple mechanism to allow large files or slow data sources to be processed without using large amounts of memory or blocking the user interface.

This facility is used in Qt to drive animated images. See QImageConsumer.

Member Function Documentation

QAsyncIO::~QAsyncIO () [virtual]

Destroys the async IO object.

void QAsyncIO::connect ( QObject * obj, const char * member )

Ensures that only one object, obj and function, member, can respond to changes in readiness.

void QAsyncIO::ready () [protected]

Derived classes should call this when they change from being unready to ready.

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


qasyncio.h Include File

qasyncio.h

This is the verbatim text of the qasyncio.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qasyncio.h   3.0.5   edited Oct 12 2001 $
**
** Definition of asynchronous I/O classes
**
** Created : 970617
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QASYNCIO_H
#define QASYNCIO_H

#ifndef QT_H
#include "qobject.h"
#include "qsignal.h"
#include "qtimer.h"
#endif // QT_H

#ifndef QT_NO_ASYNC_IO

class QIODevice;

class Q_EXPORT QAsyncIO {
public:
    virtual ~QAsyncIO();
    void connect(QObject*, const char *member);

protected:
    void ready();

private:
    QSignal signal;
};

class Q_EXPORT QDataSink : public QAsyncIO {
public:
    // Call this to know how much I can take.
    virtual int readyToReceive()=0;
    virtual void receive(const uchar*, int count)=0;
    virtual void eof()=0;
    void maybeReady();
};

class Q_EXPORT QDataSource : public QAsyncIO {
public:
    virtual int readyToSend()=0; // returns -1 when never any more ready
    virtual void sendTo(QDataSink*, int count)=0;
    void maybeReady();

    virtual bool rewindable() const;
    virtual void enableRewind(bool);
    virtual void rewind();
};

class Q_EXPORT QIODeviceSource : public QDataSource {
    const int buf_size;
    uchar *buffer;
    QIODevice* iod;
    bool rew;

public:
    QIODeviceSource(QIODevice*, int bufsize=4096);
   ~QIODeviceSource();

    int readyToSend();
    void sendTo(QDataSink* sink, int n);
    bool rewindable() const;
    void enableRewind(bool on);
    void rewind();
};

class Q_EXPORT QDataPump : public QObject {
    Q_OBJECT
    int interval;
    QTimer timer;
    QDataSource* source;
    QDataSink* sink;

public:
    QDataPump(QDataSource*, QDataSink*);

private slots:
    void kickStart();
    void tryToPump();
};

#endif	// QT_NO_ASYNC_IO

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QAsyncIO Member List

Complete Member List for QAsyncIO

This is the complete list of member functions for QAsyncIO, including inherited members.

  • ~QAsyncIO()
  • connect()
  • ready()


QBitArray类

QBitArray类参考

QBitArray类提供了一个位数组。 详情请见……

#include <qbitarray.h>

继承了QByteArray。

所有成员函数的列表。

公有成员

  • QBitArray ()
  • QBitArray ( uint size )
  • QBitArray ( const QBitArray & a )
  • QBitArray & operator= ( const QBitArray & a )
  • uint size () const
  • bool resize ( uint size )
  • bool fill ( bool v, int size = -1 )
  • virtual void detach ()
  • QBitArray copy () const
  • bool testBit ( uint index ) const
  • void setBit ( uint index )
  • void setBit ( uint index, bool value )
  • void clearBit ( uint index )
  • bool toggleBit ( uint index )
  • bool at ( uint index ) const
  • QBitVal operator[] ( int index )
  • bool operator[] ( int index ) const
  • QBitArray & operator&= ( const QBitArray & a )
  • QBitArray & operator|= ( const QBitArray & a )
  • QBitArray & operator^= ( const QBitArray & a )
  • QBitArray operator~ () const

Related Functions

  • QBitArray operator& ( const QBitArray & a1, const QBitArray & a2 )
  • QBitArray operator| ( const QBitArray & a1, const QBitArray & a2 )
  • QBitArray operator^ ( const QBitArray & a1, const QBitArray & a2 )
  • QDataStream & operator<< ( QDataStream & s, const QBitArray & a )
  • QDataStream & operator>> ( QDataStream & s, QBitArray & a )

详细描述

QBitArray类提供了一个位数组。

因为QBitArray是一个QMemArray，它通过一个引用计数使用了明显共享。

QBitArray是一个特殊的字节数组，它可以访问单独的位并且可以在整个位数组上执行为操作（AND、OR、XOR和NOT）。

位可以通过函数setBit()和clearBit()来操作，但是它也可以使用索引[]操作符来测试和设置单独的位。[]操作符比setBit()和clearBit()慢一些，因为在实现单独位分配中需要一些技巧。

实例：

    QBitArray a(3);
    a.setBit( 0 );
    a.clearBit( 1 );
    a.setBit( 2 );                      // a = [1 0 1]

    QBitArray b(3);
    b[0] = 1;
    b[1] = 1;
    b[2] = 0;                           // b = [1 1 0]

    QBitArray c;
    c = ~a & b;                         // c = [0 1 0]

当QBitArray被构造时，位没有被初始化。使用fill()可以设置所有的位为0或1。数组可以用resize()来重新定义大小并且用copy()来复制。位可以用setBit()来设置并且用clearBit()来清空。位可以用toggleBit()来切换。一个位的值可以用testBit()和at()来获得。

QBitArray支持&（AND）、|（OR）、^（XOR）和~（NOT）操作符。

也可以参考集合类、隐含和明显共享类和非GUI类。

成员函数文档

QBitArray::QBitArray ()

构造一个空的位数组。

QBitArray::QBitArray ( uint size )

构造一个size位的位数组。位没有被初始化。

也可以参考fill()。

QBitArray::QBitArray ( const QBitArray & a )

构造一个a的浅复制。

bool QBitArray::at ( uint index ) const

返回index位置的位的值（0或1）。

也可以参考operator[]()。

void QBitArray::clearBit ( uint index )

清空index位置的位（设置它为0）。

也可以参考setBit()和toggleBit()。

QBitArray QBitArray::copy () const

返回一个位数组的深复制。

也可以参考detach()。

void QBitArray::detach () [虚]

从共享位数组数据中分离并且并且确认这个位数组是数据的唯一引用。

如果是多重位数组共享公有数据，这个位数组引用计数减一并且得到一个数据的复制。如果只是一个单独的引用将没有任何操作。

也可以参考copy()。

从QMemArray中重新实现的。

bool QBitArray::fill ( bool v, int size = -1 )

用v填充位数组（如果v为真，填1，或者如果v为假，填0）。

如果size为非负数，fill()会重新定义位数组的大小为size。

如果size为非负数并且位数组没有能被重新定义大小，返回假，否则返回真。

也可以参考resize()。

QBitArray & QBitArray::operator&= ( const QBitArray & a )

对这个位数组和a的所有位进行AND操作。返回这个位数组的引用。

如果两个数组大小不同，对于缺少的位，AND操作将使用0，就像下面的例子所描述的：

    QBitArray a( 3 ), b( 2 );
    a[0] = 1;  a[1] = 0;  a[2] = 1;     // a = [1 0 1]
    b[0] = 1;  b[1] = 0;                // b = [1 0]
    a &= b;                             // a = [1 0 0]

也可以参考operator|=()、operator^=()和operator~()。

QBitArray & QBitArray::operator= ( const QBitArray & a )

分配一个a的浅复制给这个位数组并且返回这个位数组的引用。

QBitVal QBitArray::operator[] ( int index )

为位数组实现了[]操作符。

返回到QBitVal是一个上下文对象。它使得得到和设置index位置的单个位成为可能。

实例：

    QBitArray a( 3 );
    a[0] = 0;
    a[1] = 1;
    a[2] = a[0] ^ a[1];

函数testBit()、setBit()和clearBit()更快一些。

也可以参考at()。

bool QBitArray::operator[] ( int index ) const

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

为常量位数组实现了[]操作符。

QBitArray & QBitArray::operator^= ( const QBitArray & a )

对这个位数组和a的所有位做XOR操作。返回这个数组的引用。

结果的长度为两个数组中比较长的长度，比较短的数组缺少的位用0。

实例：

    QBitArray a( 3 ), b( 2 );
    a[0] = 1;  a[1] = 0;  a[2] = 1;     // a = [1 0 1]
    b[0] = 1;  b[1] = 0;                // b = [1 0]
    a ^= b;                             // a = [0 0 1]

也可以参考operator&=()、operator|=()和operator~()。

QBitArray & QBitArray::operator|= ( const QBitArray & a )

对这个位数组和a的所有位做OR操作。返回这个数组的引用。

结果的长度为两个数组中比较长的长度，比较短的数组缺少的位用0。

实例：

    QBitArray a( 3 ), b( 2 );
    a[0] = 1;  a[1] = 0;  a[2] = 1;     // a = [1 0 1]
    b[0] = 1;  b[1] = 0;                // b = [1 0]
    a |= b;                             // a = [1 0 1]

也可以参考operator&=()、operator^=()和operator~()。

QBitArray QBitArray::operator~ () const

返回这个位数组所有位取反后的位数组。

实例：

    QBitArray a( 3 ), b;
    a[0] = 1;  a[1] = 0; a[2] = 1;      // a = [1 0 1]
    b = ~a;                             // b = [0 1 0]

bool QBitArray::resize ( uint size )

重新定义位数组的大小为size位并且如果位数组可以重新定义大小，返回真，否则返回假。

如果数组被扩大了，新的位被设置为0。

也可以参考size()。

void QBitArray::setBit ( uint index, bool value )

设置index位置的位为value。

等同于：

    if ( value )
        setBit( index );
    else
        clearBit( index );

也可以参考clearBit()和toggleBit()。

void QBitArray::setBit ( uint index )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

设置index位置的位（设置它为1）。

也可以参考clearBit()和toggleBit()。

uint QBitArray::size () const

返回位数组的大小（位的个数）。

也可以参考resize()。

bool QBitArray::testBit ( uint index ) const

如果index位置的位已经被设置，比如是1，就返回真。

也可以参考setBit()和clearBit()。

bool QBitArray::toggleBit ( uint index )

切换index位置的位。

如果以前的值为0，新值就是1。如果以前的指为1，新值就为0。

也可以参考setBit()和clearBit()。

相关函数

QBitArray operator& ( const QBitArray & a1, const QBitArray & a2 )

返回位数组a1和a2的AND操作的结果。

也可以参考QBitArray::operator&=()。

QDataStream & operator<< ( QDataStream & s, const QBitArray & a )

把位数组a写到流s中。

也可以参考QDataStream操作符的格式。

QDataStream & operator>> ( QDataStream & s, QBitArray & a )

从流s中读取一个位数组到a中。

也可以参考QDataStream操作符的格式。

QBitArray operator^ ( const QBitArray & a1, const QBitArray & a2 )

返回位数组a1和a2的XOR操作的结果。

也可以参考QBitArray::operator^()。

QBitArray operator| ( const QBitArray & a1, const QBitArray & a2 )

返回位数组a1和a2的OR操作的结果。

也可以参考QBitArray::operator|=()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qbitarray.h包含文件

qbitarray.h

这里是qbitarray.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qbitarray.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QBitArray class
**
** Created : 940118
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBITARRAY_H
#define QBITARRAY_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

/*****************************************************************************
  QBitVal class; a context class for QBitArray::operator[]
 *****************************************************************************/

class QBitArray;

class Q_EXPORT QBitVal
{
private:
    QBitArray *array;
    uint    index;
public:
    QBitVal( QBitArray *a, uint i ) : array(a), index(i) {}
    operator int();
    QBitVal &operator=( const QBitVal &v );
    QBitVal &operator=( bool v );
};

/*****************************************************************************
  QBitArray class
 *****************************************************************************/

class Q_EXPORT QBitArray : public QByteArray
{
public:
    QBitArray();
    QBitArray( uint size );
    QBitArray( const QBitArray &a ) : QByteArray( a ) {}

    QBitArray &operator=( const QBitArray & );

    uint    size() const;
    bool    resize( uint size );

    bool    fill( bool v, int size = -1 );

    void    detach();
    QBitArray copy() const;

    bool    testBit( uint index ) const;
    void    setBit( uint index );
    void    setBit( uint index, bool value );
    void    clearBit( uint index );
    bool    toggleBit( uint index );

    bool    at( uint index ) const;
    QBitVal operator[]( int index );
    bool operator[]( int index ) const;

    QBitArray &operator&=( const QBitArray & );
    QBitArray &operator|=( const QBitArray & );
    QBitArray &operator^=( const QBitArray & );
    QBitArray  operator~() const;

protected:
    struct bitarr_data : public QGArray::array_data {
    uint   nbits;
    };
    array_data *newData()		    { return new bitarr_data; }
    void	deleteData( array_data *d ) { delete (bitarr_data*)d; }
private:
    void    pad0();
};

inline QBitArray &QBitArray::operator=( const QBitArray &a )
{ return (QBitArray&)assign( a ); }

inline uint QBitArray::size() const
{ return ((bitarr_data*)sharedBlock())->nbits; }

inline void QBitArray::setBit( uint index, bool value )
{ if ( value ) setBit(index); else clearBit(index); }

inline bool QBitArray::at( uint index ) const
{ return testBit(index); }

inline QBitVal QBitArray::operator[]( int index )
{ return QBitVal( (QBitArray*)this, index ); }

inline bool QBitArray::operator[]( int index ) const
{ return testBit( index ); }

/*****************************************************************************
  Misc. QBitArray operator functions
 *****************************************************************************/

Q_EXPORT QBitArray operator&( const QBitArray &, const QBitArray & );
Q_EXPORT QBitArray operator|( const QBitArray &, const QBitArray & );
Q_EXPORT QBitArray operator^( const QBitArray &, const QBitArray & );

inline QBitVal::operator int()
{
    return array->testBit( index );
}

inline QBitVal &QBitVal::operator=( const QBitVal &v )
{
    array->setBit( index, v.array->testBit(v.index) );
    return *this;
}

inline QBitVal &QBitVal::operator=( bool v )
{
    array->setBit( index, v );
    return *this;
}

/*****************************************************************************
  QBitArray stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QBitArray & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QBitArray & );
#endif

#endif // QBITARRAY_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QBitArray成员列表

完整的QBitArray成员列表

这里是QBitArray成员函数的完整列表，包括继承的成员。

  • QBitArray()
  • assign()
  • at()
  • begin()
  • bsearch()
  • clearBit()
  • contains()
  • copy()
  • count()
  • data()
  • detach()
  • duplicate()
  • end()
  • fill()
  • find()
  • isEmpty()
  • isNull()
  • nrefs()
  • operator const type *()
  • operator!=()
  • operator&=()
  • operator=()
  • operator==()
  • operator[]()
  • operator^=()
  • operator|=()
  • operator~()
  • resetRawData()
  • resize()
  • setBit()
  • setRawData()
  • size()
  • sort()
  • testBit()
  • toggleBit()
  • truncate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QBitmap Class

QBitmap Class Reference

The QBitmap class provides monochrome (1-bit depth) pixmaps. More...

#include <qbitmap.h>

Inherits QPixmap.

List of all member functions.

Public Members

  • QBitmap ()
  • QBitmap ( int w, int h, bool clear = FALSE, QPixmap::Optimization optimization = QPixmap::DefaultOptim )
  • QBitmap ( const QSize & size, bool clear = FALSE, QPixmap::Optimization optimization = QPixmap::DefaultOptim )
  • QBitmap ( int w, int h, const uchar * bits, bool isXbitmap = FALSE )
  • QBitmap ( const QSize & size, const uchar * bits, bool isXbitmap = FALSE )
  • QBitmap ( const QBitmap & bitmap )
  • QBitmap ( const QString & fileName, const char * format = 0 )
  • QBitmap & operator= ( const QBitmap & bitmap )
  • QBitmap & operator= ( const QPixmap & pixmap )
  • QBitmap & operator= ( const QImage & image )
  • QBitmap xForm ( const QWMatrix & matrix ) const

Detailed Description

The QBitmap class provides monochrome (1-bit depth) pixmaps.

The QBitmap class is a monochrome off-screen paint device used mainly for creating custom QCursor and QBrush objects, in QPixmap::setMask() and for QRegion.

A QBitmap is a QPixmap with a depth of 1. If a pixmap with a depth greater than 1 is assigned to a bitmap, the bitmap will be dithered automatically. A QBitmap is guaranteed to always have the depth 1, unless it is QPixmap::isNull() which has depth 0.

When drawing in a QBitmap (or QPixmap with depth 1), we recommend using the QColor objects Qt::color0 and Qt::color1. Painting with color0 sets the bitmap bits to 0, and painting with color1 sets the bits to 1. For a bitmap, 0-bits indicate background (or transparent) and 1-bits indicate foreground (or opaque). Using the black and white QColor objects make no sense because the QColor::pixel() value is not necessarily 0 for black and 1 for white.

The QBitmap can be transformed (translated, scaled, sheared or rotated) using xForm().

Just like the QPixmap class, QBitmap is optimized by the use of implicit sharing, so it is very efficient to pass QBitmap objects as arguments.

See also QPixmap, QPainter::drawPixmap(), bitBlt(), Shared Classes, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QBitmap::QBitmap ()

Constructs a null bitmap.

See also QPixmap::isNull().

QBitmap::QBitmap ( int w, int h, bool clear = FALSE, QPixmap::Optimization optimization = QPixmap::DefaultOptim )

Constructs a bitmap with width w and height h.

The contents of the bitmap is uninitialized if clear is FALSE; otherwise it is filled with pixel value 0 (the QColor Qt::color0).

The optional optimization argument specifies the optimization setting for the bitmap. The default optimization should be used in most cases. Games and other pixmap-intensive applications may benefit from setting this argument; see QPixmap::Optimization.

See also QPixmap::setOptimization() and QPixmap::setDefaultOptimization().

QBitmap::QBitmap ( const QSize & size, bool clear = FALSE, QPixmap::Optimization optimization = QPixmap::DefaultOptim )

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

Constructs a bitmap with the size size.

The contents of the bitmap is uninitialized if clear is FALSE; otherwise it is filled with pixel value 0 (the QColor Qt::color0).

The optional optimization argument specifies the optimization setting for the bitmap. The default optimization should be used in most cases. Games and other pixmap-intensive applications may benefit from setting this argument; see QPixmap::Optimization.

QBitmap::QBitmap ( int w, int h, const uchar * bits, bool isXbitmap = FALSE )

Constructs a bitmap with width w and height h and sets the contents to bits.

The isXbitmap flag should be TRUE if bits was generated by the X11 bitmap program. The X bitmap bit order is little endian. The QImage documentation discusses bit order of monochrome images.

Example (creates an arrow bitmap):

        uchar arrow_bits[] = { 0x3f, 0x1f, 0x0f, 0x1f, 0x3b, 0x71, 0xe0, 0xc0 };
        QBitmap bm( 8, 8, arrow_bits, TRUE );

QBitmap::QBitmap ( const QSize & size, const uchar * bits, bool isXbitmap = FALSE )

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

Constructs a bitmap with the size size and sets the contents to bits.

The isXbitmap flag should be TRUE if bits was generated by the X11 bitmap program. The X bitmap bit order is little endian. The QImage documentation discusses bit order of monochrome images.

QBitmap::QBitmap ( const QBitmap & bitmap )

Constructs a bitmap that is a copy of bitmap.

QBitmap::QBitmap ( const QString & fileName, const char * format = 0 )

Constructs a pixmap from the file fileName. If the file does not exist or is of an unknown format, the bitmap becomes a null bitmap.

The parameters fileName and format are passed on to QPixmap::load(). Dithering will be performed if the file format uses more than 1 bit per pixel.

See also QPixmap::isNull(), QPixmap::load(), QPixmap::loadFromData(), QPixmap::save() and QPixmap::imageFormat().

QBitmap & QBitmap::operator= ( const QBitmap & bitmap )

Assigns the bitmap bitmap to this bitmap and returns a reference to this bitmap.

QBitmap & QBitmap::operator= ( const QPixmap & pixmap )

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

Assigns the pixmap pixmap to this bitmap and returns a reference to this bitmap.

Dithering will be performed if the pixmap has a QPixmap::depth() greater than 1.

QBitmap & QBitmap::operator= ( const QImage & image )

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

Converts the image image to a bitmap and assigns the result to this bitmap. Returns a reference to the bitmap.

Dithering will be performed if the image has a QImage::depth() greater than 1.

QBitmap QBitmap::xForm ( const QWMatrix & matrix ) const

Returns a transformed copy of this bitmap by using matrix.

This function does exactly the same as QPixmap::xForm(), except that it returns a QBitmap instead of a QPixmap.

See also QPixmap::xForm().

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


qbitmap.h Include File

qbitmap.h

This is the verbatim text of the qbitmap.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qbitmap.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QBitmap class
**
** Created : 941020
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBITMAP_H
#define QBITMAP_H

#ifndef QT_H
#include "qpixmap.h"
#endif // QT_H

class Q_EXPORT QBitmap : public QPixmap
{
public:
    QBitmap();
    QBitmap( int w, int h,  bool clear = FALSE,
         QPixmap::Optimization = QPixmap::DefaultOptim );
    QBitmap( const QSize &, bool clear = FALSE,
         QPixmap::Optimization = QPixmap::DefaultOptim );
    QBitmap( int w, int h,  const uchar *bits, bool isXbitmap=FALSE );
    QBitmap( const QSize &, const uchar *bits, bool isXbitmap=FALSE );
    QBitmap( const QBitmap & );
#ifndef QT_NO_IMAGEIO
    QBitmap( const QString &fileName, const char *format=0 );
#endif
    QBitmap &operator=( const QBitmap & );
    QBitmap &operator=( const QPixmap & );
    QBitmap &operator=( const QImage  & );

#ifndef QT_NO_PIXMAP_TRANSFORMATION
    QBitmap  xForm( const QWMatrix & ) const;
#endif
};

#endif // QBITMAP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QBitmap Member List

Complete Member List for QBitmap

This is the complete list of member functions for QBitmap, including inherited members.

  • QBitmap()
  • cmd()
  • convertFromImage()
  • convertToImage()
  • createHeuristicMask()
  • defaultDepth()
  • defaultOptimization()
  • depth()
  • detach()
  • fill()
  • grabWidget()
  • grabWindow()
  • handle()
  • height()
  • imageFormat()
  • isExtDev()
  • isNull()
  • isQBitmap()
  • load()
  • loadFromData()
  • mask()
  • metric()
  • operator=()
  • optimization()
  • paintingActive()
  • rect()
  • resize()
  • save()
  • selfMask()
  • serialNumber()
  • setDefaultOptimization()
  • setMask()
  • setOptimization()
  • size()
  • trueMatrix()
  • width()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xForm()


QBitVal Class

QBitVal Class Reference

The QBitVal class is an internal class, used with QBitArray. More...

#include <qbitarray.h>

List of all member functions.

Public Members

  • QBitVal ( QBitArray * a, uint i )
  • operator int ()
  • QBitVal & operator= ( const QBitVal & v )
  • QBitVal & operator= ( bool v )

Detailed Description

The QBitVal class is an internal class, used with QBitArray.

The QBitVal is required by the indexing [] operator on bit arrays. Don't use it in any other context.

See also Collection Classes.

Member Function Documentation

QBitVal::QBitVal ( QBitArray * a, uint i )

Constructs a reference to element i in the QBitArray a. This is what QBitArray::operator[] constructs its return value with.

QBitVal::operator int ()

Returns the value referenced by the QBitVal.

QBitVal & QBitVal::operator= ( const QBitVal & v )

Sets the value referenced by the QBitVal to that referenced by QBitVal v.

QBitVal & QBitVal::operator= ( bool v )

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

Sets the value referenced by the QBitVal to v.

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


QBitVal Member List

Complete Member List for QBitVal

This is the complete list of member functions for QBitVal, including inherited members.

  • QBitVal()
  • operator int()
  • operator=()


QBoxLayout Class

QBoxLayout Class Reference

The QBoxLayout class lines up child widgets horizontally or vertically. More...

#include <qlayout.h>

Inherits QLayout.

Inherited by QHBoxLayout and QVBoxLayout.

List of all member functions.

Public Members

  • enum Direction { LeftToRight, RightToLeft, TopToBottom, BottomToTop, Down = TopToBottom, Up = BottomToTop }
  • QBoxLayout ( QWidget * parent, Direction d, int margin = 0, int spacing = -1, const char * name = 0 )
  • QBoxLayout ( QLayout * parentLayout, Direction d, int spacing = -1, const char * name = 0 )
  • QBoxLayout ( Direction d, int spacing = -1, const char * name = 0 )
  • ~QBoxLayout ()
  • virtual void addItem ( QLayoutItem * item )
  • Direction direction () const
  • void setDirection ( Direction direction )
  • void addSpacing ( int size )
  • void addStretch ( int stretch = 0 )
  • void addWidget ( QWidget * widget, int stretch = 0, int alignment = 0 )
  • void addLayout ( QLayout * layout, int stretch = 0 )
  • void addStrut ( int size )
  • void insertSpacing ( int index, int size )
  • void insertStretch ( int index, int stretch = 0 )
  • void insertWidget ( int index, QWidget * widget, int stretch = 0, int alignment = 0 )
  • void insertLayout ( int index, QLayout * layout, int stretch = 0 )
  • bool setStretchFactor ( QWidget * w, int stretch )
  • bool setStretchFactor ( QLayout * l, int stretch )
  • virtual QSize sizeHint () const
  • virtual QSize minimumSize () const
  • virtual QSize maximumSize () const
  • virtual bool hasHeightForWidth () const
  • virtual int heightForWidth ( int w ) const
  • virtual QSizePolicy::ExpandData expanding () const
  • virtual void invalidate ()
  • virtual void setGeometry ( const QRect & r )
  • int findWidget ( QWidget * w )

Protected Members

  • void insertItem ( int index, QLayoutItem * item )

Detailed Description

The QBoxLayout class lines up child widgets horizontally or vertically.

QBoxLayout takes the space it gets (from its parent layout or from the mainWidget()), divides it up into a row of boxes, and makes each managed widget fill one box.

Horizontal box with five child widgets

If the QBoxLayout's orientation is Horizontal the boxes are placed in a row, with suitable sizes. Each widget (or other box) will get at least its minimum size and at most its maximum size. Any excess space is shared according to the stretch factors (more about that below).

Vertical box with five child widgets

If the QBoxLayout's orientation is Vertical, the boxes are placed in a column, again with suitable sizes.

The easiest way to create a QBoxLayout is to use one of the convenience classes, e.g. QHBoxLayout (for Horizontal boxes) or QVBoxLayout (for Vertical boxes). You can also use the QBoxLayout constructor directly, specifying its direction as LeftToRight, Down, RightToLeft or Up.

If the QBoxLayout is not the top-level layout (i.e. it is not managing all of the widget's area and children), you must add it to its parent layout before you can do anything with it. The normal way to add a layout is by calling parentLayout->addLayout().

Once you have done this, you can add boxes to the QBoxLayout using one of four functions:

  • addWidget() to add a widget to the QBoxLayout and set the widget's stretch factor. (The stretch factor is along the row of boxes.)

  • addSpacing() to create an empty box; this is one of the functions you use to create nice and spacious dialogs. See below for ways to set margins.

  • addStretch() to create an empty, stretchable box.

  • addLayout() to add a box containing another QLayout to the row and set that layout's stretch factor.

Use insertWidget(), insertSpacing(), insertStretch() or insertLayout() to insert a box at a specified position in the layout.

QBoxLayout also includes two margin widths:

  • setMargin() sets the width of the outer border. This is the width of the reserved space along each of the QBoxLayout's four sides.
  • setSpacing() sets the width between neighboring boxes. (You can use addSpacing() to get more space at a particular spot.)

The margin defaults to 0. The spacing defaults to the same as the margin width for a top-level layout, or to the same as the parent layout. Both are parameters to the constructor.

To remove a widget from a layout, either delete it or reparent it with QWidget::reparent(). Hiding a widget with QWidget::hide() also effectively removes the widget from the layout, until QWidget::show() is called.

You will almost always want to use QVBoxLayout and QHBoxLayout rather than QBoxLayout because of their convenient constructors.

See also QGrid, Layout Overview, Widget Appearance and Style and Layout Management.

Member Type Documentation

QBoxLayout::Direction

This type is used to determine the direction of a box layout.

  • QBoxLayout::LeftToRight - Horizontal, from left to right
  • QBoxLayout::RightToLeft - Horizontal, from right to left
  • QBoxLayout::TopToBottom - Vertical, from top to bottom
  • QBoxLayout::Down - The same as TopToBottom
  • QBoxLayout::BottomToTop - Vertical, from bottom to top
  • QBoxLayout::Up - The same as BottomToTop

Member Function Documentation

QBoxLayout::QBoxLayout ( QWidget * parent, Direction d, int margin = 0, int spacing = -1, const char * name = 0 )

Constructs a new QBoxLayout with direction d and main widget parent. parent may not be 0.

The margin is the number of pixels between the edge of the widget and its managed children. The spacing is the default number of pixels between neighboring children. If spacing is -1 the value of margin is used for spacing.

name is the internal object name.

See also direction().

QBoxLayout::QBoxLayout ( QLayout * parentLayout, Direction d, int spacing = -1, const char * name = 0 )

Constructs a new QBoxLayout called name, with direction d, and inserts it into parentLayout.

The spacing is the default number of pixels between neighboring children. If spacing is -1, the layout will inherit its parent's spacing().

QBoxLayout::QBoxLayout ( Direction d, int spacing = -1, const char * name = 0 )

Constructs a new QBoxLayout called name, with direction d.

If spacing is -1, the layout will inherit its parent's spacing(); otherwise spacing is used.

You must insert this box into another layout.

QBoxLayout::~QBoxLayout ()

Destroys this box layout.

The layout's widgets are not destroyed.

void QBoxLayout::addItem ( QLayoutItem * item ) [virtual]

Adds item to the end of this box layout.

Examples: chart/optionsform.cpp and chart/setdataform.cpp.

Reimplemented from QLayout.

void QBoxLayout::addLayout ( QLayout * layout, int stretch = 0 )

Adds layout to the end of the box, with serial stretch factor stretch.

See also insertLayout(), setAutoAdd(), addWidget() and addSpacing().

Examples: chart/optionsform.cpp, chart/setdataform.cpp, fonts/simple-qfont-demo/viewer.cpp, listbox/listbox.cpp and tictac/tictac.cpp.

void QBoxLayout::addSpacing ( int size )

Adds a non-stretchable space with size size to the end of this box layout. QBoxLayout provides default margin and spacing. This function adds additional space.

See also insertSpacing() and addStretch().

Example: listbox/listbox.cpp.

void QBoxLayout::addStretch ( int stretch = 0 )

Adds a stretchable space with zero minimum size and stretch factor stretch to the end of this box layout.

See also addSpacing().

Examples: layout/layout.cpp, listbox/listbox.cpp and t13/gamebrd.cpp.

void QBoxLayout::addStrut ( int size )

Limits the perpendicular dimension of the box (e.g. height if the box is LeftToRight) to a minimum of size. Other constraints may increase the limit.

void QBoxLayout::addWidget ( QWidget * widget, int stretch = 0, int alignment = 0 )

Adds widget to the end of this box layout, with a stretch factor of stretch and alignment alignment.

The stretch factor applies only in the direction of the QBoxLayout, and is relative to the other boxes and widgets in this QBoxLayout. Widgets and boxes with higher stretch factors grow more.

If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved.

Alignment is specified by alignment which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

From Qt 3.0, the alignment parameter is interpreted more aggressively than in previous versions of Qt. A non-default alignment now indicates that the widget should not grow to fill the available space, but should be sized according to sizeHint().

See also insertWidget(), setAutoAdd(), addLayout() and addSpacing().

Examples: chart/optionsform.cpp, fonts/simple-qfont-demo/viewer.cpp, layout/layout.cpp, lineedits/lineedits.cpp, listbox/listbox.cpp, t13/gamebrd.cpp and t13/lcdrange.cpp.

Direction QBoxLayout::direction () const

Returns the direction of the box. addWidget() and addSpacing() work in this direction; the stretch stretches in this direction.

See also QBoxLayout::Direction, addWidget() and addSpacing().

QSizePolicy::ExpandData QBoxLayout::expanding () const [virtual]

Returns the expansiveness of this layout.

Reimplemented from QLayout.

int QBoxLayout::findWidget ( QWidget * w )

Searches for widget w in this layout (not including child layouts).

Returns the index of w, or -1 if w is not found.

bool QBoxLayout::hasHeightForWidth () const [virtual]

Returns TRUE if this layout's preferred height depends on its width; otherwise returns FALSE.

Reimplemented from QLayoutItem.

int QBoxLayout::heightForWidth ( int w ) const [virtual]

Returns the layout's preferred height when it is w pixels wide.

Reimplemented from QLayoutItem.

void QBoxLayout::insertItem ( int index, QLayoutItem * item ) [protected]

Inserts item into this box layout at position index. If index is negative, the item is added at the end.

Warning: Does not call QLayout::insertChildLayout() if item is a QLayout.

See also addItem() and findWidget().

void QBoxLayout::insertLayout ( int index, QLayout * layout, int stretch = 0 )

Inserts layout at position index, with stretch factor stretch. If index is negative, the layout is added at the end.

See also setAutoAdd(), insertWidget() and insertSpacing().

void QBoxLayout::insertSpacing ( int index, int size )

Inserts a non-stretchable space at position index, with size size. If index is negative the space is added at the end.

The box layout has default margin and spacing. This function adds additional space.

See also insertStretch().

void QBoxLayout::insertStretch ( int index, int stretch = 0 )

Inserts a stretchable space at position index, with zero minimum size and stretch factor stretch. If index is negative the space is added at the end.

See also insertSpacing().

void QBoxLayout::insertWidget ( int index, QWidget * widget, int stretch = 0, int alignment = 0 )

Inserts widget at position index, with stretch factor stretch and alignment alignment. If index is negative, the widget is added at the end.

The stretch factor applies only in the direction of the QBoxLayout, and is relative to the other boxes and widgets in this QBoxLayout. Widgets and boxes with higher stretch factors grow more.

If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved.

Alignment is specified by alignment, which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

From Qt 3.0, the alignment parameter is interpreted more aggressively than in previous versions of Qt. A non-default alignment now indicates that the widget should not grow to fill the available space, but should be sized according to sizeHint().

See also setAutoAdd(), insertLayout() and insertSpacing().

void QBoxLayout::invalidate () [virtual]

Resets cached information.

Reimplemented from QLayout.

QSize QBoxLayout::maximumSize () const [virtual]

Returns the maximum size needed by this box layout.

Reimplemented from QLayout.

QSize QBoxLayout::minimumSize () const [virtual]

Returns the minimum size needed by this box layout.

Reimplemented from QLayout.

void QBoxLayout::setDirection ( Direction direction )

Sets the direction of this layout to direction.

void QBoxLayout::setGeometry ( const QRect & r ) [virtual]

Resizes managed widgets within the rectangle r.

Reimplemented from QLayout.

bool QBoxLayout::setStretchFactor ( QWidget * w, int stretch )

Sets the stretch factor for widget w to stretch and returns TRUE if w is found in this layout (not including child layouts); otherwise returns FALSE.

bool QBoxLayout::setStretchFactor ( QLayout * l, int stretch )

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

Sets the stretch factor for the layout l to stretch and returns TRUE if l is found in this layout (not including child layouts); otherwise returns FALSE.

QSize QBoxLayout::sizeHint () const [virtual]

Returns the preferred size of this box layout.

Reimplemented from QLayoutItem.

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


QBoxLayout Member List

Complete Member List for QBoxLayout

This is the complete list of member functions for QBoxLayout, including inherited members.

  • QBoxLayout()
  • ~QBoxLayout()
  • activate()
  • add()
  • addChildLayout()
  • addItem()
  • addLayout()
  • addSpacing()
  • addStretch()
  • addStrut()
  • addWidget()
  • alignment()
  • alignmentRect()
  • autoAdd()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteAllItems()
  • deleteLater()
  • destroyed()
  • direction()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • expanding()
  • findWidget()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • highPriority()
  • inherits()
  • insertChild()
  • insertItem()
  • insertLayout()
  • insertSpacing()
  • insertStretch()
  • insertWidget()
  • installEventFilter()
  • invalidate()
  • isA()
  • isEmpty()
  • isEnabled()
  • isTopLevel()
  • isWidgetType()
  • iterator()
  • killTimer()
  • killTimers()
  • layout()
  • mainWidget()
  • margin()
  • maximumSize()
  • menuBar()
  • metaObject()
  • minimumSize()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • resizeMode()
  • sender()
  • setAlignment()
  • setAutoAdd()
  • setDirection()
  • setEnabled()
  • setGeometry()
  • setMargin()
  • setMenuBar()
  • setName()
  • setProperty()
  • setResizeMode()
  • setSpacing()
  • setStretchFactor()
  • setSupportsMargin()
  • signalsBlocked()
  • sizeHint()
  • spacerItem()
  • spacing()
  • startTimer()
  • supportsMargin()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()


QBrush Class

QBrush Class Reference

The QBrush class defines the fill pattern of shapes drawn by a QPainter. More...

#include <qbrush.h>

Inherits Qt.

List of all member functions.

Public Members

  • QBrush ()
  • QBrush ( BrushStyle style )
  • QBrush ( const QColor & color, BrushStyle style = SolidPattern )
  • QBrush ( const QColor & color, const QPixmap & pixmap )
  • QBrush ( const QBrush & b )
  • ~QBrush ()
  • QBrush & operator= ( const QBrush & b )
  • BrushStyle style () const
  • void setStyle ( BrushStyle s )
  • const QColor & color () const
  • void setColor ( const QColor & c )
  • QPixmap * pixmap () const
  • void setPixmap ( const QPixmap & pixmap )
  • bool operator== ( const QBrush & b ) const
  • bool operator!= ( const QBrush & b ) const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QBrush & b )
  • QDataStream & operator>> ( QDataStream & s, QBrush & b )

Detailed Description

The QBrush class defines the fill pattern of shapes drawn by a QPainter.

A brush has a style and a color. One of the brush styles is a custom pattern, which is defined by a QPixmap.

The brush style defines the fill pattern. The default brush style is NoBrush (depending on how you construct a brush). This style tells the painter to not fill shapes. The standard style for filling is SolidPattern.

The brush color defines the color of the fill pattern. The QColor documentation lists the predefined colors.

Use the QPen class for specifying line/outline styles.

Example:

        QPainter painter;
        QBrush   brush( yellow );           // yellow solid pattern
        painter.begin( &anyPaintDevice );   // paint something
        painter.setBrush( brush );          // set the yellow brush
        painter.setPen( NoPen );            // do not draw outline
        painter.drawRect( 40,30, 200,100 ); // draw filled rectangle
        painter.setBrush( NoBrush );        // do not fill
        painter.setPen( black );            // set black pen, 0 pixel width
        painter.drawRect( 10,10, 30,20 );   // draw rectangle outline
        painter.end();                      // painting done

See the setStyle() function for a complete list of brush styles.

See also QPainter, QPainter::setBrush(), QPainter::setBrushOrigin(), Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QBrush::QBrush ()

Constructs a default black brush with the style NoBrush (will not fill shapes).

QBrush::QBrush ( BrushStyle style )

Constructs a black brush with the style style.

See also setStyle().

QBrush::QBrush ( const QColor & color, BrushStyle style = SolidPattern )

Constructs a brush with the color color and the style style.

See also setColor() and setStyle().

QBrush::QBrush ( const QColor & color, const QPixmap & pixmap )

Constructs a brush with the color color and a custom pattern stored in pixmap.

The color will only have an effect for monochrome pixmaps, i.e. for QPixmap::depth() == 1.

See also setColor() and setPixmap().

QBrush::QBrush ( const QBrush & b )

Constructs a brush that is a shallow copy of b.

QBrush::~QBrush ()

Destroys the brush.

const QColor & QBrush::color () const

Returns the brush color.

See also setColor().

bool QBrush::operator!= ( const QBrush & b ) const

Returns TRUE if the brush is different from b; otherwise returns FALSE.

Two brushes are different if they have different styles, colors or pixmaps.

See also operator==().

QBrush & QBrush::operator= ( const QBrush & b )

Assigns b to this brush and returns a reference to this brush.

bool QBrush::operator== ( const QBrush & b ) const

Returns TRUE if the brush is equal to b; otherwise returns FALSE.

Two brushes are equal if they have equal styles, colors and pixmaps.

See also operator!=().

QPixmap * QBrush::pixmap () const

Returns a pointer to the custom brush pattern, or 0 if no custom brush pattern has been set.

See also setPixmap().

Example: richtext/richtext.cpp.

void QBrush::setColor ( const QColor & c )

Sets the brush color to c.

See also color() and setStyle().

Example: picture/picture.cpp.

void QBrush::setPixmap ( const QPixmap & pixmap )

Sets the brush pixmap to pixmap. The style is set to CustomPattern.

The current brush color will only have an effect for monochrome pixmaps, i.e. for QPixmap::depth() == 1.

See also pixmap() and color().

Example: richtext/richtext.cpp.

void QBrush::setStyle ( BrushStyle s )

Sets the brush style to s.

The brush styles are:

Pattern | Meaning
NoBrush | will not fill shapes (default).
SolidPattern | solid (100%) fill pattern.
Dense1Pattern | 94% fill pattern.
Dense2Pattern | 88% fill pattern.
Dense3Pattern | 63% fill pattern.
Dense4Pattern | 50% fill pattern.
Dense5Pattern | 37% fill pattern.
Dense6Pattern | 12% fill pattern.
Dense7Pattern | 6% fill pattern.
HorPattern | horizontal lines pattern.
VerPattern | vertical lines pattern.
CrossPattern | crossing lines pattern.
BDiagPattern | diagonal lines (directed /) pattern.
FDiagPattern | diagonal lines (directed \) pattern.
DiagCrossPattern | diagonal crossing lines pattern.
CustomPattern | set when a pixmap pattern is being used.

On Windows, only the dense patterns are transparent.

See the Detailed Description for a picture of all the styles.

See also style().

BrushStyle QBrush::style () const

Returns the brush style.

See also setStyle().

Related Functions

QDataStream & operator<< ( QDataStream & s, const QBrush & b )

Writes the brush b to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QBrush & b )

Reads the brush b from the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

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


qbrush.h Include File

qbrush.h

This is the verbatim text of the qbrush.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qbrush.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QBrush class
**
** Created : 940112
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBRUSH_H
#define QBRUSH_H

#ifndef QT_H
#include "qcolor.h"
#include "qshared.h"
#endif // QT_H

class Q_EXPORT QBrush: public Qt
{
friend class QPainter;
public:
    QBrush();
    QBrush( BrushStyle );
    QBrush( const QColor &, BrushStyle=SolidPattern );
    QBrush( const QColor &, const QPixmap & );
    QBrush( const QBrush & );
   ~QBrush();
    QBrush &operator=( const QBrush & );

    BrushStyle	style()	 const		{ return data->style; }
    void	setStyle( BrushStyle );
    const QColor &color()const		{ return data->color; }
    void	setColor( const QColor & );
    QPixmap    *pixmap() const		{ return data->pixmap; }
    void	setPixmap( const QPixmap & );

    bool	operator==( const QBrush &p ) const;
    bool	operator!=( const QBrush &b ) const
                    { return !(operator==(b)); }

private:
    QBrush	copy()	const;
    void	detach();
    void	init( const QColor &, BrushStyle );
    struct QBrushData : public QShared {	// brush data
    BrushStyle style;
    QColor	  color;
    QPixmap	 *pixmap;
    } *data;
};

/*****************************************************************************
  QBrush stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QBrush & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QBrush & );
#endif

#endif // QBRUSH_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QBrush Member List

Complete Member List for QBrush

This is the complete list of member functions for QBrush, including inherited members.

  • QBrush()
  • ~QBrush()
  • color()
  • operator!=()
  • operator=()
  • operator==()
  • pixmap()
  • setColor()
  • setPixmap()
  • setStyle()
  • style()


QBuffer类

QBuffer类参考

QBuffer类是一个操作QByteArray的输入/输出设备。 详情请见……

#include <qbuffer.h>

继承了QIODevice。

所有成员函数的列表。

公有成员

  • QBuffer ()
  • QBuffer ( QByteArray buf )
  • ~QBuffer ()
  • QByteArray buffer () const
  • bool setBuffer ( QByteArray buf )
  • virtual Q_LONG writeBlock ( const char * p, Q_ULONG len )
  • Q_LONG writeBlock ( const QByteArray & data )

详细描述

QBuffer类是一个操作QByteArray的输入/输出设备。

QBuffer是用来读写内存缓存的。它通常与QTextStream或QDataStream一起使用。QBuffer有一个相关联的QByteArray用来存储缓冲数据。缓冲的大小（size()）会根据所写的数据自动调整。

构造函数QBuffer(QByteArray)以一个现有的字节数组创建一个QBuffer。字节数组也可以由setBuffer()来设置。向QBuffer写将会更改初始字节数组，因为QByteArray是明确共享。

在使用之前使用open()来打开缓存并且设置模式（只读、只写等等）。close()可以关闭缓存。在重新打开或者调用setBuffer()之前缓存必须被关闭。

使用QBuffer的一个普通方式是通过QDataStream或QTextStream，它们可以通过一个QBuffer参数来构造。为了方便，QDataStream和QTextStream也可以使用一个QByteArray参数来构造。这些构造函数创建并且打开一个内部的QBuffer。

注意QTextStream也可以操作QString（一个Unicode字符串），而QBuffer不能。

你也可以直接通过标准的QIODevice函数readBlock()、writeBlock()、readLine()、at(),、getch()、putch()和ungetch()来使用QBuffer。

也可以参考QFile、QDataStream、QTextStream、QByteArray、共享类、 集合类和输入/输出和网络。

成员函数文档

QBuffer::QBuffer ()

构造一个空的缓存。

QBuffer::QBuffer ( QByteArray buf )

操作buf来构造一个缓存。 如果你使用写模式（IO_WriteOnly或者IO_ReadWrite）打开缓存并且写一些东西到缓存，buf将被修改。

实例：

    QCString str = "abc";
    QBuffer b( str );
    b.open( IO_WriteOnly );
    b.at( 3 ); // 定位到第四个字符（终结符\0）
    b.writeBlock( "def", 4 ); // 写入“def”，包括终结符\0
    b.close();
    // 现在，str就是“abcdef”和一个终结符\0

也可以参考setBuffer()。

QBuffer::~QBuffer ()

析构缓存。

QByteArray QBuffer::buffer () const

返回这个缓存的字节数组。

也可以参考a href="#setBuffer">setBuffer()。

bool QBuffer::setBuffer ( QByteArray buf )

把缓存的内容替换为buf。

当isOpen()为真时，这个操作也许不能被完成。

注意如果你使用写模式（IO_WriteOnly或者IO_ReadWrite）打开缓存并且写一些东西到缓存，buf也会被修改因为QByteArray是一个明显共享类。

也可以参考buffer()、open()和close()。

Q_LONG QBuffer::writeBlock ( const char * p, Q_ULONG len ) [虚]

把p中的len字节写到缓存的当前索引位置，如果需要的话，将会覆盖原有的数据并且扩充缓存。返回实际所写的字节数量。

如果发生任何错误，返回-1。

也可以参卡readBlock()。

Reimplemented from QIODevice.

Q_LONG QBuffer::writeBlock ( const QByteArray & data )

这是一个重载成员函数，提供方便。它的行为和上面的函数基本一致。

这个方便的函数使用data与调用writeBlock( data.data(), data.size() )是一样的。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qbuffer.h包含文件

qbuffer.h

这里是qbuffer.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qbuffer.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QBuffer class
**
** Created : 930812
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBUFFER_H
#define QBUFFER_H

#ifndef QT_H
#include "qiodevice.h"
#include "qstring.h"
#endif // QT_H

class Q_EXPORT QBuffer : public QIODevice
{
public:
    QBuffer();
    QBuffer( QByteArray );
   ~QBuffer();

    QByteArray buffer() const;
    bool  setBuffer( QByteArray );

    bool  open( int );
    void  close();
    void  flush();

    Offset size() const;
    Offset at() const;
    bool  at( Offset );

    Q_LONG	  readBlock( char *p, Q_ULONG );
    Q_LONG	  writeBlock( const char *p, Q_ULONG );
    Q_LONG	  writeBlock( const QByteArray& data )
          { return QIODevice::writeBlock(data); }
    Q_LONG	  readLine( char *p, Q_ULONG );

    int	  getch();
    int	  putch( int );
    int	  ungetch( int );

protected:
    QByteArray a;

private:
    uint  a_len;
    uint  a_inc;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QBuffer( const QBuffer & );
    QBuffer &operator=( const QBuffer & );
#endif
};

inline QByteArray QBuffer::buffer() const
{ return a; }

inline QIODevice::Offset QBuffer::size() const
{ return (Offset)a.size(); }

inline QIODevice::Offset QBuffer::at() const
{ return ioIndex; }

#endif // QBUFFER_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QBuffer成员列表

完整的QBuffer成员列表

这里是QBuffer成员函数的完整列表，包括继承的成员。

  • QBuffer()
  • ~QBuffer()
  • at()
  • atEnd()
  • buffer()
  • close()
  • flags()
  • flush()
  • getch()
  • isAsynchronous()
  • isBuffered()
  • isCombinedAccess()
  • isDirectAccess()
  • isInactive()
  • isOpen()
  • isRaw()
  • isReadWrite()
  • isReadable()
  • isSequentialAccess()
  • isSynchronous()
  • isTranslated()
  • isWritable()
  • mode()
  • open()
  • putch()
  • readAll()
  • readBlock()
  • readLine()
  • reset()
  • resetStatus()
  • setBuffer()
  • size()
  • state()
  • status()
  • ungetch()
  • writeBlock()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QButton类

QButton类参考

QButton类是按钮窗口部件的抽象基类，提供了按钮所共有的功能。 详情请见……

#include <qbutton.h>

继承了QWidget。

被QCheckBox、QPushButton、QRadioButton和QToolButton继承。

所有成员函数的列表。

公有成员

  • QButton ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QButton ()
  • QString text () const
  • virtual void setText ( const QString & )
  • const QPixmap * pixmap () const
  • virtual void setPixmap ( const QPixmap & )
  • QKeySequence accel () const
  • virtual void setAccel ( const QKeySequence & )
  • bool isToggleButton () const
  • enum ToggleType { SingleShot, Toggle, Tristate }
  • ToggleType toggleType () const
  • virtual void setDown ( bool )
  • bool isDown () const
  • bool isOn () const
  • enum ToggleState { Off, NoChange, On }
  • ToggleState state () const
  • bool autoResize () const (obsolete)
  • void setAutoResize ( bool ) (obsolete)
  • bool autoRepeat () const
  • virtual void setAutoRepeat ( bool )
  • bool isExclusiveToggle () const
  • QButtonGroup * group () const

公有槽

  • void animateClick ()
  • void toggle ()

信号

  • void pressed ()
  • void released ()
  • void clicked ()
  • void toggled ( bool on )
  • void stateChanged ( int state )

属性

  • QKeySequence accel - 与按钮有关的快捷键
  • bool autoRepeat - 是否能够自动重复
  • bool autoResize - 是否能够自动重定义大小 （废弃的）
  • bool down - 按钮是否被按下
  • bool exclusiveToggle - 按钮是否是排它的 （只读）
  • bool on - 按钮是否被切换 （只读）
  • QPixmap pixmap - 在按钮上显示的像素映射
  • QString text - 在按钮上显示的文本
  • bool toggleButton - 按钮是否是一个切换按钮 （只读）
  • ToggleState toggleState - 按钮是否被切换 （只读）
  • ToggleType toggleType - 按钮的切换类型 （只读）

保护成员

  • void setToggleButton ( bool b )
  • virtual void setToggleType ( ToggleType type )
  • void setOn ( bool on )
  • virtual void setState ( ToggleState s )
  • virtual bool hitButton ( const QPoint & pos ) const
  • virtual void drawButton ( QPainter * )
  • virtual void drawButtonLabel ( QPainter * )
  • virtual void paintEvent ( QPaintEvent * )

详细描述

QButton类是按钮窗口部件的抽象基类，提供了按钮所共有的功能。

如果你想创建一个按钮，请使用QPushButton。

QButton类实现了一个抽象按钮，并且让它的子类来指定如何回复用户的行为和如何画按钮。

QButton提供了推动和切换按钮。QRadioButton和QCheckBox类只提供了切换按钮，QPushButton和QToolButton提供了切换按钮和推动按钮。

任何按钮都可以有一个文本的或者像素映射的标签。setText()设置按钮为一个文本按钮并且setPixmap()设置它为一个像素映射按钮。文本/像素映射的使用中需要创建当按钮被取消使用时所需的“失效的”外观。

QButton提供了按钮所要用到的绝大多数状态：

  • isDown()决定按钮是否被按下。
  • isOn()决定按钮是否是开的。只有切换按钮才能被切换为开或关（请看下面）。
  • isEnabled()决定按钮是否可以被用户按下。
  • setAutoRepeat()决定如果用户按下按钮，按钮是否可以自动回复。
  • setToggleButton()决定按钮是否是一个切换按钮。

isDown()和isOn()的不同点如下： 当用户点击一个切换按钮并且把它切换为开，按钮首先被按下并且然后被释放变为开状态。当用户再次点击（切换为关），按钮首先移动到被按下状态，然后变为关状态（isOn()和isDown()都为假）。

默认按钮（在很多对话框中被使用的）由QPushButton::setDefault()和QPushButton::setAutoDefault()提供。

QButton提供五个信号：

  1. 当鼠标光标在按钮内，鼠标左键被按下时，pressed()被发送。
  2. 当鼠标左键被释放时，released()被发送。
  3. 当按钮首先被按下然后又被释放或者快捷键被按下，或者当animateClick()被调用时，clicked()被发送。
  4. 当切换按钮的状态变化时，toggled(bool)被发送。
  5. 当一个三态切换按钮的状态变化时，stateChanged(int)被发送。

如果一个文本按钮的文本中有“&”，QButton会创建一个自动快捷键。下面的代码创建一个标签为“Rock & Roll”（c下面有下划线）的推动按钮。这个按钮有一个自动快捷键，Alt+C：

    QPushButton *p = new QPushButton( "Ro&ck && Roll", this );

在这个实例中，当用户按下Alt+C时，按钮将会调用animateClick()。

你也可以使用setAccel()函数来设置一个定制的快捷键。这个对于绝大多数像素映射按钮是很有用的，因为它们没有自动快捷键。

    QPushButton *p;
    p->setPixmap( QPixmap("print.png") );
    p->setAccel( ALT+Key_F7 );

Qt所提供的所有按钮（QPushButton、QToolButton、QCheckBox和QRadioButton）都能够既显示文本也显示像素映射。

为了继承QButton，你至少不得不重新实现drawButton()（绘制按钮的外形）和drawButtonLabel()（绘制它的文本或像素映射）。通常也被建议重新实现sizeHint()，并且有时也被建议重新实现hitButton()（为了决定一个按钮按下是否在按钮内）。

为了减少闪烁，QButton::paintEvent()设置drawButton()中所要画的一个像素映射。你不用在QButton的子类中重新实现paintEvent()，除非你想接管全部的绘制工作。

也可以参考QButtonGroup和抽象窗口部件类。

成员类型文档

QButton::ToggleState

这个枚举类型定义了一个切换按钮在任何时候的状态。可能的值如下：

  • QButton::Off - 按钮在“关”状态
  • QButton::NoChange - 按钮在默认/未改变状态
  • QButton::On - 按钮在“开”状态

QButton::ToggleType

这个枚举类型定义了按钮对一个鼠标/键盘按下可以做什么响应：

  • QButton::SingleShot - 按下按钮导致一个行为，然后按钮返回一个未按下状态。
  • QButton::Toggle - 按下按钮，在On和Off状态中切换。
  • QButton::Tristate - 按下按钮，在On、Off和NoChange状态中循环。

成员函数文档

QButton::QButton ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个父对象为parent并且名称为name，使用窗口部件标记f的标准按钮。

如果parent是一个QButtonGroup，这个构造函数将调用QButtonGroup::insert()。

QButton::~QButton ()

销毁这个按钮。

QKeySequence QButton::accel () const

返回这个按钮的相关快捷键。详细情况请参考“accel”属性。

void QButton::animateClick () [槽]

执行一个自动点击：按钮被按下并且在一小段时间后被释放。

pressed()、released()、clicked()、toggled()和stateChanged()信号在适当的时候被发送。

如果按钮是失效的，这个函数将不做任何事情。

也可以参考accel。

bool QButton::autoRepeat () const

如果autoRepeat生效，返回真，否则返回假。详细情况请参考“autoRepeat”属性。

bool QButton::autoResize () const

如果autoResize生效，返回真，否则返回假。详细情况请参考“autoResize”属性。

void QButton::clicked () [信号]

当按钮被激活时（比如，当鼠标光标在按钮中，按钮首先被按下并且然后被释放），或者当快捷键被按下时，或者animateClick()被调用时，这个信号被发送。如果你调用setDown()，这个信号不被发送。

如果你想把几个按钮连接到同一个槽中，QButtonGroup::clicked()信号可以做这样的工作。

也可以参考pressed()、released()、toggled()、autoRepeat和down。

实例：fonts/simple-qfont-demo/viewer.cpp、listbox/listbox.cpp、network/clientserver/client/client.cpp、network/ftpclient/ftpmainwindow.cpp、richtext/richtext.cpp、t2/main.cpp和t4/main.cpp。

void QButton::drawButton ( QPainter * ) [虚 保护]

绘制按钮。默认实现是不做任何事。

这个虚函数是通过子类的重新实现来绘制真正的按钮。这些重新实现被假定同时在同一点调用drawButtonLabel()。

也可以参考drawButtonLabel()和paintEvent()。

void QButton::drawButtonLabel ( QPainter * ) [虚 保护]

绘制按钮文本或者像素映射。

这个虚函数是通过子类的重新实现来绘制真正的按钮。它是由drawButton()调用的。

也可以参考drawButton()和paintEvent()。

QButtonGroup * QButton::group () const

返回这个按钮所属的按钮组的指针。

如果这个按钮不是任何一个QButtonGroup的成员，这个函数返回0。

也可以参考QButtonGroup。

bool QButton::hitButton ( const QPoint & pos ) const [虚 保护]

如果pos在可以点击的按钮的矩形中，返回真，或者如果在外面返回假。

默认情况下，可点击区域是整个窗口部件。尽管子类可以重新实现它。

bool QButton::isDown () const

如果按钮被按下，返回真，否则返回假。详细情况请参考“down”属性。

bool QButton::isExclusiveToggle () const

如果按钮是排它的，返回真，否则返回假。详细情况请参考“exclusiveToggle”属性。

bool QButton::isOn () const

如果按钮被切换，返回真，否则返回假。详细情况请参考“on”属性。

bool QButton::isToggleButton () const

如果按钮是一个切换按钮，返回真，否则返回假。详细情况请参考“toggleButton”属性。

void QButton::paintEvent ( QPaintEvent * ) [虚 保护]

drawButtonLabel(). 处理按钮的绘制事件。小的和有代表性的复杂按钮被使用双缓存绘制来减少闪烁。实际的绘制是在虚函数drawButton()和drawButtonLabel()中完成的。

也可以参考drawButton()和drawButtonLabel()。

从QWidget中重新实现的。

const QPixmap * QButton::pixmap () const

返回按钮中所显示的像素映射。详细情况请参考“pixmap”属性。

void QButton::pressed () [信号]

当按钮被按下的时候，这个信号被发送。

也可以参考released()和clicked()。

实例：network/httpd/httpd.cpp和popup/popup.cpp。

void QButton::released () [信号]

当按钮被释放的时候，这个信号被发送。

也可以参考pressed()、clicked()和toggled()。

void QButton::setAccel ( const QKeySequence & ) [虚]

设置按钮的相关快捷键。详细情况请参考“accel”属性。

void QButton::setAutoRepeat ( bool ) [虚]

设置autoRepeat是否生效。详细情况请参考“autoRepeat”属性。

void QButton::setAutoResize ( bool )

设置autoResize是否生效。详细情况请参考“autoResize”属性。

void QButton::setDown ( bool ) [虚]

设置按钮是否被按下。详细情况请参考“down”属性。

void QButton::setOn ( bool on ) [protected]

当on为真，设置这个按钮的状态为开，否则为关。

也可以参考toggleState。

void QButton::setPixmap ( const QPixmap & ) [虚]

设置按钮上显示的像素映射。详细情况请参考“pixmap”属性。

void QButton::setState ( ToggleState s ) [虚 保护]

设置按钮的状态为s。s可以为Off、NoChange或On。

void QButton::setText ( const QString & ) [虚]

设置按钮上显示的文本。详细情况请参考“text”属性。

void QButton::setToggleButton ( bool b ) [protected]

如果b为真，这个按钮变为一个切换按钮，如果b为假，这个按钮变为一个普通按钮。

也可以参考toggleButton。

void QButton::setToggleType ( ToggleType type ) [虚 保护]

设置按钮的切换类型为type。

type可以被设置为SingleShot、Toggle和TriState。

ToggleState QButton::state () const

如果按钮是被切换的，返回真，否则返回假。详细情况请参考“toggleState”属性。

void QButton::stateChanged ( int state ) [信号]

只要切换按钮改变状态，这个信号就被发送。如果按钮是开的，state为2，如果是“未改变”状态，为1，或者如果按钮是关的，为0。

这也许是一个用户行为的结果，toggle()槽激活，或者因为setState()或setOn()被调用。

也可以参考clicked()。

QString QButton::text () const

返回按钮上所显示的文本。详细情况请参考“text”属性。

void QButton::toggle () [槽]

切换一个切换按钮的状态。

也可以参考on、setOn()、toggled()和toggleButton。

ToggleType QButton::toggleType () const

返回按钮的切换类型。详细情况请参考“toggleType”属性。

void QButton::toggled ( bool on ) [信号]

只要切换按钮改变状态，这个信号就被发送。如果按钮是开的，on为真，或者如果按钮是关的，on为假。

这也许是一个用户行为的结果，toggle()槽被激活，或者因为setOn()被调用。

也可以参考clicked()。

实例：listbox/listbox.cpp。

属性文档

QKeySequence accel

这个属性保存的是按钮相关的快捷键。

如果没有快捷键被设置，这个属性为0。如果你设置这个属性为0，那么任何当前的快捷键都被删除。

使用setAccel()来设置这个属性值并且使用accel()来得到这个属性值。

bool autoRepeat

这个属性保存的是autoRepeat是否生效。

如果autoRepeat生效，那么如果按钮是按下的，clicked()信号会被定期发送。这个属性对切换按钮没有效果。autoRepeat默认是关闭的。

使用setAutoRepeat()来设置这个属性值并且使用autoRepeat()来得到这个属性值。

bool autoResize

这个属性保存的是autoResize是否生效。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

如果autoResize生效，那么只要内容发生改变，按钮就会重新定义自己的大小。

使用setAutoResize()来设置这个属性值并且使用autoResize()来得到这个属性值。

bool down

这个属性保存的是按钮是否被按下。

如果这个属性为真，按钮就被设置为被按下。如果你设置这个属性为真，信号pressed()和clicked()就不会被发送。这个属性默认为假。

使用setDown()来设置这个属性值并且使用isDown()来得到这个属性值。

bool exclusiveToggle

这个属性保存的是按钮是否是排它的。

如果这个属性为真并且这个按钮在一个QButtonGroup里，这个按钮只有在其它按钮之一被切换为开的时候，它自己才能被切换为关。这个属性默认为假。

使用isExclusiveToggle()来得到这个属性值。

bool on

这个属性保存的是按钮是否被切换。

这个属性只有对于切换按钮才能被设置。

使用isOn()来得到这个属性值。

QPixmap pixmap

这个属性保存的是按钮上显示的像素映射。

如果像素映射是单色的（比如，它是一个QBitmap或者它的深度为1）并且没有掩码，这个属性将设置像素映射为它自己的掩码。这样的目的是为了绘制对于切换按钮是很重要的透明位图。

如果没有像素映射被设置，pixmap()返回0。

使用setPixmap()来设置这个属性值并且使用pixmap()来得到这个属性值。

QString text

这个属性保存的是按钮上显示的文本。

如果按钮没有文本，这个属性将返回一个零字符串。如果文本中有一个“&”，那么一个使用紧随“&”之后的字母的快捷键将被创建。

没有默认文本。

使用setText()来设置这个属性值并且使用text().来得到这个属性值。

bool toggleButton

这个属性保存的是按钮是否是切换按钮。

默认值为假。

使用isToggleButton()来得到这个属性值。

ToggleState toggleState

这个属性保存的是按钮是否被切换。

如果这个属性被改变，那么它不会导致按钮被重新绘制。

使用state()来得到这个属性值。

ToggleType toggleType

这个属性保存的是按钮的切换类型。

默认切换类型是SingleShot。

使用toggleType()来得到这个属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qbutton.h包含文件

qbutton.h

这里是qbutton.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qbutton.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QButton widget class
**
** Created : 940206
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBUTTON_H
#define QBUTTON_H

#ifndef QT_H
#include "qwidget.h"
#include "qkeysequence.h"
#endif // QT_H

#ifndef QT_NO_BUTTON

class QButtonGroup;
class QToolBar;
class QButtonData;

class Q_EXPORT QButton : public QWidget
{
    Q_OBJECT
    Q_ENUMS( ToggleType ToggleState )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( QPixmap pixmap READ pixmap WRITE setPixmap )
    Q_PROPERTY( QKeySequence accel READ accel WRITE setAccel )
    Q_PROPERTY( bool toggleButton READ isToggleButton )
    Q_PROPERTY( ToggleType toggleType READ toggleType )
    Q_PROPERTY( bool down READ isDown WRITE setDown DESIGNABLE false  )
    Q_PROPERTY( bool on READ isOn )
    Q_PROPERTY( ToggleState toggleState READ state )
    Q_PROPERTY( bool autoResize READ autoResize WRITE setAutoResize DESIGNABLE false )
    Q_PROPERTY( bool autoRepeat READ autoRepeat WRITE setAutoRepeat )
    Q_PROPERTY( bool exclusiveToggle READ isExclusiveToggle )

public:
    QButton( QWidget* parent=0, const char* name=0, WFlags f=0 );
    ~QButton();

    QString text() const;
    virtual void setText( const QString &);
    const QPixmap *pixmap() const;
    virtual void setPixmap( const QPixmap & );

#ifndef QT_NO_ACCEL
    QKeySequence		accel()	const;
    virtual void	setAccel( const QKeySequence& );
#endif

    bool	isToggleButton() const;

    enum ToggleType { SingleShot, Toggle, Tristate };
    ToggleType	toggleType() const;

    virtual void setDown( bool );
    bool	isDown() const;

    bool	isOn() const;

    enum ToggleState { Off, NoChange, On };
    ToggleState	state() const;

#ifndef QT_NO_COMPAT
    bool	autoResize() const;
    void	setAutoResize( bool );
#endif

    bool	autoRepeat() const;
    virtual void setAutoRepeat( bool );

    bool	isExclusiveToggle() const;

    QButtonGroup *group() const;

public slots:
    void	animateClick();
    void	toggle();

signals:
    void	pressed();
    void	released();
    void	clicked();
    void	toggled( bool );
    void	stateChanged( int );

protected:
    void	setToggleButton( bool );
    virtual void	setToggleType( ToggleType );
    void	setOn( bool );
    virtual void	setState( ToggleState );

    virtual bool hitButton( const QPoint &pos ) const;
    virtual void drawButton( QPainter * );
    virtual void drawButtonLabel( QPainter * );

    void	keyPressEvent( QKeyEvent *);
    void	keyReleaseEvent( QKeyEvent *);
    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	paintEvent( QPaintEvent * );
    void	focusInEvent( QFocusEvent * );
    void	focusOutEvent( QFocusEvent * );

    void	enabledChange( bool );

private slots:
    void	animateTimeout();
    void	autoRepeatTimeout();

private:
    QString	btext;
    QPixmap    *bpixmap;
    uint	toggleTyp	: 2;
    uint	buttonDown	: 1;
    uint	stat		: 2;
    uint	mlbDown		: 1;
    uint	autoresize	: 1;
    uint	animation	: 1;
    uint	repeat		: 1;
    QButtonData *d;

    friend class QButtonGroup;
    friend class QToolBar;
    void          ensureData();
    virtual void setGroup( QButtonGroup* );
    QTimer	 *timer();
    void	nextState();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QButton( const QButton & );
    QButton &operator=( const QButton & );
#endif
};

inline QString QButton::text() const
{
    return btext;
}

inline const QPixmap *QButton::pixmap() const
{
    return bpixmap;
}

inline bool QButton::isToggleButton() const
{
    return toggleTyp != SingleShot;
}

inline  bool QButton::isDown() const
{
    return buttonDown;
}

inline bool QButton::isOn() const
{
    return stat != Off;
}

#ifndef QT_NO_COMPAT
inline bool QButton::autoResize() const
{
    return autoresize;
}

inline bool QButton::autoRepeat() const
{
    return repeat;
}
#endif

inline QButton::ToggleState QButton::state() const
{
    return ToggleState(stat);
}

inline void QButton::setToggleButton( bool b )
{
    setToggleType( b ? Toggle : SingleShot );
}

inline void QButton::setOn( bool y )
{
    setState( y ? On : Off );
}

inline QButton::ToggleType QButton::toggleType() const
{
    return ToggleType(toggleTyp);
}

#endif // QT_NO_BUTTON

#endif // QBUTTON_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QButton成员列表

完整的QButton成员列表

这里是QButton成员函数的完整列表，包括继承的成员。

  • QButton()
  • ~QButton()
  • accel()
  • acceptDrops()
  • adjustSize()
  • animateClick()
  • autoMask()
  • autoRepeat()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawButton()
  • drawButtonLabel()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • group()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • hitButton()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isDown()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusiveToggle()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isOn()
  • isPopup()
  • isToggleButton()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setAutoRepeat()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setDown()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOn()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setState()
  • setStyle()
  • setTabOrder()
  • setText()
  • setToggleButton()
  • setToggleType()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • state()
  • stateChanged()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • toggle()
  • toggleType()
  • toggled()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QButtonGroup类

QButtonGroup类参考

QButtonGroup窗口部件把QButton窗口部件组织在一个组中。 详情请见……

#include <qbuttongroup.h>

继承了QGroupBox。

被QHButtonGroup和QVButtonGroup继承。

所有成员函数的列表。

公有成员

  • QButtonGroup ( QWidget * parent = 0, const char * name = 0 )
  • QButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • QButtonGroup ( int strips, Orientation orientation, QWidget * parent = 0, const char * name = 0 )
  • QButtonGroup ( int strips, Orientation orientation, const QString & title, QWidget * parent = 0, const char * name = 0 )
  • bool isExclusive () const
  • bool isRadioButtonExclusive () const
  • virtual void setExclusive ( bool )
  • virtual void setRadioButtonExclusive ( bool )
  • int insert ( QButton * button, int id = -1 )
  • void remove ( QButton * button )
  • QButton * find ( int id ) const
  • int id ( QButton * button ) const
  • int count () const
  • virtual void setButton ( int id )
  • virtual void moveFocus ( int key )
  • QButton * selected () const

信号

  • void pressed ( int id )
  • void released ( int id )
  • void clicked ( int id )

属性

  • bool exclusive - 按钮组是否互斥
  • bool radioButtonExclusive - 组中的单选按钮是否互斥

详细描述

QButtonGroup窗口部件把QButton窗口部件组织在一个组中。

按钮组窗口部件使处理一组按钮变得很容易。按钮组中的每一个按钮都有一个唯一的标识。当按钮组中的按钮被点击时，按钮组会发射一个带有这个按钮标识的clicked()信号。当你有一个相近的按钮并且你想把它们的clicked()信号连接到一个槽时，上述的信号是按钮组在这方面很有用处。

互斥（exclusive）的按钮组会把所有的切换按钮关闭，除了那个被点击的。按钮组默认是不互斥的。默认情况下，尽管按钮组不是互斥的，但被插入到这个按钮组的所有单选按钮都变为互斥的。（请参考setRadioButtonExclusive()。）

这里有两个使用按钮组的方法：

  • 按钮组是一组按钮的父窗口部件，也就是按钮组是按钮构造函数中的parent参数。按钮被按照它们被创建的顺序分配0、1、2等标识。QButtonGroup可以显示一个框架和一个标题，因为它继承了QGroupBox。
  • 按钮组是一个不可见的窗口部件并且被包含的按钮有其它父窗口部件。一个按钮必须使用一个有标识的insert()来被手工插入到按钮组中。

按钮可以使用remove()从组中被移除。可以使用一个包含给定标识的find()来获得一个按钮的指针。使用id()可以得到一个按钮的标识。按钮可以通过setButton()被设置为打开。count()可以返回组中的按钮数。

也可以参考QButton、QPushButton、QCheckBox、QRadioButton、窗口部件外观和风格、布局管理和组织者。

成员函数文档

QButtonGroup::QButtonGroup ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的按钮组。

parent和name参数被传递给QWidget构造函数。

QButtonGroup::QButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的按钮组。

parent和name参数被传递给QWidget构造函数。

QButtonGroup::QButtonGroup ( int strips, Orientation orientation, QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的按钮组。子窗口部件会被排列在strips列或者行中（依赖orientation）。

parent和name参数被传递给QWidget构造函数。

QButtonGroup::QButtonGroup ( int strips, Orientation orientation, const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的按钮组。子窗口部件会被排列在strips列或者行中（依赖orientation）。

parent和name参数被传递给QWidget构造函数。

void QButtonGroup::clicked ( int id ) [信号]

当组中的按钮被点击时，这个信号被发射。id参数是按钮的标识符。

也可以参考QButton::clicked()和insert()。

实例：drawdemo/drawdemo.cpp和xform/xform.cpp。

int QButtonGroup::count () const

返回组中的按钮数。

QButton * QButtonGroup::find ( int id ) const

找到并返回一个标识为id的按钮的指针。

如果这个按钮没有被找到，返回零。

int QButtonGroup::id ( QButton * button ) const

返回button的标识，或者如果button不是这个组的成员，返回-1。

int QButtonGroup::insert ( QButton * button, int id = -1 )

把标识为id的button插入到按钮组中。返回按钮的标识。

按钮通常是在被创建的时候把按钮组作为父对象，然后会被自动插入到按钮组中的。所以如果按钮的父对象是这个按钮组的话，就不需要手工插入了。一个例外就是当你想自己定义标识来代替默认的0、1、2等等。

按钮会被指定标识为id或者一个自动生成的标识。它是这样工作的：如果id >= 0，这个标识被指定。如果id == -1（默认），标识等于这个按钮组中的按钮数。如果id是其它负整数，比如-2，一个唯一的标识（这个负整数 <= -2）被生成。没有按钮的标识为-1。

也可以参考find(), remove()和exclusive。

实例：listbox/listbox.cpp和xform/xform.cpp。

bool QButtonGroup::isExclusive () const

如果按钮组互斥，返回真，否则返回假。详细情况请参考“exclusive”属性。

bool QButtonGroup::isRadioButtonExclusive () const

如果组中的单选按钮互斥，返回真，否则返回假。详细情况请参考“radioButtonExclusive”属性。

void QButtonGroup::moveFocus ( int key ) [虚]

根据key移动键盘焦点，并且如果适当，选中新的焦点项。

除非键盘焦点指向一个按钮组的成员并且key是Key_Up、Key_Down、Key_Left和Key_Right之一，否则这个函数什么都不执行。

void QButtonGroup::pressed ( int id ) [信号]

当组中的按钮被按下（pressed）时，这个信号被发射。id参数是按钮的标识。

void QButtonGroup::released ( int id ) [信号]

当组中的按钮被释放（released）时，这个信号被发射。id参数是按钮的标识。

void QButtonGroup::remove ( QButton * button )

从按钮组中移除button。

也可以参考insert()。

QButton * QButtonGroup::selected () const

如果真好有一个切换按钮被选择了，返回它的指针，否则返回0。

void QButtonGroup::setButton ( int id ) [虚]

设置标识为id的按钮为打开，如果这是一个互斥组，组中的所有其它按钮将被设置为关闭。

void QButtonGroup::setExclusive ( bool ) [虚]

设置按钮组是否互斥。详细情况请参考“exclusive”属性。

void QButtonGroup::setRadioButtonExclusive ( bool ) [虚]

设置组中的单选按钮是否互斥。详细情况请参考“radioButtonExclusive”属性。

属性文档

bool exclusive

这个属性保存的是按钮组是否互斥。

如果这个值为真，那么组中的按钮是被切换的，并且如果要取消一个按钮的选择，你必须点击组中的另一个按钮。默认为假。

通过setExclusive()设置属性值并且通过isExclusive()来获得属性值。

bool radioButtonExclusive

这个属性保存的是组中的单选按钮是否互斥。

如果这个属性为真（默认），组中的单选按钮被处理为互斥的。

通过setRadioButtonExclusive()设置属性值并且通过isRadioButtonExclusive()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qbuttongroup.h包含文件

qbuttongroup.h

这里是qbuttongroup.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qbuttongroup.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QButtonGroup class
**
** Created : 950130
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QBUTTONGROUP_H
#define QBUTTONGROUP_H

#ifndef QT_H
#include "qgroupbox.h"
#endif // QT_H

#ifndef QT_NO_BUTTONGROUP

class QButton;
class QButtonList;

class Q_EXPORT QButtonGroup : public QGroupBox
{
    Q_OBJECT
    Q_PROPERTY( bool exclusive READ isExclusive WRITE setExclusive )
    Q_PROPERTY( bool radioButtonExclusive READ isRadioButtonExclusive WRITE setRadioButtonExclusive )

public:
    QButtonGroup( QWidget* parent=0, const char* name=0 );
    QButtonGroup( const QString &title,
          QWidget* parent=0, const char* name=0 );
    QButtonGroup( int columns, Orientation o,
          QWidget* parent=0, const char* name=0 );
    QButtonGroup( int columns, Orientation o, const QString &title,
          QWidget* parent=0, const char* name=0 );
    ~QButtonGroup();

    bool	isExclusive() const;
    bool	isRadioButtonExclusive() const { return radio_excl; }
    virtual void setExclusive( bool );
    virtual void setRadioButtonExclusive( bool );

public:
    int		insert( QButton *, int id=-1 );
    void	remove( QButton * );
    QButton    *find( int id ) const;
    int		id( QButton * ) const;
    int		count() const;

    virtual void setButton( int id );

    virtual void moveFocus( int );

    QButton    *selected() const;

signals:
    void	pressed( int id );
    void	released( int id );
    void	clicked( int id );

protected slots:
    void	buttonPressed();
    void	buttonReleased();
    void	buttonClicked();
    void	buttonToggled( bool on );

private:
    void	init();
    bool	excl_grp;
    bool	radio_excl;
    QButtonList *buttons;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QButtonGroup( const QButtonGroup & );
    QButtonGroup &operator=( const QButtonGroup & );
#endif
};

#endif // QT_NO_BUTTONGROUP

#endif // QBUTTONGROUP_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QButtonGroup成员列表

完整的QButtonGroup成员列表

这里是QButtonGroup成员函数的完整列表，包括继承的成员。

  • QButtonGroup()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • id()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusive()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isRadioButtonExclusive()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • moveFocus()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • remove()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setButton()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExclusive()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRadioButtonExclusive()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QByteArray类

QByteArray类参考

QByteArray类提供了一个字节数组。 详情请见……

#include <qcstring.h>

继承了QMemArray<char>。

被QBitArray和QCString继承。

所有成员函数的列表。

公有成员

  • QByteArray ()
  • QByteArray ( int size )

详细描述

QByteArray类提供了一个字节数组。

QByteArray类提供了一个字节的明显共享数组。它对使用自定义数据来操作内存区域是很有用的。QByteArray就是QMemArray<char>的实现。请看QMemArray文档有更详细的信息。

也可以参考集合类和非GUI类。

成员函数文档

QByteArray::QByteArray ()

构造一个空的QByteArray。

QByteArray::QByteArray ( int size )

构造一个size大小的QByteArray。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QByteArray成员列表

完整的QByteArray成员列表

这里是QByteArray成员函数的完整列表，包括继承的成员。

  • QByteArray()
  • assign()
  • at()
  • begin()
  • bsearch()
  • contains()
  • copy()
  • count()
  • data()
  • detach()
  • duplicate()
  • end()
  • fill()
  • find()
  • isEmpty()
  • isNull()
  • nrefs()
  • operator const type *()
  • operator!=()
  • operator=()
  • operator==()
  • operator[]()
  • resetRawData()
  • resize()
  • setRawData()
  • size()
  • sort()
  • truncate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCache Class

QCache Class Reference

The QCache class is a template class that provides a cache based on QString keys. More...

#include <qcache.h>

Inherits QPtrCollection.

List of all member functions.

Public Members

  • QCache ( int maxCost = 100, int size = 17, bool caseSensitive = TRUE )
  • ~QCache ()
  • int maxCost () const
  • int totalCost () const
  • void setMaxCost ( int m )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • virtual void clear ()
  • bool insert ( const QString & k, const type * d, int c = 1, int p = 0 )
  • bool remove ( const QString & k )
  • type * take ( const QString & k )
  • type * find ( const QString & k, bool ref = TRUE ) const
  • type * operator[] ( const QString & k ) const
  • void statistics () const

Important Inherited Members

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

Detailed Description

The QCache class is a template class that provides a cache based on QString keys.

A cache is a least recently used (LRU) list of cache items. Each cache item has a key and a certain cost. The sum of item costs, totalCost(), never exceeds the maximum cache cost, maxCost(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed.

QCache is a template class. QCache<X> defines a cache that operates on pointers to X, or X*.

Apart from insert(), by far the most important function is find() (which also exists as operator[]()). This function looks up an item, returns it, and by default marks it as being the most recently used item.

There are also methods to remove() or take() an object from the cache. Calling setAutoDelete(TRUE) for a cache tells it to delete items that are removed. The default is to not delete items when they are removed (i.e., remove() and take() are equivalent).

When inserting an item into the cache, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the cache copy all of the item's data (known as a deep copy) when an item is inserted. insert() calls the virtual function QPtrCollection::newItem() for the item to be inserted. Inherit a cache and reimplement it if you want deep copies.

When removing a cache item, the virtual function QPtrCollection::deleteItem() is called. The default implementation deletes the item if auto-deletion is enabled, and does nothing otherwise.

There is a QCacheIterator that can be used to traverse the items in the cache in arbitrary order.

In QCache, the cache items are accessed via QString keys, which are Unicode strings. If you want to use non-Unicode, plain 8-bit char* keys, use the QAsciiCache template. A QCache has the same performace as a QAsciiCache.

See also QCacheIterator, QAsciiCache, QIntCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QCache::QCache ( int maxCost = 100, int size = 17, bool caseSensitive = TRUE )

Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items.

size is actually the size of an internal hash array; it's usually best to make it a prime number and at least 50% bigger than the largest expected number of items in the cache.

Each inserted item has an associated cost. When inserting a new item, if the total cost of all items in the cache will exceed maxCost, the cache will start throwing out the older (least recently used) items until there is enough room for the new item to be inserted.

If caseSensitive is TRUE (the default), the cache keys are case sensitive; if it is FALSE, they are case-insensitive. Case-insensitive comparison includes all letters in Unicode.

QCache::~QCache ()

Removes all items from the cache and destroys it. All iterators that access this cache will be reset.

bool QPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is FALSE.

See also setAutoDelete().

void QCache::clear () [virtual]

Removes all items from the cache and deletes them if auto-deletion has been enabled.

All cache iterators that operate this on cache are reset.

See also remove() and take().

Reimplemented from QPtrCollection.

uint QCache::count () const [virtual]

Returns the number of items in the cache.

See also totalCost().

Reimplemented from QPtrCollection.

type * QCache::find ( const QString & k, bool ref = TRUE ) const

Returns the item associated with key k, or null if the key does not exist in the cache. If ref is TRUE (the default), the item is moved to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

bool QCache::insert ( const QString & k, const type * d, int c = 1, int p = 0 )

Inserts the item d into the cache with key k and cost c. Returns TRUE if it is successful and FALSE if it fails.

The cache's size is limited, and if the total cost is too high, QCache will remove old, least recently used items until there is room for this new item.

The parameter p is internal and should be left at the default value (0).

Warning: If this function returns FALSE you must delete d yourself. Additionally, be very careful about using d after calling this function because any other insertions into the cache, from anywhere in the application or within Qt itself, could cause the object to be discarded from the cache and the pointer to become invalid.

bool QCache::isEmpty () const

Returns TRUE if the cache is empty, or FALSE if there is at least one object in it.

int QCache::maxCost () const

Returns the maximum allowed total cost of the cache.

See also setMaxCost() and totalCost().

type * QCache::operator[] ( const QString & k ) const

Returns the item associated with key k, or null if k does not exist in the cache, and moves the item to the front of the least recently used list.

If there are two or more items with equal keys, the one that was inserted last is returned.

This is the same as find( k, TRUE ).

See also find().

bool QCache::remove ( const QString & k )

Removes the item associated with k, and returns TRUE if the item was present in the cache or FALSE if it was not.

The item is deleted if auto-deletion has been enabled, i.e., you have called setAutoDelete(TRUE).

If there are two or more items with equal keys, the one that was inserted last is removed.

All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.

See also take() and clear().

void QPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is TRUE and to never delete them if enable is FALSE.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is FALSE, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp and table/bigtable/main.cpp.

void QCache::setMaxCost ( int m )

Sets the maximum allowed total cost of the cache to m. If the current total cost is greater than m, some items are deleted immediately.

See also maxCost() and totalCost().

uint QCache::size () const

Returns the size of the hash array used to implement the cache. This should be a bit bigger than count() is likely to be.

void QCache::statistics () const

A debug-only utility function. Prints out cache usage, hit/miss, and distribution information using qDebug(). This function does nothing in the release library.

type * QCache::take ( const QString & k )

Takes the item associated with k out of the cache without deleting it and returns a pointer to the item taken out, or null if the key does not exist in the cache.

If there are two or more items with equal keys, the one that was inserted last is taken.

All iterators that refer to the taken item are set to point to the next item in the cache's traversal order.

See also remove() and clear().

int QCache::totalCost () const

Returns the total cost of the items in the cache. This is an integer in the range 0 to maxCost().

See also setMaxCost().

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


qcache.h Include File

qcache.h

This is the verbatim text of the qcache.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QCache template class
**
** Created : 950209
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCACHE_H
#define QCACHE_H

#ifndef QT_H
#include "qgcache.h"
#endif // QT_H

template<class type>
class QCache
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGCache
#endif
{
public:
    QCache( const QCache<type> &c ) : QGCache(c) {}
    QCache( int maxCost=100, int size=17, bool caseSensitive=TRUE )
    : QGCache( maxCost, size, StringKey, caseSensitive, FALSE ) {}
   ~QCache()				{ clear(); }
    QCache<type> &operator=( const QCache<type> &c )
            { return (QCache<type>&)QGCache::operator=(c); }
    int	  maxCost()   const		{ return QGCache::maxCost(); }
    int	  totalCost() const		{ return QGCache::totalCost(); }
    void  setMaxCost( int m )		{ QGCache::setMaxCost(m); }
    uint  count()     const		{ return QGCache::count(); }
    uint  size()      const		{ return QGCache::size(); }
    bool  isEmpty()   const		{ return QGCache::count() == 0; }
    void  clear()			{ QGCache::clear(); }
    bool  insert( const QString &k, const type *d, int c=1, int p=0 )
            { return QGCache::insert_string(k,(Item)d,c,p);}
    bool  remove( const QString &k )
            { return QGCache::remove_string(k); }
    type *take( const QString &k )
            { return (type *)QGCache::take_string(k); }
    type *find( const QString &k, bool ref=TRUE ) const
            { return (type *)QGCache::find_string(k,ref);}
    type *operator[]( const QString &k ) const
            { return (type *)QGCache::find_string(k);}
    void  statistics() const	      { QGCache::statistics(); }
private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QCache<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QCache<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QCacheIterator
: public QGCacheIterator
{
public:
    QCacheIterator( const QCache<type> &c ):QGCacheIterator((QGCache &)c) {}
    QCacheIterator( const QCacheIterator<type> &ci)
                : QGCacheIterator( (QGCacheIterator &)ci ) {}
    QCacheIterator<type> &operator=(const QCacheIterator<type>&ci)
    { return ( QCacheIterator<type>&)QGCacheIterator::operator=( ci ); }
    uint  count()   const     { return QGCacheIterator::count(); }
    bool  isEmpty() const     { return QGCacheIterator::count() == 0; }
    bool  atFirst() const     { return QGCacheIterator::atFirst(); }
    bool  atLast()  const     { return QGCacheIterator::atLast(); }
    type *toFirst()	      { return (type *)QGCacheIterator::toFirst(); }
    type *toLast()	      { return (type *)QGCacheIterator::toLast(); }
    operator type *() const   { return (type *)QGCacheIterator::get(); }
    type *current()   const   { return (type *)QGCacheIterator::get(); }
    QString currentKey() const{ return QGCacheIterator::getKeyString(); }
    type *operator()()	      { return (type *)QGCacheIterator::operator()();}
    type *operator++()	      { return (type *)QGCacheIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGCacheIterator::operator+=(j);}
    type *operator--()	      { return (type *)QGCacheIterator::operator--(); }
    type *operator-=(uint j)  { return (type *)QGCacheIterator::operator-=(j);}
};

#endif // QCACHE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCache Member List

Complete Member List for QCache

This is the complete list of member functions for QCache, including inherited members.

  • ~QCache()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • find()
  • insert()
  • isEmpty()
  • maxCost()
  • newItem()
  • operator[]()
  • remove()
  • setAutoDelete()
  • setMaxCost()
  • size()
  • statistics()
  • take()
  • totalCost()


QCacheIterator Class

QCacheIterator Class Reference

The QCacheIterator class provides an iterator for QCache collections. More...

#include <qcache.h>

List of all member functions.

Public Members

  • QCacheIterator ( const QCache<type> & cache )
  • QCacheIterator ( const QCacheIterator<type> & ci )
  • QCacheIterator<type> & operator= ( const QCacheIterator<type> & ci )
  • uint count () const
  • bool isEmpty () const
  • bool atFirst () const
  • bool atLast () const
  • type * toFirst ()
  • type * toLast ()
  • operator type * () const
  • type * current () const
  • QString currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )
  • type * operator-- ()
  • type * operator-= ( uint jump )

Detailed Description

The QCacheIterator class provides an iterator for QCache collections.

Note that the traversal order is arbitrary; you are not guaranteed any particular order. If new objects are inserted into the cache while the iterator is active, the iterator may or may not see them.

Multiple iterators are completely independent, even when they operate on the same QCache. QCache updates all iterators that refer an item when that item is removed.

QCacheIterator provides an operator++(), and an operator+=() to traverse the cache. The current() and currentKey() functions are used to access the current cache item and its key. The atFirst() and atLast() return TRUE if the iterator points to the first or last item in the cache respectively. The isEmpty() function returns TRUE if the cache is empty, and count() returns the number of items in the cache.

Note that atFirst() and atLast() refer to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also QCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QCacheIterator::QCacheIterator ( const QCache<type> & cache )

Constructs an iterator for cache. The current iterator item is set to point to the first item in the cache.

QCacheIterator::QCacheIterator ( const QCacheIterator<type> & ci )

Constructs an iterator for the same cache as ci. The new iterator starts at the same item as ci.current(), but moves independently from there on.

bool QCacheIterator::atFirst () const

Returns TRUE if the iterator points to the first item in the cache. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also toFirst() and atLast().

bool QCacheIterator::atLast () const

Returns TRUE if the iterator points to the last item in the cache. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal least recently used list.

See also toLast() and atFirst().

uint QCacheIterator::count () const

Returns the number of items in the cache on which this iterator operates.

See also isEmpty().

type * QCacheIterator::current () const

Returns a pointer to the current iterator item.

QString QCacheIterator::currentKey () const

Returns the key for the current iterator item.

bool QCacheIterator::isEmpty () const

Returns TRUE if the cache is empty, i.e. count() == 0; otherwise it returns FALSE.

See also count().

QCacheIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QCacheIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the cache or if it was null, null is returned.

type * QCacheIterator::operator++ ()

Prefix++ makes the iterator point to the item just after current() and makes that the new current item for the iterator. If current() was the last item, operator++() returns 0.

type * QCacheIterator::operator+= ( uint jump )

Returns the item jump positions after the current item, or null if it is beyond the last item. Makes this the current item.

type * QCacheIterator::operator-- ()

Prefix-- makes the iterator point to the item just before current() and makes that the new current item for the iterator. If current() was the first item, operator--() returns 0.

type * QCacheIterator::operator-= ( uint jump )

Returns the item jump positions before the current item, or null if it is before the first item. Makes this the current item.

QCacheIterator<type> & QCacheIterator::operator= ( const QCacheIterator<type> & ci )

Makes this an iterator for the same cache as ci. The new iterator starts at the same item as ci.current(), but moves independently thereafter.

type * QCacheIterator::toFirst ()

Sets the iterator to point to the first item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if the cache is empty.

See also toLast() and isEmpty().

type * QCacheIterator::toLast ()

Sets the iterator to point to the last item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if the cache is empty.

See also toFirst() and isEmpty().

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


QCacheIterator Member List

Complete Member List for QCacheIterator

This is the complete list of member functions for QCacheIterator, including inherited members.

  • QCacheIterator()
  • atFirst()
  • atLast()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()


QCanvas Class

QCanvas Class Reference
[canvas module]

The QCanvas class provides a 2D area that can contain QCanvasItem objects. More...

#include <qcanvas.h>

Inherits QObject.

List of all member functions.

Public Members

  • QCanvas ( QObject * parent = 0, const char * name = 0 )
  • QCanvas ( int w, int h )
  • QCanvas ( QPixmap p, int h, int v, int tilewidth, int tileheight )
  • virtual ~QCanvas ()
  • virtual void setTiles ( QPixmap p, int h, int v, int tilewidth, int tileheight )
  • virtual void setBackgroundPixmap ( const QPixmap & p )
  • QPixmap backgroundPixmap () const
  • virtual void setBackgroundColor ( const QColor & c )
  • QColor backgroundColor () const
  • virtual void setTile ( int x, int y, int tilenum )
  • int tile ( int x, int y ) const
  • int tilesHorizontally () const
  • int tilesVertically () const
  • int tileWidth () const
  • int tileHeight () const
  • virtual void resize ( int w, int h )
  • int width () const
  • int height () const
  • QSize size () const
  • QRect rect () const
  • bool onCanvas ( int x, int y ) const
  • bool onCanvas ( const QPoint & p ) const
  • bool validChunk ( int x, int y ) const
  • bool validChunk ( const QPoint & p ) const
  • int chunkSize () const
  • virtual void retune ( int chunksze, int mxclusters = 100 )
  • virtual void setAllChanged ()
  • virtual void setChanged ( const QRect & area )
  • virtual void setUnchanged ( const QRect & area )
  • QCanvasItemList allItems ()
  • QCanvasItemList collisions ( const QPoint & p ) const
  • QCanvasItemList collisions ( const QRect & r ) const
  • QCanvasItemList collisions ( const QPointArray & chunklist, const QCanvasItem * item, bool exact ) const
  • void drawArea ( const QRect & clip, QPainter * painter, bool dbuf = FALSE )
  • virtual void setAdvancePeriod ( int ms )
  • virtual void setUpdatePeriod ( int ms )
  • virtual void setDoubleBuffering ( bool y )

Public Slots

  • virtual void advance ()
  • virtual void update ()

Signals

  • void resized ()

Protected Members

  • virtual void drawBackground ( QPainter & painter, const QRect & clip )
  • virtual void drawForeground ( QPainter & painter, const QRect & clip )

Detailed Description

The QCanvas class provides a 2D area that can contain QCanvasItem objects.

The QCanvas class manages its 2D graphic area and all the canvas items the area contains. The canvas is displayed on screen with a QCanvasView widget. Multiple QCanvasView widgets may be associated with a canvas to provide multiple views of the same canvas.

The canvas is optimized for large numbers of items. Qt provides a rich set of canvas item classes, e.g. QCanvasEllipse, QCanvasLine, QCanvasPolygon, QCanvasPolygonalItem, QCanvasRectangle, QCanvasSpline, QCanvasSprite and QCanvasText. You can subclass to create your own canvas items; QCanvasPolygonalItem is the most common base class used for this purpose.

Items appear on the canvas after their show() function has been called (or setVisible(TRUE)), and after update() has been called. The canvas only shows items that are visible, and then only if update() is called. If you created the canvas without passing a width and height to the constructor you'll also need to call resize().

Although a canvas may appear to be similar to a widget with child widgets, there are several notable differences:

  • Canvas items are usually far faster to manipulate and redraw than child widgets, with the speed advantage becoming especially great when there are many canvas items and non-rectangular items. In most situations canvas items are also a lot more memory efficient than child widgets.

  • It's easy to detect overlapping items (collision detection).

  • The canvas can be larger than a widget. A million-by-million canvas is perfectly possible. At such a size a widget might be very inefficient, and some window systems might not support it at all, whereas QCanvas scales well. Even with a billion pixels and a million items, finding a particular canvas item, detecting collisions, etc., is still fast (though the memory consumption may be prohibitive at such an extreme).

  • Two or more QCanvasView objects can view the same canvas.

  • An arbitrary transformation matrix can be set on each QCanvasView which makes it easy to zoom, rotate or shear the viewed canvas.

  • Widgets provide a lot more functionality, such as input (QKeyEvent, QMouseEvent etc.) and layout management (QGridLayout etc.).

A canvas consists of a background, a number of canvas items organized by x, y and z coordinates, and a foreground. A canvas item's z coordinate may be treated as a layer number -- canvas items with a higher z coordinate appear in front of canvas items with a lower z coordinate.

The background is white by default, but can be set to a different color using setBackgroundColor(), or to a repeated pixmap using setBackgroundPixmap() or to a mosaic of smaller pixmaps using setTiles(). Individual tiles can be set with setTile(). There are corresponding get functions, e.g. backgroundColor() and backgroundPixmap().

Note that QCanvas does not inherit from QWidget, even though it has some functions which provide the same functionality as those in QWidget. One of these is setBackgroundPixmap(); some others are resize(), size(), width() and height(). QCanvasView is the widget used to display a canvas on the screen.

Canvas items are added to a canvas by constructing them and passing the canvas to the canvas item's constructor. An item can be moved to a different canvas using QCanvasItem::setCanvas().

Canvas items are movable (and in the case of QCanvasSprites, animated) objects that inherit QCanvasItem. Each canvas item has a position on the canvas (x, y coordinates) and a height (z coordinate), all of which are held as floating-point numbers. Moving canvas items also have x and y velocities. It's possible for a canvas item to be outside the canvas (for example QCanvasItem::x() is greater than width()). When a canvas item is off the canvas, onCanvas() returns FALSE and the canvas disregards the item. (Canvas items off the canvas do not slow down any of the common operations on the canvas.)

Canvas items can be moved with QCanvasItem::move(). The advance() function moves all QCanvasItem::animated() canvas items and setAdvancePeriod() makes QCanvas move them automatically on a periodic basis. In the context of the QCanvas classes, to `animate' a canvas item is to set it in motion, i.e. using QCanvasItem::setVelocity(). Animation of a canvas item itself, i.e. items which change over time, is enabled by calling QCanvasSprite::setFrameAnimation(), or more generally by subclassing and reimplementing QCanvasItem::advance(). To detect collisions use one of the QCanvasItem::collisions() functions.

The changed parts of the canvas are redrawn (if they are visible in a canvas view) whenever update() is called. You can either call update() manually after having changed the contents of the canvas, or force periodic updates using setUpdatePeriod(). If you have moving objects on the canvas, you need to call advance() every time the objects should move one step further. Periodic calls to advance() can be forced using setAdvancePeriod(). The advance() function will call QCanvasItem::advance() on every item that is animated and trigger an update of the affected areas afterwards. (A canvas item that is `animated' is simply a canvas item that is in motion.)

QCanvas organizes its canvas items into chunks; these are areas on the canvas that are used to speed up most operations. Many operations start by eliminating most chunks (i.e. those which haven't changed) and then process only the canvas items that are in the few interesting (i.e. changed) chunks. A valid chunk, validChunk(), is one which is on the canvas.

The chunk size is a key factor to QCanvas's speed: if there are too many chunks, the speed benefit of grouping canvas items into chunks is reduced. If the chunks are too large, it takes too long to process each one. The QCanvas constructor picks a hopefully suitable size, but you can call retune() to change it at any time. The chunkSize() function returns the current chunk size.

The canvas items always make sure they're in the right chunks; all you need to make sure of is that the canvas uses the right chunk size. A good rule of thumb is that the size should be a bit smaller than the average canvas item size. If you have moving objects, the chunk size should be a bit smaller than the average size of the moving items.

The foreground is normally nothing, but if you reimplement drawForeground(), you can draw things in front of all canvas items.

Areas can be set as changed with setChanged() and set unchanged with setUnchanged(). The entire canvas can be set as changed with setAllChanged(). A list of all the items on the canvas is returned by allItems().

An area can be copied (painted) to a QPainter with drawArea().

If the canvas is resized it emits the resized() signal.

The examples/canvas application and the 2D graphics page of the examples/demo application demonstrate many of QCanvas's facilities.

See also QCanvasView, QCanvasItem, Abstract Widget Classes, Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvas::QCanvas ( QObject * parent = 0, const char * name = 0 )

Create a QCanvas with no size. parent and name are passed to the QObject superclass.

Warning: You must call resize() at some time after creation to be able to use the canvas.

QCanvas::QCanvas ( int w, int h )

Constructs a QCanvas that is w pixels wide and h pixels high.

QCanvas::QCanvas ( QPixmap p, int h, int v, int tilewidth, int tileheight )

Constructs a QCanvas which will be composed of h tiles horizontally and v tiles vertically. Each tile will be an image tilewidth by tileheight pixels taken from pixmap p.

The pixmap p is a list of tiles, arranged left to right, (and in the case of pixmaps that have multiple rows of tiles, top to bottom), with tile 0 in the top-left corner, tile 1 next to the right, and so on, e.g.

0 | 1 | 2 | 3
4 | 5 | 6 | 7

The QCanvas is initially sized to show exactly the given number of tiles horizontally and vertically. If it is resized to be larger, the entire matrix of tiles will be repeated as much as necessary to cover the area. If it is smaller, tiles to the right and bottom will not be visible.

See also setTiles().

QCanvas::~QCanvas () [virtual]

Destroys the canvas and all the canvas's canvas items.

void QCanvas::advance () [virtual slot]

Moves all QCanvasItem::animated() canvas items on the canvas and refreshes all changes to all views of the canvas. (An `animated' item is an item that is in motion; see setVelocity().)

The advance takes place in two phases. In phase 0, the QCanvasItem::advance() function of each QCanvasItem::animated() canvas item is called with paramater 0. Then all these canvas items are called again, with parameter 1. In phase 0, the canvas items should not change position, merely examine other items on the canvas for which special processing is required, such as collisions between items. In phase 1, all canvas items should change positions, ignoring any other items on the canvas. This two-phase approach allows for considerations of "fairness", although no QCanvasItem subclasses supplied with Qt do anything interesting in phase 0.

The canvas can be configured to call this function periodically with setAdvancePeriod().

See also update().

QCanvasItemList QCanvas::allItems ()

Returns a list of all items in the canvas.

QColor QCanvas::backgroundColor () const

Returns the color set by setBackgroundColor(). By default, this is white.

This function is not a reimplementation of QWidget::backgroundColor() (QCanvas is not a subclass of QWidget), but all QCanvasViews that are viewing the canvas will set their backgrounds to this color.

See also setBackgroundColor() and backgroundPixmap().

QPixmap QCanvas::backgroundPixmap () const

Returns the pixmap set by setBackgroundPixmap(). By default, this is a null pixmap.

See also setBackgroundPixmap() and backgroundColor().

int QCanvas::chunkSize () const

Returns the chunk size of the canvas.

See also retune().

QCanvasItemList QCanvas::collisions ( const QPoint & p ) const

Returns a list of canvas items that intersect with the point p. The list is ordered by z coordinates, from highest z coordinate (front-most item) to lowest z coordinate (rear-most item).

QCanvasItemList QCanvas::collisions ( const QRect & r ) const

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

Returns a list of items which intersect with the rectangle r. The list is ordered by z coordinates, from highest z coordinate (front-most item) to lowest z coordinate (rear-most item).

QCanvasItemList QCanvas::collisions ( const QPointArray & chunklist, const QCanvasItem * item, bool exact ) const

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

Returns a list of canvas items which intersect with the chunks listed in chunklist, excluding item. If exact is TRUE, only those which actually QCanvasItem::collidesWith() item are returned; otherwise canvas items are included just for being in the chunks.

This is a utility function mainly used to implement the simpler QCanvasItem::collisions() function.

void QCanvas::drawArea ( const QRect & clip, QPainter * painter, bool dbuf = FALSE )

Paints all canvas items that are in the area clip to painter, using double-buffering if dbuf is TRUE.

e.g. to print the canvas to a printer:

  QPrinter pr;
  if ( pr.setup() ) {
    QPainter p(&pr);
    canvas.drawArea( canvas.rect(), &p );
  }

Example: canvas/canvas.cpp.

void QCanvas::drawBackground ( QPainter & painter, const QRect & clip ) [virtual protected]

This virtual function is called for all updates of the canvas. It renders any background graphics using the painter painter, in the area clip. If the canvas has a background pixmap or a tiled background, that graphic is used, otherwise the canvas is cleared using the background color.

If the graphics for an area change, you must explicitly call setChanged(const QRect&) for the result to be visible when update() is next called.

See also setBackgroundColor(), setBackgroundPixmap() and setTiles().

void QCanvas::drawForeground ( QPainter & painter, const QRect & clip ) [virtual protected]

This virtual function is called for all updates of the canvas. It renders any foreground graphics using the painter painter, in the area clip.

If the graphics for an area change, you must explicitly call setChanged(const QRect&) for the result to be visible when update() is next called.

The default is to draw nothing.

int QCanvas::height () const

Returns the height of the canvas, in pixels.

Example: canvas/canvas.cpp.

bool QCanvas::onCanvas ( int x, int y ) const

Returns TRUE if the pixel position (x, y) is on the canvas; otherwise returns FALSE.

See also validChunk().

bool QCanvas::onCanvas ( const QPoint & p ) const

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

Returns TRUE if the pixel position p is on the canvas; otherwise returns FALSE.

See also validChunk().

QRect QCanvas::rect () const

Returns a rectangle the size of the canvas.

void QCanvas::resize ( int w, int h ) [virtual]

Changes the size of the canvas to have a width of w and a height of h. This is a slow operation.

Examples: canvas/canvas.cpp and chart/chartform.cpp.

void QCanvas::resized () [signal]

This signal is emitted whenever the canvas is resized. Each QCanvasView connects to this signal to keep the scrollview size correct.

void QCanvas::retune ( int chunksze, int mxclusters = 100 ) [virtual]

Change the efficiency tuning parameters to mxclusters clusters, each of size chunksze. This is a slow operation if there are many objects on the canvas.

The canvas is divided into chunks which are rectangular areas of the canvas chunksze wide by chunksze high. Use a chunk size which is about the average size of the canvas items. If you choose a chunk size which is too small it will increase the amount of calculation required when drawing since each change will affect many chunks. If you choose a chunk size which is too large the amount of drawing required will increase because for each change, a lot of drawing will be required since there will be many (unchanged) canvas items which are in the same chunk as the changed canvas items.

Internally, a canvas uses a low-resolution "chunk matrix" to keep track of all the items in the canvas. A 64x64 chunk matrix is the default for a 1024x1024 pixel canvas, where each chunk collects canvas items in a 16x16 pixel square. This default is also affected by setTiles(). You can tune this default with this function. For example if you have a very large canvas and want to trade off speed for memory then you might set the chunk size to 32 or 64.

The mxclusters argument is the number of rectangular groups of chunks that will be separately drawn. If the canvas has a large number of small, dispersed items, this should be about that number. Our testing suggests that a large number of clusters is almost always best.

void QCanvas::setAdvancePeriod ( int ms ) [virtual]

Sets the canvas to call advance() every ms milliseconds. Any previous setting by setAdvancePeriod() or setUpdatePeriod() is overridden.

If ms is less than 0 advancing will be stopped.

Example: canvas/main.cpp.

void QCanvas::setAllChanged () [virtual]

Marks the whole canvas as changed. All views of the canvas will be entirely redrawn when update() is called next.

void QCanvas::setBackgroundColor ( const QColor & c ) [virtual]

Sets the solid background to be the color c.

See also backgroundColor(), setBackgroundPixmap() and setTiles().

void QCanvas::setBackgroundPixmap ( const QPixmap & p ) [virtual]

Sets the solid background to be the pixmap p repeated as necessary to cover the entire canvas.

See also backgroundPixmap(), setBackgroundColor() and setTiles().

void QCanvas::setChanged ( const QRect & area ) [virtual]

Marks area as changed. This area will be redrawn in all views that are showing it when update() is called next.

void QCanvas::setDoubleBuffering ( bool y ) [virtual]

If y is TRUE (the default) double-buffering is switched on; otherwise double-buffering is switched off.

Turning off double-buffering causes the redrawn areas to flicker a bit and also gives a (usually small) performance improvement.

Example: canvas/canvas.cpp.

void QCanvas::setTile ( int x, int y, int tilenum ) [virtual]

Sets the tile at (x, y) to use tile number tilenum, which is an index into the tile pixmaps. The canvas will update appropriately when update() is next called.

The images are taken from the pixmap set by setTiles() and are arranged left to right, (and in the case of pixmaps that have multiple rows of tiles, top to bottom), with tile 0 in the top-left corner, tile 1 next to the right, and so on, e.g.

0 | 1 | 2 | 3
4 | 5 | 6 | 7

See also tile() and setTiles().

void QCanvas::setTiles ( QPixmap p, int h, int v, int tilewidth, int tileheight ) [virtual]

Sets the QCanvas to be composed of h tiles horizontally and v tiles vertically. Each tile will be an image tilewidth by tileheight pixels from pixmap p.

The pixmap p is a list of tiles, arranged left to right, (and in the case of pixmaps that have multiple rows of tiles, top to bottom), with tile 0 in the top-left corner, tile 1 next to the right, and so on, e.g.

0 | 1 | 2 | 3
4 | 5 | 6 | 7

If the canvas is larger than the matrix of tiles, the entire matrix is repeated as necessary to cover the whole canvas. If it is smaller, tiles to the right and bottom are not visible.

The width and height of p must be a multiple of tilewidth and tileheight. If they are not the function will do nothing.

void QCanvas::setUnchanged ( const QRect & area ) [virtual]

Marks area as unchanged. The area will not be redrawn in the views for the next update(), unless it is marked or changed again before the next call to update().

void QCanvas::setUpdatePeriod ( int ms ) [virtual]

Sets the canvas to call update() every ms milliseconds. Any previous setting by setAdvancePeriod() or setUpdatePeriod() is overridden.

If ms is less than 0 automatic updating will be stopped.

QSize QCanvas::size () const

Returns the size of the canvas, in pixels.

int QCanvas::tile ( int x, int y ) const

Returns the tile at position (x, y). Initially, all tiles are 0.

The parameters must be within range, i.e. 0 < x < tilesHorizontally() and 0 < y < tilesVertically().

See also setTile().

int QCanvas::tileHeight () const

Returns the height of each tile.

int QCanvas::tileWidth () const

Returns the width of each tile.

int QCanvas::tilesHorizontally () const

Returns the number of tiles horizontally.

int QCanvas::tilesVertically () const

Returns the number of tiles vertically.

void QCanvas::update () [virtual slot]

Repaints changed areas in all views of the canvas.

See also advance().

bool QCanvas::validChunk ( int x, int y ) const

Returns TRUE if the chunk position (x, y) is on the canvas; otherwise returns FALSE.

See also onCanvas().

bool QCanvas::validChunk ( const QPoint & p ) const

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

Returns TRUE if the chunk position p is on the canvas; otherwise returns FALSE.

See also onCanvas().

int QCanvas::width () const

Returns the width of the canvas, in pixels.

Example: canvas/canvas.cpp.

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


qcanvas.h Include File

qcanvas.h

This is the verbatim text of the qcanvas.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qcanvas.h   3.0.5   edited Jan 30 17:06 $
**
** Definition of QCanvas classes
**
** Created : 991211
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the canvas module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCANVAS_H
#define QCANVAS_H

#ifndef QT_H
#include "qscrollview.h"
#include "qpixmap.h"
#include "qptrlist.h"
#include "qptrdict.h"
#include "qbrush.h"
#include "qpen.h"
#include "qvaluelist.h"
#include "qpointarray.h"
#endif // QT_H

#if !defined( QT_MODULE_CANVAS ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_CANVAS )
#define QM_EXPORT_CANVAS
#else
#define QM_EXPORT_CANVAS Q_EXPORT
#endif

#ifndef QT_NO_CANVAS

class QCanvasSprite;
class QCanvasPolygonalItem;
class QCanvasRectangle;
class QCanvasPolygon;
class QCanvasEllipse;
class QCanvasText;
class QCanvasLine;
class QCanvasChunk;
class QCanvas;
class QCanvasItem;
class QCanvasView;
class QCanvasPixmap;

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
template class QM_EXPORT_CANVAS QPtrList< QCanvasItem >;
template class QM_EXPORT_CANVAS QPtrList< QCanvasView >;
template class QM_EXPORT_CANVAS QValueList< QCanvasItem* >;
// MOC_SKIP_END
#endif

class QM_EXPORT_CANVAS QCanvasItemList : public QValueList<QCanvasItem*> {
public:
    void sort();
    void drawUnique( QPainter& painter );
};

class QCanvasItemExtra;

class QM_EXPORT_CANVAS QCanvasItem : public Qt
{
public:
    QCanvasItem(QCanvas* canvas);
    virtual ~QCanvasItem();

    double x() const
    { return myx; }
    double y() const
    { return myy; }
    double z() const
    { return myz; } // (depth)

    virtual void moveBy(double dx, double dy);
    void move(double x, double y);
    void setX(double a) { move(a,y()); }
    void setY(double a) { move(x(),a); }
    void setZ(double a) { myz=a; changeChunks(); }

    bool animated() const;
    virtual void setAnimated(bool y);
    virtual void setVelocity( double vx, double vy);
    void setXVelocity( double vx ) { setVelocity(vx,yVelocity()); }
    void setYVelocity( double vy ) { setVelocity(xVelocity(),vy); }
    double xVelocity() const;
    double yVelocity() const;
    virtual void advance(int stage);

    virtual bool collidesWith( const QCanvasItem* ) const=0;

    QCanvasItemList collisions(bool exact /* NO DEFAULT */ ) const;

    virtual void setCanvas(QCanvas*);

    virtual void draw(QPainter&)=0;

    void show();
    void hide();

    virtual void setVisible(bool yes);
    bool isVisible() const
    { return (bool)vis; }
    virtual void setSelected(bool yes);
    bool isSelected() const
    { return (bool)sel; }
    virtual void setEnabled(bool yes);
    bool isEnabled() const
    { return (bool)ena; }
    virtual void setActive(bool yes);
    bool isActive() const
    { return (bool)act; }
#ifndef QT_NO_COMPAT
    bool visible() const
    { return (bool)vis; }
    bool selected() const
    { return (bool)sel; }
    bool enabled() const
    { return (bool)ena; }
    bool active() const
    { return (bool)act; }
#endif

    enum RttiValues {
    Rtti_Item = 0,
    Rtti_Sprite = 1,
    Rtti_PolygonalItem = 2,
    Rtti_Text = 3,
    Rtti_Polygon = 4,
    Rtti_Rectangle = 5,
    Rtti_Ellipse = 6,
    Rtti_Line = 7,
    Rtti_Spline = 8
    };

    virtual int rtti() const;
    static int RTTI;

    virtual QRect boundingRect() const=0;
    virtual QRect boundingRectAdvanced() const;

    QCanvas* canvas() const
    { return cnv; }

protected:
    void update() { changeChunks(); }

private:
    // For friendly subclasses...

    friend class QCanvasPolygonalItem;
    friend class QCanvasSprite;
    friend class QCanvasRectangle;
    friend class QCanvasPolygon;
    friend class QCanvasEllipse;
    friend class QCanvasText;
    friend class QCanvasLine;

    virtual QPointArray chunks() const;
    virtual void addToChunks();
    virtual void removeFromChunks();
    virtual void changeChunks();
    virtual bool collidesWith( const QCanvasSprite*,
                   const QCanvasPolygonalItem*,
                   const QCanvasRectangle*,
                   const QCanvasEllipse*,
                   const QCanvasText* ) const = 0;
    // End of friend stuff

    QCanvas* cnv;
    static QCanvas* current_canvas;
    double myx,myy,myz;
    QCanvasItemExtra *ext;
    QCanvasItemExtra& extra();
    uint ani:1;
    uint vis:1;
    uint sel:1;
    uint ena:1;
    uint act:1;
};

class QCanvasData;

class QM_EXPORT_CANVAS QCanvas : public QObject
{
    Q_OBJECT
public:
    QCanvas( QObject* parent = 0, const char* name = 0 );
    QCanvas(int w, int h);
    QCanvas( QPixmap p, int h, int v, int tilewidth, int tileheight );

    virtual ~QCanvas();

    virtual void setTiles( QPixmap tiles, int h, int v,
               int tilewidth, int tileheight );
    virtual void setBackgroundPixmap( const QPixmap& p );
    QPixmap backgroundPixmap() const;

    virtual void setBackgroundColor( const QColor& c );
    QColor backgroundColor() const;

    virtual void setTile( int x, int y, int tilenum );
    int tile( int x, int y ) const
    { return grid[x+y*htiles]; }

    int tilesHorizontally() const
    { return htiles; }
    int tilesVertically() const
    { return vtiles; }

    int tileWidth() const
    { return tilew; }
    int tileHeight() const
    { return tileh; }

    virtual void resize(int width, int height);
    int width() const
    { return awidth; }
    int height() const
    { return aheight; }
    QSize size() const
    { return QSize(awidth,aheight); }
    QRect rect() const
    { return QRect( 0, 0, awidth, aheight ); }
    bool onCanvas( int x, int y ) const
    { return x>=0 && y>=0 && x<awidth && y<aheight; }
    bool onCanvas( const QPoint& p ) const
    { return onCanvas(p.x(),p.y()); }
    bool validChunk( int x, int y ) const
    { return x>=0 && y>=0 && x<chwidth && y<chheight; }
    bool validChunk( const QPoint& p ) const
    { return validChunk(p.x(),p.y()); }

    int chunkSize() const
    { return chunksize; }
    virtual void retune(int chunksize, int maxclusters=100);

    bool sameChunk(int x1, int y1, int x2, int y2) const
    { return x1/chunksize==x2/chunksize && y1/chunksize==y2/chunksize; }
    virtual void setChangedChunk(int i, int j);
    virtual void setChangedChunkContaining(int x, int y);
    virtual void setAllChanged();
    virtual void setChanged(const QRect& area);
    virtual void setUnchanged(const QRect& area);

    // These call setChangedChunk.
    void addItemToChunk(QCanvasItem*, int i, int j);
    void removeItemFromChunk(QCanvasItem*, int i, int j);
    void addItemToChunkContaining(QCanvasItem*, int x, int y);
    void removeItemFromChunkContaining(QCanvasItem*, int x, int y);

    QCanvasItemList allItems();
    QCanvasItemList collisions( const QPoint&) const;
    QCanvasItemList collisions( const QRect&) const;
    QCanvasItemList collisions( const QPointArray& pa, const QCanvasItem* item,
                bool exact) const;

    void drawArea(const QRect&, QPainter* p, bool double_buffer=FALSE);

    // These are for QCanvasView to call
    virtual void addView(QCanvasView*);
    virtual void removeView(QCanvasView*);
    void drawCanvasArea(const QRect&, QPainter* p=0, bool double_buffer=TRUE);
#ifndef QT_NO_TRANSFORMATIONS
    void drawViewArea( QCanvasView* view, QPainter* p, const QRect& r, bool dbuf );
#endif

    // These are for QCanvasItem to call
    virtual void addItem(QCanvasItem*);
    virtual void addAnimation(QCanvasItem*);
    virtual void removeItem(QCanvasItem*);
    virtual void removeAnimation(QCanvasItem*);

    virtual void setAdvancePeriod(int ms);
    virtual void setUpdatePeriod(int ms);

    virtual void setDoubleBuffering(bool y);

signals:
    void resized();

public slots:
    virtual void advance();
    virtual void update();

protected:
    virtual void drawBackground(QPainter&, const QRect& area);
    virtual void drawForeground(QPainter&, const QRect& area);

private:
    void init(int w, int h, int chunksze=16, int maxclust=100);

    QCanvasChunk& chunk(int i, int j) const;
    QCanvasChunk& chunkContaining(int x, int y) const;

    QRect changeBounds(const QRect& inarea);
    void drawChanges(const QRect& inarea);

    void ensureOffScrSize( int osw, int osh );
    QPixmap offscr;
    int awidth,aheight;
    int chunksize;
    int maxclusters;
    int chwidth,chheight;
    QCanvasChunk* chunks;

    QCanvasData* d;

    void initTiles(QPixmap p, int h, int v, int tilewidth, int tileheight);
    ushort *grid;
    ushort htiles;
    ushort vtiles;
    ushort tilew;
    ushort tileh;
    bool oneone;
    QPixmap pm;
    QTimer* update_timer;
    QColor bgcolor;
    bool debug_redraw_areas;
    bool dblbuf;

    friend void qt_unview(QCanvas* c);
};

class QCanvasViewData;

class QM_EXPORT_CANVAS QCanvasView : public QScrollView
{
    Q_OBJECT
public:

    QCanvasView(QWidget* parent=0, const char* name=0, WFlags f=0);
    QCanvasView(QCanvas* viewing, QWidget* parent=0, const char* name=0, WFlags f=0);
    ~QCanvasView();

    QCanvas* canvas() const
    { return viewing; }
    void setCanvas(QCanvas* v);

    const QWMatrix &worldMatrix() const;
    const QWMatrix &inverseWorldMatrix() const;
    bool setWorldMatrix( const QWMatrix & );

protected:
    void drawContents( QPainter*, int cx, int cy, int cw, int ch );
    QSize sizeHint() const;

private:
    void drawContents( QPainter* );
    QCanvas* viewing;
    QCanvasViewData* d;
    friend void qt_unview(QCanvas* c);

private slots:
    void cMoving(int,int);
    void updateContentsSize();
};

class QM_EXPORT_CANVAS QCanvasPixmap : public QPixmap
{
public:
#ifndef QT_NO_IMAGEIO
    QCanvasPixmap(const QString& datafilename);
#endif
    QCanvasPixmap(const QImage& image);
    QCanvasPixmap(const QPixmap&, const QPoint& hotspot);
    ~QCanvasPixmap();

    int offsetX() const
    { return hotx; }
    int offsetY() const
    { return hoty; }
    void setOffset(int x, int y) { hotx = x; hoty = y; }

private:
    void init(const QImage&);
    void init(const QPixmap& pixmap, int hx, int hy);

    friend class QCanvasSprite;
    friend class QCanvasPixmapArray;
    friend bool qt_testCollision(const QCanvasSprite* s1, const QCanvasSprite* s2);

    int hotx,hoty;

    QImage* collision_mask;
};

class QM_EXPORT_CANVAS QCanvasPixmapArray
{
public:
    QCanvasPixmapArray();
#ifndef QT_NO_IMAGEIO
    QCanvasPixmapArray(const QString& datafilenamepattern, int framecount=0);
#endif
    // this form is deprecated
    QCanvasPixmapArray(QPtrList<QPixmap>, QPtrList<QPoint> hotspots);

    QCanvasPixmapArray(QValueList<QPixmap>, QPointArray hotspots = QPointArray() );
    ~QCanvasPixmapArray();

#ifndef QT_NO_IMAGEIO
    bool readPixmaps(const QString& datafilenamepattern, int framecount=0);
    bool readCollisionMasks(const QString& filenamepattern);
#endif

    // deprecated
    bool operator!(); // Failure check.
    bool isValid() const;

    QCanvasPixmap* image(int i) const
    { return img ? img[i] : 0; }
    void setImage(int i, QCanvasPixmap* p);
    uint count() const
    { return (uint)framecount; }

private:
#ifndef QT_NO_IMAGEIO
    bool readPixmaps(const QString& datafilenamepattern, int framecount, bool maskonly);
#endif

    void reset();
    int framecount;
    QCanvasPixmap** img;
};

class QM_EXPORT_CANVAS QCanvasSprite : public QCanvasItem
{
public:
    QCanvasSprite(QCanvasPixmapArray* array, QCanvas* canvas);

    void setSequence(QCanvasPixmapArray* seq);

    virtual ~QCanvasSprite();

    void move(double x, double y);
    virtual void move(double x, double y, int frame);
    void setFrame(int);
    enum FrameAnimationType { Cycle, Oscillate };
    virtual void setFrameAnimation(FrameAnimationType=Cycle, int step=1, int state=0);
    int frame() const
    { return frm; }
    int frameCount() const
    { return images->count(); }

    int rtti() const;
    static int RTTI;

    bool collidesWith( const QCanvasItem* ) const;

    QRect boundingRect() const;

    // is there a reason for these to be protected? Lars
//protected:

    int width() const;
    int height() const;

    int leftEdge() const;
    int topEdge() const;
    int rightEdge() const;
    int bottomEdge() const;

    int leftEdge(int nx) const;
    int topEdge(int ny) const;
    int rightEdge(int nx) const;
    int bottomEdge(int ny) const;
    QCanvasPixmap* image() const
    { return images->image(frm); }
    virtual QCanvasPixmap* imageAdvanced() const;
    QCanvasPixmap* image(int f) const
    { return images->image(f); }
    virtual void advance(int stage);

public:
    void draw(QPainter& painter);

private:
    void addToChunks();
    void removeFromChunks();
    void changeChunks();

    int frm;
    ushort anim_val;
    uint anim_state:2;
    uint anim_type:14;
    bool collidesWith( const QCanvasSprite*,
               const QCanvasPolygonalItem*,
               const QCanvasRectangle*,
               const QCanvasEllipse*,
               const QCanvasText* ) const;

    friend bool qt_testCollision( const QCanvasSprite* s1,
                  const QCanvasSprite* s2 );

    QCanvasPixmapArray* images;
};

class QPolygonalProcessor;

class QM_EXPORT_CANVAS QCanvasPolygonalItem : public QCanvasItem
{
public:
    QCanvasPolygonalItem(QCanvas* canvas);
    virtual ~QCanvasPolygonalItem();

    bool collidesWith( const QCanvasItem* ) const;

    virtual void setPen(QPen p);
    virtual void setBrush(QBrush b);

    QPen pen() const
    { return pn; }
    QBrush brush() const
    { return br; }

    virtual QPointArray areaPoints() const=0;
    virtual QPointArray areaPointsAdvanced() const;
    QRect boundingRect() const;

    int rtti() const;
    static int RTTI;

protected:
    void draw(QPainter &);
    virtual void drawShape(QPainter &) = 0;

    bool winding() const;
    void setWinding(bool);

private:
    void scanPolygon( const QPointArray& pa, int winding,
              QPolygonalProcessor& process ) const;
    QPointArray chunks() const;

    bool collidesWith( const QCanvasSprite*,
               const QCanvasPolygonalItem*,
               const QCanvasRectangle*,
               const QCanvasEllipse*,
               const QCanvasText* ) const;

    QBrush br;
    QPen pn;
    uint wind:1;
};

class QM_EXPORT_CANVAS QCanvasRectangle : public QCanvasPolygonalItem
{
public:
    QCanvasRectangle(QCanvas* canvas);
    QCanvasRectangle(const QRect&, QCanvas* canvas);
    QCanvasRectangle(int x, int y, int width, int height, QCanvas* canvas);

    ~QCanvasRectangle();

    int width() const;
    int height() const;
    void setSize(int w, int h);
    QSize size() const
    { return QSize(w,h); }
    QPointArray areaPoints() const;
    QRect rect() const
    { return QRect(int(x()),int(y()),w,h); }

    bool collidesWith( const QCanvasItem* ) const;

    int rtti() const;
    static int RTTI;

protected:
    void drawShape(QPainter &);
    QPointArray chunks() const;

private:
    bool collidesWith(   const QCanvasSprite*,
             const QCanvasPolygonalItem*,
             const QCanvasRectangle*,
             const QCanvasEllipse*,
             const QCanvasText* ) const;

    int w, h;
};

class QM_EXPORT_CANVAS QCanvasPolygon : public QCanvasPolygonalItem
{
public:
    QCanvasPolygon(QCanvas* canvas);
    ~QCanvasPolygon();
    void setPoints(QPointArray);
    QPointArray points() const;
    void moveBy(double dx, double dy);

    QPointArray areaPoints() const;

    int rtti() const;
    static int RTTI;

protected:
    void drawShape(QPainter &);
    QPointArray poly;
};

class QM_EXPORT_CANVAS QCanvasSpline : public QCanvasPolygon
{
public:
    QCanvasSpline(QCanvas* canvas);
    ~QCanvasSpline();

    void setControlPoints(QPointArray, bool closed=TRUE);
    QPointArray controlPoints() const;
    bool closed() const;

    int rtti() const;
    static int RTTI;

private:
    void recalcPoly();
    QPointArray bez;
    bool cl;
};

class QM_EXPORT_CANVAS QCanvasLine : public QCanvasPolygonalItem
{
public:
    QCanvasLine(QCanvas* canvas);
    ~QCanvasLine();
    void setPoints(int x1, int y1, int x2, int y2);

    QPoint startPoint() const
    { return QPoint(x1,y1); }
    QPoint endPoint() const
    { return QPoint(x2,y2); }

    int rtti() const;
    static int RTTI;

    void setPen(QPen p);

protected:
    void drawShape(QPainter &);
    QPointArray areaPoints() const;

private:
    int x1,y1,x2,y2;
};

class QM_EXPORT_CANVAS QCanvasEllipse : public QCanvasPolygonalItem
{

public:
    QCanvasEllipse( QCanvas* canvas );
    QCanvasEllipse( int width, int height, QCanvas* canvas );
    QCanvasEllipse( int width, int height, int startangle, int angle,
            QCanvas* canvas );

    ~QCanvasEllipse();

    int width() const;
    int height() const;
    void setSize(int w, int h);
    void setAngles(int start, int length);
    int angleStart() const
    { return a1; }
    int angleLength() const
    { return a2; }
    QPointArray areaPoints() const;

    bool collidesWith( const QCanvasItem* ) const;

    int rtti() const;
    static int RTTI;

protected:
    void drawShape(QPainter &);

private:
    bool collidesWith( const QCanvasSprite*,
               const QCanvasPolygonalItem*,
               const QCanvasRectangle*,
               const QCanvasEllipse*,
               const QCanvasText* ) const;
    int w, h;
    int a1, a2;
};

class QCanvasTextExtra;

class QM_EXPORT_CANVAS QCanvasText : public QCanvasItem
{
public:
    QCanvasText(QCanvas* canvas);
    QCanvasText(const QString&, QCanvas* canvas);
    QCanvasText(const QString&, QFont, QCanvas* canvas);

    virtual ~QCanvasText();

    void setText( const QString& );
    void setFont( const QFont& );
    void setColor( const QColor& );
    QString text() const;
    QFont font() const;
    QColor color() const;

    void moveBy(double dx, double dy);

    int textFlags() const
    { return flags; }
    void setTextFlags(int);

    QRect boundingRect() const;

    bool collidesWith( const QCanvasItem* ) const;

    int rtti() const;
    static int RTTI;

protected:
    virtual void draw(QPainter&);

private:
    void addToChunks();
    void removeFromChunks();
    void changeChunks();

    void setRect();
    QRect brect;
    QString txt;
    int flags;
    QFont fnt;
    QColor col;
    QCanvasTextExtra* extra;

    bool collidesWith(   const QCanvasSprite*,
             const QCanvasPolygonalItem*,
             const QCanvasRectangle*,
             const QCanvasEllipse*,
             const QCanvasText* ) const;
};

#endif // QT_NO_CANVAS

#endif // QCANVAS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCanvas Member List

Complete Member List for QCanvas

This is the complete list of member functions for QCanvas, including inherited members.

  • QCanvas()
  • ~QCanvas()
  • advance()
  • allItems()
  • backgroundColor()
  • backgroundPixmap()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • chunkSize()
  • className()
  • collisions()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawArea()
  • drawBackground()
  • drawForeground()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • height()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • onCanvas()
  • parent()
  • property()
  • queryList()
  • rect()
  • removeChild()
  • removeEventFilter()
  • resize()
  • resized()
  • retune()
  • sender()
  • setAdvancePeriod()
  • setAllChanged()
  • setBackgroundColor()
  • setBackgroundPixmap()
  • setChanged()
  • setDoubleBuffering()
  • setName()
  • setProperty()
  • setTile()
  • setTiles()
  • setUnchanged()
  • setUpdatePeriod()
  • signalsBlocked()
  • size()
  • startTimer()
  • tile()
  • tileHeight()
  • tileWidth()
  • tilesHorizontally()
  • tilesVertically()
  • timerEvent()
  • tr()
  • trUtf8()
  • update()
  • validChunk()
  • width()


QCanvasEllipse Class

QCanvasEllipse Class Reference
[canvas module]

The QCanvasEllipse class provides an ellipse or ellipse segment on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasPolygonalItem.

List of all member functions.

Public Members

  • QCanvasEllipse ( QCanvas * canvas )
  • QCanvasEllipse ( int width, int height, QCanvas * canvas )
  • QCanvasEllipse ( int width, int height, int startangle, int angle, QCanvas * canvas )
  • ~QCanvasEllipse ()
  • int width () const
  • int height () const
  • void setSize ( int width, int height )
  • void setAngles ( int start, int length )
  • int angleStart () const
  • int angleLength () const
  • virtual int rtti () const

Protected Members

  • virtual void drawShape ( QPainter & p )

Detailed Description

The QCanvasEllipse class provides an ellipse or ellipse segment on a QCanvas.

A canvas item that paints an ellipse or ellipse segment with a QBrush. The ellipse's height, width, start angle and angle length can be set at construction time. The size can be changed at runtime with setSize(), and the angles can be changed (if you're displaying an ellipse segment rather than a whole ellipse) with setAngles().

Note that angles are specified in 16ths of a degree.

If a start angle and length angle are set then an ellipse segment will be drawn. The start angle is the angle that goes from zero in a counter-clockwise direction (shown in green in the diagram). The length angle is the angle from the start angle in a counter-clockwise direction (shown in blue in the diagram). The blue segment is the segment of the ellipse that would be drawn. If no start angle and length angle are specified the entire ellipse is drawn.

The ellipse can be drawn on a painter with drawShape().

Like any other canvas item ellipses can be moved with move() and moveBy(), or by setting coordinates with setX(), setY() and setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasEllipse::QCanvasEllipse ( QCanvas * canvas )

Constructs a 32x32 ellipse, centered at (0, 0) on canvas.

QCanvasEllipse::QCanvasEllipse ( int width, int height, QCanvas * canvas )

Constructs a width by height pixel ellipse, centered at (0,0) on canvas.

QCanvasEllipse::QCanvasEllipse ( int width, int height, int startangle, int angle, QCanvas * canvas )

Constructs a width by height pixel ellipse, centered at (0,0) on canvas. Only a segment of the ellipse is drawn, starting at angle startangle, and extending for angle angle (the angle length).

Note that angles are specified in 1/16ths of a degree.

QCanvasEllipse::~QCanvasEllipse ()

Destroys the ellipse.

int QCanvasEllipse::angleLength () const

Returns the length angle (the extent of the ellipse segment) in 16ths of a degree. Initially this will be 360 * 16 (a complete ellipse).

See also setAngles() and angleStart().

int QCanvasEllipse::angleStart () const

Returns the start angle in 16ths of a degree. Initially this will be 0.

See also setAngles() and angleLength().

void QCanvasEllipse::drawShape ( QPainter & p ) [virtual protected]

Draws the ellipse, centered at x(), y() using the painter p.

Note that QCanvasEllipse does not support an outline (pen is always NoPen).

Reimplemented from QCanvasPolygonalItem.

int QCanvasEllipse::height () const

Returns the height of the ellipse.

int QCanvasEllipse::rtti () const [virtual]

Returns 6 (QCanvasItem::Rtti_Ellipse).

See also QCanvasItem::rtti().

Reimplemented from QCanvasPolygonalItem.

void QCanvasEllipse::setAngles ( int start, int length )

Sets the angles for the ellipse. The start angle is start and the extent of the segment is length (the angle length) from the start. The angles are specified in 16ths of a degree. By default the ellipse will start at 0 and have an angle length of 360 * 16 (a complete ellipse).

See also angleStart() and angleLength().

void QCanvasEllipse::setSize ( int width, int height )

Sets the width and height of the ellipse.

int QCanvasEllipse::width () const

Returns the width of the ellipse.

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


QCanvasEllipse Member List

Complete Member List for QCanvasEllipse

This is the complete list of member functions for QCanvasEllipse, including inherited members.

  • QCanvasEllipse()
  • ~QCanvasEllipse()
  • active()
  • advance()
  • angleLength()
  • angleStart()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • drawShape()
  • enabled()
  • height()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • rtti()
  • selected()
  • setActive()
  • setAngles()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setEnabled()
  • setPen()
  • setSelected()
  • setSize()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • update()
  • visible()
  • width()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasItem Class

QCanvasItem Class Reference
[canvas module]

The QCanvasItem class provides an abstract graphic object on a QCanvas. More...

#include <qcanvas.h>

Inherits Qt.

Inherited by QCanvasSprite, QCanvasPolygonalItem and QCanvasText.

List of all member functions.

Public Members

  • QCanvasItem ( QCanvas * canvas )
  • virtual ~QCanvasItem ()
  • double x () const
  • double y () const
  • double z () const
  • virtual void moveBy ( double dx, double dy )
  • void move ( double x, double y )
  • void setX ( double x )
  • void setY ( double y )
  • void setZ ( double z )
  • bool animated () const
  • virtual void setAnimated ( bool y )
  • virtual void setVelocity ( double vx, double vy )
  • void setXVelocity ( double vx )
  • void setYVelocity ( double vy )
  • double xVelocity () const
  • double yVelocity () const
  • virtual void advance ( int phase )
  • virtual bool collidesWith ( const QCanvasItem * other ) const = 0
  • QCanvasItemList collisions ( bool exact ) const
  • virtual void setCanvas ( QCanvas * c )
  • virtual void draw ( QPainter & painter ) = 0
  • void show ()
  • void hide ()
  • virtual void setVisible ( bool yes )
  • bool isVisible () const
  • virtual void setSelected ( bool yes )
  • bool isSelected () const
  • virtual void setEnabled ( bool yes )
  • bool isEnabled () const
  • virtual void setActive ( bool yes )
  • bool isActive () const
  • bool visible () const (obsolete)
  • bool selected () const (obsolete)
  • bool enabled () const (obsolete)
  • bool active () const (obsolete)
  • enum RttiValues { Rtti_Item = 0, Rtti_Sprite = 1, Rtti_PolygonalItem = 2, Rtti_Text = 3, Rtti_Polygon = 4, Rtti_Rectangle = 5, Rtti_Ellipse = 6, Rtti_Line = 7, Rtti_Spline = 8 }
  • virtual int rtti () const
  • virtual QRect boundingRect () const = 0
  • virtual QRect boundingRectAdvanced () const
  • QCanvas * canvas () const

Protected Members

  • void update ()

Detailed Description

The QCanvasItem class provides an abstract graphic object on a QCanvas.

A variety of QCanvasItem subclasses provide immediately usable behaviour. This class is a pure abstract superclass providing the behaviour that is shared among all the concrete canvas item classes. QCanvasItem is not intended for direct subclassing. It is much easier to subclass one of its subclasses, e.g. QCanvasPolygonalItem (the commonest base class), QCanvasRectangle, QCanvasSprite, QCanvasEllipse or QCanvasText.

Canvas items are added to a canvas by constructing them and passing the canvas to the canvas item's constructor. An item can be moved to a different canvas using setCanvas().

Items appear on the canvas after their show() function has been called (or setVisible(TRUE)), and after update() has been called. The canvas only shows items that are visible, and then only if update() is called. If you created the canvas without passing a width and height to the constructor you'll also need to call resize().

A QCanvasItem object can be moved in the x(), y() and z() dimensions using functions such as move(), moveBy(), setX(), setY() and setZ(). A canvas item can be set in motion, `animated', using setAnimated() and given a velocity in the x and y directions with setXVelocity() and setYVelocity() -- the same effect can be achieved by calling setVelocity(). Use the collidesWith() function to see if the canvas item will collide on the next advance(1) and use collisions() to see what collisions have occurred.

Use QCanvasSprite or your own subclass of QCanvasSprite to create canvas items which are animated, i.e. which change over time.

The size of a canvas item is given by boundingRect(). Use boundingRectAdvanced() to see what the size of the canvas item will be after the next advance(1) call.

The rtti() function is used for identifying subclasses of QCanvasItem. The canvas() function returns a pointer to the canvas which contains the canvas item.

QCanvasItem provides the show() and isVisible() functions like those in QWidget.

QCanvasItem also provides the setEnabled(), setActive() and setSelected() functions; these functions set the relevant boolean and cause a repaint but the boolean values they set are not used in QCanvasItem itself. You can make use of these booleans in your subclasses.

By default, canvas items have no velocity, no size, and are not in motion. The subclasses provided in Qt do not change these defaults except where noted.

See also Graphics Classes and Image Processing Classes.

Member Type Documentation

QCanvasItem::RttiValues

This enum is used to name the different types of canvas item.

  • QCanvasItem::Rtti_Item - Canvas item abstract base class
  • QCanvasItem::Rtti_Ellipse
  • QCanvasItem::Rtti_Line
  • QCanvasItem::Rtti_Polygon
  • QCanvasItem::Rtti_PolygonalItem
  • QCanvasItem::Rtti_Rectangle
  • QCanvasItem::Rtti_Spline
  • QCanvasItem::Rtti_Sprite
  • QCanvasItem::Rtti_Text

Member Function Documentation

QCanvasItem::QCanvasItem ( QCanvas * canvas )

Constructs a QCanvasItem on canvas canvas.

See also setCanvas().

QCanvasItem::~QCanvasItem () [virtual]

Destroys the QCanvasItem and removes it from its canvas.

bool QCanvasItem::active () const

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

Use isActive() instead.

void QCanvasItem::advance ( int phase ) [virtual]

The default implementation moves the canvas item, if it is animated(), by the preset velocity if phase is 1, and does nothing if phase is 0.

Note that if you reimplement this function, the reimplementation must not change the canvas in any way, for example it must not add or remove items.

See also QCanvas::advance() and setVelocity().

Example: canvas/canvas.cpp.

Reimplemented in QCanvasSprite.

bool QCanvasItem::animated () const

Returns TRUE is the canvas item is in motion; otherwise returns FALSE.

See also setVelocity() and setAnimated().

QRect QCanvasItem::boundingRect () const [pure virtual]

Returns the bounding rectangle in pixels that the canvas item covers.

See also boundingRectAdvanced().

Reimplemented in QCanvasSprite, QCanvasPolygonalItem and QCanvasText.

QRect QCanvasItem::boundingRectAdvanced () const [virtual]

Returns the bounding rectangle of pixels that the canvas item will cover after advance(1) is called.

See also boundingRect().

QCanvas * QCanvasItem::canvas () const

Returns the canvas containing the canvas item.

bool QCanvasItem::collidesWith ( const QCanvasItem * other ) const [pure virtual]

Returns TRUE if the canvas item will collide with the other item after they have moved by their current velocities; otherwise returns FALSE.

See also collisions().

Example: canvas/canvas.cpp.

QCanvasItemList QCanvasItem::collisions ( bool exact ) const

Returns the list of canvas items that this canvas item has collided with.

A collision is generally defined as occurring when the pixels of one item draw on the pixels of another item, but not all subclasses are so precise. Also, since pixel-wise collision detection can be slow, this function works in either exact or inexact mode, according to the exact parameter.

If exact is TRUE, the canvas items returned have been accurately tested for collision with the canvas item.

If exact is FALSE, the canvas items returned are near the canvas item. You can test the canvas items returned using collidesWith() if any are interesting collision candidates. By using this approach, you can ignore some canvas items for which collisions are not relevant.

The returned list is a list of QCanvasItems, but often you will need to cast the items to their subclass types. The safe way to do this is to use rtti() before casting. This provides some of the functionality of the standard C++ dynamic cast operation even on compilers where dynamic casts are not available.

Note that a canvas item may be `on' a canvas, e.g. it was created with the canvas as parameter, even though its coordinates place it beyond the edge of the canvas's area. Collision detection only works for canvas items which are wholly or partly within the canvas's area.

void QCanvasItem::draw ( QPainter & painter ) [pure virtual]

This abstract virtual function draws the canvas item using painter.

Reimplemented in QCanvasSprite, QCanvasPolygonalItem and QCanvasText.

bool QCanvasItem::enabled () const

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

Use isEnabled() instead.

void QCanvasItem::hide ()

Shorthand for setVisible(FALSE).

bool QCanvasItem::isActive () const

Returns TRUE if the QCanvasItem is active; otherwise returns FALSE.

bool QCanvasItem::isEnabled () const

Returns TRUE if the QCanvasItem is enabled; otherwise returns FALSE.

bool QCanvasItem::isSelected () const

Returns TRUE if the canvas item is selected; otherwise returns FALSE.

bool QCanvasItem::isVisible () const

Returns TRUE if the canvas item is visible; otherwise returns FALSE.

Note that in this context TRUE does not mean that the canvas item is currently in a view, merely that if a view is showing the area where the canvas item is positioned, and the item is not obscured by items with higher z values, and the view is not obscured by overlaying windows, it would be visible.

See also setVisible() and z().

void QCanvasItem::move ( double x, double y )

Moves the canvas item to the absolute position (x, y).

Example: canvas/canvas.cpp.

void QCanvasItem::moveBy ( double dx, double dy ) [virtual]

Moves the canvas item relative to its current position by (dx, dy).

Example: canvas/canvas.cpp.

int QCanvasItem::rtti () const [virtual]

Returns 0 (QCanvasItem::Rtti_Item).

Make your derived classes return their own values for rtti(), so that you can distinguish between objects returned by QCanvas::at(). You should use values greater than 1000 to allow for extensions to this class.

Overuse of this functionality can damage it's extensibility. For example, once you have identified a base class of a QCanvasItem found by QCanvas::at(), cast it to that type and call meaningful methods rather than acting upon the object based on its rtti value.

For example:

    QCanvasItem* item;
    // Find an item, eg. with QCanvasItem::collisions().
    ...
    if (item->rtti() == MySprite::RTTI ) {
        MySprite* s = (MySprite*)item;
        if (s->isDamagable()) s->loseHitPoints(1000);
        if (s->isHot()) myself->loseHitPoints(1000);
        ...
    }

Example: canvas/canvas.cpp.

Reimplemented in QCanvasSprite, QCanvasPolygonalItem and QCanvasText.

bool QCanvasItem::selected () const

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

Use isSelected() instead.

void QCanvasItem::setActive ( bool yes ) [virtual]

Sets the active flag of the item to yes. If this changes the item's active state the item will be redrawn when QCanvas::update() is next called.

The QCanvas, QCanvasItem and the Qt-supplied QCanvasItem subclasses do not make use of this value. The setActive() function is supplied because many applications need it, but it is up to you how you use the isActive() value.

void QCanvasItem::setAnimated ( bool y ) [virtual]

Sets the canvas item to be in motion if y is TRUE, or not if y is FALSE. The speed and direction of the motion is set with setVelocity(), or setXVelocity() and setYVelocity().

See also advance() and QCanvas::advance().

void QCanvasItem::setCanvas ( QCanvas * c ) [virtual]

Sets the QCanvas upon which the canvas item is to be drawn to c.

See also canvas().

void QCanvasItem::setEnabled ( bool yes ) [virtual]

Sets the enabled flag of the item to yes. If this changes the item's enabled state the item will be redrawn when QCanvas::update() is next called.

The QCanvas, QCanvasItem and the Qt-supplied QCanvasItem subclasses do not make use of this value. The setEnabled() function is supplied because many applications need it, but it is up to you how you use the isEnabled() value.

void QCanvasItem::setSelected ( bool yes ) [virtual]

Sets the selected flag of the item to yes. If this changes the item's selected state the item will be redrawn when QCanvas::update() is next called.

The QCanvas, QCanvasItem and the Qt-supplied QCanvasItem subclasses do not make use of this value. The setSelected() function is supplied because many applications need it, but it is up to you how you use the isSelected() value.

void QCanvasItem::setVelocity ( double vx, double vy ) [virtual]

Sets the canvas item to be in motion, moving by vx and vy pixels in the horizontal and vertical directions respectively.

See also advance().

void QCanvasItem::setVisible ( bool yes ) [virtual]

Makes the canvas item visible if yes is TRUE, or invisible if yes is FALSE. The change takes effect when QCanvas::update() is next called.

void QCanvasItem::setX ( double x )

Moves the canvas item so that its x-position is x.

See also x() and move().

Example: chart/chartform_canvas.cpp.

void QCanvasItem::setXVelocity ( double vx )

Sets the horizontal component of the canvas item's velocity to vx.

void QCanvasItem::setY ( double y )

Moves the canvas item so that its y-position is y.

See also y() and move().

Example: chart/chartform_canvas.cpp.

void QCanvasItem::setYVelocity ( double vy )

Sets the vertical component of the canvas item's velocity to vy.

void QCanvasItem::setZ ( double z )

Sets the z index of the canvas item to z. Higher-z items obscure (are in front of) lower-z items.

See also z() and move().

Examples: canvas/canvas.cpp and chart/chartform_canvas.cpp.

void QCanvasItem::show ()

Shorthand for setVisible(TRUE).

Examples: canvas/canvas.cpp and chart/chartform_canvas.cpp.

void QCanvasItem::update () [protected]

Call this function to repaint the canvas's changed chunks.

bool QCanvasItem::visible () const

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

Use isVisible() instead.

double QCanvasItem::x () const

Returns the horizontal position of the canvas item. Note that subclasses often have an origin other than the top-left corner.

Example: canvas/canvas.cpp.

double QCanvasItem::xVelocity () const

Returns the horizontal velocity component of the canvas item.

double QCanvasItem::y () const

Returns the vertical position of the canvas item. Note that subclasses often have an origin other than the top-left corner.

Example: canvas/canvas.cpp.

double QCanvasItem::yVelocity () const

Returns the vertical velocity component of the canvas item.

double QCanvasItem::z () const

Returns the z index of the canvas item, which is used for visual order: higher-z items obscure (are in front of) lower-z items.

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


QCanvasItem Member List

Complete Member List for QCanvasItem

This is the complete list of member functions for QCanvasItem, including inherited members.

  • QCanvasItem()
  • ~QCanvasItem()
  • active()
  • advance()
  • animated()
  • boundingRect()
  • boundingRectAdvanced()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • enabled()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setCanvas()
  • setEnabled()
  • setSelected()
  • setVelocity()
  • setVisible()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • update()
  • visible()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasItemList Class

QCanvasItemList Class Reference
[canvas module]

The QCanvasItemList class is a list of QCanvasItems. More...

#include <qcanvas.h>

Inherits QValueList<QCanvasItem * >.

List of all member functions.

Detailed Description

The QCanvasItemList class is a list of QCanvasItems.

QCanvasItemList is a QValueList of pointers to QCanvasItems. This class is used by some methods in QCanvas that need to return a list of canvas items.

The QValueList documentation describes how to use this list.

See also Graphics Classes and Image Processing Classes.

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


QCanvasItemList Member List

Complete Member List for QCanvasItemList

This is the complete list of member functions for QCanvasItemList, including inherited members.

  • append()
  • at()
  • back()
  • begin()
  • clear()
  • contains()
  • count()
  • empty()
  • end()
  • erase()
  • find()
  • findIndex()
  • first()
  • fromLast()
  • front()
  • insert()
  • isEmpty()
  • last()
  • operator!=()
  • operator+()
  • operator+=()
  • operator<<()
  • operator=()
  • operator==()
  • operator[]()
  • pop_back()
  • pop_front()
  • prepend()
  • push_back()
  • push_front()
  • remove()
  • size()


QCanvasLine Class

QCanvasLine Class Reference
[canvas module]

The QCanvasLine class provides a line on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasPolygonalItem.

List of all member functions.

Public Members

  • QCanvasLine ( QCanvas * canvas )
  • ~QCanvasLine ()
  • void setPoints ( int xa, int ya, int xb, int yb )
  • QPoint startPoint () const
  • QPoint endPoint () const
  • virtual int rtti () const

Detailed Description

The QCanvasLine class provides a line on a QCanvas.

The line inherits functionality from QCanvasPolygonalItem, for example the setPen() function. The start and end points of the line are set with setPoints().

Like any other canvas item lines can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasLine::QCanvasLine ( QCanvas * canvas )

Constructs a line from (0,0) to (0,0) on canvas.

See also setPoints().

QCanvasLine::~QCanvasLine ()

Destroys the line.

QPoint QCanvasLine::endPoint () const

Returns the end point of the line.

See also setPoints() and startPoint().

int QCanvasLine::rtti () const [virtual]

Returns 7 (QCanvasItem::Rtti_Line).

See also QCanvasItem::rtti().

Reimplemented from QCanvasPolygonalItem.

void QCanvasLine::setPoints ( int xa, int ya, int xb, int yb )

Sets the line's start point to (xa, ya) and its end point to (xb, yb).

Example: canvas/canvas.cpp.

QPoint QCanvasLine::startPoint () const

Returns the start point of the line.

See also setPoints() and endPoint().

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


QCanvasLine Member List

Complete Member List for QCanvasLine

This is the complete list of member functions for QCanvasLine, including inherited members.

  • QCanvasLine()
  • ~QCanvasLine()
  • active()
  • advance()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • drawShape()
  • enabled()
  • endPoint()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setEnabled()
  • setPen()
  • setPoints()
  • setSelected()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • startPoint()
  • update()
  • visible()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasPixmap Class

QCanvasPixmap Class Reference
[canvas module]

The QCanvasPixmap class provides pixmaps for QCanvasSprites. More...

#include <qcanvas.h>

Inherits QPixmap.

List of all member functions.

Public Members

  • QCanvasPixmap ( const QString & datafilename )
  • QCanvasPixmap ( const QImage & image )
  • QCanvasPixmap ( const QPixmap & pm, const QPoint & offset )
  • ~QCanvasPixmap ()
  • int offsetX () const
  • int offsetY () const
  • void setOffset ( int x, int y )

Detailed Description

The QCanvasPixmap class provides pixmaps for QCanvasSprites.

If you want to show a single pixmap on a QCanvas use a QCanvasSprite with just one pixmap.

When pixmaps are inserted into a QCanvasPixmapArray they are held as QCanvasPixmaps. QCanvasSprites are used to show pixmaps on QCanvases and hold their pixmaps in a QCanvasPixmapArray. If you retrieve a frame (pixmap) from a QCanvasSprite it will be returned as a QCanvasPixmap.

The pixmap is a QPixmap and can only be set in the constructor. There are three different constructors, one taking a QPixmap, one a QImage and one a file name that refers to a file in any supported file format (see QImageIO).

QCanvasPixmap can have a hotspot which is defined in terms of an (x, y) offset. When you create a QCanvasPixmap from a PNG file or from a QImage that has a QImage::offset(), the offset() is initialized appropriately, otherwise the constructor leaves it at (0, 0). You can set it later using setOffset(). When the QCanvasPixmap is used in a QCanvasSprite, the offset position is the point at QCanvasItem::x() and QCanvasItem::y(), not the top-left corner of the pixmap.

Note that for QCanvasPixmap objects created by a QCanvasSprite, the position of each QCanvasPixmap object is set so that the hotspot stays in the same position.

See also QCanvasPixmapArray, QCanvasItem, QCanvasSprite, Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasPixmap::QCanvasPixmap ( const QString & datafilename )

Constructs a QCanvasPixmap that uses the image stored in datafilename.

QCanvasPixmap::QCanvasPixmap ( const QImage & image )

Constructs a QCanvasPixmap from the image image.

QCanvasPixmap::QCanvasPixmap ( const QPixmap & pm, const QPoint & offset )

Constructs a QCanvasPixmap from the pixmap pm using the offset offset.

QCanvasPixmap::~QCanvasPixmap ()

Destroys the pixmap.

int QCanvasPixmap::offsetX () const

Returns the x-offset of the pixmap's hotspot.

See also setOffset().

int QCanvasPixmap::offsetY () const

Returns the y-offset of the pixmap's hotspot.

See also setOffset().

void QCanvasPixmap::setOffset ( int x, int y )

Sets the offset of the pixmap's hotspot to (x, y).

Warning: Do not call this function if any QCanvasSprites are currently showing this pixmap.

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


QCanvasPixmap Member List

Complete Member List for QCanvasPixmap

This is the complete list of member functions for QCanvasPixmap, including inherited members.

  • QCanvasPixmap()
  • ~QCanvasPixmap()
  • cmd()
  • convertFromImage()
  • convertToImage()
  • createHeuristicMask()
  • defaultDepth()
  • defaultOptimization()
  • depth()
  • detach()
  • fill()
  • grabWidget()
  • grabWindow()
  • handle()
  • height()
  • imageFormat()
  • isExtDev()
  • isNull()
  • isQBitmap()
  • load()
  • loadFromData()
  • mask()
  • metric()
  • offsetX()
  • offsetY()
  • operator=()
  • optimization()
  • paintingActive()
  • rect()
  • resize()
  • save()
  • selfMask()
  • serialNumber()
  • setDefaultOptimization()
  • setMask()
  • setOffset()
  • setOptimization()
  • size()
  • trueMatrix()
  • width()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xForm()


QCanvasPixmapArray Class

QCanvasPixmapArray Class Reference
[canvas module]

The QCanvasPixmapArray class provides an array of QCanvasPixmaps. More...

#include <qcanvas.h>

List of all member functions.

Public Members

  • QCanvasPixmapArray ()
  • QCanvasPixmapArray ( const QString & datafilenamepattern, int fc = 0 )
  • QCanvasPixmapArray ( QPtrList<QPixmap> list, QPtrList<QPoint> hotspots ) (obsolete)
  • QCanvasPixmapArray ( QValueList<QPixmap> list, QPointArray hotspots = QPointArray ( ) )
  • ~QCanvasPixmapArray ()
  • bool readPixmaps ( const QString & filenamepattern, int fc = 0 )
  • bool readCollisionMasks ( const QString & filename )
  • bool operator! () (obsolete)
  • bool isValid () const
  • QCanvasPixmap * image ( int i ) const
  • void setImage ( int i, QCanvasPixmap * p )
  • uint count () const

Detailed Description

The QCanvasPixmapArray class provides an array of QCanvasPixmaps.

This class is used by QCanvasSprite to hold an array of pixmaps. It is used to implement animated sprites, i.e. images that change over time, with each pixmap in the array holding one frame.

Depending on the constructor you use you can load multiple pixmaps into the array, either from a directory (specifying a wildcard pattern for the files), or from a list of QPixmaps. You can also read in a set of pixmaps after construction using readPixmaps().

Individual pixmaps can be set with setImage() and retrieved with image(). The number of pixmaps in the array is returned by count().

QCanvasSprite uses an image's mask for collision detection. You can change this by reading in a separate set of image masks using readCollisionMasks().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasPixmapArray::QCanvasPixmapArray ()

Constructs an invalid array (i.e. isValid() will return FALSE). You must call readPixmaps() before being able to use this QCanvasPixmapArray.

QCanvasPixmapArray::QCanvasPixmapArray ( const QString & datafilenamepattern, int fc = 0 )

Constructs a QCanvasPixmapArray from files.

The fc parameter sets the number of frames to be loaded for this image.

If fc is not 0, datafilenamepattern should contain "%1", e.g. "foo%1.png". The actual filenames are formed by replacing the %1 with four-digit integers from 0 to (fc - 1), e.g. foo0000.png, foo0001.png, foo0002.png, etc.

If fc is 0, datafilenamepattern is asssumed to be a filename, and the image contained in this file will be loaded as the first (and only) frame.

If datafilenamepattern does not exist, is not readable, isn't an image, or some other error occurs, the array ends up empty and isValid() returns FALSE.

QCanvasPixmapArray::QCanvasPixmapArray ( QPtrList<QPixmap> list, QPtrList<QPoint> hotspots )

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

Use QCanvasPixmapArray::QCanvasPixmapArray( QValueList , QPointArray ) instead.

Constructs a QCanvasPixmapArray from the list of QPixmaps list. The hotspots list has to be of the same size as list.

QCanvasPixmapArray::QCanvasPixmapArray ( QValueList<QPixmap> list, QPointArray hotspots = QPointArray ( ) )

Constructs a QCanvasPixmapArray from the list of QPixmaps in the list. Each pixmap will get a hotspot according to the hotspots array. If no hotspots are specified, each one is set to be at position (0, 0).

If an error occurs, isValid() will return FALSE.

QCanvasPixmapArray::~QCanvasPixmapArray ()

Destroys the pixmap array and all the pixmaps it contains.

uint QCanvasPixmapArray::count () const

Returns the number of pixmaps in the array.

QCanvasPixmap * QCanvasPixmapArray::image ( int i ) const

Returns pixmap i in the array, if i is non-negative and less than than count(), and returns an unspecified value otherwise.

bool QCanvasPixmapArray::isValid () const

Returns TRUE if the pixmap array is valid; otherwise returns FALSE.

bool QCanvasPixmapArray::operator! ()

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

Use isValid() instead.

This returns FALSE if the array is valid, and TRUE if it is not.

bool QCanvasPixmapArray::readCollisionMasks ( const QString & filename )

Reads new collision masks for the array.

By default, QCanvasSprite uses the image mask of a sprite to detect collisions. Use this function to set your own collision image masks.

If count() is 1 filename must specify a real filename to read the mask from. If count() is greater than 1, the filename must contain a "%1" that will get replaced by the number of the mask to be loaded, similar to QCanvasPixmapArray::readPixmaps().

All collision masks must be 1-bit images or this function call will fail.

If the file isn't readable, contains the wrong number of images, or there is some other error, this function will return FALSE, and the array will be flagged as invalid; otherwise this function returns TRUE.

See also isValid().

bool QCanvasPixmapArray::readPixmaps ( const QString & filenamepattern, int fc = 0 )

Reads one or more pixmaps into the pixmap array.

If fc is not 0, filenamepattern should contain "%1", e.g. "foo%1.png". The actual filenames are formed by replacing the %1 with four-digit integers from 0 to (fc - 1), e.g. foo0000.png, foo0001.png, foo0002.png, etc.

If fc is 0, filenamepattern is asssumed to be a filename, and the image contained in this file will be loaded as the first (and only) frame.

If filenamepattern does not exist, is not readable, isn't an image, or some other error occurs, this function will return FALSE, and isValid() will return FALSE; otherwise this function will return TRUE.

See also isValid().

void QCanvasPixmapArray::setImage ( int i, QCanvasPixmap * p )

Replaces the pixmap at index i with pixmap p.

The array takes ownership of p and will delete p when the array itself is deleted.

If i is beyond the end of the array the array is extended to at least i+1 elements, with elements count() to i-1 being initialized to 0.

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


QCanvasPixmapArray Member List

Complete Member List for QCanvasPixmapArray

This is the complete list of member functions for QCanvasPixmapArray, including inherited members.

  • QCanvasPixmapArray()
  • ~QCanvasPixmapArray()
  • count()
  • image()
  • isValid()
  • operator!()
  • readCollisionMasks()
  • readPixmaps()
  • setImage()


QCanvasPolygon Class

QCanvasPolygon Class Reference
[canvas module]

The QCanvasPolygon class provides a polygon on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasPolygonalItem.

Inherited by QCanvasSpline.

List of all member functions.

Public Members

  • QCanvasPolygon ( QCanvas * canvas )
  • ~QCanvasPolygon ()
  • void setPoints ( QPointArray pa )
  • QPointArray points () const
  • virtual QPointArray areaPoints () const
  • virtual int rtti () const

Protected Members

  • virtual void drawShape ( QPainter & p )

Detailed Description

The QCanvasPolygon class provides a polygon on a QCanvas.

Paints a polygon with a QBrush. The polygon's points can be set in the constructor or set or changed later using setPoints(). Use points() to retrieve the points, or areaPoints() to retrieve the points relative to the canvas's origin.

The polygon can be drawn on a painter with drawShape().

Like any other canvas item polygons can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasPolygon::QCanvasPolygon ( QCanvas * canvas )

Constructs a point-less polygon on the canvas canvas. You should call setPoints() before using it further.

QCanvasPolygon::~QCanvasPolygon ()

Destroys the polygon.

QPointArray QCanvasPolygon::areaPoints () const [virtual]

Returns the vertices of the polygon translated by the polygon's current x(), y() position, i.e. relative to the canvas's origin.

See also setPoints() and points().

Reimplemented from QCanvasPolygonalItem.

void QCanvasPolygon::drawShape ( QPainter & p ) [virtual protected]

Draws the polygon using the painter p.

Note that QCanvasPolygon does not support an outline (pen is always NoPen).

Reimplemented from QCanvasPolygonalItem.

QPointArray QCanvasPolygon::points () const

Returns the vertices of the polygon, not translated by the position.

See also setPoints() and areaPoints().

int QCanvasPolygon::rtti () const [virtual]

Returns 4 (QCanvasItem::Rtti_Polygon).

See also QCanvasItem::rtti().

Reimplemented from QCanvasPolygonalItem.

Reimplemented in QCanvasSpline.

void QCanvasPolygon::setPoints ( QPointArray pa )

Sets the points of the polygon to be pa. These points will have their x and y coordinates automatically translated by x(), y() as the polygon is moved.

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


QCanvasPolygon Member List

Complete Member List for QCanvasPolygon

This is the complete list of member functions for QCanvasPolygon, including inherited members.

  • QCanvasPolygon()
  • ~QCanvasPolygon()
  • active()
  • advance()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • drawShape()
  • enabled()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • points()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setEnabled()
  • setPen()
  • setPoints()
  • setSelected()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • update()
  • visible()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasPolygonalItem Class

QCanvasPolygonalItem Class Reference
[canvas module]

The QCanvasPolygonalItem class provides a polygonal canvas item on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasItem.

Inherited by QCanvasRectangle, QCanvasPolygon, QCanvasLine and QCanvasEllipse.

List of all member functions.

Public Members

  • QCanvasPolygonalItem ( QCanvas * canvas )
  • virtual ~QCanvasPolygonalItem ()
  • virtual void setPen ( QPen p )
  • virtual void setBrush ( QBrush b )
  • QPen pen () const
  • QBrush brush () const
  • virtual QPointArray areaPoints () const = 0
  • virtual QPointArray areaPointsAdvanced () const
  • virtual QRect boundingRect () const
  • virtual int rtti () const

Protected Members

  • virtual void draw ( QPainter & p )
  • virtual void drawShape ( QPainter & p ) = 0
  • bool winding () const
  • void setWinding ( bool enable )

Detailed Description

The QCanvasPolygonalItem class provides a polygonal canvas item on a QCanvas.

The mostly rectangular classes, such as QCanvasSprite and QCanvasText, use the object's bounding rectangle for movement, repainting and collision calculations. For most other items, the bounding rectangle can be far too large -- a diagonal line being the worst case, and there are many other cases which are also bad. QCanvasPolygonalItem provides polygon-based bounding rectangle handling, etc., which is much faster for non-rectangular items.

Derived classes should try to define as small an area as possible to maximize efficiency, but the polygon must definitely be contained completely within the polygonal area. Calculating the exact requirements is usually difficult, but if you allow a small overestimate it can be easy and quick, while still getting almost all of QCanvasPolygonalItem's speed.

Note that all subclasses must call hide() in their destructor since hide() needs to be able to access areaPoints().

Normally, QCanvasPolygonalItem uses the odd-even algorithm for determining whether an object intersects this object. You can change this to the winding algorithm using setWinding().

The bounding rectangle is available using boundingRect(). The points bounding the polygonal item are retrieved with areaPoints(). Use areaPointsAdvanced() to retrieve the bounding points the polygonal item will have after QCanvasItem::advance(1) has been called.

By default, QCanvasPolygonalItem objects have a black pen and no brush (the default QPen and QBrush constructors). You can change this with setPen() and setBrush(), but note that some QCanvasPolygonalItem subclasses only use the brush, ignoring the pen setting.

The polygonal item can be drawn on a painter with draw(). Subclasses must reimplement drawShape() to draw themselves.

Like any other canvas item polygonal items can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasPolygonalItem::QCanvasPolygonalItem ( QCanvas * canvas )

Constructs a QCanvasPolygonalItem on the canvas canvas.

QCanvasPolygonalItem::~QCanvasPolygonalItem () [virtual]

Note that all subclasses must call hide() in their destructor since hide() needs to be able to access areaPoints().

QPointArray QCanvasPolygonalItem::areaPoints () const [pure virtual]

This function must be reimplemented by subclasses. It must return the points bounding (i.e. outside and not touching) the shape or drawing errors will occur.

Reimplemented in QCanvasPolygon.

QPointArray QCanvasPolygonalItem::areaPointsAdvanced () const [virtual]

Returns the points the polygonal item will have after QCanvasItem::advance(1) is called, i.e. what the points are when advanced by the current xVelocity() and yVelocity().

QRect QCanvasPolygonalItem::boundingRect () const [virtual]

Returns the bounding rectangle of the polygonal item, based on areaPoints().

Reimplemented from QCanvasItem.

QBrush QCanvasPolygonalItem::brush () const

Returns the QBrush used to fill the item, if filled.

See also setBrush().

void QCanvasPolygonalItem::draw ( QPainter & p ) [virtual protected]

Reimplemented from QCanvasItem, this draws the polygonal item by setting the pen and brush for the item on the painter p and calling drawShape().

Reimplemented from QCanvasItem.

void QCanvasPolygonalItem::drawShape ( QPainter & p ) [pure virtual protected]

Subclasses must reimplement this function to draw their shape. The pen and brush of p are already set to pen() and brush() prior to calling this function.

See also draw().

Reimplemented in QCanvasRectangle, QCanvasPolygon and QCanvasEllipse.

QPen QCanvasPolygonalItem::pen () const

Returns the QPen used to draw the outline of the item, if any.

See also setPen().

int QCanvasPolygonalItem::rtti () const [virtual]

Returns 2 (QCanvasItem::Rtti_PolygonalItem).

See also QCanvasItem::rtti().

Reimplemented from QCanvasItem.

Reimplemented in QCanvasRectangle, QCanvasPolygon, QCanvasLine and QCanvasEllipse.

void QCanvasPolygonalItem::setBrush ( QBrush b ) [virtual]

Sets the QBrush used when drawing the polygonal item to the brush b.

See also setPen(), brush() and drawShape().

Examples: canvas/canvas.cpp and chart/chartform_canvas.cpp.

void QCanvasPolygonalItem::setPen ( QPen p ) [virtual]

Sets the QPen used when drawing the item to the pen p. Note that many QCanvasPolygonalItems do not use the pen value.

See also setBrush(), pen() and drawShape().

Examples: canvas/canvas.cpp and chart/chartform_canvas.cpp.

void QCanvasPolygonalItem::setWinding ( bool enable ) [protected]

If enable is TRUE, the polygonal item will use the winding algorithm to determine the "inside" of the polygon; otherwise the odd-even algorithm will be used.

The default is to use the odd-even algorithm.

See also winding().

bool QCanvasPolygonalItem::winding () const [protected]

Returns TRUE if the polygonal item uses the winding algorithm to determine the "inside" of the polygon. Returns FALSE if it uses the odd-even algorithm.

The default is to use the odd-even algorithm.

See also setWinding().

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


QCanvasPolygonalItem Member List

Complete Member List for QCanvasPolygonalItem

This is the complete list of member functions for QCanvasPolygonalItem, including inherited members.

  • QCanvasPolygonalItem()
  • ~QCanvasPolygonalItem()
  • active()
  • advance()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • drawShape()
  • enabled()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setEnabled()
  • setPen()
  • setSelected()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • update()
  • visible()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasRectangle Class

QCanvasRectangle Class Reference
[canvas module]

The QCanvasRectangle class provides a rectangle on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasPolygonalItem.

List of all member functions.

Public Members

  • QCanvasRectangle ( QCanvas * canvas )
  • QCanvasRectangle ( const QRect & r, QCanvas * canvas )
  • QCanvasRectangle ( int x, int y, int width, int height, QCanvas * canvas )
  • ~QCanvasRectangle ()
  • int width () const
  • int height () const
  • void setSize ( int width, int height )
  • QSize size () const
  • QRect rect () const
  • virtual int rtti () const

Protected Members

  • virtual void drawShape ( QPainter & p )
  • virtual QPointArray chunks () const

Detailed Description

The QCanvasRectangle class provides a rectangle on a QCanvas.

This item paints a single rectangle which may have any pen() and brush(), but may not be tilted/rotated. For rotated rectangles, use QCanvasPolygon.

The rectangle's size and initial position can be set in the constructor. The size can be set or changed later using setSize(). Use height() and width() to retrieve the rectangle's dimensions.

The rectangle can be drawn on a painter with drawShape().

Like any other canvas item rectangles can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasRectangle::QCanvasRectangle ( QCanvas * canvas )

Constructs a rectangle at position (0,0) with both width and height set to 32 pixels on canvas.

QCanvasRectangle::QCanvasRectangle ( const QRect & r, QCanvas * canvas )

Constructs a rectangle positioned and sized by r on canvas.

QCanvasRectangle::QCanvasRectangle ( int x, int y, int width, int height, QCanvas * canvas )

Constructs a rectangle at position (x, y) and size width by height, on canvas.

QCanvasRectangle::~QCanvasRectangle ()

Destroys the rectangle.

QPointArray QCanvasRectangle::chunks () const [virtual protected]

Simply calls QCanvasItem::chunks().

void QCanvasRectangle::drawShape ( QPainter & p ) [virtual protected]

Draws the rectangle on painter p.

Example: canvas/canvas.cpp.

Reimplemented from QCanvasPolygonalItem.

int QCanvasRectangle::height () const

Returns the height of the rectangle.

QRect QCanvasRectangle::rect () const

Returns the integer-converted x(), y() position and size() of the rectangle as a QRect.

int QCanvasRectangle::rtti () const [virtual]

Returns 5 (QCanvasItem::Rtti_Rectangle).

See also QCanvasItem::rtti().

Reimplemented from QCanvasPolygonalItem.

void QCanvasRectangle::setSize ( int width, int height )

Sets the width and height of the rectangle.

QSize QCanvasRectangle::size () const

Returns the width() and height() of the rectangle.

See also rect() and setSize().

int QCanvasRectangle::width () const

Returns the width of the rectangle.

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


QCanvasRectangle Member List

Complete Member List for QCanvasRectangle

This is the complete list of member functions for QCanvasRectangle, including inherited members.

  • QCanvasRectangle()
  • ~QCanvasRectangle()
  • active()
  • advance()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • chunks()
  • collidesWith()
  • collisions()
  • draw()
  • drawShape()
  • enabled()
  • height()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • rect()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setEnabled()
  • setPen()
  • setSelected()
  • setSize()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • size()
  • update()
  • visible()
  • width()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasSpline Class

QCanvasSpline Class Reference
[canvas module]

The QCanvasSpline class provides multi-bezier splines on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasPolygon.

List of all member functions.

Public Members

  • QCanvasSpline ( QCanvas * canvas )
  • ~QCanvasSpline ()
  • void setControlPoints ( QPointArray ctrl, bool close = TRUE )
  • QPointArray controlPoints () const
  • bool closed () const
  • virtual int rtti () const

Detailed Description

The QCanvasSpline class provides multi-bezier splines on a QCanvas.

A QCanvasSpline is a sequence of 4-point bezier curves joined together to make a curved shape.

You set the control points of the spline with setControlPoints().

If the bezier is closed(), then the first control point will be re-used as the last control point. Therefore, a closed bezier must have a multiple of 3 control points and an open bezier must have one extra point.

The beziers are not necessarily joined "smoothly". To ensure this, set control points appropriately (general reference texts about beziers will explain this in detail).

Like any other canvas item splines can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasSpline::QCanvasSpline ( QCanvas * canvas )

Create a spline with no control points on the canvas canvas.

See also setControlPoints().

QCanvasSpline::~QCanvasSpline ()

Destroy the spline.

bool QCanvasSpline::closed () const

Returns TRUE if the control points are a closed set; otherwise returns FALSE.

QPointArray QCanvasSpline::controlPoints () const

Returns the current set of control points.

See also setControlPoints() and closed().

int QCanvasSpline::rtti () const [virtual]

Returns 8 (QCanvasItem::Rtti_Spline).

See also QCanvasItem::rtti().

Reimplemented from QCanvasPolygon.

void QCanvasSpline::setControlPoints ( QPointArray ctrl, bool close = TRUE )

Set the spline control points to ctrl.

If close is TRUE, then the first point in ctrl will be re-used as the last point, and the number of control points must be a multiple of 3. If close is FALSE, one additional control point is required, and the number of control points must be one of (4, 7, 11, ...).

If the number of control points doesn't meet the above conditions, the number of points will be truncated to the largest number of points that do meet the requirement.

Example: canvas/canvas.cpp.

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


QCanvasSpline Member List

Complete Member List for QCanvasSpline

This is the complete list of member functions for QCanvasSpline, including inherited members.

  • QCanvasSpline()
  • ~QCanvasSpline()
  • active()
  • advance()
  • animated()
  • areaPoints()
  • areaPointsAdvanced()
  • boundingRect()
  • boundingRectAdvanced()
  • brush()
  • canvas()
  • closed()
  • collidesWith()
  • collisions()
  • controlPoints()
  • draw()
  • drawShape()
  • enabled()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • pen()
  • points()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setBrush()
  • setCanvas()
  • setControlPoints()
  • setEnabled()
  • setPen()
  • setPoints()
  • setSelected()
  • setVelocity()
  • setVisible()
  • setWinding()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • update()
  • visible()
  • winding()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasSprite Class

QCanvasSprite Class Reference
[canvas module]

The QCanvasSprite class provides an animated canvas item on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasItem.

List of all member functions.

Public Members

  • QCanvasSprite ( QCanvasPixmapArray * a, QCanvas * canvas )
  • void setSequence ( QCanvasPixmapArray * a )
  • virtual ~QCanvasSprite ()
  • virtual void move ( double nx, double ny, int nf )
  • void setFrame ( int f )
  • enum FrameAnimationType { Cycle, Oscillate }
  • virtual void setFrameAnimation ( FrameAnimationType type = Cycle, int step = 1, int state = 0 )
  • int frame () const
  • int frameCount () const
  • virtual int rtti () const
  • virtual QRect boundingRect () const
  • int width () const
  • int height () const
  • int leftEdge () const
  • int topEdge () const
  • int rightEdge () const
  • int bottomEdge () const
  • int leftEdge ( int nx ) const
  • int topEdge ( int ny ) const
  • int rightEdge ( int nx ) const
  • int bottomEdge ( int ny ) const
  • QCanvasPixmap * image () const
  • virtual QCanvasPixmap * imageAdvanced () const
  • QCanvasPixmap * image ( int f ) const
  • virtual void advance ( int phase )
  • virtual void draw ( QPainter & painter )

Detailed Description

The QCanvasSprite class provides an animated canvas item on a QCanvas.

A canvas sprite is an object which can contain any number of images (referred to as frames), only one of which is current, i.e. displayed, at any one time. The images can be passed in the constructor or set or changed later with setSequence(). If you subclass QCanvasSprite you can change the frame that is displayed periodically, e.g. whenever QCanvasItem::advance(1) is called to create the effect of animation.

The current frame can be set with setFrame() or with move(). The number of frames available is given by frameCount(). The bounding rectangle of the current frame is returned by boundingRect().

The current frame's image can be retrieved with image(); use imageAdvanced() to retrieve the image for the frame that will be shown after advance(1) is called. Use the image() overload passing it an integer index to retrieve a particular image from the list of frames.

Use width() and height() to retrieve the dimensions of the current frame.

Use leftEdge() and rightEdge() to retrieve the current frame's left-hand and right-hand x-coordinates respectively. Use bottomEdge() and topEdge() to retrieve the current frame's bottom and top y-coordinates respectively. These functions have an overload which will accept an integer frame number to retrieve the coordinates of a particular frame.

QCanvasSprite draws very quickly, at the expense of memory.

The current frame's image can be drawn on a painter with draw().

Like any other canvas item, canvas sprites can be moved with move() which sets the x and y coordinates and the frame number, as well as with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Type Documentation

QCanvasSprite::FrameAnimationType

This enum is used to identify the different types of frame animation of QCanvasSprite.

  • QCanvasSprite::Cycle - at each advance the frame number will be incremented by 1 (modulo the frame count).
  • QCanvasSprite::Oscillate - at each advance the frame number will be incremented by 1 up to the frame count then decremented to by 1 to 0, repeating this sequence forever.

Member Function Documentation

QCanvasSprite::QCanvasSprite ( QCanvasPixmapArray * a, QCanvas * canvas )

Constructs a QCanvasSprite which uses images from the QCanvasPixmapArray a.

The sprite in initially positioned at (0,0) on canvas, using frame 0.

QCanvasSprite::~QCanvasSprite () [virtual]

Destroys the sprite and removes it from the canvas. Does not delete the images.

void QCanvasSprite::advance ( int phase ) [virtual]

Extends the default QCanvasItem implementation to provide the functionality of setFrameAnimation().

The phase is 0 or 1: see QCanvas::animate() for details.

See also QCanvasItem::advance() and setVelocity().

Example: canvas/canvas.cpp.

Reimplemented from QCanvasItem.

int QCanvasSprite::bottomEdge () const

Returns the y-coordinate of the current bottom edge of the sprite. (This may change as the sprite animates since different frames may have different bottom edges.)

See also leftEdge(), rightEdge() and topEdge().

int QCanvasSprite::bottomEdge ( int ny ) const

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

Returns what the y-coordinate of the top edge of the sprite would be if the sprite (actually its hotspot) were moved to y-position ny.

See also leftEdge(), rightEdge() and topEdge().

QRect QCanvasSprite::boundingRect () const [virtual]

Returns the bounding rectangle for the image in sprite's current frame. This assumes that the images are tightly cropped (i.e. do not have transparent pixels all along a side).

Reimplemented from QCanvasItem.

void QCanvasSprite::draw ( QPainter & painter ) [virtual]

Draws the current frame's image at the sprite's current position on painter painter.

Reimplemented from QCanvasItem.

int QCanvasSprite::frame () const

Returns the index of the current animation frame in the QCanvasSprite's QCanvasPixmapArray.

See also setFrame() and move().

int QCanvasSprite::frameCount () const

Returns the number of frames in the QCanvasSprite's QCanvasPixmapArray.

int QCanvasSprite::height () const

The height of the sprite for the current frame's image.

See also frame().

QCanvasPixmap * QCanvasSprite::image () const

Returns the current frame's image.

See also frame() and setFrame().

QCanvasPixmap * QCanvasSprite::image ( int f ) const

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

Returns the image for frame f. Does not do any bounds checking on f.

QCanvasPixmap * QCanvasSprite::imageAdvanced () const [virtual]

Returns the image the sprite will have after advance(1) is called. By default this is the same as image().

int QCanvasSprite::leftEdge () const

Returns the x-coordinate of the current left edge of the sprite. (This may change as the sprite animates since different frames may have different left edges.)

See also rightEdge(), bottomEdge() and topEdge().

int QCanvasSprite::leftEdge ( int nx ) const

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

Returns what the x-coordinate of the left edge of the sprite would be if the sprite (actually its hotspot) were moved to x-position nx.

See also rightEdge(), bottomEdge() and topEdge().

void QCanvasSprite::move ( double nx, double ny, int nf ) [virtual]

Set the position of the sprite to nx, ny and the current frame to nf. nf will be ignored if it is larger than frameCount() or smaller than 0.

int QCanvasSprite::rightEdge () const

Returns the x-coordinate of the current right edge of the sprite. (This may change as the sprite animates since different frames may have different right edges.)

See also leftEdge(), bottomEdge() and topEdge().

int QCanvasSprite::rightEdge ( int nx ) const

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

Returns what the x-coordinate of the right edge of the sprite would be if the sprite (actually its hotspot) were moved to x-position nx.

See also leftEdge(), bottomEdge() and topEdge().

int QCanvasSprite::rtti () const [virtual]

Returns 1 (QCanvasItem::Rtti_Sprite).

See also QCanvasItem::rtti().

Example: canvas/canvas.cpp.

Reimplemented from QCanvasItem.

void QCanvasSprite::setFrame ( int f )

Sets the animation frame used for displaying the sprite to f, an index into the QCanvasSprite's QCanvasPixmapArray. The call will be ignored if f is larger than frameCount() or smaller than 0.

See also frame() and move().

void QCanvasSprite::setFrameAnimation ( FrameAnimationType type = Cycle, int step = 1, int state = 0 ) [virtual]

Sets the animation characteristics for the sprite.

For type == Cycle, the frames will increase by step at each advance, modulo the frameCount().

For type == Oscillate, the frames will increase by step at each advance, up to the frameCount(), then decrease by step back to 0, etc.

The state parameter is for internal use.

void QCanvasSprite::setSequence ( QCanvasPixmapArray * a )

Set the array of images used for displaying the sprite to the QCanvasPixmapArray a.

If the current frame() is larger than the number of images in a, the current frame will be reset to 0.

int QCanvasSprite::topEdge () const

Returns the y-coordinate of the top edge of the sprite. (This may change as the sprite animates since different frames may have different top edges.)

See also leftEdge(), rightEdge() and bottomEdge().

int QCanvasSprite::topEdge ( int ny ) const

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

Returns what the y-coordinate of the top edge of the sprite would be if the sprite (actually its hotspot) were moved to y-position ny.

See also leftEdge(), rightEdge() and bottomEdge().

int QCanvasSprite::width () const

The width of the sprite for the current frame's image.

See also frame().

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


QCanvasSprite Member List

Complete Member List for QCanvasSprite

This is the complete list of member functions for QCanvasSprite, including inherited members.

  • QCanvasSprite()
  • ~QCanvasSprite()
  • active()
  • advance()
  • animated()
  • bottomEdge()
  • boundingRect()
  • boundingRectAdvanced()
  • canvas()
  • collidesWith()
  • collisions()
  • draw()
  • enabled()
  • frame()
  • frameCount()
  • height()
  • hide()
  • image()
  • imageAdvanced()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • leftEdge()
  • move()
  • moveBy()
  • rightEdge()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setCanvas()
  • setEnabled()
  • setFrame()
  • setFrameAnimation()
  • setSelected()
  • setSequence()
  • setVelocity()
  • setVisible()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • topEdge()
  • update()
  • visible()
  • width()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasText Class

QCanvasText Class Reference
[canvas module]

The QCanvasText class provides a text object on a QCanvas. More...

#include <qcanvas.h>

Inherits QCanvasItem.

List of all member functions.

Public Members

  • QCanvasText ( QCanvas * canvas )
  • QCanvasText ( const QString & t, QCanvas * canvas )
  • QCanvasText ( const QString & t, QFont f, QCanvas * canvas )
  • virtual ~QCanvasText ()
  • void setText ( const QString & t )
  • void setFont ( const QFont & f )
  • void setColor ( const QColor & c )
  • QString text () const
  • QFont font () const
  • QColor color () const
  • int textFlags () const
  • void setTextFlags ( int f )
  • virtual QRect boundingRect () const
  • virtual int rtti () const

Protected Members

  • virtual void draw ( QPainter & painter )

Detailed Description

The QCanvasText class provides a text object on a QCanvas.

A canvas text item has text with font, color and alignment attributes. The text and font can be set in the constructor or set or changed later with setText() and setFont(). The color is set with setColor() and the alignment with setTextFlags(). The text item's bounding rectangle is retrieved with boundingRect().

The text can be drawn on a painter with draw().

Like any other canvas item text items can be moved with QCanvasItem::move() and QCanvasItem::moveBy(), or by setting coordinates with QCanvasItem::setX(), QCanvasItem::setY() and QCanvasItem::setZ().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasText::QCanvasText ( QCanvas * canvas )

Constructs a QCanvasText with the text "<text>", on canvas.

QCanvasText::QCanvasText ( const QString & t, QCanvas * canvas )

Constructs a QCanvasText with the text t, on canvas canvas.

QCanvasText::QCanvasText ( const QString & t, QFont f, QCanvas * canvas )

Constructs a QCanvasText with the text t and font f, on the canvas canvas.

QCanvasText::~QCanvasText () [virtual]

Destroys the canvas text item.

QRect QCanvasText::boundingRect () const [virtual]

Returns the bounding rectangle of the text.

Reimplemented from QCanvasItem.

QColor QCanvasText::color () const

Returns the color of the text.

See also setColor().

void QCanvasText::draw ( QPainter & painter ) [virtual protected]

Draws the text using the painter painter.

Reimplemented from QCanvasItem.

QFont QCanvasText::font () const

Returns the font in which the text is drawn.

See also setFont().

int QCanvasText::rtti () const [virtual]

Returns 3 (QCanvasItem::Rtti_Text).

See also QCanvasItem::rtti().

Reimplemented from QCanvasItem.

void QCanvasText::setColor ( const QColor & c )

Sets the color of the text to the color c.

See also color() and setFont().

Example: chart/chartform_canvas.cpp.

void QCanvasText::setFont ( const QFont & f )

Sets the font in which the text is drawn to font f.

See also font().

void QCanvasText::setText ( const QString & t )

Sets the text item's text to t. The text may contain newlines.

See also text(), setFont(), setColor() and setTextFlags().

Example: canvas/canvas.cpp.

void QCanvasText::setTextFlags ( int f )

Sets the alignment flags to f. These are a bitwise OR of the flags available to QPainter::drawText() -- see Qt::AlignmentFlags.

See also setFont() and setColor().

QString QCanvasText::text () const

Returns the text item's text.

See also setText().

int QCanvasText::textFlags () const

Returns the currently set alignment flags.

See also setTextFlags() and Qt::AlignmentFlags.

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


QCanvasText Member List

Complete Member List for QCanvasText

This is the complete list of member functions for QCanvasText, including inherited members.

  • QCanvasText()
  • ~QCanvasText()
  • active()
  • advance()
  • animated()
  • boundingRect()
  • boundingRectAdvanced()
  • canvas()
  • collidesWith()
  • collisions()
  • color()
  • draw()
  • enabled()
  • font()
  • hide()
  • isActive()
  • isEnabled()
  • isSelected()
  • isVisible()
  • move()
  • moveBy()
  • rtti()
  • selected()
  • setActive()
  • setAnimated()
  • setCanvas()
  • setColor()
  • setEnabled()
  • setFont()
  • setSelected()
  • setText()
  • setTextFlags()
  • setVelocity()
  • setVisible()
  • setX()
  • setXVelocity()
  • setY()
  • setYVelocity()
  • setZ()
  • show()
  • text()
  • textFlags()
  • update()
  • visible()
  • x()
  • xVelocity()
  • y()
  • yVelocity()
  • z()


QCanvasView Class

QCanvasView Class Reference
[canvas module]

The QCanvasView class provides an on-screen view of a QCanvas. More...

#include <qcanvas.h>

Inherits QScrollView.

List of all member functions.

Public Members

  • QCanvasView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • QCanvasView ( QCanvas * canvas, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QCanvasView ()
  • QCanvas * canvas () const
  • void setCanvas ( QCanvas * canvas )
  • const QWMatrix & worldMatrix () const
  • const QWMatrix & inverseWorldMatrix () const
  • bool setWorldMatrix ( const QWMatrix & wm )

Protected Members

  • virtual void drawContents ( QPainter * p, int cx, int cy, int cw, int ch )

Detailed Description

The QCanvasView class provides an on-screen view of a QCanvas.

A QCanvasView is widget which provides a view of a QCanvas.

If you want users to be able to interact with a canvas view, subclass QCanvasView. You might then reimplement QScrollView::contentsMousePressEvent() for example:

    void MyCanvasView::contentsMousePressEvent( QMouseEvent* e )
    {
        QCanvasItemList l = canvas()->collisions(e->pos());
        for (QCanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) {
            if ( (*it)->rtti() == QCanvasRectangle::RTTI )
                qDebug("A QCanvasRectangle lies somewhere at this point");
        }
    }

Set the canvas that the view shows with setCanvas() and retrieve the canvas which the view is showing with canvas().

A transformation matrix can be used to transform the view of the canvas in various ways, for example, zooming in or out or rotating. For example:

    QWMatrix wm;
    wm.scale( 2, 2 );   // Zooms in by 2 times
    wm.rotate( 90 );    // Rotates 90 degrees counter clockwise
                        // around the origin.
    wm.translate( 0, -canvas->height() );
                        // moves the canvas down so what was visible
                        // before is still visible.
    myCanvasView->setWorldMatrix( wm );

Use setWorldMatrix() to set the canvas view's world matrix: you must ensure that the world matrix is invertible. The current world matrix is retrievable with worldMatrix(), and its inversion is retrievable with inverseWorldMatrix().

Example:

The following code finds the part of the canvas that is visible in this view, i.e. the bounding rectangle of the view in canvas coordinates.

    QRect rc = QRect( myCanvasView->contentsX(), myCanvasView->contentsY(),
                      myCanvasView->visibleWidth(), myCanvasView->visibleHeight() );
    QRect canvasRect = myCanvasView->inverseWorldMatrix().mapRect(rc);

See also QWMatrix, QPainter::setWorldMatrix(), Graphics Classes and Image Processing Classes.

Member Function Documentation

QCanvasView::QCanvasView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a QCanvasView with parent parent, and name name, using the widget flags f. The canvas view is not associated with a canvas, so you will need to call setCanvas() to display a canvas.

QCanvasView::QCanvasView ( QCanvas * canvas, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

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

Constructs a QCanvasView which views canvas canvas, with parent parent, and name name, using the widget flags f.

QCanvasView::~QCanvasView ()

Destroys the canvas view. The associated canvas is not deleted.

QCanvas * QCanvasView::canvas () const

Returns a pointer to the canvas which the QCanvasView is currently showing.

void QCanvasView::drawContents ( QPainter * p, int cx, int cy, int cw, int ch ) [virtual protected]

Repaints part of the QCanvas that the canvas view is showing starting at cx by cy, with a width of cw and a height of ch using the painter p.

Reimplemented from QScrollView.

const QWMatrix & QCanvasView::inverseWorldMatrix () const

Returns a reference to the inverse of the canvas view's current transformation matrix.

See also setWorldMatrix() and worldMatrix().

void QCanvasView::setCanvas ( QCanvas * canvas )

Sets the canvas that the QCanvasView is showing to the canvas canvas.

bool QCanvasView::setWorldMatrix ( const QWMatrix & wm )

Sets the transformation matrix of the QCanvasView to wm. The matrix must be invertible (i.e. if you create a world matrix that zooms out by 2 times, then the inverse of this matrix is one that will zoom in by 2 times).

When you use this, you should note that the performance of the QCanvasView will decrease considerably.

Returns FALSE if wm is not invertable; otherwise returns TRUE.

See also worldMatrix(), inverseWorldMatrix() and QWMatrix::isInvertible().

Example: canvas/canvas.cpp.

const QWMatrix & QCanvasView::worldMatrix () const

Returns a reference to the canvas view's current transformation matrix.

See also setWorldMatrix() and inverseWorldMatrix().

Example: canvas/canvas.cpp.

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


QCanvasView Member List

Complete Member List for QCanvasView

This is the complete list of member functions for QCanvasView, including inherited members.

  • QCanvasView()
  • ~QCanvasView()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • canvas()
  • caption()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • cornerWidget()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • inverseWorldMatrix()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • rightMargin()
  • scroll()
  • scrollBy()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCanvas()
  • setCaption()
  • setContentsPos()
  • setCornerWidget()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizePolicy()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • setWorldMatrix()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • worldMatrix()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QCDEStyle Class

QCDEStyle Class Reference

The QCDEStyle class provides a CDE look and feel. More...

#include <qcdestyle.h>

Inherits QMotifStyle.

List of all member functions.

Public Members

  • QCDEStyle ( bool useHighlightCols = FALSE )
  • virtual ~QCDEStyle ()

Detailed Description

The QCDEStyle class provides a CDE look and feel.

This style provides a slightly improved Motif look similar to some versions of the Common Desktop Environment (CDE). The main differences are thinner frames and more modern radio buttons and check boxes. Together with a dark background and a bright text/foreground color, the style looks quite attractive (at least for Motif fans).

Note that the functions provided by QCDEStyle are reimplementations of QStyle functions; see QStyle for their documentation.

See also Widget Appearance and Style.

Member Function Documentation

QCDEStyle::QCDEStyle ( bool useHighlightCols = FALSE )

Constructs a QCDEStyle.

If useHighlightCols is FALSE (the default), then the style will polish the application's color palette to emulate the Motif way of highlighting, which is a simple inversion between the base and the text color.

QCDEStyle::~QCDEStyle () [virtual]

Destroys the style.

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


qcdestyle.h Include File

qcdestyle.h

This is the verbatim text of the qcdestyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qcdestyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the CDE-like style class
**
** Created : 990513
**
** Copyright (C) 1999 by Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCDESTYLE_H
#define QCDESTYLE_H

#ifndef QT_H
#include "qmotifstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE_CDE

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_CDE
#else
#define Q_EXPORT_STYLE_CDE Q_EXPORT
#endif

class Q_EXPORT_STYLE_CDE QCDEStyle : public QMotifStyle
{
    Q_OBJECT
public:

    QCDEStyle( bool useHighlightCols = FALSE );
    virtual ~QCDEStyle();

    int pixelMetric( PixelMetric metric, const QWidget *widget = 0 ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

};

#endif // QT_NO_STYLE_CDE

#endif // QCDESTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCDEStyle Member List

Complete Member List for QCDEStyle

This is the complete list of member functions for QCDEStyle, including inherited members.

  • QCDEStyle()
  • ~QCDEStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • setUseHighlightColors()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • useHighlightColors()
  • visualRect()


QChar Class

QChar Class Reference

The QChar class provides a lightweight Unicode character. More...

#include <qstring.h>

List of all member functions.

Public Members

  • QChar ()
  • QChar ( char c )
  • QChar ( uchar c )
  • QChar ( uchar c, uchar r )
  • QChar ( const QChar & c )
  • QChar ( ushort rc )
  • QChar ( short rc )
  • QChar ( uint rc )
  • QChar ( int rc )
  • enum Category { NoCategory, Mark_NonSpacing, Mark_SpacingCombining, Mark_Enclosing, Number_DecimalDigit, Number_Letter, Number_Other, Separator_Space, Separator_Line, Separator_Paragraph, Other_Control, Other_Format, Other_Surrogate, Other_PrivateUse, Other_NotAssigned, Letter_Uppercase, Letter_Lowercase, Letter_Titlecase, Letter_Modifier, Letter_Other, Punctuation_Connector, Punctuation_Dash, Punctuation_Dask = Punctuation_Dash, Punctuation_Open, Punctuation_Close, Punctuation_InitialQuote, Punctuation_FinalQuote, Punctuation_Other, Symbol_Math, Symbol_Currency, Symbol_Modifier, Symbol_Other }
  • enum Direction { DirL, DirR, DirEN, DirES, DirET, DirAN, DirCS, DirB, DirS, DirWS, DirON, DirLRE, DirLRO, DirAL, DirRLE, DirRLO, DirPDF, DirNSM, DirBN }
  • enum Decomposition { Single, Canonical, Font, NoBreak, Initial, Medial, Final, Isolated, Circle, Super, Sub, Vertical, Wide, Narrow, Small, Square, Compat, Fraction }
  • enum Joining { OtherJoining, Dual, Right, Center }
  • enum CombiningClass { Combining_BelowLeftAttached = 200, Combining_BelowAttached = 202, Combining_BelowRightAttached = 204, Combining_LeftAttached = 208, Combining_RightAttached = 210, Combining_AboveLeftAttached = 212, Combining_AboveAttached = 214, Combining_AboveRightAttached = 216, Combining_BelowLeft = 218, Combining_Below = 220, Combining_BelowRight = 222, Combining_Left = 224, Combining_Right = 226, Combining_AboveLeft = 228, Combining_Above = 230, Combining_AboveRight = 232, Combining_DoubleBelow = 233, Combining_DoubleAbove = 234, Combining_IotaSubscript = 240 }
  • int digitValue () const
  • QChar lower () const
  • QChar upper () const
  • Category category () const
  • Direction direction () const
  • Joining joining () const
  • bool mirrored () const
  • QChar mirroredChar () const
  • const QString & decomposition () const
  • Decomposition decompositionTag () const
  • unsigned char combiningClass () const
  • char latin1 () const
  • ushort unicode () const
  • ushort & unicode ()
  • operator char () const
  • bool isNull () const
  • bool isPrint () const
  • bool isPunct () const
  • bool isSpace () const
  • bool isMark () const
  • bool isLetter () const
  • bool isNumber () const
  • bool isLetterOrNumber () const
  • bool isDigit () const
  • bool isSymbol () const
  • uchar cell () const
  • uchar row () const

Static Public Members

  • bool networkOrdered ()

Related Functions

  • bool operator== ( QChar c1, QChar c2 )
  • bool operator== ( char ch, QChar c )
  • bool operator== ( QChar c, char ch )
  • int operator!= ( QChar c1, QChar c2 )
  • int operator!= ( char ch, QChar c )
  • int operator!= ( QChar c, char ch )
  • int operator<= ( QChar c1, QChar c2 )
  • int operator<= ( QChar c, char ch )
  • int operator<= ( char ch, QChar c )
  • int operator>= ( QChar c1, QChar c2 )
  • int operator>= ( QChar c, char ch )
  • int operator>= ( char ch, QChar c )
  • int operator< ( QChar c1, QChar c2 )
  • int operator< ( QChar c, char ch )
  • int operator< ( char ch, QChar c )
  • int operator> ( QChar c1, QChar c2 )
  • int operator> ( QChar c, char ch )
  • int operator> ( char ch, QChar c )

Detailed Description

The QChar class provides a lightweight Unicode character.

Unicode characters are (so far) 16-bit entities without any markup or structure. This class represents such an entity. It is lightweight, so it can be used everywhere. Most compilers treat it like a "short int." (In a few years it may be necessary to make QChar 32-bit when more than 65536 Unicode code points have been defined and come into use.)

QChar provides a full complement of testing/classification functions, converting to and from other formats, converting from composed to decomposed Unicode, and trying to compare and case-convert if you ask it to.

The classification functions include functions like those in ctype.h, but operating on the full range of Unicode characters. They all return TRUE if the character is a certain type of character; otherwise they return FALSE. These classification functions are isNull() (returns TRUE if the character is U+0000), isPrint() (TRUE if the character is any sort of printable character, including whitespace), isPunct() (any sort of punctation), isMark() (Unicode Mark), isLetter (a letter), isNumber() (any sort of numeric character), isLetterOrNumber(), and isDigit() (decimal digits). All of these are wrappers around category() which return the Unicode-defined category of each character.

QChar further provides direction(), which indicates the "natural" writing direction of this character. The joining() function indicates how the character joins with its neighbors (needed mostly for Arabic) and finally mirrored(), which indicates whether the character needs to be mirrored when it is printed in its "unnatural" writing direction.

Composed Unicode characters (like å) can be converted to decomposed Unicode ("a" followed by "ring above") by using decomposition().

In Unicode, comparison is not necessarily possible and case conversion is very difficult at best. Unicode, covering the "entire" world, also includes most of the world's case and sorting problems. Qt tries, but not very hard: operator== and friends will do comparison based purely on the numeric Unicode value (code point) of the characters, and upper() and lower() will do case changes when the character has a well-defined upper/lower-case equivalent. There is no provision for locale-dependent case folding rules or comparison; these functions are meant to be fast so they can be used unambiguously in data structures. (See QString::localeAwareCompare() though.)

The conversion functions include unicode() (to a scalar), latin1() (to scalar, but converts all non-Latin1 characters to 0), row() (gives the Unicode row), cell() (gives the Unicode cell), digitValue() (gives the integer value of any of the numerous digit characters), and a host of constructors.

More information can be found in the document About Unicode.

See also QString, QCharRef and Text Related Classes.

Member Type Documentation

QChar::Category

This enum maps the Unicode character categories. The following characters are normative in Unicode:

  • QChar::Mark_NonSpacing - Unicode class name Mn
  • QChar::Mark_SpacingCombining - Unicode class name Mc
  • QChar::Mark_Enclosing - Unicode class name Me
  • QChar::Number_DecimalDigit - Unicode class name Nd
  • QChar::Number_Letter - Unicode class name Nl
  • QChar::Number_Other - Unicode class name No
  • QChar::Separator_Space - Unicode class name Zs
  • QChar::Separator_Line - Unicode class name Zl
  • QChar::Separator_Paragraph - Unicode class name Zp
  • QChar::Other_Control - Unicode class name Cc
  • QChar::Other_Format - Unicode class name Cf
  • QChar::Other_Surrogate - Unicode class name Cs
  • QChar::Other_PrivateUse - Unicode class name Co
  • QChar::Other_NotAssigned - Unicode class name Cn

The following categories are informative in Unicode:

  • QChar::Letter_Uppercase - Unicode class name Lu
  • QChar::Letter_Lowercase - Unicode class name Ll
  • QChar::Letter_Titlecase - Unicode class name Lt
  • QChar::Letter_Modifier - Unicode class name Lm
  • QChar::Letter_Other - Unicode class name Lo
  • QChar::Punctuation_Connector - Unicode class name Pc
  • QChar::Punctuation_Dash - Unicode class name Pd
  • QChar::Punctuation_Open - Unicode class name Ps
  • QChar::Punctuation_Close - Unicode class name Pe
  • QChar::Punctuation_InitialQuote - Unicode class name Pi
  • QChar::Punctuation_FinalQuote - Unicode class name Pf
  • QChar::Punctuation_Other - Unicode class name Po
  • QChar::Symbol_Math - Unicode class name Sm
  • QChar::Symbol_Currency - Unicode class name Sc
  • QChar::Symbol_Modifier - Unicode class name Sk
  • QChar::Symbol_Other - Unicode class name So

There are two categories that are specific to Qt:

  • QChar::NoCategory - used when Qt is dazed and confused and cannot make sense of anything.
  • QChar::Punctuation_Dask - old typo alias for Punctuation_Dash

QChar::CombiningClass

This enum defines names for some of the combining classes defined in the Unicode standard. See the Unicode Standard for a more detailed description.

QChar::Decomposition

This enum type defines the Unicode decomposition attributes. See the Unicode Standard for a description of the values.

QChar::Direction

This enum type defines the Unicode direction attributes. See the Unicode Standard for a description of the values.

In order to conform to C/C++ naming conventions "Dir" is prepended to the codes used in the Unicode Standard.

QChar::Joining

This enum type defines the Unicode decomposition attributes. See the Unicode Standard for a description of the values.

Member Function Documentation

QChar::QChar ()

Constructs a null QChar (one that isNull()).

QChar::QChar ( char c )

Constructs a QChar corresponding to ASCII/Latin1 character c.

QChar::QChar ( uchar c )

Constructs a QChar corresponding to ASCII/Latin1 character c.

QChar::QChar ( uchar c, uchar r )

Constructs a QChar for Unicode cell c in row r.

QChar::QChar ( const QChar & c )

Constructs a copy of c. This is a deep copy, if such a lightweight object can be said to have deep copies.

QChar::QChar ( ushort rc )

Constructs a QChar for the character with Unicode code point rc.

QChar::QChar ( short rc )

Constructs a QChar for the character with Unicode code point rc.

QChar::QChar ( uint rc )

Constructs a QChar for the character with Unicode code point rc.

QChar::QChar ( int rc )

Constructs a QChar for the character with Unicode code point rc.

Category QChar::category () const

Returns the character category.

See also Category.

uchar QChar::cell () const

Returns the cell (least significant byte) of the Unicode character.

unsigned char QChar::combiningClass () const

Returns the combining class for the character as defined in the Unicode standard. This is mainly useful as a positioning hint for marks attached to a base character.

The Qt text rendering engine uses this information to correctly position non spacing marks around a base character.

const QString & QChar::decomposition () const

Decomposes a character into its parts. Returns QString::null if no decomposition exists.

Decomposition QChar::decompositionTag () const

Returns the tag defining the composition of the character. Returns QChar::Single if no decomposition exists.

int QChar::digitValue () const

Returns the numeric value of the digit, or -1 if the character is not a digit.

Direction QChar::direction () const

Returns the character's direction.

See also Direction.

bool QChar::isDigit () const

Returns whether the character is a decimal digit (Number_DecimalDigit).

bool QChar::isLetter () const

Returns whether the character is a letter (Letter_* categories).

bool QChar::isLetterOrNumber () const

Returns whether the character is a letter or number (Letter_* or Number_* categories).

bool QChar::isMark () const

Returns whether the character is a mark (Mark_* categories).

bool QChar::isNull () const

Returns TRUE if the character is the Unicode character 0x0000, i.e., ASCII NUL.

bool QChar::isNumber () const

Returns whether the character is a number (of any sort - Number_* categories).

See also isDigit().

bool QChar::isPrint () const

Returns whether the character is a printable character. This is any character not of category Cc or Cn. Note that this gives no indication of whether the character is available in a particular font.

bool QChar::isPunct () const

Returns whether the character is a punctuation mark (Punctuation_* categories).

bool QChar::isSpace () const

Returns whether the character is a separator character (Separator_* categories).

bool QChar::isSymbol () const

Returns whether the character is a symbol (Symbol_* categories)

Joining QChar::joining () const

This function is not supported (it may change to use Unicode character classes).

Returns information about the joining properties of the character (needed for Arabic).

char QChar::latin1 () const

Returns a latin-1 copy of this character, if this character is in the latin-1 character set. If not, this function returns 0.

QChar QChar::lower () const

Returns the lowercase equivalent if the character is uppercase, otherwise returns the character itself.

bool QChar::mirrored () const

Returns whether the character is a mirrored character (one that should be reversed if the text direction is reversed).

QChar QChar::mirroredChar () const

Returns the mirrored char if this character is a mirrored char, otherwise returns the char itself.

bool QChar::networkOrdered () [static]

Returns TRUE if this character is in network byte order (MSB first); otherwise returns FALSE. This is platform dependent.

QChar::operator char () const

Returns the Latin1 character equivalent to the QChar, or 0. This is mainly useful for non-internationalized software.

See also unicode().

uchar QChar::row () const

Returns the row (most significant byte) of the Unicode character.

ushort QChar::unicode () const

Returns the numeric Unicode value equal to the QChar. Normally, you should use QChar objects as they are equivalent, but for some low-level tasks (e.g. indexing into an array of Unicode information), this function is useful.

ushort & QChar::unicode ()

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

Returns a reference to the numeric Unicode value equal to the QChar.

QChar QChar::upper () const

Returns the uppercase equivalent if the character is lowercase, otherwise returns the character itself.

Related Functions

int operator!= ( QChar c1, QChar c2 )

Returns TRUE if c1 and c2 are not the same Unicode character.

int operator!= ( char ch, QChar c )

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

Returns TRUE if c is not the ASCII/Latin1 character ch.

int operator!= ( QChar c, char ch )

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

Returns TRUE if c is not the ASCII/Latin1 character ch.

int operator< ( QChar c1, QChar c2 )

Returns TRUE if the numeric Unicode value of c1 is less than that of c2.

int operator< ( QChar c, char ch )

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

Returns TRUE if the numeric Unicode value of c is less than that of the ASCII/Latin1 character ch.

int operator< ( char ch, QChar c )

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

Returns TRUE if the numeric Unicode value of the ASCII/Latin1 character ch is less than that of c.

int operator<= ( QChar c1, QChar c2 )

Returns TRUE if the numeric Unicode value of c1 is less than that of c2, or they are the same Unicode character.

int operator<= ( QChar c, char ch )

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

Returns TRUE if the numeric Unicode value of c is less than or equal to that of the ASCII/Latin1 character ch.

int operator<= ( char ch, QChar c )

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

Returns TRUE if the numeric Unicode value of the ASCII/Latin1 character ch is less than or equal to that of c.

bool operator== ( QChar c1, QChar c2 )

Returns TRUE if c1 and c2 are the same Unicode character.

bool operator== ( char ch, QChar c )

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

Returns TRUE if c is the ASCII/Latin1 character ch.

bool operator== ( QChar c, char ch )

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

Returns TRUE if c is the ASCII/Latin1 character ch.

int operator> ( QChar c1, QChar c2 )

Returns TRUE if the numeric Unicode value of c1 is greater than that of c2.

int operator> ( QChar c, char ch )

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

Returns TRUE if the numeric Unicode value of c is greater than that of the ASCII/Latin1 character ch.

int operator> ( char ch, QChar c )

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

Returns TRUE if the numeric Unicode value of the ASCII/Latin1 character ch is greater than that of c.

int operator>= ( QChar c1, QChar c2 )

Returns TRUE if the numeric Unicode value of c1 is greater than that of c2, or they are the same Unicode character.

int operator>= ( QChar c, char ch )

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

Returns TRUE if the numeric Unicode value of c is greater than or equal to that of the ASCII/Latin1 character ch.

int operator>= ( char ch, QChar c )

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

Returns TRUE if the numeric Unicode value of the ASCII/Latin1 character ch is greater than or equal to that of c.

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


QChar Member List

Complete Member List for QChar

This is the complete list of member functions for QChar, including inherited members.

  • QChar()
  • category()
  • cell()
  • combiningClass()
  • decomposition()
  • decompositionTag()
  • digitValue()
  • direction()
  • isDigit()
  • isLetter()
  • isLetterOrNumber()
  • isMark()
  • isNull()
  • isNumber()
  • isPrint()
  • isPunct()
  • isSpace()
  • isSymbol()
  • joining()
  • latin1()
  • lower()
  • mirrored()
  • mirroredChar()
  • networkOrdered()
  • operator char()
  • row()
  • unicode()
  • upper()


QCharRef Class

QCharRef Class Reference

The QCharRef class is a helper class for QString. More...

#include <qstring.h>

List of all member functions.

Detailed Description

The QCharRef class is a helper class for QString.

When you get an object of type QCharRef, you can assign to it, which will operate on the character in the string from which you got the reference. That is its whole purpose in life. The QCharRef becomes invalid once modifications are made to the string: if you want to keep the character, copy it into a QChar.

Most of the QChar member functions also exist in QCharRef. However, they are not explicitly documented here.

See also QString::operator[](), QString::at(), QChar and Text Related Classes.

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


QCharRef Member List

Complete Member List for QCharRef

This is the complete list of member functions for QCharRef, including inherited members.


QCheckBox类

QCheckBox类参考

QCheckBox窗口部件提供一个带文本标签的复选框。 详情请见……

#include <qcheckbox.h>

继承了QButton。

所有成员函数的列表。

公有成员

  • QCheckBox ( QWidget * parent, const char * name = 0 )
  • QCheckBox ( const QString & text, QWidget * parent, const char * name = 0 )
  • bool isChecked () const
  • void setNoChange ()
  • void setTristate ( bool y = TRUE )
  • bool isTristate () const

公有槽

  • void setChecked ( bool check )

重要的继承成员

  • QString text () const
  • virtual void setText ( const QString & )
  • const QPixmap * pixmap () const
  • virtual void setPixmap ( const QPixmap & )
  • QKeySequence accel () const
  • virtual void setAccel ( const QKeySequence & )
  • bool isToggleButton () const
  • virtual void setDown ( bool )
  • bool isDown () const
  • bool isOn () const
  • ToggleState state () const
  • bool autoRepeat () const
  • virtual void setAutoRepeat ( bool )
  • bool isExclusiveToggle () const
  • QButtonGroup * group () const
  • void toggle ()
  • void pressed ()
  • void released ()
  • void clicked ()
  • void toggled ( bool on )
  • void stateChanged ( int state )

属性

  • bool autoMask - 复选框是否被自动遮蔽 （只读）
  • bool checked - 复选框是否被选中
  • bool tristate - 复选框是否是三态复选框

详细描述

QCheckBox窗口部件提供一个带文本标签的复选框。

QCheckBox和QRadioButton都是选项按钮。这是因为它们都可以在开（选中）或者关（未选中）之间切换。它们的区别是对用户选择的限制。单选框定义了“多选一”的选择，而复选框提供的是“多选多”的选择。

尽管在技术上可以通过复选框来实现单选框的行为，反之亦然，但我们还是强烈建议使用众所周知的约定。

QButtonGroup可以用来在视觉上把许多复选框组织在一起。

只要复选框被选中或者清除，它都会发射一个信号toggled()。如果你想在复选框改变状态的时候触发一个行为，请连接这个信号。你可以使用isChecked()来查询复选框是否被选中。

除了常用的被选中和未选中两个状态，QCheckBox还可以任选地提供第三种状态来表明“没有改变”。当你需要给用户一个选中或者未选中复选框的选择时，这是很有用的。如果你需要第三种状态，通过setTristate()来使它生效并且使用state()来查询当前的切换状态。当三态复选框改变状态时，它发射stateChanged()信号。

和QPushButton一样，复选框可以显示文本或者像素映射。文本可以通过构造函数或者setText()来设置，像素映射可以通过setPixmap()来设置。

也可以参考QButton、QRadioButton、福勒：复选框和基本窗口部件。

成员函数文档

QCheckBox::QCheckBox ( QWidget * parent, const char * name = 0 )

构造一个没有文本的复选框。

parent和name参数被发送到QWidget的构造函数。

QCheckBox::QCheckBox ( const QString & text, QWidget * parent, const char * name = 0 )

构造一个文本为text的复选框。

parent和name参数被发送到QWidget的构造函数。

QKeySequence QButton::accel () const

返回这个按钮的相关快捷键。详细情况请参考“accel”属性。

bool QButton::autoRepeat () const

如果autoRepeat生效，返回真，否则返回假。详细情况请参考“autoRepeat”属性。

void QButton::clicked () [信号]

当按钮被激活时（比如，当鼠标光标在按钮中，按钮首先被按下并且然后被释放），或者当快捷键被按下时，或者animateClick()被调用时，这个信号被发送。如果你调用setDown()，这个信号不被发送。

如果你想把几个按钮连接到同一个槽中，QButtonGroup::clicked()信号可以做这样的工作。

也可以参考pressed()、released()、toggled()、autoRepeat和down。

实例：fonts/simple-qfont-demo/viewer.cpp、listbox/listbox.cpp、network/clientserver/client/client.cpp、network/ftpclient/ftpmainwindow.cpp、richtext/richtext.cpp、t2/main.cpp和t4/main.cpp。

QButtonGroup * QButton::group () const

返回这个按钮所属的按钮组的指针。

如果这个按钮不是任何一个QButtonGroup的成员，这个函数返回0。

也可以参考QButtonGroup。

bool QCheckBox::isChecked () const

如果复选框被选中，返回真，否则返回假。详细情况请参考“checked”属性。

bool QButton::isDown () const

如果按钮被按下，返回真，否则返回假。详细情况请参考“down”属性。

bool QButton::isExclusiveToggle () const

如果按钮是排它的，返回真，否则返回假。详细情况请参考“exclusiveToggle”属性。

bool QButton::isOn () const

如果按钮被切换，返回真，否则返回假。详细情况请参考“on”属性。

bool QButton::isToggleButton () const

如果按钮是一个切换按钮，返回真，否则返回假。详细情况请参考“toggleButton”属性。

bool QCheckBox::isTristate () const

如果复选框是三态复选框，返回真，否则返回假。详细情况请参考“tristate”属性。

const QPixmap * QButton::pixmap () const

返回按钮中所显示的像素映射。详细情况请参考“pixmap”属性。

void QButton::pressed () [信号]

当按钮被按下的时候，这个信号被发送。

也可以参考released()和clicked()。

实例：network/httpd/httpd.cpp和popup/popup.cpp。

void QButton::released () [信号]

当按钮被释放的时候，这个信号被发送。

也可以参考pressed()、clicked()和toggled()。

void QButton::setAccel ( const QKeySequence & ) [虚]

设置按钮的相关快捷键。详细情况请参考“accel”属性。

void QButton::setAutoRepeat ( bool ) [虚]

设置autoRepeat是否生效。详细情况请参考“autoRepeat”属性。

void QCheckBox::setChecked ( bool check ) [槽]

设置复选框是否被选中为check。详细情况请参考“checked”属性。

void QButton::setDown ( bool ) [虚]

设置按钮是否被按下。详细情况请参考“down”属性。

void QCheckBox::setNoChange ()

设置复选框为“没有变化”状态。

也可以参考tristate。

void QButton::setPixmap ( const QPixmap & ) [虚]

设置按钮上显示的像素映射。详细情况请参考“pixmap”属性。

void QButton::setText ( const QString & ) [虚]

设置按钮上显示的文本。详细情况请参考“text”属性。

void QCheckBox::setTristate ( bool y = TRUE )

设置复选框是否为三态复选框为y。详细情况请参考“tristate”属性。

ToggleState QButton::state () const

如果按钮是被切换的，返回真，否则返回假。详细情况请参考“toggleState”属性。

void QButton::stateChanged ( int state ) [信号]

只要切换按钮改变状态，这个信号就被发送。如果按钮是开的，state为2，如果是“未改变”状态，为1，或者如果按钮是关的，为0。

这也许是一个用户行为的结果，toggle()槽激活，或者因为setState()或setOn()被调用。

也可以参考clicked()。

QString QButton::text () const

返回按钮上所显示的文本。详细情况请参考“text”属性。

void QButton::toggle () [槽]

切换一个切换按钮的状态。

也可以参考on、setOn()、toggled()和toggleButton。

void QButton::toggled ( bool on ) [信号]

只要切换按钮改变状态，这个信号就被发送。如果按钮是开的，on为真，或者如果按钮是关的，on为假。

这也许是一个用户行为的结果，toggle()槽被激活，或者因为setOn()被调用。

也可以参考clicked()。

实例：listbox/listbox.cpp。

属性文档

QKeySequence accel

这个属性保存的是按钮相关的快捷键。

如果没有快捷键被设置，这个属性为0。如果你设置这个属性为0，那么任何当前的快捷键都被删除。

使用setAccel()来设置这个属性值并且使用accel()来得到这个属性值。

bool autoMask

这个属性保存的是复选框是否被自动遮蔽。

也可以参考QWidget::autoMask。

bool autoRepeat

这个属性保存的是autoRepeat是否生效。

如果autoRepeat生效，那么如果按钮是按下的，clicked()信号会被定期发送。这个属性对切换按钮没有效果。autoRepeat默认是关闭的。

使用setAutoRepeat()来设置这个属性值并且使用autoRepeat()来得到这个属性值。

bool checked

这个属性保存的是复选框是否被选中。

默认是未选中的，也就是假。

使用setChecked()来设置这个属性值并且使用isChecked()来得到这个属性值。

QPixmap pixmap

这个属性保存的是按钮上显示的像素映射。

如果像素映射是单色的（比如，它是一个QBitmap或者它的深度为1）并且没有掩码，这个属性将设置像素映射为它自己的掩码。这样的目的是为了绘制对于切换按钮是很重要的透明位图。

如果没有像素映射被设置，pixmap()返回0。

使用setPixmap()来设置这个属性值并且使用pixmap()来得到这个属性值。

QString text

这个属性保存的是按钮上显示的文本。

如果按钮没有文本，这个属性将返回一个零字符串。如果文本中有一个“&”，那么一个使用紧随“&”之后的字母的快捷键将被创建。

没有默认文本。

使用setText()来设置这个属性值并且使用text().来得到这个属性值。

bool tristate

这个属性保存的是复选框是否是三态复选框。

默认是两态的，也就是三态为假。

使用setTristate()来设置这个属性值并且使用isTristate()来得到这个属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qcheckbox.h包含文件

qcheckbox.h

这里是qcheckbox.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qcheckbox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QCheckBox class
**
** Created : 940222
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCHECKBOX_H
#define QCHECKBOX_H

#ifndef QT_H
#include "qbutton.h"
#endif // QT_H

#ifndef QT_NO_CHECKBOX

class Q_EXPORT QCheckBox : public QButton
{
    Q_OBJECT
    Q_PROPERTY( bool checked READ isChecked WRITE setChecked )
    Q_PROPERTY( bool tristate READ isTristate WRITE setTristate )
    Q_OVERRIDE( bool autoMask DESIGNABLE true SCRIPTABLE true )

public:
    QCheckBox( QWidget *parent, const char* name=0 );
    QCheckBox( const QString &text, QWidget *parent, const char* name=0 );

    bool    isChecked() const;

    void    setNoChange();

    void    setTristate(bool y=TRUE);
    bool    isTristate() const;

    QSize   sizeHint() const;

public slots:
    void    setChecked( bool check );

protected:
    void    resizeEvent( QResizeEvent* );
    void    drawButton( QPainter * );
    void    drawButtonLabel( QPainter * );
    void    updateMask();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QCheckBox( const QCheckBox & );
    QCheckBox &operator=( const QCheckBox & );
#endif
};

inline bool QCheckBox::isChecked() const
{ return isOn(); }

inline void QCheckBox::setChecked( bool check )
{ setOn( check ); }

#endif // QT_NO_CHECKBOX

#endif // QCHECKBOX_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCheckBox成员列表

完整的QCheckBox成员列表

这里是QCheckBox成员函数的完整列表，包括继承的成员。

  • QCheckBox()
  • accel()
  • acceptDrops()
  • adjustSize()
  • animateClick()
  • autoMask()
  • autoRepeat()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawButton()
  • drawButtonLabel()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • group()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • hitButton()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isChecked()
  • isDesktop()
  • isDialog()
  • isDown()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusiveToggle()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isOn()
  • isPopup()
  • isToggleButton()
  • isTopLevel()
  • isTristate()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setAutoRepeat()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setChecked()
  • setCursor()
  • setDisabled()
  • setDown()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNoChange()
  • setOn()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setState()
  • setStyle()
  • setTabOrder()
  • setText()
  • setToggleButton()
  • setToggleType()
  • setTristate()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • state()
  • stateChanged()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • toggle()
  • toggleType()
  • toggled()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCheckListItem Class

QCheckListItem Class Reference

The QCheckListItem class provides checkable list view items. More...

#include <qlistview.h>

Inherits QListViewItem.

List of all member functions.

Public Members

  • enum Type { RadioButton, CheckBox, Controller }
  • QCheckListItem ( QCheckListItem * parent, const QString & text, Type tt = Controller )
  • QCheckListItem ( QListViewItem * parent, const QString & text, Type tt = Controller )
  • QCheckListItem ( QListView * parent, const QString & text, Type tt = Controller )
  • QCheckListItem ( QListViewItem * parent, const QString & text, const QPixmap & p )
  • QCheckListItem ( QListView * parent, const QString & text, const QPixmap & p )
  • ~QCheckListItem ()
  • virtual void paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align )
  • virtual void paintFocus ( QPainter * p, const QColorGroup & cg, const QRect & r )
  • virtual void setOn ( bool b )
  • bool isOn () const
  • Type type () const
  • QString text () const
  • virtual int rtti () const

Protected Members

  • virtual void activate ()
  • void turnOffChild ()
  • virtual void stateChange ( bool )

Detailed Description

The QCheckListItem class provides checkable list view items.

QCheckListItems are used in QListViews to provide QListViewItems that are checkboxes, radio buttons or controllers.

Checkbox and controller check list items may be inserted at any level in a list view. Radio button check list items must be children of a controller check list item.

The item can be checked or unchecked with setOn(). Its type can be retrieved with type() and its text retrieved with text().

List View Items

See also QListViewItem, QListView and Advanced Widgets.

Member Type Documentation

QCheckListItem::Type

This enum type specifies a QCheckListItem's type:

  • QCheckListItem::RadioButton
  • QCheckListItem::CheckBox
  • QCheckListItem::Controller

Member Function Documentation

QCheckListItem::QCheckListItem ( QCheckListItem * parent, const QString & text, Type tt = Controller )

Constructs a checkable item with parent parent, text text and type tt. Note that a RadioButton must be the child of a Controller, otherwise it will not toggle.

QCheckListItem::QCheckListItem ( QListViewItem * parent, const QString & text, Type tt = Controller )

Constructs a checkable item with parent parent, text text and type tt. Note that this item must not be a RadioButton. Radio buttons must be children of a Controller.

QCheckListItem::QCheckListItem ( QListView * parent, const QString & text, Type tt = Controller )

Constructs a checkable item with parent parent, text text and type tt. Note that tt must not be RadioButton. Radio buttons must be children of a Controller.

QCheckListItem::QCheckListItem ( QListViewItem * parent, const QString & text, const QPixmap & p )

Constructs a Controller item with parent parent, text text and pixmap p.

QCheckListItem::QCheckListItem ( QListView * parent, const QString & text, const QPixmap & p )

Constructs a Controller item with parent parent, text text and pixmap p.

QCheckListItem::~QCheckListItem ()

Destroys the item, deleting all its children, freeing up all allocated resources.

void QCheckListItem::activate () [virtual protected]

Toggle check box or set radio button to on.

Reimplemented from QListViewItem.

bool QCheckListItem::isOn () const

Returns TRUE if the item is toggled on; otherwise returns FALSE.

void QCheckListItem::paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align ) [virtual]

Paints the item using the painter p and the color group cg. The item is in column column, has width width and is aligned align. (See Qt::AlignmentFlags for valid alignments.)

Reimplemented from QListViewItem.

void QCheckListItem::paintFocus ( QPainter * p, const QColorGroup & cg, const QRect & r ) [virtual]

Draws the focus rectangle r using the color group cg on the painter p.

Reimplemented from QListViewItem.

int QCheckListItem::rtti () const [virtual]

Returns 1.

Make your derived classes return their own values for rtti(), and you can distinguish between listview items. You should use values greater than 1000 preferably a large random number, to allow for extensions to this class.

Reimplemented from QListViewItem.

void QCheckListItem::setOn ( bool b ) [virtual]

Sets the button on if b is TRUE, otherwise sets it off. Maintains radio button exclusivity.

void QCheckListItem::stateChange ( bool ) [virtual protected]

This virtual function is called when the item changes its on/off state.

QString QCheckListItem::text () const

Returns the text of the item.

void QCheckListItem::turnOffChild () [protected]

If this is a Controller that has RadioButton children, turn off the child that is on.

Type QCheckListItem::type () const

Returns the type of this item.

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


QCheckListItem Member List

Complete Member List for QCheckListItem

This is the complete list of member functions for QCheckListItem, including inherited members.

  • QCheckListItem()
  • ~QCheckListItem()
  • acceptDrop()
  • activate()
  • activatedPos()
  • cancelRename()
  • childCount()
  • compare()
  • depth()
  • dragEnabled()
  • dragEntered()
  • dragLeft()
  • dropEnabled()
  • dropped()
  • enforceSortOrder()
  • firstChild()
  • height()
  • insertItem()
  • invalidateHeight()
  • isEnabled()
  • isExpandable()
  • isOn()
  • isOpen()
  • isSelectable()
  • isSelected()
  • isVisible()
  • itemAbove()
  • itemBelow()
  • itemPos()
  • key()
  • listView()
  • moveItem()
  • multiLinesEnabled()
  • nextSibling()
  • okRename()
  • paintBranches()
  • paintCell()
  • paintFocus()
  • parent()
  • pixmap()
  • removeItem()
  • renameEnabled()
  • repaint()
  • rtti()
  • setDragEnabled()
  • setDropEnabled()
  • setEnabled()
  • setExpandable()
  • setHeight()
  • setMultiLinesEnabled()
  • setOn()
  • setOpen()
  • setPixmap()
  • setRenameEnabled()
  • setSelectable()
  • setSelected()
  • setText()
  • setVisible()
  • setup()
  • sort()
  • sortChildItems()
  • startRename()
  • stateChange()
  • takeItem()
  • text()
  • totalHeight()
  • turnOffChild()
  • type()
  • width()
  • widthChanged()


QCheckTableItem类

QCheckTableItem类参考
[表格模块]

QCheckTableItem类提供了QTable中的多选框。 详见……

#include <qtable.h>

继承了QTableItem。

所有成员函数的列表。

公共成员

  • QCheckTableItem ( QTable * table, const QString & txt )
  • virtual void setChecked ( bool b )
  • bool isChecked () const
  • virtual int rtti () const

详细描述

QCheckTableItem类提供了QTable中的多选框。

一个QCheckTableItem是一个表项，其外观和行为如同多选框。使用QCheckTableItem而不是真实的多选框的好处在于，在QTable中QCheckTableItem要比真实的多选框节省很多资源。当单元格具有焦点时，QCheckTableItem显示一个与用户交互的真实多选框。当单元格没有焦点时，单元格看起来像是一个多选框。象素映射不能用于QCheckTableItem。

QCheckTableItem表项具有编辑类型WhenCurrent（参见EditType）。

要改变多选框的标签，使用setText()。多选框可以通过setChecked()来设置选中和不选中，其状态可以通过isChecked()得到。

使用QTable::setItem()以把QCheckTableItem填充进一个表格单元格。

使用运行时类型判别（rtti）值，可以辨别QCheckTableItem与QTableItem和QComboTableItem。

也参见rtti()、EditType、QComboTableItem、QTableItem和高级部件。

成员函数文档

QCheckTableItem::QCheckTableItem ( QTable * table, const QString & txt )

生成一个QCheckTableItem作为表格的子部件，其EditType为WhenCurrent。多选框初始为不选中，标签设置为字符串txt。

bool QCheckTableItem::isChecked () const

如果多选框表项选中，返回TRUE；否则返回FALSE。

也参见setChecked()。

int QCheckTableItem::rtti () const [virtual]

返回2。

让你的派生类为rtti()返回自己的值，以区别于其他表项子类。你应该使用大于1000的值，最好是大的随机数，以允许对该类的扩展。

也参见QTableItem::rtti()。

由QTableItem处重新实现。

void QCheckTableItem::setChecked ( bool b ) [virtual]

如果b为TRUE，多选框被选中；如果b为FALSE，多选框未被选中。

也参见isChecked()。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QCheckTableItem成员列表

完整的QCheckTableItem成员列表

这里是QCheckTableItem成员函数的完整列表，包括继承的成员。

  • QCheckTableItem()
  • alignment()
  • col()
  • colSpan()
  • createEditor()
  • editType()
  • isChecked()
  • isEnabled()
  • isReplaceable()
  • key()
  • paint()
  • pixmap()
  • row()
  • rowSpan()
  • rtti()
  • setChecked()
  • setCol()
  • setContentFromEditor()
  • setEnabled()
  • setPixmap()
  • setReplaceable()
  • setRow()
  • setSpan()
  • setText()
  • setWordWrap()
  • sizeHint()
  • table()
  • text()
  • wordWrap()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QChildEvent Class

QChildEvent Class Reference

The QChildEvent class contains event parameters for child object events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QChildEvent ( Type type, QObject * child )
  • QObject * child () const
  • bool inserted () const
  • bool removed () const

Detailed Description

The QChildEvent class contains event parameters for child object events.

Child events are sent to objects when children are inserted or removed.

A ChildRemoved event is sent immediately, but a ChildInserted event is posted (with QApplication::postEvent()).

Note that if a child is removed immediately after it is inserted, the ChildInserted event may be suppressed, but the ChildRemoved event will always be sent. In this case there will be a ChildRemoved event without a corresponding ChildInserted event.

The handler for these events is QObject::childEvent().

See also Event Classes.

Member Function Documentation

QChildEvent::QChildEvent ( Type type, QObject * child )

Constructs a child event object. The child is the object that is to be removed or inserted.

The type parameter must be either QEvent::ChildInserted or QEvent::ChildRemoved.

QObject * QChildEvent::child () const

Returns the child widget that was inserted or removed.

bool QChildEvent::inserted () const

Returns TRUE if the widget received a new child; otherwise returns FALSE.

bool QChildEvent::removed () const

Returns TRUE if the object lost a child; otherwise returns FALSE.

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


QChildEvent Member List

Complete Member List for QChildEvent

This is the complete list of member functions for QChildEvent, including inherited members.

  • QChildEvent()
  • child()
  • inserted()
  • removed()
  • spontaneous()
  • type()


QClipboard类

QClipboard类参考

QClipboard类提供了对窗口系统剪贴板的访问。 详情请见……

#include <qclipboard.h>

继承了QObject。

所有成员函数的列表。

公有成员

  • void clear ()
  • bool supportsSelection () const
  • bool ownsSelection () const
  • bool ownsClipboard () const
  • void setSelectionMode ( bool enable )
  • bool selectionModeEnabled () const
  • QMimeSource * data () const
  • void setData ( QMimeSource * src )
  • QString text () const
  • QString text ( QCString & subtype ) const
  • void setText ( const QString & text )
  • QImage image () const
  • QPixmap pixmap () const
  • void setImage ( const QImage & image )
  • void setPixmap ( const QPixmap & pixmap )

信号

  • void selectionChanged ()
  • void dataChanged ()

详细描述

QClipboard类提供了对窗口系统剪贴板的访问。

剪贴板提供了一种在应用程序之间复制和粘贴数据的简单机制。

QClipboard支持和QDragObject一样的数据类型，并且使用类似的机制。有关剪贴板高级的用法请阅读拖放文档。

在应用程序中只有一个QClipboard，并且你可以使用QApplication::clipboard()来访问它。

实例：

    QClipboard *cb = QApplication::clipboard();
    QString text;

    // 从剪贴板中复制文本（粘贴）
    text = cb->text();
    if ( text )
        qDebug( "The clipboard contains: %s", text );

    // 把文本复制到剪贴板
    cb->setText( "This text can be pasted by other programs" );

QClipboard提供了一些有特色的很方便的函数来访问普通数据类型：setText()允许在应用程序之间Unicode文本的交换，setPixmap()和setImage()允许在应用程序之间交换QPixmap和QImage。setData()函数在功能上是最灵活的：它允许你把任何QMimeSource添加到剪贴板。每种方式都有相应的获得函数，例如text()、image()和pixmap()。

你可以通过调用clear()清空剪贴板。

X窗口系统和微软的Windows底层的剪贴板是不同的。X窗口系统有一个选择的概念——当文本被选择，它立即被复制到选择缓冲；微软的Windows仅仅在文本被显示地复制或者剪切的时候才被复制到剪贴板。X窗口系统还有一个所有权的概念，如果你在一个窗口中改变了选择，X11仅仅通知变化的拥有者和前任拥有者，在微软的Windows是剪贴板是一个完完全全的全局资源，所以所有应用程序被通知了变化。请参考Qt设计器实例中的multiclip实例，这是一个也描述了选择处理的多平台剪贴板应用程序。

也可以参考环境类和输入/输出和网络。

成员函数文档

void QClipboard::clear ()

清空剪贴板内容。

QMimeSource * QClipboard::data () const

返回代表当前剪贴板数据的QMimeSource的引用。

void QClipboard::dataChanged () [信号]

当剪贴板内容发生变化时，这个信号被发射。

QImage QClipboard::image () const

返回剪贴板图片，或者如果剪贴板没有包含任何图片或者它包含一个不被支持的格式的图片，返回一个无效的图片。

也可以参考setImage()、pixmap()、data()和QImage::isNull()。

bool QClipboard::ownsClipboard () const

如果剪贴板对象拥有剪贴板数据，返回真，否则返回假。

bool QClipboard::ownsSelection () const

如果剪贴板对象拥有鼠标选择数据，返回真，否则返回假。

QPixmap QClipboard::pixmap () const

返回剪贴板像素映射，或者如果剪贴板不包含像素映射，返回无效的像素映射。注意这样会导致丢失信息。例如，如果图片是24位并且显示是8位，结果会被转换为8位，并且如果这个图象有一个alpha通道，结果会只有一个面具。

也可以参考setPixmap()、image()、data()和QPixmap::convertFromImage()。

void QClipboard::selectionChanged () [信号]

当选择发生变化时，这个信号被发射。这仅仅适用于支持选择的窗口系统，例如X11。Windows不支持选择。

bool QClipboard::selectionModeEnabled () const

返回选择模式。

也可以参考setSelectionMode()和supportsSelection()。

void QClipboard::setData ( QMimeSource * src )

设置剪贴板数据位src。数据的所有权被传递给剪贴板。如果你想移除这个数据，请调用clear()或者使用新数据再次调用setData()。

QDragObject子类是可以放到剪贴板中的合理对象（但是不要试图在同一个对象上调用QDragObject::drag()）。任何被放置到剪贴板中的QDragObject的父对象都必须为0。不要把QDragMoveEvent或QDropEvent的子类放到剪贴板中，因为它们不属于接收到它们的事件处理器。

setText()和setPixmap()函数只是分别地对文本和图象数据的简单封装。

void QClipboard::setImage ( const QImage & image )

把image复制到剪贴板。

这是一个快速的方式：

        setData(new QImageDrag(image))

也可以参考image()、setPixmap()和setData()。

void QClipboard::setPixmap ( const QPixmap & pixmap )

把pixmap复制到剪贴板。注意这个比setImage()慢，因为它需要首先把QPixmap转换为QImage。

也可以参考pixmap()、setImage()和setData()。

void QClipboard::setSelectionMode ( bool enable )

设置剪贴板选择模式。如果enable为真，那么后来对QClipboard::setData()的调用以及其它把数据放到简帖板的函数都将会把数据放到鼠标选择中，否则数据将会被放到剪贴板中。

也可以参考supportsSelection()和selectionModeEnabled()。

void QClipboard::setText ( const QString & text )

把text作为简单文本复制到剪贴板中。

也可以参考text()和setData()。

bool QClipboard::supportsSelection () const

如果剪贴板支持鼠标选择，返回真，否则返回假。

QString QClipboard::text ( QCString & subtype ) const

返回子类型为subtype的剪贴板文本，或者如果剪贴板不包含任何文本，返回一个无效字符串。如果subtype为空，任何子类型都是可以接受的，并且subtype被设置为被选择的子类型。

subtype的值应为“plain”和“html”。

也可以参考setText()、data()和QString::operator!()。

QString QClipboard::text () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回纯文本格式的剪贴板文本，或者如果剪贴板不包含任何文本，返回一个无效字符串。

也可以参考setText()、data()和QString::operator!()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qclipboard.h包含文件

qclipboard.h

这里是qclipboard.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QClipboard class
**
** Created : 960430
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCLIPBOARD_H
#define QCLIPBOARD_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_CLIPBOARD

class QMimeSource;

class Q_EXPORT QClipboard : public QObject
{
    Q_OBJECT
private:
    QClipboard( QObject *parent=0, const char *name=0 );
    ~QClipboard();

public:
    void	clear();

    bool supportsSelection() const;
    bool ownsSelection() const;
    bool ownsClipboard() const;

    void setSelectionMode(bool enable);
    bool selectionModeEnabled() const;

#ifndef QT_NO_MIMECLIPBOARD
    QMimeSource *data() const;
    void setData( QMimeSource* );
#endif

    QString     text()	 const;
    QString     text(QCString& subtype) const;
    void	setText( const QString &);

#ifndef QT_NO_MIMECLIPBOARD
    QImage	image() const;
    QPixmap	pixmap() const;
    void	setImage( const QImage & );
    void	setPixmap( const QPixmap & );
#endif
signals:
    void        selectionChanged();
    void	dataChanged();

private slots:
    void	ownerDestroyed();

protected:
    void	connectNotify( const char * );
    bool	event( QEvent * );

    friend class QApplication;
    friend class QBaseApplication;
    friend class QDragManager;
    friend class QMimeSource;

private:	// Disabled copy constructor and operator=
#if defined(Q_WS_X11)
    void clobber();
#elif defined(Q_WS_MAC)
    void loadScrap(bool convert);
    void saveScrap();
#endif

#if defined(Q_DISABLE_COPY)
    QClipboard( const QClipboard & );
    QClipboard &operator=( const QClipboard & );
#endif
};

#endif // QT_NO_CLIPBOARD

#endif // QCLIPBOARD_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QClipboard成员列表

完整的QClipboard成员列表

这里是QClipboard成员函数的完整列表，包括继承的成员。

  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clear()
  • connect()
  • connectNotify()
  • customEvent()
  • data()
  • dataChanged()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • image()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownsClipboard()
  • ownsSelection()
  • parent()
  • pixmap()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • selectionChanged()
  • selectionModeEnabled()
  • sender()
  • setData()
  • setImage()
  • setName()
  • setPixmap()
  • setProperty()
  • setSelectionMode()
  • setText()
  • signalsBlocked()
  • startTimer()
  • supportsSelection()
  • text()
  • timerEvent()
  • tr()
  • trUtf8()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCloseEvent Class

QCloseEvent Class Reference

The QCloseEvent class contains parameters that describe a close event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QCloseEvent ()
  • bool isAccepted () const
  • void accept ()
  • void ignore ()

Detailed Description

The QCloseEvent class contains parameters that describe a close event.

Close events are sent to widgets that the user wants to close, usually by choosing "Close" from the window menu, or by clicking the `X' titlebar button. They are also sent when you call QWidget::close() to close a widget programmatically.

Close events contain a flag that indicates whether the receiver wants the widget to be closed or not. When a widget accepts the close event, it is hidden (and destroyed if it was created with the WDestructiveClose flag). If it refuses to accept the close event nothing happens. (Under X11 it is possible that the window manager will forcibly close the window; but at the time of writing we are not aware of any window manager that does this.)

The application's main widget -- QApplication::mainWidget() -- is a special case. When it accepts the close event, Qt leaves the main event loop and the application is immediately terminated (i.e. it returns from the call to QApplication::exec() in the main() function).

The event handler QWidget::closeEvent() receives close events. The default implementation of this event handler accepts the close event. If you do not want your widget to be hidden, or want some special handing, you should reimplement the event handler.

The closeEvent() in the Application Walkthrough shows a close event handler that asks whether to save a document before closing.

If you want the widget to be deleted when it is closed, create it with the WDestructiveClose widget flag. This is very useful for independent top-level windows in a multi-window application.

QObjects emits the destroyed() signal when they are deleted.

If the last top-level window is closed, the QApplication::lastWindowClosed() signal is emitted.

The isAccepted() function returns TRUE if the event's receiver has agreed to close the widget; call accept() to agree to close the widget and call ignore() if the receiver of this event does not want the widget to be closed.

See also QWidget::close(), QWidget::hide(), QObject::destroyed(), QApplication::setMainWidget(), QApplication::lastWindowClosed(), QApplication::exec(), QApplication::quit() and Event Classes.

Member Function Documentation

QCloseEvent::QCloseEvent ()

Constructs a close event object with the accept parameter flag set to FALSE.

See also accept().

void QCloseEvent::accept ()

Sets the accept flag of the close event object.

Setting the accept flag indicates that the receiver of this event agrees to close the widget.

The accept flag is not set by default.

If you choose to accept in QWidget::closeEvent(), the widget will be hidden. If the widget's WDestructiveClose flag is set, it will also be destroyed.

See also ignore() and QWidget::hide().

Examples: action/application.cpp, application/application.cpp, popup/popup.cpp and qwerty/qwerty.cpp.

void QCloseEvent::ignore ()

Clears the accept flag of the close event object.

Clearing the accept flag indicates that the receiver of this event does not want the widget to be closed.

The close event is constructed with the accept flag cleared.

See also accept().

Examples: action/application.cpp, application/application.cpp and qwerty/qwerty.cpp.

bool QCloseEvent::isAccepted () const

Returns TRUE if the receiver of the event has agreed to close the widget; otherwise returns FALSE.

See also accept() and ignore().

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


QCloseEvent Member List

Complete Member List for QCloseEvent

This is the complete list of member functions for QCloseEvent, including inherited members.

  • QCloseEvent()
  • accept()
  • ignore()
  • isAccepted()
  • spontaneous()
  • type()


QColor Class

QColor Class Reference

The QColor class provides colors based on RGB or HSV values. More...

#include <qcolor.h>

List of all member functions.

Public Members

  • enum Spec { Rgb, Hsv }
  • QColor ()
  • QColor ( int r, int g, int b )
  • QColor ( int x, int y, int z, Spec colorSpec )
  • QColor ( QRgb rgb, uint pixel = 0xffffffff )
  • QColor ( const QString & name )
  • QColor ( const char * name )
  • QColor ( const QColor & c )
  • QColor & operator= ( const QColor & c )
  • bool isValid () const
  • QString name () const
  • void setNamedColor ( const QString & name )
  • void rgb ( int * r, int * g, int * b ) const
  • QRgb rgb () const
  • void setRgb ( int r, int g, int b )
  • void setRgb ( QRgb rgb )
  • int red () const
  • int green () const
  • int blue () const
  • void hsv ( int * h, int * s, int * v ) const
  • void getHsv ( int & h, int & s, int & v ) const (obsolete)
  • void setHsv ( int h, int s, int v )
  • QColor light ( int factor = 150 ) const
  • QColor dark ( int factor = 200 ) const
  • bool operator== ( const QColor & c ) const
  • bool operator!= ( const QColor & c ) const
  • uint alloc ()
  • uint pixel () const

Static Public Members

  • int maxColors ()
  • int numBitPlanes ()
  • int enterAllocContext ()
  • void leaveAllocContext ()
  • int currentAllocContext ()
  • void destroyAllocContext ( int context )
  • void initialize ()
  • void cleanup ()

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QColor & c )
  • QDataStream & operator>> ( QDataStream & s, QColor & c )
  • int qRed ( QRgb rgb )
  • int qGreen ( QRgb rgb )
  • int qBlue ( QRgb rgb )
  • int qAlpha ( QRgb rgba )
  • QRgb qRgb ( int r, int g, int b )
  • QRgb qRgba ( int r, int g, int b, int a )
  • int qGray ( int r, int g, int b )
  • int qGray ( qRgb rgb )

Detailed Description

The QColor class provides colors based on RGB or HSV values.

A color is normally specified in terms of RGB (red, green and blue) components, but it is also possible to specify HSV (hue, saturation and value) or set a color name (the names are copied from from the X11 color database).

In addition to the RGB value, a QColor also has a pixel value and a validity. The pixel value is used by the underlying window system to refer to a color. It can be thought of as an index into the display hardware's color table.

The validity (isValid()) indicates whether the color is legal at all. For example, a RGB color with RGB values out of range is illegal. For performance reasons, QColor mostly disregards illegal colors. The result of using an invalid color is unspecified and will usually be surprising.

There are 19 predefined QColor objects: white, black, red, darkRed, green, darkGreen, blue, darkBlue, cyan, darkCyan, magenta, darkMagenta, yellow, darkYellow, gray, darkGray, lightGray, color0 and color1.

The colors color0 (zero pixel value) and color1 (non-zero pixel value) are special colors for drawing in bitmaps. Painting with color0 sets the bitmap bits to 0 (transparent, i.e. background), and painting with color1 sets the bits to 1 (opaque, i.e. foreground).

The QColor class has an efficient, dynamic color allocation strategy. A color is normally allocated the first time it is used (lazy allocation), that is, whenever the pixel() function is called:

  1. Is the pixel value valid? If it is, just return it; otherwise, allocate a pixel value.
  2. Check an internal hash table to see if we allocated an equal RGB value earlier. If we did, set the pixel value and return.
  3. Try to allocate the RGB value. If we succeed, we get a pixel value that we save in the internal table with the RGB value. Return the pixel value.
  4. The color could not be allocated. Find the closest matching color and save it in the internal table.

A color can be set by passing setNamedColor() an RGB string like "#112233", or a color name, e.g. "blue". The names are taken from X11's rgb.txt database but can also be used under Windows. To get a lighter or darker color use light() and dark() respectively. Colors can also be set using setRgb() and setHsv(). The color components can be accessed in one go with rgb() and hsv(), or individually with red(), green() and blue().

Use maxColors() and numBitPlanes() to determine the maximum number of colors and the number of bit planes supported by the underlying window system,

If you need to allocate many colors temporarily, for example in an image viewer application, enterAllocContext(), leaveAllocContext() and destroyAllocContext() will prove useful.

HSV Colors

Because many people don't know the HSV color model very well, we'll cover it briefly here.

The RGB model is hardware-oriented. Its representation is close to what most monitors show. In contrast, HSV represents color in a way more suited to the human perception of color. For example, the relationships "stronger than", "darker than" and "the opposite of" are easily expressed in HSV but are much harder to express in RGB.

HSV, like RGB, has three components:

  • H, for hue, is either 0-359 if the color is chromatic (not gray), or meaningless if it is gray. It represents degrees on the color wheel familiar to most people. Red is 0 (degrees), green is 120 and blue is 240.

  • S, for saturation, is 0-255, and the bigger it is, the stronger the color is. Grayish colors have saturation near 0; very strong colors have saturation near 255.

  • V, for value, is 0-255 and represents lightness or brightness of the color. 0 is black; 255 is as far from black as possible.

Here are some examples: Pure red is H=0, S=255, V=255. A dark red, moving slightly towards the magenta, could be H=350 (equivalent to -10), S=255, V=180. A grayish light red could have H about 0 (say 350-359 or 0-10), S about 50-100, and S=255.

Qt returns a hue value of -1 for achromatic colors. If you pass a too-big hue value, Qt forces it into range. Hue 360 or 720 is treated as 0; hue 540 is treated as 180.

See also QPalette, QColorGroup, QApplication::setColorSpec(), Color FAQ, Widget Appearance and Style, Graphics Classes and Image Processing Classes.

Member Type Documentation

QColor::Spec

The type of color specified, either RGB or HSV, e.g. in the QColor::QColor( x, y, z, colorSpec) constructor.

  • QColor::Rgb
  • QColor::Hsv

Member Function Documentation

QColor::QColor ()

Constructs an invalid color with the RGB value (0, 0, 0). An invalid color is a color that is not properly set up for the underlying window system.

The alpha value of an invalid color is unspecified.

See also isValid().

QColor::QColor ( int r, int g, int b )

Constructs a color with the RGB value r, g, b, in the same way as setRgb().

The color is left invalid if any or the arguments are illegal.

See also setRgb().

QColor::QColor ( int x, int y, int z, Spec colorSpec )

Constructs a color with the RGB or HSV value x, y, z.

The arguments are an RGB value if colorSpec is QColor::Rgb. x (red), y (green), and z (blue). All of them must be in the range 0-255.

The arguments are an HSV value if colorSpec is QColor::Hsv. x (hue) must be -1 for achromatic colors and 0-359 for chromatic colors; y (saturation) and z (value) must both be in the range 0-255.

See also setRgb() and setHsv().

QColor::QColor ( QRgb rgb, uint pixel = 0xffffffff )

Constructs a color with the RGB value rgb and a custom pixel value pixel.

If pixel == 0xffffffff (the default), then the color uses the RGB value in a standard way. If pixel is something else, then the pixel value is set directly to pixel, skipping the normal allocation procedure.

QColor::QColor ( const QString & name )

Constructs a named color in the same way as setNamedColor() using name name.

The color is left invalid if name cannot be parsed.

See also setNamedColor().

QColor::QColor ( const char * name )

Constructs a named color in the same way as setNamedColor() using name name.

The color is left invalid if name cannot be parsed.

See also setNamedColor().

QColor::QColor ( const QColor & c )

Constructs a color that is a copy of c.

uint QColor::alloc ()

Allocates the RGB color and returns the pixel value.

Allocating a color means to obtain a pixel value from the RGB specification. The pixel value is an index into the global color table, but should be considered to be an arbitrary platform-dependent value.

The pixel() function calls alloc() if necessary, so in general you don't need to call this function.

See also enterAllocContext().

int QColor::blue () const

Returns the B (blue) component of the RGB value.

void QColor::cleanup () [static]

Internal clean up required for QColor. This function is called from the QApplication destructor.

See also initialize().

int QColor::currentAllocContext () [static]

Returns the current color allocation context.

The default context is 0.

See also enterAllocContext() and leaveAllocContext().

QColor QColor::dark ( int factor = 200 ) const

Returns a darker (or lighter) color, but does not change this object.

Returns a darker color if factor is greater than 100. Setting factor to 300 returns a color that has one-third the brightness.

Returns a lighter color if factor is less than 100. We recommend using lighter() for this purpose. If factor is 0 or negative, the return value is unspecified.

(This function converts the current RGB color to HSV, divides V by factor and converts back to RGB.)

See also light().

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

void QColor::destroyAllocContext ( int context ) [static]

Destroys a color allocation context, context.

This function deallocates all colors that were allocated in the specified context. If context == -1, it frees up all colors that the application has allocated. If context == -2, it frees up all colors that the application has allocated, except those in the default context.

The function does nothing for true color displays.

See also enterAllocContext() and alloc().

Example: showimg/showimg.cpp.

int QColor::enterAllocContext () [static]

Enters a color allocation context and returns a non-zero unique identifier.

Color allocation contexts are useful for programs that need to allocate many colors and throw them away later, like image viewers. The allocation context functions work for true color displays as well as for colormap displays, except that QColor::destroyAllocContext() does nothing for true color.

Example:

    QPixmap loadPixmap( QString fileName )
    {
        static int alloc_context = 0;
        if ( alloc_context )
            QColor::destroyAllocContext( alloc_context );
        alloc_context = QColor::enterAllocContext();
        QPixmap pm( fileName );
        QColor::leaveAllocContext();
        return pm;
    }

The example code loads a pixmap from file. It frees up all colors that were allocated the last time loadPixmap() was called.

The initial/default context is 0. Qt keeps a list of colors associated with their allocation contexts. You can call destroyAllocContext() to get rid of all colors that were allocated in a specific context.

Calling enterAllocContext() enters an allocation context. The allocation context lasts until you call leaveAllocContext(). QColor has an internal stack of allocation contexts. Each call to enterAllocContex() must have a corresponding leaveAllocContext().

        // context 0 active
    int c1 = QColor::enterAllocContext();    // enter context c1
        // context c1 active
    int c2 = QColor::enterAllocContext();    // enter context c2
        // context c2 active
    QColor::leaveAllocContext();             // leave context c2
        // context c1 active
    QColor::leaveAllocContext();             // leave context c1
        // context 0 active
        // Now, free all colors that were allocated in context c2
    QColor::destroyAllocContext( c2 );

You may also want to set the application's color specification. See QApplication::setColorSpec() for more information.

See also leaveAllocContext(), currentAllocContext(), destroyAllocContext() and QApplication::setColorSpec().

Example: showimg/showimg.cpp.

void QColor::getHsv ( int & h, int & s, int & v ) const

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

int QColor::green () const

Returns the G (green) component of the RGB value.

void QColor::hsv ( int * h, int * s, int * v ) const

Returns the current RGB value as HSV. The contents of the h, s and v pointers are set to the HSV values. If any of the three pointers are null, the function does nothing.

The hue (which h points to) is set to -1 if the color is achromatic.

See also setHsv() and rgb().

Example: themes/metal.cpp.

void QColor::initialize () [static]

Internal initialization required for QColor. This function is called from the QApplication constructor.

See also cleanup().

bool QColor::isValid () const

Returns FALSE if the color is invalid, i.e. it was constructed using the default constructor; otherwise returns TRUE.

Examples: chart/element.cpp, chart/setdataform.cpp and scribble/scribble.cpp.

void QColor::leaveAllocContext () [static]

Leaves a color allocation context.

See enterAllocContext() for a detailed explanation.

See also enterAllocContext() and currentAllocContext().

Example: showimg/showimg.cpp.

QColor QColor::light ( int factor = 150 ) const

Returns a lighter (or darker) color, but does not change this object.

Returns a lighter color if factor is greater than 100. Setting factor to 150 returns a color that is 50% brighter.

Returns a darker color if factor is less than 100. We recommend using dark() for this purpose. If factor is 0 or negative, the return value is unspecified.

(This function converts the current RGB color to HSV, multiplies V by factor, and converts the result back to RGB.)

See also dark().

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

int QColor::maxColors () [static]

Returns the maximum number of colors supported by the underlying window system.

QString QColor::name () const

Returns the name of the color in the format "#RRGGBB", i.e. a "#" character followed by three two-digit hexadecimal numbers.

See also setNamedColor().

Example: chart/setdataform.cpp.

int QColor::numBitPlanes () [static]

Returns the number of color bit planes for the underlying window system.

The returned value is equal to the default pixmap depth.

See also QPixmap::defaultDepth().

bool QColor::operator!= ( const QColor & c ) const

Returns TRUE if this color has a different RGB value from c; otherwise returns FALSE.

QColor & QColor::operator= ( const QColor & c )

Assigns a copy of the color c and returns a reference to this color.

bool QColor::operator== ( const QColor & c ) const

Returns TRUE if this color has the same RGB value as c; otherwise returns FALSE.

uint QColor::pixel () const

Returns the pixel value.

This value is used by the underlying window system to refer to a color. It can be thought of as an index into the display hardware's color table, but the value is an arbitrary 32-bit value.

See also alloc().

int QColor::red () const

Returns the R (red) component of the RGB value.

void QColor::rgb ( int * r, int * g, int * b ) const

Sets the contents pointed to by r, g and b to the red, green and blue components of the RGB value respectively. The value range for a component is 0..255.

See also setRgb() and hsv().

QRgb QColor::rgb () const

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

Returns the RGB value.

The return type QRgb is equivalent to unsigned int.

For an invalid color, the alpha value of the returned color is unspecified.

See also setRgb(), hsv(), qRed(), qBlue(), qGreen() and isValid().

void QColor::setHsv ( int h, int s, int v )

Sets a HSV color value. h is the hue, s is the saturation and v is the value of the HSV color.

If s or v are not in the range 0-255, or h is < -1, the color is not changed.

See also hsv() and setRgb().

Examples: drawdemo/drawdemo.cpp, grapher/grapher.cpp and progress/progress.cpp.

void QColor::setNamedColor ( const QString & name )

Sets the RGB value to name, which may be in one of these formats:
  • #RGB (each of R, G and B is a single hex digit)
  • #RRGGBB
  • #RRRGGGBBB
  • #RRRRGGGGBBBB
  • A name from the X color database (rgb.txt) (e.g. "steelblue" or "gainsboro"). These color names also work under Windows.

The color is left invalid if name cannot be parsed.

void QColor::setRgb ( int r, int g, int b )

Sets the RGB value to r, g, b. The arguments, r, g and b must all be in the range 0..255. If any of them are outside the legal range, the color is not changed.

See also rgb() and setHsv().

void QColor::setRgb ( QRgb rgb )

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

Sets the RGB value to rgb.

The type QRgb is equivalent to unsigned int.

See also rgb() and setHsv().

Related Functions

QDataStream & operator<< ( QDataStream & s, const QColor & c )

Writes a color object, c to the stream, s.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QColor & c )

Reads a color object, c, from the stream, s.

See also Format of the QDataStream operators.

int qAlpha ( QRgb rgba )

Returns the alpha component of the RGBA quadruplet rgba.

int qBlue ( QRgb rgb )

Returns the blue component of the RGB triplet rgb.

See also qRgb() and QColor::blue().

int qGray ( int r, int g, int b )

Returns a gray value 0..255 from the (r, g, b) triplet.

The gray value is calculated using the formula (r*11 + g*16 + b*5)/32.

int qGray ( qRgb rgb )

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

Returns a gray value 0..255 from the given rgb colour.

int qGreen ( QRgb rgb )

Returns the green component of the RGB triplet rgb.

See also qRgb() and QColor::green().

int qRed ( QRgb rgb )

Returns the red component of the RGB triplet rgb.

See also qRgb() and QColor::red().

QRgb qRgb ( int r, int g, int b )

Returns the RGB triplet (r,g,b).

The return type QRgb is equivalent to unsigned int.

See also qRgba(), qRed(), qGreen() and qBlue().

QRgb qRgba ( int r, int g, int b, int a )

Returns the RGBA quadruplet (r,g,b,a).

The return type QRgba is equivalent to unsigned int.

See also qRgb(), qRed(), qGreen() and qBlue().

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


qcolor.h Include File

qcolor.h

This is the verbatim text of the qcolor.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qcolor.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QColor class
**
** Created : 940112
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCOLOR_H
#define QCOLOR_H

#ifndef QT_H
#include "qwindowdefs.h"
#endif // QT_H

const QRgb  RGB_MASK    = 0x00ffffff;		// masks RGB values

Q_EXPORT inline int qRed( QRgb rgb )		// get red part of RGB
{ return (int)((rgb >> 16) & 0xff); }

Q_EXPORT inline int qGreen( QRgb rgb )		// get green part of RGB
{ return (int)((rgb >> 8) & 0xff); }

Q_EXPORT inline int qBlue( QRgb rgb )		// get blue part of RGB
{ return (int)(rgb & 0xff); }

Q_EXPORT inline int qAlpha( QRgb rgb )		// get alpha part of RGBA
{ return (int)((rgb >> 24) & 0xff); }

Q_EXPORT inline QRgb qRgb( int r, int g, int b )// set RGB value
{ return (0xff << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); }

Q_EXPORT inline QRgb qRgba( int r, int g, int b, int a )// set RGBA value
{ return ((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); }

Q_EXPORT inline int qGray( int r, int g, int b )// convert R,G,B to gray 0..255
{ return (r*11+g*16+b*5)/32; }

Q_EXPORT inline int qGray( QRgb rgb )		// convert RGB to gray 0..255
{ return qGray( qRed(rgb), qGreen(rgb), qBlue(rgb) ); }

class Q_EXPORT QColor
{
public:
    enum Spec { Rgb, Hsv };

    QColor();
    QColor( int r, int g, int b );
    QColor( int x, int y, int z, Spec );
    QColor( QRgb rgb, uint pixel=0xffffffff);
    QColor( const QString& name );
    QColor( const char *name );
    QColor( const QColor & );
    QColor &operator=( const QColor & );

    bool   isValid() const;
    bool   isDirty() const;
#ifndef QT_NO_SPRINTF
    QString name() const;
#endif
    void   setNamedColor( const QString& name );

    void   rgb( int *r, int *g, int *b ) const;
    QRgb   rgb()    const;
    void   setRgb( int r, int g, int b );
    void   setRgb( QRgb rgb );

    int	   red()    const;
    int	   green()  const;
    int	   blue()   const;

    void   hsv( int *h, int *s, int *v ) const;
    void   getHsv( int &h, int &s, int &v ) const { hsv( &h, &s, &v ); }
    void   setHsv( int h, int s, int v );

    QColor light( int f = 150 ) const;
    QColor dark( int f = 200 )	const;

    bool   operator==( const QColor &c ) const;
    bool   operator!=( const QColor &c ) const;

    uint   alloc();
    uint   pixel()  const;

    static int  maxColors();
    static int  numBitPlanes();

    static int  enterAllocContext();
    static void leaveAllocContext();
    static int  currentAllocContext();
    static void destroyAllocContext( int );

#if defined(Q_WS_WIN)
    static const QRgb* palette( int* numEntries = 0 );
    static int setPaletteEntries( const QRgb* entries, int numEntries,
                  int base = -1 );
    static HPALETTE hPal()  { return hpal; }
    static uint	realizePal( QWidget * );
#endif

    static void initialize();
    static void cleanup();

    enum { Dirt = 0x44495254, Invalid = 0x49000000 };

private:
    void setSystemNamedColor( const QString& name );
    void setPixel( uint pixel );
    static void initGlobalColors();
    static uint argbToPix32(QRgb);
    static QColor* globalColors();
    static bool color_init;
    static bool globals_init;
#if defined(Q_WS_WIN)
    static HPALETTE hpal;
#endif
    static enum ColorModel { d8, d32 } colormodel;
    union {
    QRgb argb;
    struct {
        QRgb argb;
        uchar pix;
        uchar invalid;
        uchar dirty;
        uchar direct;
    } d8;
    struct D32 {
        QRgb argb;
        uint pix;
        bool invalid() const { return argb == QColor::Invalid && pix == QColor::Dirt; }
        bool probablyDirty() const { return pix == QColor::Dirt; }
    } d32;
    } d;
};

inline QColor::QColor()
{ d.d32.argb = Invalid; d.d32.pix = Dirt; }

inline QColor::QColor( int r, int g, int b )
{ setRgb( r, g, b ); }

inline QRgb QColor::rgb() const
{ return d.argb; }

inline int QColor::red() const
{ return qRed(d.argb); }

inline int QColor::green() const
{ return qGreen(d.argb); }

inline int QColor::blue() const
{ return qBlue(d.argb); }

inline bool QColor::isValid() const
{
    if ( colormodel == d8 )
    return !d.d8.invalid;
    else
    return !d.d32.invalid();
}

inline bool QColor::operator==( const QColor &c ) const
{
    return d.argb == c.d.argb && isValid() == c.isValid();
}

inline bool QColor::operator!=( const QColor &c ) const
{
    return !operator==(c);
}

/*****************************************************************************
  QColor stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QColor & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QColor & );
#endif

#endif // QCOLOR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QColor Member List

Complete Member List for QColor

This is the complete list of member functions for QColor, including inherited members.

  • QColor()
  • alloc()
  • blue()
  • cleanup()
  • currentAllocContext()
  • dark()
  • destroyAllocContext()
  • enterAllocContext()
  • getHsv()
  • green()
  • hsv()
  • initialize()
  • isValid()
  • leaveAllocContext()
  • light()
  • maxColors()
  • name()
  • numBitPlanes()
  • operator!=()
  • operator=()
  • operator==()
  • pixel()
  • red()
  • rgb()
  • setHsv()
  • setNamedColor()
  • setRgb()


QColorDialog类

QColorDialog类参考

QColorDialog类提供了指定颜色的对话框窗口部件。 详情请见……

#include <qcolordialog.h>

继承了QDialog。

所有成员函数的列表。

静态公有成员

  • QColor getColor ( const QColor & initial = white, QWidget * parent = 0, const char * name = 0 )
  • QRgb getRgba ( QRgb initial, bool * ok = 0, QWidget * parent = 0, const char * name = 0 )
  • int customCount ()
  • QRgb customColor ( int i )
  • void setCustomColor ( int i, QRgb c )

详细描述

QColorDialog类提供了指定颜色的对话框窗口部件。

眼色对话框函数允许用户来选择颜色——例如，你也许在一个绘制程序中使用它来允许用户设置画刷颜色。

静态函数提供模式颜色对话框。

getColor()静态函数显示对话框并且允许用户指定一个颜色。getRgba()函数可以做同样的事情但是也允许用户指定一个有alpha通道（透明）值的颜色。

用户可以用customCount()来存储不同的自定义颜色。自定义颜色被所有颜色对话框共享，并且在这个程序执行期间被记住。使用setCustomColor()来设置自定义颜色，并且使用customColor()来得到它们。

也可以参考对话框类和图形类。

成员函数文档

QRgb QColorDialog::customColor ( int i ) [静态]

返回一个数字为i的QRgb自定义颜色。

int QColorDialog::customCount () [静态]

返回QColorDialog所支持的自定义颜色的数量。所有的颜色对话框共享相同的自定义颜色。

QColor QColorDialog::getColor ( const QColor & initial = white, QWidget * parent = 0, const char * name = 0 ) [静态]

弹出模式颜色对话框，让用户选择一个颜色并且返回那个颜色。这个颜色用initial来初始化。对话框是parent的孩子并且名为name。如果用户撤消这个对话框，返回一个无效的颜色（请参考QColor::isValid()）。对话框分配的所有颜色在函数返回之前都将被释放。

实例：chart/setdataform.cpp和scribble/scribble.cpp。

QRgb QColorDialog::getRgba ( QRgb initial, bool * ok = 0, QWidget * parent = 0, const char * name = 0 ) [静态]

弹出模式颜色对话框，让用户选择一个颜色和一个alpha通道（透明）值。这个颜色和alpha用initial来初始化。对话框是parent的孩子并且名为name。

如果ok为非空，如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。

如果用户点击Cancel，initial值被返回。

void QColorDialog::setCustomColor ( int i, QRgb c ) [静态]

设置数字为i的自定义颜色为QRgb值c。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qcolordialog.h包含文件

qcolordialog.h

这里是qcolordialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qcolordialog.h   3.0.5   edited Apr 29 14:16 $
**
** Definition of QColorDialog class
**
** Created : 990222
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCOLORDIALOG_H
#define QCOLORDIALOG_H

#ifndef QT_H
#include <qdialog.h>
#endif // QT_H

#ifndef QT_NO_COLORDIALOG

class QColorDialogPrivate;

class Q_EXPORT QColorDialog : public QDialog
{
    Q_OBJECT

public:
    static QColor getColor( const QColor& init = white, QWidget* parent=0, const char* name=0 );
    static QRgb getRgba( QRgb, bool* ok = 0,
             QWidget* parent=0, const char* name=0 );

    static int customCount();
    static QRgb customColor( int );
    static void setCustomColor( int, QRgb );

private:
    ~QColorDialog();
    QColorDialog( QWidget* parent=0, const char* name=0, bool modal=FALSE );

    void setColor( const QColor& );
    QColor color() const;

    bool selectColor( const QColor& );

private:
    void setSelectedAlpha( int );
    int selectedAlpha() const;

    void showCustom( bool=TRUE );
private:
    QColorDialogPrivate *d;
    friend class QColorDialogPrivate;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QColorDialog( const QColorDialog & );
    QColorDialog& operator=( const QColorDialog & );
#endif
};

#endif

#endif //QCOLORDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QColorDialog成员列表

完整的QColorDialog成员列表

这里是QColorDialog成员函数的完整列表，包括继承的成员。

  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customColor()
  • customCount()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getColor()
  • getRgba()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setCustomColor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QColorDrag Class

QColorDrag Class Reference

The QColorDrag class provides a drag and drop object for transferring colors. More...

#include <qdragobject.h>

Inherits QStoredDrag.

List of all member functions.

Public Members

  • QColorDrag ( const QColor & col, QWidget * dragsource = 0, const char * name = 0 )
  • QColorDrag ( QWidget * dragsource = 0, const char * name = 0 )
  • void setColor ( const QColor & col )

Static Public Members

  • bool canDecode ( QMimeSource * e )
  • bool decode ( QMimeSource * e, QColor & col )

Detailed Description

The QColorDrag class provides a drag and drop object for transferring colors.

This class provides a drag object which can be used to transfer data about colors for drag and drop and in the clipboard. For example, it is used in QColorDialog.

The color is set in the constructor but can be changed with setColor().

For more information about drag and drop, see the QDragObject class and the drag and drop documentation.

See also Drag And Drop Classes.

Member Function Documentation

QColorDrag::QColorDrag ( const QColor & col, QWidget * dragsource = 0, const char * name = 0 )

Constructs a color drag object with the color col. Passes dragsource and name to the QStoredDrag constructor.

QColorDrag::QColorDrag ( QWidget * dragsource = 0, const char * name = 0 )

Constructs a color drag object with a white color. Passes dragsource and name to the QStoredDrag constructor.

bool QColorDrag::canDecode ( QMimeSource * e ) [static]

Returns TRUE if the color drag object can decode the mime source e; otherwise returns FALSE.

bool QColorDrag::decode ( QMimeSource * e, QColor & col ) [static]

Decodes the mime source e and sets the decoded values to col.

void QColorDrag::setColor ( const QColor & col )

Sets the color of the color drag to col.

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


QColorDrag Member List

Complete Member List for QColorDrag

This is the complete list of member functions for QColorDrag, including inherited members.

  • QColorDrag()
  • blockSignals()
  • canDecode()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • decode()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setColor()
  • setEncodedData()
  • setName()
  • setPixmap()
  • setProperty()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


QColorGroup Class

QColorGroup Class Reference

The QColorGroup class contains a group of widget colors. More...

#include <qpalette.h>

List of all member functions.

Public Members

  • QColorGroup ()
  • QColorGroup ( const QColor & foreground, const QColor & background, const QColor & light, const QColor & dark, const QColor & mid, const QColor & text, const QColor & base ) (obsolete)
  • QColorGroup ( const QBrush & foreground, const QBrush & button, const QBrush & light, const QBrush & dark, const QBrush & mid, const QBrush & text, const QBrush & bright_text, const QBrush & base, const QBrush & background )
  • QColorGroup ( const QColorGroup & other )
  • ~QColorGroup ()
  • QColorGroup & operator= ( const QColorGroup & other )
  • enum ColorRole { Foreground, Button, Light, Midlight, Dark, Mid, Text, BrightText, ButtonText, Base, Background, Shadow, Highlight, HighlightedText, Link, LinkVisited, NColorRoles }
  • const QColor & color ( ColorRole r ) const
  • const QBrush & brush ( ColorRole r ) const
  • void setColor ( ColorRole r, const QColor & c )
  • void setBrush ( ColorRole r, const QBrush & b )
  • const QColor & foreground () const
  • const QColor & button () const
  • const QColor & light () const
  • const QColor & dark () const
  • const QColor & mid () const
  • const QColor & text () const
  • const QColor & base () const
  • const QColor & background () const
  • const QColor & midlight () const
  • const QColor & brightText () const
  • const QColor & buttonText () const
  • const QColor & shadow () const
  • const QColor & highlight () const
  • const QColor & highlightedText () const
  • const QColor & link () const
  • const QColor & linkVisited () const
  • bool operator== ( const QColorGroup & g ) const
  • bool operator!= ( const QColorGroup & g ) const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QColorGroup & g )

Detailed Description

The QColorGroup class contains a group of widget colors.

A color group contains a group of colors used by widgets for drawing themselves. We recommend that widgets use color group roles such as "foreground" and "base" rather than literal colors like "red" or "turqoise". The color roles are enumerated and defined in the ColorRole documentation.

The most common use of QColorGroup is like this:

        QPainter p;
        ...
        p.setPen( colorGroup().foreground() );
        p.drawLine( ... )

It is also possible to modify color groups or create new color groups from scratch.

The color group class can be created using three different constructors or by modifying one supplied by Qt. The default constructor creates an all-black color group, which can then be modified using set functions; there's also a constructor for specifying all the color group colors. And there is also a copy constructor.

We strongly recommend using a system-supplied color group and modifying that as necessary.

You modify a color group by calling the access functions setColor() and setBrush(), depending on whether you want a pure color or a pixmap pattern.

There are also corresponding color() and brush() getters, and a commonly used convenience function to get each ColorRole: background(), foreground(), base(), etc.

See also QColor, QPalette, QWidget::colorGroup, Widget Appearance and Style, Graphics Classes and Image Processing Classes.

Member Type Documentation

QColorGroup::ColorRole

The ColorRole enum defines the different symbolic color roles used in current GUIs.

The central roles are:

  • QColorGroup::Background - general background color.
  • QColorGroup::Foreground - general foreground color.
  • QColorGroup::Base - used as background color for text entry widgets, for example; usually white or another light color.
  • QColorGroup::Text - the foreground color used with Base. Usually this is the same as the Foreground, in which case it must provide good contrast with Background and Base.
  • QColorGroup::Button - general button background color in which buttons need a background different from Background, as in the Macintosh style.
  • QColorGroup::ButtonText - a foreground color used with the Button color.

There are some color roles used mostly for 3D bevel and shadow effects:

  • QColorGroup::Light - lighter than Button color.
  • QColorGroup::Midlight - between Button and Light.
  • QColorGroup::Dark - darker than Button.
  • QColorGroup::Mid - between Button and Dark.
  • QColorGroup::Shadow - a very dark color. By default, the shadow color is Qt::black.

All of these are normally derived from Background and used in ways that depend on that relationship. For example, buttons depend on it to make the bevels look attractive, and Motif scroll bars depend on Mid to be slightly different from Background.

Selected (marked) items have two roles:

  • QColorGroup::Highlight - a color to indicate a selected or highlighted item. By default, the highlight color is Qt::darkBlue.
  • QColorGroup::HighlightedText - a text color that contrasts with Highlight. By default, the highlighted text color is Qt::white.

Finally, there is a special role for text that needs to be drawn where Text or Foreground would give poor contrast, such as on pressed push buttons:

  • QColorGroup::BrightText - a text color that is very different from Foreground and contrasts well with e.g. Dark.
  • QColorGroup::Link - a text color used for unvisited hyperlinks. By default, the link color is Qt::blue.
  • QColorGroup::LinkVisited - a text color used for already visited hyperlinks. By default, the linkvisited color is Qt::magenta.
  • QColorGroup::NColorRoles - Internal.

Note that text colors can be used for things other than just words; text colors are usually used for text, but it's quite common to use the text color roles for lines, icons, etc.

This image shows most of the color roles in use:

Member Function Documentation

QColorGroup::QColorGroup ()

Constructs a color group with all colors set to black.

QColorGroup::QColorGroup ( const QColor & foreground, const QColor & background, const QColor & light, const QColor & dark, const QColor & mid, const QColor & text, const QColor & base )

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

Constructs a color group with the specified colors. The button color will be set to the background color.

QColorGroup::QColorGroup ( const QBrush & foreground, const QBrush & button, const QBrush & light, const QBrush & dark, const QBrush & mid, const QBrush & text, const QBrush & bright_text, const QBrush & base, const QBrush & background )

Constructs a color group. You can pass either brushes, pixmaps or plain colors for foreground, button, light, dark, mid, text, bright_text, base and background.

See also QBrush.

QColorGroup::QColorGroup ( const QColorGroup & other )

Constructs a color group that is an independent copy of other.

QColorGroup::~QColorGroup ()

Destroys the color group.

const QColor & QColorGroup::background () const

Returns the background color of the color group.

See also ColorRole.

const QColor & QColorGroup::base () const

Returns the base color of the color group.

See also ColorRole.

const QColor & QColorGroup::brightText () const

Returns the bright text foreground color of the color group.

See also ColorRole.

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

const QBrush & QColorGroup::brush ( ColorRole r ) const

Returns the brush that has been set for color role r.

See also color(), setBrush() and ColorRole.

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

const QColor & QColorGroup::button () const

Returns the button color of the color group.

See also ColorRole.

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

const QColor & QColorGroup::buttonText () const

Returns the button text foreground color of the color group.

See also ColorRole.

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

const QColor & QColorGroup::color ( ColorRole r ) const

Returns the color that has been set for color role r.

See also brush() and ColorRole.

const QColor & QColorGroup::dark () const

Returns the dark color of the color group.

See also ColorRole.

Example: themes/wood.cpp.

const QColor & QColorGroup::foreground () const

Returns the foreground color of the color group.

See also ColorRole.

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

const QColor & QColorGroup::highlight () const

Returns the highlight color of the color group.

See also ColorRole.

const QColor & QColorGroup::highlightedText () const

Returns the highlighted text color of the color group.

See also ColorRole.

const QColor & QColorGroup::light () const

Returns the light color of the color group.

See also ColorRole.

Example: themes/wood.cpp.

const QColor & QColorGroup::link () const

Returns the unvisited link text color of the color group.

See also ColorRole.

const QColor & QColorGroup::linkVisited () const

Returns the visited link text color of the color group.

See also ColorRole.

const QColor & QColorGroup::mid () const

Returns the mid color of the color group.

See also ColorRole.

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

const QColor & QColorGroup::midlight () const

Returns the midlight color of the color group.

See also ColorRole.

bool QColorGroup::operator!= ( const QColorGroup & g ) const

Returns TRUE if this color group is different from g; otherwise returns FALSE.

See also

QColorGroup & QColorGroup::operator= ( const QColorGroup & other )

Copies the colors of other to this color group.

bool QColorGroup::operator== ( const QColorGroup & g ) const

Returns TRUE if this color group is equal to g; otherwise returns FALSE.

See also

void QColorGroup::setBrush ( ColorRole r, const QBrush & b )

Sets the brush used for color role r to b.

See also brush(), setColor() and ColorRole.

Example: themes/wood.cpp.

void QColorGroup::setColor ( ColorRole r, const QColor & c )

Sets the brush used for color role r to a solid color c.

See also brush() and ColorRole.

Examples: listviews/listviews.cpp, table/statistics/statistics.cpp and themes/metal.cpp.

const QColor & QColorGroup::shadow () const

Returns the shadow color of the color group.

See also ColorRole.

const QColor & QColorGroup::text () const

Returns the text foreground color of the color group.

See also ColorRole.

Example: listviews/listviews.cpp.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QColorGroup & g )

Writes color group, g to the stream s.

See also Format of the QDataStream operators.

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


QColorGroup Member List

Complete Member List for QColorGroup

This is the complete list of member functions for QColorGroup, including inherited members.

  • QColorGroup()
  • ~QColorGroup()
  • background()
  • base()
  • brightText()
  • brush()
  • button()
  • buttonText()
  • color()
  • dark()
  • foreground()
  • highlight()
  • highlightedText()
  • light()
  • link()
  • linkVisited()
  • mid()
  • midlight()
  • operator!=()
  • operator=()
  • operator==()
  • setBrush()
  • setColor()
  • shadow()
  • text()


QComboBox Class

QComboBox Class Reference

The QComboBox widget is a combined button and popup list. More...

#include <qcombobox.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QComboBox ( QWidget * parent = 0, const char * name = 0 )
  • QComboBox ( bool rw, QWidget * parent = 0, const char * name = 0 )
  • ~QComboBox ()
  • int count () const
  • void insertStringList ( const QStringList & list, int index = -1 )
  • void insertStrList ( const QStrList & list, int index = -1 )
  • void insertStrList ( const QStrList * list, int index = -1 )
  • void insertStrList ( const char ** strings, int numStrings = -1, int index = -1 )
  • void insertItem ( const QString & t, int index = -1 )
  • void insertItem ( const QPixmap & pixmap, int index = -1 )
  • void insertItem ( const QPixmap & pixmap, const QString & text, int index = -1 )
  • void removeItem ( int index )
  • int currentItem () const
  • virtual void setCurrentItem ( int index )
  • QString currentText () const
  • virtual void setCurrentText ( const QString & )
  • QString text ( int index ) const
  • const QPixmap * pixmap ( int index ) const
  • void changeItem ( const QString & t, int index )
  • void changeItem ( const QPixmap & im, int index )
  • void changeItem ( const QPixmap & im, const QString & t, int index )
  • bool autoResize () const (obsolete)
  • virtual void setAutoResize ( bool ) (obsolete)
  • virtual void setPalette ( const QPalette & palette )
  • virtual void setFont ( const QFont & font )
  • virtual void setSizeLimit ( int )
  • int sizeLimit () const
  • virtual void setMaxCount ( int )
  • int maxCount () const
  • enum Policy { NoInsertion, AtTop, AtCurrent, AtBottom, AfterCurrent, BeforeCurrent }
  • virtual void setInsertionPolicy ( Policy policy )
  • Policy insertionPolicy () const
  • virtual void setValidator ( const QValidator * v )
  • const QValidator * validator () const
  • virtual void setListBox ( QListBox * newListBox )
  • QListBox * listBox () const
  • virtual void setLineEdit ( QLineEdit * edit )
  • QLineEdit * lineEdit () const
  • virtual void setAutoCompletion ( bool )
  • bool autoCompletion () const
  • void setDuplicatesEnabled ( bool enable )
  • bool duplicatesEnabled () const
  • bool editable () const
  • void setEditable ( bool )
  • virtual void popup ()

Public Slots

  • void clear ()
  • void clearValidator ()
  • void clearEdit ()
  • virtual void setEditText ( const QString & newText )

Signals

  • void activated ( int index )
  • void highlighted ( int index )
  • void activated ( const QString & string )
  • void highlighted ( const QString & string )
  • void textChanged ( const QString & string )

Properties

  • bool autoCompletion - whether auto-completion is enabled
  • bool autoMask - whether the combobox is automatically masked (read only)
  • bool autoResize - whether auto resize is enabled (obsolete)
  • int count - the number of items in the combobox (read only)
  • int currentItem - the index of the current item in the combobox
  • QString currentText - the text of the combobox's current item
  • bool duplicatesEnabled - whether duplicates are allowed
  • bool editable - whether the combobox is editable
  • Policy insertionPolicy - the position of the items inserted by the user
  • int maxCount - the maximum number of items allowed in the combobox
  • int sizeLimit - the maximum on-screen size of the combobox

Detailed Description

The QComboBox widget is a combined button and popup list.

A combobox is a selection widget which displays the current item and can pop up a list of items. A combobox may be editable in which case the user can enter arbitrary strings.

Since comboboxes occupy little screen space and always display the current item, they are well suited to displaying items that the user will want to see, such as font family or size. Using a combobox the user can always see which item they've selected with the minimum amount of screen space being used.

QComboBox supports three different display styles: Aqua/Motif 1.x, Motif 2.0 and Windows 95. In Motif 1.x, a combobox was called XmOptionMenu. In Motif 2.0, OSF introduced an improved combobox and named that XmComboBox. QComboBox provides both.

QComboBox provides two different constructors. The simplest constructor creates an old-style combobox in Motif (or Aqua) style:

      QComboBox *c = new QComboBox( this, "read-only combobox" );

The other constructor creates a new-style combobox in Motif style, and can create both read-only and read-write comboboxes:

      QComboBox *c1 = new QComboBox( FALSE, this, "read-only combobox" );
      QComboBox *c2 = new QComboBox( TRUE, this, "read-write combobox" );

New-style comboboxes use a list box in both Motif and Windows styles, and both the content size and the on-screen size of the list box can be limited with sizeLimit() and setMaxCount() respectively. Old-style comboboxes use a popup in Aqua and Motif style, and that popup will happily grow larger than the desktop if you put enough data into it.

The two constructors create identical-looking comboboxes in Windows style.

Comboboxes can contain pixmaps as well as strings; the insertItem() and changeItem() functions are suitably overloaded. For read-write comboboxes, the function clearEdit() is provided, to clear the displayed string without changing the combobox's contents.

A combobox emits two signals, activated() and highlighted(), when a new item has been activated (selected) or highlighted (made current). Both signals exist in two versions, one with a QString argument and one with an int argument. If the user highlights or activates a pixmap, only the int signals are emitted. Whenever the text of an editable combobox is changed the textChanged() signal is emitted.

When the user enters a new string in a read-write combobox, the widget may or may not insert it, and it can insert it in several locations. The default policy is is AtBottom but you can change this using setInsertionPolicy().

It is possible to constrain the input to an editable combobox using QValidator; see setValidator(). By default, all input is accepted.

If the combo box is not editable then it has a default focusPolicy() of TabFocus, i.e. it will not grab focus if clicked. This differs from both Windows and Motif. If the combo box is editable then it has a default focusPolicy() of StrongFocus, i.e. it will grab focus if clicked.

A combobox can be populated using the insert functions, insertStringList() and insertItem() for example. Items can be changed with changeItem(). An item can be removed with removeItem() and all items can be removed with clear(). The text of the current item is returned by currentText(), and the text of a numbered item is returned with text(). The current item can be set with setCurrentItem() or setCurrentText(). The number of items in the combobox is returned by count(); the maximum number of items can be set with setMaxCount(). You can allow editing using setEditable(). For editable comboboxes you can set auto-completion using setAutoCompletion() and whether or not the user can add duplicates is set with setDuplicatesEnabled().

(Motif 1, read-only)
(Motif 2, read-write)
(Motif 2, read-only)
(Windows style)

See also QLineEdit, QListBox, QSpinBox, QRadioButton, QButtonGroup, GUI Design Handbook: Combo Box, GUI Design Handbook: Drop-Down List Box and Basic Widgets.

Member Type Documentation

QComboBox::Policy

This enum specifies what the QComboBox should do when a new string is entered by the user. The following policies are defined:

  • QComboBox::NoInsertion - the string will not be inserted into the combobox.
  • QComboBox::AtTop - insert the string as the first item in the combobox.
  • QComboBox::AtCurrent - replace the previously selected item with the string the user has entered.
  • QComboBox::AtBottom - insert the string as the last item in the combobox.
  • QComboBox::AfterCurrent - insert the string after the previously selected item.
  • QComboBox::BeforeCurrent - insert the string before the previously selected item.

activated() is always emitted when the string is entered.

If inserting the new string would cause the combobox to breach its content size limit, the item at the other end of the list is deleted. The definition of "other end" is implementation-dependent.

Member Function Documentation

QComboBox::QComboBox ( QWidget * parent = 0, const char * name = 0 )

Constructs a combobox widget with parent parent and name name.

This constructor creates a popup list if the program uses Motif (or Aqua) look and feel; this is compatible with Motif 1.x and Aqua.

QComboBox::QComboBox ( bool rw, QWidget * parent = 0, const char * name = 0 )

Constructs a combobox with a maximum size and either Motif 2.0 or Windows look and feel.

The input field can be edited if rw is TRUE, otherwise the user may only choose one of the items in the combobox.

The parent and name arguments are passed on to the QWidget constructor.

QComboBox::~QComboBox ()

Destroys the combobox.

void QComboBox::activated ( int index ) [signal]

This signal is emitted when a new item has been activated (selected). The index is the position of the item in the combobox.

Examples: fileiconview/mainwindow.cpp, helpviewer/helpwindow.cpp, lineedits/lineedits.cpp, listboxcombo/listboxcombo.cpp, network/ftpclient/ftpmainwindow.cpp and qmag/qmag.cpp.

void QComboBox::activated ( const QString & string ) [signal]

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

This signal is emitted when a new item has been activated (selected). string is the selected string.

You can also use the activated(int) signal, but be aware that its argument is meaningful only for selected strings, not for user entered strings.

bool QComboBox::autoCompletion () const

Returns TRUE if auto-completion is enabled; otherwise returns FALSE. See the "autoCompletion" property for details.

bool QComboBox::autoResize () const

Returns TRUE if auto resize is enabled; otherwise returns FALSE. See the "autoResize" property for details.

void QComboBox::changeItem ( const QString & t, int index )

Replaces the item at position index with the text t.

void QComboBox::changeItem ( const QPixmap & im, int index )

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

Replaces the item at position index with the pixmap im, unless the combobox is editable.

See also insertItem().

void QComboBox::changeItem ( const QPixmap & im, const QString & t, int index )

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

Replaces the item at position index with the pixmap im and the text t.

See also insertItem().

void QComboBox::clear () [slot]

Removes all combobox items.

void QComboBox::clearEdit () [slot]

Clears the line edit without changing the combobox's contents. Does nothing if the combobox isn't editable.

This is particularly handy when using a combobox as a line edit with history. For example you can connect the combobox's activated() signal to clearEdit() in order to present the user with a new, empty line as soon as Return is pressed.

See also setEditText().

void QComboBox::clearValidator () [slot]

This slot is equivalent to setValidator( 0 ).

int QComboBox::count () const

Returns the number of items in the combobox. See the "count" property for details.

int QComboBox::currentItem () const

Returns the index of the current item in the combobox. See the "currentItem" property for details.

QString QComboBox::currentText () const

Returns the text of the combobox's current item. See the "currentText" property for details.

bool QComboBox::duplicatesEnabled () const

Returns TRUE if duplicates are allowed; otherwise returns FALSE. See the "duplicatesEnabled" property for details.

bool QComboBox::editable () const

Returns TRUE if the combobox is editable; otherwise returns FALSE. See the "editable" property for details.

void QComboBox::highlighted ( int index ) [signal]

This signal is emitted when a new item has been set to current. The index is the position of the item in the combobox.

void QComboBox::highlighted ( const QString & string ) [signal]

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

This signal is emitted when a new item has been highlighted. string is the highlighted string.

You can also use highlighted(int) signal.

void QComboBox::insertItem ( const QString & t, int index = -1 )

Inserts a text item with text t, at position index. The item will be appended if index is negative.

Examples: chart/optionsform.cpp, fileiconview/mainwindow.cpp, helpviewer/helpwindow.cpp, lineedits/lineedits.cpp, listboxcombo/listboxcombo.cpp, network/ftpclient/ftpmainwindow.cpp and tictac/tictac.cpp.

void QComboBox::insertItem ( const QPixmap & pixmap, int index = -1 )

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

Inserts a pixmap item at position index. The item will be appended if index is negative.

void QComboBox::insertItem ( const QPixmap & pixmap, const QString & text, int index = -1 )

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

Inserts a pixmap item with additional text text at position index. The item will be appended if index is negative.

void QComboBox::insertStrList ( const char ** strings, int numStrings = -1, int index = -1 )

Inserts the array of char * strings at position index in the combobox.

The numStrings argument is the number of strings. If numStrings is -1 (default), the strings array must be terminated with 0.

Example:

    static const char* items[] = { "red", "green", "blue", 0 };
    combo->insertStrList( items );

Example: qmag/qmag.cpp.

void QComboBox::insertStrList ( const QStrList & list, int index = -1 )

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

Inserts the list of strings at position index in the combobox.

This is only for compatibility, as it does not support Unicode strings. See insertStringList().

void QComboBox::insertStrList ( const QStrList * list, int index = -1 )

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

Inserts the list of strings at position index in the combobox.

This is only for compatibility, as it does not support Unicode strings. See insertStringList().

void QComboBox::insertStringList ( const QStringList & list, int index = -1 )

Inserts the list of strings at position index in the combobox.

Policy QComboBox::insertionPolicy () const

Returns the position of the items inserted by the user. See the "insertionPolicy" property for details.

QLineEdit * QComboBox::lineEdit () const

Returns the line editor, or 0 if there is no line editor.

Only editable listboxes have a line editor.

QListBox * QComboBox::listBox () const

Returns the current list box, or 0 if there is no list box. (QComboBox can use QPopupMenu instead of QListBox.) Provided to match setListBox().

See also setListBox().

Example: listboxcombo/listboxcombo.cpp.

int QComboBox::maxCount () const

Returns the maximum number of items allowed in the combobox. See the "maxCount" property for details.

const QPixmap * QComboBox::pixmap ( int index ) const

Returns the pixmap item at position index, or 0 if the item is not a pixmap.

void QComboBox::popup () [virtual]

Pops up the combobox popup list.

If the list is empty, no items appear.

void QComboBox::removeItem ( int index )

Removes the item at position index.

void QComboBox::setAutoCompletion ( bool ) [virtual]

Sets whether auto-completion is enabled. See the "autoCompletion" property for details.

void QComboBox::setAutoResize ( bool ) [virtual]

Sets whether auto resize is enabled. See the "autoResize" property for details.

void QComboBox::setCurrentItem ( int index ) [virtual]

Sets the index of the current item in the combobox to index. See the "currentItem" property for details.

void QComboBox::setCurrentText ( const QString & ) [virtual]

Sets the text of the combobox's current item. See the "currentText" property for details.

void QComboBox::setDuplicatesEnabled ( bool enable )

Sets whether duplicates are allowed to enable. See the "duplicatesEnabled" property for details.

void QComboBox::setEditText ( const QString & newText ) [virtual slot]

Sets the text in the line edit to newText without changing the combobox's contents. Does nothing if the combobox isn't editable.

This is useful e.g. for providing a good starting point for the user's editing and entering the change in the combobox only when the user presses Enter.

See also clearEdit() and insertItem().

Example: network/ftpclient/ftpmainwindow.cpp.

void QComboBox::setEditable ( bool )

Sets whether the combobox is editable. See the "editable" property for details.

void QComboBox::setFont ( const QFont & font ) [virtual]

Reimplements QWidget::setFont().

Sets the font for both the combobox button and the combobox popup list to font.

Reimplemented from QWidget.

void QComboBox::setInsertionPolicy ( Policy policy ) [virtual]

Sets the position of the items inserted by the user to policy. See the "insertionPolicy" property for details.

void QComboBox::setLineEdit ( QLineEdit * edit ) [virtual]

Sets the lineedit to use edit instead of the current lineedit.

void QComboBox::setListBox ( QListBox * newListBox ) [virtual]

Sets the combobox to use newListBox instead of the current list box or popup. As a side effect, it clears the combobox of its current contents.

Warning: QComboBox assumes that newListBox->text(n) returns non-null for 0 <= n < newListbox->count(). This assumption is necessary because of the line edit in QComboBox.

void QComboBox::setMaxCount ( int ) [virtual]

Sets the maximum number of items allowed in the combobox. See the "maxCount" property for details.

void QComboBox::setPalette ( const QPalette & palette ) [virtual]

Reimplements QWidget::setPalette().

Sets the palette for both the combobox button and the combobox popup list to palette.

Reimplemented from QWidget.

void QComboBox::setSizeLimit ( int ) [virtual]

Sets the maximum on-screen size of the combobox. See the "sizeLimit" property for details.

void QComboBox::setValidator ( const QValidator * v ) [virtual]

Applies the validator v to the combobox so that only text which is valid according to v is accepted.

This function does nothing if the combo is not editable.

See also validator(), clearValidator() and QValidator.

int QComboBox::sizeLimit () const

Returns the maximum on-screen size of the combobox. See the "sizeLimit" property for details.

QString QComboBox::text ( int index ) const

Returns the text item at position index, or null string if the item is not a string.

See also currentText.

Examples: fileiconview/mainwindow.cpp and helpviewer/helpwindow.cpp.

void QComboBox::textChanged ( const QString & string ) [signal]

This signal is used for editable comboboxes. It is emitted whenever the contents of the text entry field changes. string contains the new text.

const QValidator * QComboBox::validator () const

Returns the validator which constrains editing for this combobox if there is one, otherwise returns 0.

See also setValidator(), clearValidator() and QValidator.

Property Documentation

bool autoCompletion

This property holds whether auto-completion is enabled.

This property can only be set for editable comboboxes, for non-editable comboboxes it has no effect. It is FALSE by default.

Set this property's value with setAutoCompletion() and get this property's value with autoCompletion().

bool autoMask

This property holds whether the combobox is automatically masked.

See also QWidget::autoMask.

bool autoResize

This property holds whether auto resize is enabled.

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

If this property is set to TRUE then the combobox will resize itself whenever its contents change. The default is FALSE.

Set this property's value with setAutoResize() and get this property's value with autoResize().

int count

This property holds the number of items in the combobox.

Get this property's value with count().

int currentItem

This property holds the index of the current item in the combobox.

Set this property's value with setCurrentItem() and get this property's value with currentItem().

QString currentText

This property holds the text of the combobox's current item.

Set this property's value with setCurrentText() and get this property's value with currentText().

bool duplicatesEnabled

This property holds whether duplicates are allowed.

If the combobox is editable and the user enters some text in the lineedit of the combobox and presses Enter (and the insertionPolicy() is different from NoInsertion), then what happens is as follows:

  • If the text is not already in the list, the text is inserted.
  • If the text is in the list and this property is TRUE (the default), the text is inserted.
  • If the text is in the list and this property is FALSE, the text is not inserted; instead the item which has matching text becomes the current item.

This property only affects user-interaction. You can use insertItem() to insert duplicates if you wish regardless of this setting.

Set this property's value with setDuplicatesEnabled() and get this property's value with duplicatesEnabled().

bool editable

This property holds whether the combobox is editable.

This property's default is FALSE. Note that the combobox will be cleared if this property is set to TRUE for a 1.x Motif style combobox. To avoid this, use setEditable() before inserting any items. Also note that the 1.x version of Motif didn't have any editable comboboxes, so the combobox will change it's appearance to a 2.0 style Motif combobox is it is set to be editable.

Set this property's value with setEditable() and get this property's value with editable().

Policy insertionPolicy

This property holds the position of the items inserted by the user.

The default insertion policy is AtBottom.

Set this property's value with setInsertionPolicy() and get this property's value with insertionPolicy().

int maxCount

This property holds the maximum number of items allowed in the combobox.

Set this property's value with setMaxCount() and get this property's value with maxCount().

int sizeLimit

This property holds the maximum on-screen size of the combobox.

This is disregarded in Motif 1.x style. The default limit is ten lines. If the number of items in the combobox is or grows larger than lines, a scrollbar is added.

Set this property's value with setSizeLimit() and get this property's value with sizeLimit().

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


qcombobox.h Include File

qcombobox.h

This is the verbatim text of the qcombobox.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qcombobox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QComboBox class
**
** Created : 950426
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCOMBOBOX_H
#define QCOMBOBOX_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_COMBOBOX

class QStrList;
class QStringList;
class QLineEdit;
class QValidator;
class QListBox;
class QComboBoxData;

class Q_EXPORT QComboBox : public QWidget
{
    Q_OBJECT
    Q_ENUMS( Policy )
    Q_PROPERTY( bool editable READ editable WRITE setEditable )
    Q_PROPERTY( int count READ count )
    Q_PROPERTY( QString currentText READ currentText WRITE setCurrentText DESIGNABLE false )
    Q_PROPERTY( int currentItem READ currentItem WRITE setCurrentItem )
    Q_PROPERTY( bool autoResize READ autoResize WRITE setAutoResize DESIGNABLE false )
    Q_PROPERTY( int sizeLimit READ sizeLimit WRITE setSizeLimit )
    Q_PROPERTY( int maxCount READ maxCount WRITE setMaxCount )
    Q_PROPERTY( Policy insertionPolicy READ insertionPolicy WRITE setInsertionPolicy )
    Q_PROPERTY( bool autoCompletion READ autoCompletion WRITE setAutoCompletion )
    Q_PROPERTY( bool duplicatesEnabled READ duplicatesEnabled WRITE setDuplicatesEnabled )
    Q_OVERRIDE( bool autoMask DESIGNABLE true SCRIPTABLE true )

public:
    QComboBox( QWidget* parent=0, const char* name=0 );
    QComboBox( bool rw, QWidget* parent=0, const char* name=0 );
    ~QComboBox();

    int		count() const;

    void	insertStringList( const QStringList &, int index=-1 );
    void	insertStrList( const QStrList &, int index=-1 );
    void	insertStrList( const QStrList *, int index=-1 );
    void	insertStrList( const char **, int numStrings=-1, int index=-1);

    void	insertItem( const QString &text, int index=-1 );
    void	insertItem( const QPixmap &pixmap, int index=-1 );
    void	insertItem( const QPixmap &pixmap, const QString &text, int index=-1 );

    void	removeItem( int index );

    int		currentItem() const;
    virtual void setCurrentItem( int index );

    QString 	currentText() const;
    virtual void setCurrentText( const QString& );

    QString 	text( int index ) const;
    const QPixmap *pixmap( int index ) const;

    void	changeItem( const QString &text, int index );
    void	changeItem( const QPixmap &pixmap, int index );
    void	changeItem( const QPixmap &pixmap, const QString &text, int index );

    bool	autoResize()	const;
    virtual void setAutoResize( bool );
    QSize	sizeHint() const;

    void	setPalette( const QPalette & );
    void	setFont( const QFont & );
    void	setEnabled( bool );

    virtual void setSizeLimit( int );
    int		sizeLimit() const;

    virtual void setMaxCount( int );
    int		maxCount() const;

    enum Policy { NoInsertion, AtTop, AtCurrent, AtBottom,
          AfterCurrent, BeforeCurrent };

    virtual void setInsertionPolicy( Policy policy );
    Policy	insertionPolicy() const;

    virtual void setValidator( const QValidator * );
    const QValidator * validator() const;

    virtual void setListBox( QListBox * );
    QListBox *	listBox() const;

    virtual void setLineEdit( QLineEdit *edit );
    QLineEdit*	lineEdit() const;

    virtual void setAutoCompletion( bool );
    bool	autoCompletion() const;

    bool	eventFilter( QObject *object, QEvent *event );

    void	setDuplicatesEnabled( bool enable );
    bool	duplicatesEnabled() const;

    bool	editable() const;
    void	setEditable( bool );

    virtual void popup();

public slots:
    void	clear();
    void	clearValidator();
    void	clearEdit();
    virtual void setEditText( const QString &);

signals:
    void	activated( int index );
    void	highlighted( int index );
    void	activated( const QString &);
    void	highlighted( const QString &);
    void	textChanged( const QString &);

private slots:
    void	internalActivate( int );
    void	internalHighlight( int );
    void	internalClickTimeout();
    void	returnPressed();

protected:
    void	paintEvent( QPaintEvent * );
    void	resizeEvent( QResizeEvent * );
    void	mousePressEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseDoubleClickEvent( QMouseEvent * );
    void	keyPressEvent( QKeyEvent *e );
    void	focusInEvent( QFocusEvent *e );
    void	styleChange( QStyle& );

    void	updateMask();

private:
    void	setUpListBox();
    void	setUpLineEdit();
    void	popDownListBox();
    void	reIndex();
    void	currentChanged();
    int		completionIndex( const QString &, int ) const;

    QComboBoxData	*d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QComboBox( const QComboBox & );
    QComboBox &operator=( const QComboBox & );
#endif
};

#endif // QT_NO_COMBOBOX

#endif // QCOMBOBOX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QComboBox Member List

Complete Member List for QComboBox

This is the complete list of member functions for QComboBox, including inherited members.

  • QComboBox()
  • ~QComboBox()
  • acceptDrops()
  • activated()
  • adjustSize()
  • autoCompletion()
  • autoMask()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • changeItem()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearEdit()
  • clearFocus()
  • clearMask()
  • clearValidator()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • count()
  • create()
  • currentItem()
  • currentText()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • duplicatesEnabled()
  • editable()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • highlighted()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insertItem()
  • insertStrList()
  • insertStringList()
  • insertionPolicy()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineEdit()
  • listBox()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maxCount()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • popup()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeItem()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoCompletion()
  • setAutoMask()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCurrentItem()
  • setCurrentText()
  • setCursor()
  • setDisabled()
  • setDuplicatesEnabled()
  • setEditText()
  • setEditable()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsertionPolicy()
  • setKeyCompression()
  • setLineEdit()
  • setListBox()
  • setMask()
  • setMaxCount()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizeLimit()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setValidator()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizeLimit()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • validator()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QComboTableItem类

QComboTableItem类参考
[表格模块]

QComboTableItem类提供了QTable中使用组合框的一种方式。 详见……

#include <qtable.h>

继承了QTableItem。

所有成员函数的列表。

公共成员

  • QComboTableItem ( QTable * table, const QStringList & list, bool editable = FALSE )
  • virtual void setCurrentItem ( int i )
  • virtual void setCurrentItem ( const QString & s )
  • int currentItem () const
  • QString currentText () const
  • int count () const
  • QString text ( int i ) const
  • virtual void setEditable ( bool b )
  • bool isEditable () const
  • virtual void setStringList ( const QStringList & l )
  • virtual int rtti () const

详细描述

QComboTableItem类提供了QTable中使用组合框的一种方式。

一个QComboTableItem是一个表项，其外观和行为如同组合框。使用QComboTableItem而不是真实的组合框的好处在于，在QTable中QComboTableItem要比真实的多选框节省很多资源。当单元格具有焦点时，QComboTableItem显示一个与用户交互的真实组合框。当单元格没有焦点时，单元格看起来像是一个组合框。只有文本表项（就是说没有象素映射）能用于QComboTableItem。

QComboTableItem表项具有编辑类型WhenCurrent（参见EditType）。QComboTableItem的条目列表由传递给构造器的QStringList提供。

条目列表可以使用setStringList()来改变。用setCurrentItem()设置当前条目，用currentItem()来得到当前条目。当前条目的文本用currentText()获得，具体某个条目的文本用text()获得。

如果isEditable()未TRUE，QComboTableItem允许用户要么选择一个已存在的条目，要么输入自己的文本以生成新的条目；否则，用户只能选择一个已有的条目。

使用QTable::setItem以把QComboTableItem填充进一个表格单元格。

QComboTableItems may be deleted with QTable::clearCell()。

使用运行时类型判别（参见rtti()）值，可以辨别QComboTableItem与QTableItem和QCheckTableItem。

也参见QCheckTableItem、QTableItem和高级部件。

成员函数文档

QComboTableItem::QComboTableItem ( QTable * table, const QStringList & list, bool editable = FALSE )

为表格table生成一个组合表项。组合框的条目列表在参数list中传入。如果editable为TRUE，用户可以输入新的条目；如果editable为FALSE，用户只能从提供的条目中选择。

由于isReplaceable()缺省返回FALSE，缺省情况下QComboTableItem不能被其他表项替换。

也参见QTable::clearCell()和EditType。

int QComboTableItem::count () const

返回组合表项中的条目列表总数。

int QComboTableItem::currentItem () const

返回组合表项的当前条目的索引。

也参见setCurrentItem()。

QString QComboTableItem::currentText () const

返回组合表项的当前条目的文本。

也参见currentItem()和text()。

bool QComboTableItem::isEditable () const

返回用户是否可以向组合列表中添加自己的条目。

也参见setEditable()。

int QComboTableItem::rtti () const [virtual]

对于QComboTableItem本函数返回的运行时类型判别值为1。

也参见QTableItem::rtti()。

由QTableItem处重新实现。

void QComboTableItem::setCurrentItem ( int i ) [virtual]

把条目i设置为组合表项的当前条目。

也参见currentItem()。

例子：table/small-table-demo/main.cpp。

void QComboTableItem::setCurrentItem ( const QString & s ) [virtual]

这是重载的成员函数，为便利原因提供。本质上类似上一个函数。

把文本为s的条目设置为组合表项的当前条目。如果没有这样的条目，什么也不做。

也参见currentItem()。

void QComboTableItem::setEditable ( bool b ) [virtual]

如果b为TRUE，组合表项可以被编辑，也就是说，用户可以自己输入新的文本条目。如果b为FALSE，用户只能在已有条目中选择。

也参见isEditable()。

void QComboTableItem::setStringList ( const QStringList & l ) [virtual]

把本QComboTableItem的条目列表设置为字符串列表l中的字符串。

QString QComboTableItem::text ( int i ) const

返回组合表项中索引为i的条目的文本。

也参见currentText()。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QComboTableItem成员列表

完整的QComboTableItem成员列表

这里是QComboTableItem成员函数的完整列表，包括继承的成员。

  • QComboTableItem()
  • alignment()
  • col()
  • colSpan()
  • count()
  • createEditor()
  • currentItem()
  • currentText()
  • editType()
  • isEditable()
  • isEnabled()
  • isReplaceable()
  • key()
  • paint()
  • pixmap()
  • row()
  • rowSpan()
  • rtti()
  • setCol()
  • setContentFromEditor()
  • setCurrentItem()
  • setEditable()
  • setEnabled()
  • setPixmap()
  • setReplaceable()
  • setRow()
  • setSpan()
  • setStringList()
  • setText()
  • setWordWrap()
  • sizeHint()
  • table()
  • text()
  • wordWrap()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QCommonStyle Class

QCommonStyle Class Reference

The QCommonStyle class encapsulates the common Look and Feel of a GUI. More...

#include <qcommonstyle.h>

Inherits QStyle.

Inherited by QMotifStyle and QWindowsStyle.

List of all member functions.

Public Members

  • QCommonStyle ()

Detailed Description

The QCommonStyle class encapsulates the common Look and Feel of a GUI.

This abstract class implements some of the widget's look and feel that is common to all GUI styles provided and shipped as part of Qt.

All the functions are documented in QStyle.

See also Widget Appearance and Style.

Member Function Documentation

QCommonStyle::QCommonStyle ()

Constructs a QCommonStyle.

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


qcommonstyle.h Include File

qcommonstyle.h

This is the verbatim text of the qcommonstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qcommonstyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QCommonStyle class
**
** Created : 980616
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCOMMONSTYLE_H
#define QCOMMONSTYLE_H

#ifndef QT_H
#include "qstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE

class Q_EXPORT QCommonStyle: public QStyle
{
    Q_OBJECT

public:
    QCommonStyle();
    ~QCommonStyle();

    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawControlMask( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QStyleOption& = QStyleOption::Default ) const;

    QRect subRect( SubRect r, const QWidget *widget ) const;

    void drawComplexControl( ComplexControl control,
                 QPainter *p,
                 const QWidget *widget,
                 const QRect &r,
                 const QColorGroup &cg,
                 SFlags how = Style_Default,
                 SCFlags sub = SC_All,
                 SCFlags subActive = SC_None,
                 const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControlMask( ComplexControl control,
                 QPainter *p,
                 const QWidget *widget,
                 const QRect &r,
                 const QStyleOption& = QStyleOption::Default ) const;

    QRect querySubControlMetrics( ComplexControl control,
                  const QWidget *widget,
                  SubControl sc,
                  const QStyleOption& = QStyleOption::Default ) const;

    SubControl querySubControl( ComplexControl control,
                const QWidget *widget,
                const QPoint &pos,
                const QStyleOption& = QStyleOption::Default ) const;

    int pixelMetric( PixelMetric m, const QWidget *widget = 0 ) const;

    QSize sizeFromContents( ContentsType s,
                const QWidget *widget,
                const QSize &contentsSize,
                const QStyleOption& = QStyleOption::Default ) const;

    int styleHint(StyleHint sh, const QWidget *, const QStyleOption &, QStyleHintReturn *) const;

    QPixmap stylePixmap( StylePixmap sp,
             const QWidget *widget = 0,
             const QStyleOption& = QStyleOption::Default ) const;

private:
    // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QCommonStyle( const QCommonStyle & );
    QCommonStyle &operator=( const QCommonStyle & );
#endif
};

#endif // QT_NO_STYLE

#endif // QCOMMONSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCommonStyle Member List

Complete Member List for QCommonStyle

This is the complete list of member functions for QCommonStyle, including inherited members.

  • QCommonStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • visualRect()


QConstString Class

QConstString Class Reference

The QConstString class provides string objects using constant Unicode data. More...

#include <qstring.h>

List of all member functions.

Public Members

  • QConstString ( const QChar * unicode, uint length )
  • ~QConstString ()
  • const QString & string () const

Detailed Description

The QConstString class provides string objects using constant Unicode data.

In order to minimize copying, highly optimized applications can use QConstString to provide a QString-compatible object from existing Unicode data. It is then the programmer's responsibility to ensure that the Unicode data exists for the entire lifetime of the QConstString object.

A QConstString is created with the QConstString constructor. The string held by the object can be obtained by calling string().

See also Text Related Classes.

Member Function Documentation

QConstString::QConstString ( const QChar * unicode, uint length )

Constructs a QConstString that uses the first length Unicode characters in the array unicode. Any attempt to modify copies of the string will cause it to create a copy of the data, thus it remains forever unmodified.

The data in unicode is not copied. The caller must be able to guarantee that unicode will not be deleted or modified.

QConstString::~QConstString ()

Destroys the QConstString, creating a copy of the data if other strings are still using it.

const QString & QConstString::string () const

Returns a constant string referencing the data passed during construction.

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


QConstString Member List

Complete Member List for QConstString

This is the complete list of member functions for QConstString, including inherited members.

  • QConstString()
  • ~QConstString()
  • string()


QContextMenuEvent Class

QContextMenuEvent Class Reference

The QContextMenuEvent class contains parameters that describe a context menu event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • enum Reason { Mouse, Keyboard, Other }
  • QContextMenuEvent ( Reason reason, const QPoint & pos, const QPoint & globalPos, int state )
  • QContextMenuEvent ( Reason reason, const QPoint & pos, int state )
  • int x () const
  • int y () const
  • int globalX () const
  • int globalY () const
  • const QPoint & pos () const
  • const QPoint & globalPos () const
  • ButtonState state () const
  • bool isAccepted () const
  • bool isConsumed () const
  • void consume ()
  • void accept ()
  • void ignore ()
  • Reason reason () const

Detailed Description

The QContextMenuEvent class contains parameters that describe a context menu event.

Context menu events are sent to widgets when a user triggers a context menu. What triggers this is platform dependent. For example, on Windows, pressing the menu button or releasing the right mouse button will cause this event to be sent.

When this event occurs it is customary to show a QPopupMenu with a context menu, if this is relevant to the context.

Context menu events contain a special accept flag that indicates whether the receiver accepted the event. If the event handler does not accept the event, then whatever triggered the event will be handled as a regular input event if possible.

See also QPopupMenu and Event Classes.

Member Type Documentation

QContextMenuEvent::Reason

This enum describes the reason the ContextMenuEvent was sent. The values are:

  • QContextMenuEvent::Mouse - The mouse caused the event to be sent. Normally this means the right mouse button was clicked, but this is platform specific.
  • QContextMenuEvent::Keyboard - The keyboard caused this event to be sent. On Windows this means the menu button was pressed.
  • QContextMenuEvent::Other - The event was sent by some other means (i.e. not by the mouse or keyboard).

Member Function Documentation

QContextMenuEvent::QContextMenuEvent ( Reason reason, const QPoint & pos, const QPoint & globalPos, int state )

Constructs a context menu event object with the accept parameter flag set to FALSE.

The reason parameter must be QContextMenuEvent::Mouse or QContextMenuEvent::Keyboard.

The pos parameter specifies the mouse position relative to the receiving widget. globalPos is the mouse position in absolute coordinates. state is the ButtonState at the time of the event.

QContextMenuEvent::QContextMenuEvent ( Reason reason, const QPoint & pos, int state )

Constructs a context menu event object with the accept parameter flag set to FALSE.

The reason parameter must be QContextMenuEvent::Mouse or QContextMenuEvent::Keyboard.

The pos parameter specifies the mouse position relative to the receiving widget. state is the ButtonState at the time of the event.

The globalPos() is initialized to QCursor::pos(), which may not be appropriate. Use the other constructor to specify the global position explicitly.

void QContextMenuEvent::accept ()

Sets the accept flag of the context event object.

Setting the accept flag indicates that the receiver of this event has processed the event. Processing the event means you did something with it and it will be implicitly consumed.

The accept flag is not set by default.

See also ignore() and consume().

void QContextMenuEvent::consume ()

Sets the consume flag of the context event object.

Setting the consume flag indicates that the receiver of this event does not want the event to be propagated further (i.e. not sent to parent classes.)

The consumed flag is not set by default.

See also ignore() and accept().

const QPoint & QContextMenuEvent::globalPos () const

Returns the global position of the mouse pointer at the time of the event.

See also x(), y() and pos().

int QContextMenuEvent::globalX () const

Returns the global x-position of the mouse pointer at the time of the event.

See also globalY() and globalPos().

int QContextMenuEvent::globalY () const

Returns the global y-position of the mouse pointer at the time of the event.

See also globalX() and globalPos().

void QContextMenuEvent::ignore ()

Clears the accept flag of the context event object.

Clearing the accept flag indicates that the receiver of this event does not need to show a context menu. This will implicitly remove the consumed flag as well.

The accept flag is not set by default.

See also accept() and consume().

bool QContextMenuEvent::isAccepted () const

Returns TRUE if the receiver has processed the event; otherwise returns FALSE.

See also accept(), ignore() and consume().

bool QContextMenuEvent::isConsumed () const

Returns TRUE (which stops propagation of the event) if the receiver has blocked the event; otherwise returns FALSE.

See also accept(), ignore() and consume().

const QPoint & QContextMenuEvent::pos () const

Returns the position of the mouse pointer relative to the widget that received the event.

See also x(), y() and globalPos().

Reason QContextMenuEvent::reason () const

Returns the reason for this context event.

ButtonState QContextMenuEvent::state () const

Returns the button state (a combination of mouse buttons and keyboard modifiers), i.e. what buttons and keys were being pressed immediately before the event was generated.

The returned value is LeftButton, RightButton, MidButton, ShiftButton, ControlButton and AltButton OR'ed together.

int QContextMenuEvent::x () const

Returns the x-position of the mouse pointer, relative to the widget that received the event.

See also y() and pos().

int QContextMenuEvent::y () const

Returns the y-position of the mouse pointer, relative to the widget that received the event.

See also x() and pos().

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


QContextMenuEvent Member List

Complete Member List for QContextMenuEvent

This is the complete list of member functions for QContextMenuEvent, including inherited members.

  • QContextMenuEvent()
  • accept()
  • consume()
  • globalPos()
  • globalX()
  • globalY()
  • ignore()
  • isAccepted()
  • isConsumed()
  • pos()
  • reason()
  • spontaneous()
  • state()
  • type()
  • x()
  • y()


QCopChannel Class

QCopChannel Class Reference

The QCopChannel class provides communication capabilities between several clients. More...

#include <qcopchannel_qws.h>

Inherits QObject.

List of all member functions.

Public Members

  • QCopChannel ( const QCString & channel, QObject * parent = 0, const char * name = 0 )
  • virtual ~QCopChannel ()
  • QCString channel () const
  • virtual void receive ( const QCString & msg, const QByteArray & data )

Signals

  • void received ( const QCString & msg, const QByteArray & data )

Static Public Members

  • bool isRegistered ( const QCString & channel )
  • bool send ( const QCString & channel, const QCString & msg )
  • bool send ( const QCString & channel, const QCString & msg, const QByteArray & data )

Detailed Description

The QCopChannel class provides communication capabilities between several clients.

The Qt Cop (QCOP) is a COmmunication Protocol, allowing clients to communicate both within the same address space and between different processes.

Currently, this facility is only available on Qt/Embedded. On X11 and Windows we are exploring the use of existing standards such as DCOP and COM.

QCopChannel provides send() and isRegistered() which are static functions usable without an object.

The channel() function returns the name of the channel.

In order to listen to the traffic on a channel, you should either subclass QCopChannel and reimplement receive(), or connect() to the received() signal.

Member Function Documentation

QCopChannel::QCopChannel ( const QCString & channel, QObject * parent = 0, const char * name = 0 )

Constructs a QCop channel and registers it with the server using the name channel. The standard parent and name arguments are passed on to the QObject constructor.

QCopChannel::~QCopChannel () [virtual]

Destroys the client's end of the channel and notifies the server that the client has closed its connection. The server will keep the channel open until the last registered client detaches.

QCString QCopChannel::channel () const

Returns the name of the channel.

bool QCopChannel::isRegistered ( const QCString & channel ) [static]

Queries the server for the existence of channel.

Returns TRUE if channel is registered; otherwise returns FALSE.

void QCopChannel::receive ( const QCString & msg, const QByteArray & data ) [virtual]

This virtual function allows subclasses of QCopChannel to process data received from their channel.

The default implementation emits the received() signal.

Note that the format of data has to be well defined in order to extract the information it contains.

Example:

    void MyClass::receive( const QCString &msg, const QByteArray &data )
    {
        QDataStream stream( data, IO_ReadOnly );
        if ( msg == "execute(QString,QString)" ) {
            QString cmd, arg;
            stream >> cmd >> arg;
            ...
        } else if ( msg == "delete(QString)" ) {
            QString filenname;
            stream >> filename;
            ...
        } else ...
    }
This example assumes that the msg is a DCOP-style function signature and the data contains the function's arguments. (See send().)

Using the DCOP convention is a recommendation, but not a requirement. Whatever convention you use the sender and receiver must agree on the argument types.

See also send().

void QCopChannel::received ( const QCString & msg, const QByteArray & data ) [signal]

This signal is emitted with the msg and data whenever the receive() function gets incoming data.

bool QCopChannel::send ( const QCString & channel, const QCString & msg, const QByteArray & data ) [static]

Send the message msg on channel channel with data data. The message will be distributed to all clients subscribed to the channel.

Note that QDataStream provides a convenient way to fill the byte array with auxiliary data.

Example:

    QByteArray ba;
    QDataStream stream( ba, IO_WriteOnly );
    stream << QString("cat") << QString("file.txt");
    QCopChannel::send( "System/Shell", "execute(QString,QString)", ba );
Here the channel is "System/Shell". The msg is an arbitrary string, but in the example we've used the DCOP convention of passing a function signature. Such a signature is formatted as functionname(types) where types is a list of zero or more comma-separated type names, with no whitespace, no consts and no pointer or reference marks, i.e. no "*" or "&".

Using the DCOP convention is a recommendation, but not a requirement. Whatever convention you use the sender and receiver must agree on the argument types.

See also receive().

bool QCopChannel::send ( const QCString & channel, const QCString & msg ) [static]

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

Send the message msg on channel channel. The message will be distributed to all clients subscribed to the channel.

See also receive().

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


QCopChannel Member List

Complete Member List for QCopChannel

This is the complete list of member functions for QCopChannel, including inherited members.

  • QCopChannel()
  • ~QCopChannel()
  • blockSignals()
  • channel()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isRegistered()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • receive()
  • received()
  • removeChild()
  • removeEventFilter()
  • send()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


qcopchannel_qws.h Include File

qcopchannel_qws.h

This is the verbatim text of the qcopchannel_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qcopchannel_qws.h   3.0.5   edited Oct 31 2001 $
**
** QCOP protocol classes
**
** Created : 20000616
**
** Copyright (C) 2000-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCOP_H
#define QCOP_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_COP

class QWSClient;
class QCopChannelPrivate;

class QCopChannel : public QObject
{
    Q_OBJECT
public:
    QCopChannel( const QCString& channel, QObject* parent=0, const char* name=0 );
    virtual ~QCopChannel();

    QCString channel() const;

    static bool isRegistered( const QCString& channel );
    static bool send( const QCString &channel, const QCString &msg );
    static bool send( const QCString &channel, const QCString &msg,
              const QByteArray &data );

    static void sendLocally(  const QCString &ch, const QCString &msg,
                   const QByteArray &data );

    virtual void receive( const QCString &msg, const QByteArray &data );

signals:
    void received( const QCString &msg, const QByteArray &data );

private:
    // server side
    static void registerChannel( const QString &ch, const QWSClient *cl );
    static void detach( const QWSClient *cl );
    static void answer( QWSClient *cl, const QCString &ch,
            const QCString &msg, const QByteArray &data );
    // client side
    QCopChannelPrivate* d;

    friend class QWSServer;
    friend class QApplication;
};

#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCString类

QCString类参考

QCString类提供了一个经典C语言的以零结尾的字符数组（char *）的抽象。 详情请见……

#include <qcstring.h>

继承了QByteArray。

所有成员函数的列表。

公有成员

  • QCString ()
  • QCString ( int size )
  • QCString ( const QCString & s )
  • QCString ( const char * str )
  • QCString ( const char * str, uint maxsize )
  • QCString & operator= ( const QCString & s )
  • QCString & operator= ( const char * str )
  • bool isNull () const
  • bool isEmpty () const
  • uint length () const
  • bool resize ( uint len )
  • bool truncate ( uint pos )
  • bool fill ( char c, int len = -1 )
  • QCString copy () const
  • QCString & sprintf ( const char * format, ... )
  • int find ( char c, int index = 0, bool cs = TRUE ) const
  • int find ( const char * str, int index = 0, bool cs = TRUE ) const
  • int find ( const QRegExp & rx, int index = 0 ) const
  • int findRev ( char c, int index = -1, bool cs = TRUE ) const
  • int findRev ( const char * str, int index = -1, bool cs = TRUE ) const
  • int findRev ( const QRegExp & rx, int index = -1 ) const
  • int contains ( char c, bool cs = TRUE ) const
  • int contains ( const char * str, bool cs = TRUE ) const
  • int contains ( const QRegExp & rx ) const
  • QCString left ( uint len ) const
  • QCString right ( uint len ) const
  • QCString mid ( uint index, uint len = 0xffffffff ) const
  • QCString leftJustify ( uint width, char fill = ' ', bool truncate = FALSE ) const
  • QCString rightJustify ( uint width, char fill = ' ', bool truncate = FALSE ) const
  • QCString lower () const
  • QCString upper () const
  • QCString stripWhiteSpace () const
  • QCString simplifyWhiteSpace () const
  • QCString & insert ( uint index, const char * s )
  • QCString & insert ( uint index, char c )
  • QCString & append ( const char * str )
  • QCString & prepend ( const char * s )
  • QCString & remove ( uint index, uint len )
  • QCString & replace ( uint index, uint len, const char * str )
  • QCString & replace ( const QRegExp & rx, const char * str )
  • short toShort ( bool * ok = 0 ) const
  • ushort toUShort ( bool * ok = 0 ) const
  • int toInt ( bool * ok = 0 ) const
  • uint toUInt ( bool * ok = 0 ) const
  • long toLong ( bool * ok = 0 ) const
  • ulong toULong ( bool * ok = 0 ) const
  • float toFloat ( bool * ok = 0 ) const
  • double toDouble ( bool * ok = 0 ) const
  • QCString & setStr ( const char * str )
  • QCString & setNum ( short n )
  • QCString & setNum ( ushort n )
  • QCString & setNum ( int n )
  • QCString & setNum ( uint n )
  • QCString & setNum ( long n )
  • QCString & setNum ( ulong n )
  • QCString & setNum ( float n, char f = 'g', int prec = 6 )
  • QCString & setNum ( double n, char f = 'g', int prec = 6 )
  • bool setExpand ( uint index, char c )
  • operator const char * () const
  • QCString & operator+= ( const char * str )
  • QCString & operator+= ( char c )

相关函数

  • void * qmemmove ( void * dst, const void * src, uint len )
  • char * qstrdup ( const char * src )
  • char * qstrcpy ( char * dst, const char * src )
  • char * qstrncpy ( char * dst, const char * src, uint len )
  • int qstrcmp ( const char * str1, const char * str2 )
  • int qstrncmp ( const char * str1, const char * str2, uint len )
  • int qstricmp ( const char * str1, const char * str2 )
  • int qstrnicmp ( const char * str1, const char * str2, uint len )
  • QDataStream & operator<< ( QDataStream & s, const QCString & str )
  • QDataStream & operator>> ( QDataStream & s, QCString & str )
  • bool operator== ( const QCString & s1, const QCString & s2 )
  • bool operator== ( const QCString & s1, const char * s2 )
  • bool operator== ( const char * s1, const QCString & s2 )
  • bool operator!= ( const QCString & s1, const QCString & s2 )
  • bool operator!= ( const QCString & s1, const char * s2 )
  • bool operator!= ( const char * s1, const QCString & s2 )
  • bool operator< ( const QCString & s1, const char * s2 )
  • bool operator< ( const char * s1, const QCString & s2 )
  • bool operator<= ( const QCString & s1, const char * s2 )
  • bool operator<= ( const char * s1, const QCString & s2 )
  • bool operator> ( const QCString & s1, const char * s2 )
  • bool operator> ( const char * s1, const QCString & s2 )
  • bool operator>= ( const QCString & s1, const char * s2 )
  • bool operator>= ( const char * s1, const QCString & s2 )
  • const QCString operator+ ( const QCString & s1, const QCString & s2 )
  • const QCString operator+ ( const QCString & s1, const char * s2 )
  • const QCString operator+ ( const char * s1, const QCString & s2 )
  • const QCString operator+ ( const QCString & s, char c )
  • const QCString operator+ ( char c, const QCString & s )

详细描述

QCString类提供了一个经典C语言的以零结尾的字符数组（char *）的抽象。

QCString继承了QByteArray，后者是被QMemArray<char>这样定义的。

因为QCString是一个QMemArray，它使用了带引用计数的明显共享。

你可以在从不暴露给用户的文本中使用QCString。对于用户可见的文本，你应该使用QString（它提供隐含共享、Unicode和其它国际化支持。

注意QCString是Qt中比较薄弱的类，它的设计是有缺陷的（它试图在行为上变为更方便的const char *）并且作为结果，QCString使用的所有算法经常执行得很差。例如，因为append()扫描一个零结束符，所以它是O(length())，这也严重地影响着很多使用QCString的算法。

注意对于使用const char *参数的QCString的方法，如果QCString不是以零结尾的，结果是不确定的。const char *参数为0是合法的。

没有分配任何事物的QCString是零，也就是长度和数据指针都是0。一个引用空字符串（“”，单一的'\0'字符）的QCString是空。在方法中，零和空QCString都是合法参数。把const char * 0分配给QCString就给定了一个零QCString。

length()函数返回字符串的长度，resize()重新定义字符串的大小并且truncate()截短字符串。字符串可以使用fill()来用一个字符填充。使用leftJustify()和rightJustify()在字符串的左面或者右面填补字符。使用find()和findRev()可以搜索字符、字符串和正则表达式，并且使用contains()来计数。

字符串和字符可以通过insert()来插入并且通过append()来添加。字符串可以通过prepend()在前面添加。字符串中的字符可以通过remove()来移除并且通过replace()来替换。

字符串的一部分可以使用left()、right()和mid()来提取。空白符号可以使用stripWhiteSpace()和simplifyWhiteSpace()来移除。字符串可以使用upper()和lower()分别转换为大写或小写。

包含数字的字符串可以使用toShort()、toInt()、toLong()、toULong()、toFloat()和toDouble()来被转换为数字。数字可以使用setNum()来被转换为字符串。

很多操作符被重载以用来为QCString工作。QCString也支持更多的不明显的功能，例如sprintf()、setStr()和setExpand()。

在字符比较上请注意

在QCString中，大写和小写的字符大于或者小于另一个依赖于本地的字符。这个影响支持不区分大小写选项的或者比较大写或者小写参数的函数。如果两个字符串都只包含ACSII码，不区分大小写的操作和比较将是正确的。（如果$LC_CTYPE被设置，绝大多数Unix系统都会做“正确的事情”。）受这个影响的函数包括contains()、find()、findRev()、operator<()、operator<=()、operator>()、operator>=()、lower()和upper()。

性能注意：使用QRegExp进行搜索的QCString方法通过把QCString转换为QString来重新实现的并且在它上面执行搜索的。这意味着QCString数据的深复制。如果你要在一个大的QCString中执行许多QRegExp的搜索，你最好自己把QCString转换为QString并且在QString中进行搜索可以得到更好的执行效果。

也可以参考集合类、隐含和明显共享类、文本相关类和非图形用户界面类。

成员函数文档

QCString::QCString ()

构造一个零字符串。

也可以参考isNull()。

QCString::QCString ( int size )

构造一个空间为size字符，包括'\0'结尾符的字符串。如果size == 0，这就是一个零字符串。

如果size > 0，那么字符串的第一个和最后一个字符被初始化为'\0'.。所有其它字符没有被初始化。

也可以参考resize()和isNull()。

QCString::QCString ( const QCString & s )

构造一个s的浅复制。

也可以参考assign()。

QCString::QCString ( const char * str )

构造一个str的深复制。

如果str0，那么零字符串被创建。

也可以参考isNull()。

QCString::QCString ( const char * str, uint maxsize )

构造一个str的深复制，包括'\0'结尾符不超过maxsize字节。

实例：

    QCString str( "helloworld", 6 ); // 把“hello”分配给str

如果str在开始的maxsize字节中包含一个0字节，那么结果QCString将被这个0结束。如果str0，那么零字符串被创建。

也可以参考isNull()。

QCString & QCString::append ( const char * str )

把字符串str添加到字符串末尾并且返回这个字符串的引用。等于operator+=()。

int QCString::contains ( char c, bool cs = TRUE ) const

返回字符串中字符c出现的次数。

如果cs为真，匹配就区分大小写，或者如果cs为假，就不区分大小写。

也可以参考Note on character comparisons。

int QCString::contains ( const char * str, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回字符串中str出现的次数。

如果cs为真，匹配就区分大小写，或者如果cs为假，就不区分大小写。

这个函数对子字符串重叠计数，例如，“banana”包含两个“ana”。

也可以参考findRev()和Note on character comparisons。

int QCString::contains ( const QRegExp & rx ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

字符串中rx出现的重叠计数。

实例：

    QString s = "banana and panama";
    QRegExp r = QRegExp( "a[nm]a", TRUE, FALSE );
    s.contains( r ); // 4个匹配项

也可以参考find()和findRev()。

QCString QCString::copy () const

返回这个字符串的深复制。

也可以参考detach()。

bool QCString::fill ( char c, int len = -1 )

在字符串中填充len个字节的字符c和一个'\0'结束符。

如果len为负数，那么当前的字符串长度被使用。

返回假就是len为非负数并且没有足够的空间来重新定义字符串的大小，否则就返回真。

int QCString::find ( char c, int index = 0, bool cs = TRUE ) const

在字符串中从index位置开始，找到字符c第一次出现的位置。

如果cs为真，搜索是区分大小写的，否则如果cs为假，就不区分大小写。

返回c的位置，或者如果c没有被发现，返回-1。

也可以参考Note on character comparisons。

实例：network/networkprotocol/nntp.cpp。

int QCString::find ( const char * str, int index = 0, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串中从index位置开始，找到字符串str第一次出现的位置。

如果cs为真，搜索是区分大小写的，否则如果cs为假，就不区分大小写。

返回str的位置，或者如果str没有被发现，返回-1。

也可以参考Note on character comparisons。

int QCString::find ( const QRegExp & rx, int index = 0 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串中从index位置开始，找到正则表达式 rx第一次出现的位置。

返回下一个匹配的位置，如果rx没有被发现，返回-1。

int QCString::findRev ( char c, int index = -1, bool cs = TRUE ) const

在字符串中从index位置开始并且反向搜索，找到字符c第一次出现的位置。

如果cs为真，搜索是区分大小写的，否则如果cs为假，就不区分大小写。

返回c的位置，或者如果c没有被发现，返回-1。

也可以参考Note on character comparisons。

int QCString::findRev ( const char * str, int index = -1, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串中从index位置开始并且反向搜索，找到字符串str第一次出现的位置。

如果cs为真，搜索是区分大小写的，否则如果cs为假，就不区分大小写。

返回str的位置，或者如果str没有被发现，返回-1。

也可以参考Note on character comparisons。

int QCString::findRev ( const QRegExp & rx, int index = -1 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串中从index位置开始并且反向搜索，找到正则表达式 rx第一次出现的位置。

返回下一个匹配的位置（反向），如果rx没有被发现，返回-1。

QCString & QCString::insert ( uint index, char c )

在字符串的index位置插入字符c并且返回字符串的引用。

如果index超出字符串的结尾，字符串被使用空格（ASCII 32）延伸到index长度，然后c被添加。

实例：

    QCString s = "Yes";
    s.insert( 3, '!');                          // s == "Yes!"

也可以参考remove()和replace()。

QCString & QCString::insert ( uint index, const char * s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串的index位置插入字符串s并且返回字符串的引用。

如果index超出字符串的结尾，字符串被使用空格（ASCII 32）延伸到index长度，然后s被添加。

    QCString s = "I like fish";
    s.insert( 2, "don't "); // s == "I don't like fish"

    s = "x";                // index 01234
    s.insert( 3, "yz" );    // s == "x  yz"

bool QCString::isEmpty () const

如果字符串为空，例如如果length() == 0，返回真。空字符串不总是零字符串。

请参考isNull()中的实例。

也可以参考isNull()、length()和size()。

bool QCString::isNull () const

如果字符串为零，例如如果data() == 0，返回真。零字符串也是空字符串。

实例：

    QCString a;         // a.data() == 0,  a.size() == 0, a.length() == 0
    QCString b == "";   // b.data() == "", b.size() == 1, b.length() == 0
    a.isNull();         // TRUE，因为a.data() == 0
    a.isEmpty();        // TRUE，因为a.length() == 0
    b.isNull();         // FALSE，因为 b.data() == ""
    b.isEmpty();        // TRUE，因为b.length() == 0

也可以参考isEmpty()、length()和size()。

QCString QCString::left ( uint len ) const

返回包含字符串最左面的len个字符的子字符串。

如果len超过字符串的长度，则整个字符串被返回。

实例：

    QCString s = "Pineapple";
    QCString t = s.left( 4 );                   // t == "Pine"

也可以参考right()和mid()。

实例：network/networkprotocol/nntp.cpp。

QCString QCString::leftJustify ( uint width, char fill = ' ', bool truncate = FALSE ) const

返回一个长度为width的（为了结束符'\0'加一），包含这个字符串，并且用fill填补的字符串。

如果truncate为假并且字符串的长度超过width，那么返回的字符串是这个字符串的复制。

如果truncate为真并且字符串的长度超过width，那么返回的字符串是left(width)。

实例：

    QCString s("apple");
    QCString t = s.leftJustify(8, '.');         // t == "apple..."

也可以参考rightJustify()。

uint QCString::length () const

返回字符串的长度，除了'\0'结束符。等于strlen(data())。

零字符串和空字符串长度都为零。

也可以参考size()、isNull()和isEmpty()。

实例：network/networkprotocol/nntp.cpp。

QCString QCString::lower () const

返回由这个字符串转换的小写字符串。

实例：

    QCString s("Credit");
    QCString t = s.lower();                     // t == "credit"

也可以参考upper()和Note on character comparisons。

QCString QCString::mid ( uint index, uint len = 0xffffffff ) const

返回包含这个字符串从index位置开始len个字符的字符串。

如果这个字符串为空或者index超出范围，返回零。如果index+len超过这个字符串的长度，返回从index开始的整个字符串。

实例：

    QCString s = "Two pineapples";
    QCString t = s.mid( 4, 3 );                 // t == "pin"

也可以参考left()和right()。

实例：network/networkprotocol/nntp.cpp。

QCString::operator const char * () const

返回字符串数据。

QCString & QCString::operator+= ( const char * str )

把str添加到字符串中并且返回结果的引用。

QCString & QCString::operator+= ( char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把字符c添加到字符串中并且返回结果的引用。

QCString & QCString::operator= ( const QCString & s )

把s的一个浅度复制赋值给这个字符串并且返回这个字符串的引用。

QCString & QCString::operator= ( const char * str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把str的一个深度复制赋值给这个字符串并且返回这个字符串的引用。

如果str为0，一个零字符串就被创建。

也可以参考isNull()。

QCString & QCString::prepend ( const char * s )

在字符串开始处插入s并且返回这个字符串的引用。

也可以参考insert()。

QCString & QCString::remove ( uint index, uint len )

从字符串中的index位置开始移除len个字符并且返回这个字符串的引用。

如果index超出字符串的长度，就什么也不发生。如果index在字符串中间，但是index加上len超过字符串的结尾，这个字符串将从index开始被截短。

    QCString s = "Montreal";
    s.remove( 1, 4 );
    // s == "Meal"

也可以参考insert()和replace()。

实例：network/networkprotocol/nntp.cpp。

QCString & QCString::replace ( uint index, uint len, const char * str )

从字符串中的index位置开始使用str替换len个字符，并且返回这个字符串的引用。

如果index超出字符串的长度，就什么也不被删除并且s被添加到字符串结尾。如果 index有效并且index加上len超过字符串的结尾，那么这个字符串将从index开始被截短，并且str被添加到字符串结尾。

    QCString s = "Say yes!";
    s.replace( 4, 3, "NO" );                    // s == "Say NO!"

也可以参考insert()和remove()。

QCString & QCString::replace ( const QRegExp & rx, const char * str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

用str替换字符串中出现的每一个正则表达式rx。返回这个字符串的引用。

实例：

    QString s = "banana";
    s.replace( QRegExp("a.*a"), "" );           // 变为“b”

    s = "banana";
    s.replace( QRegExp("^[bn]a"), " " );        // 变为“ nana”

    s = "banana";
    s.replace( QRegExp("^[bn]a"), "" );         // 注意！变为“”

最后一个例子可能很令人惊奇。正则表达式的语义重复地应用于这个字符串，所以首先最开始的“ba”被移除了，接着是“na”，然后是最后的“na”，剩下的就是一个空字符串了。

bool QCString::resize ( uint len )

扩展或者收缩字符串到len字节，包括'\0'结束符。

'\0'结束符被设置在len - 1位置，除非len == 0。

实例：

    QCString s = "resize this string";
    s.resize( 7 );                              // s == "resize"

也可以参考truncate()。

实例：network/networkprotocol/nntp.cpp。

QCString QCString::right ( uint len ) const

返回包含字符串最右面的len个字符的子字符串。

如果len超过字符串的长度，则整个字符串被返回。

实例：

    QCString s = "Pineapple";
    QCString t = s.right( 5 );                  // t == "apple"

也可以参考left()和mid()。

实例：network/networkprotocol/nntp.cpp。

QCString QCString::rightJustify ( uint width, char fill = ' ', bool truncate = FALSE ) const

返回一个长度为width的（为了结束符'\0'加一），包含fill填补的字符串，后面跟着这个字符串。

如果truncate为假并且字符串的长度超过width，那么返回的字符串是这个字符串的复制。

如果truncate为真并且字符串的长度超过width，那么返回的字符串是right(width).。

实例：

    QCString s("pie");
    QCString t = s.rightJustify(8, '.');                // t == ".....pie"

也可以参考leftJustify()。

bool QCString::setExpand ( uint index, char c )

设置在index位置的字符为c并且如果需要使用空格来扩展这个字符串。

如果index超出范围并且如果字符串不能被扩大，返回假，否则为真。

QCString & QCString::setNum ( double n, char f = 'g', int prec = 6 )

设置字符串为数字n的字符表示并且返回字符串的引用。

字符表示的格式由格式字符f指定，并且精度（小数点之后的位数）由prec指定。

有效的f的格式为'e'、'E'、'f'、'g'和'G'。和sprintf()的格式相同，在QString::arg()中有它们的解释。

QCString & QCString::setNum ( short n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( ushort n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( int n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( uint n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( long n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( ulong n )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为数字n的字符表示并且返回字符串的引用。

QCString & QCString::setNum ( float n, char f = 'g', int prec = 6 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

QCString & QCString::setStr ( const char * str )

把str的一个深度复制赋值给这个字符串并且返回这个字符串的引用。

QCString QCString::simplifyWhiteSpace () const

返回一个移除了这个字符串的开始和结尾的空白符号的字符串，并且内部的空白符号都被替代为单一的空格（ASCII 32）。

空白符号是指十进制ASCII码为9、10、11、12、13和32。

    QCString s = "  lots\t of\nwhite    space ";
    QCString t = s.simplifyWhiteSpace(); // t == "lots of white space"

也可以参考stripWhiteSpace()。

QCString & QCString::sprintf ( const char * format, ... )

重新实现为本地的vsprintf()的一个调用（请参考你的C库的手册）。

如果字符串小于256字符，这个sprintf()调用resize(256)来减少内存的占用。在sprintf()返回之前，字符串被重新定义为它实际的长度。

实例：

    QCString s;
    s.sprintf( "%d - %s", 1, "first" );         // result < 256 字符

    QCString big( 25000 );                      // 很长的字符串
    big.sprintf( "%d - %s", 2, longString );    // result < 25000 字符

警告： limit. 如果format规格和参数比目标字符串常，所有的vsprintf()实现将会越过目标字符串（*this）进行写操作，并且如果目标字符串比一些任意实现限制长，会有一些失败。

把用户给定的参数传给sprintf()会导致一些问题。迟早会有一些人将会把3000个字符的行传给你的应用程序。

QCString QCString::stripWhiteSpace () const

返回一个移除了这个字符串的开始和结尾的空白符号的字符串。

空白符号是指十进制ASCII码为9、10、11、12、13和32。

实例：

    QCString s = " space ";
    QCString t = s.stripWhiteSpace();           // t == "space"

也可以参考simplifyWhiteSpace()。

double QCString::toDouble ( bool * ok = 0 ) const

返回由这个字符串转化的double值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

float QCString::toFloat ( bool * ok = 0 ) const

返回由这个字符串转化的float值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

int QCString::toInt ( bool * ok = 0 ) const

返回由这个字符串转化的int值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

long QCString::toLong ( bool * ok = 0 ) const

返回由这个字符串转化的long值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

short QCString::toShort ( bool * ok = 0 ) const

返回由这个字符串转化的short值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

uint QCString::toUInt ( bool * ok = 0 ) const

返回由这个字符串转化的unsigned int值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

ulong QCString::toULong ( bool * ok = 0 ) const

返回由这个字符串转化的unsigned long值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

ushort QCString::toUShort ( bool * ok = 0 ) const

返回由这个字符串转化的unsigned short值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

bool QCString::truncate ( uint pos )

在pos位置截短字符串。

等于调用resize(pos+1)。

实例：

    QCString s = "truncate this string";
    s.truncate( 5 );                            // s == "trunc"

也可以参考resize()。

QCString QCString::upper () const

返回由这个字符串转换的大写字符串。

实例：

    QCString s( "Debit" );
    QCString t = s.upper();                     // t == "DEBIT"

也可以参考lower()和Note on character comparisons。

相关函数

bool operator!= ( const QCString & s1, const QCString & s2 )

如果s1和s2不同，返回真，否则返回假。

等于qstrcmp(s1, s2) != 0。

bool operator!= ( const QCString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1和s2不同，返回真，否则返回假。

等于qstrcmp(s1, s2) != 0。

bool operator!= ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1和s2不同，返回真，否则返回假。

等于qstrcmp(s1, s2) != 0。

const QCString operator+ ( const QCString & s1, const QCString & s2 )

返回由s1和s2串联组成的字符串。

const QCString operator+ ( const QCString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回由s1和s2串联组成的字符串。

const QCString operator+ ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回由s1和s2串联组成的字符串。

const QCString operator+ ( const QCString & s, char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回由s和c串联组成的字符串。

const QCString operator+ ( char c, const QCString & s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回由c和s串联组成的字符串。

bool operator< ( const QCString & s1, const char * s2 )

如果s1小于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) < 0。

也可以参考有关字符比较的注意。

bool operator< ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1小于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) < 0。

也可以参考有关字符比较的注意。

QDataStream & operator<< ( QDataStream & s, const QCString & str )

把字符串str写到流s中。

也可以参考QDataStream操作符的格式。

bool operator<= ( const QCString & s1, const char * s2 )

如果s1小于等于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) <= 0。

也可以参考有关字符比较的注意。

bool operator<= ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1小于等于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) <= 0。

也可以参考有关字符比较的注意。

bool operator== ( const QCString & s1, const QCString & s2 )

如果s1和s2相等，返回真，否则返回假。

等于qstrcmp(s1, s2) == 0。

bool operator== ( const QCString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1和s2相等，返回真，否则返回假。

等于qstrcmp(s1, s2) == 0。

bool operator== ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1和s2相等，返回真，否则返回假。

等于qstrcmp(s1, s2) == 0。

bool operator> ( const QCString & s1, const char * s2 )

如果s1大于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) > 0。

也可以参考有关字符比较的注意。

bool operator> ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1大于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) > 0。

也可以参考有关字符比较的注意。

bool operator>= ( const QCString & s1, const char * s2 )

如果s1大于等于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) >= 0。

也可以参考有关字符比较的注意。

bool operator>= ( const char * s1, const QCString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1大于等于s2，返回真，否则返回假。

等于qstrcmp(s1, s2) >= 0。

也可以参考有关字符比较的注意。

QDataStream & operator>> ( QDataStream & s, QCString & str )

从流s中读取一个字符串到str。

也可以参考QDataStream操作符的格式。

void * qmemmove ( void * dst, const void * src, uint len )

这个函数通常是C库的一部分。Qt为不支持它的平台实现了memmove()。

memmove()从src中复制len字节到dst。甚至src重叠dst，数据都可以被正确复制。

int qstrcmp ( const char * str1, const char * str2 )

一个安全的strcmp()函数。

比较str1和str2。如果str1小于str2，返回一个负值，如果str1等于str2，返回0或者如果str1大于str2返回一个正值。

特例一：如果str1和str2都为零，返回0。

特例二：如果str1为零或者str2为零（但不全是），返回一个随机非零值。

也可以参考qstrncmp()、qstricmp()、qstrnicmp()和有关字符比较的注意。

char * qstrcpy ( char * dst, const char * src )

一个安全的strcpy()函数。

把src中一直到'\0'的字符（包含它）的字符复制到dst中并且返回dst的指针。

char * qstrdup ( const char * src )

返回一个复制的字符串。

为src的副本分配空间，复制并且返回副本的指针。如果src为零，它立即返回0。

返回的字符串需要使用delete[]来删除。

int qstricmp ( const char * str1, const char * str2 )

一个安全的stricmp()函数。

忽略大小写比较str1和str2。

如果str1小于str2，返回一个负值，如果str1等于str2，返回0或者如果str1大于str2返回一个正值。

特例一：如果str1和str2都为零，返回0。

特例二：如果str1为零或者str2为零（但不全是），返回一个随机非零值。

也可以参考qstrcmp()、qstrncmp()、qstrnicmp()和有关字符比较的注意。

int qstrncmp ( const char * str1, const char * str2, uint len )

一个安全的strncmp()函数。

比较str1和str2一直到len字节。

如果str1小于str2，返回一个负值，如果str1等于str2，返回0或者如果str1大于str2返回一个正值。

特例一：如果str1和str2都为零，返回0。

特例二：如果str1为零或者str2为零（但不全是），返回一个随机非零值。

也可以参考qstrcmp()、qstricmp()、qstrnicmp()和有关字符比较的注意。

char * qstrncpy ( char * dst, const char * src, uint len )

一个安全的strncpy()函数。

从src中复制一直到len字节的全部字符（或者如果src更短就更少）复制到dst中并且返回dst的指针。保证dst是'\0'结尾的。如果src或dst为零，立即返回0。

也可以参考qstrcpy()。

int qstrnicmp ( const char * str1, const char * str2, uint len )

一个安全的strnicmp()函数。

忽略大小写，比较str1和str2一直到len字节。

如果str1小于str2，返回一个负值，如果str1等于str2，返回0或者如果str1大于str2返回一个正值。

特例一：如果str1和str2都为零，返回0。

特例二：如果str1为零或者str2为零（但不全是），返回一个随机非零值。

也可以参考qstrcmp()、qstrncmp()、qstricmp()和有关字符比较的注意。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qcstring.h包含文件

qcstring.h

这里是qcstring.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qcstring.h   3.0.5   edited Jun 5 21:14 $
**
** Definition of the extended char array operations,
** and QByteArray and QCString classes
**
** Created : 920609
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCSTRING_H
#define QCSTRING_H

#ifndef QT_H
#include "qmemarray.h"
#endif // QT_H

#include <string.h>

/*****************************************************************************
  Safe and portable C string functions; extensions to standard string.h
 *****************************************************************************/

Q_EXPORT void *qmemmove( void *dst, const void *src, uint len );

Q_EXPORT char *qstrdup( const char * );

Q_EXPORT inline uint qstrlen( const char *str )
{ return str ? (uint)strlen(str) : 0; }

Q_EXPORT inline char *qstrcpy( char *dst, const char *src )
{ return src ? strcpy(dst, src) : 0; }

Q_EXPORT char *qstrncpy( char *dst, const char *src, uint len );

Q_EXPORT inline int qstrcmp( const char *str1, const char *str2 )
{
    return ( str1 && str2 ) ? strcmp( str1, str2 )
                : ( str1 ? 1 : ( str2 ? -1 : 0 ) );
}

Q_EXPORT inline int qstrncmp( const char *str1, const char *str2, uint len )
{
    return ( str1 && str2 ) ? strncmp( str1, str2, len )
                : ( str1 ? 1 : ( str2 ? -1 : 0 ) );
}

Q_EXPORT int qstricmp( const char *, const char * );

Q_EXPORT int qstrnicmp( const char *, const char *, uint len );

#ifndef QT_CLEAN_NAMESPACE
Q_EXPORT inline uint cstrlen( const char *str )
{ return (uint)strlen(str); }

Q_EXPORT inline char *cstrcpy( char *dst, const char *src )
{ return strcpy(dst,src); }

Q_EXPORT inline int cstrcmp( const char *str1, const char *str2 )
{ return strcmp(str1,str2); }

Q_EXPORT inline int cstrncmp( const char *str1, const char *str2, uint len )
{ return strncmp(str1,str2,len); }
#endif

// qChecksum: Internet checksum

Q_EXPORT Q_UINT16 qChecksum( const char *s, uint len );

/*****************************************************************************
  QByteArray class
 *****************************************************************************/

#if defined(Q_TEMPLATEDLL)
Q_TEMPLATE_EXTERN template class Q_EXPORT QMemArray<char>;
#endif

#if defined(Q_QDOC)
/*
  We want qdoc to document QByteArray as a real class that inherits
  QMemArray<char> and that is inherited by QBitArray.
*/
class QByteArray : public QMemArray<char>
{
public:
    QByteArray();
    QByteArray( int size );
};
#else
typedef QMemArray<char> QByteArray;
#endif

/*****************************************************************************
  QByteArray stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QByteArray & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QByteArray & );
#endif

/*****************************************************************************
  QCString class
 *****************************************************************************/

class QRegExp;

class Q_EXPORT QCString : public QByteArray	// C string class
{
public:
    QCString() {}				// make null string
    QCString( int size );			// allocate size incl. \0
    QCString( const QCString &s ) : QByteArray( s ) {}
    QCString( const char *str );		// deep copy
    QCString( const char *str, uint maxlen );	// deep copy, max length
    ~QCString();

    QCString    &operator=( const QCString &s );// shallow copy
    QCString    &operator=( const char *str );	// deep copy

    bool	isNull()	const;
    bool	isEmpty()	const;
    uint	length()	const;
    bool	resize( uint newlen );
    bool	truncate( uint pos );
    bool	fill( char c, int len = -1 );

    QCString	copy()	const;

    QCString    &sprintf( const char *format, ... );

    int		find( char c, int index=0, bool cs=TRUE ) const;
    int		find( const char *str, int index=0, bool cs=TRUE ) const;
#ifndef QT_NO_REGEXP
    int		find( const QRegExp &, int index=0 ) const;
#endif
    int		findRev( char c, int index=-1, bool cs=TRUE) const;
    int		findRev( const char *str, int index=-1, bool cs=TRUE) const;
#ifndef QT_NO_REGEXP
    int		findRev( const QRegExp &, int index=-1 ) const;
#endif
    int		contains( char c, bool cs=TRUE ) const;
    int		contains( const char *str, bool cs=TRUE ) const;
#ifndef QT_NO_REGEXP
    int		contains( const QRegExp & ) const;
#endif
    QCString	left( uint len )  const;
    QCString	right( uint len ) const;
    QCString	mid( uint index, uint len=0xffffffff) const;

    QCString	leftJustify( uint width, char fill=' ', bool trunc=FALSE)const;
    QCString	rightJustify( uint width, char fill=' ',bool trunc=FALSE)const;

    QCString	lower() const;
    QCString	upper() const;

    QCString	stripWhiteSpace()	const;
    QCString	simplifyWhiteSpace()	const;

    QCString    &insert( uint index, const char * );
    QCString    &insert( uint index, char );
    QCString    &append( const char * );
    QCString    &prepend( const char * );
    QCString    &remove( uint index, uint len );
    QCString    &replace( uint index, uint len, const char * );
#ifndef QT_NO_REGEXP
    QCString    &replace( const QRegExp &, const char * );
#endif
    short	toShort( bool *ok=0 )	const;
    ushort	toUShort( bool *ok=0 )	const;
    int		toInt( bool *ok=0 )	const;
    uint	toUInt( bool *ok=0 )	const;
    long	toLong( bool *ok=0 )	const;
    ulong	toULong( bool *ok=0 )	const;
    float	toFloat( bool *ok=0 )	const;
    double	toDouble( bool *ok=0 )	const;

    QCString    &setStr( const char *s );
    QCString    &setNum( short );
    QCString    &setNum( ushort );
    QCString    &setNum( int );
    QCString    &setNum( uint );
    QCString    &setNum( long );
    QCString    &setNum( ulong );
    QCString    &setNum( float, char f='g', int prec=6 );
    QCString    &setNum( double, char f='g', int prec=6 );

    bool	setExpand( uint index, char c );

        operator const char *() const;
    QCString    &operator+=( const char *str );
    QCString    &operator+=( char c );
};

/*****************************************************************************
  QCString stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QCString & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QCString & );
#endif

/*****************************************************************************
  QCString inline functions
 *****************************************************************************/

inline QCString &QCString::operator=( const QCString &s )
{ return (QCString&)assign( s ); }

inline QCString &QCString::operator=( const char *str )
{ return (QCString&)duplicate( str, qstrlen(str)+1 ); }

inline bool QCString::isNull() const
{ return data() == 0; }

inline bool QCString::isEmpty() const
{ return data() == 0 || *data() == '\0'; }

inline uint QCString::length() const
{ return qstrlen( data() ); }

inline bool QCString::truncate( uint pos )
{ return resize(pos+1); }

inline QCString QCString::copy() const
{ return QCString( data() ); }

inline QCString &QCString::prepend( const char *s )
{ return insert(0,s); }

inline QCString &QCString::append( const char *s )
{ return operator+=(s); }

inline QCString &QCString::setNum( short n )
{ return setNum((long)n); }

inline QCString &QCString::setNum( ushort n )
{ return setNum((ulong)n); }

inline QCString &QCString::setNum( int n )
{ return setNum((long)n); }

inline QCString &QCString::setNum( uint n )
{ return setNum((ulong)n); }

inline QCString &QCString::setNum( float n, char f, int prec )
{ return setNum((double)n,f,prec); }

inline QCString::operator const char *() const
{ return (const char *)data(); }

/*****************************************************************************
  QCString non-member operators
 *****************************************************************************/

Q_EXPORT inline bool operator==( const QCString &s1, const QCString &s2 )
{ return qstrcmp(s1.data(),s2.data()) == 0; }

Q_EXPORT inline bool operator==( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) == 0; }

Q_EXPORT inline bool operator==( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) == 0; }

Q_EXPORT inline bool operator!=( const QCString &s1, const QCString &s2 )
{ return qstrcmp(s1.data(),s2.data()) != 0; }

Q_EXPORT inline bool operator!=( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) != 0; }

Q_EXPORT inline bool operator!=( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) != 0; }

Q_EXPORT inline bool operator<( const QCString &s1, const QCString& s2 )
{ return qstrcmp(s1.data(),s2.data()) < 0; }

Q_EXPORT inline bool operator<( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) < 0; }

Q_EXPORT inline bool operator<( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) < 0; }

Q_EXPORT inline bool operator<=( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) <= 0; }

Q_EXPORT inline bool operator<=( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) <= 0; }

Q_EXPORT inline bool operator>( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) > 0; }

Q_EXPORT inline bool operator>( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) > 0; }

Q_EXPORT inline bool operator>=( const QCString &s1, const char *s2 )
{ return qstrcmp(s1.data(),s2) >= 0; }

Q_EXPORT inline bool operator>=( const char *s1, const QCString &s2 )
{ return qstrcmp(s1,s2.data()) >= 0; }

Q_EXPORT inline const QCString operator+( const QCString &s1, const QCString &s2 )
{
    QCString tmp( s1.data() );
    tmp += s2;
    return tmp;
}

Q_EXPORT inline const QCString operator+( const QCString &s1, const char *s2 )
{
    QCString tmp( s1.data() );
    tmp += s2;
    return tmp;
}

Q_EXPORT inline const QCString operator+( const char *s1, const QCString &s2 )
{
    QCString tmp( s1 );
    tmp += s2;
    return tmp;
}

Q_EXPORT inline const QCString operator+( const QCString &s1, char c2 )
{
    QCString tmp( s1.data() );
    tmp += c2;
    return tmp;
}

Q_EXPORT inline const QCString operator+( char c1, const QCString &s2 )
{
    QCString tmp;
    tmp += c1;
    tmp += s2;
    return tmp;
}

#endif // QCSTRING_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCString成员列表

完整的QCString成员列表

这里是QCString成员函数的完整列表，包括继承的成员。

  • QCString()
  • append()
  • assign()
  • at()
  • begin()
  • bsearch()
  • contains()
  • copy()
  • count()
  • data()
  • detach()
  • duplicate()
  • end()
  • fill()
  • find()
  • findRev()
  • insert()
  • isEmpty()
  • isNull()
  • left()
  • leftJustify()
  • length()
  • lower()
  • mid()
  • nrefs()
  • operator const char *()
  • operator const type *()
  • operator+=()
  • operator=()
  • operator[]()
  • prepend()
  • remove()
  • replace()
  • resetRawData()
  • resize()
  • right()
  • rightJustify()
  • setExpand()
  • setNum()
  • setRawData()
  • setStr()
  • simplifyWhiteSpace()
  • size()
  • sort()
  • sprintf()
  • stripWhiteSpace()
  • toDouble()
  • toFloat()
  • toInt()
  • toLong()
  • toShort()
  • toUInt()
  • toULong()
  • toUShort()
  • truncate()
  • upper()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QCursor Class

QCursor Class Reference

The QCursor class provides a mouse cursor with an arbitrary shape. More...

#include <qcursor.h>

Inherits Qt.

List of all member functions.

Public Members

  • QCursor ()
  • QCursor ( int shape )
  • QCursor ( const QBitmap & bitmap, const QBitmap & mask, int hotX = -1, int hotY = -1 )
  • QCursor ( const QPixmap & pixmap, int hotX = -1, int hotY = -1 )
  • QCursor ( const QCursor & c )
  • ~QCursor ()
  • QCursor & operator= ( const QCursor & c )
  • int shape () const
  • void setShape ( int shape )
  • const QBitmap * bitmap () const
  • const QBitmap * mask () const
  • QPoint hotSpot () const
  • HCURSOR handle () const
  • QCursor ( HCURSOR handle )
  • HANDLE handle () const

Static Public Members

  • QPoint pos ()
  • void setPos ( int x, int y )
  • void setPos ( const QPoint & )
  • void initialize ()
  • void cleanup ()

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QCursor & c )
  • QDataStream & operator>> ( QDataStream & s, QCursor & c )

Detailed Description

The QCursor class provides a mouse cursor with an arbitrary shape.

This class is mainly used to create mouse cursors that are associated with particular widgets and to get and set the position of the mouse cursor.

Qt has a number of standard cursor shapes, but you can also make custom cursor shapes based on a QBitmap, a mask and a hotspot.

To associate a cursor with a widget, use QWidget::setCursor(). To associate a cursor with all widgets (normally for a short period of time), use QApplication::setOverrideCursor().

To set a cursor shape use QCursor::setShape() or use the QCursor constructor which takes the shape as argument, or you can use one of the predefined cursors defined in the CursorShape enum.

If you want to create a cursor with your own bitmap, either use the QCursor constructor which takes a bitmap and a mask or the constructor which takes a pixmap as arguments.

To set or get the position of the mouse cursor use the static methods QCursor::pos() and QCursor::setPos().

See also QWidget, GUI Design Handbook: Cursors, Widget Appearance and Style and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QCursor::QCursor ()

Constructs a cursor with the default arrow shape.

QCursor::QCursor ( int shape )

Constructs a cursor with the specified shape.

See CursorShape for a list of shapes.

See also setShape().

QCursor::QCursor ( const QBitmap & bitmap, const QBitmap & mask, int hotX = -1, int hotY = -1 )

Constructs a custom bitmap cursor.

bitmap and mask make up the bitmap. hotX and hotY define the cursor's hot spot.

If hotX is negative, it is set to the bitmap().width()/2. If hotY is negative, it is set to the bitmap().height()/2.

The cursor bitmap (B) and mask (M) bits are combined like this:

  • B=1 and M=1 gives black.
  • B=0 and M=1 gives white.
  • B=0 and M=0 gives transparent.
  • B=1 and M=0 gives an undefined result.

Use the global color color0 to draw 0-pixels and color1 to draw 1-pixels in the bitmaps.

Valid cursor sizes depend on the display hardware (or the underlying window system). We recommend using 32x32 cursors, because this size is supported on all platforms. Some platforms also support 16x16, 48x48 and 64x64 cursors.

See also QBitmap::QBitmap() and QBitmap::setMask().

QCursor::QCursor ( const QPixmap & pixmap, int hotX = -1, int hotY = -1 )

Constructs a custom pixmap cursor.

pixmap is the image. It is usual to give it a mask (set using QPixmap::setMask()). hotX and hotY define the cursor's hot spot.

If hotX is negative, it is set to the pixmap().width()/2. If hotY is negative, it is set to the pixmap().height()/2.

Valid cursor sizes depend on the display hardware (or the underlying window system). We recommend using 32x32 cursors, because this size is supported on all platforms. Some platforms also support 16x16, 48x48 and 64x64 cursors.

Currently, only black-and-white pixmaps can be used.

See also QPixmap::QPixmap() and QPixmap::setMask().

QCursor::QCursor ( const QCursor & c )

Constructs a copy of the cursor c.

QCursor::QCursor ( HCURSOR handle )

Creates a cursor with the specified window system handle handle.

Warning: Portable in principle, but if you use it you are probably about to do something non-portable. Be careful.

QCursor::~QCursor ()

Destroys the cursor.

const QBitmap * QCursor::bitmap () const

Returns the cursor bitmap, or 0 if it is one of the standard cursors.

void QCursor::cleanup () [static]

Internal function that deinitializes the predefined cursors. This function is called from the QApplication destructor.

See also initialize().

HANDLE QCursor::handle () const

Returns the window system cursor handle.

Warning: Portable in principle, but if you use it you are probably about to do something non-portable. Be careful.

QPoint QCursor::hotSpot () const

Returns the cursor hot spot, or (0, 0) if it is one of the standard cursors.

void QCursor::initialize () [static]

Internal function that initializes the predefined cursors. This function is called from the QApplication constructor.

See also cleanup().

const QBitmap * QCursor::mask () const

Returns the cursor bitmap mask, or 0 if it is one of the standard cursors.

QCursor & QCursor::operator= ( const QCursor & c )

Assigns c to this cursor and returns a reference to this cursor.

QPoint QCursor::pos () [static]

Returns the position of the cursor (hot spot) in global screen coordinates.

You can call QWidget::mapFromGlobal() to translate it to widget coordinates.

See also setPos(), QWidget::mapFromGlobal() and QWidget::mapToGlobal().

Examples: chart/canvasview.cpp and fileiconview/qfileiconview.cpp.

void QCursor::setPos ( int x, int y ) [static]

Moves the cursor (hot spot) to the global screen position (x, y).

You can call QWidget::mapToGlobal() to translate widget coordinates to global screen coordinates.

See also pos(), QWidget::mapFromGlobal() and QWidget::mapToGlobal().

void QCursor::setPos ( const QPoint & ) [static]

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

void QCursor::setShape ( int shape )

Sets the cursor to the shape identified by shape.

See CursorShape for the list of cursor shapes.

See also shape().

int QCursor::shape () const

Returns the cursor shape identifier. The return value is one of the CursorShape enum values (cast to an int).

See also setShape().

Related Functions

QDataStream & operator<< ( QDataStream & s, const QCursor & c )

Writes the cursor c to the stream s.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QCursor & c )

Reads a cursor from the stream s and sets c to the read data.

See also Format of the QDataStream operators.

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


qcursor.h Include File

qcursor.h

This is the verbatim text of the qcursor.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qcursor.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QCursor class
**
** Created : 940219
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QCURSOR_H
#define QCURSOR_H

#ifndef QT_H
#include "qpoint.h"
#include "qshared.h"
#endif // QT_H

/*
  ### The fake cursor has to go first with old qdoc.
*/
#ifdef QT_NO_CURSOR

class Q_EXPORT QCursor : public Qt
{
public:
    static QPoint pos();
    static void	  setPos( int x, int y );
    static void	  setPos( const QPoint & );
private:
    QCursor();
};

#endif // QT_NO_CURSOR

#ifndef QT_NO_CURSOR

struct QCursorData;

class Q_EXPORT QCursor : public Qt
{
public:
    QCursor();				// create default arrow cursor
    QCursor( int shape );
    QCursor( const QBitmap &bitmap, const QBitmap &mask,
         int hotX=-1, int hotY=-1 );
    QCursor( const QPixmap &pixmap,
         int hotX=-1, int hotY=-1 );
    QCursor( const QCursor & );
   ~QCursor();
    QCursor &operator=( const QCursor & );

    int		  shape()   const;
    void	  setShape( int );

    const QBitmap *bitmap() const;
    const QBitmap *mask()   const;
    QPoint	  hotSpot() const;

#if defined(Q_WS_WIN)
    HCURSOR	  handle()  const;
    QCursor( HCURSOR );
#elif defined(Q_WS_X11)
    HANDLE	  handle()  const;
#elif defined(Q_WS_MAC)
    HANDLE handle() const;
#elif defined(Q_WS_QWS)
    HANDLE	  handle()  const;
#endif

    static QPoint pos();
    static void	  setPos( int x, int y );
    static void	  setPos( const QPoint & );

    static void	  initialize();
    static void	  cleanup();

#if defined(Q_WS_X11)
    static int 	  x11Screen();
#endif
private:
    void	  setBitmap( const QBitmap &bitmap, const QBitmap &mask,
                 int hotX, int hotY );
    void	  update() const;
    QCursorData	 *data;
    QCursor	 *find_cur(int);
#if defined(Q_WS_MAC)
    friend void qt_mac_set_cursor(const QCursor *c, const Point *p);
#endif
};

#if !defined(QT_CLEAN_NAMESPACE)
// CursorShape is defined in X11/X.h
#ifdef CursorShape
#define X_CursorShape CursorShape
#undef CursorShape
#endif
typedef Qt::CursorShape QCursorShape;
#ifdef X_CursorShape
#define CursorShape X_CursorShape
#endif
#endif

/*****************************************************************************
  QCursor stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QCursor & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QCursor & );
#endif
#endif // QT_NO_CURSOR

inline void QCursor::setPos( const QPoint &p )
{
    setPos( p.x(), p.y() );
}

#endif // QCURSOR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QCursor Member List

Complete Member List for QCursor

This is the complete list of member functions for QCursor, including inherited members.

  • QCursor()
  • ~QCursor()
  • bitmap()
  • cleanup()
  • handle()
  • hotSpot()
  • initialize()
  • mask()
  • operator=()
  • pos()
  • setPos()
  • setShape()
  • shape()


QCustomEvent Class

QCustomEvent Class Reference

The QCustomEvent class provides support for custom events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QCustomEvent ( int type )
  • QCustomEvent ( Type type, void * data )
  • void * data () const
  • void setData ( void * data )

Detailed Description

The QCustomEvent class provides support for custom events.

QCustomEvent is a generic event class for user-defined events. User defined events can be sent to widgets or other QObject instances using QApplication::postEvent() or QApplication::sendEvent(). Subclasses of QWidget can easily receive custom events by implementing the QWidget::customEvent() event handler function.

QCustomEvent objects should be created with a type ID that uniquely identifies the event type. To avoid clashes with the Qt-defined events types, the value should be at least as large as the value of the "User" entry in the QEvent::Type enum.

QCustomEvent contains a generic void* data member that may be used for transferring event-specific data to the receiver. Note that since events are normally delivered asynchronously, the data pointer, if used, must remain valid until the event has been received and processed.

QCustomEvent can be used as-is for simple user-defined event types, but normally you will want to make a subclass of it for your event types. In a subclass, you can add data members that are suitable for your event type.

Example:

    class ColorChangeEvent : public QCustomEvent
    {
    public:
        ColorChangeEvent( QColor color )
            : QCustomEvent( 346798 ), c( color ) {};
        QColor color() const { return c; };
    private:
        QColor c;
    };

    // To send an event of this custom event type:

    ColorChangeEvent* ce = new ColorChangeEvent( blue );
    QApplication::postEvent( receiver, ce );  // Qt will delete it when done

    // To receive an event of this custom event type:

    void MyWidget::customEvent( QCustomEvent * e )
    {
        if ( e->type() == 346798 ) {  // It must be a ColorChangeEvent
            ColorChangeEvent* ce = (ColorChangeEvent*)e;
            newColor = ce->color();
        }
    }

See also QWidget::customEvent(), QApplication::notify() and Event Classes.

Member Function Documentation

QCustomEvent::QCustomEvent ( int type )

Constructs a custom event object with event type type. The value of type must be at least as large as QEvent::User. The data pointer is set to 0.

QCustomEvent::QCustomEvent ( Type type, void * data )

Constructs a custom event object with the event type type and a pointer to data. (Note that any int value may safely be cast to QEvent::Type).

void * QCustomEvent::data () const

Returns a pointer to the generic event data.

See also setData().

void QCustomEvent::setData ( void * data )

Sets the generic data pointer to data.

See also data().

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


QCustomEvent Member List

Complete Member List for QCustomEvent

This is the complete list of member functions for QCustomEvent, including inherited members.

  • QCustomEvent()
  • data()
  • setData()
  • spontaneous()
  • type()


QCustomMenuItem Class

QCustomMenuItem Class Reference

The QCustomMenuItem class is an abstract base class for custom menu items in popup menus. More...

#include <qmenudata.h>

Inherits Qt.

List of all member functions.

Public Members

  • QCustomMenuItem ()
  • virtual ~QCustomMenuItem ()
  • virtual bool fullSpan () const
  • virtual bool isSeparator () const
  • virtual void setFont ( const QFont & font )
  • virtual void paint ( QPainter * p, const QColorGroup & cg, bool act, bool enabled, int x, int y, int w, int h ) = 0
  • virtual QSize sizeHint () = 0

Detailed Description

The QCustomMenuItem class is an abstract base class for custom menu items in popup menus.

A custom menu item is a menu item that is defined by two purely virtual functions, paint() and sizeHint(). The size hint tells the menu how much space it needs to reserve for this item, and paint is called whenever the item needs painting.

This simple mechanism allows you to create all kinds of application specific menu items. Examples are items showing different fonts in a word processor or menus that allow the selection of drawing utilities in a vector drawing program.

A custom item is inserted into a popup menu with QPopupMenu::insertItem().

By default, a custom item can also have an icon set and a keyboard accelerator. You can reimplement fullSpan() to return TRUE if you want the item to span the entire popup menu width. This is particularly useful for labels.

If you want the custom item to be treated just as a separator, reimplement isSeparator() to return TRUE.

Note that you can insert pixmaps or bitmaps as items into a popup menu without needing to create a QCustomMenuItem. However, custom menu items offer more flexibility, and -- especially important with windows style -- provide the possibility of drawing the item with a different color when it is highlighted.

menu/menu.cpp shows a simply example how custom menu items can be used.

Please note: the current implementation of QCustomMenuItem will not recognize shortcut keys that are from text with ampersands. Normal accelerators work though.

See also QMenuData, QPopupMenu and Miscellaneous Classes.

Member Function Documentation

QCustomMenuItem::QCustomMenuItem ()

Constructs a QCustomMenuItem

QCustomMenuItem::~QCustomMenuItem () [virtual]

Destroys a QCustomMenuItem

bool QCustomMenuItem::fullSpan () const [virtual]

Returns TRUE if this item wants to span the entire popup menu width. The default is FALSE, meaning that the menu may show an icon and an accelerator key for this item as well.

bool QCustomMenuItem::isSeparator () const [virtual]

Returns TRUE if this item is just a separator; otherwise returns FALSE.

void QCustomMenuItem::paint ( QPainter * p, const QColorGroup & cg, bool act, bool enabled, int x, int y, int w, int h ) [pure virtual]

Paints this item. When this function is invoked, the painter p is set to the right font and the right foreground color suitable for a menu item text using color group cg. The item is active if act is TRUE and enabled if enabled is TRUE. The geometry values x, y, w and h specify where to draw the item.

Do not draw any background, this has already been done by the popup menu according to the current GUI style.

void QCustomMenuItem::setFont ( const QFont & font ) [virtual]

Sets the font of the custom menu item to font.

This function is called whenever the font in the popup menu changes. For menu items that show their own individual font entry, you want to ignore this.

QSize QCustomMenuItem::sizeHint () [pure virtual]

Returns the size hint of this item.

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


QCustomMenuItem Member List

Complete Member List for QCustomMenuItem

This is the complete list of member functions for QCustomMenuItem, including inherited members.

  • QCustomMenuItem()
  • ~QCustomMenuItem()
  • fullSpan()
  • isSeparator()
  • paint()
  • setFont()
  • sizeHint()


QDataBrowser Class

QDataBrowser Class Reference
[sql module]

The QDataBrowser class provides data manipulation and navigation for data entry forms. More...

#include <qdatabrowser.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QDataBrowser ( QWidget * parent = 0, const char * name = 0, WFlags fl = 0 )
  • ~QDataBrowser ()
  • enum Boundary { Unknown, None, BeforeBeginning, Beginning, End, AfterEnd }
  • Boundary boundary ()
  • void setBoundaryChecking ( bool active )
  • bool boundaryChecking () const
  • void setSort ( const QSqlIndex & sort )
  • void setSort ( const QStringList & sort )
  • QStringList sort () const
  • void setFilter ( const QString & filter )
  • QString filter () const
  • virtual void setSqlCursor ( QSqlCursor * cursor, bool autoDelete = FALSE )
  • QSqlCursor * sqlCursor () const
  • virtual void setForm ( QSqlForm * form )
  • QSqlForm * form ()
  • virtual void setConfirmEdits ( bool confirm )
  • virtual void setConfirmInsert ( bool confirm )
  • virtual void setConfirmUpdate ( bool confirm )
  • virtual void setConfirmDelete ( bool confirm )
  • virtual void setConfirmCancels ( bool confirm )
  • bool confirmEdits () const
  • bool confirmInsert () const
  • bool confirmUpdate () const
  • bool confirmDelete () const
  • bool confirmCancels () const
  • virtual void setReadOnly ( bool active )
  • bool isReadOnly () const
  • virtual void setAutoEdit ( bool autoEdit )
  • bool autoEdit () const
  • virtual bool seek ( int i, bool relative = FALSE )

Public Slots

  • virtual void refresh ()
  • virtual void insert ()
  • virtual void update ()
  • virtual void del ()
  • virtual void first ()
  • virtual void last ()
  • virtual void next ()
  • virtual void prev ()
  • virtual void readFields ()
  • virtual void writeFields ()
  • virtual void clearValues ()
  • void updateBoundary ()

Signals

  • void firstRecordAvailable ( bool available )
  • void lastRecordAvailable ( bool available )
  • void nextRecordAvailable ( bool available )
  • void prevRecordAvailable ( bool available )
  • void currentChanged ( const QSqlRecord * record )
  • void primeInsert ( QSqlRecord * buf )
  • void primeUpdate ( QSqlRecord * buf )
  • void primeDelete ( QSqlRecord * buf )
  • void beforeInsert ( QSqlRecord * buf )
  • void beforeUpdate ( QSqlRecord * buf )
  • void beforeDelete ( QSqlRecord * buf )
  • void cursorChanged ( QSqlCursor::Mode mode )

Properties

  • bool autoEdit - whether the browser automatically applies edits
  • bool boundaryChecking - whether boundary checking is active
  • bool confirmCancels - whether the browser confirms cancel operations
  • bool confirmDelete - whether the browser confirms deletions
  • bool confirmEdits - whether the browser confirms edit operations
  • bool confirmInsert - whether the data browser confirms insertions
  • bool confirmUpdate - whether the browser confirms updates
  • QString filter - the data browser's filter
  • bool readOnly - whether the browser is read-only
  • QStringList sort - the data browser's sort

Protected Members

  • virtual bool insertCurrent ()
  • virtual bool updateCurrent ()
  • virtual bool deleteCurrent ()
  • virtual bool currentEdited ()
  • virtual QSql::Confirm confirmEdit ( QSql::Op m )
  • virtual QSql::Confirm confirmCancel ( QSql::Op m )
  • virtual void handleError ( const QSqlError & error )

Detailed Description

The QDataBrowser class provides data manipulation and navigation for data entry forms.

A high-level API is provided to navigate through data records in a cursor, insert, update and delete records, and refresh data in the display.

If you want a read-only form to present database data use QDataView; if you want a table-based presentation of your data use QDataTable.

A QDataBrowser is used to associate a dataset with a form in much the same way as a QDataTable associates a dataset with a table. Once the data browser has been constructed it can be associated with a dataset with setSqlCursor(), and with a form with setForm(). Boundary checking, sorting and filtering can be set with setBoundaryChecking(), setSort() and setFilter(), respectively.

The insertCurrent() function reads the fields from the default form into the default cursor and performs the insert. The updateCurrent() and deleteCurrent() functions perform similarly to update and delete the current record respectively.

The user can be asked to confirm all edits with setConfirmEdits(). For more precise control use setConfirmInsert(), setConfirmUpdate(), setConfirmDelete() and setConfirmCancels(). Use setAutoEdit() to control the behaviour of the form when the user edits a record and then navigates.

The record set is navigated using first(), next(), prev(), last() and seek(). The form's display is updated with refresh(). When navigation takes place the firstRecordAvailable(), lastRecordAvailable(), nextRecordAvailable() and prevRecordAvailable() signals are emitted. When the cursor record is changed due to navigation the cursorChanged() signal is emitted.

If you want finer control of the insert, update and delete processes then you can use the low level functions to perform these operations as described below.

The form is populated with data from the database with readFields(). If the user is allowed to edit, (see setReadOnly()), write the form's data back to the cursor's edit buffer with writeFields(). You can clear the values in the form with clearValues(). Editing is performed as follows:

  • insert When the data browser enters insertion mode it emits the primeInsert() signal which you can connect to, for example to pre-populate fields. Call writeFields() to write the user's edits to the cursor's edit buffer then call insert() to insert the record into the database. The beforeInsert() signal is emitted just before the cursor's edit buffer is inserted into the database; connect to this for example, to populate fields such as an auto-generated primary key.
  • update For updates the primeUpdate() signal is emitted when the data browser enters update mode. After calling writeFields() call update() to update the record and connect to the beforeUpdate() signal to manipulate the user's data before the update takes place.
  • delete For deletion the primeDelete() signal is emitted when the data browser enters deletion mode. After calling writeFields() call del() to delete the record and connect to the beforeDelete() signal, for example to record an audit of the deleted record.

See also Database Classes.

Member Type Documentation

QDataBrowser::Boundary

This enum describes where the data browser is positioned.

The currently defined values are:

  • QDataBrowser::Unknown - the boundary cannot be determined (usually because there is no default cursor, or the default cursor is not active).
  • QDataBrowser::None - the browser is not positioned on a boundary, but it is positioned on a record somewhere in the middle.
  • QDataBrowser::BeforeBeginning - the browser is positioned before the first available record.
  • QDataBrowser::Beginning - the browser is positioned at the first record.
  • QDataBrowser::End - the browser is positioned at the last record.
  • QDataBrowser::AfterEnd - the browser is positioned after the last available record.

Member Function Documentation

QDataBrowser::QDataBrowser ( QWidget * parent = 0, const char * name = 0, WFlags fl = 0 )

Constructs a data browser which is a child of parent, with the name name and widget flags set to fl.

QDataBrowser::~QDataBrowser ()

Destroys the object and frees any allocated resources.

bool QDataBrowser::autoEdit () const

Returns TRUE if the browser automatically applies edits; otherwise returns FALSE. See the "autoEdit" property for details.

void QDataBrowser::beforeDelete ( QSqlRecord * buf ) [signal]

This signal is emitted just before the cursor's edit buffer is deleted from the database. The buf parameter points to the edit buffer being deleted. You might connect to this signal to capture some auditing information about the deletion.

void QDataBrowser::beforeInsert ( QSqlRecord * buf ) [signal]

This signal is emitted just before the cursor's edit buffer is inserted into the database. The buf parameter points to the edit buffer being inserted. You might connect to this signal to populate a generated primary key for example.

void QDataBrowser::beforeUpdate ( QSqlRecord * buf ) [signal]

This signal is emitted just before the cursor's edit buffer is updated in the database. The buf parameter points to the edit buffer being updated. You might connect to this signal to capture some auditing information about the update.

Boundary QDataBrowser::boundary ()

Returns an enum indicating the boundary status of the browser.

This is achieved by moving the default cursor and checking the position, however the current default form values will not be altered. After checking for the boundary, the cursor is moved back to its former position. See QDataBrowser::Boundary.

See also Boundary.

bool QDataBrowser::boundaryChecking () const

Returns TRUE if boundary checking is active; otherwise returns FALSE. See the "boundaryChecking" property for details.

void QDataBrowser::clearValues () [virtual slot]

Clears all the values in the form.

All the edit buffer field values are set to their 'zero state', e.g. 0 for numeric fields and "" for string fields. Then the widgets are updated using the property map. For example, a combobox that is property-mapped to integers would scroll to the first item. See the QSqlPropertyMap constructor for the default mappings of widgets to properties.

QSql::Confirm QDataBrowser::confirmCancel ( QSql::Op m ) [virtual protected]

Protected virtual function which returns a confirmation for cancelling an edit mode m. Derived classes can reimplement this function and provide their own confirmation dialog. The default implementation uses a message box which prompts the user to confirm the edit action.

bool QDataBrowser::confirmCancels () const

Returns TRUE if the browser confirms cancel operations; otherwise returns FALSE. See the "confirmCancels" property for details.

bool QDataBrowser::confirmDelete () const

Returns TRUE if the browser confirms deletions; otherwise returns FALSE. See the "confirmDelete" property for details.

QSql::Confirm QDataBrowser::confirmEdit ( QSql::Op m ) [virtual protected]

Protected virtual function which returns a confirmation for an edit of mode m. Derived classes can reimplement this function and provide their own confirmation dialog. The default implementation uses a message box which prompts the user to confirm the edit action.

bool QDataBrowser::confirmEdits () const

Returns TRUE if the browser confirms edit operations; otherwise returns FALSE. See the "confirmEdits" property for details.

bool QDataBrowser::confirmInsert () const

Returns TRUE if the data browser confirms insertions; otherwise returns FALSE. See the "confirmInsert" property for details.

bool QDataBrowser::confirmUpdate () const

Returns TRUE if the browser confirms updates; otherwise returns FALSE. See the "confirmUpdate" property for details.

void QDataBrowser::currentChanged ( const QSqlRecord * record ) [signal]

This signal is emitted whenever the current cursor position changes. The record parameter points to the contents of the current cursor's record.

bool QDataBrowser::currentEdited () [virtual protected]

Returns TRUE if the form's edit buffer differs from the current cursor buffer, otherwise FALSE is returned.

void QDataBrowser::cursorChanged ( QSqlCursor::Mode mode ) [signal]

This signal is emitted whenever the cursor record was changed due to navigation. The mode parameter is the edit that just took place, e.g. Insert, Update or Delete. See QSqlCursor::Mode.

void QDataBrowser::del () [virtual slot]

Performs a delete operation on the data browser's cursor. If there is no default cursor or no default form, nothing happens.

Otherwise, the following happens:

The current form's record is deleted from the database, providing that the data browser is not in insert mode. If the data browser is actively inserting a record (see insert()), the insert action is cancelled, and the browser navigates to the last valid record that was current. If there is an error, handleError() is called.

bool QDataBrowser::deleteCurrent () [virtual protected]

Performs a delete on the default cursor using the values from the default form and updates the default form. If there is no default form or no default cursor, nothing happens. If the deletion was successful, the cursor is repositioned to the nearest record and TRUE is returned. The nearest record is the next record if there is one otherwise the previous record if there is one. If an error occurred during the deletion from the database, handleError() is called and FALSE is returned.

See also cursor, form() and handleError().

QString QDataBrowser::filter () const

Returns the data browser's filter. See the "filter" property for details.

void QDataBrowser::first () [virtual slot]

Moves the default cursor to the first record and refreshes the default form to display this record. If there is no default form or no default cursor, nothing happens. If the data browser successfully navigated to the first record, the default cursor is primed for update and the primeUpdate() signal is emitted.

If the browser is already positioned on the first record nothing happens.

void QDataBrowser::firstRecordAvailable ( bool available ) [signal]

This signal is emitted whenever the position of the cursor changes. The available parameter indicates whether or not the first record in the default cursor is available.

QSqlForm * QDataBrowser::form ()

Returns a pointer to the data browser's default form or 0 if no form has been set.

void QDataBrowser::handleError ( const QSqlError & error ) [virtual protected]

Virtual function which handles the error error. The default implementation warns the user with a message box.

void QDataBrowser::insert () [virtual slot]

Performs an insert operation on the data browser's cursor. If there is no default cursor or no default form, nothing happens.

If auto-editing is on (see setAutoEdit()), the following happens:

  • If the browser is already actively inserting a record, the current form's data is inserted into the database.
  • If the browser is not inserting a record, but the current record was changed by the user, the record is updated in the database with the current form's data (i.e. with the changes).

If there is an error handling any of the above auto-edit actions, handleError() is called and no insert or update is performed.

If no error occurred, or auto-editing is not enabled, the data browser begins actively inserting a record into the database by performing the following actions:

  • The default cursor is primed for insert using QSqlCursor::primeInsert().
  • The primeInsert() signal is emitted.
  • The form is updated with the values in the default cursor's. edit buffer so that the user can fill in the values to be inserted.

bool QDataBrowser::insertCurrent () [virtual protected]

Reads the fields from the default form into the default cursor and performs an insert on the default cursor. If there is no default form or no default cursor, nothing happens. If an error occurred during the insert into the database, handleError() is called and FALSE is returned. If the insert was successfull, the cursor is refreshed and relocated to the newly inserted record, the cursorChanged() signal is emitted, and TRUE is returned.

See also cursorChanged(), sqlCursor(), form() and handleError().

bool QDataBrowser::isReadOnly () const

Returns TRUE if the browser is read-only; otherwise returns FALSE. See the "readOnly" property for details.

void QDataBrowser::last () [virtual slot]

Moves the default cursor to the last record and refreshes the default form to display this record. If there is no default form or no default cursor, nothing happens. If the data browser successfully navigated to the last record, the default cursor is primed for update and the primeUpdate() signal is emitted.

If the browser is already positioned on the last record nothing happens.

void QDataBrowser::lastRecordAvailable ( bool available ) [signal]

This signal is emitted whenever the position of the cursor changes. The available parameter indicates whether or not the last record in the default cursor is available.

void QDataBrowser::next () [virtual slot]

Moves the default cursor to the next record and refreshes the default form to display this record. If there is no default form or no default cursor, nothing happens. If the data browser successfully navigated to the next record, the default cursor is primed for update and the primeUpdate() signal is emitted.

If the browser is positioned on the last record nothing happens.

void QDataBrowser::nextRecordAvailable ( bool available ) [signal]

This signal is emitted whenever the position of the cursor changes. The available parameter indicates whether or not the next record in the default cursor is available.

void QDataBrowser::prev () [virtual slot]

Moves the default cursor to the previous record and refreshes the default form to display this record. If there is no default form or no default cursor, nothing happens. If the data browser successfully navigated to the previous record, the default cursor is primed for update and the primeUpdate() signal is emitted.

If the browser is positioned on the first record nothing happens.

void QDataBrowser::prevRecordAvailable ( bool available ) [signal]

This signal is emitted whenever the position of the cursor changes. The available parameter indicates whether or not the previous record in the default cursor is available.

void QDataBrowser::primeDelete ( QSqlRecord * buf ) [signal]

This signal is emitted when the data browser enters deletion mode. The buf parameter points to the record buffer being deleted. (Note that QSqlCursor::primeDelete() is not called on the default cursor, as this would corrupt values in the form.) Connect to this signal in order to, for example, save a copy of the deleted record for auditing purposes.

See also del().

void QDataBrowser::primeInsert ( QSqlRecord * buf ) [signal]

This signal is emitted when the data browser enters insertion mode. The buf parameter points to the record buffer that is to be inserted. Connect to this signal to, for example, prime the record buffer with default data values, auto-numbered fields etc. (Note that QSqlCursor::primeInsert() is not called on the default cursor, as this would corrupt values in the form.)

See also insert().

void QDataBrowser::primeUpdate ( QSqlRecord * buf ) [signal]

This signal is emitted when the data browser enters update mode. Note that during naviagtion (first(), last(), next(), prev()), each record that is shown in the default form is primed for update. The buf parameter points to the record buffer being updated. (Note that QSqlCursor::primeUpdate() is not called on the default cursor, as this would corrupt values in the form.) Connect to this signal in order to, for example, keep track of which records have been updated, perhaps for auditing purposes.

See also update().

void QDataBrowser::readFields () [virtual slot]

Reads the fields from the default cursor's edit buffer and displays them in the form. If there is no default cursor or no default form, nothing happens.

void QDataBrowser::refresh () [virtual slot]

Refreshes the data browser's data using the default cursor. The browser's current filter and sort are applied if they have been set.

See also filter and sort.

bool QDataBrowser::seek ( int i, bool relative = FALSE ) [virtual]

Moves the default cursor to the record specified by the index i and refreshes the default form to display this record. If there is no default form or no default cursor, nothing happens. If relative is TRUE (the default is FALSE), the cursor is moved relative to its current position. If the data browser successfully navigated to the desired record, the default cursor is primed for update and the primeUpdate() signal is emitted.

If the browser is already positioned on the desired record nothing happens.

void QDataBrowser::setAutoEdit ( bool autoEdit ) [virtual]

Sets whether the browser automatically applies edits to autoEdit. See the "autoEdit" property for details.

void QDataBrowser::setBoundaryChecking ( bool active )

Sets whether boundary checking is active to active. See the "boundaryChecking" property for details.

void QDataBrowser::setConfirmCancels ( bool confirm ) [virtual]

Sets whether the browser confirms cancel operations to confirm. See the "confirmCancels" property for details.

void QDataBrowser::setConfirmDelete ( bool confirm ) [virtual]

Sets whether the browser confirms deletions to confirm. See the "confirmDelete" property for details.

void QDataBrowser::setConfirmEdits ( bool confirm ) [virtual]

Sets whether the browser confirms edit operations to confirm. See the "confirmEdits" property for details.

void QDataBrowser::setConfirmInsert ( bool confirm ) [virtual]

Sets whether the data browser confirms insertions to confirm. See the "confirmInsert" property for details.

void QDataBrowser::setConfirmUpdate ( bool confirm ) [virtual]

Sets whether the browser confirms updates to confirm. See the "confirmUpdate" property for details.

void QDataBrowser::setFilter ( const QString & filter )

Sets the data browser's filter to filter. See the "filter" property for details.

void QDataBrowser::setForm ( QSqlForm * form ) [virtual]

Sets the browser's default form to form. The cursor and all navigation and data manipulation functions that the browser provides become available to the form.

void QDataBrowser::setReadOnly ( bool active ) [virtual]

Sets whether the browser is read-only to active. See the "readOnly" property for details.

void QDataBrowser::setSort ( const QStringList & sort )

Sets the data browser's sort to sort. See the "sort" property for details.

void QDataBrowser::setSort ( const QSqlIndex & sort )

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

Sets the data browser's sort to the QSqlIndex sort. To apply the new sort, use refresh().

void QDataBrowser::setSqlCursor ( QSqlCursor * cursor, bool autoDelete = FALSE ) [virtual]

Sets the default cursor used by the data browser to cursor. If autoDelete is TRUE (the default is FALSE), the data browser takes ownership of the cursor pointer, which will be deleted when the browser is destroyed, or when setSqlCursor() is called again. To activate the cursor use refresh(). The cursor's edit buffer is used in the default form to browse and edit records.

See also sqlCursor(), form() and setForm().

QStringList QDataBrowser::sort () const

Returns the data browser's sort. See the "sort" property for details.

QSqlCursor * QDataBrowser::sqlCursor () const

Returns a pointer to the default cursor used for navigation, or 0 if there is no default cursor.

See also setSqlCursor().

void QDataBrowser::update () [virtual slot]

Performs an update operation on the data browser's cursor.

If there is no default cursor or no default form, nothing happens. Otherwise, the following happens:

If the data browser is actively inserting a record (see insert()), that record is inserted into the database using insertCurrent(). Otherwise, the database is updated with the current form's data using updateCurrent(). If there is an error handling either action, handleError() is called.

void QDataBrowser::updateBoundary () [slot]

If boundaryChecking() is TRUE, checks the boundary of the current default cursor and emits signals which indicate the position of the cursor.

bool QDataBrowser::updateCurrent () [virtual protected]

Reads the fields from the default form into the default cursor and performs an update on the default cursor. If there is no default form or no default cursor, nothing happens. If an error occurred during the update on the database, handleError() is called and FALSE is returned. If the update was successfull, the cursor is refreshed and relocated to the updated record, the cursorChanged() signal is emitted, and TRUE is returned.

See also cursor, form() and handleError().

void QDataBrowser::writeFields () [virtual slot]

Writes the form's data to the default cursor's edit buffer. If there is no default cursor or no default form, nothing happens.

Property Documentation

bool autoEdit

This property holds whether the browser automatically applies edits.

The default value for this property is TRUE. When the user begins an insertion or an update on a form there are two possible outcomes when they navigate to another record:

  • the insert or update is is performed -- this occurs if autoEdit is TRUE
  • the insert or update is discarded -- this occurs if autoEdit is FALSE

Set this property's value with setAutoEdit() and get this property's value with autoEdit().

bool boundaryChecking

This property holds whether boundary checking is active.

When boundary checking is active (the default), signals are emitted indicating the current position of the default cursor.

See also boundary().

Set this property's value with setBoundaryChecking() and get this property's value with boundaryChecking().

bool confirmCancels

This property holds whether the browser confirms cancel operations.

If this property is TRUE, all cancels must be confirmed by the user through a message box (this behavior can be changed by overriding the confirmCancel() function), otherwise all cancels occur immediately. The default is FALSE.

See also confirmEdits and confirmCancel().

Set this property's value with setConfirmCancels() and get this property's value with confirmCancels().

bool confirmDelete

This property holds whether the browser confirms deletions.

If this property is TRUE, the browser confirms deletions, otherwise deletions happen immediately.

See also confirmCancels, confirmEdits, confirmUpdate, confirmInsert and confirmEdit().

Set this property's value with setConfirmDelete() and get this property's value with confirmDelete().

bool confirmEdits

This property holds whether the browser confirms edit operations.

If this property is TRUE, the browser confirms all edit operations (insertions, updates and deletions), otherwise all edit operations happen immediately. Confirmation is achieved by presenting the user with a message box -- this behavior can be changed by reimplementing the confirmEdit() function,

See also confirmEdit(), confirmCancels, confirmInsert, confirmUpdate and confirmDelete.

Set this property's value with setConfirmEdits() and get this property's value with confirmEdits().

bool confirmInsert

This property holds whether the data browser confirms insertions.

If this property is TRUE, the browser confirms insertions, otherwise insertions happen immediately.

See also confirmCancels, confirmEdits, confirmUpdate, confirmDelete and confirmEdit().

Set this property's value with setConfirmInsert() and get this property's value with confirmInsert().

bool confirmUpdate

This property holds whether the browser confirms updates.

If this property is TRUE, the browser confirms updates, otherwise updates happen immediately.

See also confirmCancels, confirmEdits, confirmInsert, confirmDelete and confirmEdit().

Set this property's value with setConfirmUpdate() and get this property's value with confirmUpdate().

QString filter

This property holds the data browser's filter.

The filter applies to the data shown in the browser. Call refresh() to apply the new filter. A filter is a string containing a SQL WHERE clause without the WHERE keyword, e.g. "id>1000", "name LIKE 'A%'".

There is no default filter.

See also sort.

Set this property's value with setFilter() and get this property's value with filter().

bool readOnly

This property holds whether the browser is read-only.

The default is FALSE, i.e. data can be edited. If the data browser is read-only, no database edits will be allowed.

Set this property's value with setReadOnly() and get this property's value with isReadOnly().

QStringList sort

This property holds the data browser's sort.

The data browser's sort affects the order in which records are viewed in the browser. Call refresh() to apply the new sort.

When retrieving the sort property, a string list is returned in the form 'fieldname order', e.g. 'id ASC', 'surname DESC'.

There is no default sort.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDataBrowser.sort();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

Set this property's value with setSort() and get this property's value with sort().

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


qdatabrowser.h Include File

qdatabrowser.h

This is the verbatim text of the qdatabrowser.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QDataBrowser class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATABROWSER_H
#define QDATABROWSER_H

#ifndef QT_H
#include "qwidget.h"
#include "qstring.h"
#include "qstringlist.h"
#include "qsql.h"
#include "qsqlindex.h"
#include "qsqlcursor.h"
#include "qsqlerror.h"
#endif // QT_H

#ifndef QT_NO_SQL

class QSqlForm;
class QDataBrowserPrivate;

class Q_EXPORT QDataBrowser : public QWidget
{
    Q_OBJECT
    Q_PROPERTY( bool boundaryChecking READ boundaryChecking WRITE setBoundaryChecking )
    Q_PROPERTY( QString filter READ filter WRITE setFilter )
    Q_PROPERTY( QStringList sort READ sort WRITE setSort )
    Q_PROPERTY( bool confirmEdits READ confirmEdits WRITE setConfirmEdits )
    Q_PROPERTY( bool confirmInsert READ confirmInsert WRITE setConfirmInsert )
    Q_PROPERTY( bool confirmUpdate READ confirmUpdate WRITE setConfirmUpdate )
    Q_PROPERTY( bool confirmDelete READ confirmDelete WRITE setConfirmDelete )
    Q_PROPERTY( bool confirmCancels READ confirmCancels WRITE setConfirmCancels )
    Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly )
    Q_PROPERTY( bool autoEdit READ autoEdit WRITE setAutoEdit )

public:
    QDataBrowser( QWidget* parent=0, const char* name=0, WFlags fl = 0 );
    ~QDataBrowser();

    enum Boundary {
    Unknown,
    None,
    BeforeBeginning,
    Beginning,
    End,
    AfterEnd
    };

    Boundary boundary();
    void setBoundaryChecking( bool active );
    bool boundaryChecking() const;

    void setSort( const QSqlIndex& sort );
    void setSort( const QStringList& sort );
    QStringList  sort() const;
    void setFilter( const QString& filter );
    QString filter() const;
    virtual void setSqlCursor( QSqlCursor* cursor, bool autoDelete = FALSE );
    QSqlCursor* sqlCursor() const;
    virtual void setForm( QSqlForm* form );
    QSqlForm* form();

    virtual void setConfirmEdits( bool confirm );
    virtual void setConfirmInsert( bool confirm );
    virtual void setConfirmUpdate( bool confirm );
    virtual void setConfirmDelete( bool confirm );
    virtual void setConfirmCancels( bool confirm );
    bool confirmEdits() const;
    bool confirmInsert() const;
    bool confirmUpdate() const;
    bool confirmDelete() const;
    bool confirmCancels() const;

    virtual void setReadOnly( bool active );
    bool isReadOnly() const;
    virtual void setAutoEdit( bool autoEdit );
    bool autoEdit() const;

    virtual bool seek( int i, bool relative = FALSE );

signals:
    void firstRecordAvailable( bool available );
    void lastRecordAvailable( bool available );
    void nextRecordAvailable( bool available );
    void prevRecordAvailable( bool available );

    void currentChanged( const QSqlRecord* record );
    void primeInsert( QSqlRecord* buf );
    void primeUpdate( QSqlRecord* buf );
    void primeDelete( QSqlRecord* buf );
    void beforeInsert( QSqlRecord* buf );
    void beforeUpdate( QSqlRecord* buf );
    void beforeDelete( QSqlRecord* buf );
    void cursorChanged( QSqlCursor::Mode mode );

public slots:
    virtual void refresh();

    virtual void insert();
    virtual void update();
    virtual void del();

    virtual void first();
    virtual void last();
    virtual void next();
    virtual void prev();

    virtual void readFields();
    virtual void writeFields();
    virtual void clearValues();

    void updateBoundary();

protected:
    virtual bool insertCurrent();
    virtual bool updateCurrent();
    virtual bool deleteCurrent();
    virtual bool currentEdited();

    virtual QSql::Confirm confirmEdit( QSql::Op m );
    virtual QSql::Confirm confirmCancel( QSql::Op m );

    virtual void handleError( const QSqlError& error );

private:
    typedef bool (QSqlCursor::*Nav)();
    bool preNav();
    void postNav( bool primeUpd );
    void nav( Nav nav );
    QDataBrowserPrivate* d;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDataBrowser Member List

Complete Member List for QDataBrowser

This is the complete list of member functions for QDataBrowser, including inherited members.

  • QDataBrowser()
  • ~QDataBrowser()
  • acceptDrops()
  • adjustSize()
  • autoEdit()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • beforeDelete()
  • beforeInsert()
  • beforeUpdate()
  • blockSignals()
  • boundary()
  • boundaryChecking()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearValues()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • confirmCancel()
  • confirmCancels()
  • confirmDelete()
  • confirmEdit()
  • confirmEdits()
  • confirmInsert()
  • confirmUpdate()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • currentChanged()
  • currentEdited()
  • cursor()
  • cursorChanged()
  • customEvent()
  • customWhatsThis()
  • del()
  • deleteCurrent()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • filter()
  • find()
  • first()
  • firstRecordAvailable()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • form()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • handleError()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertChild()
  • insertCurrent()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isReadOnly()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • last()
  • lastRecordAvailable()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • next()
  • nextRecordAvailable()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • prev()
  • prevRecordAvailable()
  • primeDelete()
  • primeInsert()
  • primeUpdate()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • readFields()
  • recreate()
  • rect()
  • refresh()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • seek()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoEdit()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBoundaryChecking()
  • setCaption()
  • setConfirmCancels()
  • setConfirmDelete()
  • setConfirmEdits()
  • setConfirmInsert()
  • setConfirmUpdate()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFilter()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setForm()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setReadOnly()
  • setSizeIncrement()
  • setSizePolicy()
  • setSort()
  • setSqlCursor()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sort()
  • sqlCursor()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateBoundary()
  • updateCurrent()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • writeFields()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDataPump Class

QDataPump Class Reference
[obsolete]

The QDataPump class moves data from a QDataSource to a QDataSink during event processing. More...

#include <qasyncio.h>

Inherits QObject.

List of all member functions.

Public Members

  • QDataPump ( QDataSource * data_source, QDataSink * data_sink )

Detailed Description

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

The QDataPump class moves data from a QDataSource to a QDataSink during event processing.

For a QDataSource to provide data to a QDataSink, a controller must exist to examine the QDataSource::readyToSend() and QDataSink::readyToReceive() methods and respond to the QASyncIO::activate() signal of the source and sink. One very useful way to do this is interleaved with other event processing. QDataPump provides this - create a pipe between a source and a sink, and data will be moved during subsequent event processing.

Note that each source can only provide data to one sink and each sink can only receive data from one source (although it is quite possible to write a multiplexing sink that is multiple sources).

Member Function Documentation

QDataPump::QDataPump ( QDataSource * data_source, QDataSink * data_sink )

Constructs a QDataPump to move data from a given data_source to a given data_sink.

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


QDataPump Member List

Complete Member List for QDataPump

This is the complete list of member functions for QDataPump, including inherited members.

  • QDataPump()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QDataSink Class

QDataSink Class Reference
[obsolete]

The QDataSink class is an asynchronous consumer of data. More...

#include <qasyncio.h>

Inherits QAsyncIO.

List of all member functions.

Public Members

  • virtual int readyToReceive () = 0
  • virtual void receive ( const uchar *, int count ) = 0
  • virtual void eof () = 0
  • void maybeReady ()

Detailed Description

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

The QDataSink class is an asynchronous consumer of data.

A data sink is an object which receives data from some source in an asynchronous manner. This means that at some time not determined by the data sink, blocks of data are given to it from processing. The data sink is able to limit the maximum size of such blocks which it is currently able to process.

See also QAsyncIO, QDataSource and QDataPump.

Member Function Documentation

void QDataSink::eof () [pure virtual]

This function will be called when no more data is available for processing.

void QDataSink::maybeReady ()

This should be called whenever readyToReceive() might have become non-zero. It is merely calls QAsyncIO::ready() if readyToReceive() is non-zero.

int QDataSink::readyToReceive () [pure virtual]

The data sink should return a value indicating how much data it is ready to consume. This may be 0.

void QDataSink::receive ( const uchar *, int count ) [pure virtual]

This function is called to provide data for the data sink. The count will be no more than the amount indicated by the most recent call to readyToReceive(). The sink must use all the provided data.

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


QDataSink Member List

Complete Member List for QDataSink

This is the complete list of member functions for QDataSink, including inherited members.

  • connect()
  • eof()
  • maybeReady()
  • ready()
  • readyToReceive()
  • receive()


QDataSource Class

QDataSource Class Reference
[obsolete]

The QDataSource class is an asynchronous producer of data. More...

#include <qasyncio.h>

Inherits QAsyncIO.

Inherited by QIODeviceSource.

List of all member functions.

Public Members

  • virtual int readyToSend () = 0
  • virtual void sendTo ( QDataSink *, int count ) = 0
  • void maybeReady ()
  • virtual bool rewindable () const
  • virtual void enableRewind ( bool on )
  • virtual void rewind ()

Detailed Description

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

The QDataSource class is an asynchronous producer of data.

A data source is an object which provides data from some source in an asynchronous manner. This means that at some time not determined by the data source, blocks of data will be taken from it for processing. The data source is able to limit the maximum size of such blocks which it is currently able to provide.

See also QAsyncIO, QDataSink and QDataPump.

Member Function Documentation

void QDataSource::enableRewind ( bool on ) [virtual]

If this function is called with on set to TRUE, and rewindable() is TRUE, then the data source must take measures to allow the rewind() function to subsequently operate as described. If rewindable() is FALSE, the function should call QDataSource::enableRewind(), which aborts with a qFatal() error.

For example, a network connection may choose to use a disk cache of input only if rewinding is enabled before the first buffer-full of data is discarded, returning FALSE in rewindable() if that first buffer is discarded.

Reimplemented in QIODeviceSource.

void QDataSource::maybeReady ()

This should be called whenever readyToSend() might have become non-zero. It is merely calls QAsyncIO::ready() if readyToSend() is non-zero.

int QDataSource::readyToSend () [pure virtual]

The data source should return a value indicating how much data it is ready to provide. This may be 0. If the data source knows it will never be able to provide any more data (until after a rewind()), it may return -1.

Reimplemented in QIODeviceSource.

void QDataSource::rewind () [virtual]

This function rewinds the data source. This may only be called if enableRewind(TRUE) has been previously called.

Reimplemented in QIODeviceSource.

bool QDataSource::rewindable () const [virtual]

This function should return TRUE if the data source can be rewound.

The default returns FALSE.

Reimplemented in QIODeviceSource.

void QDataSource::sendTo ( QDataSink *, int count ) [pure virtual]

This function is called to extract data from the source, by sending it to the given data sink. The count will be no more than the amount indicated by the most recent call to readyToSend(). The source must use all the provided data, and the sink will be prepared to accept at least this much data.

Reimplemented in QIODeviceSource.

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


QDataSource Member List

Complete Member List for QDataSource

This is the complete list of member functions for QDataSource, including inherited members.

  • connect()
  • enableRewind()
  • maybeReady()
  • ready()
  • readyToSend()
  • rewind()
  • rewindable()
  • sendTo()


QDataStream类

QDataStream类参考

QDataStream类提供了二进制数据到QIODevice的串行化。 详情请见……

#include <qdatastream.h>

所有成员函数的列表。

公有成员

  • QDataStream ()
  • QDataStream ( QIODevice * d )
  • QDataStream ( QByteArray a, int mode )
  • virtual ~QDataStream ()
  • QIODevice * device () const
  • void setDevice ( QIODevice * d )
  • void unsetDevice ()
  • bool atEnd () const
  • bool eof () const (obsolete)
  • enum ByteOrder { BigEndian, LittleEndian }
  • int byteOrder () const
  • void setByteOrder ( int bo )
  • bool isPrintableData () const
  • void setPrintableData ( bool enable )
  • int version () const
  • void setVersion ( int v )
  • QDataStream & operator>> ( Q_INT8 & i )
  • QDataStream & operator>> ( Q_UINT8 & i )
  • QDataStream & operator>> ( Q_INT16 & i )
  • QDataStream & operator>> ( Q_UINT16 & i )
  • QDataStream & operator>> ( Q_INT32 & i )
  • QDataStream & operator>> ( Q_UINT32 & i )
  • QDataStream & operator>> ( Q_LONG & i )
  • QDataStream & operator>> ( Q_ULONG & i )
  • QDataStream & operator>> ( float & f )
  • QDataStream & operator>> ( double & f )
  • QDataStream & operator>> ( char *& s )
  • QDataStream & operator<< ( Q_INT8 i )
  • QDataStream & operator<< ( Q_UINT8 i )
  • QDataStream & operator<< ( Q_INT16 i )
  • QDataStream & operator<< ( Q_UINT16 i )
  • QDataStream & operator<< ( Q_INT32 i )
  • QDataStream & operator<< ( Q_UINT32 i )
  • QDataStream & operator<< ( Q_LONG i )
  • QDataStream & operator<< ( Q_ULONG i )
  • QDataStream & operator<< ( float f )
  • QDataStream & operator<< ( double f )
  • QDataStream & operator<< ( const char * s )
  • QDataStream & readBytes ( char *& s, uint & l )
  • QDataStream & readRawBytes ( char * s, uint len )
  • QDataStream & writeBytes ( const char * s, uint len )
  • QDataStream & writeRawBytes ( const char * s, uint len )

详细描述

QDataStream类提供了二进制数据到QIODevice的串行化。

数据流是一个编码信息的二进制流，它与主机的操作系统、CPU或字节顺序100％的没有关系。比如一个在PC的Windows下写的数据流可以在Sun SPARC的Solaris中读出。

QTextStream. 你也可以使用一个数据流来读/写原始的未编码的二进制数据。如果你想“解析”输入流，请参考QTextStream。

QDataStream类实现了基本类型的串行化，比如char、short、int、char*等等。更加复杂的类型的串行化是通过把数据分解为简单单元来实现的。

数据流和QIODevice合作非常紧密。QIODevice描述了一个可以从中读数据和向它写数据的输入/输出介质。QFile类就是一个IO设备的例子。

实例（向一个流中写二进制数据）：

    QFile f( "file.dta" );
    f.open( IO_WriteOnly );
    QDataStream s( &f );    // 我们将把数据串行化至文件f
    s << "the answer is";   // 串行化一个字符串
    s << (Q_INT32)42;       // 串行化一个整数

实例（从一个流中读二进制数据）：

    QFile f( "file.dta" );
    f.open( IO_ReadOnly );
    QDataStream s( &f );    // 从文件f中读取串行化的数据
    QString str;
    Q_INT32 a;
    s >> str >> a;          // 提取出“the answer is”和42

每一个要写到流中的项都被写成一种预定义的二进制格式，这种格式取决于这个项的类型。Qt中支持的类型有QBrush、QColor、QDateTime、QFont、QPixmap、QString、QVariant和其它一些。支持数据流的所有的Qt类型的列表请看QDataStream操作符的格式。

举个例子，char*字符串被写做一个等于包括NUL字节的字符串长度的32位整数，后面跟着字符串中包括NUL字节的所有字节。当读取char*字符串的时候，先读4个字节创建一个32位长度值，然后读取包括NUL的这么多的字节到char*字符串中。

初始的IODevice通常在构造函数中设置，但是也可以使用setDevice()来改变。如果你到达了数据的终点（或者如果没有IODevice被设置），atEnd()将返回真。

如果你希望数据和以前版本的Qt一致，请使用setVersion()。

如果你希望数据是人们可读的，比如，用于调试，你可以用setPrintableData()设置数据流为可打印数据模式。然后这个数据写起来慢一些，并且膨胀起来但已经是人们可以读取的格式了。

如果你正在生成一种新的二进制数据格式，比如是你的应用程序创建的一种文档的文件格式，你可以使用QDataStream来把数据写成一种可移植的格式。通常，你可以写一个包含幻数字符串和版本信息的简要的头信息，这样可以给你以后的扩展提供一定的空间。比如：

    QFile f( "file.xxx" );
    f.open( IO_WriteOnly );
    QDataStream s( &f );

    // 写一个含有“幻数”和版本号的头
    s << (Q_UINT32)0xa0b0c0d0;
    s << (Q_INT32)123;

    // 写数据
    s << [lots of interesting data]

然后这样读：

    QFile f( "file.xxx" );
    f.open( IO_ReadOnly );
    QDataStream s( &f );

    // 读取并检查头
    Q_UINT32 magic;
    s >> magic;
    if ( magic != 0xa0b0c0d0 )
        return XXX_BAD_FILE_FORMAT;

    // 读取版本号
    Q_INT32 version;
    s >> version;
    if ( version < 100 )
        return XXX_BAD_FILE_TOO_OLD;
    if ( version > 123 )
        return XXX_BAD_FILE_TOO_NEW;
    if ( version <= 110 )
        s.setVersion(1);

    // 读取数据
    s >> [很多有趣的数据];
    if ( version > 120 )
        s >> [在1.2版中的新数据XXX];
    s >> [其它有趣的数据];

当你串行化数据的时候，你可以选择你要使用的字节顺序。默认的设置是高字节在前。把它改变为低字节在前会破坏可移植性（除非读取程序也是用低字节在前）。我们建议你使用默认设置，除非你有特殊需要。

读写原始二进制数据

你也许希望把你自己的原始二进制数据直接写到数据流中，或者从数据流中直接读取它们。数据可以使用readRawBytes()从流中读取到一个预先分配好的char*。同样地也可以使用writeRawBytes()把数据写到流中。注意，任何数据的编码/解码就只能由你自己来完成了。

一对相似的函数readBytes()和writeBytes()。它们与操作原始数据的那两个的区别是：readBytes()先读取可读的数据长度到一个Q_UINT32，然后读取这个数量的字节到已经预先分配空间的char*；writeBytes()写一个包含数据长度的Q_UNIT32，然后再是数据。注意任何数据的编码/解码（除了长度Q_UINT32）都必须由你自己来做。

也可以参考QTextStream、QVariant和输入/输出和网络。

成员类型文档

QDataStream::ByteOrder

读/写数据时使用的字节顺序。

  • QDataStream::BigEndian - 高位在前（默认的）
  • QDataStream::LittleEndian - 低位在前

成员函数文档

QDataStream::QDataStream ()

构造一个没有IO设备的数据流。

也可以参考setDevice()。

QDataStream::QDataStream ( QIODevice * d )

构造一个使用IO设备d的数据流。

警告：如果你使用QSocket或QSocketDevice来作为IO设备d进行读数据，为了确保操作能够成功地执行，你必须确认在套接字提供了足够的数据，QDataStream没有任何方法来处理和恢复这种读取缺少地情况。

也可以参考setDevice() and device().

QDataStream::QDataStream ( QByteArray a, int mode )

构造一个通过内置的QBuffer设备来操作一个字节数组a的数据流。mode就是QIODevice::mode()，通常不是IO_ReadOnly就是IO_WriteOnly。

实例：

    static char bindata[] = { 231, 1, 44, ... };
    QByteArray a;
    a.setRawData( bindata, sizeof(bindata) );   // a指向bindata
    QDataStream s( a, IO_ReadOnly );            // 打开a的数据
    s >> [something];                           // 读取原始的bindata
    a.resetRawData( bindata, sizeof(bindata) ); // 完成

QByteArray::setRawData()函数不是提供给没有经验的人的。

QDataStream::~QDataStream () [虚]

销毁这个数据流。

析构函数对当前的IO设备没有任何效果，除非他是一个通过构造函数传递的一个处理QByteArray的内部IO设备，这种情况下，内部IO设备被销毁。。

bool QDataStream::atEnd () const

如果IO设备已经到达终点（流或文件的终点），或者如果没有IO设备被设置，返回真，否则返回假，比如，如果IO设备当前位置在终点之前。

也可以参考QIODevice::atEnd()。

int QDataStream::byteOrder () const

返回当前字节顺序设置——不是BigEndian就是LittleEndian。

也可以参考setByteOrder()。

QIODevice * QDataStream::device () const

返回当前设置的IO设备。

也可以参考setDevice()和unsetDevice()。

bool QDataStream::eof () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

如果IO设备到达终点（流或文件的终点），或者如果没有IO设备被设置，返回真。

如果当前的IO的读写位置在终点之前，返回假。

也可以参考QIODevice::atEnd()。

bool QDataStream::isPrintableData () const

如果可打印数据标记已经被设定，返回真。

也可以参考setPrintableData()。

QDataStream & QDataStream::operator<< ( Q_INT8 i )

写一个有符号的字节i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_UINT8 i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个无符号的字节i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_INT16 i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个有符号的16位整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_UINT16 i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个无符号的16位整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_INT32 i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个有符号的32位整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_UINT32 i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个无符号的32位整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_LONG i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个有符号的，长度为系统字长度的整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( Q_ULONG i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个无符号的，长度为系统字长度的整数i到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( float f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个使用标准IEEE754格式的32位浮点数f到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( double f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个使用标准IEEE754格式的64位浮点数f到流中并返回流的引用。

QDataStream & QDataStream::operator<< ( const char * s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个以“\0”结尾的字符串s到流中并返回流的引用。

这个字符串是使用writeBytes()串行化的。

QDataStream & QDataStream::operator>> ( Q_INT8 & i )

从流中读取一个有符号的字节到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_UINT8 & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的字节到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_INT16 & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个有符号的16位整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_UINT16 & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的16位整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_INT32 & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个有符号的32位整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_UINT32 & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的32位整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_LONG & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个有符号的，长度为系统字长度的整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( Q_ULONG & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的，长度为系统字长度的整数到i并返回流的引用。

QDataStream & QDataStream::operator>> ( float & f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个使用标准IEEE754格式的32位浮点数到f并返回流的引用。

QDataStream & QDataStream::operator>> ( double & f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个使用标准IEEE754格式的64位浮点数到f并返回流的引用。

QDataStream & QDataStream::operator>> ( char *& s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个以“\0”结尾的字符串到s并返回流的引用。

存放这个字符串的空间是使用new来分配的——调用者必须使用delete[]来销毁它。

QDataStream & QDataStream::readBytes ( char *& s, uint & l )

从流中读取缓存s并返回流的引用。

这个缓存s是使用new来分配的。需要使用delete[]来销毁它。如果长度为0或者s没能被分配，s就被设置为0。

l参数将被设置为缓存的长度。

串行化格式首先是一个Q_UINT32长度的说明符，然后是l字节的数据。注意数据不是编码的。

也可以参考readRawBytes()和writeBytes()。

QDataStream & QDataStream::readRawBytes ( char * s, uint len )

从流中读取len字节到s并返回流的引用。

这个缓存s必须被预先分配。数据不是编码的。

也可以参考readBytes()、QIODevice::readBlock()和writeRawBytes()。

void QDataStream::setByteOrder ( int bo )

设置串行化字节顺序为bo。

bo参数可以是QDataStream::BigEndian或QDataStream::LittleEndian。

默认设置是高字节在前。我们强烈建议你保留这个设置，除非你有特殊需要。

也可以参考byteOrder()。

void QDataStream::setDevice ( QIODevice * d )

设置IO设备为d。

也可以参考device()和unsetDevice()。

void QDataStream::setPrintableData ( bool enable )

设置（如果enable为真）或者清空可打印数据标记。

如果这个标记被设置，写函数将生成由可打印字符（7位ASCII码）的输出。

我们建议只有在调试的情况下打开可打印数据设置（它比较慢并且生成了更多的输出）。

void QDataStream::setVersion ( int v )

设置数据串行化格式的版本号。

如果你只使用当前版本的Qt，你不需要设置这个版本号。

为了提供新的功能，在一些Qt的版本中，一些Qt类的数据流串行化格式变化了。如果你想读较早版本Qt中创建的数据，或者写可供较早版本Qt编译的程序能够读的数据，请使用这个函数来设置QDataStream的串行化格式。

  • 为了兼容Qt 3.0，请使用v == 4。
  • 为了兼容Qt 2.1.x和Qt 2.2.x，请使用v == 3。
  • 为了兼容Qt 2.0.x，请使用v == 2。
  • 为了兼容Qt 1.x，请使用v == 1。

也可以参考version().

void QDataStream::unsetDevice ()

清除IO设备。这个和调用setDevice( 0 )一样。

也可以参考device()和setDevice()。

int QDataStream::version () const

返回数据串行化格式的版本号。 在Qt 3.0中，这个版本号为4。

也可以参考setVersion()。

QDataStream & QDataStream::writeBytes ( const char * s, uint len )

写长度说明符len和缓存s到流中并返回流的引用。

len被串行化为一个Q_UINT32，接着的是s中的len字节。注意数据不是编码的。

也可以参考writeRawBytes()和readBytes()。

QDataStream & QDataStream::writeRawBytes ( const char * s, uint len )

从s中写len字节到流中并且返回流的引用。数据不是编码的。

也可以参考writeBytes()、QIODevice::writeBlock()和readRawBytes()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdatastream.h包含文件

qdatastream.h

这里是qdatastream.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qdatastream.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QDataStream class
**
** Created : 930831
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATASTREAM_H
#define QDATASTREAM_H

#ifndef QT_H
#include "qiodevice.h"
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_DATASTREAM
class Q_EXPORT QDataStream				// data stream class
{
public:
    QDataStream();
    QDataStream( QIODevice * );
    QDataStream( QByteArray, int mode );
    virtual ~QDataStream();

    QIODevice	*device() const;
    void	 setDevice( QIODevice * );
    void	 unsetDevice();

    bool	 atEnd() const;
    bool	 eof() const;

    enum ByteOrder { BigEndian, LittleEndian };
    int		 byteOrder()	const;
    void	 setByteOrder( int );

    bool	 isPrintableData() const;
    void	 setPrintableData( bool );

    int		 version() const;
    void	 setVersion( int );

    QDataStream &operator>>( Q_INT8 &i );
    QDataStream &operator>>( Q_UINT8 &i );
    QDataStream &operator>>( Q_INT16 &i );
    QDataStream &operator>>( Q_UINT16 &i );
    QDataStream &operator>>( Q_INT32 &i );
    QDataStream &operator>>( Q_UINT32 &i );
    QDataStream &operator>>( Q_LONG &i );
    QDataStream &operator>>( Q_ULONG &i );

    QDataStream &operator>>( float &f );
    QDataStream &operator>>( double &f );
    QDataStream &operator>>( char *&str );

    QDataStream &operator<<( Q_INT8 i );
    QDataStream &operator<<( Q_UINT8 i );
    QDataStream &operator<<( Q_INT16 i );
    QDataStream &operator<<( Q_UINT16 i );
    QDataStream &operator<<( Q_INT32 i );
    QDataStream &operator<<( Q_UINT32 i );
    QDataStream &operator<<( Q_LONG i );
    QDataStream &operator<<( Q_ULONG i );
    QDataStream &operator<<( float f );
    QDataStream &operator<<( double f );
    QDataStream &operator<<( const char *str );

    QDataStream &readBytes( char *&, uint &len );
    QDataStream &readRawBytes( char *, uint len );

    QDataStream &writeBytes( const char *, uint len );
    QDataStream &writeRawBytes( const char *, uint len );

private:
    QIODevice	*dev;
    bool	 owndev;
    int		 byteorder;
    bool	 printable;
    bool	 noswap;
    int		 ver;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QDataStream( const QDataStream & );
    QDataStream &operator=( const QDataStream & );
#endif
};

/*****************************************************************************
  QDataStream inline functions
 *****************************************************************************/

inline QIODevice *QDataStream::device() const
{ return dev; }

inline bool QDataStream::atEnd() const
{ return dev ? dev->atEnd() : TRUE; }

inline bool QDataStream::eof() const
{ return atEnd(); }

inline int QDataStream::byteOrder() const
{ return byteorder; }

inline bool QDataStream::isPrintableData() const
{ return printable; }

inline void QDataStream::setPrintableData( bool p )
{ printable = p; }

inline int QDataStream::version() const
{ return ver; }

inline void QDataStream::setVersion( int v )
{ ver = v; }

inline QDataStream &QDataStream::operator>>( Q_UINT8 &i )
{ return *this >> (Q_INT8&)i; }

inline QDataStream &QDataStream::operator>>( Q_UINT16 &i )
{ return *this >> (Q_INT16&)i; }

inline QDataStream &QDataStream::operator>>( Q_UINT32 &i )
{ return *this >> (Q_INT32&)i; }

inline QDataStream &QDataStream::operator>>( Q_ULONG &i )
{ return *this >> (Q_LONG&)i; }

inline QDataStream &QDataStream::operator<<( Q_UINT8 i )
{ return *this << (Q_INT8)i; }

inline QDataStream &QDataStream::operator<<( Q_UINT16 i )
{ return *this << (Q_INT16)i; }

inline QDataStream &QDataStream::operator<<( Q_UINT32 i )
{ return *this << (Q_INT32)i; }

inline QDataStream &QDataStream::operator<<( Q_ULONG i )
{ return *this << (Q_LONG)i; }

#endif // QT_NO_DATASTREAM
#endif // QDATASTREAM_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDataStream成员列表

完整的QDataStream成员列表

这里是QDataStream成员函数的完整列表，包括继承的成员。

  • QDataStream()
  • ~QDataStream()
  • atEnd()
  • byteOrder()
  • device()
  • eof()
  • isPrintableData()
  • operator<<()
  • operator>>()
  • readBytes()
  • readRawBytes()
  • setByteOrder()
  • setDevice()
  • setPrintableData()
  • setVersion()
  • unsetDevice()
  • version()
  • writeBytes()
  • writeRawBytes()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDataTable Class

QDataTable Class Reference
[sql module]

The QDataTable class provides a flexible SQL table widget that supports browsing and editing. More...

#include <qdatatable.h>

Inherits QTable.

List of all member functions.

Public Members

  • QDataTable ( QWidget * parent = 0, const char * name = 0 )
  • QDataTable ( QSqlCursor * cursor, bool autoPopulate = FALSE, QWidget * parent = 0, const char * name = 0 )
  • ~QDataTable ()
  • virtual void addColumn ( const QString & fieldName, const QString & label = QString::null, int width = -1, const QIconSet & iconset = QIconSet ( ) )
  • virtual void removeColumn ( uint col )
  • virtual void setColumn ( uint col, const QString & fieldName, const QString & label = QString::null, int width = -1, const QIconSet & iconset = QIconSet ( ) )
  • QString nullText () const
  • QString trueText () const
  • QString falseText () const
  • DateFormat dateFormat () const
  • bool confirmEdits () const
  • bool confirmInsert () const
  • bool confirmUpdate () const
  • bool confirmDelete () const
  • bool confirmCancels () const
  • bool autoDelete () const
  • bool autoEdit () const
  • QString filter () const
  • QStringList sort () const
  • virtual void setSqlCursor ( QSqlCursor * cursor = 0, bool autoPopulate = FALSE, bool autoDelete = FALSE )
  • QSqlCursor * sqlCursor () const
  • virtual void setNullText ( const QString & nullText )
  • virtual void setTrueText ( const QString & trueText )
  • virtual void setFalseText ( const QString & falseText )
  • virtual void setDateFormat ( const DateFormat f )
  • virtual void setConfirmEdits ( bool confirm )
  • virtual void setConfirmInsert ( bool confirm )
  • virtual void setConfirmUpdate ( bool confirm )
  • virtual void setConfirmDelete ( bool confirm )
  • virtual void setConfirmCancels ( bool confirm )
  • virtual void setAutoDelete ( bool enable )
  • virtual void setAutoEdit ( bool autoEdit )
  • virtual void setFilter ( const QString & filter )
  • virtual void setSort ( const QStringList & sort )
  • virtual void setSort ( const QSqlIndex & sort )
  • enum Refresh { RefreshData = 1, RefreshColumns = 2, RefreshAll = 3 }
  • void refresh ( Refresh mode )
  • virtual void sortColumn ( int col, bool ascending = TRUE, bool wholeRows = FALSE )
  • virtual QString text ( int row, int col ) const
  • QVariant value ( int row, int col ) const
  • QSqlRecord * currentRecord () const
  • void installEditorFactory ( QSqlEditorFactory * f )
  • void installPropertyMap ( QSqlPropertyMap * m )
  • virtual int numCols () const
  • virtual int numRows () const

Public Slots

  • virtual void find ( const QString & str, bool caseSensitive, bool backwards )
  • virtual void sortAscending ( int col )
  • virtual void sortDescending ( int col )
  • virtual void refresh ()
  • virtual void setColumnWidth ( int col, int w )
  • virtual void adjustColumn ( int col )

Signals

  • void currentChanged ( QSqlRecord * record )
  • void primeInsert ( QSqlRecord * buf )
  • void primeUpdate ( QSqlRecord * buf )
  • void primeDelete ( QSqlRecord * buf )
  • void beforeInsert ( QSqlRecord * buf )
  • void beforeUpdate ( QSqlRecord * buf )
  • void beforeDelete ( QSqlRecord * buf )
  • void cursorChanged ( QSql::Op mode )

Properties

  • bool autoEdit - whether the data table automatically applies edits
  • bool confirmCancels - whether the data table confirms cancel operations
  • bool confirmDelete - whether the data table confirms delete operations
  • bool confirmEdits - whether the data table confirms edit operations
  • bool confirmInsert - whether the data table confirms insert operations
  • bool confirmUpdate - whether the data table confirms update operations
  • DateFormat dateFormat - the format how date/time values are displayed
  • QString falseText - the text used to represent false values
  • QString filter - the data filter for the data table
  • QString nullText - the text used to represent NULL values
  • int numCols - the number of columns in the table (read only)
  • int numRows - the number of rows in the table (read only)
  • QStringList sort - the data table's sort
  • QString trueText - the text used to represent true values

Protected Members

  • virtual bool insertCurrent ()
  • virtual bool updateCurrent ()
  • virtual bool deleteCurrent ()
  • virtual QSql::Confirm confirmEdit ( QSql::Op m )
  • virtual QSql::Confirm confirmCancel ( QSql::Op m )
  • virtual void handleError ( const QSqlError & e )
  • virtual bool beginInsert ()
  • virtual QWidget * beginUpdate ( int row, int col, bool replace )
  • int indexOf ( uint i ) const
  • void reset ()
  • void setSize ( QSqlCursor * sql )
  • virtual void paintField ( QPainter * p, const QSqlField * field, const QRect & cr, bool selected )
  • virtual int fieldAlignment ( const QSqlField * field )

Detailed Description

The QDataTable class provides a flexible SQL table widget that supports browsing and editing.

QDataTable supports various functions for presenting and editing SQL data from a QSqlCursor in a table.

If you want a to present your data in a form use QDataBrowser, or for read-only forms, QDataView.

When displaying data, QDataTable only retrieves data for visible rows. If the driver supports the 'query size' property the QDataTable will have the correct number of rows and the vertical scrollbar will accurately reflect the number of rows displayed in proportion to the number of rows in the dataset. If the driver does not support the 'query size' property rows are dynamically fetched from the database on an as-needed basis with the scrollbar becoming more accurate as the user scrolls down through the records. This allows extremely large queries to be displayed as quickly as possible, with minimum memory usage.

QDataTable inherits QTable's API and extends it with functions to sort and filter the data and sort columns. See setSqlCursor(), setFilter(), setSort(), setSorting(), sortColumn() and refresh().

When displaying editable cursors, cell editing will be enabled. (For more information on editable cursors, see QSqlCursor). QDataTable can be used to modify existing data and to add new records. When a user makes changes to a field in the table, the cursor's edit buffer is used. The table will not send changes in the edit buffer to the database until the user moves to a different record in the grid or presses Return. Cell editing is initiated by pressing F2 (or right clicking and then clicking the appropriate popup menu item) and cancelled by pressing Esc. If there is a problem updating or adding data, errors are handled automatically (see handleError() to change this behavior). Note that if autoEdit() is FALSE navigating to another record will cancel the insert or update.

The user can be asked to confirm all edits with setConfirmEdits(). For more precise control use setConfirmInsert(), setConfirmUpdate(), setConfirmDelete() and setConfirmCancels(). Use setAutoEdit() to control the behaviour of the table when the user edits a record and then navigates. (Note that setAutoDelete() is unrelated; it is used to set whether the QSqlCursor is deleted when the table is deleted.)

Since the data table can perform edits, it must be able to uniquely identify every record so that edits are correctly applied. Because of this the underlying cursor must have a valid primary index to ensure that a unique record is inserted, updated or deleted within the database otherwise the database may be changed to an inconsistent state.

QDataTable creates editors using the default QSqlEditorFactory. Different editor factories can be used by calling installEditorFactory(). A property map is used to map between the cell's value and the editor. You can use your own property map with installPropertyMap().

The contents of a cell is available as a QString with text() or as a QVariant with value(). The current record is returned by currentRecord(). Use the find() function to search for a string in the table.

Editing actions can be applied programatically. For example, the insertCurrent() function reads the fields from the current record into the cursor and performs the insert. The updateCurrent() and deleteCurrent() functions perform similarly to update and delete the current record respectively.

Columns in the table can be created automatically based on the cursor (see setSqlCursor()). Columns can be manipulated manually using addColumn(), removeColumn() and setColumn().

The table automatically copies many of the properties of the cursor to format the display of data within cells (alignment, visibility, etc.). The cursor can be changed with setSqlCursor(). The filter (see setFilter()) and sort defined within the table are used instead of the filter and sort set on the cursor. For sorting options see setSort(), sortColumn(), sortAscending() and sortDescending().

The text used to represent NULL, TRUE and FALSE values can be changed with setNullText(), setTrueText() and setFalseText() respectively. You can change the appearance of cells by reimplementing paintField().

Whenever a new row is selected in the table the currentChanged() signal is emitted. The primeInsert() signal is emitted when an insert is initiated. The primeUpdate() and primeDelete() signals are emitted when update and deletion are initiated respectively. Just before the database is updated a signal is emitted; beforeInsert(), beforeUpdate() or beforeDelete() as appropriate.

See also Database Classes.

Member Type Documentation

QDataTable::Refresh

This enum describes the refresh options.

The currently defined values are:

  • QDataTable::RefreshData - refresh the data, i.e. read it from the database
  • QDataTable::RefreshColumns - refresh the list of fields, e.g. the column headings
  • QDataTable::RefreshAll - refresh both the data and the list of fields

Member Function Documentation

QDataTable::QDataTable ( QWidget * parent = 0, const char * name = 0 )

Constructs a data table which is a child of parent, with the name name.

QDataTable::QDataTable ( QSqlCursor * cursor, bool autoPopulate = FALSE, QWidget * parent = 0, const char * name = 0 )

Constructs a data table which is a child of parent, with the name name using the cursor cursor.

If autoPopulate is TRUE (the default is FALSE), columns are automatically created based upon the fields in the cursor record. Note that autoPopulate only governs the creation of columns; to load the cursor's data into the table use refresh().

If the cursor is read-only, the table also becomes read-only. In addition, the table adopts the cursor's driver's definition for representing NULL values as strings.

QDataTable::~QDataTable ()

Destroys the object and frees any allocated resources.

void QDataTable::addColumn ( const QString & fieldName, const QString & label = QString::null, int width = -1, const QIconSet & iconset = QIconSet ( ) ) [virtual]

Adds the next column to be displayed using the field fieldName, column label label, width width and iconset iconset.

If label is specified, it is used as the column's header label, otherwise the field's display label is used when setSqlCursor() is called. The iconset is used to set the icon used by the column header; by default there is no icon.

See also setSqlCursor() and refresh().

Examples: sql/overview/subclass1/main.cpp, sql/overview/subclass3/main.cpp, sql/overview/table2/main.cpp and sql/sqltable/main.cpp.

void QDataTable::adjustColumn ( int col ) [virtual slot]

Resizes column col so that the column width is wide enough to display the widest item the column contains. Note that opposed to QTable the QDataTable is not immediately redrawn, you have to call refresh() first. If the table's QSqlCursor is currently not active, the cursor will be refreshed before the column width is calculated. Be aware that this function may be slow on tables that contain large result sets.

See also refresh().

Reimplemented from QTable.

bool QDataTable::autoDelete () const

Returns TRUE if the table will automatically delete the cursor specified by setSqlCursor(), otherwise returns FALSE.

bool QDataTable::autoEdit () const

Returns TRUE if the data table automatically applies edits; otherwise returns FALSE. See the "autoEdit" property for details.

void QDataTable::beforeDelete ( QSqlRecord * buf ) [signal]

This signal is emitted just before the currently selected record is deleted from the database. The buf parameter points to the edit buffer being deleted. Connect to this signal to, for example, copy some of the fields for later use.

void QDataTable::beforeInsert ( QSqlRecord * buf ) [signal]

This signal is emitted just before the cursor's edit buffer is inserted into the database. The buf parameter points to the edit buffer being inserted. Connect to this signal to, for example, populate a key field with a unique sequence number.

void QDataTable::beforeUpdate ( QSqlRecord * buf ) [signal]

This signal is emitted just before the cursor's edit buffer is updated in the database. The buf parameter points to the edit buffer being updated. Connect to this signal when you want to transform the user's data behind-the-scenes.

bool QDataTable::beginInsert () [virtual protected]

Protected virtual function called when editing is about to begin on a new record. If the table is read-only, or if there's no cursor or the cursor does not allow inserts, nothing happens.

Editing takes place using the cursor's edit buffer(see QSqlCursor::editBuffer()).

When editing begins, a new row is created in the table marked with an asterisk '*' in the row's vertical header column, i.e. at the left of the row.

QWidget * QDataTable::beginUpdate ( int row, int col, bool replace ) [virtual protected]

Protected virtual function called when editing is about to begin on an existing row. If the table is read-only, or if there's no cursor, nothing happens.

Editing takes place using the cursor's edit buffer (see QSqlCursor::editBuffer()).

row and col refer to the row and column in the QDataTable.

(replace is provided for reimplementors and reflects the API of QTable::beginEdit().)

QSql::Confirm QDataTable::confirmCancel ( QSql::Op m ) [virtual protected]

Protected virtual function which returns a confirmation for cancelling an edit mode of m. Derived classes can reimplement this function to provide their own cancel dialog. The default implementation uses a message box which prompts the user to confirm the cancel.

bool QDataTable::confirmCancels () const

Returns TRUE if the data table confirms cancel operations; otherwise returns FALSE. See the "confirmCancels" property for details.

bool QDataTable::confirmDelete () const

Returns TRUE if the data table confirms delete operations; otherwise returns FALSE. See the "confirmDelete" property for details.

QSql::Confirm QDataTable::confirmEdit ( QSql::Op m ) [virtual protected]

Protected virtual function which returns a confirmation for an edit of mode m. Derived classes can reimplement this function to provide their own confirmation dialog. The default implementation uses a message box which prompts the user to confirm the edit action.

bool QDataTable::confirmEdits () const

Returns TRUE if the data table confirms edit operations; otherwise returns FALSE. See the "confirmEdits" property for details.

bool QDataTable::confirmInsert () const

Returns TRUE if the data table confirms insert operations; otherwise returns FALSE. See the "confirmInsert" property for details.

bool QDataTable::confirmUpdate () const

Returns TRUE if the data table confirms update operations; otherwise returns FALSE. See the "confirmUpdate" property for details.

void QDataTable::currentChanged ( QSqlRecord * record ) [signal]

This signal is emitted whenever a new row is selected in the table. The record parameter points to the contents of the newly selected record.

QSqlRecord * QDataTable::currentRecord () const

Returns a pointer to the currently selected record, or 0 if there is no current selection. The table owns the pointer, so do not delete it or otherwise modify it or the cursor it points to.

void QDataTable::cursorChanged ( QSql::Op mode ) [signal]

This signal is emitted whenever the cursor record was changed due to an edit. The mode parameter is the type of edit that just took place.

DateFormat QDataTable::dateFormat () const

Returns the format how date/time values are displayed. See the "dateFormat" property for details.

bool QDataTable::deleteCurrent () [virtual protected]

For an editable table, issues a delete on the current cursor's primary index using the values of the currently selected row. If there is no current cursor or there is no current selection, nothing happens. If confirmEdits() or confirmDelete() is TRUE, confirmEdit() is called to confirm the delete. Returns TRUE if the delete succeeded, otherwise FALSE.

The underlying cursor must have a valid primary index to ensure that a unique record is deleted within the database otherwise the database may be changed to an inconsistent state.

QString QDataTable::falseText () const

Returns the text used to represent false values. See the "falseText" property for details.

int QDataTable::fieldAlignment ( const QSqlField * field ) [virtual protected]

Returns the alignment for field.

QString QDataTable::filter () const

Returns the data filter for the data table. See the "filter" property for details.

void QDataTable::find ( const QString & str, bool caseSensitive, bool backwards ) [virtual slot]

Searches the current cursor for a cell containing the string str starting at the current cell and working forwards (or backwards if backwards is TRUE). If the string is found, the cell containing the string is set as the current cell. If caseSensitive is FALSE the case of str will be ignored.

The search will wrap, i.e. if the first (or if backwards is TRUE, last) cell is reached without finding str the search will continue until it reaches the starting cell. If str is not found the search will fail and the current cell will remain unchanged.

void QDataTable::handleError ( const QSqlError & e ) [virtual protected]

Protected virtual function which is called when an error e has occurred on the current cursor(). The default implementation displays a warning message to the user with information about the error.

int QDataTable::indexOf ( uint i ) const [protected]

Returns the index of the field within the current SQL query that is displayed in column i.

bool QDataTable::insertCurrent () [virtual protected]

For an editable table, issues an insert on the current cursor using the values in the cursor's edit buffer. If there is no current cursor or there is no current "insert" row, nothing happens. If confirmEdits() or confirmInsert() is TRUE, confirmEdit() is called to confirm the insert. Returns TRUE if the insert succeeded, otherwise returns FALSE.

The underlying cursor must have a valid primary index to ensure that a unique record is inserted within the database otherwise the database may be changed to an inconsistent state.

void QDataTable::installEditorFactory ( QSqlEditorFactory * f )

Installs a new SQL editor factory f. This enables the user to create and instantiate their own editors for use in cell editing. Note that QDataTable takes ownership of this pointer, and will delete it when it is no longer needed or when installEditorFactory() is called again.

See also QSqlEditorFactory.

void QDataTable::installPropertyMap ( QSqlPropertyMap * m )

Installs a new property map m. This enables the user to create and instantiate their own property maps for use in cell editing. Note that QDataTable takes ownership of this pointer, and will delete it when it is no longer needed or when installPropertMap() is called again.

See also QSqlPropertyMap.

QString QDataTable::nullText () const

Returns the text used to represent NULL values. See the "nullText" property for details.

int QDataTable::numCols () const [virtual]

Returns the number of columns in the table. See the "numCols" property for details.

Reimplemented from QTable.

int QDataTable::numRows () const [virtual]

Returns the number of rows in the table. See the "numRows" property for details.

Reimplemented from QTable.

void QDataTable::paintField ( QPainter * p, const QSqlField * field, const QRect & cr, bool selected ) [virtual protected]

Paints the field on the painter p. The painter has already been translated to the appropriate cell's origin where the field is to be rendered. cr describes the cell coordinates in the content coordinate system. The selected parameter is ignored.

If you want to draw custom field content you have to reimplement paintField() to do the custom drawing. The default implementation renders the field value as text. If the field is NULL, nullText() is displayed in the cell. If the field is Boolean, trueText() or falseText() is displayed as appropriate.

Example: sql/overview/table4/main.cpp.

void QDataTable::primeDelete ( QSqlRecord * buf ) [signal]

This signal is emitted after the cursor is primed for delete by the table, when a delete action is beginning on the table. The buf parameter points to the edit buffer being deleted. Connect to this signal in order to, for example, record auditing information on deletions.

void QDataTable::primeInsert ( QSqlRecord * buf ) [signal]

This signal is emitted after the cursor is primed for insert by the table, when an insert action is beginning on the table. The buf parameter points to the edit buffer being inserted. Connect to this signal in order to, for example, prime the record buffer with default data values.

void QDataTable::primeUpdate ( QSqlRecord * buf ) [signal]

This signal is emitted after the cursor is primed for update by the table, when an update action is beginning on the table. The buf parameter points to the edit buffer being updated. Connect to this signal in order to, for example, provide some visual feedback that the user is in 'insert mode'.

void QDataTable::refresh () [virtual slot]

Refreshes the table. The cursor is refreshed using the current filter, the current sort, and the currently defined columns. Equivalent to calling refresh( QDataTable::RefreshData ).

Examples: sql/overview/subclass1/main.cpp, sql/overview/table1/main.cpp, sql/overview/table2/main.cpp and sql/sqltable/main.cpp.

void QDataTable::refresh ( Refresh mode )

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

Refreshes the table. If there is no currently defined cursor (see setSqlCursor()), nothing happens. The mode parameter determines which type of refresh will take place.

See also Refresh, setSqlCursor() and addColumn().

void QDataTable::removeColumn ( uint col ) [virtual]

Removes column col from the list of columns to be displayed. If col does not exist, nothing happens.

See also QSqlField.

void QDataTable::reset () [protected]

Resets the table so that it displays no data.

See also setSqlCursor().

void QDataTable::setAutoDelete ( bool enable ) [virtual]

Sets the cursor auto-delete flag to enable. If enable is TRUE, the table will automatically delete the cursor specified by setSqlCursor(). Otherwise, (the default), the cursor will not be deleted.

void QDataTable::setAutoEdit ( bool autoEdit ) [virtual]

Sets whether the data table automatically applies edits to autoEdit. See the "autoEdit" property for details.

void QDataTable::setColumn ( uint col, const QString & fieldName, const QString & label = QString::null, int width = -1, const QIconSet & iconset = QIconSet ( ) ) [virtual]

Sets the col column to display using the field fieldName, column label label, width width and iconset iconset.

If label is specified, it is used as the column's header label, otherwise the field's display label is used when setSqlCursor() is called. The iconset is used to set the icon used by the column header; by default there is no icon.

See also setSqlCursor() and refresh().

void QDataTable::setColumnWidth ( int col, int w ) [virtual slot]

Sets the column col to the width w. Note that opposed to QTable the QDataTable is not immediately redrawn, you have to call refresh() first.

See also refresh().

Reimplemented from QTable.

void QDataTable::setConfirmCancels ( bool confirm ) [virtual]

Sets whether the data table confirms cancel operations to confirm. See the "confirmCancels" property for details.

void QDataTable::setConfirmDelete ( bool confirm ) [virtual]

Sets whether the data table confirms delete operations to confirm. See the "confirmDelete" property for details.

void QDataTable::setConfirmEdits ( bool confirm ) [virtual]

Sets whether the data table confirms edit operations to confirm. See the "confirmEdits" property for details.

void QDataTable::setConfirmInsert ( bool confirm ) [virtual]

Sets whether the data table confirms insert operations to confirm. See the "confirmInsert" property for details.

void QDataTable::setConfirmUpdate ( bool confirm ) [virtual]

Sets whether the data table confirms update operations to confirm. See the "confirmUpdate" property for details.

void QDataTable::setDateFormat ( const DateFormat f ) [virtual]

Sets the format how date/time values are displayed to f. See the "dateFormat" property for details.

void QDataTable::setFalseText ( const QString & falseText ) [virtual]

Sets the text used to represent false values to falseText. See the "falseText" property for details.

void QDataTable::setFilter ( const QString & filter ) [virtual]

Sets the data filter for the data table to filter. See the "filter" property for details.

void QDataTable::setNullText ( const QString & nullText ) [virtual]

Sets the text used to represent NULL values to nullText. See the "nullText" property for details.

void QDataTable::setSize ( QSqlCursor * sql ) [protected]

If the cursor's sql driver supports query sizes, the number of rows in the table is set to the size of the query. Otherwise, the table dynamically resizes itself as it is scrolled. If sql is not active, it is made active by issuing a select() on the cursor using the sql cursor's current filter and current sort.

void QDataTable::setSort ( const QStringList & sort ) [virtual]

Sets the data table's sort to sort. See the "sort" property for details.

void QDataTable::setSort ( const QSqlIndex & sort ) [virtual]

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

Sets the sort to be applied to the displayed data to sort. If there is no current cursor, nothing happens. A QSqlIndex contains field names and their ordering (ASC or DESC); these are used to compose the ORDER BY clause.

See also sort.

void QDataTable::setSqlCursor ( QSqlCursor * cursor = 0, bool autoPopulate = FALSE, bool autoDelete = FALSE ) [virtual]

Sets cursor as the data source for the table. To force the display of the data from cursor, use refresh(). If autoPopulate is TRUE, columns are automatically created based upon the fields in the cursor record. If autoDelete is TRUE (the default is FALSE), the table will take ownership of the cursor and delete it when appropriate. If the cursor is read-only, the table becomes read-only. The table adopts the cursor's driver's definition for representing NULL values as strings.

See also refresh(), readOnly, setAutoDelete() and QSqlDriver::nullText().

void QDataTable::setTrueText ( const QString & trueText ) [virtual]

Sets the text used to represent true values to trueText. See the "trueText" property for details.

QStringList QDataTable::sort () const

Returns the data table's sort. See the "sort" property for details.

void QDataTable::sortAscending ( int col ) [virtual slot]

Sorts column col in ascending order.

See also sorting.

void QDataTable::sortColumn ( int col, bool ascending = TRUE, bool wholeRows = FALSE ) [virtual]

Sorts column col in ascending order if ascending is TRUE (the default), otherwise sorts in descending order. The wholeRows parameter is ignored for SQL tables.

Reimplemented from QTable.

void QDataTable::sortDescending ( int col ) [virtual slot]

Sorts column col in descending order.

See also sorting.

QSqlCursor * QDataTable::sqlCursor () const

Returns a pointer to the cursor used by the data table.

QString QDataTable::text ( int row, int col ) const [virtual]

Returns the text in cell row, col, or an empty string if the cell is empty. If the cell's value is NULL then nullText() will be returned. If the cell does not exist then a null QString is returned.

Reimplemented from QTable.

QString QDataTable::trueText () const

Returns the text used to represent true values. See the "trueText" property for details.

bool QDataTable::updateCurrent () [virtual protected]

For an editable table, issues an update using the cursor's edit buffer. If there is no current cursor or there is no current selection, nothing happens. If confirmEdits() or confirmUpdate() is TRUE, confirmEdit() is called to confirm the update. Returns TRUE if the update succeeded, otherwise returns FALSE.

The underlying cursor must have a valid primary index to ensure that a unique record is updated within the database otherwise the database may be changed to an inconsistent state.

QVariant QDataTable::value ( int row, int col ) const

Returns the value in cell row, col, or an invalid value if the cell does not exist or has no value.

Property Documentation

bool autoEdit

This property holds whether the data table automatically applies edits.

The default value for this property is TRUE. When the user begins an insert or update in the table there are two possible outcomes when they navigate to another record:

  1. the insert or update is is performed -- this occurs if autoEdit is TRUE
  2. the insert or update is abandoned -- this occurs if autoEdit is FALSE

Set this property's value with setAutoEdit() and get this property's value with autoEdit().

bool confirmCancels

This property holds whether the data table confirms cancel operations.

If the confirmCancel property is active, all cancels must be confirmed by the user through a message box (this behavior can be changed by overriding the confirmCancel() function), otherwise all cancels occur immediately. The default is FALSE.

See also confirmEdits and confirmCancel().

Set this property's value with setConfirmCancels() and get this property's value with confirmCancels().

bool confirmDelete

This property holds whether the data table confirms delete operations.

If the confirmDelete property is active, all deletions must be confirmed by the user through a message box (this behaviour can be changed by overriding the confirmEdit() function), otherwise all delete operations occur immediately.

See also confirmCancels, confirmEdits, confirmUpdate and confirmInsert.

Set this property's value with setConfirmDelete() and get this property's value with confirmDelete().

bool confirmEdits

This property holds whether the data table confirms edit operations.

If the confirmEdits property is active, the data table confirms all edit operations (inserts, updates and deletes), otherwise all edit operations occur immediately.

See also confirmCancels, confirmInsert, confirmUpdate and confirmDelete.

Set this property's value with setConfirmEdits() and get this property's value with confirmEdits().

bool confirmInsert

This property holds whether the data table confirms insert operations.

If the confirmInsert property is active, all insertions must be confirmed by the user through a message box (this behaviour can be changed by overriding the confirmEdit() function), otherwise all insert operations occur immediately.

See also confirmCancels, confirmEdits, confirmUpdate and confirmDelete.

Set this property's value with setConfirmInsert() and get this property's value with confirmInsert().

bool confirmUpdate

This property holds whether the data table confirms update operations.

If the confirmUpdate property is active, all updates must be confirmed by the user through a message box (this behaviour can be changed by overriding the confirmEdit() function), otherwise all update operations occur immediately.

See also confirmCancels, confirmEdits, confirmInsert and confirmDelete.

Set this property's value with setConfirmUpdate() and get this property's value with confirmUpdate().

DateFormat dateFormat

This property holds the format how date/time values are displayed.

The dateFormat property will be used to display date/time values in the table. The default value is 'Qt::LocalDate'.

Set this property's value with setDateFormat() and get this property's value with dateFormat().

QString falseText

This property holds the text used to represent false values.

The falseText property will be used to represent NULL values in the table. The default value is 'False'.

Set this property's value with setFalseText() and get this property's value with falseText().

QString filter

This property holds the data filter for the data table.

The filter applies to the data shown in the table. To view data with a new filter, use refresh(). A filter string is an SQL WHERE clause without the WHERE keyword.

There is no default filter.

See also sort.

Set this property's value with setFilter() and get this property's value with filter().

QString nullText

This property holds the text used to represent NULL values.

The nullText property will be used to represent NULL values in the table. The default value is provided by the cursor's driver.

Set this property's value with setNullText() and get this property's value with nullText().

int numCols

This property holds the number of columns in the table.

Get this property's value with numCols().

int numRows

This property holds the number of rows in the table.

Get this property's value with numRows().

QStringList sort

This property holds the data table's sort.

The table's sort affects the order in which data records are displayed in the table. To apply a sort, use refresh().

When examining the sort property, a string list is returned with each item having the form 'fieldname order' (e.g., 'id ASC', 'surname DESC').

There is no default sort.

Note that if you want to iterate over the sort list, you should iterate over a copy, e.g.

    QStringList list = myDataTable.sort();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also filter and refresh().

Set this property's value with setSort() and get this property's value with sort().

QString trueText

This property holds the text used to represent true values.

The trueText property will be used to represent NULL values in the table. The default value is 'True'.

Set this property's value with setTrueText() and get this property's value with trueText().

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


qdatatable.h Include File

qdatatable.h

This is the verbatim text of the qdatatable.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QDataTable class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATATABLE_H
#define QDATATABLE_H

#ifndef QT_H
#include "qstring.h"
#include "qvariant.h"
#include "qtable.h"
#include "qsql.h"
#include "qsqlcursor.h"
#include "qsqlindex.h"
#include "qsqleditorfactory.h"
#include "qiconset.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QPainter;
class QSqlField;
class QSqlPropertyMap;
class QDataTablePrivate;

class QM_EXPORT_SQL QDataTable : public QTable
{
    Q_OBJECT

    Q_PROPERTY( QString nullText READ nullText WRITE setNullText )
    Q_PROPERTY( QString trueText READ trueText WRITE setTrueText )
    Q_PROPERTY( QString falseText READ falseText WRITE setFalseText )
    Q_PROPERTY( DateFormat dateFormat READ dateFormat WRITE setDateFormat )
    Q_PROPERTY( bool confirmEdits READ confirmEdits WRITE setConfirmEdits )
    Q_PROPERTY( bool confirmInsert READ confirmInsert WRITE setConfirmInsert )
    Q_PROPERTY( bool confirmUpdate READ confirmUpdate WRITE setConfirmUpdate )
    Q_PROPERTY( bool confirmDelete READ confirmDelete WRITE setConfirmDelete )
    Q_PROPERTY( bool confirmCancels READ confirmCancels WRITE setConfirmCancels )
    Q_PROPERTY( bool autoEdit READ autoEdit WRITE setAutoEdit )
    Q_PROPERTY( QString filter READ filter WRITE setFilter )
    Q_PROPERTY( QStringList sort READ sort WRITE setSort )
    Q_PROPERTY( int numCols READ numCols )
    Q_PROPERTY( int numRows READ numRows )

public:
    QDataTable ( QWidget* parent=0, const char* name=0 );
    QDataTable ( QSqlCursor* cursor, bool autoPopulate = FALSE, QWidget* parent=0, const char* name=0 );
    ~QDataTable();

    virtual void addColumn( const QString& fieldName,
                const QString& label = QString::null,
                int width = -1,
                const QIconSet& iconset = QIconSet() );
    virtual void removeColumn( uint col );
    virtual void setColumn( uint col, const QString& fieldName,
                const QString& label = QString::null,
                int width = -1,
                const QIconSet& iconset = QIconSet() );

    QString      nullText() const;
    QString      trueText() const;
    QString      falseText() const;
    DateFormat   dateFormat() const;
    bool         confirmEdits() const;
    bool         confirmInsert() const;
    bool         confirmUpdate() const;
    bool         confirmDelete() const;
    bool         confirmCancels() const;
    bool         autoDelete() const;
    bool         autoEdit() const;
    QString      filter() const;
    QStringList  sort() const;

    virtual void setSqlCursor( QSqlCursor* cursor = 0,
                bool autoPopulate = FALSE, bool autoDelete = FALSE );
    QSqlCursor* sqlCursor() const;

    virtual void setNullText( const QString& nullText );
    virtual void setTrueText( const QString& trueText );
    virtual void setFalseText( const QString& falseText );
    virtual void setDateFormat( const DateFormat f );
    virtual void setConfirmEdits( bool confirm );
    virtual void setConfirmInsert( bool confirm );
    virtual void setConfirmUpdate( bool confirm );
    virtual void setConfirmDelete( bool confirm );
    virtual void setConfirmCancels( bool confirm );
    virtual void setAutoDelete( bool enable );
    virtual void setAutoEdit( bool autoEdit );
    virtual void setFilter( const QString& filter );
    virtual void setSort( const QStringList& sort );
    virtual void setSort( const QSqlIndex& sort );

    enum Refresh {
    RefreshData = 1,
    RefreshColumns = 2,
    RefreshAll = 3
    };
    void         refresh( Refresh mode );
    void         sortColumn ( int col, bool ascending = TRUE,
                  bool wholeRows = FALSE );
    QString      text ( int row, int col ) const;
    QVariant     value ( int row, int col ) const;
    QSqlRecord*  currentRecord() const;

    void         installEditorFactory( QSqlEditorFactory * f );
    void         installPropertyMap( QSqlPropertyMap* m );

    int          numCols() const;
    int          numRows() const;
    void         setNumCols( int c );
    void         setNumRows ( int r );
    bool         findBuffer( const QSqlIndex& idx, int atHint = 0 );

signals:
    void         currentChanged( QSqlRecord* record );
    void         primeInsert( QSqlRecord* buf );
    void         primeUpdate( QSqlRecord* buf );
    void         primeDelete( QSqlRecord* buf );
    void         beforeInsert( QSqlRecord* buf );
    void         beforeUpdate( QSqlRecord* buf );
    void         beforeDelete( QSqlRecord* buf );
    void         cursorChanged( QSql::Op mode );

public slots:
    virtual void find( const QString & str, bool caseSensitive,
                 bool backwards );
    virtual void sortAscending( int col );
    virtual void sortDescending( int col );
    virtual void refresh();
    void setColumnWidth( int col, int w );
    void adjustColumn( int col );
    void setColumnStretchable( int col, bool stretch );

protected:
    virtual bool insertCurrent();
    virtual bool updateCurrent();
    virtual bool deleteCurrent();

    virtual QSql::Confirm confirmEdit( QSql::Op m );
    virtual QSql::Confirm confirmCancel( QSql::Op m );

    virtual void handleError( const QSqlError& e );

    virtual bool beginInsert();
    virtual QWidget* beginUpdate ( int row, int col, bool replace );

    bool         eventFilter( QObject *o, QEvent *e );
    void         resizeEvent ( QResizeEvent * );
    void         contentsMousePressEvent( QMouseEvent* e );
    void         contentsContextMenuEvent( QContextMenuEvent* e );
    void         endEdit( int row, int col, bool accept, bool replace );
    QWidget *    createEditor( int row, int col, bool initFromCell ) const;
    void         activateNextCell();
    int          indexOf( uint i ) const;
    void         reset();
    void         setSize( QSqlCursor* sql );
    void         repaintCell( int row, int col );
    void         paintCell ( QPainter * p, int row, int col, const QRect & cr,
                 bool selected, const QColorGroup &cg );
    virtual void paintField( QPainter * p, const QSqlField* field, const QRect & cr,
                 bool selected );
    virtual int  fieldAlignment( const QSqlField* field );
    void         columnClicked ( int col );
    void         resizeData ( int len );

    QTableItem * item ( int row, int col ) const;
    void         setItem ( int row, int col, QTableItem * item );
    void         clearCell ( int row, int col ) ;
    void         setPixmap ( int row, int col, const QPixmap & pix );
    void         takeItem ( QTableItem * i );

private slots:
    void         loadNextPage();
    void         setCurrentSelection( int row, int col );
    void 	 sliderPressed();
    void 	 sliderReleased();

private:
    void         init();
    QWidget*     beginEdit ( int row, int col, bool replace );
    void         updateRow( int row );
    void         endInsert();
    void         endUpdate();
    QDataTablePrivate* d;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDataTable Member List

Complete Member List for QDataTable

This is the complete list of member functions for QDataTable, including inherited members.

  • QDataTable()
  • ~QDataTable()
  • acceptDrops()
  • activateNextCell()
  • addChild()
  • addColumn()
  • addSelection()
  • adjustColumn()
  • adjustRow()
  • adjustSize()
  • autoDelete()
  • autoEdit()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • beforeDelete()
  • beforeInsert()
  • beforeUpdate()
  • beginEdit()
  • beginInsert()
  • beginUpdate()
  • blockSignals()
  • bottomMargin()
  • caption()
  • cellGeometry()
  • cellRect()
  • cellWidget()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearCell()
  • clearCellWidget()
  • clearFocus()
  • clearMask()
  • clearSelection()
  • clearWFlags()
  • clicked()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columnAt()
  • columnClicked()
  • columnIndexChanged()
  • columnMovingEnabled()
  • columnPos()
  • columnWidth()
  • columnWidthChanged()
  • confirmCancel()
  • confirmCancels()
  • confirmDelete()
  • confirmEdit()
  • confirmEdits()
  • confirmInsert()
  • confirmUpdate()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • contextMenuRequested()
  • cornerWidget()
  • create()
  • createEditor()
  • currEditCol()
  • currEditRow()
  • currentChanged()
  • currentColumn()
  • currentRecord()
  • currentRow()
  • currentSelection()
  • cursor()
  • cursorChanged()
  • customEvent()
  • customWhatsThis()
  • dateFormat()
  • deleteCurrent()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doubleClicked()
  • dragAutoScroll()
  • dragEnabled()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • dragObject()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dropped()
  • dumpObjectInfo()
  • dumpObjectTree()
  • editCell()
  • editMode()
  • enableClipper()
  • enabledChange()
  • endEdit()
  • ensureCellVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • falseText()
  • fieldAlignment()
  • filter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusStyle()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • handleError()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideColumn()
  • hideEvent()
  • hideRow()
  • highPriority()
  • horizontalHeader()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertColumns()
  • insertCurrent()
  • insertRows()
  • insertWidget()
  • installEditorFactory()
  • installEventFilter()
  • installPropertyMap()
  • isA()
  • isActiveWindow()
  • isColumnReadOnly()
  • isColumnSelected()
  • isColumnStretchable()
  • isDesktop()
  • isDialog()
  • isEditing()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isReadOnly()
  • isRowReadOnly()
  • isRowSelected()
  • isRowStretchable()
  • isSelected()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • item()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • nullText()
  • numCols()
  • numRows()
  • numSelections()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintCell()
  • paintEmptyArea()
  • paintEvent()
  • paintField()
  • paintFocus()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • primeDelete()
  • primeInsert()
  • primeUpdate()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • refresh()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeColumn()
  • removeColumns()
  • removeEventFilter()
  • removeRow()
  • removeRows()
  • removeSelection()
  • repaint()
  • repaintContents()
  • repaintSelections()
  • reparent()
  • reset()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeData()
  • resizeEvent()
  • resizePolicy()
  • rightMargin()
  • rowAt()
  • rowHeight()
  • rowHeightChanged()
  • rowIndexChanged()
  • rowMovingEnabled()
  • rowPos()
  • scroll()
  • scrollBy()
  • selection()
  • selectionChanged()
  • selectionMode()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoDelete()
  • setAutoEdit()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellContentFromEditor()
  • setCellWidget()
  • setColumn()
  • setColumnMovingEnabled()
  • setColumnReadOnly()
  • setColumnStretchable()
  • setColumnWidth()
  • setConfirmCancels()
  • setConfirmDelete()
  • setConfirmEdits()
  • setConfirmInsert()
  • setConfirmUpdate()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentCell()
  • setCursor()
  • setDateFormat()
  • setDisabled()
  • setDragAutoScroll()
  • setDragEnabled()
  • setEditMode()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFalseText()
  • setFilter()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFocusStyle()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItem()
  • setKeyCompression()
  • setLeftMargin()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNullText()
  • setNumCols()
  • setNumRows()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setRowHeight()
  • setRowMovingEnabled()
  • setRowReadOnly()
  • setRowStretchable()
  • setSelectionMode()
  • setShowGrid()
  • setSize()
  • setSizeIncrement()
  • setSizePolicy()
  • setSort()
  • setSorting()
  • setSqlCursor()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setText()
  • setTopMargin()
  • setTrueText()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • show()
  • showChild()
  • showColumn()
  • showEvent()
  • showFullScreen()
  • showGrid()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showRow()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sort()
  • sortAscending()
  • sortColumn()
  • sortDescending()
  • sorting()
  • sqlCursor()
  • stackUnder()
  • startDrag()
  • startTimer()
  • style()
  • styleChange()
  • swapCells()
  • swapColumns()
  • swapRows()
  • tabletEvent()
  • takeItem()
  • testWFlags()
  • text()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • trueText()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateCell()
  • updateContents()
  • updateCurrent()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • value()
  • valueChanged()
  • verticalHeader()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDataView Class

QDataView Class Reference
[sql module]

The QDataView class provides read-only SQL forms. More...

#include <qdataview.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QDataView ( QWidget * parent = 0, const char * name = 0, WFlags fl = 0 )
  • ~QDataView ()
  • virtual void setForm ( QSqlForm * form )
  • QSqlForm * form ()
  • virtual void setRecord ( QSqlRecord * record )
  • QSqlRecord * record ()

Public Slots

  • virtual void refresh ( QSqlRecord * buf )
  • virtual void readFields ()
  • virtual void writeFields ()
  • virtual void clearValues ()

Detailed Description

The QDataView class provides read-only SQL forms.

This class provides a form which displays SQL field data from a record buffer. Because QDataView does not support editing it uses less resources than a QDataBrowser. This class is well suited for displaying read-only data from a SQL database.

If you want a to present your data in an editable form use QDataBrowser; if you want a table-based presentation of your data use QDataTable.

The form is associated with the data view with setForm() and the record is associated with setRecord(). You can also pass a QSqlRecord to the refresh() function which will set the record to the given record and read the record's fields into the form.

See also Database Classes.

Member Function Documentation

QDataView::QDataView ( QWidget * parent = 0, const char * name = 0, WFlags fl = 0 )

Constructs a data view which is a child of parent, with the name name and widget flags set to fl.

QDataView::~QDataView ()

Destroys the object and frees any allocated resources.

void QDataView::clearValues () [virtual slot]

Clears the default form's values. If there is no default form, nothing happens. All the values are set to their 'zero state', e.g. 0 for numeric fields, "" for string fields.

QSqlForm * QDataView::form ()

Returns the default form used by the data view, or 0 if there is none.

See also setForm().

void QDataView::readFields () [virtual slot]

Causes the default form to read its fields from the record buffer. If there is no default form, or no record, nothing happens.

See also setForm().

QSqlRecord * QDataView::record ()

Returns the default record used by the data view, or 0 if there is none.

See also setRecord().

void QDataView::refresh ( QSqlRecord * buf ) [virtual slot]

Causes the default form to display the contents of buf. If there is no default form, nothing happens.The buf also becomes the default record for all subsequent calls to readFields() and writefields(). This slot is equivalant to calling:

  myView.setRecord( record );
  myView.readFields();

See also setRecord() and readFields().

void QDataView::setForm ( QSqlForm * form ) [virtual]

Sets the form used by the data view to form. If a record has already been assigned to the data view, the form will display that record's data.

See also form().

void QDataView::setRecord ( QSqlRecord * record ) [virtual]

Sets the record used by the data view to record. If a form has already been assigned to the data view, the form will display the data from record in that form.

See also record().

void QDataView::writeFields () [virtual slot]

Causes the default form to write its fields to the record buffer. If there is no default form, or no record, nothing happens.

See also setForm().

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


qdataview.h Include File

qdataview.h

This is the verbatim text of the qdataview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QDataView class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATAVIEW_H
#define QDATAVIEW_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlForm;
class QSqlRecord;
class QDataViewPrivate;

class QM_EXPORT_SQL QDataView : public QWidget
{
    Q_OBJECT

public:
    QDataView( QWidget* parent=0, const char* name=0, WFlags fl = 0 );
    ~QDataView();

    virtual void setForm( QSqlForm* form );
    QSqlForm* form();
    virtual void setRecord( QSqlRecord* record );
    QSqlRecord* record();

public slots:
    virtual void refresh( QSqlRecord* buf );
    virtual void readFields();
    virtual void writeFields();
    virtual void clearValues();

private:
    QDataViewPrivate* d;

};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDataView Member List

Complete Member List for QDataView

This is the complete list of member functions for QDataView, including inherited members.

  • QDataView()
  • ~QDataView()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearValues()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • form()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • readFields()
  • record()
  • recreate()
  • rect()
  • refresh()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setForm()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRecord()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • writeFields()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDate类

QDate类参考

QDate类提供了日期功能。 详情请见……

#include <qdatetime.h>

所有成员函数的列表。

公有成员

  • QDate ()
  • QDate ( int y, int m, int d )
  • bool isNull () const
  • bool isValid () const
  • int year () const
  • int month () const
  • int day () const
  • int dayOfWeek () const
  • int dayOfYear () const
  • int daysInMonth () const
  • int daysInYear () const
  • QString toString ( Qt::DateFormat f = Qt::TextDate ) const
  • QString toString ( const QString & format ) const
  • bool setYMD ( int y, int m, int d )
  • QDate addDays ( int ndays ) const
  • QDate addMonths ( int nmonths ) const
  • QDate addYears ( int nyears ) const
  • int daysTo ( const QDate & d ) const
  • bool operator== ( const QDate & d ) const
  • bool operator!= ( const QDate & d ) const
  • bool operator< ( const QDate & d ) const
  • bool operator<= ( const QDate & d ) const
  • bool operator> ( const QDate & d ) const
  • bool operator>= ( const QDate & d ) const

静态公有成员

  • QString monthName ( int month ) (obsolete)
  • QString dayName ( int weekday ) (obsolete)
  • QString shortMonthName ( int month )
  • QString shortDayName ( int weekday )
  • QString longMonthName ( int month )
  • QString longDayName ( int weekday )
  • QDate currentDate ()
  • QDate fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate )
  • bool isValid ( int y, int m, int d )
  • bool leapYear ( int y )

相关函数

  • QDataStream & operator<< ( QDataStream & s, const QDate & d )
  • QDataStream & operator>> ( QDataStream & s, QDate & d )

详细描述

QDate类提供了日期功能。

QDate对象包含日历日期，比如现代西方（教皇格列高利一世的）日历年、月和日的数字。它可以从系统时钟中读取当前日期。它提供比较日期和操作日期的函数，比如加上一定数量的天、月或年。

QDate对象通常可以由明白地给定的年、月、日数字来创建，或者使用静态函数currentDate()让QDate对象包含系统时钟日期。一个明确的日期也可以用setYMD()来设置。fromString()函数通过一个给定的字符串和在字符串中日期格式的间隔说明就可以返回一个QDate。

year()、month()和day()函数提供了对年、月、日数字的访问。也提供了dayOfWeek()和dayOfYear()函数。toString()、shortDayName()、longDayName()、shortMonthName()和longMonthName()提供了文本格式的相同信息。

QDate提供了一整套的操作符来比较两个QDate对象，在这里小于表示早一些，大于表示晚一些。

你可以使用addDays()给一个日期增加（或减少）一个给定的天数。相似地你可以使用addMonths()和addYears()。daysTo()函数返回两个日期之间的天数。

daysInMonth()和daysInYear()函数分别返回这个日期在当月和当年的天数。leapYear()函数说明这个日期是不是在一个闰年中。

注意QDate不应用于早于格列高利历的日期的计算。这个历法是英格兰从1752年9月14日采用的（因此这是最早有效的QDate），并且后来其他绝大多数西方国家知道1923年才采用。

QDate的结束时间可以一直到8000年，到那个时候我们希望Qt已经被废弃了。

也可以参考QTime、QDateTime、QDateEdit、QDateTimeEdit和时间和日期。

成员函数文档

QDate::QDate ()

构造一个零日期。零日期是无效的。

也可以参考isNull()和isValid()。

QDate::QDate ( int y, int m, int d )

构造一个年、月、日分别为y、m、d的日期。

y必须在1752－8000之间，m必须在1－12之间，d必须在1－31之间。例外，如果y在0－99之间，它表示的是1900－1999。

也可以参考isValid()。

QDate QDate::addDays ( int ndays ) const

返回这个日期对象ndays天之后的一个QDate对象（或者ndays天之前的，如果它是一个负数）。

也可以参考daysTo()。

QDate QDate::addMonths ( int nmonths ) const

返回这个日期对象nmonths月之后的一个QDate对象（或者nmonths月之前的，如果它是一个负数）。

QDate QDate::addYears ( int nyears ) const

返回这个日期对象nyears年之后的一个QDate对象（或者nyears年之前的，如果它是一个负数）。

QDate QDate::currentDate () [静态]

返回当前日期，来自于系统时钟。

也可以参考QTime::currentTime()和QDateTime::currentDateTime()。

实例：dclock/dclock.cpp。

int QDate::day () const

返回这个日期在月中的天数（1－31）。

也可以参考year()、month()和dayOfWeek()。

实例：dclock/dclock.cpp。

QString QDate::dayName ( int weekday ) [静态]

这个函数是废弃的。它的提供是为了保证就代码能够工作。我们强烈建议你在新代码中不要使用它。

使用shortDayName()来替代它。

int QDate::dayOfWeek () const

返回这个日期中在星期中的天数（星期一为1－星期日为7）。

也可以参考day()和dayOfYear()。

int QDate::dayOfYear () const

返回这个日期中在年中的天数（1－365）。

也可以参考day()和dayOfWeek()。

int QDate::daysInMonth () const

返回这个日期中这个月的总天数（28－31）。

也可以参考day()和daysInYear()。

int QDate::daysInYear () const

返回这个日期中这个年的总天数（365－366）。

也可以参考day()和daysInMonth()。

int QDate::daysTo ( const QDate & d ) const

返回从这个日期到d的天数（如果d早于这个日期，返回的为负数）。

实例：

    QDate d1( 1995, 5, 17 );  // 1995年5月17日
    QDate d2( 1995, 5, 20 );  // 1995年5月20日
    d1.daysTo( d2 );          // 返回3
    d2.daysTo( d1 );          // 返回-3

也可以参考addDays()。

QDate QDate::fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate ) [静态]

通过给定的字符串s，使用格式f，返回这个QDate，或者如果这是不可能的话返回一个无效的日期。

注意Qt::LocalDate在这里不能使用。

注意Qt::TextDate：它被推荐使用英语中的月的缩写格式（比如Jan）。本地的月名称也可以被使用，但这取决于用户的本地设置。

bool QDate::isNull () const

如果这个日期是零日期，返回真，否则返回假。一个零日期是无效的。

也可以参考isValid()。

bool QDate::isValid () const

如果这个日期是有效的，返回真，否则返回假。

也可以参考isNull()。

bool QDate::isValid ( int y, int m, int d ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果一个给定的（年、月、日分别为y、m、d）日期是有效的，返回真。

实例：

    QDate::isValid( 2002, 5, 17 );  // 真，2002年5月17日是有效的
    QDate::isValid( 2002, 2, 30 );  // 假，2月30日是不存在的
    QDate::isValid( 2004, 2, 29 );  // 真，2004年是闰年
    QDate::isValid( 1202, 6, 6 );   // 假，1202是在格列高利历之前的

注意如果y在0－99范围内表示1900－1999。

也可以参考isNull()和setYMD()。

bool QDate::leapYear ( int y ) [静态]

如果给定的年y是闰年，返回真。

QString QDate::longDayName ( int weekday ) [静态]

返回这一日weekday在星期中的长名称。

1 = “Monday”、2 = “Tuesday”、……7 = “Sunday”

日名称将根据系统本地设置而改变。

也可以参考toString()、shortDayName()、shortMonthName()和longMonthName()。

QString QDate::longMonthName ( int month ) [静态]

返回这一月month的长名称。

1 = “January”、2 = “February”、……12 = “December”

月名称将根据系统本地设置而改变。

也可以参考toString()、shortMonthName()、shortDayName()和longDayName()。

int QDate::month () const

返回这个日期的月（一月为1－十二月为12）。

也可以参考year()和day()。

实例：dclock/dclock.cpp。

QString QDate::monthName ( int month ) [静态]

这个函数是废弃的。它的提供是为了保证就代码能够工作。我们强烈建议你在新代码中不要使用它。

使用shortMonthName()来替代它。

bool QDate::operator!= ( const QDate & d ) const

如果这个日期不等于d，返回真，否则返回假。

bool QDate::operator< ( const QDate & d ) const

如果这个日期早于d，返回真，否则返回假。

bool QDate::operator<= ( const QDate & d ) const

如果这个日期不晚于d，返回真，否则返回假。

bool QDate::operator== ( const QDate & d ) const

如果这个日期等于d，返回真，否则返回假。

bool QDate::operator> ( const QDate & d ) const

如果这个日期晚于d，返回真，否则返回假。

bool QDate::operator>= ( const QDate & d ) const

如果这个日期不早于d，返回真，否则返回假。

bool QDate::setYMD ( int y, int m, int d )

设置日期的年、月、日分别为y、m、d。

y必须在1752－8000之间，m必须在1－12之间，d必须在1－31之间。例外，如果y在0－99之间，它表示的是1900－1999。

如果日期有效，返回真，否则返回假。

QString QDate::shortDayName ( int weekday ) [静态]

返回这一日weekday在星期中的名称。

1 = “Mon”、2 = “Tue”、……7 = “Sun”

日名称将根据系统本地设置而改变。

也可以参考toString()、shortMonthName()、longMonthName()和longDayName()。

QString QDate::shortMonthName ( int month ) [静态]

返回这一月month的名称。

1 = “Jan”、2 = “Feb”、……12 = “Dec”

月名称将根据系统本地设置而改变。

也可以参考toString()、longMonthName()、shortDayName()和longDayName()。

QString QDate::toString ( const QString & format ) const

返回一个字符串的日期。format参数决定了结果字符串的格式。

这些是可能用到的表达式：

  • d - 没有前置0的数字的天（1－31）
  • dd - 前置0的数字的天（01－31）
  • ddd - 缩写的日名称（Mon－Sun）。使用QDate::shortDayName()。
  • dddd - 长的日名称（Monday－Sunday）。使用QDate::longDayName()。
  • M - 没有前置0的数字的月（1－12）
  • MM - 前置0的数字的月（01－12）
  • MMM - 缩写的月名称（Jan－Dec）。使用QDate::shortMonthName()。
  • MMMM - 长的月名称（January－December）。使用QDate::longMonthName()。
  • yy - 两位数字的年（00－99）
  • yyyy - 四位数字的年（0000-9999）

所有其他输入字符都将被忽略。

格式字符串实例（假设这个QDate为2001年5月21日）

  • “dd.MM.yyyy”的结果将是“21.05.2001”。
  • “ddd MMMM d yy”的结果将是“Tue May 21 01”。

也可以参考QDate::toString() and QTime::toString().

QString QDate::toString ( Qt::DateFormat f = Qt::TextDate ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回一个字符串的日期。f参数决定了结果字符串的格式。

如果f是Qt::TextDate，字符串格式是“Sat May 20 1995”（使用shortDayName()和shortMonthName()函数来生成本地指定的字符串）。

如果f是Qt::ISODate，字符串格式遵循ISO 8601表示日期的说明，也就是YYYY-MM-DD，YYYY是年，MM是月（01－12），DD是日（01－31）。

如果f是Qt::LocalDate，字符串格式依赖于系统的本地设置。

也可以参考shortDayName() and shortMonthName().

int QDate::year () const

返回这个日期的年（1752－8000）。

也可以参考month()和day()。

相关函数

QDataStream & operator<< ( QDataStream & s, const QDate & d )

写日期d到流s中。

也可以参考QDataStream操作符的格式。

QDataStream & operator>> ( QDataStream & s, QDate & d )

从流s中读取一个日期到d中。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDate成员列表

完整的QDate成员列表

这里是QDate成员函数的完整列表，包括继承的成员。

  • QDate()
  • addDays()
  • addMonths()
  • addYears()
  • currentDate()
  • day()
  • dayName()
  • dayOfWeek()
  • dayOfYear()
  • daysInMonth()
  • daysInYear()
  • daysTo()
  • fromString()
  • isNull()
  • isValid()
  • leapYear()
  • longDayName()
  • longMonthName()
  • month()
  • monthName()
  • operator!=()
  • operator<()
  • operator<=()
  • operator==()
  • operator>()
  • operator>=()
  • setYMD()
  • shortDayName()
  • shortMonthName()
  • toString()
  • year()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDateEdit Class

QDateEdit Class Reference

The QDateEdit class provides a date editor. More...

#include <qdatetimeedit.h>

List of all member functions.

Public Members

  • QDateEdit ( QWidget * parent = 0, const char * name = 0 )
  • QDateEdit ( const QDate & date, QWidget * parent = 0, const char * name = 0 )
  • ~QDateEdit ()
  • enum Order { DMY, MDY, YMD, YDM }
  • virtual void setDate ( const QDate & date )
  • QDate date () const
  • virtual void setOrder ( Order order )
  • Order order () const
  • virtual void setAutoAdvance ( bool advance )
  • bool autoAdvance () const
  • virtual void setMinValue ( const QDate & d )
  • QDate minValue () const
  • virtual void setMaxValue ( const QDate & d )
  • QDate maxValue () const
  • virtual void setRange ( const QDate & min, const QDate & max )
  • QString separator () const
  • virtual void setSeparator ( const QString & s )

Signals

  • void valueChanged ( const QDate & date )

Properties

  • bool autoAdvance - whether the editor automatically advances to the next section
  • QDate date - the date value of the editor
  • QDate maxValue - the maximum editor value
  • QDate minValue - the minimum editor value
  • Order order - the order in which the year, month and day appear

Protected Members

  • virtual QString sectionFormattedText ( int sec )
  • virtual void setYear ( int year )
  • virtual void setMonth ( int month )
  • virtual void setDay ( int day )
  • virtual void fix ()

Protected Slots

  • void updateButtons ()

Detailed Description

The QDateEdit class provides a date editor.

QDateEdit allows the user to edit dates by using the keyboard or the arrow keys to increase/decrease date values. The arrow keys can be used to move from section to section within the QDateEdit box. Dates appear according the local date/time settings or in year, month, day order if the system doesn't provide this information. It is recommended that the QDateEdit be initialised with a date, e.g.

    QDateEdit *dateEdit = new QDateEdit( QDate::currentDate(), this );
    dateEdit->setRange( QDate::currentDate().addDays( -365 ),
                        QDate::currentDate().addDays(  365 ) );
    dateEdit->setOrder( QDateEdit::MDY );
    dateEdit->setAutoAdvance( TRUE );

Here we've created a new QDateEdit object initialised with today's date and restricted the valid date range to today plus or minus 365 days. We've set the order to month, day, year. If the auto advance property is TRUE (as we've set it here) when the user completes a section of the date, e.g. enters two digits for the month, they are automatically taken to the next section.

The maximum and minimum values for a date value in the date editor default to the maximum and minimum values for a QDate. You can change this by calling setMinValue(), setMaxValue() or setRange().

Terminology: A QDateEdit widget comprises three 'sections', one each for the year, month and day. You can change the separator character using QDateTimeEditor::setSeparator(), by default the separator will be taken from the systems settings. If that is impossible, it defaults to "-".

Date Time Widgets

See also QDate, QTimeEdit, QDateTimeEdit, Advanced Widgets and Time and Date.

Member Type Documentation

QDateEdit::Order

This enum defines the order in which the sections that comprise a date appear.

  • QDateEdit::MDY - month-day-year
  • QDateEdit::DMY - day-month-year
  • QDateEdit::YMD - year-month-day (the default)
  • QDateEdit::YDM - year-day-month (a very bad idea)

Member Function Documentation

QDateEdit::QDateEdit ( QWidget * parent = 0, const char * name = 0 )

Constructs an empty date editor which is a child of parent and the name name.

QDateEdit::QDateEdit ( const QDate & date, QWidget * parent = 0, const char * name = 0 )

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

Constructs a date editor with the initial value date, parent parent and name name.

The date editor is initialized with date.

QDateEdit::~QDateEdit ()

Destroys the object and frees any allocated resources.

bool QDateEdit::autoAdvance () const

Returns TRUE if the editor automatically advances to the next section; otherwise returns FALSE. See the "autoAdvance" property for details.

QDate QDateEdit::date () const

Returns the date value of the editor. See the "date" property for details.

void QDateEdit::fix () [virtual protected]

Attempts to fix any invalid date entries.

The rules applied are as follows:

  • If the year has four digits it is left unchanged.
  • If the year has two digits in the range 70..99, the previous century, i.e. 1900, will be added giving a year in the range 1970..1999.
  • If the year has two digits in the range 0..69, the current century, i.e. 2000, will be added giving a year in the range 2000..2069.
  • If the year is in the range 100..999, the current century, i.e. 2000, will be added giving a year in the range 2100..2999.

QDate QDateEdit::maxValue () const

Returns the maximum editor value. See the "maxValue" property for details.

QDate QDateEdit::minValue () const

Returns the minimum editor value. See the "minValue" property for details.

Order QDateEdit::order () const

Returns the order in which the year, month and day appear. See the "order" property for details.

QString QDateEdit::sectionFormattedText ( int sec ) [virtual protected]

Returns the formatted number for section sec. This will correspond to either the year, month or day section, depending on the current display order.

See also order.

QString QDateEdit::separator () const

Returns the separator for the editor.

void QDateEdit::setAutoAdvance ( bool advance ) [virtual]

Sets whether the editor automatically advances to the next section to advance. See the "autoAdvance" property for details.

void QDateEdit::setDate ( const QDate & date ) [virtual]

Sets the date value of the editor to date. See the "date" property for details.

void QDateEdit::setDay ( int day ) [virtual protected]

Sets the day to day, which must be a valid day. The function will ensure that the day set is valid for the month and year.

void QDateEdit::setMaxValue ( const QDate & d ) [virtual]

Sets the maximum editor value to d. See the "maxValue" property for details.

void QDateEdit::setMinValue ( const QDate & d ) [virtual]

Sets the minimum editor value to d. See the "minValue" property for details.

void QDateEdit::setMonth ( int month ) [virtual protected]

Sets the month to month, which must be a valid month, i.e. between 1 and 12.

void QDateEdit::setOrder ( Order order ) [virtual]

Sets the order in which the year, month and day appear to order. See the "order" property for details.

void QDateEdit::setRange ( const QDate & min, const QDate & max ) [virtual]

Sets the valid input range for the editor to be from min to max inclusive. If min is invalid no minimum date will be set. Similarly, if max is invalid no maximum date will be set.

void QDateEdit::setSeparator ( const QString & s ) [virtual]

Sets the separator to s. Note that currently only the first character of s is used.

void QDateEdit::setYear ( int year ) [virtual protected]

Sets the year to year, which must be a valid year. The range currently supported is from 1752 to 8000.

See also QDate.

void QDateEdit::updateButtons () [protected slot]

Enables/disables the push buttons according to the min/max date for this widget.

void QDateEdit::valueChanged ( const QDate & date ) [signal]

This signal is emitted whenever the editor's value changes. The date parameter is the new value.

Property Documentation

bool autoAdvance

This property holds whether the editor automatically advances to the next section.

If autoAdvance is TRUE, the editor will automatically advance focus to the next date section if a user has completed a section. The default is FALSE.

Set this property's value with setAutoAdvance() and get this property's value with autoAdvance().

QDate date

This property holds the date value of the editor.

If the date property is not valid, the editor displays all zeroes and QDateEdit::date() will return an invalid date. It is strongly recommended that the editor be given a default date value. That way, attempts to set the date property to an invalid date will fail.

When changing the date property, if the date is less than minValue(), or is greater than maxValue(), nothing happens.

Set this property's value with setDate() and get this property's value with date().

QDate maxValue

This property holds the maximum editor value.

Setting the maximum date value for the editor is equivalent to calling QDateEdit::setRange( minValue(), d ), where d is the maximum date. The default maximum date is 8000-12-31.

Set this property's value with setMaxValue() and get this property's value with maxValue().

QDate minValue

This property holds the minimum editor value.

Setting the minimum date value is equivalent to calling QDateEdit::setRange( d, maxValue() ), where d is the minimum date. The default minimum date is 1752-09-14.

Set this property's value with setMinValue() and get this property's value with minValue().

Order order

This property holds the order in which the year, month and day appear.

The default order is locale dependent.

See also Order.

Set this property's value with setOrder() and get this property's value with order().

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


QDateEdit Member List

Complete Member List for QDateEdit

This is the complete list of member functions for QDateEdit, including inherited members.

  • QDateEdit()
  • ~QDateEdit()
  • autoAdvance()
  • date()
  • fix()
  • maxValue()
  • minValue()
  • order()
  • sectionFormattedText()
  • separator()
  • setAutoAdvance()
  • setDate()
  • setDay()
  • setMaxValue()
  • setMinValue()
  • setMonth()
  • setOrder()
  • setRange()
  • setSeparator()
  • setYear()
  • updateButtons()
  • valueChanged()


QDateTime类

QDateTime类参考

QDateTime类提供了日期和时间功能。 详情请见……

#include <qdatetime.h>

所有成员函数的列表。

公有成员

  • QDateTime ()
  • QDateTime ( const QDate & date )
  • QDateTime ( const QDate & date, const QTime & time )
  • bool isNull () const
  • bool isValid () const
  • QDate date () const
  • QTime time () const
  • void setDate ( const QDate & date )
  • void setTime ( const QTime & time )
  • void setTime_t ( uint secsSince1Jan1970UTC )
  • QString toString ( Qt::DateFormat f = Qt::TextDate ) const
  • QString toString ( const QString & format ) const
  • QDateTime addDays ( int ndays ) const
  • QDateTime addMonths ( int nmonths ) const
  • QDateTime addYears ( int nyears ) const
  • QDateTime addSecs ( int nsecs ) const
  • int daysTo ( const QDateTime & dt ) const
  • int secsTo ( const QDateTime & dt ) const
  • bool operator== ( const QDateTime & dt ) const
  • bool operator!= ( const QDateTime & dt ) const
  • bool operator< ( const QDateTime & dt ) const
  • bool operator<= ( const QDateTime & dt ) const
  • bool operator> ( const QDateTime & dt ) const
  • bool operator>= ( const QDateTime & dt ) const

静态公有成员

  • QDateTime currentDateTime ()
  • QDateTime fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate )

相关函数

  • QDataStream & operator<< ( QDataStream & s, const QDateTime & dt )
  • QDataStream & operator>> ( QDataStream & s, QDateTime & dt )

详细描述

QDateTime类提供了日期和时间功能。

QDateTime对象包含一个日历日期和一个时钟时间（一个“日期时间”）。它是QDate和QTime两个类的组合。它可以从系统时钟中读取当前日期时间。它提供比较日期时间和操作日期时间的函数，比如加上一定数量的秒、天、月或年。

QDateTime对象通常可以由明白地给定的日期和时间来创建，或者使用静态函数currentDateTime()让QDateTime对象包含系统时钟的日期时间。日期时间也可以由setDate()和setTime()来改变。日期时间也可以通过使用setTime_t()函数来得到一个POSIX标准的时间，它表示的是自从1970年1月1日00:00:00以来的秒数。fromString()函数通过一个给定的字符串和在字符串中日期时间格式的间隔说明就可以返回一个QDateTime。

date()和time()函数提供了对日期和时间的访问。toString()提供了文本格式的相同信息。

QDateTime提供了一整套的操作符来比较两个QDateTime对象，在这里小于表示早一些，大于表示晚一些。

你可以使用addSecs()或addDays()给一个日期增加（或减少）一个给定的秒数或天数。相似地你可以使用addMonths()和addYears()。daysTo()函数返回两个日期时间之间的天数，sectTo()返回两个日期时间之间的秒数。

日期时间对象的范围由QDate和QTime对象的范围约束。

也可以参考QDate、QTime、QDateTimeEdit和时间和日期。

成员函数文档

QDateTime::QDateTime ()

构造一个零日期时间（比如，零日期和零时间）。一个零日期时间是无效的，因为零日期是无效的。

也可以参考isValid()。

QDateTime::QDateTime ( const QDate & date )

构造一个日期为date和零时间（00:00:00.000）的日期时间。

QDateTime::QDateTime ( const QDate & date, const QTime & time )

构造一个日期为date和时间为time的日期时间。

QDateTime QDateTime::addDays ( int ndays ) const

返回这个日期时间对象ndays天之后的一个日期时间对象（或者ndays天之前的，如果它是一个负数）。

也可以参考daysTo()、addMonths()、addYears()和addSecs()。

QDateTime QDateTime::addMonths ( int nmonths ) const

返回这个日期时间对象nmonths月之后的一个日期时间对象（或者nmonths月之前的，如果它是一个负数）。

也可以参考daysTo()、addDays()、addYears()和addSecs()。

QDateTime QDateTime::addSecs ( int nsecs ) const

返回这个日期时间对象nsecs秒之后的一个日期时间对象（或者nsecs秒之前的，如果它是一个负数）。

也可以参考secsTo()、addDays()、addMonths()和addYears()。

实例：listviews/listviews.cpp。

QDateTime QDateTime::addYears ( int nyears ) const

返回这个日期时间对象nyears年之后的一个日期时间对象（或者nyears年之前的，如果它是一个负数）。

也可以参考daysTo()、addDays()、addMonths()和addSecs()。

QDateTime QDateTime::currentDateTime () [静态]

返回当前日期时间，来自于系统时钟。

也可以参考QDate::currentDate()和QTime::currentTime()。

实例：listviews/listviews.cpp。

QDate QDateTime::date () const

返回日期时间的日期部分。

也可以参考setDate()和time()。

int QDateTime::daysTo ( const QDateTime & dt ) const

返回这个日期时间到dt的天数（如果dt早于这个日期时间，返回的为负数）。

也可以参考addDays()和secsTo()。

QDateTime QDateTime::fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate ) [静态]

通过给定的字符串s，使用格式f，返回这个QDateTime，或者如果这是不可能的话返回一个无效的日期时间。

注意Qt::LocalDate在这里不能使用。

注意Qt::TextDate：它被推荐使用英语中的月的缩写格式（比如Jan）。本地的月名称也可以被使用，但这取决于用户的本地设置。

bool QDateTime::isNull () const

如果日期和时间都是零，返回真，否则返回假。一个零日期时间是无效的。

也可以参考QDate::isNull()和QTime::isNull()。

bool QDateTime::isValid () const

如果日期和时间都是有效的，返回真，否则返回假。

也可以参考QDate::isValid()和QTime::isValid()。

bool QDateTime::operator!= ( const QDateTime & dt ) const

如果这个日期时间不等于dt，返回真，否则返回假。

也可以参考operator==()。

bool QDateTime::operator< ( const QDateTime & dt ) const

如果这个日期时间早于dt，返回真，否则返回假。

bool QDateTime::operator<= ( const QDateTime & dt ) const

如果这个日期时间不晚于dt，返回真，否则返回假。

bool QDateTime::operator== ( const QDateTime & dt ) const

如果这个日期时间等于dt，返回真，否则返回假。

也可以参考operator!=()。

bool QDateTime::operator> ( const QDateTime & dt ) const

如果这个日期时间晚于dt，返回真，否则返回假。

bool QDateTime::operator>= ( const QDateTime & dt ) const

如果这个日期时间不早于dt，返回真，否则返回假。

int QDateTime::secsTo ( const QDateTime & dt ) const

返回从这个日期到dt的秒数（如果dt早于这个日期，返回的为负数）。

实例：

    QDateTime dt = QDateTime::currentDateTime();
    QDateTime xmas( QDate(dt.year(),12,24), QTime(17,00) );
    qDebug( "There are %d seconds to Christmas", dt.secsTo(xmas) ); // 离圣诞节还有多少秒

也可以参考addSecs()、daysTo()和QTime::secsTo()。

void QDateTime::setDate ( const QDate & date )

设置日期时间的日期部分为date。

也可以参考date()和setTime()。

void QDateTime::setTime ( const QTime & time )

设置日期时间的时间部分为time。

也可以参考time()和setDate()。

void QDateTime::setTime_t ( uint secsSince1Jan1970UTC )

通过给定的从1970年1月1日00:00:00（通用协调时间）所过的秒来设置本地时间的日期和时间。在不支持时区的系统上，这个函数的行为就好像本地时间是通用协调时间一样。

注意Microsoft Windows只支持一定范围的secsSince1Jan1970UTC的值。

QTime QDateTime::time () const

返回日期时间的时间部分。

也可以参考setTime()和date()。

QString QDateTime::toString ( const QString & format ) const

返回一个字符串的日期时间。format参数决定了结果字符串的格式。

这些是可能用到的日期表达式：

  • d - 没有前置0的数字的天（1－31）
  • dd - 前置0的数字的天（01－31）
  • ddd - 缩写的日名称（Mon－Sun）。使用QDate::shortDayName()。
  • dddd - 长的日名称（Monday－Sunday）。使用QDate::longDayName()。
  • M - 没有前置0的数字的月（1－12）
  • MM - 前置0的数字的月（01－12）
  • MMM - 缩写的月名称（Jan－Dec）。使用QDate::shortMonthName()。
  • MMMM - 长的月名称（January－December）。使用QDate::longMonthName()。
  • yy - 两位数字的年（00－99）
  • yyyy - 四位数字的年（0000-9999）

这些是可能用到的时间表达式：

  • h - 没有前置0的数字的小时（0－23或者如果显示AM/PM时，1－12）
  • hh - 前置0的数字的小时（00－23或者如果显示AM/PM时，01－12）
  • m - 没有前置0的数字的分钟（0－59）
  • mm - 前置0的数字的分钟（00－59）
  • s - 没有前置0的数字的秒（0－59）
  • ss - 前置0的数字的秒（00－59）
  • z - 没有前置0的数字的毫秒（0－999）
  • zzz - 前置0的数字的毫秒（000－999）
  • AP - 切换为AM/PM显示。AP将被“AM”或“PM”替换。
  • ap - 切换为am/pm显示。ap将被“am”或“pm”替换。

所有其他输入字符都将被忽略。

格式字符串实例（假设这个QDateTime为2001年5月21日14:13:09）

  • “dd.MM.yyyy”的结果将是“21.05.2001”
  • “ddd MMMM d yy”的结果将是“Tue May 21 01”
  • “hh:mm:ss.zzz”的结果将是“14:13:09.042”
  • “h:m:s ap”的结果将是“2:13:9 pm”

也可以参考QDate::toString()和QTime::toString()。

QString QDateTime::toString ( Qt::DateFormat f = Qt::TextDate ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回一个字符串的日期时间。f参数决定了结果字符串的格式。

如果f是Qt::TextDate，字符串格式是“Wed May 20 03:40:13 1998”（使用shortDayName()、shortMonthName()和QTime::toString()函数来生成本地指定的字符串）。

如果f是Qt::ISODate，字符串格式遵循ISO 8601表示日期和时间的说明，也就是YYYY-MM-DDTHH:MM:SS。

如果f是Qt::LocalDate，字符串格式依赖于系统的本地设置。

如果f是无效的，toString()返回一个空字符串。

也可以参考QDate::toString()和QTime::toString()。

相关函数

QDataStream & operator<< ( QDataStream & s, const QDateTime & dt )

写日期时间dt到流s中。

也可以参考QDataStream操作符的格式。

QDataStream & operator>> ( QDataStream & s, QDateTime & dt )

从流s中读取一个日期时间到dt。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdatetime.h包含文件

qdatetime.h

这里是qdatetime.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/*************************************************************************
** $Id:  qt/qdatetime.h   3.0.5   edited Oct 12 2001 $
**
** Definition of date and time classes
**
** Created : 940124
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATETIME_H
#define QDATETIME_H

#ifndef QT_H
#include "qstring.h"
#include "qnamespace.h"
#endif // QT_H

/*****************************************************************************
  QDate class
 *****************************************************************************/

class Q_EXPORT QDate
{
public:
    QDate()  { jd=0; }				// set null date
    QDate( int y, int m, int d );		// set date

    bool   isNull()	 const { return jd == 0; }
    bool   isValid()	 const;			// valid date

    int	   year()	 const;			// 1752..
    int	   month()	 const;			// 1..12
    int	   day()	 const;			// 1..31
    int	   dayOfWeek()	 const;			// 1..7 (monday==1)
    int	   dayOfYear()	 const;			// 1..365
    int	   daysInMonth() const;			// 28..31
    int	   daysInYear()	 const;			// 365 or 366

#ifndef QT_NO_TEXTDATE
#ifndef QT_NO_COMPAT
    static QString monthName( int month ) { return shortMonthName( month ); }
    static QString dayName( int weekday ) { return shortDayName( weekday ); }
#endif
    static QString shortMonthName( int month );
    static QString shortDayName( int weekday );
    static QString longMonthName( int month );
    static QString longDayName( int weekday );
#endif //QT_NO_TEXTDATE
#if !defined(QT_NO_SPRINTF)
    QString toString( Qt::DateFormat f = Qt::TextDate )	 const;
#endif
    QString toString( const QString& format ) const;
    bool   setYMD( int y, int m, int d );

    QDate  addDays( int days )		const;
    QDate  addMonths( int months )      const;
    QDate  addYears( int years )        const;
    int	   daysTo( const QDate & )	const;

    bool   operator==( const QDate &d ) const { return jd == d.jd; }
    bool   operator!=( const QDate &d ) const { return jd != d.jd; }
    bool   operator<( const QDate &d )	const { return jd < d.jd; }
    bool   operator<=( const QDate &d ) const { return jd <= d.jd; }
    bool   operator>( const QDate &d )	const { return jd > d.jd; }
    bool   operator>=( const QDate &d ) const { return jd >= d.jd; }

    static QDate currentDate();
    static QDate fromString( const QString& s, Qt::DateFormat f = Qt::TextDate );

    static bool	 isValid( int y, int m, int d );
    static bool	 leapYear( int year );

    static uint	 gregorianToJulian( int y, int m, int d );
    static void	 julianToGregorian( uint jd, int &y, int &m, int &d );
private:
    uint	 jd;
    friend class QDateTime;
#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QDate & );
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QDate & );
#endif
};

/*****************************************************************************
  QTime class
 *****************************************************************************/

class Q_EXPORT QTime
{
public:
    QTime() { ds=0; }				// set null time
    QTime( int h, int m, int s=0, int ms=0 );	// set time

    bool   isNull()	 const { return ds == 0; }
    bool   isValid()	 const;			// valid time

    int	   hour()	 const;			// 0..23
    int	   minute()	 const;			// 0..59
    int	   second()	 const;			// 0..59
    int	   msec()	 const;			// 0..999

#ifndef QT_NO_SPRINTF
    QString toString( Qt::DateFormat f = Qt::TextDate )	 const;
#endif
    QString toString( const QString& format ) const;

    bool   setHMS( int h, int m, int s, int ms=0 );

    QTime  addSecs( int secs )		const;
    int	   secsTo( const QTime & )	const;
    QTime  addMSecs( int ms )		const;
    int	   msecsTo( const QTime & )	const;

    bool   operator==( const QTime &d ) const { return ds == d.ds; }
    bool   operator!=( const QTime &d ) const { return ds != d.ds; }
    bool   operator<( const QTime &d )	const { return ds < d.ds; }
    bool   operator<=( const QTime &d ) const { return ds <= d.ds; }
    bool   operator>( const QTime &d )	const { return ds > d.ds; }
    bool   operator>=( const QTime &d ) const { return ds >= d.ds; }

    static QTime currentTime();
    static QTime fromString( const QString& s, Qt::DateFormat f = Qt::TextDate );
    static bool	 isValid( int h, int m, int s, int ms=0 );

    void   start();
    int	   restart();
    int	   elapsed() const;

private:
    static bool currentTime( QTime * );

    uint   ds;
    friend class QDateTime;
#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QTime & );
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QTime & );
#endif
};

/*****************************************************************************
  QDateTime class
 *****************************************************************************/

class Q_EXPORT QDateTime
{
public:
    QDateTime() {}				// set null date and null time
    QDateTime( const QDate & );
    QDateTime( const QDate &, const QTime & );

    bool   isNull()	const		{ return d.isNull() && t.isNull(); }
    bool   isValid()	const		{ return d.isValid() && t.isValid(); }

    QDate  date()	const		{ return d; }
    QTime  time()	const		{ return t; }
    void   setDate( const QDate &date ) { d=date; }
    void   setTime( const QTime &time ) { t=time; }
    void   setTime_t( uint secsSince1Jan1970UTC );

#ifndef QT_NO_SPRINTF
    QString toString( Qt::DateFormat f = Qt::TextDate )	const;
#endif
    QString toString( const QString& format ) const;

    QDateTime addDays( int days )	const;
    QDateTime addMonths( int months )   const;
    QDateTime addYears( int years )     const;
    QDateTime addSecs( int secs )	const;
    int	   daysTo( const QDateTime & )	const;
    int	   secsTo( const QDateTime & )	const;

    bool   operator==( const QDateTime &dt ) const;
    bool   operator!=( const QDateTime &dt ) const;
    bool   operator<( const QDateTime &dt )  const;
    bool   operator<=( const QDateTime &dt ) const;
    bool   operator>( const QDateTime &dt )  const;
    bool   operator>=( const QDateTime &dt ) const;

    static QDateTime currentDateTime();
    static QDateTime fromString( const QString& s, Qt::DateFormat f = Qt::TextDate );

private:
    QDate  d;
    QTime  t;
#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QDateTime &);
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QDateTime & );
#endif
};

/*****************************************************************************
  Date and time stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QDate & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QDate & );
Q_EXPORT QDataStream &operator<<( QDataStream &, const QTime & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QTime & );
Q_EXPORT QDataStream &operator<<( QDataStream &, const QDateTime & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QDateTime & );
#endif // QT_NO_DATASTREAM

#endif // QDATETIME_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDateTime成员列表

完整的QDateTime成员列表

这里是QDateTime成员函数的完整列表，包括继承的成员。

  • QDateTime()
  • addDays()
  • addMonths()
  • addSecs()
  • addYears()
  • currentDateTime()
  • date()
  • daysTo()
  • fromString()
  • isNull()
  • isValid()
  • operator!=()
  • operator<()
  • operator<=()
  • operator==()
  • operator>()
  • operator>=()
  • secsTo()
  • setDate()
  • setTime()
  • setTime_t()
  • time()
  • toString()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDateTimeEdit Class

QDateTimeEdit Class Reference

The QDateTimeEdit class combines a QDateEdit and QTimeEdit widget into a single widget for editing datetimes. More...

#include <qdatetimeedit.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QDateTimeEdit ( QWidget * parent = 0, const char * name = 0 )
  • QDateTimeEdit ( const QDateTime & datetime, QWidget * parent = 0, const char * name = 0 )
  • ~QDateTimeEdit ()
  • virtual void setDateTime ( const QDateTime & dt )
  • QDateTime dateTime () const
  • QDateEdit * dateEdit ()
  • QTimeEdit * timeEdit ()
  • virtual void setAutoAdvance ( bool advance )
  • bool autoAdvance () const

Signals

  • void valueChanged ( const QDateTime & datetime )

Properties

  • QDateTime dateTime - the datetime value of the editor

Detailed Description

The QDateTimeEdit class combines a QDateEdit and QTimeEdit widget into a single widget for editing datetimes.

QDateTimeEdit consists of a QDateEdit and QTimeEdit widget placed side by side and offers the functionality of both. The user can edit the date and time by using the keyboard or the arrow keys to increase/decrease date or time values. The Tab key can be used to move from section to section within the QDateTimeEdit widget, and the user can be moved automatically when they complete a section using setAutoAdvance(). The datetime can be set with setDateTime().

The dateformat is read from the system's locale settings. It is set to year, month, day order if that is not possible. see QDateEdit::setOrder() to change this. Times appear in the order hours, minutes, seconds using the 24 hour clock.

It is recommended that the QDateTimeEdit is initialised with a datetime, e.g.

    QDateTimeEdit *dateTimeEdit = new QDateTimeEdit( QDateTime::currentDateTime(), this );
    dateTimeEdit->dateEdit()->setRange( QDateTime::currentDate(),
                                        QDateTime::currentDate().addDays( 7 ) );
Here we've created a new QDateTimeEdit set to the current date and time, and set the date to have a minimum date of now and a maximum date of a week from now.

Terminology: A QDateEdit widget consists of three 'sections', one each for the year, month and day. Similarly a QTimeEdit consists of three sections, one each for the hour, minute and second. The character that separates each date section is specified with setDateSeparator(); similarly setTimeSeparator() is used for the time sections.

Date Time Widgets

See also QDateEdit, QTimeEdit, Advanced Widgets and Time and Date.

Member Function Documentation

QDateTimeEdit::QDateTimeEdit ( QWidget * parent = 0, const char * name = 0 )

Constructs an empty datetime edit with parent parent and name name.

QDateTimeEdit::QDateTimeEdit ( const QDateTime & datetime, QWidget * parent = 0, const char * name = 0 )

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

Constructs a datetime edit with the initial value datetime, parent parent and name name.

QDateTimeEdit::~QDateTimeEdit ()

Destroys the object and frees any allocated resources.

bool QDateTimeEdit::autoAdvance () const

Returns TRUE if auto-advance is enabled, otherwise returns FALSE.

See also setAutoAdvance().

QDateEdit * QDateTimeEdit::dateEdit ()

Returns the internal widget used for editing the date part of the datetime.

QDateTime QDateTimeEdit::dateTime () const

Returns the datetime value of the editor. See the "dateTime" property for details.

void QDateTimeEdit::setAutoAdvance ( bool advance ) [virtual]

Sets the auto advance property of the editor to advance. If set to TRUE, the editor will automatically advance focus to the next date or time section if the user has completed a section.

void QDateTimeEdit::setDateTime ( const QDateTime & dt ) [virtual]

Sets the datetime value of the editor to dt. See the "dateTime" property for details.

QTimeEdit * QDateTimeEdit::timeEdit ()

Returns the internal widget used for editing the time part of the datetime.

void QDateTimeEdit::valueChanged ( const QDateTime & datetime ) [signal]

This signal is emitted every time the date or time changes. The datetime argument is the new datetime.

Property Documentation

QDateTime dateTime

This property holds the datetime value of the editor.

The datetime edit's datetime which may be an invalid datetime.

Set this property's value with setDateTime() and get this property's value with dateTime().

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


qdatetimeedit.h Include File

qdatetimeedit.h

This is the verbatim text of the qdatetimeedit.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of date and time edit classes
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDATETIMEEDIT_H
#define QDATETIMEEDIT_H

#ifndef QT_H
#include "qwidget.h"
#include "qstring.h"
#include "qdatetime.h"
#endif // QT_H

#ifndef QT_NO_DATETIMEEDIT

class Q_EXPORT QDateTimeEditBase : public QWidget
{
    Q_OBJECT
public:
    QDateTimeEditBase( QWidget* parent=0, const char* name=0 )
    : QWidget( parent, name ) {}

    virtual bool setFocusSection( int sec ) = 0;
    virtual QString sectionFormattedText( int sec ) = 0;
    virtual void addNumber( int sec, int num ) = 0;
    virtual void removeLastNumber( int sec ) = 0;

public slots:
    virtual void stepUp() = 0;
    virtual void stepDown() = 0;
};

class QDateEditPrivate;

class Q_EXPORT QDateEdit : public QDateTimeEditBase
{
    Q_OBJECT
    Q_ENUMS( Order )
    Q_PROPERTY( Order order READ order WRITE setOrder )
    Q_PROPERTY( QDate date READ date WRITE setDate )
    Q_PROPERTY( bool autoAdvance READ autoAdvance WRITE setAutoAdvance )
    Q_PROPERTY( QDate maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( QDate minValue READ minValue WRITE setMinValue )

public:
    QDateEdit( QWidget* parent=0,  const char* name=0 );
    QDateEdit( const QDate& date, QWidget* parent=0,  const char* name=0 );
    ~QDateEdit();

    enum Order {
    DMY,
    MDY,
    YMD,
    YDM
    };

    QSize sizeHint() const;
    QSize minimumSizeHint() const;
    virtual void setDate( const QDate& date );
    QDate date() const;
    virtual void setOrder( Order order );
    Order order() const;
    virtual void setAutoAdvance( bool advance );
    bool autoAdvance() const;

    virtual void setMinValue( const QDate& d ) { setRange( d, maxValue() ); }
    QDate minValue() const;
    virtual void setMaxValue( const QDate& d ) { setRange( minValue(), d ); }
    QDate maxValue() const;
    virtual void setRange( const QDate& min, const QDate& max );
    QString separator() const;
    virtual void setSeparator( const QString& s );

signals:
    void valueChanged( const QDate& date );

protected:
    bool event( QEvent *e );
    void timerEvent ( QTimerEvent * );
    void resizeEvent ( QResizeEvent * );
    void stepUp();
    void stepDown();
    QString sectionFormattedText( int sec );
    void addNumber( int sec, int num );
    void removeLastNumber( int sec );
    bool setFocusSection( int s );

    virtual void setYear( int year );
    virtual void setMonth( int month );
    virtual void setDay( int day );
    virtual void fix();
    virtual bool outOfRange( int y, int m, int d ) const;

protected slots:
    void updateButtons();

private:
    void init();
    int sectionOffsetEnd( int sec ) const;
    int sectionLength( int sec ) const;
    QString sectionText( int sec ) const;
    QDateEditPrivate* d;
};

class QTimeEditPrivate;

class Q_EXPORT QTimeEdit : public QDateTimeEditBase
{
    Q_OBJECT
    Q_PROPERTY( QTime time READ time WRITE setTime )
    Q_PROPERTY( bool autoAdvance READ autoAdvance WRITE setAutoAdvance )
    Q_PROPERTY( QTime maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( QTime minValue READ minValue WRITE setMinValue )

public:
    QTimeEdit( QWidget* parent=0,  const char* name=0 );
    QTimeEdit( const QTime& time, QWidget* parent=0,  const char* name=0 );
    ~QTimeEdit();

    QSize sizeHint() const;
    QSize minimumSizeHint() const;
    virtual void setTime( const QTime& time );
    QTime time() const;
    virtual void setAutoAdvance( bool advance );
    bool autoAdvance() const;

    virtual void setMinValue( const QTime& d ) { setRange( d, maxValue() ); }
    QTime minValue() const;
    virtual void setMaxValue( const QTime& d ) { setRange( minValue(), d ); }
    QTime maxValue() const;
    virtual void setRange( const QTime& min, const QTime& max );
    QString separator() const;
    virtual void setSeparator( const QString& s );

signals:
    void valueChanged( const QTime& time );

protected:
    bool event( QEvent *e );
    void timerEvent ( QTimerEvent *e );
    void resizeEvent ( QResizeEvent * );
    void stepUp();
    void stepDown();
    QString sectionFormattedText( int sec );
    void addNumber( int sec, int num );
    void removeLastNumber( int sec );
    bool setFocusSection( int s );

    virtual bool outOfRange( int h, int m, int s ) const;
    virtual void setHour( int h );
    virtual void setMinute( int m );
    virtual void setSecond( int s );

protected slots:
    void updateButtons();

private:
    void init();
    QString sectionText( int sec );
    QTimeEditPrivate* d;
};

class QDateTimeEditPrivate;

class Q_EXPORT QDateTimeEdit : public QWidget
{
    Q_OBJECT
    Q_PROPERTY( QDateTime dateTime READ dateTime WRITE setDateTime )

public:
    QDateTimeEdit( QWidget* parent=0, const char* name=0 );
    QDateTimeEdit( const QDateTime& datetime, QWidget* parent=0,
           const char* name=0 );
    ~QDateTimeEdit();

    QSize sizeHint() const;
    QSize minimumSizeHint() const;
    virtual void  setDateTime( const QDateTime & dt );
    QDateTime dateTime() const;

    QDateEdit* dateEdit() { return de; }
    QTimeEdit* timeEdit() { return te; }

    virtual void setAutoAdvance( bool advance );
    bool autoAdvance() const;

signals:
    void valueChanged( const QDateTime& datetime );

protected:
    void init();
    void resizeEvent( QResizeEvent * );
    void layoutEditors();

protected slots:
    void newValue( const QDate& d );
    void newValue( const QTime& t );

private:
    QDateEdit* de;
    QTimeEdit* te;
    QDateTimeEditPrivate* d;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDateTimeEdit Member List

Complete Member List for QDateTimeEdit

This is the complete list of member functions for QDateTimeEdit, including inherited members.

  • QDateTimeEdit()
  • ~QDateTimeEdit()
  • acceptDrops()
  • adjustSize()
  • autoAdvance()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • dateEdit()
  • dateTime()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoAdvance()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDateTime()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timeEdit()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • valueChanged()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDesktopWidget Class

QDesktopWidget Class Reference

The QDesktopWidget class provides access to screen information on multi-head systems. More...

#include <qdesktopwidget.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QDesktopWidget ()
  • ~QDesktopWidget ()
  • bool isVirtualDesktop () const
  • int numScreens () const
  • int primaryScreen () const
  • int screenNumber ( QWidget * widget = 0 ) const
  • int screenNumber ( const QPoint & point ) const
  • QWidget * screen ( int screen = -1 )
  • const QRect & screenGeometry ( int screen = -1 ) const

Detailed Description

The QDesktopWidget class provides access to screen information on multi-head systems.

Systems with more than one graphics card and monitor can manage the physical screen space available either as multiple desktops, or as a large virtual desktop, which usually has the size of the bounding rectangle of all the screens (see isVirtualDesktop()). For an application, one of the available screens is the primary screen, i.e. the screen where the main widget resides (see primaryScreen()). All windows opened in the context of the application must be constrained to the boundaries of the primary screen; for example, it would be inconvenient if a dialog box popped up on a different screen, or split over two screens.

The QDesktopWidget provides information about the geometry of the available screens with screenGeometry(). The number of screens available is returned by numScreens(). The screen number that a particular point or widget is located in is returned by screenNumber().

Widgets provided by Qt use this class, for example, to place tooltips, menus and dialog boxes according to the parent or application widget.

Applications can use this class to save window positions, or to place child widgets on one screen.

Managing Multiple Screens

In the illustration above, Application One's primary screen is screen 0, and App Two's primary screen is screen 1.

See also Advanced Widgets and Environment Classes.

Member Function Documentation

QDesktopWidget::QDesktopWidget ()

Creates the desktop widget.

If the system supports a virtual desktop, this widget will have the size of the virtual desktop; otherwise this widget will have the size of the primary screen.

Instead of using QDesktopWidget directly, use QAppliation::desktop().

QDesktopWidget::~QDesktopWidget ()

Destroy the object and free allocated resources.

bool QDesktopWidget::isVirtualDesktop () const

Returns TRUE if the system manages the available screens in a virtual desktop; otherwise returns FALSE.

For virtual desktops, screen() will always return the same widget. The size of the virtual desktop is the size of this desktop widget.

int QDesktopWidget::numScreens () const

Returns the number of available screens.

See also primaryScreen().

int QDesktopWidget::primaryScreen () const

Returns the index of the primary screen.

See also numScreens().

QWidget * QDesktopWidget::screen ( int screen = -1 )

Returns a widget that represents the screen with index screen. This widget can be used to draw directly on the desktop, using an unclipped painter like this:

    QPainter paint( QApplication::desktop()->screen( 0 ), TRUE );
    paint.draw...
    ...
    paint.end();

If the system uses a virtual desktop, the returned widget will have the geometry of the entire virtual desktop i.e. bounding every screen.

See also primaryScreen(), numScreens() and isVirtualDesktop().

const QRect & QDesktopWidget::screenGeometry ( int screen = -1 ) const

Returns the geometry of the screen with index screen.

See also screenNumber().

int QDesktopWidget::screenNumber ( QWidget * widget = 0 ) const

Returns the index of the screen that contains the largest part of widget, or -1 if the widget is not on a screen.

See also primaryScreen().

int QDesktopWidget::screenNumber ( const QPoint & point ) const

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

Returns the index of the screen that contains point, or -1 if no screen contains the point.

See also primaryScreen().

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


qdesktopwidget.h Include File

qdesktopwidget.h

This is the verbatim text of the qdesktopwidget.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QDesktopWidget class.
**
** Created :
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Unix/X11 may use this file in accordance with the Qt Commercial
** License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDESKTOPWIDGET_H
#define QDESKTOPWIDGET_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

class QDesktopWidgetPrivate; /* Don't touch! */

class Q_EXPORT QDesktopWidget : public QWidget
{
    Q_OBJECT
public:
    QDesktopWidget();
    ~QDesktopWidget();

    bool isVirtualDesktop() const;

    int numScreens() const;
    int primaryScreen() const;

    int screenNumber( QWidget *widget = 0 ) const;
    int screenNumber( const QPoint & ) const;

    QWidget *screen( int screen = -1 );

    const QRect& screenGeometry( int screen = -1 ) const;

    // ### use Qt::HANDLE ?
    // ### if related, reimplement QPaintDevice::handle() to avoid warnings
#ifdef Q_WS_MAC
    GDHandle handle( int screen ) const;
#else
    // void *handle( int ) const { return 0; }
#endif

private:
    QDesktopWidgetPrivate *d;
};

#endif //QDESKTOPWIDGET_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDesktopWidget Member List

Complete Member List for QDesktopWidget

This is the complete list of member functions for QDesktopWidget, including inherited members.

  • QDesktopWidget()
  • ~QDesktopWidget()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVirtualDesktop()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numScreens()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • primaryScreen()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • screen()
  • screenGeometry()
  • screenNumber()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDial Class

QDial Class Reference

The QDial class provides a rounded range control (like a speedometer or potentiometer). More...

#include <qdial.h>

Inherits QWidget and QRangeControl.

List of all member functions.

Public Members

  • QDial ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • QDial ( int minValue, int maxValue, int pageStep, int value, QWidget * parent = 0, const char * name = 0 )
  • ~QDial ()
  • bool tracking () const
  • bool wrapping () const
  • int notchSize () const
  • virtual void setNotchTarget ( double )
  • double notchTarget () const
  • bool notchesVisible () const
  • int minValue () const
  • int maxValue () const
  • void setMinValue ( int )
  • void setMaxValue ( int )
  • int lineStep () const
  • int pageStep () const
  • void setLineStep ( int )
  • void setPageStep ( int )
  • int value () const

Public Slots

  • virtual void setValue ( int )
  • void addLine ()
  • void subtractLine ()
  • void addPage ()
  • void subtractPage ()
  • virtual void setNotchesVisible ( bool b )
  • virtual void setWrapping ( bool on )
  • virtual void setTracking ( bool enable )

Signals

  • void valueChanged ( int value )
  • void dialPressed ()
  • void dialMoved ( int value )
  • void dialReleased ()

Properties

  • int lineStep - the current line step
  • int maxValue - the current maximum value
  • int minValue - the current minimum value
  • int notchSize - the current notch size (read only)
  • double notchTarget - the target number of pixels between notches
  • bool notchesVisible - whether the notches are shown
  • int pageStep - the current page step
  • bool tracking - whether tracking is enabled
  • int value - the current dial value
  • bool wrapping - whether wrapping is enabled

Protected Members

  • virtual void valueChange ()
  • virtual void rangeChange ()
  • virtual void repaintScreen ( const QRect * cr = 0 )

Detailed Description

The QDial class provides a rounded range control (like a speedometer or potentiometer).

QDial is used when the user needs to control a value within a program-definable range, and the range either wraps around (typically, 0..359 degrees) or the dialog layout needs a square widget.

Both API- and UI-wise, the dial is very similar to a slider. Indeed, when wrapping() is FALSE (the default) there is no real difference between a slider and a dial. They have the same signals, slots and member functions, all of which do the same things. Which one you use depends only on your taste and on the application.

The dial initially emits valueChanged() signals continuously while the slider is being moved; you can make it emit the signal less often by calling setTracking(FALSE). dialMoved() is emitted continuously even when tracking() is FALSE.

The slider also emits dialPressed() and dialReleased() signals when the mouse button is pressed and released. But note that the dial's value can change without these signals being emitted; the keyboard and wheel can be used to change the value.

Unlike the slider, QDial attempts to draw a "nice" number of notches rather than one per lineStep(). If possible, the number of notches drawn is one per lineStep(), but if there aren't enough pixels to draw every one, QDial will draw every second, third etc., notch. notchSize() returns the number of units per notch, hopefully a multiple of lineStep(); setNotchTarget() sets the target distance between neighbouring notches in pixels. The default is 3.75 pixels.

Like the slider, the dial makes the QRangeControl functions setValue(), addLine(), subtractLine(), addPage() and subtractPage() available as slots.

The dial's keyboard interface is fairly simple: The left/up and right/down arrow keys move by lineStep(), page up and page down by pageStep() and Home and End to minValue() and maxValue().

See also QScrollBar, QSpinBox, GUI Design Handbook: Slider and Basic Widgets.

Member Function Documentation

QDial::QDial ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a dial called name with parent parent. f is propagated to the QWidget constructor. It has the default range of a QRangeControl.

QDial::QDial ( int minValue, int maxValue, int pageStep, int value, QWidget * parent = 0, const char * name = 0 )

Constructs a dial called name with parent parent. The dial's value can never be smaller than minValue or greater than maxValue. Its page step size is pageStep, and its initial value is value.

value is forced to be within the legal range.

QDial::~QDial ()

Destroys the dial.

void QDial::addLine () [slot]

Increments the dial's value() by one lineStep().

void QDial::addPage () [slot]

Increments the dial's value() by one pageStep() of steps.

void QDial::dialMoved ( int value ) [signal]

This signal is emitted whenever the dial value changes. The frequency of this signal is not influenced by setTracking().

See also valueChanged().

void QDial::dialPressed () [signal]

This signal is emitted when the use begins mouse interaction with the dial.

See also dialReleased().

void QDial::dialReleased () [signal]

This signal is emitted when the use ends mouse interaction with the dial.

See also dialPressed().

int QDial::lineStep () const

Returns the current line step. See the "lineStep" property for details.

int QDial::maxValue () const

Returns the current maximum value. See the "maxValue" property for details.

int QDial::minValue () const

Returns the current minimum value. See the "minValue" property for details.

int QDial::notchSize () const

Returns the current notch size. See the "notchSize" property for details.

double QDial::notchTarget () const

Returns the target number of pixels between notches. See the "notchTarget" property for details.

bool QDial::notchesVisible () const

Returns TRUE if the notches are shown; otherwise returns FALSE. See the "notchesVisible" property for details.

int QDial::pageStep () const

Returns the current page step. See the "pageStep" property for details.

void QDial::rangeChange () [virtual protected]

Reimplemented to ensure tick-marks are consistent with the new range.

Reimplemented from QRangeControl.

void QDial::repaintScreen ( const QRect * cr = 0 ) [virtual protected]

Paints the dial using clip region cr.

void QDial::setLineStep ( int )

Sets the current line step. See the "lineStep" property for details.

void QDial::setMaxValue ( int )

Sets the current maximum value. See the "maxValue" property for details.

void QDial::setMinValue ( int )

Sets the current minimum value. See the "minValue" property for details.

void QDial::setNotchTarget ( double ) [virtual]

Sets the target number of pixels between notches. See the "notchTarget" property for details.

void QDial::setNotchesVisible ( bool b ) [virtual slot]

Sets whether the notches are shown to b. See the "notchesVisible" property for details.

void QDial::setPageStep ( int )

Sets the current page step. See the "pageStep" property for details.

void QDial::setTracking ( bool enable ) [virtual slot]

Sets whether tracking is enabled to enable. See the "tracking" property for details.

void QDial::setValue ( int ) [virtual slot]

Sets the current dial value. See the "value" property for details.

void QDial::setWrapping ( bool on ) [virtual slot]

Sets whether wrapping is enabled to on. See the "wrapping" property for details.

void QDial::subtractLine () [slot]

Decrements the dial's value() by one lineStep().

void QDial::subtractPage () [slot]

Decrements the dial's value() by one pageStep() of steps.

bool QDial::tracking () const

Returns TRUE if tracking is enabled; otherwise returns FALSE. See the "tracking" property for details.

int QDial::value () const

Returns the current dial value. See the "value" property for details.

void QDial::valueChange () [virtual protected]

Reimplemented to ensure the display is correct and to emit the valueChanged(int) signal when appropriate.

Reimplemented from QRangeControl.

void QDial::valueChanged ( int value ) [signal]

This signal is emitted whenever the dial's value changes. The frequency of this signal is influenced by setTracking().

bool QDial::wrapping () const

Returns TRUE if wrapping is enabled; otherwise returns FALSE. See the "wrapping" property for details.

Property Documentation

int lineStep

This property holds the current line step.

setLineStep() calls the virtual stepChange() function if the new line step is different from the previous setting.

See also QRangeControl::setSteps(), pageStep and setRange().

Set this property's value with setLineStep() and get this property's value with lineStep().

int maxValue

This property holds the current maximum value.

When setting this property, the QDial::minValue is adjusted so that the range remains valid if necessary.

See also setRange().

Set this property's value with setMaxValue() and get this property's value with maxValue().

int minValue

This property holds the current minimum value.

When setting this property, the QDial::maxValue is adjusted so that the range remains valid if necessary.

See also setRange().

Set this property's value with setMinValue() and get this property's value with minValue().

int notchSize

This property holds the current notch size.

The notch size is in range control units, not pixels, and if possible it is a multiple of lineStep() that results in an on-screen notch size near notchTarget().

See also notchTarget and lineStep.

Get this property's value with notchSize().

double notchTarget

This property holds the target number of pixels between notches.

The notch target is the number of pixels QDial attempts to put between each notch.

The actual size may differ from the target size.

Set this property's value with setNotchTarget() and get this property's value with notchTarget().

bool notchesVisible

This property holds whether the notches are shown.

If TRUE, the notches are shown. If FALSE (the default) notches are not shown.

Set this property's value with setNotchesVisible() and get this property's value with notchesVisible().

int pageStep

This property holds the current page step.

setPageStep() calls the virtual stepChange() function if the new page step is different from the previous setting.

See also stepChange().

Set this property's value with setPageStep() and get this property's value with pageStep().

bool tracking

This property holds whether tracking is enabled.

If TRUE (the default), tracking is enabled. This means that the arrow can be moved using the mouse; otherwise the arrow cannot be moved with the mouse.

Set this property's value with setTracking() and get this property's value with tracking().

int value

This property holds the current dial value.

This is guaranteed to be within the range QDial::minValue..QDial::maxValue.

See also minValue and maxValue.

Set this property's value with setValue() and get this property's value with value().

bool wrapping

This property holds whether wrapping is enabled.

If TRUE, wrapping is enabled. This means that the arrow can be turned around 360°. Otherwise there is some space at the bottom of the dial which is skipped by the arrow.

This property's default is FALSE.

Set this property's value with setWrapping() and get this property's value with wrapping().

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


qdial.h Include File

qdial.h

This is the verbatim text of the qdial.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qdial.h   3.0.5   edited Nov 9 2001 $
**
** Definition of the dial widget
**
** Created : 1999.01.04
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDIAL_H
#define QDIAL_H

#ifndef QT_H
#include "qwidget.h"
#include "qrangecontrol.h"
#endif // QT_H

#ifndef QT_NO_DIAL

class QDialPrivate;

class Q_EXPORT QDial: public QWidget, public QRangeControl
{
    Q_OBJECT
    Q_PROPERTY( bool tracking READ tracking WRITE setTracking )
    Q_PROPERTY( bool wrapping READ wrapping WRITE setWrapping )
    Q_PROPERTY( int notchSize READ notchSize )
    Q_PROPERTY( double notchTarget READ notchTarget WRITE setNotchTarget )
    Q_PROPERTY( bool notchesVisible READ notchesVisible WRITE setNotchesVisible )
    Q_PROPERTY( int minValue READ minValue WRITE setMinValue )
    Q_PROPERTY( int maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( int lineStep READ lineStep WRITE setLineStep )
    Q_PROPERTY( int pageStep READ pageStep WRITE setPageStep )
    Q_PROPERTY( int value READ value WRITE setValue )

public:
    QDial( QWidget* parent=0, const char* name=0, WFlags f = 0 );
    QDial( int minValue, int maxValue, int pageStep, int value,
       QWidget* parent=0, const char* name=0 );
    ~QDial();

    bool tracking() const;

    bool wrapping() const;

    int notchSize() const;

    virtual void setNotchTarget( double );
    double notchTarget() const;

    bool notchesVisible() const;

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    int	 minValue() const;
    int	 maxValue() const;
    void setMinValue( int );
    void setMaxValue( int );
    int	 lineStep() const;
    int	 pageStep() const;
    void setLineStep( int );
    void setPageStep( int );
    int  value() const;

public slots:
    virtual void setValue( int );
    void addLine();
    void subtractLine();
    void addPage();
    void subtractPage();
    virtual void setNotchesVisible( bool b );
    virtual void setWrapping( bool on );
    virtual void setTracking( bool enable );

signals:
    void valueChanged( int value );
    void dialPressed();
    void dialMoved( int value );
    void dialReleased();

protected:
    void resizeEvent( QResizeEvent * );
    void paintEvent( QPaintEvent * );

    void keyPressEvent( QKeyEvent * );
    void mousePressEvent( QMouseEvent * );
    void mouseReleaseEvent( QMouseEvent * );
    void mouseMoveEvent( QMouseEvent * );
#ifndef QT_NO_WHEELEVENT
    void wheelEvent( QWheelEvent * );
#endif
    void focusInEvent( QFocusEvent * );
    void focusOutEvent( QFocusEvent * );

    void valueChange();
    void rangeChange();

    virtual void repaintScreen( const QRect *cr = 0 );

private:
    QDialPrivate * d;

    int valueFromPoint( const QPoint & ) const;
    double angle( const QPoint &, const QPoint & ) const;
    QPointArray calcArrow( double &a ) const;
    QRect calcDial() const;
    int calcBigLineSize() const;
    void calcLines();

private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QDial( const QDial & );
    QDial &operator=( const QDial & );
#endif

};

#endif  // QT_NO_DIAL

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDial Member List

Complete Member List for QDial

This is the complete list of member functions for QDial, including inherited members.

  • QDial()
  • ~QDial()
  • acceptDrops()
  • addLine()
  • addPage()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bound()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • dialMoved()
  • dialPressed()
  • dialReleased()
  • directSetValue()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineStep()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maxValue()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minValue()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • notchSize()
  • notchTarget()
  • notchesVisible()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageStep()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • positionFromValue()
  • prevValue()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • rangeChange()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintScreen()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineStep()
  • setMask()
  • setMaxValue()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinValue()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNotchTarget()
  • setNotchesVisible()
  • setPageStep()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRange()
  • setSizeIncrement()
  • setSizePolicy()
  • setSteps()
  • setStyle()
  • setTabOrder()
  • setTracking()
  • setUpdatesEnabled()
  • setValue()
  • setWFlags()
  • setWrapping()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • stepChange()
  • style()
  • styleChange()
  • subtractLine()
  • subtractPage()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • tracking()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • value()
  • valueChange()
  • valueChanged()
  • valueFromPosition()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wrapping()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QDialog类

QDialog类参考

QDialog类是对话框窗口的基类。 详情请见……

#include <qdialog.h>

继承了QWidget。

被QColorDialog、QErrorMessage、QFileDialog、QFontDialog、QInputDialog、QMessageBox、QProgressDialog、QTabDialog和QWizard继承。

所有成员函数的列表。

公有成员

  • QDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )
  • ~QDialog ()
  • enum DialogCode { Rejected, Accepted }
  • int result () const
  • virtual void show ()
  • void setOrientation ( Orientation orientation )
  • Orientation orientation () const
  • void setExtension ( QWidget * extension )
  • QWidget * extension () const
  • void setSizeGripEnabled ( bool )
  • bool isSizeGripEnabled () const

公有槽

  • int exec ()

属性

  • bool sizeGripEnabled - 大小控制是否生效

保护成员

  • void setResult ( int i )

保护槽

  • virtual void done ( int r )
  • virtual void accept ()
  • virtual void reject ()
  • void showExtension ( bool showIt )

详细描述

QDialog类是对话框窗口的基类。

对话框窗口是主要用于短期任务以及和用户进行简要通讯的顶级窗口。QDialog可以是模式的也可以是非模式的。QDialog支持扩展性并且可以提供返回值。它们可以有默认按钮。QDialog也可以有一个QSizeGrip在它的右下角，使用setSizeGripEnabled()。

注意QDialog使用父窗口部件的方法和Qt中其它类稍微不同。对话框总是顶级窗口部件，但是如果它有一个父对象，它的默认位置就是父对象的中间。它也将和父对象共享工具条条目。

这里有三种有用的对话框：

  1. 模式对话框就是阻塞同一应用程序中其它可视窗口的输入的对话框：用户必须完成这个对话框中的交互操作并且关闭了它之后才能访问应用程序中的其它任何窗口。模式对话框有它们自己的本地事件循环。用来让用户选择一个文件或者用来设置应用程序参数的对话框通常是模式的。调用exec()来显示模式对话框。当用户关闭这个对话框，exec()将提供一个可用的返回值并且这时流程控制继续从调用exec()的地方进行。通常，我们连接默认按钮，例如“OK”到accept()槽并且把“Cancel”连接到reject()槽，来使对话框关闭并且返回适当的值。另外我们也可以连接done()槽，传递给它Accepted或Rejected。

  2. 非模式对话框是和同一个程序中其它窗口操作无关的对话框。在字处理软件中查找和替换对话框通常是非模式的来允许同时与应用程序主窗口和对话框进行交互。调用show()来显示非模式对话框。show()立即返回，这样调用代码中的控制流将会继续。在实践中你将会经常调用show()并且在调用show()的函数最后，控制返回主事件循环。

  3. “半模式”对话框是立即把控制返回给调用者的模式对话框。半模式对话框没有它们自己的事件循环，所以你将需要周期性地调用QApplication::processEvents()来让这个半模式对话框有处理它的事件的机会。进程对话框（例如QProgressDialog）就是一个实例，在你想让用户能够和进程对话框交互的地方那个，例如撤销一个长期运行的操作，但是需要实际上执行这个操作。半模式对话框模式标记被设置为真并且调用show()函数来被显示。

默认按钮

对话框的“默认”按钮适当用户按下回车键或者换行键时被按下的按钮。这个按钮用来表示用户接受对话框的设置并且希望关闭这个对话框。使用QPushButton::setDefault()、QPushButton::isDefault()和QPushButton::autoDefault()来设置并且控制对话框的默认按钮。

扩展性

扩展性是可以用两种方式来显示对话框：一个局部对话框用来显示通常最常用的选项，和一个显示所有选项的完全对话框。通常可扩展的对话框将初始化为一个局部对话框，但是有一个“更多”按钮。如果用户点击这个“更多”按钮，完全对话框将会出现。扩展性是由setExtension()、setOrientation()和showExtension()。

返回值（模式对话框）

模式对话框通常用在需要返回值的地方，例如需要分清用户按下“OK”还是“Cancel”。对话框可以通过调用accept()或reject()槽来被关闭，并且exec()将返回适当的Accepted或Rejected。exec()返回这个对话框的结果。如果窗口还没有被销毁，这个结果也可以通过result()得到。如果WDestructiveClose标记被设置，那么当exec()返回时，对话框被删除。

实例

模式对话框。

        QFileDialog *dlg = new QFileDialog( workingDirectory,
                QString::null, 0, 0, TRUE );
        dlg->setCaption( QFileDialog::tr( "Open" ) );
        dlg->setMode( QFileDialog::ExistingFile );
        QString result;
        if ( dlg->exec() == QDialog::Accepted ) {
            result = dlg->selectedFile();
            workingDirectory = dlg->url();
        }
        delete dlg;
        return result;

非模式对话框。在show()调用之后，控制返回到主事件循环中。

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

        int scale = 10;

        LifeDialog *life = new LifeDialog( scale );
        a.setMainWidget( life );
        life->setCaption("Qt Example - Life");
        life->show();

        return a.exec();
    }

半模式对话框的实例请参考QProgressDialog文档。

请参考QTabDialog、QWidget、QProgressDialog、GUI Design Handbook: Dialogs, Standard、抽象窗口部件类和对话框类。

成员类型文档

QDialog::DialogCode

模式对话框返回的值。

  • QDialog::Accepted
  • QDialog::Rejected

成员函数文档

QDialog::QDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )

构造一个父对象为parent、名称为name的对话框。

如果modal为假（默认），这个对话框是非模式的并且应该使用show()来被显示。如果modal为真，这个对话框使用exec()来被显示，则它是模式的，也就是说会阻塞这个应用程序中其它窗口的输入。如果modal为真并且使用show()来被显示，则它是半模式的。

窗口部件f将被传递给QWidget的构造函数。

如果，例如，我们不想要对话框的标题栏中“这是什么”按钮，在f中传递WStyle_Customize | WStyle_NormalBorder | WStyle_Title | WStyle_SysMenu。

我们建议你传递一个非空的父对象。

请参考QWidget::setWFlags()和Qt::WidgetFlags。

QDialog::~QDialog ()

销毁这个对话框，删除它所有的子对象。

void QDialog::accept () [虚 保护 槽]

隐藏模式对话框并且设置结果代码为Accepted。

请参考reject()和done()。

实例：chart/setdataform.cpp。

void QDialog::done ( int r ) [虚 保护 槽]

隐藏模式对话框并且设置结果代码为r。这将使用本地事件循环来完成，并且exec()返回r。

如果对话框使用WDestructiveClose来被设置，done()也会销毁这个对话框。如果对话框是应用程序的主窗口部件，那么应用程序终止。

请参考accept()、reject()、QApplication::mainWidget()和QApplication::quit()。

int QDialog::exec () [槽]

执行模式对话框。控制传递给这个对话框一直到用户关闭它，在本地事件循环完成的点并且函数返回DialogCode结果。在用户关闭这个对话框之前，不能和同一应用程序中的其它窗口交互。对于非模式或半模式对话框请使用show()。

请参考show()和result()。

实例：chart/chartform.cpp、i18n/main.cpp、network/networkprotocol/view.cpp、a href="qdir-example.html#x1805">qdir/qdir.cpp、showimg/showimg.cpp和wizard/main.cpp。

QWidget * QDialog::extension () const

返回对话框的扩展或者如果没有扩展被定义返回0。

请参考setExtension()。

bool QDialog::isSizeGripEnabled () const

如果大小控制生效，返回真，否则返回假。详细情况请参考“sizeGripEnabled”属性。

Orientation QDialog::orientation () const

返回对话框的扩展方向。

请参考setOrientation()。

void QDialog::reject () [虚 保护 槽]

隐藏模式对话框并且设置结果代码为Rejected。

请参考accept()和done()。

int QDialog::result () const

返回模式对话框的结果代码，Accepted或Rejected。

如果对话框使用WDestructiveClose标记构造，不要调用这个函数。（无论如何，exec()返回结果代码。）

void QDialog::setExtension ( QWidget * extension )

设置窗口部件extension为对话框的扩展，删除任何以前的扩展。对话框拥有扩展的所有权。注意如果传递0，则任何存在的扩展都将被删除。

只有当对话框被隐藏时，这个函数才能被调用。

请参考showExtension()、setOrientation()和extension()。

void QDialog::setOrientation ( Orientation orientation )

如果orientation是Horizontal，扩展将会显示在对话框主区域的右面。如果orientation是Vertical，扩展将会显示在对话框主区域的下面。

请参考orientation()和setExtension()。

void QDialog::setResult ( int i ) [保护]

设置模式对话框的结果代码为i。

void QDialog::setSizeGripEnabled ( bool )

设置大小控制是否生效。详细情况请参考“sizeGripEnabled”属性。

void QDialog::show () [虚]

显示非模式或半模式对话框。控制立即返回到调用代码中。

对话框没有一个本地事件循环，所以你必须定时地调用QApplication::processEvents()来使对话框能够得到处理它的事件的机会。

如果在构造函数中，模式标记被设置为真，对话框将为半模式。

警告：

在Qt 2.x中，在一个模式对话框中调用show()进入一个本地事件循环并且像exec()一样工作，但是不返回exec()所返回的结果代码。Trolltech已经一直警告这样做是不被建议的。

请参考exec()。

实例：movies/main.cpp、showimg/showimg.cpp和sql/overview/form1/main.cpp。

从QWidget中重新实现的。

void QDialog::showExtension ( bool showIt ) [保护 槽]

如果showIt为真，对话框的扩展被显示，否则扩展被隐藏。

这个槽通常被连接到QPushButton的QButton::toggled()信号上。

如果对话框不是可视的，或者没有扩展，则什么都不会发生。

请参考show()、setExtension()和setOrientation()。

属性文档

bool sizeGripEnabled

这个属性保存的是大小控制是否生效。

当这个属性生效时，QSizeGrip被放置到对话框的右下角。默认情况下，大小控制失效。

通过setSizeGripEnabled()设置属性值并且通过isSizeGripEnabled()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdialog.h包含文件

qdialog.h

这里是qdialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QDialog class
**
** Created : 950502
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDIALOG_H
#define QDIALOG_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H
#ifndef QT_NO_DIALOG
#if 0
Q_OBJECT
#endif

class QPushButton;
class QDialogPrivate;

class Q_EXPORT QDialog : public QWidget			// dialog widget
{
friend class QPushButton;
    Q_OBJECT
    Q_PROPERTY( bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled )

public:
    QDialog( QWidget* parent=0, const char* name=0, bool modal=FALSE,
         WFlags f=0 );
    ~QDialog();

    enum DialogCode { Rejected, Accepted };

    int		result()  const { return rescode; }

    void	show();
    void	hide();
    void	move( int x, int y );
    void	move( const QPoint &p );
    void	resize( int w, int h );
    void	resize( const QSize & );
    void	setGeometry( int x, int y, int w, int h );
    void	setGeometry( const QRect & );

    void	setOrientation( Orientation orientation );
    Orientation	orientation() const;

    void	setExtension( QWidget* extension );
    QWidget* extension() const;

    QSize	sizeHint() const;
    QSize	minimumSizeHint() const;

    void setSizeGripEnabled(bool);
    bool isSizeGripEnabled() const;

public slots:
    int exec();

protected slots:
    virtual void done( int );
    virtual void accept();
    virtual void reject();

    void	showExtension( bool );

protected:
    void	setResult( int r )	{ rescode = r; }
    void	keyPressEvent( QKeyEvent * );
    void	closeEvent( QCloseEvent * );
    void	resizeEvent( QResizeEvent * );
    void 	contextMenuEvent( QContextMenuEvent * );
    bool 	eventFilter( QObject *, QEvent * );
    void     adjustPosition( QWidget*);

private:
    void	setDefault( QPushButton * );
    void		hideDefault();
    int		rescode;
    uint	did_move   : 1;
    uint 	has_relpos : 1;
    uint	did_resize : 1;
    uint	in_loop: 1;
    void adjustPositionInternal( QWidget*, bool useRelPos = FALSE );
    QDialogPrivate* d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QDialog( const QDialog & );
    QDialog &operator=( const QDialog & );
#endif
};

#endif // QT_NO_DIALOG
#endif // QDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDialog成员列表

完整的QDialog成员列表

这里是QDialog成员函数的完整列表，包括继承的成员。

  • QDialog()
  • ~QDialog()
  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDict Class

QDict Class Reference

The QDict class is a template class that provides a dictionary based on QString keys. More...

#include <qdict.h>

Inherits QPtrCollection.

List of all member functions.

Public Members

  • QDict ( int size = 17, bool caseSensitive = TRUE )
  • QDict ( const QDict<type> & dict )
  • ~QDict ()
  • QDict<type> & operator= ( const QDict<type> & dict )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • void insert ( const QString & key, const type * item )
  • void replace ( const QString & key, const type * item )
  • bool remove ( const QString & key )
  • type * take ( const QString & key )
  • type * find ( const QString & key ) const
  • type * operator[] ( const QString & key ) const
  • virtual void clear ()
  • void resize ( uint newsize )
  • void statistics () const

Important Inherited Members

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

Protected Members

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item ) const

Detailed Description

The QDict class is a template class that provides a dictionary based on QString keys.

QMap is an STL-compatible alternative to this class.

QDict is implemented as a template class. Define a template instance QDict<X> to create a dictionary that operates on pointers to X (X*).

A dictionary is a collection of key-value pairs. The key is a QString used for insertion, removal and lookup. The value is a pointer. Dictionaries provide very fast insertion and lookup.

If you want to use non-Unicode, plain 8-bit char* keys, use the QAsciiDict template. A QDict has the same performance as a QAsciiDict. If you want to have a dictionary that maps QStrings to QStrings use QMap.

The size() of the dictionary is very important. In order to get good performance, you should use a suitably large prime number. Suitable means equal to or larger than the maximum expected number of dictionary items. Size is set in the constructor but may be changed with resize().

Items are inserted with insert(), and removed with remove(). All the items in a dictionary can be removed with clear(). The number of items in the dictionary is returned by count(). If the dictionary contains no items isEmpty() returns TRUE. You can change an item's value with replace(). Items are looked up with operator[](), or with find() which return a pointer to the value or 0 if the given key does not exist. You can take an item out of the dictionary with take().

Calling setAutoDelete(TRUE) for a dictionary tells it to delete items that are removed. The default behaviour is not to delete items when they are removed.

QDict is implemented by QGDict as a hash array with a fixed number of entries. Each array entry points to a singly linked list of buckets, in which the dictionary items are stored. When an item is inserted with a key, the key is converted (hashed) to an integer index into the hash array. The item is inserted before the first bucket in the list of buckets.

Looking up an item is normally very fast. The key is again hashed to an array index. Then QDict scans the list of buckets and returns the item found or null if the item was not found. You cannot insert null pointers into a dictionary.

Items with equal keys are allowed. When inserting two items with the same key, only the last inserted item will be visible (last in, first out) until it is removed.

The QDictIterator class can traverse the dictionary, but only in an arbitrary order. Multiple iterators may independently traverse the same dictionary.

When inserting an item into a dictionary, only the pointer is copied, not the item itself, i.e. a shallow copy is made. It is possible to make the dictionary copy all of the item's data (a deep copy) when an item is inserted. insert() calls the virtual function QPtrCollection::newItem() for the item to be inserted. Inherit a dictionary and reimplement it if you want deep copies.

When removing a dictionary item, the virtual function QPtrCollection::deleteItem() is called. QDict's default implementation is to delete the item if auto-deletion is enabled.

Example #1:

    QDict<QLineEdit> fields;
    fields.insert( "forename", new QLineEdit( this ) );
    fields.insert( "surname", new QLineEdit( this ) );

    fields["forename"]->setText( "Homer" );
    fields["surname"]->setText( "Simpson" );

    QDictIterator<char> it( extra ); // See QDictIterator
    for( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;
    cout << endl;

    if ( fields["forename"] && fields["surname"] )
        cout << fields["forename"]->text() << " "
            << fields["surname"]->text() << endl;  // Prints "Homer Simpson"

    fields.remove( "forename" ); // Does not delete the line edit
    if ( ! fields["forename"] )
        cout << "forename is not in the dictionary" << endl;
In this example we use a dictionary to keep track of the line edits we're using. We insert each line edit into the dictionary with a unique name and then access the line edits via the dictionary.

Example #2:

    QStringList styleList = QStyleFactory::styles();
    styleList.sort();
    QDict<int> letterDict( 17, FALSE );
    for ( QStringList::Iterator it = styleList.begin(); it != styleList.end(); ++it ) {
        QString styleName = *it;
        QString styleAccel = styleName;
        if ( letterDict[styleAccel.left(1)] ) {
            for ( uint i = 0; i < styleAccel.length(); i++ ) {
                if ( ! letterDict[styleAccel.mid( i, 1 )] ) {
                    styleAccel = styleAccel.insert( i, '&' );
                    letterDict.insert(styleAccel.mid( i, 1 ), (const int *)1);
                    break;
                }
            }
        } else {
            styleAccel = "&" + styleAccel;
            letterDict.insert(styleAccel.left(1), (const int *)1);
        }
        (void) new QAction( styleName, QIconSet(), styleAccel, parent );
    }
In the example we are using the dictionary to provide fast random access to the keys, and we don't care what the values are. The example is used to generate a menu of QStyles, each with a unique accelerator key (or no accelerator if there are no unused letters left).

We first obtain the list of available styles, then sort them so that the menu items will be ordered alphabetically. Next we create a dictionary of int pointers. The keys in the dictionary are each one character long, representing letters that have been used for accelerators. We iterate through our list of style names. If the first letter of the style name is in the dictionary, i.e. has been used, we iterate over all the characters in the style name to see if we can find a letter that hasn't been used. If we find an unused letter we put the accelerator ampersand (&) in front of it and add that letter to the dictionary. If we can't find an unused letter the style will simply have no accelerator. If the first letter of the style name is not in the dictionary we use it for the accelerator and add it to the dictionary. Finally we create a QAction for each style.

See also QDictIterator, QAsciiDict, QIntDict, QPtrDict, Collection Classes and Non-GUI Classes.

Member Function Documentation

QDict::QDict ( int size = 17, bool caseSensitive = TRUE )

Constructs a dictionary optimized for less than size entries.

We recommend setting size to a suitably large prime number (e.g. a prime that's slightly larger than the expected number of entries). This makes the hash distribution better which will lead to faster lookup.

If caseSensitive is TRUE (the default), keys which differ only in case are considered different.

QDict::QDict ( const QDict<type> & dict )

Constructs a copy of dict.

Each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy).

QDict::~QDict ()

Removes all items from the dictionary and destroys it. If setAutoDelete() is TRUE each value is deleted. All iterators that access this dictionary will be reset.

See also setAutoDelete().

bool QPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is FALSE.

See also setAutoDelete().

void QDict::clear () [virtual]

Removes all items from the dictionary.

The removed items are deleted if auto-deletion is enabled.

All dictionary iterators that operate on the dictionary are reset.

See also remove(), take() and setAutoDelete().

Reimplemented from QPtrCollection.

uint QDict::count () const [virtual]

Returns the number of items in the dictionary.

See also isEmpty().

Reimplemented from QPtrCollection.

type * QDict::find ( const QString & key ) const

Returns the item with key key, or null if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last item that was inserted will be found.

Equivalent to the [] operator.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also operator[]().

void QDict::insert ( const QString & key, const type * item )

Inserts the key key with value item into the dictionary.

The key does not have to be unique. If multiple items are inserted with the same key, only the last item will be visible.

Null items are not allowed.

See also replace().

Example: themes/themes.cpp.

bool QDict::isEmpty () const

Returns TRUE if the dictionary is empty, i.e. count() == 0; otherwise returns FALSE.

See also count().

QDict<type> & QDict::operator= ( const QDict<type> & dict )

Assigns dict to this dictionary and returns a reference to this dictionary.

This dictionary is first cleared, then each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy), unless newItem() has been reimplemented().

type * QDict::operator[] ( const QString & key ) const

Returns the item with key key, or null if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last item that was inserted will be found.

Equivalent to the find() function.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also find().

QDataStream & QDict::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

Reads a dictionary item from the stream s and returns a reference to the stream.

The default implementation sets item to 0.

See also write().

bool QDict::remove ( const QString & key )

Removes the item with key from the dictionary. Returns TRUE if successful, or FALSE if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last item that was inserted will be removed.

The removed item is deleted if auto-deletion is enabled.

All dictionary iterators that refer to the removed item will be set to point to the next item in the dictionary traversing order.

See also take(), clear() and setAutoDelete().

void QDict::replace ( const QString & key, const type * item )

Replaces the value of the key, key with item.

If the item does not already exist, it will be inserted.

Null items are not allowed.

Equivalent to:

    QDict<char> dict;
        ...
    if ( dict.find( key ) )
        dict.remove( key );
    dict.insert( key, item );

If there are two or more items with equal keys, then the last item that was inserted will be replaced.

See also insert().

void QDict::resize ( uint newsize )

Changes the size of the hashtable the newsize. The contents of the dictionary are preserved, but all iterators on the dictionary become invalid.

void QPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is TRUE and to never delete them if enable is FALSE.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is FALSE, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp and table/bigtable/main.cpp.

uint QDict::size () const

Returns the size of the internal hash array (as specified in the constructor).

See also count().

void QDict::statistics () const

Debugging-only function that prints out the dictionary distribution using qDebug().

type * QDict::take ( const QString & key )

Takes the item with key out of the dictionary without deleting it (even if auto-deletion is enabled).

If there are two or more items with equal keys, then the last item that was inserted will be taken.

Returns a pointer to the item taken out, or null if the key does not exist in the dictionary.

All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary traversal order.

See also remove(), clear() and setAutoDelete().

QDataStream & QDict::write ( QDataStream & s, QPtrCollection::Item ) const [virtual protected]

Writes a dictionary item to the stream s and returns a reference to the stream.

See also read().

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


qdict.h Include File

qdict.h

This is the verbatim text of the qdict.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QDict template class
**
** Created : 920821
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDICT_H
#define QDICT_H

#ifndef QT_H
#include "qgdict.h"
#endif // QT_H

template<class type>
class QDict
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGDict
#endif
{
public:
    QDict( int size = 17, bool caseSensitive = TRUE )
    : QGDict( size, StringKey, caseSensitive, FALSE ) { }
    QDict( const QDict<type> &d ) : QGDict( d ) { }
    ~QDict()				{ clear(); }
    QDict<type> &operator=(const QDict<type> &d)
            { return (QDict<type>&)QGDict::operator=(d); }
    uint  count()   const		{ return QGDict::count(); }
    uint  size()    const		{ return QGDict::size(); }
    bool  isEmpty() const		{ return QGDict::count() == 0; }

    void  insert( const QString &k, const type *d )
                    { QGDict::look_string(k,(Item)d,1); }
    void  replace( const QString &k, const type *d )
                    { QGDict::look_string(k,(Item)d,2); }
    bool  remove( const QString &k )	{ return QGDict::remove_string(k); }
    type *take( const QString &k )	{ return (type *)QGDict::take_string(k); }
    type *find( const QString &k ) const
        { return (type *)((QGDict*)this)->QGDict::look_string(k,0,0); }
    type *operator[]( const QString &k ) const
        { return (type *)((QGDict*)this)->QGDict::look_string(k,0,0); }

    void  clear()			{ QGDict::clear(); }
    void  resize( uint n )		{ QGDict::resize(n); }
    void  statistics() const		{ QGDict::statistics(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream &, QPtrCollection::Item & );
    virtual QDataStream& write( QDataStream &, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QDict<void>::deleteItem( Item )
{
}
#endif

template<class type> inline void QDict<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QDictIterator
 : public QGDictIterator
{
public:
    QDictIterator(const QDict<type> &d) : QGDictIterator((QGDict &)d) { }
    ~QDictIterator()	      {}
    uint  count()   const     { return dict->count(); }
    bool  isEmpty() const     { return dict->count() == 0; }
    type *toFirst()	      { return (type *)QGDictIterator::toFirst(); }
    operator type *() const   { return (type *)QGDictIterator::get(); }
    type *operator*()         { return (type *)QGDictIterator::get(); }
    type   *current() const   { return (type *)QGDictIterator::get(); }
    QString currentKey() const{ return QGDictIterator::getKeyString(); }
    type *operator()()	      { return (type *)QGDictIterator::operator()(); }
    type *operator++()	      { return (type *)QGDictIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGDictIterator::operator+=(j); }
};

#endif // QDICT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDict Member List

Complete Member List for QDict

This is the complete list of member functions for QDict, including inherited members.

  • QDict()
  • ~QDict()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • find()
  • insert()
  • isEmpty()
  • newItem()
  • operator=()
  • operator[]()
  • read()
  • remove()
  • replace()
  • resize()
  • setAutoDelete()
  • size()
  • statistics()
  • take()
  • write()


QDictIterator Class

QDictIterator Class Reference

The QDictIterator class provides an iterator for QDict collections. More...

#include <qdict.h>

List of all member functions.

Public Members

  • QDictIterator ( const QDict<type> & dict )
  • ~QDictIterator ()
  • uint count () const
  • bool isEmpty () const
  • type * toFirst ()
  • operator type * () const
  • type * current () const
  • QString currentKey () const
  • type * operator() ()
  • type * operator++ ()

Detailed Description

The QDictIterator class provides an iterator for QDict collections.

QDictIterator is implemented as a template class. Define a template instance QDictIterator<X> to create a dictionary iterator that operates on QDict<X> (dictionary of X*).

The traversal order is arbitrary; when we speak of the "first", "last" and "next" item we are talking in terms of this arbitrary order.

Multiple iterators may independently traverse the same dictionary. A QDict knows about all iterators that are operating on the dictionary. When an item is removed from the dictionary, QDict update all iterators that are referring to the removed item to point to the next item in the traversal order.

Example:

    QDict<QLineEdit> fields;
    fields.insert( "forename", new QLineEdit( this ) );
    fields.insert( "surname", new QLineEdit( this ) );
    fields.insert( "age", new QLineEdit( this ) );

    fields["forename"]->setText( "Homer" );
    fields["surname"]->setText( "Simpson" );
    fields["age"]->setText( "45" );

    QDictIterator<QLineEdit> it( fields );
    for( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;
    cout << endl;

    // Output (random order):
    //  age: 45
    //  surname: Simpson
    //  forename: Homer
In the example we insert some pointers to line edits into a dictionary, then iterate over the dictionary printing the strings associated with the line edits.

See also QDict, Collection Classes and Non-GUI Classes.

Member Function Documentation

QDictIterator::QDictIterator ( const QDict<type> & dict )

Constructs an iterator for dict. The current iterator item is set to point to the first item in the dictionary, dict. First in this context means first in the arbitrary traversal order.

QDictIterator::~QDictIterator ()

Destroys the iterator.

uint QDictIterator::count () const

Returns the number of items in the dictionary over which the iterator is operating.

See also isEmpty().

type * QDictIterator::current () const

Returns a pointer to the current iterator item's value.

QString QDictIterator::currentKey () const

Returns the current iterator item's key.

bool QDictIterator::isEmpty () const

Returns TRUE if the dictionary is empty, i.e. count() == 0; otherwise returns FALSE.

See also count().

QDictIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QDictIterator::operator() ()

Makes the next item current and returns the original current item.

If the current iterator item was the last item in the dictionary or if it was 0, 0 is returned.

type * QDictIterator::operator++ ()

Prefix ++ makes the next item current and returns the new current item.

If the current iterator item was the last item in the dictionary or if it was 0, 0 is returned.

type * QDictIterator::toFirst ()

Resets the iterator, making the first item the first current item. First in this context means first in the arbitrary traversal order. Returns a pointer to this item.

If the dictionary is empty it sets the current item to 0 and returns 0.

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


QDictIterator Member List

Complete Member List for QDictIterator

This is the complete list of member functions for QDictIterator, including inherited members.

  • QDictIterator()
  • ~QDictIterator()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • toFirst()


QDir类

QDir类参考

QDir类提供了访问目录结构和它们的内容的与平台无关的方式。 详情请见……

#include <qdir.h>

所有成员函数的列表。

公有成员

  • enum FilterSpec { Dirs = 0x001, Files = 0x002, Drives = 0x004, NoSymLinks = 0x008, All = 0x007, TypeMask = 0x00F, Readable = 0x010, Writable = 0x020, Executable = 0x040, RWEMask = 0x070, Modified = 0x080, Hidden = 0x100, System = 0x200, AccessMask = 0x3F0, DefaultFilter = -1 }
  • enum SortSpec { Name = 0x00, Time = 0x01, Size = 0x02, Unsorted = 0x03, SortByMask = 0x03, DirsFirst = 0x04, Reversed = 0x08, IgnoreCase = 0x10, DefaultSort = -1 }
  • QDir ()
  • QDir ( const QString & path, const QString & nameFilter = QString::null, int sortSpec = Name | IgnoreCase, int filterSpec = All )
  • QDir ( const QDir & d )
  • virtual ~QDir ()
  • QDir & operator= ( const QDir & d )
  • QDir & operator= ( const QString & path )
  • virtual void setPath ( const QString & path )
  • virtual QString path () const
  • virtual QString absPath () const
  • virtual QString canonicalPath () const
  • virtual QString dirName () const
  • virtual QString filePath ( const QString & fileName, bool acceptAbsPath = TRUE ) const
  • virtual QString absFilePath ( const QString & fileName, bool acceptAbsPath = TRUE ) const
  • virtual bool cd ( const QString & dirName, bool acceptAbsPath = TRUE )
  • virtual bool cdUp ()
  • QString nameFilter () const
  • virtual void setNameFilter ( const QString & nameFilter )
  • FilterSpec filter () const
  • virtual void setFilter ( int filterSpec )
  • SortSpec sorting () const
  • virtual void setSorting ( int sortSpec )
  • bool matchAllDirs () const
  • virtual void setMatchAllDirs ( bool enable )
  • uint count () const
  • QString operator[] ( int index ) const
  • virtual QStrList encodedEntryList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const (obsolete)
  • virtual QStrList encodedEntryList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const (obsolete)
  • virtual QStringList entryList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • virtual QStringList entryList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • virtual const QFileInfoList * entryInfoList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • virtual const QFileInfoList * entryInfoList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const
  • virtual bool mkdir ( const QString & dirName, bool acceptAbsPath = TRUE ) const
  • virtual bool rmdir ( const QString & dirName, bool acceptAbsPath = TRUE ) const
  • virtual bool isReadable () const
  • virtual bool exists () const
  • virtual bool isRoot () const
  • virtual bool isRelative () const
  • virtual void convertToAbs ()
  • virtual bool operator== ( const QDir & d ) const
  • virtual bool operator!= ( const QDir & d ) const
  • virtual bool remove ( const QString & fileName, bool acceptAbsPath = TRUE )
  • virtual bool rename ( const QString & oldName, const QString & newName, bool acceptAbsPaths = TRUE )
  • virtual bool exists ( const QString & name, bool acceptAbsPath = TRUE )

静态公有成员s

  • QString convertSeparators ( const QString & pathName )
  • const QFileInfoList * drives ()
  • char separator ()
  • bool setCurrent ( const QString & path )
  • QDir current ()
  • QDir home ()
  • QDir root ()
  • QString currentDirPath ()
  • QString homeDirPath ()
  • QString rootDirPath ()
  • bool match ( const QStringList & filters, const QString & fileName )
  • bool match ( const QString & filter, const QString & fileName )
  • QString cleanDirPath ( const QString & filePath )
  • bool isRelativePath ( const QString & path )

详细描述

QDir类提供了访问目录结构和它们的内容的与平台无关的方式。

QDir用来操作路径名称、关于路径和文件的访问信息和操作底层文件系统。

QDir使用相对或绝对文件路径来指向一个文件。绝对路径是从目录分隔符“/”或者带有一个驱动器标识（除了在Unix下）。如果你总是使用“/”作为目录分隔符，Qt将会把你的路径转化为符合底层的操作系统的。相对文件名是由一个目录名称或者文件名开始并且指定一个相对于当前路径的路径。

“当前”路径是指应用程序的工作目录。QDir自己的路径可以通过setPath()设置并且通过path()获得。

一个绝对路径的实例是字符串“/tmp/quartz”，相对路径看起来像是“src/fatlib”。你可以使用函数isRelative()来检查一个QDir使用的是相对还是绝对文件路径。调用convertToAbs()可以把一个相对的QDir转化为绝对的。使用cleanDirPath()可以得到一个简化的路径。为了获得没有符号连接或者多余的“..”元素的路径，请使用canonicalPath()。路径可以通过setPath()设置，或者使用cd()和cdUp()来改变。

QDir提供了几个静态函数，例如，setCurrent()设置应用程序的工作目录并且currentDirPath()来获得应用程序的工作目录。访问一些普通的路径是由以下一些静态函数提供的，current()、home()和root()返回QDir对象或者currentDirPath()、homeDirPath()和rootDirPath()返回字符串路径。

count()返回目录中的条目数量。通过entryList()可以获得目录中的所有文件和目录的名称的字符串列表。如果你希望得到QFileInfo指针的列表请使用entryInfoList()。这些函数都可以使用名称过滤器、属性过滤器（例如只读、只要文件不要目录等等）和排列顺序。过滤器和排序可以调用setNameFilter()、setFilter()和setSorting()来设置。它们可以通过entryList()和entryInfoList()的参数来指定。

mkdir()可以创建一个新目录，rename()可以重命名一个目录并且rmdir()可以移除一个已经存在的目录。remove()可以移除一个已经存在的文件。你可以通过exists()、isReadable()和isRoot()来询问一个目录。

使用filePath()可以得到一个带有文件名的路径，并且dirName()可以得到目录名称，这两个函数都不能检测文件或者目录是否存在。

drives()提供根目录的列表，在Unix系统上，这个返回一个只包含根目录“/”的列表，在Windows上，这个列表将包含“C:/”并且还有“D:/”等等。

如果你需要一个适应底层操作系统形式的路径，请使用convertSeparators()。

实例：

请参考一个目录是否存在。

    QDir d( "example" );                        // “./example”
    if ( !d.exists() )
        qWarning( "Cannot find the example directory" );

Traversing directories and reading a file.

    QDir d = QDir::root();                      // “/”
    if ( !d.cd("tmp") ) {                       // “/tmp”
        qWarning( "Cannot find the \"/tmp\" directory" );
    } else {
        QFile f( d.filePath("ex1.txt") );       // “/tmp/ex1.txt”
        if ( !f.open(IO_ReadWrite) )
            qWarning( "Cannot create the file %s", f.name() );
    }

一个列出当前目录中所有文件（不包括符号连接）的程序，按大小排序，小的在前。

    #include <stdio.h>
    #include <qdir.h>

    int main( int argc, char **argv )
    {
        QDir d;
        d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );
        d.setSorting( QDir::Size | QDir::Reversed );

        const QFileInfoList *list = d.entryInfoList();
        QFileInfoListIterator it( *list );
        QFileInfo *fi;

        printf( "     Bytes Filename\n" );
        while ( (fi = it.current()) != 0 ) {
            printf( "%10li %s\n", fi->size(), fi->fileName()。latin1() );
            ++it;
        }
        return 0;
    }

也可以参考输入/输出和网络。

成员类型文档

QDir::FilterSpec

这个枚举变量描述的是QDir是如何选择目录中的哪些条目被返回的。被指定的过滤器的值可以由下述列表中的值或运算得到：

  • QDir::Dirs - 只列出目录。
  • QDir::Files - 只列出文件。
  • QDir::Drives - 列出磁盘驱动器（在Unix下被忽略）。
  • QDir::NoSymLinks - 不列出符号连接（不支持符号连接的操作系统会忽略它）。
  • QDir::All - 列出目录、文件、驱动器和符号连接（除非你指定系统，这不会列出损坏的符号连接）。
  • QDir::TypeMask - Dirs、Files、Drives和NoSymLink的掩码。
  • QDir::Readable - 列出应用程序可以读访问的文件。
  • QDir::Writable - 列出应用程序可以写访问的文件。
  • QDir::Executable - 列出应用程序可以执行访问的文件。可执行需要由Dirs和Files组合。
  • QDir::RWEMask - Readable、Writable和Executable标记的掩码。
  • QDir::Modified - 只列出已经被修改的文件（在Unix下被忽略）。
  • QDir::Hidden - 列出隐藏文件（在Unix下就是以.开始的文件）。
  • QDir::System - 列出系统文件（在Unix下就是FIFO、套接字和设备文件）。
  • QDir::AccessMask - Readable、Writable、Executable、Modified、Hidden和System标记的掩码。
  • QDir::DefaultFilter - 内部标记

如果你不设置Readable、Writable或Executable中的任何一个，QDir将会设置它们三个全部。这使得默认很容易写并且同时也很有用。

实例：Readable|Writable是指列出应用程序可以读访问、写访问或者两者都可以的所有文件。Dirs|Drives是指列出驱动器、目录、所有应用程序可以读、写、执行的文件并且也包括到这些文件/目录的符号连接。

QDir::SortSpec

这个枚举变量描述的是QDir如何排列由entryList()或entryInfoList()返回的条目。被指定的排列的值可以由下述列表中的值或运算得到：

  • QDir::Name - 按名称排序。
  • QDir::Time - 按时间排序（修改时间）。
  • QDir::Size - 按文件大小排序。
  • QDir::Unsorted - 不排序。
  • QDir::SortByMask - Name、Time和Size的掩码。
  • QDir::DirsFirst - 首先是目录，然后是文件。
  • QDir::Reversed - 相反的排序顺序。
  • QDir::IgnoreCase - 不区分大小写进行排序。
  • QDir::DefaultSort - 内部标记。

前四种中你只能指定一个。

如果你同时指定DirsFirst和Reversed，目录仍然会被放在前面，但是按照反向的顺序，文件仍然排在目录后面，当然也是按照反向的顺序。

成员函数文档

QDir::QDir ()

构造一个指向当前目录的QDir。

也可以参考currentDirPath()。

QDir::QDir ( const QString & path, const QString & nameFilter = QString::null, int sortSpec = Name | IgnoreCase, int filterSpec = All )

构造一个路径为path、名称过滤器为nameFilter并且属性过滤器为filterSpec的QDir。它也使用sortSpec来排列名称。

默认的nameFilter是一个空字符串，不包含任何东西，默认的filterSpec是All，也就是说也不包含任何东西。默认的sortSpec是Name|IgnoreCase，也就是说不区分大小写按名称排序。

下面是列出“/tmp”中所有文件的实例：

    QDir d( "/tmp" );
    for ( int i = 0; i < d.count(); i++ )
        printf( "%s\n", d[i] );

如果path为“”或零，QDir使用“.”（当前目录）。如果nameFilter为“”或零，QDir使用“*”（所有文件）。

注意path不需要存在。

也可以参考exists()、setPath()、setNameFilter()、setFilter()和setSorting()。

QDir::QDir ( const QDir & d )

构造一个目录d的复制的QDir。

也可以参考operator=()。

QDir::~QDir () [虚]

销毁QDir并且释放它的资源。

QString QDir::absFilePath ( const QString & fileName, bool acceptAbsPath = TRUE ) const [虚]

返回路径中一个文件的绝对路径名称。不检查这个文件是否真的存在于这个目录中。在fileName中多余的分隔符或者“.”和“..”目录将被移除（请参考cleanDirPath()）。

如果acceptAbsPath为真，由分隔符“/”开始的fileName将会被不改变地立即返回。如果acceptAbsPath为假，绝对路径将被被加到fileName的前面并且结果字符串被返回。

也可以参考filePath()。

QString QDir::absPath () const [虚]

返回绝对路径（一个由“/”或驱动器标识开始的路径），可能包含符号连接，但是不会包含“.”、“..”或者多个分隔符。

也可以参考setPath()、canonicalPath()、exists()、cleanDirPath()、dirName()和absFilePath()。

实例：fileiconview/qfileiconview.cpp。

QString QDir::canonicalPath () const [虚]

返回规范的路径，也就是没有符号连接或者多余的“.”、“..”元素的路径。

在没有符号连接的系统上，这个函数总是返回和absPath()返回值一样的值。如果规范路径不存在（通常是因为挂起的符号连接）。

也可以参考path()、absPath()、exists()、cleanDirPath()、dirName()、absFilePath()和QString::isNull()。

bool QDir::cd ( const QString & dirName, bool acceptAbsPath = TRUE ) [虚]

改变QDir的目录为dirName。

如果acceptAbsPath为真，由分隔符“/”开始的路径将会导致这个函数改变到这个绝对路径。如果acceptAbsPath为假，dirName前面的任何数量的分隔符都将被移除并且这个函数将会进入到dirName中。

如果新的路径存在并且是可读的，返回真。注意如果新的目录不存在，逻辑上的cd()操作不会被执行。

调用cd( ".." )等于调用cdUp()。

也可以参考cdUp()、isReadable()、exists()和path()。

实例：fileiconview/mainwindow.cpp。

bool QDir::cdUp () [虚]

改变目录为QDir的当前目录的上一级目录。

如果新的路径存在并且是可读的，返回真。注意如果新的目录不存在，逻辑上的cdUp()操作不会被执行。

也可以参考cd()、isReadable()、exists()和path()。

QString QDir::cleanDirPath ( const QString & filePath ) [静态]

移除filePath的多重目录分隔符“/”并且解析其中的“.”或者“..”。

符号连接会被保留。这个函数不返回规范路径，但会是输入的最简化的版本。“./local”变为“local”、“local/../bin”变为“bin”并且“/local/usr/../bin”变为“/local/bin”。

也可以参考absPath()和canonicalPath()。

QString QDir::convertSeparators ( const QString & pathName ) [静态]

把pathName里面的“/”分隔符转化为适用于底层操作系统的分隔符。返回转化的字符串。

在Windows上，convertSeparators("c:/winnt/system32")返回“c:\winnt\system32”。

在一些操作系统上，例如在Unix上，返回的字符串可能和参数是一样的。

void QDir::convertToAbs () [虚]

把目录路经转化为绝对路径。如果它已经是绝对路径了，就什么也不做。

也可以参考isRelative()。

uint QDir::count () const

返回找到的目录和文件的数量。

Equivalent to entryList()。count()。

也可以参考operator[]()和entryList()。

QDir QDir::current () [静态]

返回应用程序当前目录。

使用path()来访问QDir对象的路径。

也可以参考currentDirPath()和QDir::QDir()。

QString QDir::currentDirPath () [静态]

返回应用程序当前目录的绝对路径。

也可以参考current()。

实例：helpviewer/helpwindow.cpp和qdir/qdir.cpp。

QString QDir::dirName () const [虚]

返回目录的名称，这和路径是不同的，例如一个名称为“mail”的目录，也许路径为“/var/spool/mail”。如果目录没有名字（例如，它是根目录），一个零字符串被返回。

不会执行检测来确保这个名称的目录真正存在。

也可以参考path()、absPath()、absFilePath()、exists()和QString::isNull()。

const QFileInfoList * QDir::drives () [静态]

返回这个系统中根目录的列表。在Windows中，这将返回许多包含“”、“”等等的QFileInfo对象。在其它操作系统，它返回的是只包含一个根目录（例如“/”）的列表。

返回的指针的所有权归Qt。调用者不要删除或者修改它。

实例：dirview/main.cpp。

QStrList QDir::encodedEntryList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数被包含是因为可以很容易地从Qt 1.x移植到Qt 3.0，它和entryList()是一样地，但是文件名的编码方式是使用QFile::encodedName()的8位字符串。

使用它比使用entryList()更有效率。

QStrList QDir::encodedEntryList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这是一个重载成员函数，用于提供方便。它的行为基于上面的函数。

这个函数被包含是因为可以很容易地从Qt 1.x移植到Qt 3.0，它和entryList()是一样地，但是文件名的编码方式是使用QFile::encodedName()的8位字符串。

使用它比使用entryList()更有效率。

const QFileInfoList * QDir::entryInfoList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

返回这个目录中所有目录和文件的QFileInfo对象的列表，根据setSorting()排序并且根据setFilter()和setNameFilter()进行过滤。

过滤器和排序的规定可以使用nameFilter、filterSpec和sortSpec参数来指定。

如果这个目录是不可读的或者不存在，返回0。

返回的指针是一个指向QFileInfoList的常量指针。这个列表归QDir对象所有并且将会在同一个QDir实例下次调用entryInfoList()时被重新使用。如果你想在调用这个函数之后保留这个列表的条目，你将需要复制它们。

也可以参考entryList()、setNameFilter()、setSorting()和setFilter()。

实例：dirview/dirview.cpp和fileiconview/qfileiconview.cpp。

const QFileInfoList * QDir::entryInfoList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回这个目录中所有目录和文件的QFileInfo对象的列表，根据setSorting()排序并且根据setFilter()和setNameFilter()进行过滤。

过滤器和排序的规定可以使用filterSpec和sortSpec参数来指定。

如果这个目录是不可读的或者不存在，返回0。

返回的指针是一个指向QFileInfoList的常量指针。这个列表归QDir对象所有并且将会在同一个QDir实例下次调用entryInfoList()时被重新使用。如果你想在调用这个函数之后保留这个列表的条目，你将需要复制它们。

也可以参考entryList()、setNameFilter()、setSorting()和setFilter()。

QStringList QDir::entryList ( const QString & nameFilter, int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

返回这个目录中所有目录和文件的名称的列表，根据setSorting()排序并且根据setFilter()和setNameFilter()进行过滤。

过滤器和排序的规定可以使用nameFilter、filterSpec和sortSpec参数来指定。

如果这个目录是不可读的或者不存在，返回空的列表。。

也可以参考entryInfoList()、setNameFilter()、setSorting()和setFilter()。

实例：table/statistics/statistics.cpp。

QStringList QDir::entryList ( int filterSpec = DefaultFilter, int sortSpec = DefaultSort ) const [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回这个目录中所有目录和文件的名称的列表，根据setSorting()排序并且根据setFilter()和setNameFilter()进行过滤。

过滤器和排序的规定可以使用filterSpec和sortSpec参数来指定。

如果这个目录是不可读的或者不存在，返回空的列表。。

也可以参考entryInfoList()、setNameFilter()、setSorting()和setFilter()。

bool QDir::exists ( const QString & name, bool acceptAbsPath = TRUE ) [虚]

检查文件name的存在性。

如果acceptAbsPath为真，由分隔符“/”开始的路径将会使用绝对路径检查这个文件。如果acceptAbsPath为假，name开始的任何数量的分隔符将会被移除并且结果文件名将被检查。

如果文件存在，返回真，否则返回假。

也可以参考QFileInfo::exists()和QFile::exists()。

bool QDir::exists () const [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果directory存在，返回真。（如果发现一个同名的文件，这个函数将返回假）。

也可以参考QFileInfo::exists()和QFile::exists()。

QString QDir::filePath ( const QString & fileName, bool acceptAbsPath = TRUE ) const [虚]

返回目录中一个文件的路径名称。不检查这个文件是否真的存在于这个目录中。如果QDir是相对的，返回的路径名称也是相对的。fileName中多余的多重分隔符或者“.”和“..”目录将被移除（请参考cleanDirPath()）。

如果acceptAbsPath为真，由分隔符“/”开始的fileName将会被不改变地立即返回。如果acceptAbsPath为假，绝对路径将被被加到fileName的前面并且结果字符串被返回。

也可以参考absFilePath()、isRelative()和canonicalPath()。

FilterSpec QDir::filter () const

返回由setFilter()设置的值。

QDir QDir::home () [静态]

返回主目录。

在Windows NT/2000下，这个函数通过连接HOMEDRIVE和HOMEPATH环境变量来形成这个路径。

在Windows 9x和非Windows操作系统，HOME环境变量被使用。

如果这个环境变量没有被设置，rootDirPath()用来代替它。

也可以参考homeDirPath()。

QString QDir::homeDirPath () [静态]

返回用户的主目录的绝对路径。

也可以参考home()。

bool QDir::isReadable () const [虚]

如果目录是可读的并且我们可以通过名称打开文件，返回真。如果只有上述一个条件存在，这个函数返回假。 警告： 这个函数返回的假并不保证这个目录不可访问。

也可以参考QFileInfo::isReadable()。

实例：dirview/dirview.cpp和fileiconview/qfileiconview.cpp。

bool QDir::isRelative () const [虚]

如果目录路径是相对于当前路径的，返回真，并且如果路径是绝对的（例如在Unix下，一个路径如果没有以“/”开始就是相对的），返回假。

也可以参考convertToAbs()。

bool QDir::isRelativePath ( const QString & path ) [静态]

如果path是相对的，返回真，如果它是绝对的，返回假。

也可以参考isRelative()。

bool QDir::isRoot () const [虚]

如果目录是根目录，返回真，否则返回假。

注意：如果目录是一个连接到根目录的符号连接，这个函数返回假。如果你想测试这一点，你可以使用canonicalPath()：

实例：

    QDir d( "/tmp/root_link" );
    d = d.canonicalPath();
    if ( d.isRoot() )
        qWarning( "It IS a root link!" );

也可以参考root()和rootDirPath()。

bool QDir::match ( const QString & filter, const QString & fileName ) [静态]

如果fileName与通配符模式filter匹配，返回真。filter也可以包含由空格或者分号分割的多个模式。

（请参考QRegExp通配符匹配。）

也可以参考QRegExp::match()。

bool QDir::match ( const QStringList & filters, const QString & fileName ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果fileName与列表filters中的通配符模式匹配，返回真。

（请参考QRegExp通配符匹配。）

也可以参考QRegExp::match()。

bool QDir::matchAllDirs () const

返回由setMatchAllDirs()设置的值。

也可以参考setMatchAllDirs()。

bool QDir::mkdir ( const QString & dirName, bool acceptAbsPath = TRUE ) const [虚]

创建一个目录。

如果acceptAbsPath为真，由分隔符“/”开始的dirName将会被不改变地立即返回。如果acceptAbsPath为假，dirName的开始的任意个分隔符将被移除。

如果成功，返回真，否则返回假。

也可以参考rmdir()。

QString QDir::nameFilter () const

返回由setNameFilter()设置的字符串。

bool QDir::operator!= ( const QDir & d ) const [虚]

如果目录d和这个目录是不同的路径或者不同的排序或过滤器设置，返回真，否则返回假。

实例：

    // 当前目录为“/usr/local”
    QDir d1( "/usr/local/bin" );
    QDir d2( "bin" );
    if ( d1 != d2 ) qDebug( "They differ\n" ); // 这是被打印的

QDir & QDir::operator= ( const QDir & d )

完成一个QDir d的复制并且把它赋给这个QDir。

QDir & QDir::operator= ( const QString & path )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置这个目录的路径为给定的path。

bool QDir::operator== ( const QDir & d ) const [虚]

如果目录d和这个目录有相同的路径、相同的排序和过滤器，返回真，否则返回假。

实例：

    // 当前目录为“/usr/local”
    QDir d1( "/usr/local/bin" );
    QDir d2( "bin" );
    d2.convertToAbs();
    if ( d1 == d2 ) qDebug( "They're the same\n" ); // 这是被打印的

QString QDir::operator[] ( int index ) const

返回在文件名列表的index位置的文件名。等于entryList().at(index)。

如果index超出范围或者entryList()函数失败，返回一个零字符串。

也可以参考count()和entryList()。

QString QDir::path () const [虚]

返回这个路径，这也许包含符号连接，但决不会包含多余的“.”、“..”或者多重分隔符。

返回的路径可能是相对的也可能是绝对的（请参考setPath()）。

也可以参考setPath()、absPath()、exists()、cleanDirPath()、dirName()、absFilePath()和convertSeparators()。

bool QDir::remove ( const QString & fileName, bool acceptAbsPath = TRUE ) [虚]

移除文件。

如果acceptAbsPath为真，由分隔符“/”开始的路径将会移除使用绝对路径的文件。如果acceptAbsPath为假，fileName开始的任意个分隔符将被移除并且结果文件将被移除。

如果文件移除成功，返回真，否则返回假。

bool QDir::rename ( const QString & oldName, const QString & newName, bool acceptAbsPaths = TRUE ) [虚]

重命名一个文件或目录。

如果acceptAbsPath为真，由分隔符“/”开始的路径将会重命名使用绝对路径的文件。如果acceptAbsPath为假，fileName开始的任意个分隔符将被移除并且结果文件将被重命名。

如果成功，返回真，否则返回假。

在绝大多数文件系统中，只有在oldName不存在或者newName和oldName不在同一个分区中，rename()才会失败。在Windows下，如果newName已经存在，rename()将会失败。无论如何，还有其它几个原因导致rename()失败。例如，例如在文件系统中如果newName指向一个打开的文件，rename()会失败。

实例：fileiconview/qfileiconview.cpp。

bool QDir::rmdir ( const QString & dirName, bool acceptAbsPath = TRUE ) const [虚]

移除一个目录。

如果acceptAbsPath为真，由分隔符“/”开始的路径将会移除使用绝对路径的目录。如果acceptAbsPath为假，dirName开始的任意个分隔符将被移除并且结果目录将被移除。

为了使rmdir()成功，这个目录必须为空。

如果成功，返回真，否则返回假。

也可以参考mkdir()。

QDir QDir::root () [静态]

返回根目录。

也可以参考rootDirPath()和drives()。

QString QDir::rootDirPath () [静态]

返回根目录的绝对路径。

在Unix操作系统这个返回“/”。在Windows文件系统这个返回“C:/”。

也可以参考root()和drives()。

char QDir::separator () [静态]

返回本地目录分隔符，在Unix下是“/”，在MS-DOS、Windows NT和OS/2下是“\”，在Mac OS下是“:”。

你不需要这个函数来构建文件路径。如果你一直使用“/”，Qt将会把你的路径转化为符合底层操作系统的路径的。

bool QDir::setCurrent ( const QString & path ) [静态]

设置你的应用程序的当前工作目录为path。如果目录被成功改变，返回真，否则返回假。

void QDir::setFilter ( int filterSpec ) [虚]

设置被entryList()和entryInfoList()使用的过滤器为filterSpec。过滤器被用来指定entryList()和entryInfoList()返回哪些文件。请参考QDir::FilterSpec。

也可以参考filter()和setNameFilter()。

void QDir::setMatchAllDirs ( bool enable ) [虚]

如果enable为真，那么所有的目录被包含（例如在entryList()中），并且nameFilter()仅适用于文件。如果enable为假，那么nameFilter()同时适用于文件和目录。

也可以参考matchAllDirs()。

void QDir::setNameFilter ( const QString & nameFilter ) [虚]

设置entryList()和entryInfoList()使用的名称过滤器为nameFilter。

nameFilter是一个可以理解“*”和“?”的通配符过滤器。（请参考QRegExp通配符匹配。）你可以使用单个空格“ ”或者分号“;”来分割几个过滤器条目。

例如，如果你想entryList()和entryInfoList()列出所有以“.cpp”和“.h”结尾的文件，你需要使用dir.setNameFilter("*.cpp *.h")或dir.setNameFilter("*.cpp;*.h")。

也可以参考nameFilter()和setFilter()。

void QDir::setPath ( const QString & path ) [虚]

设置目录的路径为path。这个路径被清除多余的“.”、“..”和多重分隔符。不会完成检查来确保这个路径的目录是否存在。

路径可以是相对的也可以是绝对的。绝对路径是由目录分隔符“/”或驱动器标识开始的（除了Unix下）。相对路径是一个指定了相对于当前目录的目录名称和文件名称。一个绝对路径的实例是“/tmp/quartz”，一个相对路径的实例是“src/fatlib”。

也可以参考path()、absPath()、exists()、cleanDirPath()、dirName()、absFilePath()、isRelative()和convertToAbs()。

void QDir::setSorting ( int sortSpec ) [虚]

设置entryList()和entryInfoList()使用的排序顺序。

sortSpec是由QDir::SortSpec中的枚举变量的值或运算得到。

也可以参考sorting()和SortSpec。

SortSpec QDir::sorting () const

返回由setSorting()设置的值。

也可以参考setSorting()和SortSpec。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDir

Main:

/****************************************************************************
** $Id:  qt/qdir.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "../dirview/dirview.h"
#include "qdir.h"

#include <qapplication.h>
#include <qtextview.h>
#include <qfileinfo.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qhbox.h>
#include <qspinbox.h>
#include <qlabel.h>
#include <qmultilineedit.h>
#include <qheader.h>
#include <qevent.h>
#include <qpainter.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qtooltip.h>

#include <stdlib.h>

/* XPM */
static const char *bookmarks[]={
    "22 14 8 1",
    "# c #000080",
    "a c #585858",
    "b c #000000",
    "c c #ffffff",
    "d c #ffffff",
    "e c #ffffff",
    "f c #000000",
    ". c None",
    "...bb.................",
    "..bacb....bbb.........",
    "..badcb.bbccbab.......",
    "..bacccbadccbab.......",
    "..baecdbcccdbab.......",
    "..bacccbacccbab.......",
    "..badcdbcecdfab.......",
    "..bacecbacccbab.......",
    "..baccdbcccdbab.......",
    "...badcbacdbbab.......",
    "....bacbcbbccab.......",
    ".....babbaaaaab.......",
    ".....bbabbbbbbb.......",
    "......bb.............."
};

/* XPM */
static const char *home[]={
    "16 15 4 1",
    "# c #000000",
    "a c #ffffff",
    "b c #c0c0c0",
    ". c None",
    ".......##.......",
    "..#...####......",
    "..#..#aabb#.....",
    "..#.#aaaabb#....",
    "..##aaaaaabb#...",
    "..#aaaaaaaabb#..",
    ".#aaaaaaaaabbb#.",
    "###aaaaaaaabb###",
    "..#aaaaaaaabb#..",
    "..#aaa###aabb#..",
    "..#aaa#.#aabb#..",
    "..#aaa#.#aabb#..",
    "..#aaa#.#aabb#..",
    "..#aaa#.#aabb#..",
    "..#####.######.."
};

// ****************************************************************************************************

PixmapView::PixmapView( QWidget *parent )
    : QScrollView( parent )
{
    viewport()->setBackgroundMode( PaletteBase );
}

void PixmapView::setPixmap( const QPixmap &pix )
{
    pixmap = pix;
    resizeContents( pixmap.size().width(), pixmap.size().height() );
    viewport()->repaint( FALSE );
}

void PixmapView::drawContents( QPainter *p, int cx, int cy, int cw, int ch )
{
    p->fillRect( cx, cy, cw, ch, colorGroup().brush( QColorGroup::Base ) );
    p->drawPixmap( 0, 0, pixmap );
}

// ****************************************************************************************************

Preview::Preview( QWidget *parent )
    : QWidgetStack( parent )
{
    normalText = new QMultiLineEdit( this );
    normalText->setReadOnly( TRUE );
    html = new QTextView( this );
    pixmap = new PixmapView( this );
    raiseWidget( normalText );
}

void Preview::showPreview( const QUrl &u, int size )
{
    if ( u.isLocalFile() ) {
        QString path = u.path();
        QFileInfo fi( path );
        if ( fi.isFile() && (int)fi.size() > size * 1000 ) {
            normalText->setText( tr( "The File\n%1\nis too large, so I don't show it!" ).arg( path ) );
            raiseWidget( normalText );
            return;
        }

        QPixmap pix( path );
        if ( pix.isNull() ) {
            if ( fi.isFile() ) {
                QFile f( path );
                if ( f.open( IO_ReadOnly ) ) {
                    QTextStream ts( &f );
                    QString text = ts.read();
                    f.close();
                    if ( fi.extension().lower().contains( "htm" ) ) {
                        QString url = html->mimeSourceFactory()->makeAbsolute( path, html->context() );
                        html->setText( text, url );
                        raiseWidget( html );
                        return;
                    } else {
                        normalText->setText( text );
                        raiseWidget( normalText );
                        return;
                    }
                }
            }
            normalText->setText( QString::null );
            raiseWidget( normalText );
        } else {
            pixmap->setPixmap( pix );
            raiseWidget( pixmap );
        }
    } else {
        normalText->setText( "I only show local files!" );
        raiseWidget( normalText );
    }
}

// ****************************************************************************************************

PreviewWidget::PreviewWidget( QWidget *parent )
    : QVBox( parent ), QFilePreview()
{
    setSpacing( 5 );
    setMargin( 5 );
    QHBox *row = new QHBox( this );
    row->setSpacing( 5 );
    (void)new QLabel( tr( "Only show files smaller than: " ), row );
    sizeSpinBox = new QSpinBox( 1, 10000, 1, row );
    sizeSpinBox->setSuffix( " KB" );
    sizeSpinBox->setValue( 64 );
    row->setFixedHeight( 10 + sizeSpinBox->sizeHint().height() );
    preview = new Preview( this );
}

void PreviewWidget::previewUrl( const QUrl &u )
{
    preview->showPreview( u, sizeSpinBox->value() );
}

// ****************************************************************************************************

CustomFileDialog::CustomFileDialog()
    :  QFileDialog( 0, 0, TRUE )
{
    setDir( "/" );

    dirView = new DirectoryView( this, 0, TRUE );
    dirView->addColumn( "" );
    dirView->header()->hide();
    ::Directory *root = new ::Directory( dirView, "/" );
    root->setOpen( TRUE );
    dirView->setFixedWidth( 150 );

    addLeftWidget( dirView );

    QPushButton *p = new QPushButton( this );
    p->setPixmap( QPixmap( bookmarks ) );
    QToolTip::add( p, tr( "Bookmarks" ) );

    bookmarkMenu = new QPopupMenu( this );
    connect( bookmarkMenu, SIGNAL( activated( int ) ),
             this, SLOT( bookmarkChosen( int ) ) );
    addId = bookmarkMenu->insertItem( tr( "Add bookmark" ) );
    bookmarkMenu->insertSeparator();

    QFile f( ".bookmarks" );
    if ( f.open( IO_ReadOnly ) ) {
        QDataStream ds( &f );
        ds >> bookmarkList;
        f.close();

        QStringList::Iterator it = bookmarkList.begin();
        for ( ; it != bookmarkList.end(); ++it ) {
            bookmarkMenu->insertItem( *it );
        }
    }

    p->setPopup( bookmarkMenu );

    addToolButton( p, TRUE );

    connect( dirView, SIGNAL( folderSelected( const QString & ) ),
             this, SLOT( setDir2( const QString & ) ) );
    connect( this, SIGNAL( dirEntered( const QString & ) ),
             dirView, SLOT( setDir( const QString & ) ) );

    QToolButton *b = new QToolButton( this );
    QToolTip::add( b, tr( "Go Home!" ) );
    b->setPixmap( QPixmap( home ) );
    connect( b, SIGNAL( clicked() ),
             this, SLOT( goHome() ) );

    addToolButton( b );

    resize( width() + width() / 3, height() );
}

CustomFileDialog::~CustomFileDialog()
{
    if ( !bookmarkList.isEmpty() ) {
        QFile f( ".bookmarks" );
        if ( f.open( IO_WriteOnly ) ) {
            QDataStream ds( &f );
            ds << bookmarkList;
            f.close();
        }
    }
}

void CustomFileDialog::setDir2( const QString &s )
{
    blockSignals( TRUE );
    setDir( s );
    blockSignals( FALSE );
}

void CustomFileDialog::showEvent( QShowEvent *e )
{
    QFileDialog::showEvent( e );
    dirView->setDir( dirPath() );
}

void CustomFileDialog::bookmarkChosen( int i )
{
    if ( i == addId ) {
        bookmarkList << dirPath();
        bookmarkMenu->insertItem( dirPath() );
    } else {
        setDir( bookmarkMenu->text( i ) );
    }
}

void CustomFileDialog::goHome()
{
    if ( getenv( "HOME" ) )
        setDir( getenv( "HOME" ) );
    else
        setDir( "/" );
}

// ****************************************************************************************************

int main( int argc, char ** argv )
{
    QFileDialog::Mode mode = QFileDialog::ExistingFile;
    QString start;
    QString filter;
    QString caption;
    bool preview = FALSE;
    bool custom = FALSE;
    QApplication a( argc, argv );
    for (int i=1; i<argc; i++) {
        QString arg = argv[i];
        if ( arg == "-any" )
            mode = QFileDialog::AnyFile;
        else if ( arg == "-dir" )
            mode = QFileDialog::Directory;
        else if ( arg == "-default" )
            start = argv[++i];
        else if ( arg == "-filter" )
            filter = argv[++i];
        else if ( arg == "-preview" )
            preview = TRUE;
        else if ( arg == "-custom" )
            custom = TRUE;
        else if ( arg[0] == '-' ) {
            qDebug("Usage: qdir [-any | -dir | -custom] [-preview] [-default f] {-filter f} [caption ...]\n"
                   "      -any         Get any filename, need not exist.\n"
                   "      -dir         Return a directory rather than a file.\n"
                   "      -custom      Opens a customized QFileDialog with \n"
                   "                   dir browser, bookmark menu, etc.\n"
                   "      -preview     Show a preview widget.\n"
                   "      -default f   Start from directory/file f.\n"
                   "      -filter f    eg. '*.gif' '*.bmp'\n"
                   "      caption ...  Caption for dialog.\n"
                   );
            return 1;
        } else {
            if ( !caption.isNull() )
                caption += ' ';
            caption += arg;
        }
    }

    if ( !start )
        start = QDir::currentDirPath();

    if ( !caption )
        caption = mode == QFileDialog::Directory
                    ? "Choose directory..." : "Choose file...";

    if ( !custom ) {
        QFileDialog fd( QString::null, filter, 0, 0, TRUE );
        fd.setMode( mode );
        if ( preview ) {
            fd.setContentsPreviewEnabled( TRUE );
            PreviewWidget *pw = new PreviewWidget( &fd );
            fd.setContentsPreview( pw, pw );
            fd.setViewMode( QFileDialog::List );
            fd.setPreviewMode( QFileDialog::Contents );
        }
        fd.setCaption( caption );
        fd.setSelection( start );
        if ( fd.exec() == QDialog::Accepted ) {
            QString result = fd.selectedFile();
            printf("%s\n", (const char*)result);
            return 0;
        } else {
            return 1;
        }
    } else {
        CustomFileDialog fd;
        fd.exec();
        return 1;
    }
}

See also Examples.


qdir.h包含文件

qdir.h

这里是qdir.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qdir.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QDir class
**
** Created : 950427
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDIR_H
#define QDIR_H

#ifndef QT_H
#include "qstrlist.h"
#include "qfileinfo.h"
#include "qglobal.h"
#include "qwindowdefs.h"
#endif // QT_H

#ifndef QT_NO_DIR
typedef QPtrList<QFileInfo> QFileInfoList;
typedef QPtrListIterator<QFileInfo> QFileInfoListIterator;
class QStringList;

class Q_EXPORT QDir
{
public:
    enum FilterSpec { Dirs	    = 0x001,
              Files	    = 0x002,
              Drives	    = 0x004,
              NoSymLinks    = 0x008,
              All	    = 0x007,
               TypeMask	    = 0x00F,

              Readable	    = 0x010,
              Writable	    = 0x020,
              Executable    = 0x040,
               RWEMask	    = 0x070,

              Modified	    = 0x080,
              Hidden	    = 0x100,
              System	    = 0x200,
               AccessMask    = 0x3F0,

              DefaultFilter = -1 };

    enum SortSpec   { Name	    = 0x00,
              Time	    = 0x01,
              Size	    = 0x02,
              Unsorted	    = 0x03,
               SortByMask    = 0x03,

              DirsFirst	    = 0x04,
              Reversed	    = 0x08,
              IgnoreCase    = 0x10,
              DefaultSort   = -1 };

    QDir();
    QDir( const QString &path, const QString &nameFilter = QString::null,
      int sortSpec = Name | IgnoreCase, int filterSpec = All );
    QDir( const QDir & );

    virtual ~QDir();

    QDir       &operator=( const QDir & );
    QDir       &operator=( const QString &path );

    virtual void setPath( const QString &path );
    virtual QString path()		const;
    virtual QString absPath()	const;
    virtual QString canonicalPath()	const;

    virtual QString dirName() const;
    virtual QString filePath( const QString &fileName,
                  bool acceptAbsPath = TRUE ) const;
    virtual QString absFilePath( const QString &fileName,
                 bool acceptAbsPath = TRUE ) const;

    static QString convertSeparators( const QString &pathName );

    virtual bool cd( const QString &dirName, bool acceptAbsPath = TRUE );
    virtual bool cdUp();

    QString	nameFilter() const;
    virtual void setNameFilter( const QString &nameFilter );
    FilterSpec filter() const;
    virtual void setFilter( int filterSpec );
    SortSpec sorting() const;
    virtual void setSorting( int sortSpec );

    bool	matchAllDirs() const;
    virtual void setMatchAllDirs( bool );

    uint count() const;
    QString	operator[]( int ) const;

    virtual QStrList encodedEntryList( int filterSpec = DefaultFilter,
                       int sortSpec   = DefaultSort  ) const;
    virtual QStrList encodedEntryList( const QString &nameFilter,
                       int filterSpec = DefaultFilter,
                       int sortSpec   = DefaultSort   ) const;
    virtual QStringList entryList( int filterSpec = DefaultFilter,
                   int sortSpec   = DefaultSort  ) const;
    virtual QStringList entryList( const QString &nameFilter,
                   int filterSpec = DefaultFilter,
                   int sortSpec   = DefaultSort   ) const;

    virtual const QFileInfoList *entryInfoList( int filterSpec = DefaultFilter,
                        int sortSpec = DefaultSort ) const;
    virtual const QFileInfoList *entryInfoList( const QString &nameFilter,
                        int filterSpec = DefaultFilter,
                        int sortSpec = DefaultSort ) const;

    static const QFileInfoList *drives();

    virtual bool mkdir( const QString &dirName,
            bool acceptAbsPath = TRUE ) const;
    virtual bool rmdir( const QString &dirName,
            bool acceptAbsPath = TRUE ) const;

    virtual bool isReadable() const;
    virtual bool exists()   const;
    virtual bool isRoot()   const;

    virtual bool isRelative() const;
    virtual void convertToAbs();

    virtual bool operator==( const QDir & ) const;
    virtual bool operator!=( const QDir & ) const;

    virtual bool remove( const QString &fileName,
             bool acceptAbsPath = TRUE );
    virtual bool rename( const QString &name, const QString &newName,
             bool acceptAbsPaths = TRUE  );
    virtual bool exists( const QString &name,
             bool acceptAbsPath = TRUE );

    static char separator();

    static bool setCurrent( const QString &path );
    static QDir current();
    static QDir home();
    static QDir root();
    static QString currentDirPath();
    static QString homeDirPath();
    static QString rootDirPath();

    static bool match( const QStringList &filters, const QString &fileName );
    static bool match( const QString &filter, const QString &fileName );
    static QString cleanDirPath( const QString &dirPath );
    static bool isRelativePath( const QString &path );

private:
#ifdef Q_OS_MAC
    static FSSpec *make_spec(const QString &);
#endif
    void init();
    virtual bool readDirEntries( const QString &nameFilter,
                 int FilterSpec, int SortSpec  );

    static void slashify ( QString &);

    QString	dPath;
    QStringList   *fList;
    QFileInfoList *fiList;
    QString	nameFilt;
    FilterSpec	filtS;
    SortSpec	sortS;
    uint	dirty	: 1;
    uint	allDirs : 1;
};

inline QString QDir::path() const
{
    return dPath;
}

inline QString QDir::nameFilter() const
{
    return nameFilt;
}

inline QDir::FilterSpec QDir::filter() const
{
    return filtS;
}

inline QDir::SortSpec QDir::sorting() const
{
    return sortS;
}

inline bool QDir::matchAllDirs() const
{
    return allDirs;
}

inline bool QDir::operator!=( const QDir &d ) const
{
    return !(*this == d);
}

struct QDirSortItem {
    QString filename_cache;
    QFileInfo* item;
};

#endif // QT_NO_DIR
#endif // QDIR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDir成员列表

完整的QDir成员列表

这里是QDir成员函数的完整列表，包括继承的成员。

  • QDir()
  • ~QDir()
  • absFilePath()
  • absPath()
  • canonicalPath()
  • cd()
  • cdUp()
  • cleanDirPath()
  • convertSeparators()
  • convertToAbs()
  • count()
  • current()
  • currentDirPath()
  • dirName()
  • drives()
  • encodedEntryList()
  • entryInfoList()
  • entryList()
  • exists()
  • filePath()
  • filter()
  • home()
  • homeDirPath()
  • isReadable()
  • isRelative()
  • isRelativePath()
  • isRoot()
  • match()
  • matchAllDirs()
  • mkdir()
  • nameFilter()
  • operator!=()
  • operator=()
  • operator==()
  • operator[]()
  • path()
  • remove()
  • rename()
  • rmdir()
  • root()
  • rootDirPath()
  • separator()
  • setCurrent()
  • setFilter()
  • setMatchAllDirs()
  • setNameFilter()
  • setPath()
  • setSorting()
  • sorting()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDirectPainter Class

QDirectPainter Class Reference

The QDirectPainter class provides direct access to the video hardware. More...

#include <qdirectpainter_qws.h>

Inherits QPainter.

List of all member functions.

Public Members

  • QDirectPainter ( const QWidget * w )
  • ~QDirectPainter ()
  • uchar * frameBuffer ()
  • int lineStep ()
  • int transformOrientation ()
  • int numRects () const
  • const QRect & rect ( int i ) const
  • QRegion region ()
  • int depth () const
  • int width () const
  • int height () const
  • int xOffset () const
  • int yOffset () const
  • QPoint offset () const
  • QSize size () const
  • void setAreaChanged ( const QRect & r )

Detailed Description

The QDirectPainter class provides direct access to the video hardware.

Only available in Qt/Embedded.

When the hardware is known and well defined, as is often the case with software for embedded devices, it may be useful to manipulate the underlying video hardware directly. In order to do this in a way that is co-operative with other applications, you must lock the video hardware for exclusive use for a small time while you write to it, and you must know the clipping region which is allocated to a widget.

QDirectPainter provides this functionality.

In the simplest case, you make a QDirectPainter on a widget and then, observing the clip region, perform some platform-specific operation. For example:

        void MyWidget::updatePlatformGraphics()
        {
            QDirectPainter dp( this );
            for ( int i = 0; i < dp.numRects; i++ ) {
                const QRect& clip = dp.rect(i);
                ... // platform specific operation
            }
        }

The platform-specific code has access to the display, but should only modify graphics in the rectangles specified by numRects() and rect(). Note that these rectangles are relative to the entire display.

The offset() function returns the position of the widget relative to the entire display, allowing you to offset platform-specific operations appropriately. The xOffset() and yOffset() functions merely return the component values of offset().

For simple frame-buffer hardware, the frameBuffer(), lineStep(), and depth() functions provide basic access, though some hardware configurations are insufficiently specified by such simple parameters.

Note that while a QDirectPainter exists, the entire Qt/Embedded window system is locked from use by other applications. Always construct the QDirectPainter as an auto (stack) variable, and be very careful to write robust and stable code within its scope.

See also Graphics Classes.

Member Function Documentation

QDirectPainter::QDirectPainter ( const QWidget * w )

Construct a direct painter on w. The display is locked and the mouse cursor is hidden if it is above w.

QDirectPainter::~QDirectPainter ()

Destroys the direct painter. The mouse cursor is revealed if necessary and the display is unlocked.

int QDirectPainter::depth () const

Returns the bit-depth of the display.

uchar * QDirectPainter::frameBuffer ()

Returns a pointer to the framebuffer memory if available.

int QDirectPainter::height () const

Returns the height of the widget drawn upon.

int QDirectPainter::lineStep ()

Returns the spacing in bytes from one framebuffer line to the next.

int QDirectPainter::numRects () const

Returns the number of rectangles in the clip region.

See also rect() and clipRegion().

QPoint QDirectPainter::offset () const

Returns the position of the widget relative to the entire display.

const QRect & QDirectPainter::rect ( int i ) const

Returns a reference to rectangle i of the clip region. Valid values for i are 0..numRects()-1.

See also clipRegion().

void QDirectPainter::setAreaChanged ( const QRect & r )

Sets the area changed by the transaction to r. By default, the entire widget is assumed to have changed. The area changed is only used by some graphics drivers, so often calling this function for a smaller area will make no difference.

QSize QDirectPainter::size () const

Returns the size of the widget drawn upon.

See also width() and height().

int QDirectPainter::transformOrientation ()

Returns a number that signifies the orientation of the framebuffer.
0 | no rotation
1 | 90 degrees rotation
2 | 180 degrees rotation
3 | 270 degrees rotation

int QDirectPainter::width () const

Returns the width of the widget drawn upon.

int QDirectPainter::xOffset () const

Returns the X-position of the widget relative to the entire display.

int QDirectPainter::yOffset () const

Returns the Y-position of the widget relative to the entire display.

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


QDirectPainter Member List

Complete Member List for QDirectPainter

This is the complete list of member functions for QDirectPainter, including inherited members.

  • QDirectPainter()
  • ~QDirectPainter()
  • backgroundColor()
  • backgroundMode()
  • begin()
  • boundingRect()
  • brush()
  • brushOrigin()
  • clipRegion()
  • depth()
  • device()
  • drawArc()
  • drawChord()
  • drawConvexPolygon()
  • drawCubicBezier()
  • drawEllipse()
  • drawImage()
  • drawLine()
  • drawLineSegments()
  • drawPicture()
  • drawPie()
  • drawPixmap()
  • drawPoint()
  • drawPoints()
  • drawPolygon()
  • drawPolyline()
  • drawRect()
  • drawRoundRect()
  • drawText()
  • drawTiledPixmap()
  • drawWinFocusRect()
  • end()
  • eraseRect()
  • fillRect()
  • flush()
  • font()
  • fontInfo()
  • fontMetrics()
  • frameBuffer()
  • handle()
  • hasClipping()
  • hasViewXForm()
  • hasWorldXForm()
  • height()
  • isActive()
  • lineStep()
  • lineTo()
  • moveTo()
  • numRects()
  • offset()
  • pen()
  • pos()
  • rasterOp()
  • rect()
  • redirect()
  • resetXForm()
  • restore()
  • restoreWorldMatrix()
  • rotate()
  • save()
  • saveWorldMatrix()
  • scale()
  • setAreaChanged()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBrush()
  • setBrushOrigin()
  • setClipRect()
  • setClipRegion()
  • setClipping()
  • setFont()
  • setPen()
  • setRasterOp()
  • setTabArray()
  • setTabStops()
  • setViewXForm()
  • setViewport()
  • setWindow()
  • setWorldMatrix()
  • setWorldXForm()
  • shear()
  • size()
  • tabArray()
  • tabStops()
  • transformOrientation()
  • translate()
  • viewport()
  • width()
  • window()
  • worldMatrix()
  • xForm()
  • xFormDev()
  • xOffset()
  • yOffset()


qdirectpainter_qws.h Include File

qdirectpainter_qws.h

This is the verbatim text of the qdirectpainter_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qdirectpainter_qws.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QDirectPainter class
**
** Created : 010101
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDIRECTPAINTER_H
#define QDIRECTPAINTER_H

#ifndef QT_H
#include <qpainter.h>
#endif // QT_H

#ifdef Q_WS_QWS

class QDirectPainter : public QPainter {
public:
    QDirectPainter( const QWidget* );
    ~QDirectPainter();

    uchar* frameBuffer();
    int lineStep();
    int transformOrientation();

    int numRects() const;
    const QRect& rect(int i) const;
    QRegion region();

    int depth() const;
    int width() const;
    int height() const;
    int xOffset() const;
    int yOffset() const;

    QPoint offset() const;
    QSize size() const;

    void setAreaChanged( const QRect& );

private:
    class Private;
    Private* d;
};

#endif

#endif // QDIRECTPAINTER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDns Class

QDns Class Reference
[network module]

The QDns class provides asynchronous DNS lookups. More...

#include <qdns.h>

Inherits QObject.

List of all member functions.

Public Members

  • enum RecordType { None, A, Aaaa, Mx, Srv, Cname, Ptr, Txt }
  • QDns ()
  • QDns ( const QString & label, RecordType rr = A )
  • QDns ( const QHostAddress & address, RecordType rr = Ptr )
  • virtual ~QDns ()
  • virtual void setLabel ( const QString & label )
  • virtual void setLabel ( const QHostAddress & address )
  • QString label () const
  • virtual void setRecordType ( RecordType rr = A )
  • RecordType recordType () const
  • bool isWorking () const
  • QValueList<QHostAddress> addresses () const
  • QValueList<MailServer> mailServers () const
  • QValueList<Server> servers () const
  • QStringList hostNames () const
  • QStringList texts () const
  • QString canonicalName () const
  • QStringList qualifiedNames () const

Signals

  • void resultsReady ()

Detailed Description

The QDns class provides asynchronous DNS lookups.

Both Windows and Unix provide synchronous DNS lookups; Windows provides some asynchronous support too. At the time of writing neither operating system provides asynchronous support for anything other than hostname-to-address mapping.

QDns rectifies this shortcoming, by providing asynchronous caching lookups for the record types that we expect modern GUI applications to need in the near future.

The class is not straightforward to use (although it is much simpler than the native APIs); QSocket provides much easier to use TCP connection facilities. The aim of QDns is to provide a correct and small API to the DNS and nothing more. (We use "correctness" to mean that the DNS information is correctly cached, and correctly timed out.)

The API comprises a constructor, functions to set the DNS node (the domain in DNS terminology) and record type (setLabel() and setRecordType()), the corresponding get functions, an isWorking() function to determine whether QDns is working or reading, a resultsReady() signal and query functions for the result.

There is one query function for each RecordType, namely addresses(), mailServers(), servers(), hostNames() and texts(). There are also two generic query functions: canonicalName() returns the name you'll presumably end up using (the exact meaning of this depends on the record type) and qualifiedNames() returns a list of the fully qualified names label() maps to.

See also QSocket and Input/Output and Networking.

Member Type Documentation

QDns::RecordType

This enum type defines the record types QDns can handle. The DNS provides many more; these are the ones we've judged to be in current use, useful for GUI programs and important enough to support right away:

  • QDns::None - No information. This exists only so that QDns can have a default.
  • QDns::A - IPv4 addresses. By far the most common type.
  • QDns::Aaaa - IPv6 addresses. So far mostly unused.
  • QDns::Mx - Mail eXchanger names. Used for mail delivery.
  • QDns::Srv - SeRVer names. Generic record type for finding servers. So far mostly unused.
  • QDns::Cname - Canonical names. Maps from nicknames to the true name (the canonical name) for a host.
  • QDns::Ptr - name PoinTeRs. Maps from IPv4 or IPv6 addresses to hostnames.
  • QDns::Txt - arbitrary TeXT for domains.

We expect that some support for the RFC-2535 extensions will be added in future versions.

Member Function Documentation

QDns::QDns ()

Constructs a DNS query object with invalid settings for both the label and the search type.

QDns::QDns ( const QString & label, RecordType rr = A )

Constructs a DNS query object that will return record type rr information about label.

The DNS lookup is started the next time the application enters the event loop. When the result is found the signal resultsReady() is emitted.

rr defaults to A, IPv4 addresses.

QDns::QDns ( const QHostAddress & address, RecordType rr = Ptr )

Constructs a DNS query object that will return record type rr information about host address address. The label is set to the IN-ADDR.ARPA domain name. This is useful in combination with the Ptr record type (e.g. if you want to look up a hostname for a given address).

The DNS lookup is started the next time the application enters the event loop. When the result is found the signal resultsReady() is emitted.

rr defaults to Ptr, that maps addresses to hostnames.

QDns::~QDns () [virtual]

Destroys the DNS query object and frees its allocated resources.

QValueList<QHostAddress> QDns::addresses () const

Returns a list of the addresses for this name if this QDns object has a recordType() of QDns::A or QDns::Aaaa and the answer is available; otherwise returns an empty list.

As a special case, if label() is a valid numeric IP address, this function returns that address.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QHostAddress> list = myDns.addresses();
    QValueList<QHostAddress>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

QString QDns::canonicalName () const

Returns the canonical name for this DNS node. (This works regardless of what recordType() is set to.)

If the canonical name isn't known, this function returns a null string.

The canonical name of a DNS node is its full name, or the full name of the target of its CNAME. For example, if l.trolltech.com is a CNAME to lupinella.troll.no, and the search path for QDns is "trolltech.com", then the canonical name for all of "lupinella", "l", "lupinella.troll.no." and "l.trolltech.com" is "lupinella.troll.no.".

QStringList QDns::hostNames () const

Returns a list of host names if the record type is Ptr.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDns.hostNames();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

bool QDns::isWorking () const

Returns TRUE if QDns is doing a lookup for this object, and FALSE if this object already has the information it wants.

QDns emits the resultsReady() signal when the status changes to FALSE.

Example: network/mail/smtp.cpp.

QString QDns::label () const

Returns the domain name for which this object returns information.

See also setLabel().

QValueList<MailServer> QDns::mailServers () const

Returns a list of mail servers if the record type is Mx. The class QDns::MailServer contains the following public variables:
  • QString QDns::MailServer::name
  • Q_UINT16 QDns::MailServer::priority

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QDns::MailServer> list = myDns.mailServers();
    QValueList<QDns::MailServer>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

Example: network/mail/smtp.cpp.

QStringList QDns::qualifiedNames () const

Returns a list of the fully qualified names label() maps to.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDns.qualifiedNames();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

RecordType QDns::recordType () const

Returns the record type of this DNS query object.

See also setRecordType() and RecordType.

void QDns::resultsReady () [signal]

This signal is emitted when results are available for one of the qualifiedNames().

Example: network/mail/smtp.cpp.

QValueList<Server> QDns::servers () const

Returns a list of servers if the record type is Srv. The class QDns::Server contains the following public variables:
  • QString QDns::Server::name
  • Q_UINT16 QDns::Server::priority
  • Q_UINT16 QDns::Server::weight
  • Q_UINT16 QDns::Server::port

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QDns::Server> list = myDns.servers();
    QValueList<QDns::Server>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

void QDns::setLabel ( const QString & label ) [virtual]

Sets this DNS query object to query for information about label.

This does not change the recordType(), but its isWorking() status will probably change as a result.

The DNS lookup is started the next time the application enters the event loop. When the result is found the signal resultsReady() is emitted.

void QDns::setLabel ( const QHostAddress & address ) [virtual]

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

Sets this DNS query object to query for information about the host address address. The label is set to the IN-ADDR.ARPA domain name. This is useful in combination with the Ptr record type (e.g. if you want to look up a hostname for a given address).

void QDns::setRecordType ( RecordType rr = A ) [virtual]

Sets this object to query for record type rr records.

The DNS lookup is started the next time the application enters the event loop. When the result is found the signal resultsReady() is emitted.

See also RecordType.

QStringList QDns::texts () const

Returns a list of texts if the record type is Txt.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDns.texts();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

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


qdns.h Include File

qdns.h

This is the verbatim text of the qdns.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QDns class.
**
** Created : 991122
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDNS_H
#define QDNS_H

#ifndef QT_H
#include "qobject.h"
#include "qhostaddress.h"
#include "qsocketnotifier.h"
#include "qstringlist.h"
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_DNS
#else
#define QM_EXPORT_DNS Q_EXPORT
#endif

#ifndef QT_NO_DNS

//#define Q_DNS_SYNCHRONOUS

class QDnsPrivate;

class QM_EXPORT_DNS QDns: public QObject {
    Q_OBJECT
public:
    enum RecordType {
    None,
    A, Aaaa,
    Mx, Srv,
    Cname,
    Ptr,
    Txt
    };

    QDns();
    QDns( const QString & label, RecordType rr = A );
    QDns( const QHostAddress & address, RecordType rr = Ptr );
    virtual ~QDns();

    // to set/change the query
    virtual void setLabel( const QString & label );
    virtual void setLabel( const QHostAddress & address );
    QString label() const { return l; }

    virtual void setRecordType( RecordType rr = A );
    RecordType recordType() const { return t; }

    // whether something is happening behind the scenes
    bool isWorking() const;

    // to query for replies
    QValueList<QHostAddress> addresses() const;

    class QM_EXPORT_DNS MailServer {
    public:
    MailServer( const QString & n=QString::null, Q_UINT16 p=0 )
        :name(n), priority(p) {}
    QString name;
    Q_UINT16 priority;
#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const MailServer& ) const { return FALSE; }
#endif
    };
    QValueList<MailServer> mailServers() const;

    class QM_EXPORT_DNS Server {
    public:
    Server(const QString & n=QString::null, Q_UINT16 p=0, Q_UINT16 w=0, Q_UINT16 po=0 )
        : name(n), priority(p), weight(w), port(po) {}
    QString name;
    Q_UINT16 priority;
    Q_UINT16 weight;
    Q_UINT16 port;
#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const Server& ) const { return FALSE; }
#endif
    };
    QValueList<Server> servers() const;

    QStringList hostNames() const;

    QStringList texts() const;

    QString canonicalName() const; // ### real-world but uncommon: QStringList

    QStringList qualifiedNames() const { return n; }

#if defined(Q_DNS_SYNCHRONOUS)
protected:
    void connectNotify( const char *signal );
#endif

signals:
    void resultsReady();

private slots:
    void startQuery();

private:
    void setStartQueryTimer();
    QString toInAddrArpaDomain( const QHostAddress &address );
#if defined(Q_DNS_SYNCHRONOUS)
    void doSynchronousLookup();
#endif

    QString l;
    QStringList n;
    RecordType t;
    QDnsPrivate * d;
};

// QDnsSocket are sockets that are used for DNS lookup

class QDnsSocket: public QObject {
    Q_OBJECT
    // note: Private not public.  This class contains NO public API.
protected:
    QDnsSocket( QObject *, const char * );
    virtual ~QDnsSocket();

private slots:
    virtual void cleanCache();
    virtual void retransmit();
    virtual void answer();
};

#endif // QT_NO_DNS

#endif // QDNS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDns Member List

Complete Member List for QDns

This is the complete list of member functions for QDns, including inherited members.

  • QDns()
  • ~QDns()
  • addresses()
  • blockSignals()
  • canonicalName()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • hostNames()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • isWorking()
  • killTimer()
  • killTimers()
  • label()
  • mailServers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • qualifiedNames()
  • queryList()
  • recordType()
  • removeChild()
  • removeEventFilter()
  • resultsReady()
  • sender()
  • servers()
  • setLabel()
  • setName()
  • setProperty()
  • setRecordType()
  • signalsBlocked()
  • startTimer()
  • texts()
  • timerEvent()
  • tr()
  • trUtf8()


QDockArea类

QDockArea类参考

QDockArea类管理和布局QDockWindow。 详情请见……

#include <qdockarea.h>

继承了QWidget。

所有成员函数的列表。

公有成员

  • enum HandlePosition { Normal, Reverse }
  • QDockArea ( Orientation o, HandlePosition h = Normal, QWidget * parent = 0, const char * name = 0 )
  • ~QDockArea ()
  • void moveDockWindow ( QDockWindow * w, const QPoint & p, const QRect & r, bool swap )
  • void removeDockWindow ( QDockWindow * w, bool makeFloating, bool swap, bool fixNewLines = TRUE )
  • void moveDockWindow ( QDockWindow * w, int index = -1 )
  • bool hasDockWindow ( QDockWindow * w, int * index = 0 )
  • Orientation orientation () const
  • HandlePosition handlePosition () const
  • bool isEmpty () const
  • int count () const
  • QPtrList<QDockWindow> dockWindowList () const
  • bool isDockWindowAccepted ( QDockWindow * dw )
  • void setAcceptDockWindow ( QDockWindow * dw, bool accept )

公有槽

  • void lineUp ( bool keepNewLines )

属性

  • int count - 锚接区域中的锚接窗口的数量 （只读）
  • bool empty - 锚接区域是否为空 （只读）
  • HandlePosition handlePosition - 锚接窗口的分隔句柄被放在锚接区域的哪里 （只读）
  • Orientation orientation - 锚接区域的方向 （只读）

相关函数

  • QTextStream & operator<< ( QTextStream & ts, const QDockArea & dockArea )
  • QTextStream & operator>> ( QTextStream & ts, QDockArea & dockArea )

详细描述

QDockArea类管理和布局QDockWindow。

QDockArea是一个管理QDockWindow的列表，把它们布局在它的区域中的一个容器。在和QDockWindow的合作当中，它负责QDockWindow的锚接和取消锚接并且在锚接区域中移动它们。QDockArea也处理QDockWindow的自动换行来填充尽可能紧密的可用空间。QDockArea可以包含QToolBar，因为QToolBar是QDockWindow的一个子类。

QMainWindow包含四个你可以使用你的QToolBar和QDockWindow的QDockArea，所以在绝大多数情况下，你不需要直接使用QDockArea类。尽管QMainWindow包含了它自己的锚接区域，但是对于添加新的QDockArea它是不方便的。如果你需要创建你自己的锚接区域，我们建议你创建QWidget的一个子类并且把你的QDockArea添加到你的子类中。

行。QDockAre使用行的概念。一行就是可以并排地包含锚接窗口的一个水平区域。一个锚接区域可以拥有比一行更多的空间。当锚接窗口被锚接到一个锚接区域中时，它们通常被添加到这个空间中最上面一行的最右侧（除了是由用户手工放置的）。当用户移动锚接窗口时，它们可以离开空白行或者放入非空行的空隙中。使用lineUp()函数，锚接窗口可以被按行排序来使浪费的空间最小化。

QDockArea类维护着所有它的子锚接窗口的位置列表。被添加到锚接区域的锚接窗口是从0开始的。锚接窗口被按从左到右的顺序布局，并且对于多行的锚接窗口，是从上到下。如果一个锚接窗口被浮动起来，它还保持着它的位置，因为如果用户双击它的标题，它会返回它原来的位置。锚接窗口的位置可以被hasDockWindow()决定。位置可以被moveDockWindow()改变。

使用QDockWindow::dock()和QDockWindow::undock()可以分别锚接一个锚接窗口或者取消锚接一个锚接窗口。如果你想控制哪个锚接窗口可以锚接在一个锚接区域中请使用setAcceptDockWindow()。为了查看一个锚接区域是否有一个特定锚接窗口请使用hasDockWindow()，为了查看一个锚接区域中包含多少个锚接窗口请使用count()。

流操作符可以把锚接区域中的锚接窗口的位置写到QTextStream中。这些位置也可以在这之后被读出来恢复被保存的位置。

把位置存储到QTextStream中。

    ts << *myDockArea;

从QTextStream中恢复位置：

    ts >> *myDockArea;

也可以参考主窗口和相关类。

成员类型文档

QDockArea::HandlePosition

锚接窗口有两种句柄，锚接窗口句柄用于拖动锚接窗口，并且分隔句柄用于使用一个分隔符和其它锚接窗口的关系中来重新定义锚接窗口的大小。

这个枚举变量指定了锚接窗口分割句柄被放置到锚接区域的哪里。

  • QDockArea::Normal - 锚接窗口的分割句柄被放置到右面或者下面。
  • QDockArea::Reverse - 锚接窗口的分割句柄被放置到左面或者上面。

成员函数文档

QDockArea::QDockArea ( Orientation o, HandlePosition h = Normal, QWidget * parent = 0, const char * name = 0 )

构造一个方向为o、句柄位置为h、父对象为parent并且名称为name的QDockArea。

QDockArea::~QDockArea ()

销毁这个锚接区域和所有锚接到这个锚接区域的锚接窗口。

不会影响任何正在浮动的锚接窗口或者在其它锚接区域的锚接窗口，尽管它们最开始出现在这个锚接窗口中。正在浮动的锚接窗口是有效地顶级窗口并且不再是这个锚接区域的子窗口。当一个正在浮动的锚接窗口被锚接（拖动进入一个锚接区域），它的父对象变为这个锚接区域。

int QDockArea::count () const

返回锚接区域中锚接窗口的数量。详细情况请参考“count”属性。

QPtrList<QDockWindow> QDockArea::dockWindowList () const

返回锚接区域中锚接窗口的列表。

HandlePosition QDockArea::handlePosition () const

返回锚接窗口的分割处理器被放置到锚接区域的哪里。详细情况请参考“handlePosition”属性。

bool QDockArea::hasDockWindow ( QDockWindow * w, int * index = 0 )

如果锚接区域包含锚接窗口w，返回真，否则返回假。如果一个非空指针被作为index传递，它将被设置为如下这样：如果锚接区域包含锚接窗口，index被设置为w的位置，否则index被设置为-1。

bool QDockArea::isDockWindowAccepted ( QDockWindow * dw )

如果锚接窗口dw可以被锚接入这个锚接区域中，返回真，否则返回家爱。

也可以参考setAcceptDockWindow()。

bool QDockArea::isEmpty () const

如果锚接区域为空，返回真，否则返回假。详细情况请参考“empty”属性。

void QDockArea::lineUp ( bool keepNewLines ) [槽]

把在这个锚接区域中的锚接窗口排列起来使浪费的空间最小化。如果keepNewLines为真，只有行中的空间被清空。如果keepNewLines为假，行数可能被改变。

void QDockArea::moveDockWindow ( QDockWindow * w, int index = -1 )

把QDockWindow w移入锚接区域中。如果w没有被锚接到这个区域中，w首先被锚接。如果index为-1或者大于被锚接窗口的数量，w被添加到末尾，否则它被插入到index位置。

void QDockArea::moveDockWindow ( QDockWindow * w, const QPoint & p, const QRect & r, bool swap )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把锚接窗口w移入新位置为p（在全局屏幕坐标中）的锚接区域中，r是锚接窗口的被建议矩形并且swap指定锚接窗口的方向是否需要被改变。

这个函数被QDockWindow内部使用。你不应该需要自己调用它。

Orientation QDockArea::orientation () const

返回锚接区域的方向。详细情况请参考“orientation”属性。

void QDockArea::removeDockWindow ( QDockWindow * w, bool makeFloating, bool swap, bool fixNewLines = TRUE )

从锚接区域中移除锚接窗口w。如果makeFloating为真，w就会被浮动，并且如果swap为真，w的方向被切换。如果fixNewLines为真（默认），区域中的新行将被固定。

你应该永远不需要自己调用这个函数。使用QDockWindow::dock()和QDockWindow::undock()来替代它。

void QDockArea::setAcceptDockWindow ( QDockWindow * dw, bool accept )

如果accept为真，锚接窗口dw可以被锚接入锚接区域。如果accept为假，锚接窗口dw不可以被锚接入锚接区域。

也可以参考isDockWindowAccepted()。

属性文档

int count

这个属性保存的是锚接区域中的锚接窗口的数量。

通过count()来获得属性值。

bool empty

这个属性保存的是锚接区域是否为空。

通过isEmpty()来获得属性值。

HandlePosition handlePosition

这个属性保存的是锚接窗口的分隔句柄被放在锚接区域的哪里。

默认位置是Normal。

通过handlePosition()来获得属性值。

Orientation orientation

这个属性保存的是锚接区域的方向。

这个没有默认值，方向在构造函数中被指定。

通过orientation()来获得属性值。

相关函数

QTextStream & operator<< ( QTextStream & ts, const QDockArea & dockArea )

把锚接区域dockArea中的锚接窗口的布局写入文本流ts。

也可以参考operator>>()。

QTextStream & operator>> ( QTextStream & ts, QDockArea & dockArea )

从文本流ts中读取锚接区域dockArea的锚接窗口的布局描述并且恢复它。这隔布局描述必须已经由以前的operator<<()函数已经写入过了。

也可以参考operator<<()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdockarea.h包含文件

qdockarea.h

这里是qdockarea.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qdockarea.h   3.0.5   edited Jun 5 21:14 $
**
** Definition of the QDockArea class
**
** Created : 001010
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the workspace module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDOCKAREA_H
#define QDOCKAREA_H

#ifndef QT_H
#include "qwidget.h"
#include "qptrlist.h"
#include "qdockwindow.h"
#include "qlayout.h"
#include "qvaluelist.h"
#include "qguardedptr.h"
#include "qtextstream.h"
#endif // QT_H

#ifndef QT_NO_MAINWINDOW

class QSplitter;
class QBoxLayout;
class QDockAreaLayout;
class QMouseEvent;
class QDockWindowResizeHandle;
class QDockAreaPrivate;

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QValueList<QRect>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrList<QDockWindow>;
// MOC_SKIP_END
#endif

class Q_EXPORT QDockAreaLayout : public QLayout
{
    Q_OBJECT
    friend class QDockArea;

public:
    QDockAreaLayout( QWidget* parent, Qt::Orientation o, QPtrList<QDockWindow> *wl, int space = -1, int margin = -1, const char *name = 0 )
    : QLayout( parent, space, margin, name ), orient( o ), dockWindows( wl ), parentWidget( parent ) { init(); }
    ~QDockAreaLayout() {}

    void addItem( QLayoutItem * ) {}
    bool hasHeightForWidth() const;
    int heightForWidth( int ) const;
    int widthForHeight( int ) const;
    QSize sizeHint() const;
    QSize minimumSize() const;
    QLayoutIterator iterator();
    QSizePolicy::ExpandData expanding() const { return QSizePolicy::NoDirection; }
    void invalidate();
    Qt::Orientation orientation() const { return orient; }
    QValueList<QRect> lineList() const { return lines; }
    QPtrList<QDockWindow> lineStarts() const { return ls; }

protected:
    void setGeometry( const QRect& );

private:
    void init();
    int layoutItems( const QRect&, bool testonly = FALSE );
    Qt::Orientation orient;
    bool dirty;
    int cached_width, cached_height;
    int cached_hfw, cached_wfh;
    QPtrList<QDockWindow> *dockWindows;
    QWidget *parentWidget;
    QValueList<QRect> lines;
    QPtrList<QDockWindow> ls;

};

class Q_EXPORT QDockArea : public QWidget
{
    Q_OBJECT
    Q_ENUMS( HandlePosition )
    Q_PROPERTY( Orientation orientation READ orientation )
    Q_PROPERTY( int count READ count )
    Q_PROPERTY( bool empty READ isEmpty )
    Q_PROPERTY( HandlePosition handlePosition READ handlePosition )

    friend class QDockWindow;
    friend class QDockWindowResizeHandle;
    friend class QDockAreaLayout;

public:
    enum HandlePosition { Normal, Reverse };

    QDockArea( Orientation o, HandlePosition h = Normal, QWidget* parent=0, const char* name=0 );
    ~QDockArea();

    void moveDockWindow( QDockWindow *w, const QPoint &globalPos, const QRect &rect, bool swap );
    void removeDockWindow( QDockWindow *w, bool makeFloating, bool swap, bool fixNewLines = TRUE );
    void moveDockWindow( QDockWindow *w, int index = -1 );
    bool hasDockWindow( QDockWindow *w, int *index = 0 );

    void invalidNextOffset( QDockWindow *dw );

    Orientation orientation() const { return orient; }
    HandlePosition handlePosition() const { return hPos; }

    bool eventFilter( QObject *, QEvent * );
    bool isEmpty() const;
    int count() const;
    QPtrList<QDockWindow> dockWindowList() const;

    bool isDockWindowAccepted( QDockWindow *dw );
    void setAcceptDockWindow( QDockWindow *dw, bool accept );

public slots:
    void lineUp( bool keepNewLines );

private:
    struct DockWindowData
    {
    int index;
    int offset;
    int line;
    QSize fixedExtent;
    QGuardedPtr<QDockArea> area;
    };

    int findDockWindow( QDockWindow *w );
    int lineOf( int index );
    DockWindowData *dockWindowData( QDockWindow *w );
    void dockWindow( QDockWindow *dockWindow, DockWindowData *data );
    void updateLayout();
    void invalidateFixedSizes();
    int maxSpace( int hint, QDockWindow *dw );
    void setFixedExtent( int d, QDockWindow *dw );
    bool isLastDockWindow( QDockWindow *dw );

private:
    Orientation orient;
    QPtrList<QDockWindow> *dockWindows;
    QDockAreaLayout *layout;
    HandlePosition hPos;
    QPtrList<QDockWindow> forbiddenWidgets;
    QDockAreaPrivate *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QDockArea( const QDockArea & );
    QDockArea& operator=( const QDockArea & );
#endif

};

#ifndef QT_NO_TEXTSTREAM
Q_EXPORT QTextStream &operator<<( QTextStream &, const QDockArea & );
Q_EXPORT QTextStream &operator>>( QTextStream &, QDockArea & );
#endif

#endif

#endif //QT_NO_MAINWINDOW

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDockArea成员列表

完整的QDockArea成员列表

这里是QDockArea成员函数的完整列表，包括继承的成员。

  • QDockArea()
  • ~QDockArea()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dockWindowList()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • handlePosition()
  • hasDockWindow()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isDockWindowAccepted()
  • isEmpty()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineUp()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveDockWindow()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeDockWindow()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDockWindow()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDockWindow类

QDockWindow类参考

QDockWindow类提供了可以被锚接入QDockArea或者作为顶级窗口在桌面上浮动的窗口部件。 详情请见……

#include <qdockwindow.h>

继承了QFrame。

被QToolBar继承。

所有成员函数的列表。

公有成员

  • enum Place { InDock, OutsideDock }
  • enum CloseMode { Never = 0, Docked = 1, Undocked = 2, Always = Docked | Undocked }
  • QDockWindow ( Place p = InDock, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • virtual void setWidget ( QWidget * w )
  • QWidget * widget () const
  • Place place () const
  • QDockArea * area () const
  • virtual void setCloseMode ( int m )
  • bool isCloseEnabled () const
  • int closeMode () const
  • virtual void setResizeEnabled ( bool b )
  • virtual void setMovingEnabled ( bool b )
  • bool isResizeEnabled () const
  • bool isMovingEnabled () const
  • virtual void setHorizontallyStretchable ( bool b )
  • virtual void setVerticallyStretchable ( bool b )
  • bool isHorizontallyStretchable () const
  • bool isVerticallyStretchable () const
  • void setHorizontalStretchable ( bool b ) (obsolete)
  • void setVerticalStretchable ( bool b ) (obsolete)
  • bool isHorizontalStretchable () const (obsolete)
  • bool isVerticalStretchable () const (obsolete)
  • bool isStretchable () const
  • virtual void setOffset ( int o )
  • int offset () const
  • virtual void setFixedExtentWidth ( int w )
  • virtual void setFixedExtentHeight ( int h )
  • QSize fixedExtent () const
  • virtual void setNewLine ( bool b )
  • bool newLine () const
  • Qt::Orientation orientation () const
  • QBoxLayout * boxLayout ()
  • virtual void setOpaqueMoving ( bool b )
  • bool opaqueMoving () const

公有槽

  • virtual void undock ()
  • virtual void dock ()
  • virtual void setOrientation ( Orientation o )

信号

  • void orientationChanged ( Orientation o )
  • void placeChanged ( QDockWindow::Place p )
  • void visibilityChanged ( bool visible )

属性

  • int closeMode - 锚接窗口的关闭模式
  • bool horizontallyStretchable - 锚接窗口水平方向上可否延伸
  • bool movingEnabled - 用户可不可以在锚接区域内移动锚接窗口、把锚接窗口移动到其他锚接区域、或者浮动锚接窗口
  • bool newLine - 锚接窗口是否更愿意在锚接区域中新开一行
  • int offset - 锚接窗口对于锚接区域的左边界（对于垂直锚接区域是上边界）首选的位移
  • bool opaqueMoving - 在锚接窗口正在被移动的时候，锚接窗口是否将被正常显示
  • Place place - 锚接窗口是否在锚接区域中 （只读）
  • bool resizeEnabled - 锚接窗口是否是可以重新定义大小的
  • bool stretchable - 锚接窗口在当前的orientation()上是否是可延伸的 （只读）
  • bool verticallyStretchable - 锚接窗口垂直方向上可否延伸

详细描述

QDockWindow类提供了可以被锚接入QDockArea或者作为顶级窗口在桌面上浮动的窗口部件。

这个类处理锚接窗口的移动、重定义大小、锚接和取消锚接。QToolBar是QDockWindow的一个子类，所以提供给锚接窗口的功能对于工具条的相同应用编程接口也是可用的。

QDockWindows in a QDockArea

在QDockArea中的两个QDockWindow（QToolBar）

一个浮动的QDockWindow

如果用户把锚接窗口拖动到锚接区域中，锚接窗口将被锚接。如果用户锚接窗口拖动到任何锚接窗口外面，锚接窗口将被取消锚接（也就是被浮动）并且变为一个顶级窗口。双击浮动的锚接窗口的标题栏将会把锚接窗口锚接到它最近一次被锚接的地方。双击被锚接的锚接窗口句柄将取消锚接窗口的锚接（也就是浮动起来）。单击被锚接的锚接窗口句柄将最小化这个锚接窗口（只有它的句柄被显示，在菜单条下面）。单击最小化句柄将会把锚接窗口恢复到最近一次被锚接的地方。如果用户点击关闭按钮（默认情况下会出现在浮动的锚接窗口上），锚接窗口将会消失。你可以通过setCloseMode()控制锚接窗口是否有一个关闭按钮。

QMainWindow提供四个可以用来锚接窗口的锚接区域（上、下、左、右）。对于一些应用程序使用这些QMainWindow提供的锚接区域将是足够的。（如果你想创建你自己的锚接区域，请参考QDockArea文档。）在QMainWindow中右键单击弹出菜单（锚接窗口菜单）是可以用来列出锚接窗口的列表的并且可以用来显示或者隐藏它们。

当你构造一个锚接窗口时，如果你想它被锚接的话，你必须把QDockArea或者QMainWindow传递给它作为父对象。如果你想它被浮动，就传递0给它作为父对象。

    QToolBar *fileTools = new QToolBar( this, "File Actions" );
    moveDockWindow( fileTools, Left );

在上述的实例中，你在一个QMainWindow的子类的构造函数中创建一个新的QToolBar（所以this指针指向QMainWindow）。默认情况下，这个工具条将被添加到Top锚接区域，但是我们已经把它移动到Left锚接区域了。

锚接窗口通常用于包含一个单一的窗口部件。在这些情况下，这个窗口部件可以通过调用setWidget()来被设置。如果你正在构造一个包含多个窗口部件的锚接窗口，例如一个工具条把窗口部件排列在锚接窗口的盒子布局中。为了做到这点，请使用boxLayout()函数来获得锚接窗口的盒子布局，然后使用盒子布局的QBoxLayout::addWidget()函数来把窗口部件添加到这个布局中。锚接窗口将会按需要动态地设置布局的方向为水平或者垂直，尽管你可以通过setOrientation()来自己控制它。

尽管锚接窗口的通常用途是为了工具条，它们可以被用于任何窗口部件。（对于实例，请参考Qt设计器和Qt语言学家应用程序。）当使用更大的窗口部件，它可以通过调用setResizeEnabled()来告诉锚接窗口可以被重新定义大小。可重新定义大小的锚接窗口是给定像分割句柄来允许用户在它们的锚接区域中重新定义它们的大小。当可重新定义大小的锚接窗口被取消锚接，它们变为顶级窗口并且可以像其它顶级窗口被重新定义大小，例如通过拖动角或者边缘来实现。

锚接窗口可以使用dock()和undock()来被锚接和取消锚接。锚接窗口的方向可以使用setOrientation()来设置。你也可以使用QDockArea::moveDockWindow()。如果你正在使用一个QMainWindow，QMainWindow::moveDockWindow()和QMainWindow::removeDockWindow()是可用的。

锚接窗口有一些首选设置，例如，你可以使用setOffset()设置从锚接区域的左边界（对于垂直锚接区域是上边界）开始的首选位移。如果你喜欢锚接窗口当它被锚接时开始一个新行，请使用setNewLine()。setFixedExtentWidth()和setFixedExtentHeight()函数可以用来定义锚接窗口的首选大小，并且setHorizontallyStretchable()和setVerticallyStretchable()函数设置锚接窗口是否可以被延伸。默认情况下锚接窗口可以被移动，但是这个可以通过setMovingEnabled()来改变。当锚接窗口被移动时，它被显示唯一个矩形边界，但是使用setOpaqueMoving()它可以被正常地显示。

当锚接窗口的可视性发生改变，也就是它被显示或者隐藏，visibilityChanged() 信号被发射。当锚接窗口被锚接或者取消锚接时，placeChanged()信号被发射。

也可以参考主窗口和相关类。

成员类型文档

QDockWindow::CloseMode

这个枚举变量指定了锚接窗口什么时候有（如果）一个关闭按钮。

  • QDockWindow::Never - 锚接窗口从没有一个关闭按钮并且不能被用户关闭
  • QDockWindow::Docked - 锚接窗口只有在被锚接的时候有一个关闭按钮。
  • QDockWindow::Undocked - 锚接窗口只有在浮动的时候有一个关闭按钮。
  • QDockWindow::Always - 锚接窗口总是有一个关闭按钮。

注意如果用户在锚接窗口被锚接时点击它们的锚接窗口句柄，锚接窗口总是被最小化。

QDockWindow::Place

这个枚举变量指定了QDockWindow的可能位置：

  • QDockWindow::InDock - 在一个QDockArea中
  • QDockWindow::OutsideDock - 在桌面上作为顶级窗口浮动。

成员函数文档

QDockWindow::QDockWindow ( Place p = InDock, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个父对象为parent、名称为name并且窗口部件标记为f的QDockWindow。

如果p为InDock，这个锚接窗口被锚接如一个锚接区域并且parent必须为QDockArea或QMainWindow。如果parent为QMainWindow，锚接窗口将被锚接到这个主窗口的Top锚接区域。

如果p为OutsideDock，parent必须为0并且这个锚接窗口被创建为浮动窗口。

我们建议创建QMainWindow为父对象，锚接位置为InDock的锚接窗口，然后调用QMainWindow::moveDockWindow()来把这个锚接窗口移动到你想要的位置。

QDockArea * QDockWindow::area () const

返回锚接窗口被锚接的锚接区域，或者如果它正在浮动，返回0。

QBoxLayout * QDockWindow::boxLayout ()

返回用于把窗口部件添加到锚接窗口的布局。布局的方向自动与锚接窗口的方向匹配。你可以使用盒子布局的QBoxLayout::addWidget()函数来添加窗口部件到这个布局中。

如果锚接窗口只需要包含一个窗口部件，请使用setWidget()来替代它。

也可以参考setWidget()和setOrientation()。

int QDockWindow::closeMode () const

返回锚接窗口的关闭模式。详细情况请参考“closeMode”属性。

void QDockWindow::dock () [虚 槽]

把锚接窗口锚接到它最近一次被锚接的锚接区域中。

如果锚接窗口没有最近一次被锚接的区域（例如它被创建为浮动的并且从没有被锚接过），或者如果最近一次被锚接的区域已经不存在了（例如那个锚接区域已经被删除了），就什么也不会发生。

也可以参考undock()。

QSize QDockWindow::fixedExtent () const

返回锚接窗口的首选大小（固定的宽度）。

也可以参考setFixedExtentWidth()和setFixedExtentHeight()。

bool QDockWindow::isCloseEnabled () const

如果锚接窗口有一个关闭按钮，返回真，否则返回假。这个结果依赖于锚接窗口的Place和它的CloseMode。

也可以参考closeMode。

bool QDockWindow::isHorizontalStretchable () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

bool QDockWindow::isHorizontallyStretchable () const

如果锚接窗口是水平方向上可延伸的，返回真，否则返回假。详细情况请参考“horizontallyStretchable”属性。

bool QDockWindow::isMovingEnabled () const

如果用户可以在锚接区域内移动锚接窗口、把锚接窗口移动到其他锚接区域、或者浮动锚接窗口，返回真，否则返回假。详细情况请参考“movingEnabled”属性。

bool QDockWindow::isResizeEnabled () const

如果锚接窗口是可以重新定义大小的，返回真，否则返回假。详细情况请参考“resizeEnabled”属性。

bool QDockWindow::isStretchable () const

如果锚接窗口在当前的orientation()上是可延伸的，返回真，否则返回假。详细情况请参考“stretchable”属性。

bool QDockWindow::isVerticalStretchable () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

bool QDockWindow::isVerticallyStretchable () const

如果锚接窗口是垂直方向上可延伸的，返回真，否则返回假。详细情况请参考“verticallyStretchable”属性。

bool QDockWindow::newLine () const

如果锚接窗口更愿意在锚接区域中新开一行，返回真否则返回假。详细情况请参考“newLine”属性。

int QDockWindow::offset () const

返回锚接窗口对于锚接区域的左边界（对于垂直锚接区域是上边界）首选的位移。详细情况请参考“offset”属性。

bool QDockWindow::opaqueMoving () const

如果在锚接窗口正在被移动的时候，锚接窗口将被正常显示，返回真，否则返回假。详细情况请参考“opaqueMoving”属性。

Qt::Orientation QDockWindow::orientation () const

返回锚接窗口的方向。

也可以参考orientationChanged()。

void QDockWindow::orientationChanged ( Orientation o ) [信号]

当锚接窗口的方向发生改变时，这个信号被发射。新方向为o。

Place QDockWindow::place () const

如果锚接窗口在锚接区域中，返回真，否则返回假。详细情况请参考“place”属性。

void QDockWindow::placeChanged ( QDockWindow::Place p ) [信号]

当锚接窗口被锚接时（p为InDock）或者被取消锚接时（p为OutsideDock），这个信号被发射。

也可以参考QDockArea::moveDockWindow()、QDockArea::removeDockWindow()、QMainWindow::moveDockWindow()和QMainWindow::removeDockWindow()。

void QDockWindow::setCloseMode ( int m ) [信号]

设置锚接窗口的关闭模式为m。详细情况请参考“closeMode”属性。

void QDockWindow::setFixedExtentHeight ( int h ) [虚]

设置锚接窗口的固定宽度（大小）时的首选高度为h。

也可以参考setFixedExtentWidth()。

void QDockWindow::setFixedExtentWidth ( int w ) [虚]

设置锚接窗口的固定宽度（大小）时的首选宽度为w。

也可以参考setFixedExtentHeight()。

void QDockWindow::setHorizontalStretchable ( bool b )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QDockWindow::setHorizontallyStretchable ( bool b ) [虚]

设置锚接窗口在水平方向上是否可延伸为b。详细情况请参考“horizontallyStretchable”属性。

void QDockWindow::setMovingEnabled ( bool b ) [虚]

设置用户可不可以在锚接区域内移动锚接窗口、把锚接窗口移动到其他锚接区域、或者浮动锚接窗口为b。详细情况请参考“movingEnabled”属性。

void QDockWindow::setNewLine ( bool b ) [虚]

设置锚接窗口是否更愿意在锚接区域中新开一行为b。详细情况请参考“newLine”属性。

void QDockWindow::setOffset ( int o ) [虚]

设置锚接窗口对于锚接区域的左边界（对于垂直锚接区域是上边界）首选的位移为o。详细情况请参考“offset”属性。

void QDockWindow::setOpaqueMoving ( bool b ) [虚]

设置在锚接窗口正在被移动的时候，锚接窗口是否将被正常显示为b。详细情况请参考“opaqueMoving”属性。

void QDockWindow::setOrientation ( Orientation o ) [虚 槽]

设置锚接窗口的方向为o。这个方向被发送给boxLayout()布局。

void QDockWindow::setResizeEnabled ( bool b ) [虚]

设置锚接窗口在当前的orientation()上是否是可延伸的为b。详细情况请参考“resizeEnabled”属性。

void QDockWindow::setVerticalStretchable ( bool b )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QDockWindow::setVerticallyStretchable ( bool b ) [虚]

See the "verticallyStretchable" property for details. 设置锚接窗口垂直方向上可否延伸为b。详细情况请参考“verticallyStretchable”属性。

void QDockWindow::setWidget ( QWidget * w ) [虚]

设置锚接窗口的主窗口为w。

也可以参考boxLayout()。

void QDockWindow::undock () [虚 槽]

Undocks the QDockWindow from its current dock area if it is docked; otherwise does nothing.

也可以参考dock()、QDockArea::moveDockWindow()、QDockArea::removeDockWindow()、QMainWindow::moveDockWindow()和QMainWindow::removeDockWindow()。

void QDockWindow::visibilityChanged ( bool visible ) [信号]

如果锚接窗口的可视性发生变化，这个信号被发射。如果visible为真，QDockWindow现在是可视的，否则它已经被隐藏。

如果锚接窗口有一个用户可点击的关闭按钮，它可以被隐藏。在QMainWindow中，通过点击在QMainWindow的锚接窗口列表的锚接窗口菜单中它的名称，锚接窗口可以有它们自己的可视性变化（隐藏或者显示）。

QWidget * QDockWindow::widget () const

返回锚接窗口的主窗口。

也可以参考setWidget()。

属性文档

int closeMode

这个属性保存的是锚接窗口的关闭模式。

定义了锚接窗口什么时候有（如果）一个关闭按钮。可以选择Never、Docked（也就是只当被锚接的时候）、Undocked（仅当被取消锚接的时候，也就是浮动时）或者Always。

默认是Never。

通过setCloseMode()设置属性值并且通过closeMode()来获得属性值。

bool horizontallyStretchable

这个属性保存的是锚接窗口水平方向上可否延伸。

如果你调用setHorizontallyStretchable(TRUE)或者setResizeEnabled(TRUE)，锚接窗口是水平可延伸的。

也可以参考resizeEnabled。

通过setHorizontallyStretchable()设置属性值并且通过isHorizontallyStretchable()来获得属性值。

bool movingEnabled

这个属性保存的是用户可不可以在锚接区域内移动锚接窗口、把锚接窗口移动到其他锚接区域、或者浮动锚接窗口。

这个属性默认为真。

通过setMovingEnabled()设置属性值并且通过isMovingEnabled()来获得属性值。

bool newLine

这个属性保存的是锚接窗口是否更愿意在锚接区域中新开一行。

默认为假，也就是锚接窗口不需要在锚接区域中新开一行。

通过setNewLine()设置属性值并且通过newLine()来获得属性值。

int offset

这个属性保存的是锚接窗口对于锚接区域的左边界（对于垂直锚接区域是上边界）首选的位移。

默认为0。

通过setOffset()设置属性值并且通过offset()来获得属性值。

bool opaqueMoving

这个属性保存的是在锚接窗口正在被移动的时候，锚接窗口是否将被正常显示。

如果这个属性为假（默认），锚接窗口在被移动的时候将被表现为一个边界矩形。

工具条和锚接窗口的不透明移动已经被知道有一些问题。我们建议不要在这时使用这一点。我们将在稍后的发布中修改这个行为问题。

通过setOpaqueMoving()设置属性值并且通过opaqueMoving()来获得属性值。

Place place

这个属性保存的是锚接窗口是否在锚接区域中。

place()函数返回锚接窗口的当前位置。结果是InDock或OutsideDock。

也可以参考QDockArea::moveDockWindow()、QDockArea::removeDockWindow()、QMainWindow::moveDockWindow()和QMainWindow::removeDockWindow()。

通过place()来获得属性值。

bool resizeEnabled

这个属性保存的是锚接窗口是否是可以重新定义大小的。

可重新定义大小的锚接窗口是可以通过在锚接区域中使用像分割句柄并且当浮动时像每一个其它顶级窗口那样被重新定义大小。

如果你调用setResizeEnabled(TRUE)，锚接窗口水平方向和垂直方向都是可延伸的。

默认为假。

也可以参考verticallyStretchable和horizontallyStretchable。

通过setResizeEnabled()设置属性值并且通过isResizeEnabled()来获得属性值。

bool stretchable

这个属性保存的是锚接窗口在当前的orientation()上是否是可延伸的。

这个属性可以通过使用setHorizontallyStretchable()和setVerticallyStretchable()或者setResizeEnabled()来被设置。

也可以参考resizeEnabled。

通过isStretchable()来获得属性值。

bool verticallyStretchable

这个属性保存的是锚接窗口垂直方向上可否延伸。

如果你调用setVerticallyStretchable(TRUE)或setResizeEnabled(TRUE)，锚接窗口在垂直方向上是可延伸的。

也可以参考resizeEnabled。

通过setVerticallyStretchable()设置属性值并且通过isVerticallyStretchable()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdockwindow.h包含文件

qdockwindow.h

这里是qdockwindow.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qdockwindow.h   3.0.5   edited Nov 15 2001 $
**
** Definition of the QDockWindow class
**
** Created : 001010
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the workspace module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDOCKWIDGET_H
#define QDOCKWIDGET_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_MAINWINDOW

class QDockWindowHandle;
class QDockWindowTitleBar;
class QPainter;
class QDockWindowResizeHandle;
class QBoxLayout;
class QHBoxLayout;
class QVBoxLayout;
class QDockArea;
class QWidgetResizeHandler;
class QMainWindow;
class QDockAreaLayout;
class QDockWindowPrivate;

class Q_EXPORT QDockWindow : public QFrame
{
    Q_OBJECT
    Q_ENUMS( CloseMode Place )
    Q_PROPERTY( int closeMode READ closeMode  WRITE setCloseMode ) //### this shouldn't be of type int?!
    Q_PROPERTY( bool resizeEnabled READ isResizeEnabled  WRITE setResizeEnabled )
    Q_PROPERTY( bool movingEnabled READ isMovingEnabled  WRITE setMovingEnabled )
    Q_PROPERTY( bool horizontallyStretchable READ isHorizontallyStretchable  WRITE setHorizontallyStretchable )
    Q_PROPERTY( bool verticallyStretchable READ isVerticallyStretchable  WRITE setVerticallyStretchable )
    Q_PROPERTY( bool stretchable READ isStretchable )
    Q_PROPERTY( bool newLine READ newLine  WRITE setNewLine )
    Q_PROPERTY( bool opaqueMoving READ opaqueMoving  WRITE setOpaqueMoving )
    Q_PROPERTY( int offset READ offset  WRITE setOffset )
    Q_PROPERTY( Place place READ place )

    friend class QDockWindowHandle;
    friend class QDockWindowTitleBar;
    friend class QDockArea;
    friend class QDockAreaLayout;
    friend class QMainWindow;

public:
    enum Place { InDock, OutsideDock };
    enum CloseMode { Never = 0, Docked = 1, Undocked = 2, Always = Docked | Undocked };

    QDockWindow( Place p = InDock, QWidget* parent=0, const char* name=0, WFlags f = 0 );
    ~QDockWindow();

    virtual void setWidget( QWidget *w );
    QWidget *widget() const;

    Place place() const { return curPlace; }

    QDockArea *area() const;

    virtual void setCloseMode( int m );
    bool isCloseEnabled() const;
    int closeMode() const;

    virtual void setResizeEnabled( bool b );
    virtual void setMovingEnabled( bool b );
    bool isResizeEnabled() const;
    bool isMovingEnabled() const;

    virtual void setHorizontallyStretchable( bool b );
    virtual void setVerticallyStretchable( bool b );
    bool isHorizontallyStretchable() const;
    bool isVerticallyStretchable() const;
    void setHorizontalStretchable( bool b ) { setHorizontallyStretchable( b ); }
    void setVerticalStretchable( bool b ) { setVerticallyStretchable( b ); }
    bool isHorizontalStretchable() const { return isHorizontallyStretchable(); }
    bool isVerticalStretchable() const { return isVerticallyStretchable(); }
    bool isStretchable() const;

    virtual void setOffset( int o );
    int offset() const;

    virtual void setFixedExtentWidth( int w );
    virtual void setFixedExtentHeight( int h );
    QSize fixedExtent() const;

    virtual void setNewLine( bool b );
    bool newLine() const;

    Qt::Orientation orientation() const;

    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize minimumSizeHint() const;

    QBoxLayout *boxLayout();

    virtual void setOpaqueMoving( bool b );
    bool opaqueMoving() const;

    bool eventFilter( QObject *o, QEvent *e );

#ifdef QT_NO_WIDGET_TOPEXTRA
    QString caption() const;
#endif

signals:
    void orientationChanged( Orientation o );
    void placeChanged( QDockWindow::Place p );
    void visibilityChanged( bool );

public slots:
    virtual void undock( QWidget *w );
    virtual void undock() { undock( 0 ); }
    virtual void dock();
    virtual void setOrientation( Orientation o );
    void setCaption( const QString &s );

protected:
    void resizeEvent( QResizeEvent *e );
    void showEvent( QShowEvent *e );
    void hideEvent( QHideEvent *e );
    void contextMenuEvent( QContextMenuEvent *e );

    void drawFrame( QPainter * );

    bool event( QEvent *e );

private slots:
    void toggleVisible() { if ( !isVisible() ) show(); else hide(); }

private:
    void handleMove( const QPoint &pos, const QPoint &gp, bool drawRect );
    void updateGui();
    void updateSplitterVisibility( bool visible );

    void startRectDraw( const QPoint &so, bool drawRect );
    void endRectDraw( bool drawRect );
    void updatePosition( const QPoint &globalPos  );
    QWidget *areaAt( const QPoint &gp );
    void removeFromDock( bool fixNewLines = TRUE );
    void swapRect( QRect &r, Qt::Orientation o, const QPoint &offset, QDockArea *area );

private:
    QDockWindowHandle *horHandle, *verHandle;
    QDockWindowTitleBar *titleBar;
    QWidget *wid;
    QPainter *unclippedPainter;
    QDockArea *dockArea, *tmpDockArea;
    QRect currRect;
    Place curPlace;
    Place state;
    bool resizeEnabled : 1;
    bool moveEnabled : 1;
    bool nl : 1;
    bool opaque : 1;
    bool stretchable[ 3 ];
    Orientation startOrientation;
    int cMode;
    QPoint startOffset;
    int offs;
    QSize fExtent;
    QDockWindowResizeHandle *hHandleTop, *hHandleBottom, *vHandleLeft, *vHandleRight;
    QVBoxLayout *hbox;
    QHBoxLayout *vbox;
    QBoxLayout *layout;
    void *dockWindowData;
    QPoint lastPos;
    QSize lastSize;
    QWidgetResizeHandler *widgetResizeHandler;
    QDockWindowPrivate *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QDockWindow( const QDockWindow & );
    QDockWindow& operator=( const QDockWindow & );
#endif
};

inline QDockArea *QDockWindow::area() const
{
    return dockArea;
}

#endif

#endif //QT_NO_MAINWINDOW

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDockWindow成员列表

完整的QDockWindow成员列表

这里是QDockWindow成员函数的完整列表，包括继承的成员。

  • QDockWindow()
  • acceptDrops()
  • adjustSize()
  • area()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • boxLayout()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • closeMode()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dock()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • fixedExtent()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isCloseEnabled()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isHorizontalStretchable()
  • isHorizontallyStretchable()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isMovingEnabled()
  • isPopup()
  • isResizeEnabled()
  • isStretchable()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVerticalStretchable()
  • isVerticallyStretchable()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • newLine()
  • normalizeSignalSlot()
  • objectTrees()
  • offset()
  • opaqueMoving()
  • orientation()
  • orientationChanged()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • place()
  • placeChanged()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCloseMode()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedExtentHeight()
  • setFixedExtentWidth()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHorizontalStretchable()
  • setHorizontallyStretchable()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMovingEnabled()
  • setName()
  • setNewLine()
  • setOffset()
  • setOpaqueMoving()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVerticalStretchable()
  • setVerticallyStretchable()
  • setWFlags()
  • setWidget()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • undock()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibilityChanged()
  • visibleRect()
  • wheelEvent()
  • widget()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qdom.h Include File

qdom.h

This is the verbatim text of the qdom.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QDomDocument and related classes.
**
** Created : 000518
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the xml module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDOM_H
#define QDOM_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#if !defined(QT_MODULE_XML) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_XML )
#define QM_EXPORT_DOM
#else
#define QM_EXPORT_DOM Q_EXPORT
#endif

#ifndef QT_NO_DOM

class QIODevice;
class QTextStream;

class QDomDocumentPrivate;
class QDomDocumentTypePrivate;
class QDomDocumentFragmentPrivate;
class QDomNodePrivate;
class QDomNodeListPrivate;
class QDomImplementationPrivate;
class QDomElementPrivate;
class QDomNotationPrivate;
class QDomEntityPrivate;
class QDomEntityReferencePrivate;
class QDomProcessingInstructionPrivate;
class QDomAttrPrivate;
class QDomCharacterDataPrivate;
class QDomTextPrivate;
class QDomCommentPrivate;
class QDomCDATASectionPrivate;
class QDomNamedNodeMapPrivate;
class QDomImplementationPrivate;

class QDomNodeList;
class QDomElement;
class QDomText;
class QDomComment;
class QDomCDATASection;
class QDomProcessingInstruction;
class QDomAttr;
class QDomEntityReference;
class QDomDocument;
class QDomNamedNodeMap;
class QDomDocument;
class QDomDocumentFragment;
class QDomDocumentType;
class QDomImplementation;
class QDomNode;
class QDomEntity;
class QDomNotation;
class QDomCharacterData;

class QM_EXPORT_DOM QDomImplementation
{
public:
    QDomImplementation();
    QDomImplementation( const QDomImplementation& );
    virtual ~QDomImplementation();
    QDomImplementation& operator= ( const QDomImplementation& );
    bool operator== ( const QDomImplementation& ) const;
    bool operator!= ( const QDomImplementation& ) const;

    // functions
    virtual bool hasFeature( const QString& feature, const QString& version );
    virtual QDomDocumentType createDocumentType( const QString& qName, const QString& publicId, const QString& systemId );
    virtual QDomDocument createDocument( const QString& nsURI, const QString& qName, const QDomDocumentType& doctype );

    // Qt extension
    bool isNull();

private:
    QDomImplementationPrivate* impl;
    QDomImplementation( QDomImplementationPrivate* );

    friend class QDomDocument;
};

class QM_EXPORT_DOM QDomNode
{
public:
    enum NodeType {
    ElementNode               = 1,
    AttributeNode             = 2,
    TextNode                  = 3,
    CDATASectionNode          = 4,
    EntityReferenceNode       = 5,
    EntityNode                = 6,
    ProcessingInstructionNode = 7,
    CommentNode               = 8,
    DocumentNode              = 9,
    DocumentTypeNode          = 10,
    DocumentFragmentNode      = 11,
    NotationNode              = 12,
    BaseNode                  = 21,// this is not in the standard
    CharacterDataNode         = 22 // this is not in the standard
    };

    QDomNode();
    QDomNode( const QDomNode& );
    QDomNode& operator= ( const QDomNode& );
    bool operator== ( const QDomNode& ) const;
    bool operator!= ( const QDomNode& ) const;
    virtual ~QDomNode();

    // DOM functions
    virtual QDomNode insertBefore( const QDomNode& newChild, const QDomNode& refChild );
    virtual QDomNode insertAfter( const QDomNode& newChild, const QDomNode& refChild );
    virtual QDomNode replaceChild( const QDomNode& newChild, const QDomNode& oldChild );
    virtual QDomNode removeChild( const QDomNode& oldChild );
    virtual QDomNode appendChild( const QDomNode& newChild );
    virtual bool hasChildNodes() const;
    virtual QDomNode cloneNode( bool deep = TRUE ) const;
    virtual void normalize();
    virtual bool isSupported( const QString& feature, const QString& version ) const;

    // DOM read only attributes
    virtual QString nodeName() const;
    virtual QDomNode::NodeType nodeType() const;
    virtual QDomNode         parentNode() const;
    virtual QDomNodeList     childNodes() const;
    virtual QDomNode         firstChild() const;
    virtual QDomNode         lastChild() const;
    virtual QDomNode         previousSibling() const;
    virtual QDomNode         nextSibling() const;
    virtual QDomNamedNodeMap attributes() const;
    virtual QDomDocument     ownerDocument() const;
    virtual QString namespaceURI() const;
    virtual QString localName() const;
    virtual bool hasAttributes() const;

    // DOM attributes
    virtual QString nodeValue() const;
    virtual void setNodeValue( const QString& );
    virtual QString prefix() const;
    virtual void setPrefix( const QString& pre );

    // Qt extensions
    virtual bool isAttr() const;
    virtual bool isCDATASection() const;
    virtual bool isDocumentFragment() const;
    virtual bool isDocument() const;
    virtual bool isDocumentType() const;
    virtual bool isElement() const;
    virtual bool isEntityReference() const;
    virtual bool isText() const;
    virtual bool isEntity() const;
    virtual bool isNotation() const;
    virtual bool isProcessingInstruction() const;
    virtual bool isCharacterData() const;
    virtual bool isComment() const;

    /**
     * Shortcut to avoid dealing with QDomNodeList
     * all the time.
     */
    QDomNode namedItem( const QString& name ) const;

    bool isNull() const;
    void clear();

    QDomAttr toAttr();
    QDomCDATASection toCDATASection();
    QDomDocumentFragment toDocumentFragment();
    QDomDocument toDocument();
    QDomDocumentType toDocumentType();
    QDomElement toElement();
    QDomEntityReference toEntityReference();
    QDomText toText();
    QDomEntity toEntity();
    QDomNotation toNotation();
    QDomProcessingInstruction toProcessingInstruction();
    QDomCharacterData toCharacterData();
    QDomComment toComment();

    void save( QTextStream&, int ) const;

protected:
    QDomNodePrivate* impl;
    QDomNode( QDomNodePrivate* );

private:
    friend class QDomDocument;
    friend class QDomDocumentType;
    friend class QDomNodeList;
    friend class QDomNamedNodeMap;
};

class QM_EXPORT_DOM QDomNodeList
{
public:
    QDomNodeList();
    QDomNodeList( const QDomNodeList& );
    QDomNodeList& operator= ( const QDomNodeList& );
    bool operator== ( const QDomNodeList& ) const;
    bool operator!= ( const QDomNodeList& ) const;
    virtual ~QDomNodeList();

    // DOM functions
    virtual QDomNode item( int index ) const;

    // DOM read only attributes
    virtual uint length() const;
    uint count() const { return length(); } // Qt API consitancy

private:
    QDomNodeListPrivate* impl;
    QDomNodeList( QDomNodeListPrivate* );

    friend class QDomNode;
    friend class QDomElement;
    friend class QDomDocument;
};

class QM_EXPORT_DOM QDomDocumentType : public QDomNode
{
public:
    QDomDocumentType();
    QDomDocumentType( const QDomDocumentType& x );
    QDomDocumentType& operator= ( const QDomDocumentType& );
    ~QDomDocumentType();

    // DOM read only attributes
    virtual QString name() const;
    virtual QDomNamedNodeMap entities() const;
    virtual QDomNamedNodeMap notations() const;
    virtual QString publicId() const;
    virtual QString systemId() const;
    virtual QString internalSubset() const;

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isDocumentType() const;

private:
    QDomDocumentType( QDomDocumentTypePrivate* );

    friend class QDomImplementation;
    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomDocument : public QDomNode
{
public:
    QDomDocument();
    QDomDocument( const QString& name );
    QDomDocument( const QDomDocumentType& doctype );
    QDomDocument( const QDomDocument& x );
    QDomDocument& operator= ( const QDomDocument& );
    ~QDomDocument();

    // DOM functions
    QDomElement createElement( const QString& tagName );
    QDomDocumentFragment createDocumentFragment();
    QDomText createTextNode( const QString& data );
    QDomComment createComment( const QString& data );
    QDomCDATASection createCDATASection( const QString& data );
    QDomProcessingInstruction createProcessingInstruction( const QString& target, const QString& data );
    QDomAttr createAttribute( const QString& name );
    QDomEntityReference createEntityReference( const QString& name );
    QDomNodeList elementsByTagName( const QString& tagname ) const;
    QDomNode importNode( const QDomNode& importedNode, bool deep );
    QDomElement createElementNS( const QString& nsURI, const QString& qName );
    QDomAttr createAttributeNS( const QString& nsURI, const QString& qName );
    QDomNodeList elementsByTagNameNS( const QString& nsURI, const QString& localName );
    QDomElement elementById( const QString& elementId );

    // DOM read only attributes
    QDomDocumentType doctype() const;
    QDomImplementation implementation() const;
    QDomElement documentElement() const;

    // Qt extensions
    bool setContent( const QCString& text, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( const QByteArray& text, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( const QString& text, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( QIODevice* dev, bool namespaceProcessing, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( const QCString& text, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0 );
    bool setContent( const QByteArray& text, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( const QString& text, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );
    bool setContent( QIODevice* dev, QString *errorMsg=0, int *errorLine=0, int *errorColumn=0  );

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isDocument() const;

    // Qt extensions
    QString toString() const;
    QCString toCString() const;

private:
    QDomDocument( QDomDocumentPrivate* );

    friend class QDomNode;
};

class QM_EXPORT_DOM QDomNamedNodeMap
{
public:
    QDomNamedNodeMap();
    QDomNamedNodeMap( const QDomNamedNodeMap& );
    QDomNamedNodeMap& operator= ( const QDomNamedNodeMap& );
    bool operator== ( const QDomNamedNodeMap& ) const;
    bool operator!= ( const QDomNamedNodeMap& ) const;
    ~QDomNamedNodeMap();

    // DOM functions
    QDomNode namedItem( const QString& name ) const;
    QDomNode setNamedItem( const QDomNode& newNode );
    QDomNode removeNamedItem( const QString& name );
    QDomNode item( int index ) const;
    QDomNode namedItemNS( const QString& nsURI, const QString& localName ) const;
    QDomNode setNamedItemNS( const QDomNode& newNode );
    QDomNode removeNamedItemNS( const QString& nsURI, const QString& localName );

    // DOM read only attributes
    uint length() const;
    uint count() const { return length(); } // Qt API consitancy

    // Qt extension
    bool contains( const QString& name ) const;

private:
    QDomNamedNodeMapPrivate* impl;
    QDomNamedNodeMap( QDomNamedNodeMapPrivate* );

    friend class QDomNode;
    friend class QDomDocumentType;
    friend class QDomElement;
};

class QM_EXPORT_DOM QDomDocumentFragment : public QDomNode
{
public:
    QDomDocumentFragment();
    QDomDocumentFragment( const QDomDocumentFragment& x );
    QDomDocumentFragment& operator= ( const QDomDocumentFragment& );
    ~QDomDocumentFragment();

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isDocumentFragment() const;

private:
    QDomDocumentFragment( QDomDocumentFragmentPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomCharacterData : public QDomNode
{
public:
    QDomCharacterData();
    QDomCharacterData( const QDomCharacterData& x );
    QDomCharacterData& operator= ( const QDomCharacterData& );
    ~QDomCharacterData();

    // DOM functions
    virtual QString substringData( unsigned long offset, unsigned long count );
    virtual void appendData( const QString& arg );
    virtual void insertData( unsigned long offset, const QString& arg );
    virtual void deleteData( unsigned long offset, unsigned long count );
    virtual void replaceData( unsigned long offset, unsigned long count, const QString& arg );

    // DOM read only attributes
    virtual uint length() const;

    // DOM attributes
    virtual QString data() const;
    virtual void setData( const QString& );

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isCharacterData() const;

private:
    QDomCharacterData( QDomCharacterDataPrivate* );

    friend class QDomDocument;
    friend class QDomText;
    friend class QDomComment;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomAttr : public QDomNode
{
public:
    QDomAttr();
    QDomAttr( const QDomAttr& x );
    QDomAttr& operator= ( const QDomAttr& );
    ~QDomAttr();

    // DOM read only attributes
    virtual QString name() const;
    virtual bool specified() const;
    virtual QDomElement ownerElement() const;

    // DOM attributes
    virtual QString value() const;
    virtual void setValue( const QString& );

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isAttr() const;

private:
    QDomAttr( QDomAttrPrivate* );

    friend class QDomDocument;
    friend class QDomElement;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomElement : public QDomNode
{
public:
    QDomElement();
    QDomElement( const QDomElement& x );
    QDomElement& operator= ( const QDomElement& );
    ~QDomElement();

    // DOM functions
    QString attribute( const QString& name, const QString& defValue = QString::null ) const;
    void setAttribute( const QString& name, const QString& value );
    void setAttribute( const QString& name, int value );
    void setAttribute( const QString& name, uint value );
    void setAttribute( const QString& name, double value );
    void removeAttribute( const QString& name );
    QDomAttr attributeNode( const QString& name);
    QDomAttr setAttributeNode( const QDomAttr& newAttr );
    QDomAttr removeAttributeNode( const QDomAttr& oldAttr );
    virtual QDomNodeList elementsByTagName( const QString& tagname ) const;
    bool hasAttribute( const QString& name ) const;

    QString attributeNS( const QString nsURI, const QString& localName, const QString& defValue ) const;
    void setAttributeNS( const QString nsURI, const QString& qName, const QString& value );
    void setAttributeNS( const QString nsURI, const QString& qName, int value );
    void setAttributeNS( const QString nsURI, const QString& qName, uint value );
    void setAttributeNS( const QString nsURI, const QString& qName, double value );
    void removeAttributeNS( const QString& nsURI, const QString& localName );
    QDomAttr attributeNodeNS( const QString& nsURI, const QString& localName );
    QDomAttr setAttributeNodeNS( const QDomAttr& newAttr );
    virtual QDomNodeList elementsByTagNameNS( const QString& nsURI, const QString& localName ) const;
    bool hasAttributeNS( const QString& nsURI, const QString& localName ) const;

    // DOM read only attributes
    QString tagName() const;
    void setTagName( const QString& name ); // Qt extension

    // Reimplemented from QDomNode
    QDomNamedNodeMap attributes() const;
    QDomNode::NodeType nodeType() const;
    bool isElement() const;

    QString text() const;

private:
    QDomElement( QDomElementPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
    friend class QDomAttr;
};

class QM_EXPORT_DOM QDomText : public QDomCharacterData
{
public:
    QDomText();
    QDomText( const QDomText& x );
    QDomText& operator= ( const QDomText& );
    ~QDomText();

    // DOM functions
    QDomText splitText( int offset );

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isText() const;

private:
    QDomText( QDomTextPrivate* );

    friend class QDomCDATASection;
    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomComment : public QDomCharacterData
{
public:
    QDomComment();
    QDomComment( const QDomComment& x );
    QDomComment& operator= ( const QDomComment& );
    ~QDomComment();

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isComment() const;

private:
    QDomComment( QDomCommentPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomCDATASection : public QDomText
{
public:
    QDomCDATASection();
    QDomCDATASection( const QDomCDATASection& x );
    QDomCDATASection& operator= ( const QDomCDATASection& );
    ~QDomCDATASection();

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isCDATASection() const;

private:
    QDomCDATASection( QDomCDATASectionPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomNotation : public QDomNode
{
public:
    QDomNotation();
    QDomNotation( const QDomNotation& x );
    QDomNotation& operator= ( const QDomNotation& );
    ~QDomNotation();

    // DOM read only attributes
    QString publicId() const;
    QString systemId() const;

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isNotation() const;

private:
    QDomNotation( QDomNotationPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomEntity : public QDomNode
{
public:
    QDomEntity();
    QDomEntity( const QDomEntity& x );
    QDomEntity& operator= ( const QDomEntity& );
    ~QDomEntity();

    // DOM read only attributes
    virtual QString publicId() const;
    virtual QString systemId() const;
    virtual QString notationName() const;

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isEntity() const;

private:
    QDomEntity( QDomEntityPrivate* );

    friend class QDomNode;
};

class QM_EXPORT_DOM QDomEntityReference : public QDomNode
{
public:
    QDomEntityReference();
    QDomEntityReference( const QDomEntityReference& x );
    QDomEntityReference& operator= ( const QDomEntityReference& );
    ~QDomEntityReference();

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isEntityReference() const;

private:
    QDomEntityReference( QDomEntityReferencePrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

class QM_EXPORT_DOM QDomProcessingInstruction : public QDomNode
{
public:
    QDomProcessingInstruction();
    QDomProcessingInstruction( const QDomProcessingInstruction& x );
    QDomProcessingInstruction& operator= ( const QDomProcessingInstruction& );
    ~QDomProcessingInstruction();

    // DOM read only attributes
    virtual QString target() const;

    // DOM attributes
    virtual QString data() const;
    virtual void setData( const QString& d );

    // Reimplemented from QDomNode
    QDomNode::NodeType nodeType() const;
    bool isProcessingInstruction() const;

private:
    QDomProcessingInstruction( QDomProcessingInstructionPrivate* );

    friend class QDomDocument;
    friend class QDomNode;
};

QM_EXPORT_DOM QTextStream& operator<<( QTextStream&, const QDomNode& );

#endif //QT_NO_DOM
#endif // QDOM_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDomAttr Class

QDomAttr Class Reference
[XML module]

The QDomAttr class represents one attribute of a QDomElement. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomAttr ()
  • QDomAttr ( const QDomAttr & x )
  • QDomAttr & operator= ( const QDomAttr & x )
  • ~QDomAttr ()
  • virtual QString name () const
  • virtual bool specified () const
  • virtual QDomElement ownerElement () const
  • virtual QString value () const
  • virtual void setValue ( const QString & v )
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isAttr () const

Detailed Description

The QDomAttr class represents one attribute of a QDomElement.

For example, the following piece of XML gives an element with no children, but two attributes:

  <link href="http://www.trolltech.com" color="red" />

One can use the attributes of an element with code like this:

  QDomElement e = //...
  //...
  QDomAttr a = e.attributeNode( "href" );
  cout << a.value() << endl // gives "http://www.trolltech.com"
  a.setValue( "http://doc.trolltech.com" ); // change the node's attribute
  QDomAttr a2 = e.attributeNode( "href" );
  cout << a2.value() << endl // gives "http://doc.trolltech.com"

This example also shows that changing an attribute received from an element changes the attribute of the element. If you do not want to change the value of the element's attribute you have to use cloneNode() to get an independent copy of the attribute.

QDomAttr can return the name() and value() of an attribute. An attribute's value is set with setValue(). If specified returns TRUE the value was either set in the document or set with setValue(); otherwise the value hasn't been set. The node this attribute is attached to (if any) is returned by ownerElement().

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomAttr::QDomAttr ()

Constructs an empty attribute.

QDomAttr::QDomAttr ( const QDomAttr & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomAttr::~QDomAttr ()

Destroys the object and frees its resources.

bool QDomAttr::isAttr () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QString QDomAttr::name () const [virtual]

Returns the name of the attribute.

QDomNode::NodeType QDomAttr::nodeType () const [virtual]

Returns AttributeNode.

Reimplemented from QDomNode.

QDomAttr & QDomAttr::operator= ( const QDomAttr & x )

Assigns x to this DOM attribute.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomElement QDomAttr::ownerElement () const [virtual]

Returns the element node, this attribute is attached to. If this attribute is not attached to any element, a null element node is returned (i.e. a node for which QDomNode::isNull() returns TRUE).

void QDomAttr::setValue ( const QString & v ) [virtual]

Sets the value of the attribute to v.

See also value().

bool QDomAttr::specified () const [virtual]

Returns TRUE if the attribute has either been expicitly specified in the XML document or was set by the user with setValue(). Returns FALSE if the value hasn't been specified or set.

See also setValue().

QString QDomAttr::value () const [virtual]

Returns the value of the attribute. Returns a null string if the attribute has not been specified.

See also specified() and setValue().

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


QDomAttr Member List

Complete Member List for QDomAttr

This is the complete list of member functions for QDomAttr, including inherited members.

  • QDomAttr()
  • ~QDomAttr()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • name()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • ownerElement()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • setValue()
  • specified()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()
  • value()


QDomCDATASection Class

QDomCDATASection Class Reference
[XML module]

The QDomCDATASection class represents an XML CDATA section. More...

#include <qdom.h>

Inherits QDomText.

List of all member functions.

Public Members

  • QDomCDATASection ()
  • QDomCDATASection ( const QDomCDATASection & x )
  • QDomCDATASection & operator= ( const QDomCDATASection & x )
  • ~QDomCDATASection ()
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isCDATASection () const

Detailed Description

The QDomCDATASection class represents an XML CDATA section.

CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. The only delimiter that is recognized in a CDATA section is the "]]>" string that terminates the CDATA section. CDATA sections cannot be nested. Their primary purpose is for including material such as XML fragments, without needing to escape all the delimiters.

Adjacent QDomCDATASection nodes are not merged by the QDomNode::normalize() function.

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomCDATASection::QDomCDATASection ()

Constructs an empty CDATA section. To create a CDATA section with content, use the QDomDocument::createCDATASection() function.

QDomCDATASection::QDomCDATASection ( const QDomCDATASection & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomCDATASection::~QDomCDATASection ()

Destroys the object and frees its resources.

bool QDomCDATASection::isCDATASection () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomCDATASection::nodeType () const [virtual]

Returns CDATASection.

Reimplemented from QDomText.

QDomCDATASection & QDomCDATASection::operator= ( const QDomCDATASection & x )

Assigns x to this CDATA section.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

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


QDomCDATASection Member List

Complete Member List for QDomCDATASection

This is the complete list of member functions for QDomCDATASection, including inherited members.

  • QDomCDATASection()
  • ~QDomCDATASection()
  • appendChild()
  • appendData()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • data()
  • deleteData()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • insertData()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • length()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • replaceData()
  • save()
  • setData()
  • setNodeValue()
  • setPrefix()
  • splitText()
  • substringData()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomCharacterData Class

QDomCharacterData Class Reference
[XML module]

The QDomCharacterData class represents a generic string in the DOM. More...

#include <qdom.h>

Inherits QDomNode.

Inherited by QDomText and QDomComment.

List of all member functions.

Public Members

  • QDomCharacterData ()
  • QDomCharacterData ( const QDomCharacterData & x )
  • QDomCharacterData & operator= ( const QDomCharacterData & x )
  • ~QDomCharacterData ()
  • virtual QString substringData ( unsigned long offset, unsigned long count )
  • virtual void appendData ( const QString & arg )
  • virtual void insertData ( unsigned long offset, const QString & arg )
  • virtual void deleteData ( unsigned long offset, unsigned long count )
  • virtual void replaceData ( unsigned long offset, unsigned long count, const QString & arg )
  • virtual uint length () const
  • virtual QString data () const
  • virtual void setData ( const QString & v )
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isCharacterData () const

Detailed Description

The QDomCharacterData class represents a generic string in the DOM.

Character data as used in XML specifies a generic data string. More specialized versions of this class are QDomText, QDomComment and QDomCDATASection.

The data string is set with setData() and retrieved with data(). You can retrieve a portion of the data string using substringData(). Extra data can be appended with appendData(), or inserted with insertData(). Portions of the data string can be deleted with deleteData() or replaced with replaceData(). The length of the data string is returned by length().

The node type of the node containing this character data is returned by nodeType().

See also QDomText, QDomComment, QDomCDATASection and XML.

Member Function Documentation

QDomCharacterData::QDomCharacterData ()

Constructs an empty character data object.

QDomCharacterData::QDomCharacterData ( const QDomCharacterData & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomCharacterData::~QDomCharacterData ()

Destroys the object and frees its resources.

void QDomCharacterData::appendData ( const QString & arg ) [virtual]

Appends the string arg, to the stored string.

QString QDomCharacterData::data () const [virtual]

Returns the string stored in this object.

If the node is a null node, it will return a null string.

void QDomCharacterData::deleteData ( unsigned long offset, unsigned long count ) [virtual]

Deletes a substring of length count from position offset.

void QDomCharacterData::insertData ( unsigned long offset, const QString & arg ) [virtual]

Inserts the string arg into the stored string at position offset.

bool QDomCharacterData::isCharacterData () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

uint QDomCharacterData::length () const [virtual]

Returns the length of the stored string.

QDomNode::NodeType QDomCharacterData::nodeType () const [virtual]

Returns the type of node this object refers to (i.e. TextNode, CDATASectionNode, CommentNode or CharacterDataNode). For a null node CharacterDataNode is returned.

Reimplemented from QDomNode.

Reimplemented in QDomText and QDomComment.

QDomCharacterData & QDomCharacterData::operator= ( const QDomCharacterData & x )

Assigns x to this character data.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

void QDomCharacterData::replaceData ( unsigned long offset, unsigned long count, const QString & arg ) [virtual]

Replaces the substring of length count starting at position offset with the string arg.

void QDomCharacterData::setData ( const QString & v ) [virtual]

Sets the string of this object to v.

QString QDomCharacterData::substringData ( unsigned long offset, unsigned long count ) [virtual]

Returns the substring of length count from position offset.

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


QDomCharacterData Member List

Complete Member List for QDomCharacterData

This is the complete list of member functions for QDomCharacterData, including inherited members.

  • QDomCharacterData()
  • ~QDomCharacterData()
  • appendChild()
  • appendData()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • data()
  • deleteData()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • insertData()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • length()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • replaceData()
  • save()
  • setData()
  • setNodeValue()
  • setPrefix()
  • substringData()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomComment Class

QDomComment Class Reference
[XML module]

The QDomComment class represents an XML comment. More...

#include <qdom.h>

Inherits QDomCharacterData.

List of all member functions.

Public Members

  • QDomComment ()
  • QDomComment ( const QDomComment & x )
  • QDomComment & operator= ( const QDomComment & x )
  • ~QDomComment ()
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isComment () const

Detailed Description

The QDomComment class represents an XML comment.

A comment in the parsed XML such as this:

  <!-- this is a comment -->
is represented by QDomComment objects in the parsed Dom tree.

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomComment::QDomComment ()

Constructs an empty comment. To construct a comment with content, use the QDomDocument::createComment() function.

QDomComment::QDomComment ( const QDomComment & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomComment::~QDomComment ()

Destroys the object and frees its resources.

bool QDomComment::isComment () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomComment::nodeType () const [virtual]

Returns CommentNode.

Reimplemented from QDomCharacterData.

QDomComment & QDomComment::operator= ( const QDomComment & x )

Assigns x to this DOM comment.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

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


QDomComment Member List

Complete Member List for QDomComment

This is the complete list of member functions for QDomComment, including inherited members.

  • QDomComment()
  • ~QDomComment()
  • appendChild()
  • appendData()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • data()
  • deleteData()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • insertData()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • length()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • replaceData()
  • save()
  • setData()
  • setNodeValue()
  • setPrefix()
  • substringData()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomDocument Class

QDomDocument Class Reference
[XML module]

The QDomDocument class represents an XML document. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomDocument ()
  • QDomDocument ( const QString & name )
  • QDomDocument ( const QDomDocumentType & doctype )
  • QDomDocument ( const QDomDocument & x )
  • QDomDocument & operator= ( const QDomDocument & x )
  • ~QDomDocument ()
  • QDomElement createElement ( const QString & tagName )
  • QDomDocumentFragment createDocumentFragment ()
  • QDomText createTextNode ( const QString & value )
  • QDomComment createComment ( const QString & value )
  • QDomCDATASection createCDATASection ( const QString & value )
  • QDomProcessingInstruction createProcessingInstruction ( const QString & target, const QString & data )
  • QDomAttr createAttribute ( const QString & name )
  • QDomEntityReference createEntityReference ( const QString & name )
  • QDomNodeList elementsByTagName ( const QString & tagname ) const
  • QDomNode importNode ( const QDomNode & importedNode, bool deep )
  • QDomElement createElementNS ( const QString & nsURI, const QString & qName )
  • QDomAttr createAttributeNS ( const QString & nsURI, const QString & qName )
  • QDomNodeList elementsByTagNameNS ( const QString & nsURI, const QString & localName )
  • QDomElement elementById ( const QString & elementId )
  • QDomDocumentType doctype () const
  • QDomImplementation implementation () const
  • QDomElement documentElement () const
  • bool setContent ( const QCString & buffer, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( const QByteArray & buffer, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( const QString & text, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( QIODevice * dev, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( const QCString & buffer, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( const QByteArray & buffer, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( const QString & text, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • bool setContent ( QIODevice * dev, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isDocument () const
  • QString toString () const
  • QCString toCString () const

Detailed Description

The QDomDocument class represents an XML document.

The QDomDocument class represents the entire XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.

Since elements, text nodes, comments, processing instructions, etc. cannot exist outside the context of a document, the document class also contains the factory functions needed to create these objects. The node objects created have an ownerDocument() function which associates them with the document within whose context they were created. The DOM classes that will be used most often are QDomNode, QDomDocument, QDomElement and QDomText.

The parsed XML is represented internally by a tree of objects that can be accessed using the various QDom classes. All QDom classes only reference objects in the internal tree. The internal objects in the DOM tree will get deleted, once the last QDom object referencing them and the QDomDocument itself are deleted.

Creation of elements, text nodes, etc. is done via the various factory functions provided in this class. Using the default constructors of the QDom classes will only result in empty objects, that cannot be manipulated or inserted into the Document.

The QDomDocument class has several functions for creating document data, for example, createElement(), createTextNode(), createComment(), createCDATASection(), createProcessingInstruction(), createAttribute() and createEntityReference(). Some of these functions have versions that support namespaces, i.e. createElementNS() and createAttributeNS(). The createDocumentFragment() function is used to hold parts of the document, e.g. for complex documents.

The entire content of the document is set with setContent(). This function parses the string it is passed as an XML document and creates the DOM tree that represents the document. The root element is available using documentElement(). The textual representation of the document can be obtained using toString().

It is possible to insert a node from another document into the document using importNode().

You can obtain a list of all the elements that have a particular tag with elementsByTagName() or with elementsByTagNameNS().

The QDom classes are typically used as follows:

  QDomDocument doc( "mydocument" );
  QFile f( "mydocument.xml" );
  if ( !f.open( IO_ReadOnly ) )
      return;
  if ( !doc.setContent( &f ) ) {
      f.close();
      return;
  }
  f.close();

  // print out the element names of all elements that are direct children
  // of the outermost element.
  QDomElement docElem = doc.documentElement();

  QDomNode n = docElem.firstChild();
  while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {
          cout << e.tagName() << endl; // the node really is an element.
      }
      n = n.nextSibling();
  }

  // Here we append a new element to the end of the document
  QDomElement elem = doc.createElement( "img" );
  elem.setAttribute( "src", "myimage.png" );
  docElem.appendChild( elem );

Once doc and elem go out of scope, the whole internal tree representing the XML document will get deleted.

To create a document using DOM use code like this:

    QDomDocument doc( "MyML" );
    QDomElement root = doc.createElement( "MyML" );
    doc.appendChild( root );

    QDomElement tag = doc.createElement( "Greeting" );
    root.appendChild( tag );

    QDomText t = doc.createTextNode( "Hello World" );
    tag.appendChild( t );

    QString xml = doc.toString();

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomDocument::QDomDocument ()

Constructs an empty document.

QDomDocument::QDomDocument ( const QString & name )

Creates a document and sets the name of the document type to name.

QDomDocument::QDomDocument ( const QDomDocumentType & doctype )

Creates a document with the document type doctype.

See also QDomImplementation::createDocumentType().

QDomDocument::QDomDocument ( const QDomDocument & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomDocument::~QDomDocument ()

Destroys the object and frees its resources.

QDomAttr QDomDocument::createAttribute ( const QString & name )

Creates a new attribute called name that can be inserted into an element, e.g. using QDomElement::setAttributeNode().

See also createAttributeNS().

QDomAttr QDomDocument::createAttributeNS ( const QString & nsURI, const QString & qName )

Creates a new attribute with namespace support that can be inserted into an element. The name of the attribute is qName and the namespace URI is nsURI. This function also sets QDomNode::prefix() and QDomNode::localName() to appropriate values (depending on qName).

See also createAttribute().

QDomCDATASection QDomDocument::createCDATASection ( const QString & value )

Creates a new CDATA section for the string value that can be inserted into the document, e.g. using QDomNode::appendChild().

See also QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomComment QDomDocument::createComment ( const QString & value )

Creates a new comment for the string value that can be inserted into the document, e.g. using QDomNode::appendChild().

See also QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomDocumentFragment QDomDocument::createDocumentFragment ()

Creates a new document fragment, that can be used to hold parts of the document, e.g. when doing complex manipulations of the document tree.

QDomElement QDomDocument::createElement ( const QString & tagName )

Creates a new element called tagName that can be inserted into the DOM tree, e.g. using QDomNode::appendChild().

See also createElementNS(), QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomElement QDomDocument::createElementNS ( const QString & nsURI, const QString & qName )

Creates a new element with namespace support that can be inserted into the DOM tree. The name of the element is qName and the namespace URI is nsURI. This function also sets QDomNode::prefix() and QDomNode::localName() to appropriate values (depending on qName).

See also createElement().

QDomEntityReference QDomDocument::createEntityReference ( const QString & name )

Creates a new entity reference called name that can be inserted into the document, e.g. using QDomNode::appendChild().

See also QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomProcessingInstruction QDomDocument::createProcessingInstruction ( const QString & target, const QString & data )

Creates a new processing instruction that can be inserted into the document, e.g. using QDomNode::appendChild(). This function sets the target for the processing instruction to target and the data to data.

See also QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomText QDomDocument::createTextNode ( const QString & value )

Creates a text node for the string value that can be inserted into the document tree, e.g. using QDomNode::appendChild().

See also QDomNode::appendChild(), QDomNode::insertBefore() and QDomNode::insertAfter().

QDomDocumentType QDomDocument::doctype () const

Returns the document type of this document.

QDomElement QDomDocument::documentElement () const

Returns the root element of the document.

QDomElement QDomDocument::elementById ( const QString & elementId )

Returns the element whose ID is equal to elementId. If no element with the ID was found, this function returns a null element.

Since the actual version of the QDomClasses does not know which attributes are element IDs, this function returns always a null element. This may change in a future version.

QDomNodeList QDomDocument::elementsByTagName ( const QString & tagname ) const

Returns a QDomNodeList, that contains all the elements in the document with the name tagname. The order of the node list is the order they are encountered in a preorder traversal of the element tree.

See also elementsByTagNameNS() and QDomElement::elementsByTagName().

QDomNodeList QDomDocument::elementsByTagNameNS ( const QString & nsURI, const QString & localName )

Returns a QDomNodeList that contains all the elements in the document with the local name localName and a namespace URI of nsURI. The order of the node list, is the order they are encountered in a preorder traversal of the element tree.

See also elementsByTagName() and QDomElement::elementsByTagNameNS().

QDomImplementation QDomDocument::implementation () const

Returns a QDomImplementation object.

QDomNode QDomDocument::importNode ( const QDomNode & importedNode, bool deep )

Imports the node importedNode from another document to this document. importedNode remains in the original document; this function creates a copy of it that can be used within this document.

This function returns the imported node that belongs to this document. The returned node has no parent. It is not possible to import QDomDocument and QDomDocumentType nodes. In those cases this function returns a null node.

If deep is TRUE, this function imports not only the node importedNode but the whole subtree; if it is FALSE, only the importedNode is imported. The argument deep has no effect on QDomAttr and QDomEntityReference nodes, since the descendants of QDomAttr nodes are always imported and those of QDomEntityReference nodes are never imported.

The behavior of this function is slightly different depending on the node types:

  • QDomAttr - The owner element is set to 0 and the specified flag is set to TRUE on the generated attribute. The whole subtree of importedNode is always imported for attribute nodes - deep has no effect.
  • QDomDocument - Document nodes cannot be imported.
  • QDomDocumentFragment - If deep is TRUE, this function imports the whole document fragment, otherwise it only generates an empty document fragment.
  • QDomDocumentType - Document type nodes cannot be imported.
  • QDomElement - Attributes for which QDomAttr::specified() is TRUE are also imported, other attributes are not imported. If deep is TRUE, this function also imports the subtree of importedNode, otherwise it imports only the element node (and some attributes, see above).
  • QDomEntity - Entity nodes can be imported, but at the moment there is no way to use them since the document type is readonly in DOM level 2.
  • QDomEntityReference - Descendants of entity reference nodes are never imported - deep has no effect.
  • QDomNotation - Notation nodes can be imported, but at the moment there is no way to use them since the document type is readonly in DOM level 2.
  • QDomProcessingInstruction - The target and value of the processing instruction is copied to the new node.
  • QDomText, QDomCDATASection and QDomComment - The text is copied to the new node.

See also QDomElement::setAttribute(), QDomNode::insertBefore(), QDomNode::insertAfter(), QDomNode::replaceChild(), QDomNode::removeChild() and QDomNode::appendChild().

bool QDomDocument::isDocument () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomDocument::nodeType () const [virtual]

Returns DocumentNode.

Reimplemented from QDomNode.

QDomDocument & QDomDocument::operator= ( const QDomDocument & x )

Assigns x to this DOM document.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

bool QDomDocument::setContent ( const QByteArray & buffer, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

This function parses the XML document from the byte array buffer and sets it as the content of the document. It tries to detect the encoding of the document as required by the XML specification.

If namespaceProcessing is TRUE, the parser recognizes namespaces in the XML file and sets the prefix name, local name and namespace URI to appropriate values. If namespaceProcessing is FALSE, the parser does no namespace processing when it reads the XML file.

If a parse error occurs, the function returns FALSE; otherwise TRUE. If a parse error occurs the error message is placed in *errorMsg, the line number in *errorLine and the column number in *errorColumn. These error variables will only be populated if they are non-null.

If namespaceProcessing is TRUE, the function QDomNode::prefix() returns a string for all elements and attributes. It returns an empty string if the element or attribute has no prefix.

If namespaceProcessing is FALSE, the functions QDomNode::prefix(), QDomNode::localName() and QDomNode::namespaceURI() return a null string.

See also QDomNode::namespaceURI(), QDomNode::localName(), QDomNode::prefix(), QString::isNull() and QString::isEmpty().

bool QDomDocument::setContent ( const QCString & buffer, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the C string buffer.

Use this function with extreme care, since it does not try to detect the encoding, but rather assumes that the C string is in Utf8 encoding.

bool QDomDocument::setContent ( const QString & text, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the string text. Since text is already a unicode string, no encoding detection is done.

bool QDomDocument::setContent ( QIODevice * dev, bool namespaceProcessing, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the IO device dev.

bool QDomDocument::setContent ( const QCString & buffer, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the C string buffer.

Use this function with extreme care, since it does not try to detect the encoding, but rather assumes that the C string is in Utf8 encoding.

No namespace processing is done.

bool QDomDocument::setContent ( const QByteArray & buffer, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the byte array buffer.

No namespace processing is done.

bool QDomDocument::setContent ( const QString & text, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the string text. Since text is already a unicode string, no encoding detection is done.

No namespace processing is done.

bool QDomDocument::setContent ( QIODevice * dev, QString * errorMsg = 0, int * errorLine = 0, int * errorColumn = 0 )

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

This function reads the XML document from the IO device dev.

No namespace processing is done.

QCString QDomDocument::toCString () const

Converts the parsed document back to its textual representation and returns a QCString for that is encoded in UTF-8.

See also toString().

QString QDomDocument::toString () const

Converts the parsed document back to its textual representation.

See also toCString().

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


QDomDocument Member List

Complete Member List for QDomDocument

This is the complete list of member functions for QDomDocument, including inherited members.

  • QDomDocument()
  • ~QDomDocument()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • createAttribute()
  • createAttributeNS()
  • createCDATASection()
  • createComment()
  • createDocumentFragment()
  • createElement()
  • createElementNS()
  • createEntityReference()
  • createProcessingInstruction()
  • createTextNode()
  • doctype()
  • documentElement()
  • elementById()
  • elementsByTagName()
  • elementsByTagNameNS()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • implementation()
  • importNode()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setContent()
  • setNodeValue()
  • setPrefix()
  • toAttr()
  • toCDATASection()
  • toCString()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toString()
  • toText()


QDomDocumentFragment Class

QDomDocumentFragment Class Reference
[XML module]

The QDomDocumentFragment class is a tree of QDomNodes which is not usually a complete QDomDocument. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomDocumentFragment ()
  • QDomDocumentFragment ( const QDomDocumentFragment & x )
  • QDomDocumentFragment & operator= ( const QDomDocumentFragment & x )
  • ~QDomDocumentFragment ()
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isDocumentFragment () const

Detailed Description

The QDomDocumentFragment class is a tree of QDomNodes which is not usually a complete QDomDocument.

If you want to do complex tree operations it is useful to have a lightweight class to store nodes and their relations. QDomDocumentFragment stores a subtree of a document which does not necessarily represent a well-formed XML document.

QDomDocumentFragment is also useful if you want to group several nodes in a list and insert them all together as children of some node. In these cases QDomDocumentFragment can be used as a temporary container for this list of children.

The most important feature of QDomDocumentFragment is that it is treated in a special way by QDomNode::insertAfter(), QDomNode::insertBefore() and QDomNode::replaceChild(): instead of inserting the fragment itself, all the fragment's children are inserted.

See also XML.

Member Function Documentation

QDomDocumentFragment::QDomDocumentFragment ()

Constructs an empty document fragment.

QDomDocumentFragment::QDomDocumentFragment ( const QDomDocumentFragment & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomDocumentFragment::~QDomDocumentFragment ()

Destroys the object and frees its resources.

bool QDomDocumentFragment::isDocumentFragment () const [virtual]

This function reimplements QDomNode::isDocumentFragment().

See also nodeType() and QDomNode::toDocumentFragment().

Reimplemented from QDomNode.

QDomNode::NodeType QDomDocumentFragment::nodeType () const [virtual]

Returns DocumentFragment.

See also isDocumentFragment() and QDomNode::toDocumentFragment().

Reimplemented from QDomNode.

QDomDocumentFragment & QDomDocumentFragment::operator= ( const QDomDocumentFragment & x )

Assigns x to this DOM document fragment.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

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


QDomDocumentFragment Member List

Complete Member List for QDomDocumentFragment

This is the complete list of member functions for QDomDocumentFragment, including inherited members.

  • QDomDocumentFragment()
  • ~QDomDocumentFragment()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomDocumentType Class

QDomDocumentType Class Reference
[XML module]

The QDomDocumentType class is the representation of the DTD in the document tree. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomDocumentType ()
  • QDomDocumentType ( const QDomDocumentType & n )
  • QDomDocumentType & operator= ( const QDomDocumentType & n )
  • ~QDomDocumentType ()
  • virtual QString name () const
  • virtual QDomNamedNodeMap entities () const
  • virtual QDomNamedNodeMap notations () const
  • virtual QString publicId () const
  • virtual QString systemId () const
  • virtual QString internalSubset () const
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isDocumentType () const

Detailed Description

The QDomDocumentType class is the representation of the DTD in the document tree.

The QDomDocumentType class allows read-only access to some of the data structures in the DTD: it can return a map of all entities() and notations(). In addition the function name() returns the name of the document type as specified in the <!DOCTYPE name> tag. This class also provides the publicId(), systemId() and internalSubset() functions.

See also QDomDocument and XML.

Member Function Documentation

QDomDocumentType::QDomDocumentType ()

Creates an empty QDomDocumentType object.

QDomDocumentType::QDomDocumentType ( const QDomDocumentType & n )

Constructs a copy of n.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomDocumentType::~QDomDocumentType ()

Destroys the object and frees its resources.

QDomNamedNodeMap QDomDocumentType::entities () const [virtual]

Returns a map of all entities described in the DTD.

QString QDomDocumentType::internalSubset () const [virtual]

Returns the internal subset of the document type, if there is any. Otherwise this function returns QString::null.

See also publicId() and systemId().

bool QDomDocumentType::isDocumentType () const [virtual]

This function overloads QDomNode::isDocumentType().

See also nodeType() and QDomNode::toDocumentType().

Reimplemented from QDomNode.

QString QDomDocumentType::name () const [virtual]

Returns the name of the document type as specified in the <!DOCTYPE name> tag.

See also nodeName().

QDomNode::NodeType QDomDocumentType::nodeType () const [virtual]

Returns DocumentTypeNode.

See also isDocumentType() and QDomNode::toDocumentType().

Reimplemented from QDomNode.

QDomNamedNodeMap QDomDocumentType::notations () const [virtual]

Returns a map of all notations described in the DTD.

QDomDocumentType & QDomDocumentType::operator= ( const QDomDocumentType & n )

Assigns n to this document type.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QString QDomDocumentType::publicId () const [virtual]

Returns the public identifier of the external DTD subset, if there is any. Otherwise this function returns QString::null.

See also systemId(), internalSubset() and QDomImplementation::createDocumentType().

QString QDomDocumentType::systemId () const [virtual]

Returns the system identifier of the external DTD subset, if there is any. Otherwise this function returns QString::null.

See also publicId(), internalSubset() and QDomImplementation::createDocumentType().

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


QDomDocumentType Member List

Complete Member List for QDomDocumentType

This is the complete list of member functions for QDomDocumentType, including inherited members.

  • QDomDocumentType()
  • ~QDomDocumentType()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • entities()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • internalSubset()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • name()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • notations()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • publicId()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • systemId()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomElement Class

QDomElement Class Reference
[XML module]

The QDomElement class represents one element in the DOM tree. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomElement ()
  • QDomElement ( const QDomElement & x )
  • QDomElement & operator= ( const QDomElement & x )
  • ~QDomElement ()
  • QString attribute ( const QString & name, const QString & defValue = QString::null ) const
  • void setAttribute ( const QString & name, const QString & value )
  • void setAttribute ( const QString & name, int value )
  • void setAttribute ( const QString & name, uint value )
  • void setAttribute ( const QString & name, double value )
  • void removeAttribute ( const QString & name )
  • QDomAttr attributeNode ( const QString & name )
  • QDomAttr setAttributeNode ( const QDomAttr & newAttr )
  • QDomAttr removeAttributeNode ( const QDomAttr & oldAttr )
  • virtual QDomNodeList elementsByTagName ( const QString & tagname ) const
  • bool hasAttribute ( const QString & name ) const
  • QString attributeNS ( const QString nsURI, const QString & localName, const QString & defValue ) const
  • void setAttributeNS ( const QString nsURI, const QString & qName, const QString & value )
  • void setAttributeNS ( const QString nsURI, const QString & qName, int value )
  • void setAttributeNS ( const QString nsURI, const QString & qName, uint value )
  • void setAttributeNS ( const QString nsURI, const QString & qName, double value )
  • void removeAttributeNS ( const QString & nsURI, const QString & localName )
  • QDomAttr attributeNodeNS ( const QString & nsURI, const QString & localName )
  • QDomAttr setAttributeNodeNS ( const QDomAttr & newAttr )
  • virtual QDomNodeList elementsByTagNameNS ( const QString & nsURI, const QString & localName ) const
  • bool hasAttributeNS ( const QString & nsURI, const QString & localName ) const
  • QString tagName () const
  • void setTagName ( const QString & name )
  • virtual QDomNamedNodeMap attributes () const
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isElement () const
  • QString text () const

Detailed Description

The QDomElement class represents one element in the DOM tree.

Elements have a tagName() and zero or more attributes associated with them. The tag name can be changed with setTagName().

Attributes of the element are represented by QDomAttr objects, that can be queried using the attribute() and attributeNode() functions. You can set attributes with the setAttribute() and setAttributeNode() functions. Attributes can be removed with removeAttribute(). There are namespace-aware equivalents to these functions, i.e. setAttributeNS(), setAttributeNodeNS() and removeAttributeNS().

If you want to access the text of a node use text(), e.g.

    QDomElement e = //...
    //...
    QString s = e.text()
The text() function operates recursively to find the text (since not all elements contain text). If you want to find all the text in all of a node's children iterate over the children looking for QDomText nodes, e.g.
    QString text;
    QDomElement element = doc.documentElement();
    for( QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling() )
    {
             QDomText t = n.toText();
             if ( !t.isNull() )
                     text += t.data();
    }
Note that we attempt to convert each node to a text node and use text() rather than using firstChild().toText().data() or n.toText().data() directly on the node, because the node may not be a text element.

You can get a list of all the decendents of an element which have a specified tag name with elementsByTagName() or elementsByTagNameNS().

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomElement::QDomElement ()

Constructs an empty element. Use the QDomDocument::createElement() function to construct elements with content.

QDomElement::QDomElement ( const QDomElement & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomElement::~QDomElement ()

Destroys the object and frees its resources.

QString QDomElement::attribute ( const QString & name, const QString & defValue = QString::null ) const

Returns the attribute called name. If the attribute does not exist defValue is returned.

See also setAttribute(), attributeNode(), setAttributeNode() and attributeNS().

QString QDomElement::attributeNS ( const QString nsURI, const QString & localName, const QString & defValue ) const

Returns the attribute with the local name localName and the namespace URI nsURI. If the attribute does not exist defValue is returned.

See also setAttributeNS(), attributeNodeNS(), setAttributeNodeNS() and attribute().

QDomAttr QDomElement::attributeNode ( const QString & name )

Returns the QDomAttr object that corresponds to the attribute called name. If no such attribute exists a null object is returned.

See also setAttributeNode(), attribute(), setAttribute() and attributeNodeNS().

QDomAttr QDomElement::attributeNodeNS ( const QString & nsURI, const QString & localName )

Returns the QDomAttr object that corresponds to the attribute with the local name localName and the namespace URI nsURI. If no such attribute exists a null object is returned.

See also setAttributeNode(), attribute() and setAttribute().

QDomNamedNodeMap QDomElement::attributes () const [virtual]

Returns a QDomNamedNodeMap containing all this element's attributes.

See also attribute(), setAttribute(), attributeNode() and setAttributeNode().

Reimplemented from QDomNode.

QDomNodeList QDomElement::elementsByTagName ( const QString & tagname ) const [virtual]

Returns a QDomNodeList containing all descendant elements of this element called tagname. The order they are in the node list, is the order they are encountered in a preorder traversal of the element tree.

See also elementsByTagNameNS() and QDomDocument::elementsByTagName().

QDomNodeList QDomElement::elementsByTagNameNS ( const QString & nsURI, const QString & localName ) const [virtual]

Returns a QDomNodeList containing all the descendant elements of this element with the local name localName and the namespace URI nsURI. The order they are in the node list, is the order they are encountered in a preorder traversal of the element tree.

See also elementsByTagName() and QDomDocument::elementsByTagNameNS().

bool QDomElement::hasAttribute ( const QString & name ) const

Returns TRUE if this element has an attribute called name; otherwise returns FALSE.

bool QDomElement::hasAttributeNS ( const QString & nsURI, const QString & localName ) const

Returns TRUE if this element has an attribute with the local name localName and the namespace URI nsURI; otherwise returns FALSE.

bool QDomElement::isElement () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomElement::nodeType () const [virtual]

Returns ElementNode.

Reimplemented from QDomNode.

QDomElement & QDomElement::operator= ( const QDomElement & x )

Assigns x to this DOM element.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

void QDomElement::removeAttribute ( const QString & name )

Removes the attribute called name name from this element.

See also setAttribute(), attribute() and removeAttributeNS().

void QDomElement::removeAttributeNS ( const QString & nsURI, const QString & localName )

Removes the attribute with the local name localName and the namespace URI nsURI from this element.

See also setAttributeNS(), attributeNS() and removeAttribute().

QDomAttr QDomElement::removeAttributeNode ( const QDomAttr & oldAttr )

Removes the attribute oldAttr from the element and returns it.

See also attributeNode() and setAttributeNode().

void QDomElement::setAttribute ( const QString & name, const QString & value )

Adds an attribute called name name with value value. If an attribute with the same name exists, its value is replaced by value.

See also attribute(), setAttributeNode() and setAttributeNS().

void QDomElement::setAttribute ( const QString & name, int value )

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

void QDomElement::setAttribute ( const QString & name, uint value )

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

void QDomElement::setAttribute ( const QString & name, double value )

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

void QDomElement::setAttributeNS ( const QString nsURI, const QString & qName, const QString & value )

Adds an attribute with the qualified name qName and the namespace URI nsURI with the value value. If an attribute with the same local name and namespace URI exists, its prefix is replaced by the prefix of qName and its value is repaced by value.

Although qName is the qualified name, the local name is used to decide if an existing attribute's value should be replaced.

See also attributeNS(), setAttributeNodeNS() and setAttribute().

void QDomElement::setAttributeNS ( const QString nsURI, const QString & qName, int value )

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

void QDomElement::setAttributeNS ( const QString nsURI, const QString & qName, uint value )

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

void QDomElement::setAttributeNS ( const QString nsURI, const QString & qName, double value )

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

QDomAttr QDomElement::setAttributeNode ( const QDomAttr & newAttr )

Adds the attribute newAttr to this element.

If the element has another attribute that has the same name as newAttr, this function replaces that attribute and returns it; otherwise the function returns a null attribute.

See also attributeNode(), setAttribute() and setAttributeNodeNS().

QDomAttr QDomElement::setAttributeNodeNS ( const QDomAttr & newAttr )

Adds the attribute newAttr to this element.

If the element has another attribute that has the same local name and namespace URI as newAttr, this function replaces that attribute and returns it; otherwise the function returns a null attribute.

See also attributeNodeNS(), setAttributeNS() and setAttributeNode().

void QDomElement::setTagName ( const QString & name )

Sets the tag name of this element to name.

See also tagName().

QString QDomElement::tagName () const

Returns the tag name of this element. For an XML element like
  <img src="myimg.png">
the tagname would return "img".

See also setTagName().

QString QDomElement::text () const

Returns the text contained inside this element.

Example:

  <h1>Hello <b>Qt</b> <![CDATA[<xml is cool>]]></h1>

The function text() of the QDomElement for the <h1> tag, will return "Hello Qt <xml is cool>".

Comments are ignored by this function. It only evaluates QDomText and QDomCDATASection objects.

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


QDomElement Member List

Complete Member List for QDomElement

This is the complete list of member functions for QDomElement, including inherited members.

  • QDomElement()
  • ~QDomElement()
  • appendChild()
  • attribute()
  • attributeNS()
  • attributeNode()
  • attributeNodeNS()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • elementsByTagName()
  • elementsByTagNameNS()
  • firstChild()
  • hasAttribute()
  • hasAttributeNS()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeAttribute()
  • removeAttributeNS()
  • removeAttributeNode()
  • removeChild()
  • replaceChild()
  • save()
  • setAttribute()
  • setAttributeNS()
  • setAttributeNode()
  • setAttributeNodeNS()
  • setNodeValue()
  • setPrefix()
  • setTagName()
  • tagName()
  • text()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomEntity Class

QDomEntity Class Reference
[XML module]

The QDomEntity class represents an XML entity. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomEntity ()
  • QDomEntity ( const QDomEntity & x )
  • QDomEntity & operator= ( const QDomEntity & x )
  • ~QDomEntity ()
  • virtual QString publicId () const
  • virtual QString systemId () const
  • virtual QString notationName () const
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isEntity () const

Detailed Description

The QDomEntity class represents an XML entity.

This class represents an entity in an XML document, either parsed or unparsed. Note that this models the entity itself not the entity declaration.

DOM does not support editing entity nodes; if a user wants to make changes to the contents of an entity, every related QDomEntityReference node has to be replaced in the DOM tree by a clone of the entity's contents, and then the desired changes must be made to each of the clones instead. All the descendants of an entity node are read-only.

An entity node does not have any parent.

You can access the entity's publicId(), systemId() and notationName() when available.

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomEntity::QDomEntity ()

Constructs an empty entity.

QDomEntity::QDomEntity ( const QDomEntity & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomEntity::~QDomEntity ()

Destroys the object and frees its resources.

bool QDomEntity::isEntity () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomEntity::nodeType () const [virtual]

Returns EntityNode.

Reimplemented from QDomNode.

QString QDomEntity::notationName () const [virtual]

For unparsed entities this function returns the name of the notation for the entity. For parsed entities this function returns QString::null.

QDomEntity & QDomEntity::operator= ( const QDomEntity & x )

Assigns x to this DOM entity.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QString QDomEntity::publicId () const [virtual]

Returns the public identifier associated with this entity. If the public identifier was not specified QString::null is returned.

QString QDomEntity::systemId () const [virtual]

Returns the system identifier associated with this entity. If the system identifier was not specified QString::null is returned.

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


QDomEntity Member List

Complete Member List for QDomEntity

This is the complete list of member functions for QDomEntity, including inherited members.

  • QDomEntity()
  • ~QDomEntity()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • notationName()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • publicId()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • systemId()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomEntityReference Class

QDomEntityReference Class Reference
[XML module]

The QDomEntityReference class represents an XML entity reference. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomEntityReference ()
  • QDomEntityReference ( const QDomEntityReference & x )
  • QDomEntityReference & operator= ( const QDomEntityReference & x )
  • ~QDomEntityReference ()
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isEntityReference () const

Detailed Description

The QDomEntityReference class represents an XML entity reference.

A QDomEntityReference object may be inserted into the DOM tree when an entity reference is in the source document, or when the user wishes to insert an entity reference.

Note that character references and references to predefined entities are expanded by the XML processor so that characters are represented by their Unicode equivalent rather than by an entity reference.

Moreover, the XML processor may completely expand references to entities while building the DOM tree, instead of providing QDomEntityReference objects.

If it does provide such objects, then for a given entity reference node, it may be that there is no entity node representing the referenced entity; but if such an entity exists, then the child list of the entity reference node is the same as that of the entity node. As with the entity node, all descendants of the entity reference are read-only.

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomEntityReference::QDomEntityReference ()

Constructs an empty entity reference. Use QDomDocument::createEntityReference() to create a entity reference with content.

QDomEntityReference::QDomEntityReference ( const QDomEntityReference & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomEntityReference::~QDomEntityReference ()

Destroys the object and frees its resources.

bool QDomEntityReference::isEntityReference () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomEntityReference::nodeType () const [virtual]

Returns EntityReference.

Reimplemented from QDomNode.

QDomEntityReference & QDomEntityReference::operator= ( const QDomEntityReference & x )

Assigns x to this entity reference.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

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


QDomEntityReference Member List

Complete Member List for QDomEntityReference

This is the complete list of member functions for QDomEntityReference, including inherited members.

  • QDomEntityReference()
  • ~QDomEntityReference()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomImplementation Class

QDomImplementation Class Reference
[XML module]

The QDomImplementation class provides information about the features of the DOM implementation. More...

#include <qdom.h>

List of all member functions.

Public Members

  • QDomImplementation ()
  • QDomImplementation ( const QDomImplementation & x )
  • virtual ~QDomImplementation ()
  • QDomImplementation & operator= ( const QDomImplementation & x )
  • bool operator== ( const QDomImplementation & x ) const
  • bool operator!= ( const QDomImplementation & x ) const
  • virtual bool hasFeature ( const QString & feature, const QString & version )
  • virtual QDomDocumentType createDocumentType ( const QString & qName, const QString & publicId, const QString & systemId )
  • virtual QDomDocument createDocument ( const QString & nsURI, const QString & qName, const QDomDocumentType & doctype )
  • bool isNull ()

Detailed Description

The QDomImplementation class provides information about the features of the DOM implementation.

This class describes the features that are supported by the DOM implementation. Currently only the XML subset of DOM Level 1 and DOM Level 2 Core are supported.

Normally you will use the function QDomDocument::implementation() to get the implementation object.

You can create a new document type with createDocumentType() and a new document with createDocument().

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also hasFeature() and XML.

Member Function Documentation

QDomImplementation::QDomImplementation ()

Constructs a QDomImplementation object.

QDomImplementation::QDomImplementation ( const QDomImplementation & x )

Constructs a copy of x.

QDomImplementation::~QDomImplementation () [virtual]

Destroys the object and frees its resources.

QDomDocument QDomImplementation::createDocument ( const QString & nsURI, const QString & qName, const QDomDocumentType & doctype ) [virtual]

Creates a DOM document with the document type doctype. This function also adds a root element node with the qualified name qName and the namespace URI nsURI.

QDomDocumentType QDomImplementation::createDocumentType ( const QString & qName, const QString & publicId, const QString & systemId ) [virtual]

Creates a document type node for the name qName.

publicId specifies the public identifier of the external subset; If you specify QString::null as the publicId, this means that the document type has no public identifier.

Similarly, you specify the system identifier of the external subset with systemId. If you specify QString::null as the systemId, this means that the document type has no system identifier. Since you cannot have a public identifier without a system identifier, the public identifier is set to QString::null if there is no system identifier.

Other features of a document type declaration are not supported by DOM level 2.

The only way you can use a document type that was created this way, is in combination with the createDocument() function to create a QDomDocument with this document type.

See also createDocument().

bool QDomImplementation::hasFeature ( const QString & feature, const QString & version ) [virtual]

The function returns TRUE if QDom implements the requested version of a feature.

Currently only the feature "XML" in version "1.0" is supported.

bool QDomImplementation::isNull ()

Returns FALSE if the object was created by QDomDocument::implementation(); otherwise returns TRUE.

bool QDomImplementation::operator!= ( const QDomImplementation & x ) const

Returns TRUE if x and this DOM implementation object were created from different QDomDocuments.

QDomImplementation & QDomImplementation::operator= ( const QDomImplementation & x )

Assigns x to this DOM implementation.

bool QDomImplementation::operator== ( const QDomImplementation & x ) const

Returns TRUE if x and this DOM implementation object were created from the same QDomDocument.

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


QDomImplementation Member List

Complete Member List for QDomImplementation

This is the complete list of member functions for QDomImplementation, including inherited members.

  • QDomImplementation()
  • ~QDomImplementation()
  • createDocument()
  • createDocumentType()
  • hasFeature()
  • isNull()
  • operator!=()
  • operator=()
  • operator==()


QDomNamedNodeMap Class

QDomNamedNodeMap Class Reference
[XML module]

The QDomNamedNodeMap class contains a collection of nodes that can be accessed by name. More...

#include <qdom.h>

List of all member functions.

Public Members

  • QDomNamedNodeMap ()
  • QDomNamedNodeMap ( const QDomNamedNodeMap & n )
  • QDomNamedNodeMap & operator= ( const QDomNamedNodeMap & n )
  • bool operator== ( const QDomNamedNodeMap & n ) const
  • bool operator!= ( const QDomNamedNodeMap & n ) const
  • ~QDomNamedNodeMap ()
  • QDomNode namedItem ( const QString & name ) const
  • QDomNode setNamedItem ( const QDomNode & newNode )
  • QDomNode removeNamedItem ( const QString & name )
  • QDomNode item ( int index ) const
  • QDomNode namedItemNS ( const QString & nsURI, const QString & localName ) const
  • QDomNode setNamedItemNS ( const QDomNode & newNode )
  • QDomNode removeNamedItemNS ( const QString & nsURI, const QString & localName )
  • uint length () const
  • uint count () const
  • bool contains ( const QString & name ) const

Detailed Description

The QDomNamedNodeMap class contains a collection of nodes that can be accessed by name.

Note that QDomNamedNodeMap does not inherit from QDomNodeList. QDomNamedNodeMaps do not provide any specific node ordering. Although nodes in a QDomNamedNodeMap may be accessed by an ordinal index, this is simply to allow a convenient enumeration of the contents of a QDomNamedNodeMap, and does not imply that the DOM specifies an ordering of the nodes.

The QDomNamedNodeMap is used in three places:

  • QDomDocumentType::entities() returns a map of all entities described in the DTD.
  • QDomDocumentType::notations() returns a map of all notations described in the DTD.
  • QDomNode::attributes() returns a map of all attributes of the element.

Items in the map are identified by the name which QDomNode::name() returns. Nodes are retrieved using namedItem(), namedItemNS() or item(). New nodes are inserted with setNamedItem() or setNamedItem() and removed with removeNamedItem() or removeNamedItemNS(). Use contains() to see if an item with the given name is in the named node map. The number of items is returned by length().

Terminology: in this class we use "item" and "node" interchangeably.

See also XML.

Member Function Documentation

QDomNamedNodeMap::QDomNamedNodeMap ()

Constructs an empty named node map.

QDomNamedNodeMap::QDomNamedNodeMap ( const QDomNamedNodeMap & n )

Constructs a copy of n.

QDomNamedNodeMap::~QDomNamedNodeMap ()

Destroys the object and frees its resources.

bool QDomNamedNodeMap::contains ( const QString & name ) const

Returns TRUE if the map contains a node called name; otherwise returns FALSE.

uint QDomNamedNodeMap::count () const

Returns the number of nodes in the map.

This function is the same as length().

QDomNode QDomNamedNodeMap::item ( int index ) const

Retrieves the node at position index.

This can be used to iterate over the map. Note that the nodes in the map are ordered arbitrarily.

See also length().

uint QDomNamedNodeMap::length () const

Returns the number of nodes in the map.

See also item().

QDomNode QDomNamedNodeMap::namedItem ( const QString & name ) const

Returns the node called name.

If the named node map does not contain such a node, a null node is returned. A node's name is the name returned by QDomNode::nodeName().

See also setNamedItem() and namedItemNS().

QDomNode QDomNamedNodeMap::namedItemNS ( const QString & nsURI, const QString & localName ) const

Returns the node associated with the local name localName and the namespace URI nsURI.

If the map does not contain such a node, a null node is returned.

See also setNamedItemNS() and namedItem().

bool QDomNamedNodeMap::operator!= ( const QDomNamedNodeMap & n ) const

Returns TRUE if n and this named node map are not equal; otherwise returns FALSE.

QDomNamedNodeMap & QDomNamedNodeMap::operator= ( const QDomNamedNodeMap & n )

Assigns n to this named node map.

bool QDomNamedNodeMap::operator== ( const QDomNamedNodeMap & n ) const

Returns TRUE if n and this named node map are equal; otherwise returns FALSE.

QDomNode QDomNamedNodeMap::removeNamedItem ( const QString & name )

Removes the node called name from the map.

The function returns the removed node or a null node if the map did not contain a node called name.

See also setNamedItem(), namedItem() and removeNamedItemNS().

QDomNode QDomNamedNodeMap::removeNamedItemNS ( const QString & nsURI, const QString & localName )

Removes the node with the local name localName and the namespace URI nsURI from the map.

The function returns the removed node or a null node if the map did not contain a node with the local name localName and the namespace URI nsURI.

See also setNamedItemNS(), namedItemNS() and removeNamedItem().

QDomNode QDomNamedNodeMap::setNamedItem ( const QDomNode & newNode )

Inserts the node newNode into the named node map. The name used by the map is the node name of newNode as returned by QDomNode::nodeName().

If the new node replaces an existing node, i.e. the map contains a node with the same name, the replaced node is returned.

See also namedItem(), removeNamedItem() and setNamedItemNS().

QDomNode QDomNamedNodeMap::setNamedItemNS ( const QDomNode & newNode )

Inserts the node newNode in the map. If a node with the same namespace URI and the same local name already exists in the map, it is replaced by newNode. If the new node replaces an existing node, the replaced node is returned.

See also namedItemNS(), removeNamedItemNS() and setNamedItem().

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


QDomNamedNodeMap Member List

Complete Member List for QDomNamedNodeMap

This is the complete list of member functions for QDomNamedNodeMap, including inherited members.

  • QDomNamedNodeMap()
  • ~QDomNamedNodeMap()
  • contains()
  • count()
  • item()
  • length()
  • namedItem()
  • namedItemNS()
  • operator!=()
  • operator=()
  • operator==()
  • removeNamedItem()
  • removeNamedItemNS()
  • setNamedItem()
  • setNamedItemNS()


QDomNode Class

QDomNode Class Reference
[XML module]

The QDomNode class is the base class for all the nodes in a DOM tree. More...

#include <qdom.h>

Inherited by QDomDocumentType, QDomDocument, QDomDocumentFragment, QDomCharacterData, QDomAttr, QDomElement, QDomNotation, QDomEntity, QDomEntityReference and QDomProcessingInstruction.

List of all member functions.

Public Members

  • enum NodeType { ElementNode = 1, AttributeNode = 2, TextNode = 3, CDATASectionNode = 4, EntityReferenceNode = 5, EntityNode = 6, ProcessingInstructionNode = 7, CommentNode = 8, DocumentNode = 9, DocumentTypeNode = 10, DocumentFragmentNode = 11, NotationNode = 12, BaseNode = 21, CharacterDataNode = 22 }
  • QDomNode ()
  • QDomNode ( const QDomNode & n )
  • QDomNode & operator= ( const QDomNode & n )
  • bool operator== ( const QDomNode & n ) const
  • bool operator!= ( const QDomNode & n ) const
  • virtual ~QDomNode ()
  • virtual QDomNode insertBefore ( const QDomNode & newChild, const QDomNode & refChild )
  • virtual QDomNode insertAfter ( const QDomNode & newChild, const QDomNode & refChild )
  • virtual QDomNode replaceChild ( const QDomNode & newChild, const QDomNode & oldChild )
  • virtual QDomNode removeChild ( const QDomNode & oldChild )
  • virtual QDomNode appendChild ( const QDomNode & newChild )
  • virtual bool hasChildNodes () const
  • virtual QDomNode cloneNode ( bool deep = TRUE ) const
  • virtual void normalize ()
  • virtual bool isSupported ( const QString & feature, const QString & version ) const
  • virtual QString nodeName () const
  • virtual QDomNode::NodeType nodeType () const
  • virtual QDomNode parentNode () const
  • virtual QDomNodeList childNodes () const
  • virtual QDomNode firstChild () const
  • virtual QDomNode lastChild () const
  • virtual QDomNode previousSibling () const
  • virtual QDomNode nextSibling () const
  • virtual QDomNamedNodeMap attributes () const
  • virtual QDomDocument ownerDocument () const
  • virtual QString namespaceURI () const
  • virtual QString localName () const
  • virtual bool hasAttributes () const
  • virtual QString nodeValue () const
  • virtual void setNodeValue ( const QString & v )
  • virtual QString prefix () const
  • virtual void setPrefix ( const QString & pre )
  • virtual bool isAttr () const
  • virtual bool isCDATASection () const
  • virtual bool isDocumentFragment () const
  • virtual bool isDocument () const
  • virtual bool isDocumentType () const
  • virtual bool isElement () const
  • virtual bool isEntityReference () const
  • virtual bool isText () const
  • virtual bool isEntity () const
  • virtual bool isNotation () const
  • virtual bool isProcessingInstruction () const
  • virtual bool isCharacterData () const
  • virtual bool isComment () const
  • QDomNode namedItem ( const QString & name ) const
  • bool isNull () const
  • void clear ()
  • QDomAttr toAttr ()
  • QDomCDATASection toCDATASection ()
  • QDomDocumentFragment toDocumentFragment ()
  • QDomDocument toDocument ()
  • QDomDocumentType toDocumentType ()
  • QDomElement toElement ()
  • QDomEntityReference toEntityReference ()
  • QDomText toText ()
  • QDomEntity toEntity ()
  • QDomNotation toNotation ()
  • QDomProcessingInstruction toProcessingInstruction ()
  • QDomCharacterData toCharacterData ()
  • QDomComment toComment ()
  • void save ( QTextStream & str, int indent ) const

Related Functions

  • QTextStream & operator<< ( QTextStream & str, const QDomNode & node )

Detailed Description

The QDomNode class is the base class for all the nodes in a DOM tree.

Many functions in the DOM return a QDomNode.

 You can find out the type of a node using isAttr(), isCDATASection(),
isDocumentFragment(), isDocument(), isDocumentType(), isElement(),
isEntityReference(), isText(), isEntity(), isNotation(),
isProcessingInstruction(), isCharacterData() and isComment().

A QDomNode can be converted into one of its subclasses using toAttr(), toCDATASection(), toDocumentFragment(), toDocument(), toDocumentType(), toElement(), toEntityReference(), toText(), toEntity(), toNotation(), toProcessingInstruction(), toCharacterData() or toComment(). You can convert a node to a null node with clear().

Copies of the QDomNode class share their data; this means modifying one node will change all copies. This is especially useful in combination with functions which return a QDomNode, e.g. firstChild(). You can make an independent (deep) copy of the node with cloneNode().

Nodes are inserted with insertBefore(), insertAfter() or appendChild(). You can replace one node with another using replaceChild() and remove a node with removeChild().

To traverse nodes use firstChild() to get a node's first child (if any), and nextSibling() to traverse. QDomNode also provides lastChild(), previousSibling() and parentNode(). To find the first child node with a particular node name use namedItem().

To find out if a node has children use hasChildNodes() and to get a list of all of a node's children use childNodes().

The node's name and value (the meaning of which varies depending on its type) is returned by nodeName() and nodeValue() respectively. The node's type is returned by nodeType(). The node's value can be set with setNodeValue().

The document to which the node belongs is returned by ownerDocument().

Adjacent QDomText nodes can be merged into a single node with normalize().

QDomElement nodes have attributes which can be retrieved with attributes().

QDomElement and QDomAttr nodes can have namespaces which can be retrieved with namespaceURI(). Their local name is retrieved with localName(), and their prefix with prefix(). The prefix can be set with setPrefix().

You can write the XML representation of the node to a text stream with save().

The following example looks for the first element in an XML document and prints the names of all the elements that are its direct children.

  QDomDocument d;
  d.setContent( someXML );
  QDomNode n = d.firstChild();
  while ( !n.isNull() ) {
      if ( n.isElement() ) {
          QDomElement e = n.toElement();
          cout << "Element name: " << e.tagName() << endl;
          return;
      }
      n = n.nextSibling();
  }

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Type Documentation

QDomNode::NodeType

This enum defines the type of the node:

  • QDomNode::ElementNode
  • QDomNode::AttributeNode
  • QDomNode::TextNode
  • QDomNode::CDATASectionNode
  • QDomNode::EntityReferenceNode
  • QDomNode::EntityNode
  • QDomNode::ProcessingInstructionNode
  • QDomNode::CommentNode
  • QDomNode::DocumentNode
  • QDomNode::DocumentTypeNode
  • QDomNode::DocumentFragmentNode
  • QDomNode::NotationNode
  • QDomNode::BaseNode - A QDomNode object, i.e. not a QDomNode subclass.
  • QDomNode::CharacterDataNode

Member Function Documentation

QDomNode::QDomNode ()

Constructs an empty node.

QDomNode::QDomNode ( const QDomNode & n )

Constructs a copy of n.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomNode::~QDomNode () [virtual]

Destroys the object and frees its resources.

QDomNode QDomNode::appendChild ( const QDomNode & newChild ) [virtual]

Appends newChild as the node's last child.

If newChild is the child of another node, it is reparented to this node. If newChild is a child of this node, then its position in the list of children is changed.

Returns a new reference to newChild.

See also insertBefore(), insertAfter(), replaceChild() and removeChild().

QDomNamedNodeMap QDomNode::attributes () const [virtual]

Returns a named node map of all attributes. Attributes are only provided for QDomElement.

Changing the attributes in the map will also change the attributes of this QDomNode.

Reimplemented in QDomElement.

QDomNodeList QDomNode::childNodes () const [virtual]

Returns a list of all direct child nodes.

Most often you will call this function on a QDomElement object.

For example, if the XML document looks like this:

  <body>
   <h1>Heading</h1>
   <p>Hello <b>you</b></p>
  </body>
Then the list of child nodes for the "body"-element will contain the node created by the <h1> tag and the node created by the <p> tag.

The nodes in the list are not copied; so changing the nodes in the list will also change the children of this node.

See also firstChild() and lastChild().

void QDomNode::clear ()

Dereferences the internal object. The node becomes a null node.

See also isNull().

QDomNode QDomNode::cloneNode ( bool deep = TRUE ) const [virtual]

Creates a real (not shallow) copy of the QDomNode.

If deep is TRUE, then the cloning is done recursively which means that all the node's children are copied, too. If deep is FALSE only the node itself is copied and the copy will have no child nodes.

QDomNode QDomNode::firstChild () const [virtual]

Returns the first child of the node. If there is no child node, a null node is returned. Changing the returned node will also change the node in the document tree.

See also lastChild() and childNodes().

Example: xml/outliner/outlinetree.cpp.

bool QDomNode::hasAttributes () const [virtual]

Returns TRUE if the node has attributes; otherwise returns FALSE.

See also attributes().

bool QDomNode::hasChildNodes () const [virtual]

Returns TRUE if the node has one or more children; otherwise returns FALSE.

QDomNode QDomNode::insertAfter ( const QDomNode & newChild, const QDomNode & refChild ) [virtual]

Inserts the node newChild after the child node refChild. refChild must be a direct child of this node. If refChild is null then newChild is appended as this node's last child.

If newChild is the child of another node, it is reparented to this node. If newChild is a child of this node, then its position in the list of children is changed.

If newChild is a QDomDocumentFragment, then the children of the fragment are removed from the fragment and inserted after refChild.

Returns a new reference to newChild on success or an empty node on failure.

See also insertBefore(), replaceChild(), removeChild() and appendChild().

QDomNode QDomNode::insertBefore ( const QDomNode & newChild, const QDomNode & refChild ) [virtual]

Inserts the node newChild before the child node refChild. refChild must be a direct child of this node. If refChild is null then newChild is inserted as the node's first child.

If newChild is the child of another node, it is reparented to this node. If newChild is a child of this node, then its position in the list of children is changed.

If newChild is a QDomDocumentFragment, then the children of the fragment are removed from the fragment and inserted before refChild.

Returns a new reference to newChild on success or an empty node on failure.

See also insertAfter(), replaceChild(), removeChild() and appendChild().

bool QDomNode::isAttr () const [virtual]

Returns TRUE if the node is an attribute; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomAttribute; you can get the QDomAttribute with toAttribute().

See also toAttr().

Reimplemented in QDomAttr.

bool QDomNode::isCDATASection () const [virtual]

Returns TRUE if the node is a CDATA section; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomCDATASection; you can get the QDomCDATASection with toCDATASection().

See also toCDATASection().

Reimplemented in QDomCDATASection.

bool QDomNode::isCharacterData () const [virtual]

Returns TRUE if the node is a character data node; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomCharacterData; you can get the QDomCharacterData with toCharacterData().

See also toCharacterData().

Reimplemented in QDomCharacterData.

bool QDomNode::isComment () const [virtual]

Returns TRUE if the node is a comment; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomComment; you can get the QDomComment with toComment().

See also toComment().

Reimplemented in QDomComment.

bool QDomNode::isDocument () const [virtual]

Returns TRUE if the node is a document; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomDocument; you can get the QDomDocument with toDocument().

See also toDocument().

Reimplemented in QDomDocument.

bool QDomNode::isDocumentFragment () const [virtual]

Returns TRUE if the node is a document fragment; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomDocumentFragment; you can get the QDomDocumentFragment with toDocumentFragment().

See also toDocumentFragment().

Reimplemented in QDomDocumentFragment.

bool QDomNode::isDocumentType () const [virtual]

Returns TRUE if the node is a document type; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomDocumentType; you can get the QDomDocumentType with toDocumentType().

See also toDocumentType().

Reimplemented in QDomDocumentType.

bool QDomNode::isElement () const [virtual]

Returns TRUE if the node is an element; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomElement; you can get the QDomElement with toElement().

See also toElement().

Example: xml/outliner/outlinetree.cpp.

Reimplemented in QDomElement.

bool QDomNode::isEntity () const [virtual]

Returns TRUE if the node is an entity; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomEntity; you can get the QDomEntity with toEntity().

See also toEntity().

Reimplemented in QDomEntity.

bool QDomNode::isEntityReference () const [virtual]

Returns TRUE if the node is an entity reference; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomEntityReference; you can get the QDomEntityReference with toEntityReference().

See also toEntityReference().

Reimplemented in QDomEntityReference.

bool QDomNode::isNotation () const [virtual]

Returns TRUE if the node is a notation; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomNotation; you can get the QDomNotation with toNotation().

See also toNotation().

Reimplemented in QDomNotation.

bool QDomNode::isNull () const

Returns TRUE if this node does not reference any internal object; otherwise returns FALSE.

Example: xml/outliner/outlinetree.cpp.

bool QDomNode::isProcessingInstruction () const [virtual]

Returns TRUE if the node is a processing instruction; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomProcessingInstruction; you can get the QProcessingInstruction with toProcessingInstruction().

See also toProcessingInstruction().

Reimplemented in QDomProcessingInstruction.

bool QDomNode::isSupported ( const QString & feature, const QString & version ) const [virtual]

Returns TRUE if the DOM implementation implements the feature feature and that feature is supported by this node in the version version. Otherwise this function returns FALSE.

See also QDomImplementation::hasFeature().

bool QDomNode::isText () const [virtual]

Returns TRUE if the node is a text; otherwise returns FALSE.

If this function returns TRUE, it does not imply that this object is a QDomText; you can get the QDomText with toText().

See also toText().

Reimplemented in QDomText.

QDomNode QDomNode::lastChild () const [virtual]

Returns the last child of the node. If there is no child node, a null node is returned. Changing the returned node will also change the node in the document tree.

See also firstChild() and childNodes().

QString QDomNode::localName () const [virtual]

If the node uses namespaces, this function returns the local name of the node. Otherwise it returns QString::null.

Only nodes of type ElementNode or AttributeNode can have namespaces. A namespace must have been specified at creation time; it is not possible to add a namespace afterwards.

See also prefix(), namespaceURI(), QDomDocument::createElementNS() and QDomDocument::createAttributeNS().

QDomNode QDomNode::namedItem ( const QString & name ) const

Returns the first direct child node for which nodeName() equals name.

If no such direct child exists, a null node is returned.

See also nodeName().

QString QDomNode::namespaceURI () const [virtual]

Returns the namespace URI of this node; if the node has no namespace URI, this function returns QString::null.

Only nodes of type ElementNode or AttributeNode can have namespaces. A namespace URI must be specified at creation time and cannot be changed later.

See also prefix(), localName(), QDomDocument::createElementNS() and QDomDocument::createAttributeNS().

QDomNode QDomNode::nextSibling () const [virtual]

Returns the next sibling in the document tree. Changing the returned node will also change the node in the document tree.

If you have XML like this:

  <h1>Heading</h1>
  <p>The text...</p>
  <h2>Next heading</h2>
and this QDomNode represents the <p> tag, nextSibling() will return the node representing the <h2> tag.

See also previousSibling().

Example: xml/outliner/outlinetree.cpp.

QString QDomNode::nodeName () const [virtual]

Returns the name of the node.

The meaning of the name depends on the subclass:

  • QDomAttr - the name of the attribute
  • QDomCDATASection - the string "#cdata-section"
  • QDomComment - the string "#comment"
  • QDomDocument - the string "#document"
  • QDomDocumentFragment - the string "#document-fragment"
  • QDomDocumentType - the name of the document type
  • QDomElement - the tag name
  • QDomEntity - the name of the entity
  • QDomEntityReference - the name of the referenced entity
  • QDomNotation - the name of the notation
  • QDomProcessingInstruction - the target of the processing instruction
  • QDomText - the string "#text"

See also nodeValue().

Example: xml/outliner/outlinetree.cpp.

QDomNode::NodeType QDomNode::nodeType () const [virtual]

Returns the type of the node.

See also toAttr(), toCDATASection(), toDocumentFragment(), toDocument(), toDocumentType(), toElement(), toEntityReference(), toText(), toEntity(), toNotation(), toProcessingInstruction(), toCharacterData() and toComment().

Reimplemented in QDomDocumentType, QDomDocument, QDomDocumentFragment, QDomCharacterData, QDomAttr, QDomElement, QDomNotation, QDomEntity, QDomEntityReference and QDomProcessingInstruction.

QString QDomNode::nodeValue () const [virtual]

Returns the value of the node.

The meaning of the value depends on the subclass:

  • QDomAttr - the attribute value
  • QDomCDATASection - the content of the CDATA section
  • QDomComment - the comment
  • QDomProcessingInstruction - the data of the processing intruction
  • QDomText - the text

All other subclasses do not have a node value and will return a null string.

See also setNodeValue() and nodeName().

Example: xml/outliner/outlinetree.cpp.

void QDomNode::normalize () [virtual]

Calling normalize() on an element converts all its children into a standard form. This means, that adjacent QDomText objects will be merged into a single text object (QDomCDATASection nodes are not merged).

bool QDomNode::operator!= ( const QDomNode & n ) const

Returns TRUE if n and this DOM node are not equal; otherwise returns FALSE.

QDomNode & QDomNode::operator= ( const QDomNode & n )

Assigns a copy of n to this DOM node.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

bool QDomNode::operator== ( const QDomNode & n ) const

Returns TRUE if n and this DOM node are equal; otherwise returns FALSE.

QDomDocument QDomNode::ownerDocument () const [virtual]

Returns the document to which this node belongs.

QDomNode QDomNode::parentNode () const [virtual]

Returns the parent node. If this node has no parent, a null node is returned (i.e. a node for which isNull() returns TRUE).

QString QDomNode::prefix () const [virtual]

Returns the namespace prefix of the node; if a node has no namespace prefix, this function returns QString::null.

Only nodes of type ElementNode or AttributeNode can have namespaces. A namespace prefix must be specified at creation time. If a node was created with a namespace prefix, you can change it later with setPrefix().

If you create an element or attribute with QDomDocument::createElement() or QDomDocument::createAttribute(), the prefix will be null. If you use QDomDocument::createElementNS() or QDomDocument::createAttributeNS() instead, the prefix will not be null - although it might be an empty string if the name does not have a prefix.

See also setPrefix(), localName(), namespaceURI(), QDomDocument::createElementNS() and QDomDocument::createAttributeNS().

QDomNode QDomNode::previousSibling () const [virtual]

Returns the previous sibling in the document tree. Changing the returned node will also change the node in the document tree.

For example, if you have XML like this:

  <h1>Heading</h1>
  <p>The text...</p>
  <h2>Next heading</h2>
and this QDomNode represents the <p> tag, previousSibling() will return the node representing the <h1> tag.

See also nextSibling().

QDomNode QDomNode::removeChild ( const QDomNode & oldChild ) [virtual]

Removes oldChild from the list of children. oldChild must be a direct child of this node.

Returns a new reference to oldChild on success or a null node on failure.

See also insertBefore(), insertAfter(), replaceChild() and appendChild().

QDomNode QDomNode::replaceChild ( const QDomNode & newChild, const QDomNode & oldChild ) [virtual]

Replaces oldChild with newChild. oldChild must be a direct child of this node.

If newChild is the child of another node, it is reparented to this node. If newChild is a child of this node, then its position in the list of children is changed.

If newChild is a QDomDocumentFragment, then oldChild is replaced by all of the children of the fragment.

Returns a new reference to oldChild on success or a null node an failure.

See also insertBefore(), insertAfter(), removeChild() and appendChild().

void QDomNode::save ( QTextStream & str, int indent ) const

Writes the XML representation of the node and all its children to the stream str. This function uses indent as the amount of space to indent the node.

void QDomNode::setNodeValue ( const QString & v ) [virtual]

Sets the value of the node to v.

See also nodeValue().

void QDomNode::setPrefix ( const QString & pre ) [virtual]

If the node has a namespace prefix, this function changes the namespace prefix of the node to pre. Otherwise this function has no effect.

Only nodes of type ElementNode or AttributeNode can have namespaces. A namespace prefix must have be specified at creation time; it is not possible to add a namespace prefix afterwards.

See also prefix(), localName(), namespaceURI(), QDomDocument::createElementNS() and QDomDocument::createAttributeNS().

QDomAttr QDomNode::toAttr ()

Converts a QDomNode into a QDomAttr. If the node is not an attribute, the returned object will be null.

See also isAttr().

QDomCDATASection QDomNode::toCDATASection ()

Converts a QDomNode into a QDomCDATASection. If the node is not a CDATA section, the returned object will be null.

See also isCDATASection().

QDomCharacterData QDomNode::toCharacterData ()

Converts a QDomNode into a QDomCharacterData. If the node is not a character data node the returned object will be null.

See also isCharacterData().

QDomComment QDomNode::toComment ()

Converts a QDomNode into a QDomComment. If the node is not a comment the returned object will be null.

See also isComment().

QDomDocument QDomNode::toDocument ()

Converts a QDomNode into a QDomDocument. If the node is not a document the returned object will be null.

See also isDocument().

QDomDocumentFragment QDomNode::toDocumentFragment ()

Converts a QDomNode into a QDomDocumentFragment. If the node is not a document fragment the returned object will be null.

See also isDocumentFragment().

QDomDocumentType QDomNode::toDocumentType ()

Converts a QDomNode into a QDomDocumentType. If the node is not a document type the returned object will be null.

See also isDocumentType().

QDomElement QDomNode::toElement ()

Converts a QDomNode into a QDomElement. If the node is not an element the returned object will be null.

See also isElement().

Example: xml/outliner/outlinetree.cpp.

QDomEntity QDomNode::toEntity ()

Converts a QDomNode into a QDomEntity. If the node is not an entity the returned object will be null.

See also isEntity().

QDomEntityReference QDomNode::toEntityReference ()

Converts a QDomNode into a QDomEntityReference. If the node is not an entity reference, the returned object will be null.

See also isEntityReference().

QDomNotation QDomNode::toNotation ()

Converts a QDomNode into a QDomNotation. If the node is not a notation the returned object will be null.

See also isNotation().

QDomProcessingInstruction QDomNode::toProcessingInstruction ()

Converts a QDomNode into a QDomProcessingInstruction. If the node is not a processing instruction the returned object will be null.

See also isProcessingInstruction().

QDomText QDomNode::toText ()

Converts a QDomNode into a QDomText. If the node is not a text, the returned object will be null.

See also isText().

Related Functions

QTextStream & operator<< ( QTextStream & str, const QDomNode & node )

Writes the XML representation of the node node and all its children to the stream str.

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


QDomNode Member List

Complete Member List for QDomNode

This is the complete list of member functions for QDomNode, including inherited members.

  • QDomNode()
  • ~QDomNode()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomNodeList Class

QDomNodeList Class Reference
[XML module]

The QDomNodeList class is a list of QDomNode objects. More...

#include <qdom.h>

List of all member functions.

Public Members

  • QDomNodeList ()
  • QDomNodeList ( const QDomNodeList & n )
  • QDomNodeList & operator= ( const QDomNodeList & n )
  • bool operator== ( const QDomNodeList & n ) const
  • bool operator!= ( const QDomNodeList & n ) const
  • virtual ~QDomNodeList ()
  • virtual QDomNode item ( int index ) const
  • virtual uint length () const
  • uint count () const

Detailed Description

The QDomNodeList class is a list of QDomNode objects.

Lists can be obtained by QDomDocument::elementsByTagName() and QDomNode::childNodes(). The Document Object Model (DOM) requires these lists to be "live": whenever you change the underlying document, the contents of the list will get updated.

You can get a particular node from the list with item(). The number of items in the list is returned by count() (and by length()).

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also QDomNode::childNodes(), QDomDocument::elementsByTagName() and XML.

Member Function Documentation

QDomNodeList::QDomNodeList ()

Creates an empty node list.

QDomNodeList::QDomNodeList ( const QDomNodeList & n )

Constructs a copy of n.

QDomNodeList::~QDomNodeList () [virtual]

Destroys the object and frees its resources.

uint QDomNodeList::count () const

Returns the number of nodes in the list.

This function is the same as length().

QDomNode QDomNodeList::item ( int index ) const [virtual]

Returns the node at position index.

If index is negative or if index >= length() then a null node is returned (i.e. a node for which QDomNode::isNull() returns TRUE).

See also count().

uint QDomNodeList::length () const [virtual]

Returns the number of nodes in the list.

This function is the same as count().

bool QDomNodeList::operator!= ( const QDomNodeList & n ) const

Returns TRUE the node list n and this node list are not equal; otherwise returns FALSE.

QDomNodeList & QDomNodeList::operator= ( const QDomNodeList & n )

Assigns n to this node list.

bool QDomNodeList::operator== ( const QDomNodeList & n ) const

Returns TRUE if the node list n and this node list are equal; otherwise returns FALSE.

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


QDomNodeList Member List

Complete Member List for QDomNodeList

This is the complete list of member functions for QDomNodeList, including inherited members.

  • QDomNodeList()
  • ~QDomNodeList()
  • count()
  • item()
  • length()
  • operator!=()
  • operator=()
  • operator==()


QDomNotation Class

QDomNotation Class Reference
[XML module]

The QDomNotation class represents an XML notation. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomNotation ()
  • QDomNotation ( const QDomNotation & x )
  • QDomNotation & operator= ( const QDomNotation & x )
  • ~QDomNotation ()
  • QString publicId () const
  • QString systemId () const
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isNotation () const

Detailed Description

The QDomNotation class represents an XML notation.

A notation either declares, by name, the format of an unparsed entity (see section 4.7 of the XML 1.0 specification), or is used for formal declaration of processing instruction targets (see section 2.6 of the XML 1.0 specification).

DOM does not support editing notation nodes; they are therefore read-only.

A notation node does not have any parent.

You can retrieve the publicId() and systemId() from a notation node.

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomNotation::QDomNotation ()

Constructor.

QDomNotation::QDomNotation ( const QDomNotation & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomNotation::~QDomNotation ()

Destroys the object and frees its resources.

bool QDomNotation::isNotation () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomNotation::nodeType () const [virtual]

Returns NotationNode.

Reimplemented from QDomNode.

QDomNotation & QDomNotation::operator= ( const QDomNotation & x )

Assigns x to this DOM notation.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QString QDomNotation::publicId () const

Returns the public identifier of this notation.

QString QDomNotation::systemId () const

Returns the system identifier of this notation.

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


QDomNotation Member List

Complete Member List for QDomNotation

This is the complete list of member functions for QDomNotation, including inherited members.

  • QDomNotation()
  • ~QDomNotation()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • publicId()
  • removeChild()
  • replaceChild()
  • save()
  • setNodeValue()
  • setPrefix()
  • systemId()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomProcessingInstruction Class

QDomProcessingInstruction Class Reference
[XML module]

The QDomProcessingInstruction class represents an XML processing instruction. More...

#include <qdom.h>

Inherits QDomNode.

List of all member functions.

Public Members

  • QDomProcessingInstruction ()
  • QDomProcessingInstruction ( const QDomProcessingInstruction & x )
  • QDomProcessingInstruction & operator= ( const QDomProcessingInstruction & x )
  • ~QDomProcessingInstruction ()
  • virtual QString target () const
  • virtual QString data () const
  • virtual void setData ( const QString & d )
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isProcessingInstruction () const

Detailed Description

The QDomProcessingInstruction class represents an XML processing instruction.

Processing instructions are used in XML as a way to keep processor-specific information in the text of the document.

The content of the processing instruction is retrieved with data() and set with setData(). The processing instruction's target is retrieved with target().

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomProcessingInstruction::QDomProcessingInstruction ()

Constructs an empty processing instruction. Use QDomDocument::createProcessingInstruction() to create a processing instruction with content.

QDomProcessingInstruction::QDomProcessingInstruction ( const QDomProcessingInstruction & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomProcessingInstruction::~QDomProcessingInstruction ()

Destroys the object and frees its resources.

QString QDomProcessingInstruction::data () const [virtual]

Returns the content of this processing instruction.

See also setData() and target().

bool QDomProcessingInstruction::isProcessingInstruction () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomProcessingInstruction::nodeType () const [virtual]

Returns ProcessingInstructionNode.

Reimplemented from QDomNode.

QDomProcessingInstruction & QDomProcessingInstruction::operator= ( const QDomProcessingInstruction & x )

Assigns x to this processing instruction.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

void QDomProcessingInstruction::setData ( const QString & d ) [virtual]

Sets the data contained in the processing instruction to d.

See also data().

QString QDomProcessingInstruction::target () const [virtual]

Returns the target of this processing instruction.

See also data().

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


QDomProcessingInstruction Member List

Complete Member List for QDomProcessingInstruction

This is the complete list of member functions for QDomProcessingInstruction, including inherited members.

  • QDomProcessingInstruction()
  • ~QDomProcessingInstruction()
  • appendChild()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • data()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • save()
  • setData()
  • setNodeValue()
  • setPrefix()
  • target()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDomText Class

QDomText Class Reference
[XML module]

The QDomText class represents text data in the parsed XML document. More...

#include <qdom.h>

Inherits QDomCharacterData.

Inherited by QDomCDATASection.

List of all member functions.

Public Members

  • QDomText ()
  • QDomText ( const QDomText & x )
  • QDomText & operator= ( const QDomText & x )
  • ~QDomText ()
  • QDomText splitText ( int offset )
  • virtual QDomNode::NodeType nodeType () const
  • virtual bool isText () const

Detailed Description

The QDomText class represents text data in the parsed XML document.

You can split the text in a QDomText object over two QDomText objecs with splitText().

For further information about the Document Object Model see http://www.w3.org/TR/REC-DOM-Level-1/ and http://www.w3.org/TR/DOM-Level-2-Core/. For a more general introduction of the DOM implementation see the QDomDocument documentation.

See also XML.

Member Function Documentation

QDomText::QDomText ()

Constructs an empty QDomText object.

To construct a QDomText with content, use QDomDocument::createTextNode().

QDomText::QDomText ( const QDomText & x )

Constructs a copy of x.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomText::~QDomText ()

Destroys the object and frees its resources.

bool QDomText::isText () const [virtual]

Returns TRUE.

Reimplemented from QDomNode.

QDomNode::NodeType QDomText::nodeType () const [virtual]

Returns TextNode.

Reimplemented from QDomCharacterData.

Reimplemented in QDomCDATASection.

QDomText & QDomText::operator= ( const QDomText & x )

Assigns x to this DOM text.

The data of the copy is shared (shallow copy): modifying one node will also change the other. If you want to make a deep copy, use cloneNode().

QDomText QDomText::splitText ( int offset )

Splits this object at position offset into two QDomText objects. The newly created object is inserted into the document tree after this object.

The function returns the newly created object.

See also QDomNode::normalize().

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


QDomText Member List

Complete Member List for QDomText

This is the complete list of member functions for QDomText, including inherited members.

  • QDomText()
  • ~QDomText()
  • appendChild()
  • appendData()
  • attributes()
  • childNodes()
  • clear()
  • cloneNode()
  • data()
  • deleteData()
  • firstChild()
  • hasAttributes()
  • hasChildNodes()
  • insertAfter()
  • insertBefore()
  • insertData()
  • isAttr()
  • isCDATASection()
  • isCharacterData()
  • isComment()
  • isDocument()
  • isDocumentFragment()
  • isDocumentType()
  • isElement()
  • isEntity()
  • isEntityReference()
  • isNotation()
  • isNull()
  • isProcessingInstruction()
  • isSupported()
  • isText()
  • lastChild()
  • length()
  • localName()
  • namedItem()
  • namespaceURI()
  • nextSibling()
  • nodeName()
  • nodeType()
  • nodeValue()
  • normalize()
  • operator!=()
  • operator=()
  • operator==()
  • ownerDocument()
  • parentNode()
  • prefix()
  • previousSibling()
  • removeChild()
  • replaceChild()
  • replaceData()
  • save()
  • setData()
  • setNodeValue()
  • setPrefix()
  • splitText()
  • substringData()
  • toAttr()
  • toCDATASection()
  • toCharacterData()
  • toComment()
  • toDocument()
  • toDocumentFragment()
  • toDocumentType()
  • toElement()
  • toEntity()
  • toEntityReference()
  • toNotation()
  • toProcessingInstruction()
  • toText()


QDoubleValidator类

QDoubleValidator类参考

QDoubleValidator类提供了对浮点数的范围检查。 详情请见……

#include <qvalidator.h>

继承了QValidator。

所有成员函数的列表。

公有成员

  • QDoubleValidator ( QObject * parent, const char * name = 0 )
  • QDoubleValidator ( double bottom, double top, int decimals, QObject * parent, const char * name = 0 )
  • ~QDoubleValidator ()
  • virtual QValidator::State validate ( QString & input, int & ) const
  • virtual void setRange ( double minimum, double maximum, int decimals = 0 )
  • void setBottom ( double )
  • void setTop ( double )
  • void setDecimals ( int )
  • double bottom () const
  • double top () const
  • int decimals () const

属性

  • double bottom - 验证器可接受的最小值
  • int decimals - 验证器可接受的小数点后数字的最大位数
  • double top - 验证器可接受的最大值

详细描述

QDoubleValidator类提供了对浮点数的范围检查。

QDoubleValidator提供了一个上限、一个下限和一个小数点后数字位数的限制。它没有提供fixup()函数。

你可以通过调用setRange()或者setBottom()和setTop()来设置可接受的范围。可以通过调用setDecimals()设置小数的位数。validate()函数返回验证状态。

请参考QIntValidator、QRegExpValidator和杂项类。

成员函数文档

QDoubleValidator::QDoubleValidator ( QObject * parent, const char * name = 0 )

构造一个父对象为parent、名称为name的接受任何双精度实数的验证器。

QDoubleValidator::QDoubleValidator ( double bottom, double top, int decimals, QObject * parent, const char * name = 0 )

构造一个一个父对象为parent、名称为name的接受从bottom到top，最多decimals小数的双精度实数的验证器。

QDoubleValidator::~QDoubleValidator ()

销毁这个验证器，释放所有已经使用的资源。

double QDoubleValidator::bottom () const

返回验证器可接受的最小值。详细情况请参考“bottom”属性。

int QDoubleValidator::decimals () const

返回验证器可接受的小数点后数字的最大位数。详细情况请参考“decimals”属性。

void QDoubleValidator::setBottom ( double )

设置验证器可接受的最小值。详细情况请参考“bottom”属性。

void QDoubleValidator::setDecimals ( int )

设置验证器可接受的小数点后数字的最大位数。详细情况请参考“decimals”属性。

void QDoubleValidator::setRange ( double minimum, double maximum, int decimals = 0 ) [虚]

设置验证器可以接受从minimum到maximum（包括边界），小数点后数字的最大位数为decimals的双精度实数。

void QDoubleValidator::setTop ( double )

设置验证器可接受的最大值。详细情况请参考“top”属性。

double QDoubleValidator::top () const

返回验证器可接受的最大值。详细情况请参考“top”属性。

QValidator::State QDoubleValidator::validate ( QString & input, int & ) const [虚]

如果字符串input包含在正确范围内并且格式正确的双精度实数，返回Acceptable。

如果input包含在范围之外的或者格式错误的双精度实数，例如为空或者小数位数超过范围，返回Intermediate。

如果input不是双精度实数，返回Invalid。

从 QValidator中重新实现的。

属性文档

double bottom

这个属性保存的是验证器可接受的最小值。

通过setBottom()可以设置属性值并且通过bottom()返回属性值。

也可以参考setRange()。

int decimals

这个属性保存的是可接受的小数点后数字的最大位数。

通过setDecimals()可以设置属性值并且通过decimals()返回属性值。

也可以参考setRange()。

double top

这个属性保存的是验证器可接受的最大值。

通过setTop()可以设置属性值并且通过top()返回属性值。

也可以参考setRange()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDoubleValidator成员列表

完整的QDoubleValidator成员列表

这里是QDoubleValidator成员函数的完整列表，包括继承的成员。

  • QDoubleValidator()
  • ~QDoubleValidator()
  • blockSignals()
  • bottom()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • decimals()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fixup()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setBottom()
  • setDecimals()
  • setName()
  • setProperty()
  • setRange()
  • setTop()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • top()
  • tr()
  • trUtf8()
  • validate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QDragEnterEvent Class

QDragEnterEvent Class Reference

The QDragEnterEvent class provides an event which is sent to the widget when a drag and drop first drags onto the widget. More...

#include <qevent.h>

Inherits QDragMoveEvent.

List of all member functions.

Public Members

  • QDragEnterEvent ( const QPoint & pos )

Detailed Description

The QDragEnterEvent class provides an event which is sent to the widget when a drag and drop first drags onto the widget.

This event is always immediately followed by a QDragMoveEvent, so you only need to respond to one or the other event. This class inherits most of its functionality from QDragMoveEvent, which in turn inherits most of its functionality from QDropEvent.

See also QDragLeaveEvent, QDragMoveEvent, QDropEvent, Drag And Drop Classes and Event Classes.

Member Function Documentation

QDragEnterEvent::QDragEnterEvent ( const QPoint & pos )

Constructs a QDragEnterEvent entering at the given point, pos.

Warning: Do not create a QDragEnterEvent yourself since these objects rely on Qt's internal state.

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


QDragEnterEvent Member List

Complete Member List for QDragEnterEvent

This is the complete list of member functions for QDragEnterEvent, including inherited members.

  • QDragEnterEvent()
  • accept()
  • acceptAction()
  • action()
  • answerRect()
  • data()
  • encodedData()
  • format()
  • ignore()
  • isAccepted()
  • isActionAccepted()
  • pos()
  • provides()
  • serialNumber()
  • setAction()
  • setPoint()
  • source()
  • spontaneous()
  • type()


QDragLeaveEvent Class

QDragLeaveEvent Class Reference

The QDragLeaveEvent class provides an event which is sent to the widget when a drag and drop leaves the widget. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QDragLeaveEvent ()

Detailed Description

The QDragLeaveEvent class provides an event which is sent to the widget when a drag and drop leaves the widget.

This event is always preceded by a QDragEnterEvent and a series of QDragMoveEvents. It is not sent if a QDropEvent is sent instead.

See also QDragEnterEvent, QDragMoveEvent, QDropEvent, Drag And Drop Classes and Event Classes.

Member Function Documentation

QDragLeaveEvent::QDragLeaveEvent ()

Constructs a QDragLeaveEvent.

Warning: Do not create a QDragLeaveEvent yourself since these objects rely on Qt's internal state.

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


QDragLeaveEvent Member List

Complete Member List for QDragLeaveEvent

This is the complete list of member functions for QDragLeaveEvent, including inherited members.

  • QDragLeaveEvent()
  • spontaneous()
  • type()


QDragMoveEvent Class

QDragMoveEvent Class Reference

The QDragMoveEvent class provides an event which is sent while a drag and drop is in progress. More...

#include <qevent.h>

Inherits QDropEvent.

Inherited by QDragEnterEvent.

List of all member functions.

Public Members

  • QDragMoveEvent ( const QPoint & pos, Type type = DragMove )
  • QRect answerRect () const
  • void accept ( const QRect & r )
  • void ignore ( const QRect & r )

Detailed Description

The QDragMoveEvent class provides an event which is sent while a drag and drop is in progress.

When a widget accepts drop events, it will receive this event repeatedly while the drag is within the widget's boundaries. The widget should examine the event to see what data it provides, and accept() the drop if appropriate.

Note that this class inherits most of its functionality from QDropEvent.

See also Drag And Drop Classes and Event Classes.

Member Function Documentation

QDragMoveEvent::QDragMoveEvent ( const QPoint & pos, Type type = DragMove )

Creates a QDragMoveEvent for which the mouse is at point pos, and the event is of type type.

Warning: Do not create a QDragMoveEvent yourself since these objects rely on Qt's internal state.

void QDragMoveEvent::accept ( const QRect & r )

The same as accept(), but also notifies that future moves will also be acceptable if they remain within the rectangle r on the widget: this can improve performance, but may also be ignored by the underlying system.

If the rectangle is empty, then drag move events will be sent continuously. This is useful if the source is scrolling in a timer event.

Examples: desktop/desktop.cpp and dirview/dirview.cpp.

QRect QDragMoveEvent::answerRect () const

Returns the rectangle for which the acceptance of the move event applies.

void QDragMoveEvent::ignore ( const QRect & r )

The opposite of accept(const QRect&), i.e. says that moves within rectangle r are not acceptable (will be ignored).

Example: dirview/dirview.cpp.

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


QDragMoveEvent Member List

Complete Member List for QDragMoveEvent

This is the complete list of member functions for QDragMoveEvent, including inherited members.

  • QDragMoveEvent()
  • accept()
  • acceptAction()
  • action()
  • answerRect()
  • data()
  • encodedData()
  • format()
  • ignore()
  • isAccepted()
  • isActionAccepted()
  • pos()
  • provides()
  • serialNumber()
  • setAction()
  • setPoint()
  • source()
  • spontaneous()
  • type()


QDragObject Class

QDragObject Class Reference

The QDragObject class encapsulates MIME-based data transfer. More...

#include <qdragobject.h>

Inherits QObject and QMimeSource.

Inherited by QStoredDrag, QTextDrag, QImageDrag and QIconDrag.

List of all member functions.

Public Members

  • QDragObject ( QWidget * dragSource = 0, const char * name = 0 )
  • virtual ~QDragObject ()
  • bool drag ()
  • bool dragMove ()
  • void dragCopy ()
  • void dragLink ()
  • virtual void setPixmap ( QPixmap pm )
  • virtual void setPixmap ( QPixmap pm, const QPoint & hotspot )
  • QPixmap pixmap () const
  • QPoint pixmapHotSpot () const
  • QWidget * source ()
  • enum DragMode { DragDefault, DragCopy, DragMove, DragLink, DragCopyOrMove }

Static Public Members

  • QWidget * target ()

Protected Members

  • virtual bool drag ( DragMode mode )

Detailed Description

The QDragObject class encapsulates MIME-based data transfer.

QDragObject is the base class for all data that needs to be transferred between and within applications, both for drag and drop and for the clipboard.

See the Drag-and-drop documentation for an overview of how to provide drag and drop in your application.

See the QClipboard documentation for an overview of how to provide cut-and-paste in your application.

The drag() function is used to start a drag operation. You can specify the DragMode in the call or use one of the convenience functions dragCopy(), dragMove() or dragLink(). The drag source where the data originated is retrieved with source(). If the data was dropped on a widget within the application, target() will return a pointer to that widget. Specify the pixmap to display during the drag with setPixmap().

See also Drag And Drop Classes.

Member Type Documentation

QDragObject::DragMode

This enum describes the possible drag modes.

  • QDragObject::DragDefault - The mode is determined heuristically.
  • QDragObject::DragCopy - The data is copied, never moved.
  • QDragObject::DragMove - The data is moved, if dragged at all.
  • QDragObject::DragLink - The data is linked, if dragged at all.
  • QDragObject::DragCopyOrMove - The user chooses the mode by using a control key to switch from the default.

Member Function Documentation

QDragObject::QDragObject ( QWidget * dragSource = 0, const char * name = 0 )

Constructs a drag object called name, which is a child of dragSource.

Note that the drag object will be deleted when dragSource is deleted.

QDragObject::~QDragObject () [virtual]

Destroys the drag object, canceling any drag and drop operation in which it is involved, and frees up the storage used.

bool QDragObject::drag ()

Starts a drag operation using the contents of this object, using DragDefault mode.

The function returns TRUE if the caller should delete the original copy of the dragged data (but see target()); otherwise returns FALSE.

If the drag contains references to information (e.g. file names in a QUriDrag are references) then the return value should always be ignored, as the target is expected to manipulate the referred-to content directly. On X11 the return value should always be correct anyway, but on Windows this is not necessarily the case (e.g. the file manager starts a background process to move files, so the source must not delete the files!)

Example: dirview/dirview.cpp.

bool QDragObject::drag ( DragMode mode ) [virtual protected]

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

Starts a drag operation using the contents of this object.

At this point, the object becomes owned by Qt, not the application. You should not delete the drag object or anything it references. The actual transfer of data to the target application will be done during future event processing - after that time the drag object will be deleted.

Returns TRUE if the dragged data was dragged as a move, indicating that the caller should remove the original source of the data (the drag object must continue to have a copy); otherwise returns FALSE.

The mode specifies the drag mode (see QDragObject::DragMode.) Normally one of the simpler drag(), dragMove(), or dragCopy() functions would be used instead.

Warning: in Qt 1.x, drag operations all return FALSE.

void QDragObject::dragCopy ()

Starts a drag operation using the contents of this object, using DragCopy mode. Be sure to read the constraints described in drag().

See also drag(), dragMove() and dragLink().

Example: iconview/simple_dd/main.cpp.

void QDragObject::dragLink ()

Starts a drag operation using the contents of this object, using DragLink mode. Be sure to read the constraints described in drag().

See also drag(), dragCopy() and dragMove().

bool QDragObject::dragMove ()

Starts a drag operation using the contents of this object, using DragMove mode. Be sure to read the constraints described in drag().

See also drag(), dragCopy() and dragLink().

QPixmap QDragObject::pixmap () const

Returns the currently set pixmap (which isNull() if none is set).

QPoint QDragObject::pixmapHotSpot () const

Returns the currently set pixmap hotspot.

void QDragObject::setPixmap ( QPixmap pm, const QPoint & hotspot ) [virtual]

Set the pixmap pm to display while dragging the object. The platform-specific implementation will use this where it can - so provide a small masked pixmap, and do not assume that the user will actually see it. For example, cursors on Windows 95 are of limited size.

The hotspot is the point on (or off) the pixmap that should be under the cursor as it is dragged. It is relative to the top-left pixel of the pixmap.

Example: fileiconview/qfileiconview.cpp.

void QDragObject::setPixmap ( QPixmap pm ) [virtual]

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

Uses a hotspot that positions the pixmap below and to the right of the mouse pointer. This allows the user to clearly see the point on the window which they are dragging the data onto.

QWidget * QDragObject::source ()

Returns a pointer to the drag source where this object originated.

QWidget * QDragObject::target () [static]

After the drag completes, this function will return the QWidget which received the drop, or 0 if the data was dropped on another application.

This can be useful for detecting the case where drag and drop is to and from the same widget.

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


qdragobject.h Include File

qdragobject.h

This is the verbatim text of the qdragobject.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qdragobject.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QDragObject
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDRAGOBJECT_H
#define QDRAGOBJECT_H

class QWidget;
class QTextDragPrivate;
class QDragObjectData;
class QStoredDragData;
class QImageDragData;

#ifndef QT_H
#include "qobject.h"
#include "qimage.h"
#include "qstrlist.h"
#include "qcolor.h"
#endif // QT_H

#ifndef QT_NO_MIME

class Q_EXPORT QDragObject: public QObject, public QMimeSource {
    Q_OBJECT
public:
    QDragObject( QWidget * dragSource = 0, const char * name = 0 );
    virtual ~QDragObject();

#ifndef QT_NO_DRAGANDDROP
    bool drag();
    bool dragMove();
    void dragCopy();
    void dragLink();

    virtual void setPixmap(QPixmap);
    virtual void setPixmap(QPixmap, const QPoint& hotspot);
    QPixmap pixmap() const;
    QPoint pixmapHotSpot() const;
#endif

    QWidget * source();
    static QWidget * target();

    static void setTarget(QWidget*);

#ifndef QT_NO_DRAGANDDROP
    enum DragMode { DragDefault, DragCopy, DragMove, DragLink, DragCopyOrMove };

protected:
    virtual bool drag(DragMode);
#endif

private:
    QDragObjectData * d;
};

class Q_EXPORT QStoredDrag: public QDragObject {
    Q_OBJECT
    QStoredDragData * d;

public:
    QStoredDrag( const char * mimeType,
         QWidget * dragSource = 0, const char * name = 0 );
    ~QStoredDrag();

    virtual void setEncodedData( const QByteArray & );

    const char * format(int i) const;
    virtual QByteArray encodedData(const char*) const;
};

class Q_EXPORT QTextDrag: public QDragObject {
    Q_OBJECT
    QTextDragPrivate* d;
public:
    QTextDrag( const QString &,
           QWidget * dragSource = 0, const char * name = 0 );
    QTextDrag( QWidget * dragSource = 0, const char * name = 0 );
    ~QTextDrag();

    virtual void setText( const QString &);
    virtual void setSubtype( const QCString &);

    const char * format(int i) const;
    virtual QByteArray encodedData(const char*) const;

    static bool canDecode( const QMimeSource* e );
    static bool decode( const QMimeSource* e, QString& s );
    static bool decode( const QMimeSource* e, QString& s, QCString& subtype );
};

class Q_EXPORT QImageDrag: public QDragObject {
    Q_OBJECT
    QImage img;
    QStrList ofmts;
    QImageDragData* d;

public:
    QImageDrag( QImage image, QWidget * dragSource = 0, const char * name = 0 );
    QImageDrag( QWidget * dragSource = 0, const char * name = 0 );
    ~QImageDrag();

    virtual void setImage( QImage image );

    const char * format(int i) const;
    virtual QByteArray encodedData(const char*) const;

    static bool canDecode( const QMimeSource* e );
    static bool decode( const QMimeSource* e, QImage& i );
    static bool decode( const QMimeSource* e, QPixmap& i );
};

class Q_EXPORT QUriDrag: public QStoredDrag {
    Q_OBJECT

public:
    QUriDrag( QStrList uris, QWidget * dragSource = 0, const char * name = 0 );
    QUriDrag( QWidget * dragSource = 0, const char * name = 0 );
    ~QUriDrag();

    void setFilenames( const QStringList & fnames ) { setFileNames( fnames ); }
    void setFileNames( const QStringList & fnames );
    void setUnicodeUris( const QStringList & uuris );
    virtual void setUris( QStrList uris );

    static QString uriToLocalFile(const char*);
    static QCString localFileToUri(const QString&);
    static QString uriToUnicodeUri(const char*);
    static QCString unicodeUriToUri(const QString&);
    static bool canDecode( const QMimeSource* e );
    static bool decode( const QMimeSource* e, QStrList& i );
    static bool decodeToUnicodeUris( const QMimeSource* e, QStringList& i );
    static bool decodeLocalFiles( const QMimeSource* e, QStringList& i );
};

class Q_EXPORT QColorDrag : public QStoredDrag
{
    Q_OBJECT
    QColor color;

public:
    QColorDrag( const QColor &col, QWidget *dragsource = 0, const char *name = 0 );
    QColorDrag( QWidget * dragSource = 0, const char * name = 0 );
    void setColor( const QColor &col );

    static bool canDecode( QMimeSource * );
    static bool decode( QMimeSource *, QColor &col );
};

#ifndef QT_NO_COMPAT
typedef QUriDrag QUrlDrag;
#endif

#ifndef QT_NO_DRAGANDDROP

// QDragManager is not part of the public API.  It is defined in a
// header file simply so different .cpp files can implement different
// member functions.
//

class Q_EXPORT QDragManager: public QObject {
    Q_OBJECT

private:
    QDragManager();
    ~QDragManager();
    // only friend classes can use QDragManager.
    friend class QDragObject;
    friend class QDragMoveEvent;
    friend class QDropEvent;

    bool eventFilter( QObject *, QEvent * );
    void timerEvent( QTimerEvent* );

    bool drag( QDragObject *, QDragObject::DragMode );

    void cancel( bool deleteSource = TRUE );
    void move( const QPoint & );
    void drop();
    void updatePixmap();

private:
    QDragObject * object;
    void updateMode( ButtonState newstate );
    void updateCursor();

    QWidget * dragSource;
    QWidget * dropWidget;
    bool beingCancelled;
    bool restoreCursor;
    bool willDrop;

    QPixmap *pm_cursor;
    int n_cursor;
};

#endif

#endif // QT_NO_MIME

#endif // QDRAGOBJECT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDragObject Member List

Complete Member List for QDragObject

This is the complete list of member functions for QDragObject, including inherited members.

  • QDragObject()
  • ~QDragObject()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setName()
  • setPixmap()
  • setProperty()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


qdrawutil.h Include File

qdrawutil.h

This is the verbatim text of the qdrawutil.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qdrawutil.h   3.0.5   edited Oct 12 2001 $
**
** Definition of draw utilities
**
** Created : 950920
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDRAWUTIL_H
#define QDRAWUTIL_H

#ifndef QT_H
#include "qnamespace.h"
#include "qstring.h" // char*->QString conversion
#endif // QT_H

class QPainter;
class QColorGroup;
class QPoint;
class QBrush;
class QRect;
class QPixmap;

#ifndef QT_NO_DRAWUTIL
//
// Standard shade drawing
//

Q_EXPORT
void qDrawShadeLine( QPainter *p, int x1, int y1, int x2, int y2,
             const QColorGroup &g, bool sunken = TRUE,
             int lineWidth = 1, int midLineWidth = 0 );

Q_EXPORT
void qDrawShadeLine( QPainter *p, const QPoint &p1, const QPoint &p2,
             const QColorGroup &g, bool sunken = TRUE,
             int lineWidth = 1, int midLineWidth = 0 );

Q_EXPORT
void qDrawShadeRect( QPainter *p, int x, int y, int w, int h,
             const QColorGroup &, bool sunken=FALSE,
             int lineWidth = 1, int midLineWidth = 0,
             const QBrush *fill = 0 );

Q_EXPORT
void qDrawShadeRect( QPainter *p, const QRect &r,
             const QColorGroup &, bool sunken=FALSE,
             int lineWidth = 1, int midLineWidth = 0,
             const QBrush *fill = 0 );

Q_EXPORT
void qDrawShadePanel( QPainter *p, int x, int y, int w, int h,
              const QColorGroup &, bool sunken=FALSE,
              int lineWidth = 1, const QBrush *fill = 0 );

Q_EXPORT
void qDrawShadePanel( QPainter *p, const QRect &r,
              const QColorGroup &, bool sunken=FALSE,
              int lineWidth = 1, const QBrush *fill = 0 );

Q_EXPORT
void qDrawWinButton( QPainter *p, int x, int y, int w, int h,
             const QColorGroup &g, bool sunken = FALSE,
             const QBrush *fill = 0 );

Q_EXPORT
void qDrawWinButton( QPainter *p, const QRect &r,
             const QColorGroup &g, bool sunken = FALSE,
             const QBrush *fill = 0 );

Q_EXPORT
void qDrawWinPanel( QPainter *p, int x, int y, int w, int h,
            const QColorGroup &, bool sunken=FALSE,
            const QBrush *fill = 0 );

Q_EXPORT
void qDrawWinPanel( QPainter *p, const QRect &r,
            const QColorGroup &, bool sunken=FALSE,
            const QBrush *fill = 0 );

Q_EXPORT
void qDrawPlainRect( QPainter *p, int x, int y, int w, int h, const QColor &,
             int lineWidth = 1, const QBrush *fill = 0 );

Q_EXPORT
void qDrawPlainRect( QPainter *p, const QRect &r, const QColor &,
             int lineWidth = 1, const QBrush *fill = 0 );

//
// Other obsolete drawing functions.
// Use QStyle::itemRect(), QStyle::drawItem() and QStyle::drawArrow() instead.
//
Q_EXPORT
QRect qItemRect( QPainter *p, Qt::GUIStyle gs, int x, int y, int w, int h,
        int flags, bool enabled,
        const QPixmap *pixmap, const QString& text, int len=-1 );

Q_EXPORT
void qDrawItem( QPainter *p, Qt::GUIStyle gs, int x, int y, int w, int h,
        int flags, const QColorGroup &g, bool enabled,
        const QPixmap *pixmap, const QString& text,
        int len=-1, const QColor* penColor = 0 );

Q_EXPORT
void qDrawArrow( QPainter *p, Qt::ArrowType type, Qt::GUIStyle style, bool down,
         int x, int y, int w, int h,
         const QColorGroup &g, bool enabled );

#endif // QT_NO_DRAWUTIL
#endif // QDRAWUTIL_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDropEvent Class

QDropEvent Class Reference

The QDropEvent class provides an event which is sent when a drag and drop is completed. More...

#include <qevent.h>

Inherits QEvent and QMimeSource.

Inherited by QDragMoveEvent.

List of all member functions.

Public Members

  • QDropEvent ( const QPoint & pos, Type typ = Drop )
  • const QPoint & pos () const
  • bool isAccepted () const
  • void accept ( bool y = TRUE )
  • void ignore ()
  • bool isActionAccepted () const
  • void acceptAction ( bool y = TRUE )
  • enum Action { Copy, Link, Move, Private, UserAction = 100 }
  • void setAction ( Action a )
  • Action action () const
  • QWidget * source () const
  • virtual const char * format ( int n = 0 ) const
  • virtual QByteArray encodedData ( const char * format ) const
  • virtual bool provides ( const char * mimeType ) const
  • QByteArray data ( const char * f ) const (obsolete)
  • void setPoint ( const QPoint & np )

Detailed Description

The QDropEvent class provides an event which is sent when a drag and drop is completed.

When a widget accepts drop events, it will receive this event if it has accepted the most recent QDragEnterEvent or QDragMoveEvent sent to it.

The widget should use data() to extract the data in an appropriate format.

See also Drag And Drop Classes and Event Classes.

Member Type Documentation

QDropEvent::Action

This enum describes the action which a source requests that a target perform with dropped data.

  • QDropEvent::Copy - The default action. The source simply uses the data provided in the operation.
  • QDropEvent::Link - The source should somehow create a link to the location specified by the data.
  • QDropEvent::Move - The source should somehow move the object from the location specified by the data to a new location.
  • QDropEvent::Private - The target has special knowledge of the MIME type, which the source should respond to in a similar way to a Copy.
  • QDropEvent::UserAction - The source and target can co-operate using special actions. This feature is not currently supported.

The Link and Move actions only makes sense if the data is a reference, for example, text/uri-list file lists (see QUriDrag).

Member Function Documentation

QDropEvent::QDropEvent ( const QPoint & pos, Type typ = Drop )

Constructs a drop event that drops a drop of type typ on point pos.

void QDropEvent::accept ( bool y = TRUE )

Call this function to indicate whether the event provided data which your widget processed. Set y to TRUE (the default) if your widget could process the data, otherwise set y to FALSE. To get the data, use encodedData(), or preferably, the decode() methods of existing QDragObject subclasses, such as QTextDrag::decode(), or your own subclasses.

Warning: To accept or reject the drop, don't call this function, call acceptAction() instead. This function indicates whether you processed the event at all.

See also acceptAction().

Example: iconview/simple_dd/main.cpp.

void QDropEvent::acceptAction ( bool y = TRUE )

Call this to indicate that the action described by action() is accepted (i.e. if y is TRUE, which is the default), not merely the default copy action. If you call acceptAction(TRUE), there is no need to also call accept(TRUE).

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

Action QDropEvent::action () const

Returns the Action which the target is requesting to be performed with the data. If your application understands the action and can process the supplied data, call acceptAction(); if your application can process the supplied data but can only perform the Copy action, call accept().

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

QByteArray QDropEvent::data ( const char * f ) const

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

Use QDropEvent::encodedData().

QByteArray QDropEvent::encodedData ( const char * format ) const [virtual]

Returns a byte array containing the drag's data, in format.

data() normally needs to get the data from the drag source, which is potentially very slow, so it's advisable to call this function only if you're sure that you will need the data in format.

The resulting data will have a size of 0 if the format was not available.

See also format() and QByteArray::size().

Reimplemented from QMimeSource.

const char * QDropEvent::format ( int n = 0 ) const [virtual]

Returns a string describing one of the available data types for this drag. Common examples are "text/plain" and "image/gif". If n is less than zero or greater than the number of available data types, format() returns 0.

This function is provided mainly for debugging. Most drop targets will use provides().

See also data() and provides().

Example: iconview/main.cpp.

Reimplemented from QMimeSource.

void QDropEvent::ignore ()

The opposite of accept(), i.e. you have ignored the drop event.

Example: fileiconview/qfileiconview.cpp.

bool QDropEvent::isAccepted () const

Returns TRUE if the drop target accepts the event; otherwise returns FALSE.

bool QDropEvent::isActionAccepted () const

Returns TRUE if the drop action was accepted by the drop site; otherwise returns FALSE.

const QPoint & QDropEvent::pos () const

Returns the position where the drop was made.

Example: dirview/dirview.cpp.

bool QDropEvent::provides ( const char * mimeType ) const [virtual]

Returns TRUE if this event provides format mimeType; otherwise returns FALSE.

See also data().

Example: fileiconview/qfileiconview.cpp.

Reimplemented from QMimeSource.

void QDropEvent::setAction ( Action a )

Sets the action to a. This is used internally, you should not need to call this in your code: the source decides the action, not the target.

void QDropEvent::setPoint ( const QPoint & np )

Sets the drop to happen at point np. You do not normally need to use this as it will be set internally before your widget receives the drop event.

QWidget * QDropEvent::source () const

If the source of the drag operation is a widget in this application, this function returns that source, otherwise it returns 0. The source of the operation is the first parameter to drag object subclasses.

This is useful if your widget needs special behavior when dragging to itself, etc.

See QDragObject::QDragObject() and subclasses.

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


QDropEvent Member List

Complete Member List for QDropEvent

This is the complete list of member functions for QDropEvent, including inherited members.

  • QDropEvent()
  • accept()
  • acceptAction()
  • action()
  • data()
  • encodedData()
  • format()
  • ignore()
  • isAccepted()
  • isActionAccepted()
  • pos()
  • provides()
  • serialNumber()
  • setAction()
  • setPoint()
  • source()
  • spontaneous()
  • type()


QDropSite Class

QDropSite Class Reference
[obsolete]

The QDropSite class provides nothing and does nothing. More...

#include <qdropsite.h>

List of all member functions.

Public Members

  • QDropSite ( QWidget * self )
  • virtual ~QDropSite ()

Detailed Description

The QDropSite class provides nothing and does nothing.

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

If your code uses it, you can safely delete it.

It was used in Qt 1.x to do some drag and drop; that has since been folded into QWidget.

For detailed information about drag-and-drop, see the QDragObject class.

See also QDragObject, QTextDrag and QImageDrag.

Member Function Documentation

QDropSite::QDropSite ( QWidget * self )

Constructs a QDropSite to handle events for the widget self.

Pass this as the self parameter. This enables dropping by calling QWidget::setAcceptDrops(TRUE).

QDropSite::~QDropSite () [virtual]

Destroys the drop site.

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


qdropsite.h Include File

qdropsite.h

This is the verbatim text of the qdropsite.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qdropsite.h   3.0.5   edited Oct 12 2001 $
**
** Definitation of Drag and Drop support
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QDROPSITE_H
#define QDROPSITE_H

#ifndef QT_H
#ifndef QT_H
#include "qglobal.h"
#endif // QT_H
#endif

class QWidget;

class Q_EXPORT QDropSite {
public:
    QDropSite( QWidget* parent );
    virtual ~QDropSite();
};

#endif  // QDROPSITE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QDropSite Member List

Complete Member List for QDropSite

This is the complete list of member functions for QDropSite, including inherited members.

  • QDropSite()
  • ~QDropSite()


QEditorFactory Class

QEditorFactory Class Reference

The QEditorFactory class is used to create editor widgets for QVariant data types. More...

#include <qeditorfactory.h>

Inherits QObject.

Inherited by QSqlEditorFactory.

List of all member functions.

Public Members

  • QEditorFactory ( QObject * parent = 0, const char * name = 0 )
  • ~QEditorFactory ()
  • virtual QWidget * createEditor ( QWidget * parent, const QVariant & v )

Static Public Members

  • QEditorFactory * defaultFactory ()
  • void installDefaultFactory ( QEditorFactory * factory )

Detailed Description

The QEditorFactory class is used to create editor widgets for QVariant data types.

Each editor factory provides the createEditor() function which given a QVariant will create and return a QWidget that can edit that QVariant. For example if you have a QVariant::String type, a QLineEdit would be the default editor returned, whereas a QVariant::Int's default editor would be a QSpinBox.

If you want to create different editors for fields with the same data type, subclass QEditorFactory and reimplement the createEditor() function.

See also Advanced Widgets.

Member Function Documentation

QEditorFactory::QEditorFactory ( QObject * parent = 0, const char * name = 0 )

Constructs an editor factory with parent parent and name name.

QEditorFactory::~QEditorFactory ()

Destroys the object and frees any allocated resources.

QWidget * QEditorFactory::createEditor ( QWidget * parent, const QVariant & v ) [virtual]

Creates and returns the appropriate editor for the QVariant v. If the QVariant is invalid, 0 is returned. The parent is passed to the appropriate editor's constructor.

Reimplemented in QSqlEditorFactory.

QEditorFactory * QEditorFactory::defaultFactory () [static]

Returns an instance of a default editor factory.

void QEditorFactory::installDefaultFactory ( QEditorFactory * factory ) [static]

Replaces the default editor factory with factory. QEditorFactory takes ownership of factory, and destroys it when it is no longer needed.

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


qeditorfactory.h Include File

qeditorfactory.h

This is the verbatim text of the qeditorfactory.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QEditorFactory class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QEDITORFACTORY_H
#define QEDITORFACTORY_H

#ifndef QT_H
#include "qobject.h"
#include "qvariant.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QM_EXPORT_SQL QEditorFactory : public QObject
{
public:
    QEditorFactory ( QObject * parent = 0, const char * name = 0 );
    ~QEditorFactory();

    virtual QWidget * createEditor( QWidget * parent, const QVariant & v );

    static QEditorFactory * defaultFactory();
    static void installDefaultFactory( QEditorFactory * factory);
};

#endif // QT_NO_SQL
#endif // QEDITORFACTORY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QEditorFactory Member List

Complete Member List for QEditorFactory

This is the complete list of member functions for QEditorFactory, including inherited members.

  • QEditorFactory()
  • ~QEditorFactory()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • createEditor()
  • customEvent()
  • defaultFactory()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installDefaultFactory()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QEmbed - File and Image Embedder

The QEmbed tool, found in qt/tools/qembed, converts arbitrary files into C++ code. This is useful for including image files and other resources directly into your application rather than loading the data from external files.

QEmbed can also generate uncompressed versions of images that can be included directly into your application, thus avoiding both the external file and the need to parse the image file format. This is useful for small images such as icons for which compression is not a great gain.

Usage

    qembed [ general-files ] [ --images image-files ]

  • general-files

    These files can be any type of file.

  • --images image-files

    These files must be in image formats supported by Qt.

Output

The output from QEmbed is a C++ header file which you should include in a C++ source file. In the source file, you should make a wrapper function that suits your application. Two functions are provided; your wrapper function could just call one of these, or you can implement your own. Here's a simple example of usage for each of the supplied functions:

qembed_findImage()

    #include "generated_qembed_file.h"

    QImage myFindImage(const char* name)
    {
        return qembed_findImage(name);
    }

Just call the generated function; name is the original image filename without the extension.

qembed_findData()
    #include "generated_qembed_file.h"

    QByteArray myFindData(const char* name)
    {
        return qembed_findData(name);
    }

Just call the generated function; name is the original filename with the extension

Alternatively, look at the output from QEmbed and write a function tailored to your needs.


QErrorMessage类

QErrorMessage类参考

QErrorMessage类提供了错误消息显示对话框。 详情请见……

#include <qerrormessage.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • QErrorMessage ( QWidget * parent, const char * name = 0 )
  • ~QErrorMessage ()

公有槽

  • void message ( const QString & m )

静态公有成员

  • QErrorMessage * qtHandler ()

详细描述

QErrorMessage类提供了错误消息显示对话框。

基本上是QLabel和记住什么不显示的“show this message again”检查框。

这里是使用这个类的两种方法：

  1. 对于产品应用程序。在这种情况下，这个类可以用来显示你不需要用户看到超过一次的信息。像这样使用QErrorMessage，你用手工的方式创建对话框并且调用message()槽，或者把信号和它连接起来。

  2. 对于开发人员。在这种情况下，静态的qtHandler()使用qInstallMsgHandler()安装一个消息处理器并且创建一个用来显示qDebug()、qWarning()和qFatal()的QErrorMessage。

在这两种情况下，QErrorMessage将把没有处理的信息排队，并且按顺序显示它们（或者不显示），只要用户在看到每一条消息之后按下Enter或者点击OK。

也可以参考QMessageBox、QStatusBar::message()、对话框类和杂项类。

成员函数文档

QErrorMessage::QErrorMessage ( QWidget * parent, const char * name = 0 )

构造并安装一个错误处理器窗口。父对象parent和名称name都被传递给QDialog的构造函数。

QErrorMessage::~QErrorMessage ()

销毁这个对象并且释放任何已经分配的资源。特别地，“do not show again”消息列表也被删除。

void QErrorMessage::message ( const QString & m ) [槽]

显示消息m并且立即返回。如果用户要求m不被显示，这个函数将什么都不做。

通常，m只被立即显示，但是如果存在未处理的消息，m将被排到队列中，稍后会显示。

QErrorMessage * QErrorMessage::qtHandler () [静态]

返回输出默认Qt消息的QErrorMessage对象的指针。如果没有这样的对象存在，这个函数创建一个这样的对象。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qerrormessage.h包含文件

qerrormessage.h

这里是qerrormessage.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qerrormessage.h   3.0.5   edited Oct 12 2001 $
**
** Definition of a nice qInstallErrorMessage() handler
**
** Created : 2000-05-27, after Kalle Dalheimer's birthday
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QERRORHANDLER_H
#define QERRORHANDLER_H

#ifndef QT_H
#include "qdialog.h"
#endif // QT_H

#ifndef QT_NO_ERRORMESSAGE
class QPushButton;
class QCheckBox;
class QLabel;
class QTextView;
class QStringList;
template<class type> class QDict;

class Q_EXPORT QErrorMessage: public QDialog {
    Q_OBJECT
public:
    QErrorMessage( QWidget* parent, const char* name=0 );
    ~QErrorMessage();

    static QErrorMessage * qtHandler();

public slots:
    void message( const QString & );

protected:
    void done( int );

private:
    QPushButton * ok;
    QCheckBox * again;
    QTextView * errors;
    QLabel * icon;
    QStringList * pending;
    QDict<int> * doNotShow;

    bool nextPending();
};

#endif //QT_NO_ERRORMESSAGE

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QErrorMessage成员列表

完整的QErrorMessage成员列表

这里是QErrorMessage成员函数的完整列表，包括继承的成员。

  • QErrorMessage()
  • ~QErrorMessage()
  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • message()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • qtHandler()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QEucJpCodec Class

QEucJpCodec Class Reference

The QEucJpCodec class provides conversion to and from EUC-JP character sets. More...

#include <qeucjpcodec.h>

Inherits QTextCodec.

List of all member functions.

Public Members

  • virtual int mibEnum () const
  • virtual const char * mimeName () const
  • QEucJpCodec ()
  • ~QEucJpCodec ()

Detailed Description

The QEucJpCodec class provides conversion to and from EUC-JP character sets.

More precisely, the QEucJpCodec class subclasses QTextCodec to provide support for EUC-JP, the main legacy encoding for Unix machines in Japan.

The environment variable UNICODEMAP_JP can be used to fine-tune QJisCodec, QSjisCodec and QEucJpCodec. The QJisCodec documentation describes how to use this variable.

Most of the code here was written by Serika Kurusugawa, a.k.a. Junji Takagi, and is included in Qt with the author's permission and the grateful thanks of the Trolltech team. Here is the copyright statement for that code:

Copyright (c) 1999 Serika Kurusugawa. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS". ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

Member Function Documentation

QEucJpCodec::QEucJpCodec ()

Constructs a QEucJpCodec.

QEucJpCodec::~QEucJpCodec ()

Destroys the codec.

int QEucJpCodec::mibEnum () const [virtual]

Returns 18.

Reimplemented from QTextCodec.

const char * QEucJpCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


qeucjpcodec.h Include File

qeucjpcodec.h

This is the verbatim text of the qeucjpcodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qeucjpcodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QEucJpCodec class
**
** Created : 990225
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

// Most of the code here was originally written by Serika Kurusugawa
// a.k.a. Junji Takagi, and is include in Qt with the author's permission,
// and the grateful thanks of the Trolltech team.

/*
 * Copyright (c) 1999 Serika Kurusugawa, All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef QEUCJPCODEC_H
#define QEUCJPCODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#include "qjpunicode.h"
#endif // QT_H

#ifndef QT_NO_BIG_CODECS

#if defined(QT_PLUGIN)
#define Q_EXPORT_CODECS_JP
#else
#define Q_EXPORT_CODECS_JP Q_EXPORT
#endif

class Q_EXPORT_CODECS_JP QEucJpCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;

    QEucJpCodec();
    ~QEucJpCodec();

protected:
    const QJpUnicodeConv *conv;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QEucJpCodec Member List

Complete Member List for QEucJpCodec

This is the complete list of member functions for QEucJpCodec, including inherited members.

  • QEucJpCodec()
  • ~QEucJpCodec()
  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QEucKrCodec Class

QEucKrCodec Class Reference

The QEucKrCodec class provides conversion to and from EUC-KR character sets. More...

#include <qeuckrcodec.h>

Inherits QTextCodec.

List of all member functions.

Public Members

  • virtual const char * mimeName () const

Detailed Description

The QEucKrCodec class provides conversion to and from EUC-KR character sets.

The QEucKrCodec class subclasses QTextCodec to provide support for EUC-KR, the main legacy encoding for UNIX machines in Korea.

It was largely written by Mizi Research Inc. Here is the copyright statement for the code as it was at the point of contribution (Trolltech's subsequent modifications are covered by the usual copyright for Qt.)

Copyright (c) 1999 Mizi Research Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

Member Function Documentation

const char * QEucKrCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


qeuckrcodec.h Include File

qeuckrcodec.h

This is the verbatim text of the qeuckrcodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qeuckrcodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QEucKrCodec class
**
** Created : 990303
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

/*
 * Copyright (c) 1999-2000 Mizi Research Inc., All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef QEUCKRCODEC_H
#define QEUCKRCODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#endif // QT_H

#ifndef QT_NO_BIG_CODECS

#if defined(QT_PLUGIN)
#define Q_EXPORT_CODECS_KR
#else
#define Q_EXPORT_CODECS_KR Q_EXPORT
#endif

class Q_EXPORT_CODECS_KR QEucKrCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QEucKrCodec Member List

Complete Member List for QEucKrCodec

This is the complete list of member functions for QEucKrCodec, including inherited members.

  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QEvent类

QEvent类参考

QEvent类是所有事件类的基类。事件类包含事件参数。 详情请见……

#include <qevent.h>

继承了Qt。

由QTimerEvent、QMouseEvent、QWheelEvent、QTabletEvent、QKeyEvent、QFocusEvent、QPaintEvent、QMoveEvent、QResizeEvent、QCloseEvent、QShowEvent、QHideEvent、QContextMenuEvent、QIMEvent、QDropEvent、QDragLeaveEvent、QChildEvent和QCustomEvent继承。

所有成员函数的列表。

公有成员

  • enum Type { None = 0, Timer = 1, MouseButtonPress = 2, MouseButtonRelease = 3, MouseButtonDblClick = 4, MouseMove = 5, KeyPress = 6, KeyRelease = 7, FocusIn = 8, FocusOut = 9, Enter = 10, Leave = 11, Paint = 12, Move = 13, Resize = 14, Create = 15, Destroy = 16, Show = 17, Hide = 18, Close = 19, Quit = 20, Reparent = 21, ShowMinimized = 22, ShowNormal = 23, WindowActivate = 24, WindowDeactivate = 25, ShowToParent = 26, HideToParent = 27, ShowMaximized = 28, ShowFullScreen = 29, Accel = 30, Wheel = 31, AccelAvailable = 32, CaptionChange = 33, IconChange = 34, ParentFontChange = 35, ApplicationFontChange = 36, ParentPaletteChange = 37, ApplicationPaletteChange = 38, PaletteChange = 39, Clipboard = 40, Speech = 42, SockAct = 50, AccelOverride = 51, DeferredDelete = 52, DragEnter = 60, DragMove = 61, DragLeave = 62, Drop = 63, DragResponse = 64, ChildInserted = 70, ChildRemoved = 71, LayoutHint = 72, ShowWindowRequest = 73, ActivateControl = 80, DeactivateControl = 81, ContextMenu = 82, IMStart = 83, IMCompose = 84, IMEnd = 85, Accessibility = 86, Tablet = 87, User = 1000, MaxUser = 65535 } (obsolete)
  • QEvent ( Type type )
  • Type type () const
  • bool spontaneous () const

详细描述

QEvent类是所有事件类的基类。事件类包含事件参数。

Qt的主事件回路（QApplication::exec()）从事件队列里取得本地窗口系统事件，并把它们转换为QEvent并且把这些转换过的事件发给QObject。

通常情况下，来自于窗口系统的事件（spontaneous()返回真），但是它也可以使用QApplication::sendEvent()和QApplication::postEvent()手动发送事件（spontaneous()返回假）。

QObject通过它们的QObject::event()函数调用来接收事件。这个函数可以在子类中重新实现来处理自定义的事件和添加额外的事件类型，QWidget::event()就是一个著名的例子。默认情况下，像QObject::timerEvent()和QWidget::mouseMoveEvent()这样的事件可以被发送给事件处理函数。QObject::installEventFilter()允许一个对象中途截取发往另一个对象的事件。

基本的QEvent只包含了一个事件类型参数。QEvent的子类包含了额外的描述特定事件的参数。

也可以参考QObject::event()、QObject::installEventFilter()、QWidget::event()、QApplication::sendEvent()、a href="qapplication.html#postEvent">QApplication::postEvent()、QApplication::processEvents()、Environment Classes和事件类。

成员类型文档

QEvent::Type

这个枚举类型定义了Qt中有效的事件类型。事件类型和每个类型的专门类如下：

  • QEvent::None - 不是一个事件。
  • QEvent::Accessibility - 可存取性信息被请求。
  • QEvent::Timer - 规则的定时器事件，QTimerEvent。
  • QEvent::MouseButtonPress - 鼠标按下，QMouseEvent。
  • QEvent::MouseButtonRelease - 鼠标抬起，QMouseEvent。
  • QEvent::MouseButtonDblClick - 鼠标再次按下，a href="qmouseevent.html">QMouseEvent。
  • QEvent::MouseMove - 鼠标移动，QMouseEvent。
  • QEvent::KeyPress - 键按下（举例，包括Shift）QKeyEvent。
  • QEvent::KeyRelease - 键抬起，QKeyEvent。
  • QEvent::IMStart - 输入法写作开始。
  • QEvent::IMCompose - 发生输入法写作。
  • QEvent::IMEnd - 输入法写作结束。
  • QEvent::FocusIn - 窗口部件获得键盘焦点，QFocusEvent。
  • QEvent::FocusOut - 窗口部件失去键盘焦点，QFocusEvent。
  • QEvent::Enter - 鼠标进入窗口部件边缘。
  • QEvent::Leave - 鼠标离开窗口部件边缘。
  • QEvent::Paint - 屏幕更新所需要的，QPaintEvent。
  • QEvent::Move - 窗口部件位置改变了，QMoveEvent。
  • QEvent::Resize - 窗口部件大小改变了，QResizeEvent。
  • QEvent::Show - 窗口部件被显示到屏幕上，QShowEvent。
  • QEvent::Hide - 窗口部件被隐藏，QHideEvent。
  • QEvent::ShowToParent - 一个子窗口部件被显示。
  • QEvent::HideToParent - 一个子窗口部件被隐藏。
  • QEvent::Close - 窗口部件被关闭（永久性地） QCloseEvent。
  • QEvent::ShowNormal - 窗口部件应该按通常模式显示。
  • QEvent::ShowMaximized - 窗口部件应该按最大化模式显示。
  • QEvent::ShowMinimized - 窗口部件应该按最小化模式显示。
  • QEvent::ShowFullScreen - 窗口部件应该按全屏模式显示。
  • QEvent::ShowWindowRequest - 窗口部件窗口应该被显示。这个类型是废弃的。它的提供是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。
  • QEvent::DeferredDelete - 在这个对象被清理干净之后，它将被删除。
  • QEvent::Accel - 孩子中的键按下，用于快捷键处理。QKeyEvent。
  • QEvent::Wheel - 鼠标滚轮转动，QWheelEvent。
  • QEvent::ContextMenu - 上下文弹出菜单，QContextMenuEvent。
  • QEvent::AccelAvailable - 在一些平台上Qt使用的内部事件。
  • QEvent::AccelOverride - Key press in child, for overriding shortcut key handling, QKeyEvent.
  • QEvent::WindowActivate - 窗口被激活了。
  • QEvent::WindowDeactivate - 窗口被停用了。
  • QEvent::CaptionChange - 窗口部件的标题改变了。
  • QEvent::IconChange - 窗口部件的图标改变了。
  • QEvent::ParentFontChange - 父窗口部件的字体改变了。
  • QEvent::ApplicationFontChange - 默认的应用程序字体改变了。
  • QEvent::PaletteChange - 窗口部件的调色板改变了。
  • QEvent::ParentPaletteChange - 父窗口部件的调色板改变了。
  • QEvent::ApplicationPaletteChange - 默认的应用程序调色板改变了。
  • QEvent::Clipboard - 剪贴板内容发生改变，QClipboard。
  • QEvent::SockAct - 套接字触发，通常在QSocketNotifier中实现。
  • QEvent::DragEnter - 一个拖拽进入了一个窗口部件，QDragEnterEvent。
  • QEvent::DragMove - 一个拖拽正在进行中，QDragMoveEvent。
  • QEvent::DragLeave - 一个拖拽离开了窗口部件，QDragLeaveEvent。
  • QEvent::Drop - 一个拖拽完成了，QDropEvent。
  • QEvent::DragResponse - 在一些平台上Qt使用的内部事件。
  • QEvent::ChildInserted - 对象得到了一个孩子，QChildEvent。
  • QEvent::ChildRemoved - 对象失去了一个孩子，QChildEvent。
  • QEvent::LayoutHint - 窗口部件孩子改变了布局属性。
  • QEvent::ActivateControl - 在一些平台上Qt使用的内部事件。
  • QEvent::DeactivateControl - 在一些平台上Qt使用的内部事件。
  • QEvent::Quit - 保留的。
  • QEvent::Create - 保留的。
  • QEvent::Destroy - 保留的。
  • QEvent::Reparent - 保留的。
  • QEvent::Speech - 为语音输入而保留的。
  • QEvent::Tablet - Wacom Tablet事件。
  • QEvent::User - 用户定义事件。
  • QEvent::MaxUser - 最后用户事件id。

用户事件应该包含User和MaxUser值。

成员函数文档

QEvent::QEvent ( Type type )

构造一个类型为type的事件对象。

bool QEvent::spontaneous () const

如果事件由应用程序之外产生的，比如一个系统事件，返回真，否则返回假。

Type QEvent::type () const

返回事件类型。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qevent.h包含文件

qevent.h

这里是qevent.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qevent.h   3.0.5   edited Oct 12 2001 $
**
** Definition of event classes
**
** Created : 931029
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QEVENT_H
#define QEVENT_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qregion.h"
#include "qnamespace.h"
#include "qmime.h"
#include "qpair.h"
#endif // QT_H

class Q_EXPORT QEvent: public Qt		// event base class
{
public:
    enum Type {

    // NOTE: if you get a strange compiler error on the line with "None",
    //       it's probably because you're trying to include X11, which
    //	 has a mess of #defines in it.  Put the messy X11 includes
    //	 *AFTER* the nice clean Qt includes.

    None = 0,				// invalid event

    Timer = 1,				// timer event
    MouseButtonPress = 2,			// mouse button pressed
    MouseButtonRelease = 3,			// mouse button released
    MouseButtonDblClick= 4,			// mouse button double click
    MouseMove = 5,				// mouse move
    KeyPress = 6,				// key pressed
    KeyRelease = 7,				// key released
    FocusIn = 8,				// keyboard focus received
    FocusOut = 9,				// keyboard focus lost
    Enter = 10,				// mouse enters widget
    Leave = 11,				// mouse leaves widget
    Paint = 12,				// paint widget
    Move = 13,				// move widget
    Resize = 14,				// resize widget
    Create = 15,				// after object creation
    Destroy = 16,				// during object destruction
    Show = 17,				// widget is shown
    Hide = 18,				// widget is hidden
    Close = 19,				// request to close widget
    Quit = 20,				// request to quit application
    Reparent = 21,				// widget has been reparented
    ShowMinimized = 22,		       	// widget is shown minimized
    ShowNormal = 23,	       		// widget is shown normal
    WindowActivate = 24,	       		// window was activated
    WindowDeactivate = 25,	       		// window was deactivated
    ShowToParent = 26,	       		// widget is shown to parent
    HideToParent = 27,	       		// widget is hidden to parent
    ShowMaximized = 28,		       	// widget is shown maximized
    ShowFullScreen = 29,			// widget is shown full-screen
    Accel = 30,				// accelerator event
    Wheel = 31,				// wheel event
    AccelAvailable = 32,			// accelerator available event
    CaptionChange = 33,			// caption changed
    IconChange = 34,			// icon changed
    ParentFontChange = 35,			// parent font changed
    ApplicationFontChange = 36,		// application font changed
    ParentPaletteChange = 37,		// parent palette changed
    ApplicationPaletteChange = 38,		// application palette changed
    PaletteChange = 39,			// widget palette changed
    Clipboard = 40,				// internal clipboard event
    Speech = 42,				// reserved for speech input
    SockAct = 50,				// socket activation
    AccelOverride = 51,			// accelerator override event
    DeferredDelete = 52,			// deferred delete event
    DragEnter = 60,				// drag moves into widget
    DragMove = 61,				// drag moves in widget
    DragLeave = 62,				// drag leaves or is cancelled
    Drop = 63,				// actual drop
    DragResponse = 64,			// drag accepted/rejected
    ChildInserted = 70,			// new child widget
    ChildRemoved = 71,			// deleted child widget
    LayoutHint = 72,			// child min/max size changed
    ShowWindowRequest = 73,			// widget's window should be mapped
    ActivateControl = 80,			// ActiveX activation
    DeactivateControl = 81,			// ActiveX deactivation
    ContextMenu = 82,                       // context popup menu
    IMStart = 83,				// input method composition start
    IMCompose = 84,				// input method composition
    IMEnd = 85,				// input method composition end
    Accessibility = 86,			// accessibility information is requested
    Tablet = 87,				// Wacom Tablet Event
    User = 1000,				// first user event id
    MaxUser  = 65535                        // last user event id
    };

    QEvent( Type type ) : t(type), posted(FALSE), spont(FALSE) {}
    virtual ~QEvent();
    Type  type() const	{ return t; }
    bool spontaneous() const 	{ return spont; }
protected:
    Type  t;
private:
    uint posted : 1;
    uint spont : 1;

    friend class QApplication;
    friend class QBaseApplication;
    friend class QETWidget;
};

class Q_EXPORT QTimerEvent : public QEvent
{
public:
    QTimerEvent( int timerId )
    : QEvent(Timer), id(timerId) {}
    int	  timerId()	const	{ return id; }
protected:
    int	  id;
};

class Q_EXPORT QMouseEvent : public QEvent
{
public:
    QMouseEvent( Type type, const QPoint &pos, int button, int state );

    QMouseEvent( Type type, const QPoint &pos, const QPoint&globalPos,
         int button, int state )
    : QEvent(type), p(pos), g(globalPos), b((ushort)button),s((ushort)state),accpt(TRUE) {};

    const QPoint &pos() const	{ return p; }
    const QPoint &globalPos() const { return g; }
    int	   x()		const	{ return p.x(); }
    int	   y()		const	{ return p.y(); }
    int	   globalX()	const	{ return g.x(); }
    int	   globalY()	const	{ return g.y(); }
    ButtonState button() const	{ return (ButtonState) b; }
    ButtonState state()	const	{ return (ButtonState) s; }
    ButtonState stateAfter() const;
    bool   isAccepted() const	{ return accpt; }
    void   accept()		{ accpt = TRUE; }
    void   ignore()		{ accpt = FALSE; }
protected:
    QPoint p;
    QPoint g;
    ushort b;
    ushort s;
    uint   accpt:1;
};

#ifndef QT_NO_WHEELEVENT
class Q_EXPORT QWheelEvent : public QEvent
{
public:
    QWheelEvent( const QPoint &pos, int delta, int state, Orientation orient = Vertical );
    QWheelEvent( const QPoint &pos, const QPoint& globalPos, int delta, int state, Orientation orient = Vertical  )
    : QEvent(Wheel), p(pos), g(globalPos), d(delta), s((ushort)state),
      accpt(TRUE), o(orient) {}
    int	   delta()	const	{ return d; }
    const QPoint &pos() const	{ return p; }
    const QPoint &globalPos() const	{ return g; }
    int	   x()		const	{ return p.x(); }
    int	   y()		const	{ return p.y(); }
    int	   globalX()	const	{ return g.x(); }
    int	   globalY()	const	{ return g.y(); }
    ButtonState state()	const	{ return ButtonState(s); }
    Orientation orientation() 	const 	{ return o; }
    bool   isAccepted() const	{ return accpt; }
    void   accept()		{ accpt = TRUE; }
    void   ignore()		{ accpt = FALSE; }
protected:
    QPoint p;
    QPoint g;
    int d;
    ushort s;
    bool   accpt;
    Orientation o;
};
#endif

class Q_EXPORT QTabletEvent : public QEvent
{
public:
    enum TabletDevice { NoDevice = -1, Puck, Stylus, Eraser };
    QTabletEvent( const QPoint &pos, int device, int pressure, int xTilt,
                  int yTilt, const QPair<int,int> &uId )
    : QEvent( Tablet ), mPos( pos ), mDev( device ), mPress( pressure ),
      mXT( xTilt ), mYT( yTilt ), mType( uId.first ), mPhy( uId.second )
    {}
    QTabletEvent( const QPoint &pos, const QPoint &globalPos, int device,
          int pressure, int xTilt, int yTilt, const QPair<int,int> &uId )
    : QEvent( Tablet ), mPos( pos ), mGPos( globalPos ), mDev( device ),
      mPress( pressure ), mXT( xTilt ), mYT( yTilt ), mType( uId.first ),
      mPhy( uId.second )
    {}
    int pressure()	const { return mPress; }
    int xTilt()		const { return mXT; }
    int yTilt()		const { return mYT; }
    const QPoint &pos()	const { return mPos; }
    const QPoint &globalPos() const { return mGPos; }
    int x()		const { return mPos.x(); }
    int y()		const { return mPos.y(); }
    int globalX()	const { return mGPos.x(); }
    int globalY()	const { return mGPos.y(); }
    TabletDevice device() 	const { return TabletDevice(mDev); }
    int isAccepted() const { return mbAcc; }
    void accept() { mbAcc = TRUE; }
    void ignore() { mbAcc = FALSE; }
    QPair<int,int> uniqueId() { return QPair<int,int>( mType, mPhy); }
protected:
    QPoint mPos;
    QPoint mGPos;
    int mDev,
        mPress,
        mXT,
        mYT,
        mType,
    mPhy;
    bool mbAcc;

};

class Q_EXPORT QKeyEvent : public QEvent
{
public:
    QKeyEvent( Type type, int key, int ascii, int state,
        const QString& text=QString::null, bool autorep=FALSE, ushort count=1 )
    : QEvent(type), txt(text), k((ushort)key), s((ushort)state),
        a((uchar)ascii), accpt(TRUE), autor(autorep), c(count) {}
    int	   key()	const	{ return k; }
    int	   ascii()	const	{ return a; }
    ButtonState state()	const	{ return ButtonState(s); }
    ButtonState stateAfter() const;
    bool   isAccepted() const	{ return accpt; }
    QString text()      const   { return txt; }
    bool   isAutoRepeat() const	{ return autor; }
    int   count() const	{ return int(c); }
    void   accept()		{ accpt = TRUE; }
    void   ignore()		{ accpt = FALSE; }

protected:
    QString txt;
    ushort k, s;
    uchar  a;
    uint   accpt:1;
    uint   autor:1;
    ushort c;
};

class Q_EXPORT QFocusEvent : public QEvent
{
public:

    QFocusEvent( Type type )
    : QEvent(type) {}

    bool   gotFocus()	const { return type() == FocusIn; }
    bool   lostFocus()	const { return type() == FocusOut; }

    enum Reason { Mouse, Tab, Backtab, ActiveWindow, Popup, Shortcut, Other };
    static Reason reason();
    static void setReason( Reason reason );
    static void resetReason();

private:
    static Reason m_reason;
    static Reason prev_reason;
};

class Q_EXPORT QPaintEvent : public QEvent
{
public:
    QPaintEvent( const QRegion& paintRegion, bool erased = TRUE)
    : QEvent(Paint),
      rec(paintRegion.boundingRect()),
      reg(paintRegion),
      erase(erased){}
    QPaintEvent( const QRect &paintRect, bool erased = TRUE )
    : QEvent(Paint),
      rec(paintRect),
      reg(paintRect),
      erase(erased){}
    const QRect &rect() const	  { return rec; }
    const QRegion &region() const { return reg; }
    bool erased() const { return erase; }
protected:
    friend class QApplication;
    friend class QBaseApplication;
    QRect rec;
    QRegion reg;
    bool erase;
};

class Q_EXPORT QMoveEvent : public QEvent
{
public:
    QMoveEvent( const QPoint &pos, const QPoint &oldPos )
    : QEvent(Move), p(pos), oldp(oldPos) {}
    const QPoint &pos()	  const { return p; }
    const QPoint &oldPos()const { return oldp;}
protected:
    QPoint p, oldp;
    friend class QApplication;
    friend class QBaseApplication;
};

class Q_EXPORT QResizeEvent : public QEvent
{
public:
    QResizeEvent( const QSize &size, const QSize &oldSize )
    : QEvent(Resize), s(size), olds(oldSize) {}
    const QSize &size()	  const { return s; }
    const QSize &oldSize()const { return olds;}
protected:
    QSize s, olds;
    friend class QApplication;
    friend class QBaseApplication;
};

class Q_EXPORT QCloseEvent : public QEvent
{
public:
    QCloseEvent()
    : QEvent(Close), accpt(FALSE) {}
    bool   isAccepted() const	{ return accpt; }
    void   accept()		{ accpt = TRUE; }
    void   ignore()		{ accpt = FALSE; }
protected:
    bool   accpt;
};

class Q_EXPORT QShowEvent : public QEvent
{
public:
    QShowEvent()
    : QEvent(Show) {}
};

class Q_EXPORT QHideEvent : public QEvent
{
public:
    QHideEvent()
    : QEvent(Hide) {}
};

class Q_EXPORT QContextMenuEvent : public QEvent
{
public:
    enum Reason { Mouse, Keyboard, Other };
    QContextMenuEvent( Reason reason, const QPoint &pos, const QPoint &globalPos, int state )
    : QEvent( ContextMenu ), p( pos ), gp( globalPos ), accpt( FALSE ), consum(FALSE),
    reas( reason ), s((ushort)state) {}
    QContextMenuEvent( Reason reason, const QPoint &pos, int state );

    int	    x() const { return p.x(); }
    int	    y() const { return p.y(); }
    int	    globalX() const { return gp.x(); }
    int	    globalY() const { return gp.y(); }

    const QPoint&   pos() const { return p; }
    const QPoint&   globalPos() const { return gp; }

    ButtonState state()	const	{ return (ButtonState) s; }
    bool    isAccepted() const	{ return accpt; }
    bool    isConsumed() const  { return consum; }
    void    consume()           { consum = TRUE; }
    void    accept()		{ accpt = TRUE; consum = TRUE; }
    void    ignore()		{ accpt = FALSE; consum = FALSE; }

    Reason  reason() const { return Reason( reas ); }

protected:
    QPoint  p;
    QPoint  gp;
    bool    accpt;
    bool    consum;
    uint    reas:8;
    ushort s;
};

class Q_EXPORT QIMEvent : public QEvent
{
public:
    QIMEvent( Type type, const QString &text, int cursorPosition )
    : QEvent(type), txt(text), cpos(cursorPosition), a(FALSE) {}
    const QString &text() const { return txt; }
    int cursorPos() const { return cpos; }
    bool isAccepted() const { return a; }
    void accept() { a = TRUE; }
    void ignore() { a = FALSE; }
private:
    QString txt;
    int cpos;
    bool a;
};

#ifndef QT_NO_DRAGANDDROP

// This class is rather closed at the moment.  If you need to create your
// own DND event objects, write to qt-bugs@trolltech.com and we'll try to
// find a way to extend it so it covers your needs.

class Q_EXPORT QDropEvent : public QEvent, public QMimeSource
{
public:
    QDropEvent( const QPoint& pos, Type typ=Drop )
    : QEvent(typ), p(pos),
      act(0), accpt(0), accptact(0), resv(0),
      d(0)
    {}
    const QPoint &pos() const	{ return p; }
    bool isAccepted() const	{ return accpt || accptact; }
    void accept(bool y=TRUE)	{ accpt = y; }
    void ignore()		{ accpt = FALSE; }

    bool isActionAccepted() const { return accptact; }
    void acceptAction(bool y=TRUE) { accptact = y; }
    enum Action { Copy, Link, Move, Private, UserAction=100 };
    void setAction( Action a ) { act = (uint)a; }
    Action action() const { return Action(act); }

    QWidget* source() const;
    const char* format( int n = 0 ) const;
    QByteArray encodedData( const char* ) const;
    bool provides( const char* ) const;

    QByteArray data(const char* f) const { return encodedData(f); }

    void setPoint( const QPoint& np ) { p = np; }

protected:
    QPoint p;
    uint act:8;
    uint accpt:1;
    uint accptact:1;
    uint resv:5;
    void * d;
};

class Q_EXPORT QDragMoveEvent : public QDropEvent
{
public:
    QDragMoveEvent( const QPoint& pos, Type typ=DragMove )
    : QDropEvent(pos,typ),
      rect( pos, QSize( 1, 1 ) ) {}
    QRect answerRect() const { return rect; }
    void accept( bool y=TRUE ) { QDropEvent::accept(y); }
    void accept( const QRect & r) { accpt = TRUE; rect = r; }
    void ignore( const QRect & r) { accpt =FALSE; rect = r; }
    void ignore()		{ QDropEvent::ignore(); }

protected:
    QRect rect;
};

class Q_EXPORT QDragEnterEvent : public QDragMoveEvent
{
public:
    QDragEnterEvent( const QPoint& pos ) :
    QDragMoveEvent(pos, DragEnter) { }
};

/* An internal class */
class Q_EXPORT QDragResponseEvent : public QEvent
{
public:
    QDragResponseEvent( bool accepted )
    : QEvent(DragResponse), a(accepted) {}
    bool   dragAccepted() const	{ return a; }
protected:
    bool a;
};

class Q_EXPORT QDragLeaveEvent : public QEvent
{
public:
    QDragLeaveEvent()
    : QEvent(DragLeave) {}
};

#endif // QT_NO_DRAGANDDROP

class Q_EXPORT QChildEvent : public QEvent
{
public:
    QChildEvent( Type type, QObject *child )
    : QEvent(type), c(child) {}
    QObject *child() const	{ return c; }
    bool inserted() const { return t == ChildInserted; }
    bool removed() const { return t == ChildRemoved; }
protected:
    QObject *c;
};

class Q_EXPORT QCustomEvent : public QEvent
{
public:
    QCustomEvent( int type );
    QCustomEvent( Type type, void *data )
    : QEvent(type), d(data) {};
    void       *data()	const	{ return d; }
    void	setData( void* data )	{ d = data; }
private:
    void       *d;
};

#endif // QEVENT_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QEvent成员列表

完整的QEvent成员列表

这里是QEvent成员函数的完整列表，包括继承的成员。

  • QEvent()
  • spontaneous()
  • type()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Font Displayer

This example program displays all characters of a font.

Header file:

/****************************************************************************
** $Id:  qt/fontdisplayer.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef FontDisplayer_H
#define FontDisplayer_H

#include <qframe.h>
#include <qmainwindow.h>

class QSlider;

class FontRowTable : public QFrame {
    Q_OBJECT
public:
    FontRowTable( QWidget* parent=0, const char* name=0 );

    QSize sizeHint() const;

signals:
    void fontInformation(const QString&);

public slots:
    void setRow(int);
    void chooseFont();

protected:
    QSize cellSize() const;
    void paintEvent( QPaintEvent* );
private:
    QFont tablefont;
    int row;
};

class FontDisplayer : public QMainWindow {
    Q_OBJECT
public:
    FontDisplayer( QWidget* parent=0, const char* name=0 );
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/fontdisplayer.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "fontdisplayer.h"
#include <qapplication.h>
#include <qslider.h>
#include <qspinbox.h>
#include <qpainter.h>
#include <qtoolbar.h>
#include <qstatusbar.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qfontdialog.h>
#include <stdlib.h>

FontRowTable::FontRowTable( QWidget* parent, const char* name ) :
    QFrame(parent,name)
{
    setBackgroundMode(PaletteBase);
    setFrameStyle(Panel|Sunken);
    setMargin(8);
    setRow(0);
    tablefont = QApplication::font();
}

QSize FontRowTable::sizeHint() const
{
    return 16*cellSize()+QSize(2,2)*(margin()+frameWidth());
}

QSize FontRowTable::cellSize() const
{
    QFontMetrics fm = fontMetrics();
    return QSize( fm.maxWidth(), fm.lineSpacing()+1 );
}

void FontRowTable::paintEvent( QPaintEvent* e )
{
    QFrame::paintEvent(e);
    QPainter p(this);
    p.setClipRegion(e->region());
    QRect r = e->rect();
    QFontMetrics fm = fontMetrics();
    int ml = frameWidth()+margin() + 1 + QMAX(0,-fm.minLeftBearing());
    int mt = frameWidth()+margin();
    QSize cell((width()-15-ml)/16,(height()-15-mt)/16);

    if ( !cell.width() || !cell.height() )
        return;

    int mini = r.left() / cell.width();
    int maxi = (r.right()+cell.width()-1) / cell.width();
    int minj = r.top() / cell.height();
    int maxj = (r.bottom()+cell.height()-1) / cell.height();

    int h = fm.height();

    QColor body(255,255,192);
    QColor negative(255,192,192);
    QColor positive(192,192,255);
    QColor rnegative(255,128,128);
    QColor rpositive(128,128,255);

    for (int j = minj; j<=maxj; j++) {
        for (int i = mini; i<=maxi; i++) {
            if ( i < 16 && j < 16 ) {
                int x = i*cell.width();
                int y = j*cell.height();

                QChar ch = QChar(j*16+i,row);

                if ( fm.inFont(ch) ) {
                    int w = fm.width(ch);
                    int l = fm.leftBearing(ch);
                    int r = fm.rightBearing(ch);

                    x += ml;
                    y += mt+h;

                    p.fillRect(x,y,w,-h,body);
                    if ( w ) {
                        if ( l ) {
                            p.fillRect(x+(l>0?0:l), y-h/2, abs(l),-h/2,
                                       l < 0 ? negative : positive);
                        }
                        if ( r ) {
                            p.fillRect(x+w-(r>0?r:0),y+2, abs(r),-h/2,
                                       r < 0 ? rnegative : rpositive);
                        }
                    }
                    QString s;
                    s += ch;
                    p.setPen(QPen(Qt::black));
                    p.drawText(x,y,s);
                }
            }
        }
    }
}

void FontRowTable::setRow(int r)
{
    row = r;

    QFontMetrics fm = fontMetrics();
    QString str;
    str.sprintf("mLB=%d mRB=%d mW=%d",
        fm.minLeftBearing(),
        fm.minRightBearing(),
        fm.maxWidth()
        );

    emit fontInformation(str);
    update();
}

void FontRowTable::chooseFont()
{
    bool ok;
    QFont oldfont = tablefont;
    tablefont = QFontDialog::getFont(&ok, oldfont, this);

    if (ok)
        setFont(tablefont);
    else
        tablefont = oldfont;

}

FontDisplayer::FontDisplayer( QWidget* parent, const char* name ) :
    QMainWindow(parent,name)
{
    FontRowTable* table = new FontRowTable(this);
    QToolBar* controls = new QToolBar(this);
    (void) new QLabel(tr("Row:"), controls);
    QSpinBox *row = new QSpinBox(0,255,1,controls);
    controls->addSeparator();
    QPushButton *fontbutton = new QPushButton(tr("Font..."), controls);

    connect(row,SIGNAL(valueChanged(int)),table,SLOT(setRow(int)));
    connect(fontbutton, SIGNAL(clicked()), table, SLOT(chooseFont()));
    connect(table,SIGNAL(fontInformation(const QString&)),
            statusBar(),SLOT(message(const QString&)));
    table->setRow(0);
    setCentralWidget(table);
}

Main:

/****************************************************************************
** $Id:  qt/qfd.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "fontdisplayer.h"

#include <qapplication.h>
#include <qslider.h>
#include <qpainter.h>
#include <qstatusbar.h>

int main(int argc, char** argv)
{
    // Use an interesting font
    QApplication::setFont(QFont("unifont",16));

    QApplication app(argc,argv);

    FontDisplayer m;
    QSize sh = m.centralWidget()->sizeHint();
    m.resize(sh.width(),
             sh.height()+3*m.statusBar()->height());
    app.setMainWidget(&m);
    m.setCaption("Qt Example - QFD");
    m.show();

    return app.exec();
}

See also Examples.


QFile类

QFile类参考

QFile类是一个操作文件的输入/输出设备。 详情请见……

#include <qfile.h>

继承了 QIODevice。

所有成员函数的列表。

公有成员

  • QFile ()
  • QFile ( const QString & name )
  • ~QFile ()
  • QString name () const
  • void setName ( const QString & name )
  • typedef QCString (* EncoderFn ) ( const QString & fileName )
  • typedef QString (* DecoderFn ) ( const QCString & localfileName )
  • bool exists () const
  • bool remove ()
  • virtual bool open ( int m )
  • bool open ( int m, FILE * f )
  • bool open ( int m, int f )
  • virtual void close ()
  • virtual void flush ()
  • virtual Offset size () const
  • virtual Offset at () const
  • virtual bool at ( Offset pos )
  • virtual bool atEnd () const
  • virtual Q_LONG readBlock ( char * p, Q_ULONG len )
  • virtual Q_LONG readLine ( char * p, Q_ULONG maxlen )
  • Q_LONG readLine ( QString & s, Q_ULONG maxlen )
  • virtual int getch ()
  • virtual int putch ( int ch )
  • virtual int ungetch ( int ch )
  • int handle () const

静态公有成员

  • QCString encodeName ( const QString & fileName )
  • QString decodeName ( const QCString & localFileName )
  • void setEncodingFunction ( EncoderFn f )
  • void setDecodingFunction ( DecoderFn f )
  • bool exists ( const QString & fileName )
  • bool remove ( const QString & fileName )

重要的继承成员

  • virtual QByteArray readAll ()

详细描述

QFile类是一个操作文件的输入/输出设备。

QFile是用来读写二进制文件和文本文件的输入/输出设备。QFile可以自己单独被使用，但是如果和QDataStream或QTextStream一起使用将更加方便。

文件名通常可以通过构造函数来传递，但也可以使用setName()来设置。你可以通过exists()来检查一个文件是否存在并且可以通过remove()来移去一个文件。

文件可以用open()来打开、用close()来关闭、用flush()来刷新。数据通常可以使用QDataStream或者QTextStream进行读写，但你也可以使用readBlock()和readLine()来读，使用writeBlock()来写。QFile也支持getch()、 ungetch()和putch()。

size()可以返回文件的大小。你可以通过使用at()函数得到当前文件位置或者移到一个新的文件位置。如果你到了文件的末尾，atEnd()返回真。handle()返回文件句柄。

这里是一个使用QTextStream来一行一行地读取一个文本文件的代码段。它会把每一行带上一个行号打印出来。

    QStringList lines;
    QFile file( "file.txt" );
    if ( file.open( IO_ReadOnly ) ) {
        QTextStream stream( &file );
        QString line;
        int n = 1;
        while ( !stream.eof() ) {
            line = stream.readLine(); // 不包括“\n”的一行文本
            printf( "%3d: %s\n", n++, line.latin1() );
            lines += line;
        }
        file.close();
    }

写文本也很容易（假设我们有一个行的字符串列表要写）：

    QFile file( "file.txt" );
    if ( file.open( IO_WriteOnly ) ) {
        QTextStream stream( &file );
        for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
            stream << *it << "\n";
        file.close();
    }

QFileInfo类控制文件的详细信息，比如访问权限、文件日期和文件类型。

QDir类管理目录和文件名列表。

Qt使用Unicode文件名。如果你想在Unix系统上使用你自己的输入/输出，你可以使用encodeName()（和decodeName()）来把文件名转换为本地编码。

也可以参考QDataStream、QTextStream和输入/输出和网络。

成员类型文档

QFile::DecoderFn

被QFile::setDecodingFunction()使用。

QFile::EncoderFn

被QFile::setEncodingFunction()使用。

成员函数文档

QFile::QFile ()

构造一个没有名称的QFile。

QFile::QFile ( const QString & name )

构造一个文件名为name的QFile。

也可以参考setName()。

QFile::~QFile ()

析构QFile。调用close()。

bool QFile::at ( Offset pos ) [虚]

设置文件索引到pos。如果成功，返回真，否则返回假。

实例：

    QFile f( "data.bin" );
    f.open( IO_ReadOnly );                      // 索引设置为0
    f.at( 100 );                                // 设置索引为100
    f.at( f.at()+50 );                          // 设置索引为150
    f.at( f.size()-80 );                        // 设置索引为EOF之前的80
    f.close();

不带参数使用at()可以重新得到文件的位移。

警告：如果文件是使用IO_Append方式打开（open()）的话，结果是未定义的。

也可以参考size()和open()。

从QIODevice中重新实现的。

Offset QFile::at () const [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回文件中的位置。

也可以参考size()。

从QIODevice中重新实现的。

bool QFile::atEnd () const [虚]

如果到达文件的末尾，返回真，否则返回假。

也可以参考size()。

从QIODevice中重新实现的。

void QFile::close () [虚]

关闭一个打开的文件。

如果一个文件是使用一个存在的文件句柄打开的，那么它不是关闭的。如果这个存在的文件句柄是一个FILE*，这个文件被刷新。如果这个存在的文件句柄是一个int文件描述符，那么对这个文件将没有操作。

一些“在后面写的”文件系统也许会在关闭文件时报告一个未详细说明的错误。这些错误只表明在上一次打开（open()）之后也许发生了一些错误。在这种情况下，status()会在关闭之后（close()）报告IO_UnspecifiedError，否则是IO_Ok。

也可以参考open()和flush()。

实例：application/application.cpp、chart/chartform_files.cpp、helpviewer/helpwindow.cpp、mdi/application.cpp、qdir/qdir.cpp、qwerty/qwerty.cpp和xml/outliner/outlinetree.cpp。

从QIODevice中重新实现的。

QString QFile::decodeName ( const QCString & localFileName ) [静态]

这个将会使用localFileName做与QFile::encodeName()相反的操作。

也可以参考setDecodingFunction()。

QCString QFile::encodeName ( const QString & fileName ) [静态]

当你使用QFile时，在Qt中QFileInfo和QDir访问文件系统，你可以使用Unicode文件名。在Unix上，这些文件名被转换为8位的编码。如果你想在Unix上使用你自己的文件输入/输出，你应该使用这个函数来转换文件名。在Windows NT上，Unicode文件名在文件系统中是直接被支持的并且这个函数应该避免使用。在Windows 95上，在这时候非Latin1的场所设置是不被支持的。

默认情况下，这个函数把fileName转换为本地的8位编码，这取决于用户的场所设置。对于用户选择的文件名这足够了。应用程序中的文件名硬编码只是需要使用7位ASCII文件名字符。

这种转换方案可以使用setEncodingFunction()来改变。如果你需要给用户一个存储文件名为utf-8等等情况下，这也许很有用，但是这些文件名可能在这之后对其它应用程序来说是不可识别的。

也可以参考decodeName()。

bool QFile::exists ( const QString & fileName ) [静态]

如果给定的文件fileName存在，返回真，否则返回假。

实例：chart/chartform.cpp、dirview/dirview.cpp和helpviewer/helpwindow.cpp。

bool QFile::exists () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果这个文件存在，返回真，否则返回假。

也可以参考name()。

void QFile::flush () [虚]

刷新文件缓存到磁盘。

close()也刷新文件缓存。

从QIODevice中重新实现的。

int QFile::getch () [虚]

从文件中读取一个单字节/字符。

返回所读的字节/字符，如果到达文件的末尾，返回-1。

也可以参考putch()和ungetch()。

从QIODevice中重新实现的。

int QFile::handle () const

返回这个文件的文件句柄。

如果是一个小的正整数，可以用在像fdopen()和fcntl()这样的C库函数中，也可以用在QSocketNotifier中。

如果这个文件没有被打开或者存在错误，handle()返回-1。

也可以参考QSocketNotifier。

QString QFile::name () const

返回由setName()设置的名称。

也可以参考setName()和QFileInfo::fileName()。

bool QFile::open ( int m ) [虚]

使用m模式和当前指定的文件名打开文件。如果成功，返回真，否则返回假。

模式参数m必须是下列标记的组合：

  • IO_Raw 指定直接的（非缓存的）文件访问。
  • IO_ReadOnly 以只读模式打开文件。
  • IO_WriteOnly 以只写模式（并且截短）打开文件。
  • IO_ReadWrite 以读/写模式打开文件，等于(IO_ReadOnly | IO_WriteOnly)。
  • IO_Append 以附加的模式打开文件。当你想向日志文件写些东西时这个模式非常有用。文件索引被设置到文件末尾。注意如果你在附加模式中使用at()定位文件索引，结果将是为定义的。
  • IO_Truncate 截短文件。
  • IO_Translate 在MS-DOS、Windows和OS/2下对文本文件翻译回车和换行。

直接访问模式在输入/输出的块操作使用4千字节或更大的情况下使用最好。当每次读小量数据时，缓存访问工作的更好。

重要：当使用缓存的文件工作时，数据没有被立刻写到文件中。调用flush()可以确保数据被真正地写完。

警告：如果你有一个缓存文件以同时读写方式打开，你不要在一次输入操作之后立即输出，反之亦然。你必须在输入和输出操作之间调用flush()或者一次文件定位操作，比如seek()，否则缓存中可能会包含无用信息。

如果文件不存在并且指定IO_WriteOnly或IO_ReadWrite时，文件被创建。

实例：

    QFile f1( "/tmp/data.bin" );
    QFile f2( "readme.txt" );
    f1.open( IO_Raw | IO_ReadWrite | IO_Append );
    f2.open( IO_ReadOnly | IO_Translate );

也可以参考name()、 close()、isOpen()和flush()。

实例：action/application.cpp、application/application.cpp、chart/chartform_files.cpp、helpviewer/helpwindow.cpp、qdir/qdir.cpp、qwerty/qwerty.cpp和xml/outliner/outlinetree.cpp。

从QIODevice中重新实现的。

bool QFile::open ( int m, FILE * f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用m模式和一个存在的文件句柄f打开文件。如果成功，返回真，否则返回假。

实例：

    #include <stdio.h>

    void printError( const char* msg )
    {
        QFile f;
        f.open( IO_WriteOnly, stderr );
        f.writeBlock( msg, qstrlen(msg) );      // 写到标准错误输出（stderr）
        f.close();
    }

当使用这个函数打开一个QFile时，close()并不真正关闭这个文件，只是刷新它。

警告：如果f是标准输入（stdin）、标准输出（stdout）、标准错误输出（stderr），你也许不能搜索。更详细的信息请看QIODevice::isSequentialAccess()。

也可以参考close()。

bool QFile::open ( int m, int f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用m模式和一个存在的文件描述符f打开文件。如果成功，返回真，否则返回假。

当使用这个函数打开一个QFile时，close()并不真正关闭这个文件。

使用这个函数打开一个QFile时，它被自动设置为直接模式，这就意味着文件输入/输出函数是慢的。如果你需要更好的执行效率，请你试着使用其它打开函数。

警告：如果f是0（stdin）、1（stdout）或2（stderr）其中之一时，你也许不能搜索。size()被设置为INT_MAX（在limits.h文件中）。

也可以参考close()。

int QFile::putch ( int ch ) [虚]

写字符ch到文件。

返回ch，或者如果发生错误，返回-1。

也可以参考getch()和ungetch()。

从QIODevice中重新实现的。

QByteArray QIODevice::readAll () [虚]

这个方便的函数返回这个设备中的所有剩余数据。

Q_LONG QFile::readBlock ( char * p, Q_ULONG len ) [虚]

从这个文件中读取最多maxlen字节到p并且返回实际读取的字节数量。

如果发生严重错误，返回-1。

警告：当一个缓存文件为了读写而打开时，我们已经在使用一些C库时遇到了问题。如果在一个写操作后立即执行一个读操作，读缓存中就会包含无用信息。更可怕的是，一些无用信息被写到文件中。在readBlock()之前调用flush()就可以解决这个问题。

也可以参考writeBlock()。

实例：qwerty/qwerty.cpp。

从QIODevice中重新实现的。

Q_LONG QFile::readLine ( char * p, Q_ULONG maxlen ) [虚]

读一行文本。

从这个文本中读取最多maxlen字节或者行结束符到p，哪个先发生以哪个为准。返回实际读取的字节数量，或者如果发生错误，返回-1。换行将不会被省略。

这个函数只对缓存文件有效。避免在以IO_Raw标记方式打开的文件中使用readLine()。

也可以参考readBlock()和QTextStream::readLine()。

从QIODevice中重新实现的。

Q_LONG QFile::readLine ( QString & s, Q_ULONG maxlen )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

读一行文本。

从这个文本中读取最多maxlen字节或者行结束符到字符串s，哪个先发生以哪个为准。返回实际读取的字节数量，或者如果发生错误，返回-1。换行将不会被省略。

这个函数只对缓存文件有效。避免在以IO_Raw标记方式打开的文件中使用readLine()。

注意这个字符串只能作为无格式的Latin1字节来读，不是Unicode。

也可以参考readBlock()和QTextStream::readLine()。

bool QFile::remove ()

移去当前指定文件名的文件。如果成功，返回真，否则返回假。

在文件被移去之前，它被关闭。

bool QFile::remove ( const QString & fileName ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

移去文件fileName。如果成功，返回真，否则返回假。

void QFile::setDecodingFunction ( DecoderFn f ) [静态]

设置8位文件名的译码函数位f。默认使用本地指定的8位编码。

也可以参考encodeName()和decodeName()。

void QFile::setEncodingFunction ( EncoderFn f ) [静态]

设置Unicode文件名的编码函数为f。默认使用本地指定的8位编码。

也可以参考encodeName()。

void QFile::setName ( const QString & name )

设置文件的名称为name。这个名称可以不包含路径，也可以包含相对路径或者绝对路径。

如果文件已经被打开，不要调用这个函数。

如果文件名没有路径或者使用相对路径，这是使用的路径就是应用程序在调用open()的时候的当前路径。

实例：

     QFile f;
     QDir::setCurrent( "/tmp" );
     f.setName( "readme.txt" );
     QDir::setCurrent( "/home" );
     f.open( IO_ReadOnly );        // 在Unix下打开“/home/readme.txt”

注意Qt支持在所有的操作系统中使用目录分隔符“/”。

也可以参卡name()、QFileInfo和QDir。

Offset QFile::size () const [虚]

返回文件大小。

也可以参考at()。

实例：table/statistics/statistics.cpp。

从QIODevice中重新实现的。

int QFile::ungetch ( int ch ) [虚]

把字符ch放回到这个文件中并且如果索引位置不是零的话，减一。

这个函数正常地被调用就是“撤销”getch()操作。

返回ch，否则，如果发生错误，返回-1。

也可以参考getch()和putch()。

从QIODevice中重新实现的。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qfile.h包含文件

qfile.h

这里是qfile.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qfile.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QFile class
**
** Created : 930831
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFILE_H
#define QFILE_H

#ifndef QT_H
#include "qiodevice.h"
#include "qstring.h"
#include <stdio.h>
#endif // QT_H

class QDir;

class Q_EXPORT QFile : public QIODevice			// file I/O device class
{
public:
    QFile();
    QFile( const QString &name );
   ~QFile();

    QString	name()	const;
    void	setName( const QString &name );

    typedef QCString (*EncoderFn)( const QString &fileName );
    typedef QString (*DecoderFn)( const QCString &localfileName );
    static QCString encodeName( const QString &fileName );
    static QString decodeName( const QCString &localFileName );
    static void setEncodingFunction( EncoderFn );
    static void setDecodingFunction( DecoderFn );

    bool	exists()   const;
    static bool exists( const QString &fileName );

    bool	remove();
    static bool remove( const QString &fileName );

    bool	open( int );
    bool	open( int, FILE * );
    bool	open( int, int );
    void	close();
    void	flush();

    Offset	size() const;
    Offset	at() const;
    bool	at( Offset );
    bool	atEnd() const;

    Q_LONG	readBlock( char *data, Q_ULONG len );
    Q_LONG	writeBlock( const char *data, Q_ULONG len );
    Q_LONG	writeBlock( const QByteArray& data )
              { return QIODevice::writeBlock(data); }
    Q_LONG	readLine( char *data, Q_ULONG maxlen );
    Q_LONG	readLine( QString &, Q_ULONG maxlen );

    int		getch();
    int		putch( int );
    int		ungetch( int );

    int		handle() const;

protected:
    QString	fn;
    FILE       *fh;
    int		fd;
    Offset	length;
    bool	ext_f;
    void * 	d;

private:
    void	init();
    QCString	ungetchBuffer;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QFile( const QFile & );
    QFile &operator=( const QFile & );
#endif
};

inline QString QFile::name() const
{ return fn; }

inline QIODevice::Offset QFile::at() const
{ return ioIndex; }

#endif // QFILE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFile成员列表

完整的QFile成员列表

这里是QFile成员函数的完整列表，包括继承的成员。

  • QFile()
  • ~QFile()
  • at()
  • atEnd()
  • close()
  • decodeName()
  • encodeName()
  • exists()
  • flags()
  • flush()
  • getch()
  • handle()
  • isAsynchronous()
  • isBuffered()
  • isCombinedAccess()
  • isDirectAccess()
  • isInactive()
  • isOpen()
  • isRaw()
  • isReadWrite()
  • isReadable()
  • isSequentialAccess()
  • isSynchronous()
  • isTranslated()
  • isWritable()
  • mode()
  • name()
  • open()
  • putch()
  • readAll()
  • readBlock()
  • readLine()
  • remove()
  • reset()
  • resetStatus()
  • setDecodingFunction()
  • setEncodingFunction()
  • setName()
  • size()
  • state()
  • status()
  • ungetch()
  • writeBlock()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFileDialog类

QFileDialog类参考

QFileDialog类提供了允许用户选择文件或者目录的对话框。 详情请见……

#include <qfiledialog.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • QFileDialog ( const QString & dirName, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, bool modal = FALSE )
  • QFileDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE )
  • ~QFileDialog ()
  • QString selectedFile () const
  • QString selectedFilter () const
  • virtual void setSelectedFilter ( const QString & mask )
  • virtual void setSelectedFilter ( int n )
  • void setSelection ( const QString & filename )
  • void selectAll ( bool b )
  • QStringList selectedFiles () const
  • QString dirPath () const
  • void setDir ( const QDir & dir )
  • const QDir * dir () const
  • void setShowHiddenFiles ( bool s )
  • bool showHiddenFiles () const
  • void rereadDir ()
  • void resortDir ()
  • enum Mode { AnyFile, ExistingFile, Directory, ExistingFiles, DirectoryOnly }
  • void setMode ( Mode )
  • Mode mode () const
  • enum ViewMode { Detail, List }
  • enum PreviewMode { NoPreview, Contents, Info }
  • void setViewMode ( ViewMode m )
  • ViewMode viewMode () const
  • void setPreviewMode ( PreviewMode m )
  • PreviewMode previewMode () const
  • bool isInfoPreviewEnabled () const
  • bool isContentsPreviewEnabled () const
  • void setInfoPreviewEnabled ( bool )
  • void setContentsPreviewEnabled ( bool )
  • void setInfoPreview ( QWidget * w, QFilePreview * preview )
  • void setContentsPreview ( QWidget * w, QFilePreview * preview )
  • QUrl url () const
  • void addFilter ( const QString & filter )

公有槽

  • void setDir ( const QString & pathstr )
  • void setUrl ( const QUrlOperator & url )
  • void setFilter ( const QString & newFilter )
  • void setFilters ( const QString & filters )
  • void setFilters ( const char ** types )
  • void setFilters ( const QStringList & )

信号

  • void fileHighlighted ( const QString & )
  • void fileSelected ( const QString & )
  • void filesSelected ( const QStringList & )
  • void dirEntered ( const QString & )
  • void filterSelected ( const QString & )

静态公有函数

  • QString getOpenFileName ( const QString & startWith = QString::null, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE )
  • QString getSaveFileName ( const QString & startWith = QString::null, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE )
  • QString getExistingDirectory ( const QString & dir = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, bool dirOnly = TRUE, bool resolveSymlinks = TRUE )
  • QStringList getOpenFileNames ( const QString & filter = QString::null, const QString & dir = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE )
  • void setIconProvider ( QFileIconProvider * provider )
  • QFileIconProvider * iconProvider ()

属性

  • bool contentsPreview - 文件对话框是否提供当前选择文件的内容预览
  • QString dirPath - 文件对话框的工作目录 （只读）
  • bool infoPreview - 文件对话框是否提供当前选择文件的信息预览
  • Mode mode - 文件对话框的模式
  • PreviewMode previewMode - 文件的对话框的预览模式
  • QString selectedFile - 选择的文件的名称 （只读）
  • QStringList selectedFiles - 选择的文件的列表 （只读）
  • QString selectedFilter - 文件对话框中用户选择文件的过滤器 （只读）
  • bool showHiddenFiles - 文件对话框中隐藏文件是否显示
  • ViewMode viewMode - 文件对话框的视图模式

保护成员

  • void addWidgets ( QLabel * l, QWidget * w, QPushButton * b )
  • void addToolButton ( QButton * b, bool separator = FALSE )
  • void addLeftWidget ( QWidget * w )
  • void addRightWidget ( QWidget * w )

详细描述

QFileDialog类提供了允许用户选择文件或者目录的对话框。

QFileDialog类允许用户在它们的文件系统上遍历来选择一个或多个文件或目录。

最简单的方式是使用静态函数来创建一个QFileDialog。在Windows上，这些静态函数将调用本地Windows文件对话框并且在Mac OS X上，这些静态函数将调用本地Mac OS X文件对话框。

    QString s = QFileDialog::getOpenFileName(
                    "/home",
                    "Images (*.png *.xpm *.jpg)",
                    this,
                    "open file dialog"
                    "Choose a file" );

在上面的实例中，一个模式对话框被使用静态函数来创建。开始目录被设置为“/home”。文件过滤器被设置为“Images (*.png *.xpm *.jpg)”。文件对话框的父对象被设置为this并且它被给定一个标识名称——“open file dialog”。文件对话框上面的标题被设置为“Choose a file”。

你可以不使用静态函数创建你自己的QFileDialog。通过调用setMode()，你可以设置可以从QFileDialog返回什么。

    QFileDialog* fd = new QFileDialog( this, "file dialog", TRUE );
    fd->setMode( QFileDialog::AnyFile );

在上面的实例中，文件对话框的模式被设置为AnyFile，也就是说用户可以设置任何文件或者甚至指定一个不存在的文件。这个模式对于创建一个“File Save As”文件对话框。如果用户必须选择存在的文件，请使用ExistingFile，或者如果可以选择目录，请使用Directory。（模式的完整列表请参考QFileDialog::Mode枚举变量。）

你可以通过mode()重新得到对话框的模式。也可以使用setFilter()来设置对话框的文件过滤器。

    fd->setFilter( "Images (*.png *.xpm *.jpg)" );

在上面的实例中，过滤器被设置为“Images (*.png *.xpm *.jpg)”，这也就是说只有扩展名为png、xpm或jpg的文件可以被显示在QFileDialog中。你可以使用setFilters()来设置几个过滤器并且使用addFilter()来添加额外的过滤器。使用setSelectedFilter()来选择你给定的其中一个作为文件对话框默认过滤器。只用用户改变过滤器，filterSelected()信号就被发射。

文件对话框有两种视图模式，QFileDialog::List可以简单地列出文件和目录名称并且QFileDialog::Detail会在旁边显示额外的信息，例如，文件大小。

    fd->setViewMode( QFileDialog::Detail );

在创建你自己的文件对话框时最后需要的最后重要的函数是selectedFile()。

    QString fileName;
    if ( fd->exec() == QDialog::Accepted )
        fileName = fd->selectedFile();

在上面的实例中，模式对话框被创建并被显示。如果用户点击OK，然后他们选择的文件被放入fileName中。

如果你使用ExistingFiles模式，那么你将需要使用selectedFiles()在一个QStringList中返回选择的文件。

对话框工作目录可以使用setDir()来设置。隐藏文件的显示控制可以使用setShowHiddenFiles()。对话框可以被强制使用rereadDir()重新读取目录并且使用resortDir()来重新排列目录。可以使用selectAll()来选择当前目录下的所有文件。

创建和使用预览窗口部件

QFileDialog中使用两种预览窗口部件：内容预览窗口部件和信息预览窗口部件。它们的创建和使用方法相同，除了函数名不同以外，例如，setContentsPreview()和setInfoPreview()。

预览窗口部件被放置在QFileDialog中，让用户能够看到文件的内容或者有关文件的信息。

    class Preview : public QLabel, public QFilePreview
    {
    public:
        Preview( QWidget *parent=0 ) : QLabel( parent ) {}

        void previewUrl( const QUrl &u )
        {
            QString path = u.path();
            QPixmap pix( path );
            if ( pix.isNull() )
                setText( "This is not a pixmap" );
            else
                setPixmap( pix );
        }
    };

在上面的代码段中，我们创建一个继承与QLabel和QFilePreview的预览窗口部件。文件预览窗口部件必须从QFilePreview继承。

在这个类中我们重新实现了QFilePreview::previewUrl()，这是我们决定当文件被选择时发生什么。在上面的实例中，如果它是有效的像素映射，我们只是显示文件的预览。这里是文件对话框如何使用预览窗口部件的：

    Preview* p = new Preview;

    QFileDialog* fd = new QFileDialog( this );
    fd->setContentsPreviewEnabled( TRUE );
    fd->setContentsPreview( p, p );
    fd->setPreviewMode( QFileDialog::Contents );
    fd->show();

第一行创建了我们的预览窗口部件的实例。然后我们创建我们的文件对话框并且调用setContentsPreviewEnabled( TRUE )，这告诉文件对话框预览当前选择文件的内容。然后我们调用setContentsPreview()——注意我们传递同样的预览窗口部件两次。最后，在显示文件对话框之前，我们调用setPreviewMode()来设置Contents为用户选择文件的预览模式来显示内容预览。

如果你创建另一个预览窗口部件来显示有关文件的信息，那么像内容预览窗口部件一样的方式来创建它并且调用setInfoPreviewEnabled()和setInfoPreview()。然后用户将能够在两种预览模式中切换。

有关创建QFilePreview窗口部件的更多信息，请参考QFilePreview。

也可以参考对话框类。

成员类型文档

QFileDialog::Mode

这个枚举变量用来表明用户可以在文件对话框中选择什么，也就是如果用户点击OK，这个对话框返回什么。

  • QFileDialog::AnyFile - 文件名称，不论是否存在。
  • QFileDialog::ExistingFile - 一个单一存在文件的名称
  • QFileDialog::Directory - 目录名称。文件和目录都被显示。
  • QFileDialog::DirectoryOnly - 目录名称。只显示目录。
  • QFileDialog::ExistingFiles - 0个或更多个存在文件的名称。

请参考setMode()。

QFileDialog::PreviewMode

这个枚举变量描述的是文件对话框的预览模式。

  • QFileDialog::NoPreview - 没有预览被显示。
  • QFileDialog::Contents - 使用内容预览窗口部件来预览当前文件的内容。
  • QFileDialog::Info - 使用信息预览窗口部件来预览有关当前文件的信息。

请参考setPreviewMode()、setContentsPreview()和setInfoPreview()。

QFileDialog::ViewMode

这个枚举变量描述的是文件对话框的视图模式，也就是说关于每个文件都显示什么。

  • QFileDialog::List - 显示文件和目录的名称和图标。
  • QFileDialog::Detail - 显示文件和目录的名称和图标以及更多的信息，比如文件的大小和修改日期。

请参考setViewMode()。

成员函数文档

QFileDialog::QFileDialog ( const QString & dirName, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, bool modal = FALSE )

构造一个父对象为parent、名称为name的文件对话框。如果modal为真，那么文件对话框是模式的，否则它就是非模式的。

如果dirName被指定，那么它将被作为对话框的工作目录，比如，当对话框出现时，它将被作为被显示的目录。如果filter被指定，它将会被用作对话框的文件过滤器。

QFileDialog::QFileDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE )

构造一个父对象为parent、名称为name的文件对话框。如果modal为真，那么文件对话框是模式的，否则它就是非模式的。

QFileDialog::~QFileDialog ()

销毁这个文件对话框。

void QFileDialog::addFilter ( const QString & filter )

添加过滤器filter到过滤器的列表中并且把它作为当前过滤器。

    QFileDialog* fd = new QFileDialog( this );
    fd->addFilter( "Images (*.png *.jpg *.xpm)" );
    fd->show();

在上面的实例中，一个文件对话框被创建，并且文件过滤器“Images (*.png *.jpg *.xpm)”被添加并且它被设置为当前过滤器。初始过滤器“All Files (*)”仍然是有效的。

也可以参考setFilter()和setFilters()。

void QFileDialog::addLeftWidget ( QWidget * w ) [保护]

添加窗口部件w到文件对话框左侧。

也可以参考addRightWidget()、addWidgets()和addToolButton()。

void QFileDialog::addRightWidget ( QWidget * w ) [保护]

添加窗口部件w到文件对话框右侧。

也可以参考addLeftWidget()、addWidgets()和addToolButton()。

void QFileDialog::addToolButton ( QButton * b, bool separator = FALSE ) [保护]

把工具按钮b添加到文件对话框上面的一排工具按钮中。这个按钮被添加到这一行的右面。如果separator为真，在这行按钮中的最后一个和这个新按钮b之间会被插入一小块空间。

也可以参考addWidgets()、addLeftWidget()和addRightWidget()。

void QFileDialog::addWidgets ( QLabel * l, QWidget * w, QPushButton * b ) [保护]

把指定的窗口部件添加到文件对话框的底部。标签l会被放置到“file name”和“file types”标签的下面。窗口部件w会被放置到文件类型组合框的下面。按钮b会被放到Cancel推动按钮的下面。

    MyFileDialog::MyFileDialog( QWidget* parent, const char* name ) :
        QFileDialog( parent, name )
    {
        QLabel* label = new QLabel( "Added widgets", this );
        QLineEdit* lineedit = new QLineEdit( this );
        QToolButton* toolbutton = new QToolButton( this );

        addWidgets( label, lineedit, toolbutton );
    }

如果你不想添加任何其中一个窗口部件，就在那个窗口部件的位置上传递0。

每一次你调用这个函数，一行新的窗口部件被添加到文件对话框的底部。

也可以参考addToolButton()、addLeftWidget()和addRightWidget()。

const QDir * QFileDialog::dir () const

返回文件对话框中显示的当前目录。

QDir指针的所有权被传递给被调用者，所以你必须在调用者不需要它的时候删除它。

也可以参考setDir()。

void QFileDialog::dirEntered ( const QString & ) [信号]

当用户进入一个目录时，这个信号被发射。

也可以参考dir()。

QString QFileDialog::dirPath () const

返回文件对话框的工作目录。详细情况请参考“dirPath”属性。

void QFileDialog::fileHighlighted ( const QString & ) [信号]

当用户高亮显示一个文件时，这个信号被发射。

也可以参考fileSelected()和filesSelected()。

void QFileDialog::fileSelected ( const QString & ) [信号]

当用户选择一个文件时，这个信号被发射。

也可以参考filesSelected()、fileHighlighted()和selectedFile。

void QFileDialog::filesSelected ( const QStringList & ) [信号]

当用户在ExistingFiles模式下选择一个或多个文件时，这个信号被发射。

也可以参考fileSelected()、fileHighlighted()和selectedFiles。

void QFileDialog::filterSelected ( const QString & ) [信号]

当用户选择一个过滤器时，这个信号被发射。

也可以参考selectedFilter。

QString QFileDialog::getExistingDirectory ( const QString & dir = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, bool dirOnly = TRUE, bool resolveSymlinks = TRUE ) [静态]

这是一个返回由用户选择的已经存在的目录的方便的静态函数。

    QString s = QFileDialog::getExistingDirectory(
                    "/home",
                    this,
                    "get existing directory"
                    "Choose a directory",
                    TRUE );

这个函数创建了一个父对象为parent、名称为name的模式文件对话框。如果父对象不为0，这个对话框将被显示在它的父对象上面的中间。

对话框的工作目录被设置为dir，并且标题被设置为caption。它们当中的任何一个都可以是QString::null，在这种情况下，当前目录和默认标题将被分别使用。

如果dirOnly为真，那么只有目录被显示在文件对话框中，否则目录和文件都将被显示。

在Unix/X11下，文件对话框的通常行为是解析并跟踪符号连接。例如，如果/usr/tmp是/var/tmp的符号连接，那么在进入/usr/tmp之后，文件对话框将改变到/var/tmp。如果resolveSymlinks为假，文件对话框将把符号连接看作通常的目录。

也可以参考getOpenFileName()、getOpenFileNames()和getSaveFileName()。

QString QFileDialog::getOpenFileName ( const QString & startWith = QString::null, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE ) [静态]

这是一个返回由用户选择的已经存在的文件的方便的静态函数。如果用户按下Cancel，它返回一个零字符串。

    QString s = QFileDialog::getOpenFileName(
                    "/home",
                    "Images (*.png *.xpm *.jpg)",
                    this,
                    "open file dialog",
                    "Choose a file to open" );

这个函数创建了一个父对象为parent、名称为name的模式文件对话框。如果父对象不为0，这个对话框将被显示在它的父对象上面的中间。

文件的工作目录将被设置为startWith。如果startWith包括一个文件名，这个文件将被选择。过滤器被设置为filter，这样只有匹配过滤器的文件才会被显示。被选择的过滤器被设置为selectedFilter。参数startWith、selectedFilter和filter可以为QString::null。

对话框的标题可以被设置为caption。如果caption没有被指定，那么将会有一个默认标题被使用。

在Windows和Mac OS X下，这个静态函数将使用本地文件对话框而不是QFileDialog，除非应用程序的风格被设置为本地风格以外的某种风格。

在Unix/X11下，文件对话框的通常行为是解析并跟踪符号连接。例如，如果/usr/tmp是/var/tmp的符号连接，那么在进入/usr/tmp之后，文件对话框将改变到/var/tmp。如果resolveSymlinks为假，文件对话框将把符号连接看作通常的目录。

也可以参考getOpenFileNames(), getSaveFileName() and getExistingDirectory().

实例：action/application.cpp、addressbook/mainwindow.cpp、application/application.cpp、chart/chartform.cpp、mdi/application.cpp、qwerty/qwerty.cpp和showimg/showimg.cpp。

QStringList QFileDialog::getOpenFileNames ( const QString & filter = QString::null, const QString & dir = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE ) [静态]

这是一个返回由用户选择的已经存在的一个或多个文件的方便的静态函数。

    QStringList files = QFileDialog::getOpenFileNames(
                            "Images (*.png *.xpm *.jpg)",
                            "/home",
                            this,
                            "open files dialog"
                            "Select one or more files to open" );

这个函数创建了一个父对象为parent、名称为name的模式文件对话框。如果父对象不为0，这个对话框将被显示在它的父对象上面的中间。

文件的工作目录将被设置为dir。如果dir包括一个文件名，这个文件将被选择。过滤器被设置为filter，这样只有匹配过滤器的文件才会被显示。被选择的过滤器被设置为selectedFilter。参数dir、selectedFilter和filter可以为QString::null。

对话框的标题可以被设置为caption。如果caption没有被指定，那么将会有一个默认标题被使用。

在Windows和Mac OS X下，这个静态函数将使用本地文件对话框而不是QFileDialog，除非应用程序的风格被设置为本地风格以外的某种风格。

在Unix/X11下，文件对话框的通常行为是解析并跟踪符号连接。例如，如果/usr/tmp是/var/tmp的符号连接，那么在进入/usr/tmp之后，文件对话框将改变到/var/tmp。如果resolveSymlinks为假，文件对话框将把符号连接看作通常的目录。

注意如果你想遍历文件的列表，你应该在一个复制上进行遍历，例如：

    QStringList list = files;
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

也可以参考getOpenFileName()、getSaveFileName()和getExistingDirectory()。

QString QFileDialog::getSaveFileName ( const QString & startWith = QString::null, const QString & filter = QString::null, QWidget * parent = 0, const char * name = 0, const QString & caption = QString::null, QString * selectedFilter = 0, bool resolveSymlinks = TRUE ) [静态]

这是一个返回由用户选择的已经存在的文件的方便的静态函数。这个文件不一定存在。

这个函数创建了一个父对象为parent、名称为name的模式文件对话框。如果父对象不为0，这个对话框将被显示在它的父对象上面的中间。

    QString s = QFileDialog::getSaveFileName(
                    "/home",
                    "Images (*.png *.xpm *.jpg)",
                    this,
                    "save file dialog"
                    "Choose a filename to save under" );

文件的工作目录将被设置为startWith。如果startWith包括一个文件名，这个文件将被选择。过滤器被设置为filter，这样只有匹配过滤器的文件才会被显示。被选择的过滤器被设置为selectedFilter。参数startWith、selectedFilter和filter可以为QString::null。

对话框的标题可以被设置为caption。如果caption没有被指定，那么将会有一个默认标题被使用。

在Windows和Mac OS X下，这个静态函数将使用本地文件对话框而不是QFileDialog，除非应用程序的风格被设置为本地风格以外的某种风格。

在Unix/X11下，文件对话框的通常行为是解析并跟踪符号连接。例如，如果/usr/tmp是/var/tmp的符号连接，那么在进入/usr/tmp之后，文件对话框将改变到/var/tmp。如果resolveSymlinks为假，文件对话框将把符号连接看作通常的目录。

也可以参考getOpenFileName()、getOpenFileNames()和getExistingDirectory()。

实例：action/application.cpp、addressbook/mainwindow.cpp、application/application.cpp、chart/chartform.cpp、qmag/qmag.cpp、qwerty/qwerty.cpp和showimg/showimg.cpp。

QFileIconProvider * QFileDialog::iconProvider () [静态]

返回在文件对话框上当前设置的图标提供者的指针。默认情况下没有图标提供者，并且这个函数返回0。

也可以参考setIconProvider()和QFileIconProvider。

bool QFileDialog::isContentsPreviewEnabled () const

如果文件对话框提供当前选择文件的内容预览，返回真，否则返回假。详细情况请参考“contentsPreview”属性。

bool QFileDialog::isInfoPreviewEnabled () const

如果文件对话框提供当前选择文件的信息预览，返回真，否则返回假。详细情况请参考“infoPreview”属性。

Mode QFileDialog::mode () const

Returns the file dialog's mode. See the "mode" property for details.

PreviewMode QFileDialog::previewMode () const

返回文件对话框的预览模式。详细情况请参考“previewMode”属性。

void QFileDialog::rereadDir ()

重新读取在文件对话框中显示的当前目录。

只有在如果目录的内容发生改变并且你想刷新文件对话框来反映这样的变化时，你才需要调用这个函数。

也可以参考resortDir()。

void QFileDialog::resortDir ()

重新排列所显示的目录。

也可以参考rereadDir()。

void QFileDialog::selectAll ( bool b )

如果b为真，那么当前目录下的所有文件都被选择，否则它们都被取消选择。

QString QFileDialog::selectedFile () const

返回被选择文件的名称。详细情况请参考“selectedFile”属性。

QStringList QFileDialog::selectedFiles () const

返回被选择文件的列表。详细情况请参考“selectedFiles”属性。

QString QFileDialog::selectedFilter () const

返回文件对话框中用户所选择的过滤器。详细情况请参考“selectedFilter”属性。

void QFileDialog::setContentsPreview ( QWidget * w, QFilePreview * preview )

设置被用于作为文件对话框显示文件内容的窗口部件为w并且使用QFilePreview preview来预览内容。

通常你需要创建一个继承QWidget和QFilePreview的预览窗口部件，所以你需要传递同一个窗口部件两次。

    class Preview : public QLabel, public QFilePreview
    {
    public:
        Preview( QWidget *parent=0 ) : QLabel( parent ) {}

        void previewUrl( const QUrl &u )
        {
            QString path = u.path();
            QPixmap pix( path );
            if ( pix.isNull() )
                setText( "This is not a pixmap" );
            else
                setPixmap( pix );
        }
    };

  //...

  int main( int argc, char** argv )
  {
    Preview* p = new Preview;

    QFileDialog* fd = new QFileDialog( this );
    fd->setContentsPreviewEnabled( TRUE );
    fd->setContentsPreview( p, p );
    fd->setPreviewMode( QFileDialog::Contents );
    fd->show();
  }

也可以参考contentsPreview、setInfoPreview()和previewMode。

实例：qdir/qdir.cpp。

void QFileDialog::setContentsPreviewEnabled ( bool )

设置文件对话框是否提供当前选择文件的内容预览。详细情况请参考“contentsPreview”属性。

void QFileDialog::setDir ( const QDir & dir )

设置文件对话框的工作目录是dir。

也可以参考dir()。

void QFileDialog::setDir ( const QString & pathstr ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置文件对话框的工作目录是pathstr。

也可以参考dir()。

void QFileDialog::setFilter ( const QString & newFilter ) [槽]

设置文件对话框中使用的过滤器为newFilter。

如果newFilter中包含一对包含一个或多个anything*something，由空格或者分号分隔的括号，那么只有其中被括号包含的内容会被作为过滤器。这也就是说下面这些调用方法都是相同的：

     fd->setFilter( "All C++ files (*.cpp *.cc *.C *.cxx *.c++)" );
     fd->setFilter( "*.cpp *.cc *.C *.cxx *.c++" );
     fd->setFilter( "All C++ files (*.cpp;*.cc;*.C;*.cxx;*.c++)" );
     fd->setFilter( "*.cpp;*.cc;*.C;*.cxx;*.c++" );

也可以参考setFilters()。

void QFileDialog::setFilters ( const QString & filters ) [槽]

设置文件对话框中使用的过滤器为filters。过滤器中的每一组必须使用;;（两个分号）来分隔。

    QString types("*.png;;*.xpm;;*.jpg");
    QFileDialog fd = new QFileDialog( this );
    fd->setFilters( types );
    fd->show();

void QFileDialog::setFilters ( const char ** types ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

必须是以结束符结尾的字符串列表。

void QFileDialog::setFilters ( const QStringList & ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

void QFileDialog::setIconProvider ( QFileIconProvider * provider ) [静态]

设置文件对话框使用的QFileIconProvider为provider。

默认没有QFileIconProvider并且QFileDialog只为每一个目录绘制一个文件夹图标，而对文件则没有图标。

也可以参考QFileIconProvider和iconProvider()。

实例：showimg/main.cpp。

void QFileDialog::setInfoPreview ( QWidget * w, QFilePreview * preview )

设置被用于作为文件对话框显示文件信息的窗口部件为w并且使用QFilePreview preview来预览信息。

通常你需要创建一个继承QWidget和QFilePreview的预览窗口部件，所以你需要传递同一个窗口部件两次。

    class Preview : public QLabel, public QFilePreview
    {
    public:
        Preview( QWidget *parent=0 ) : QLabel( parent ) {}

        void previewUrl( const QUrl &u )
        {
            QString path = u.path();
            QPixmap pix( path );
            if ( pix.isNull() )
                setText( "This is not a pixmap" );
            else
                setText( "This is a pixmap" );
        }
    };

  //...

  int main( int argc, char** argv )
  {
    Preview* p = new Preview;

    QFileDialog* fd = new QFileDialog( this );
    fd->setInfoPreviewEnabled( TRUE );
    fd->setInfoPreview( p, p );
    fd->setPreviewMode( QFileDialog::Info );
    fd->show();
  }

也可以参考setContentsPreview()、infoPreview和previewMode。

void QFileDialog::setInfoPreviewEnabled ( bool )

设置文件对话框是否提供当前选择文件的信息预览。详细情况请参考“infoPreview”属性。

void QFileDialog::setMode ( Mode )

设置文件对话框的模式。详细情况请参考“mode”属性。

void QFileDialog::setPreviewMode ( PreviewMode m )

设置文件对话框的预览模式为m。详细情况请参考“previewMode”属性。

void QFileDialog::setSelectedFilter ( const QString & mask ) [虚]

设置文件对话框中当前选择的过滤器为文本mask中包含的第一个。

void QFileDialog::setSelectedFilter ( int n ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置文件对话框中当前选择的过滤器为过滤器列表中的第n个过滤器。

也可以参考filterSelected()、selectedFilter、selectedFiles和selectedFile。

void QFileDialog::setSelection ( const QString & filename )

设置默认选择为filename。如果filename为绝对的，setDir()也会被调用来设置文件对话框的工作目录为filename中的目录。

实例：qdir/qdir.cpp。

void QFileDialog::setShowHiddenFiles ( bool s )

设置文件对话框中隐藏文件是否被显示为s。详细情况请参考“showHiddenFiles”属性。

void QFileDialog::setUrl ( const QUrlOperator & url ) [槽]

设置文件对话框的工作目录为url指定的目录。

也可以参考url()。

void QFileDialog::setViewMode ( ViewMode m )

设置文件对话框的视图模式为m。详细情况请参考“viewMode”属性。

bool QFileDialog::showHiddenFiles () const

如果文件对话框中隐藏文件被显示，返回真，否则返回假。详细情况请参考“showHiddenFiles”属性。

QUrl QFileDialog::url () const

返回文件对话框中当前工作目录的URL。

也可以参考setUrl()。

实例：network/networkprotocol/view.cpp。

ViewMode QFileDialog::viewMode () const

返回文件对话框的视图模式。详细情况请参考“viewMode”属性。

属性文档

bool contentsPreview

这个属性保存的是文件对话框是否提供当前选择文件的内容预览。

默认为假。

也可以参考setContentsPreview()和infoPreview。

通过setContentsPreviewEnabled()设置属性值并且通过isContentsPreviewEnabled()来获得属性值。

QString dirPath

这个属性保存的是文件对话框的工作目录。

通过dirPath()来获得属性值。

也可以参考dir()和setDir()。

bool infoPreview

这个属性保存的是文件对话框是否提供当前选择文件的信息预览。

默认为假。

通过setInfoPreviewEnabled()设置属性值并且通过isInfoPreviewEnabled()来获得属性值。

Mode mode

这个属性保存的是文件对话框的模式。

默认模式为ExistingFile。

通过setMode()设置属性值并且通过mode()来获得属性值。

PreviewMode previewMode

这个属性保存的是文件的对话框的预览模式。

如果你设置这个模式为NoPreview之外的模式，你必须使用setInfoPreview()或者setContentsPreview()来设置这个对话框的预览窗口部件为你的预览窗口部件并且使用setInfoPreviewEnabled()或setContentsPreviewEnabled()来让预览窗口部件生效。

也可以参考infoPreview、contentsPreview和viewMode。

通过setPreviewMode()设置属性值并且通过previewMode()来获得属性值。

QString selectedFile

这个属性保存的是选择的文件的名称。

如果文件被选择，则selectedFile包含文件的名称和它的绝对路径，否则selectedFile为空。

也可以参考QString::isEmpty()、selectedFiles和selectedFilter。

通过selectedFile()来获得属性值。

QStringList selectedFiles

这个属性保存的是选择的文件的列表。

如果有一个或多个文件被选择，selectedFiles包含这些文件的名称和它们的绝对路径。如果没有文件被选择或者模式不是ExistingFiles，selectedFiles是一个空列表。

如果模式为ExistingFile、Directory或DirectoryOnly，使用selectedFile()更方便。

注意，如果你想遍历这个列表，你应该遍历它的复制，例如：

    QStringList list = myFileDialog.selectedFiles();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

也可以参考selectedFile、selectedFilter和QValueList::empty()。

通过selectedFiles()来获得属性值。

QString selectedFilter

这个属性保存的是文件对话框中用户选择文件的过滤器。

通过selectedFilter()来获得属性值。

也可以参考filterSelected()、selectedFiles和selectedFile。

bool showHiddenFiles

这个属性保存的是文件对话框中隐藏文件是否显示。

默认是假，也就是不显示隐藏文件。

通过setShowHiddenFiles()设置属性值并且通过showHiddenFiles()来获得属性值。

ViewMode viewMode

这个属性保存的是文件对话框的视图模式。

如果你设置视图模式为Detail（默认），那么你将看到文件的详细情况，除了文件名之外，还有文件的大小和这个文件最近一次被修改的日期。

如果你设置视图模式为List，那么你将只会看到文件和文件夹的列表。

请参考QFileDialog::ViewMode。

通过setViewMode()设置属性值并且通过viewMode()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qfiledialog.h包含文件

qfiledialog.h

这里是qfiledialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qfiledialog.h   3.0.5   edited Oct 19 2001 $
**
** Definition of QFileDialog class
**
** Created : 950428
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFILEDIALOG_H
#define QFILEDIALOG_H

class QPushButton;
class QButton;
class QLabel;
class QWidget;
class QFileDialog;
class QTimer;
class QNetworkOperation;
class QLineEdit;
class QListViewItem;
class QListBoxItem;
class QFileDialogPrivate;
class QFileDialogQFileListView;

#ifndef QT_H
#include "qdir.h"
#include "qdialog.h"
#include "qurloperator.h"
#include "qurlinfo.h"
#endif // QT_H

#ifndef QT_NO_FILEDIALOG

class Q_EXPORT QFileIconProvider : public QObject
{
    Q_OBJECT
public:
    QFileIconProvider( QObject * parent = 0, const char* name = 0 );
    virtual const QPixmap * pixmap( const QFileInfo & );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QFileIconProvider( const QFileIconProvider & );
    QFileIconProvider& operator=( const QFileIconProvider & );
#endif
};

class Q_EXPORT QFilePreview
{
public:
    QFilePreview();
    virtual void previewUrl( const QUrl &url ) = 0;

};

class Q_EXPORT QFileDialog : public QDialog
{
    Q_OBJECT
    Q_ENUMS( Mode ViewMode PreviewMode )
    // ##### Why are this read-only properties ?
    Q_PROPERTY( QString selectedFile READ selectedFile )
    Q_PROPERTY( QString selectedFilter READ selectedFilter )
    Q_PROPERTY( QStringList selectedFiles READ selectedFiles )
    // #### Should not we be able to set the path ?
    Q_PROPERTY( QString dirPath READ dirPath )
    Q_PROPERTY( bool showHiddenFiles READ showHiddenFiles WRITE setShowHiddenFiles )
    Q_PROPERTY( Mode mode READ mode WRITE setMode )
    Q_PROPERTY( ViewMode viewMode READ viewMode WRITE setViewMode )
    Q_PROPERTY( PreviewMode previewMode READ previewMode WRITE setPreviewMode )
    Q_PROPERTY( bool infoPreview READ isInfoPreviewEnabled WRITE setInfoPreviewEnabled )
    Q_PROPERTY( bool contentsPreview READ isContentsPreviewEnabled WRITE setContentsPreviewEnabled )

public:
    QFileDialog( const QString& dirName, const QString& filter = QString::null,
         QWidget* parent=0, const char* name=0, bool modal = FALSE );
    QFileDialog( QWidget* parent=0, const char* name=0, bool modal = FALSE );
    ~QFileDialog();

    // recommended static functions

    static QString getOpenFileName( const QString &initially = QString::null,
                    const QString &filter = QString::null,
                    QWidget *parent = 0, const char* name = 0,
                    const QString &caption = QString::null,
                    QString *selectedFilter = 0,
                    bool resolveSymlinks = TRUE);
    static QString getSaveFileName( const QString &initially = QString::null,
                    const QString &filter = QString::null,
                    QWidget *parent = 0, const char* name = 0,
                    const QString &caption = QString::null,
                    QString *selectedFilter = 0,
                    bool resolveSymlinks = TRUE);
    static QString getExistingDirectory( const QString &dir = QString::null,
                     QWidget *parent = 0,
                     const char* name = 0,
                     const QString &caption = QString::null,
                     bool dirOnly = TRUE,
                     bool resolveSymlinks = TRUE);
    static QStringList getOpenFileNames( const QString &filter= QString::null,
                     const QString &dir = QString::null,
                     QWidget *parent = 0,
                     const char* name = 0,
                     const QString &caption = QString::null,
                     QString *selectedFilter = 0,
                     bool resolveSymlinks = TRUE);

    // other static functions

    static void setIconProvider( QFileIconProvider * );
    static QFileIconProvider * iconProvider();

    // non-static function for special needs

    QString selectedFile() const;
    QString selectedFilter() const;
    virtual void setSelectedFilter( const QString& );
    virtual void setSelectedFilter( int );

    void setSelection( const QString &);

    void selectAll( bool b );

    QStringList selectedFiles() const;

    QString dirPath() const;

    void setDir( const QDir & );
    const QDir *dir() const;

    void setShowHiddenFiles( bool s );
    bool showHiddenFiles() const;

    void rereadDir();
    void resortDir();

    enum Mode { AnyFile, ExistingFile, Directory, ExistingFiles, DirectoryOnly };
    void setMode( Mode );
    Mode mode() const;

    enum ViewMode { Detail, List };
    enum PreviewMode { NoPreview, Contents, Info };
    void setViewMode( ViewMode m );
    ViewMode viewMode() const;
    void setPreviewMode( PreviewMode m );
    PreviewMode previewMode() const;

    bool eventFilter( QObject *, QEvent * );

    bool isInfoPreviewEnabled() const;
    bool isContentsPreviewEnabled() const;
    void setInfoPreviewEnabled( bool );
    void setContentsPreviewEnabled( bool );

    void setInfoPreview( QWidget *w, QFilePreview *preview );
    void setContentsPreview( QWidget *w, QFilePreview *preview );

    QUrl url() const;

    void addFilter( const QString &filter );

public slots:
    void done( int );
    void setDir( const QString& );
    void setUrl( const QUrlOperator &url );
    void setFilter( const QString& );
    void setFilters( const QString& );
    void setFilters( const char ** );
    void setFilters( const QStringList& );

protected:
    void resizeEvent( QResizeEvent * );
    void keyPressEvent( QKeyEvent * );

    void addWidgets( QLabel *, QWidget *, QPushButton * );
    void addToolButton( QButton *b, bool separator = FALSE );
    void addLeftWidget( QWidget *w );
    void addRightWidget( QWidget *w );

signals:
    void fileHighlighted( const QString& );
    void fileSelected( const QString& );
    void filesSelected( const QStringList& );
    void dirEntered( const QString& );
    void filterSelected( const QString& );

private slots:
    void detailViewSelectionChanged();
    void listBoxSelectionChanged();
    void changeMode( int );
    void fileNameEditReturnPressed();
    void stopCopy();
    void removeProgressDia();

    void fileSelected( int );
    void fileHighlighted( int );
    void dirSelected( int );
    void pathSelected( int );

    void updateFileNameEdit( QListViewItem *);
    void selectDirectoryOrFile( QListViewItem * );
    void popupContextMenu( QListViewItem *, const QPoint &, int );
    void popupContextMenu( QListBoxItem *, const QPoint & );
    void updateFileNameEdit( QListBoxItem *);
    void selectDirectoryOrFile( QListBoxItem * );
    void fileNameEditDone();

    void okClicked();
    void filterClicked(); // not used
    void cancelClicked();

    void cdUpClicked();
    void newFolderClicked();

    void fixupNameEdit();

    void doMimeTypeLookup();

    void updateGeometries();
    void modeButtonsDestroyed();
    void urlStart( QNetworkOperation *op );
    void urlFinished( QNetworkOperation *op );
    void dataTransferProgress( int bytesDone, int bytesTotal, QNetworkOperation * );
    void insertEntry( const QValueList<QUrlInfo> &fi, QNetworkOperation *op );
    void removeEntry( QNetworkOperation * );
    void createdDirectory( const QUrlInfo &info, QNetworkOperation * );
    void itemChanged( QNetworkOperation * );
    void goBack();

private:
    enum PopupAction {
    PA_Open = 0,
    PA_Delete,
    PA_Rename,
    PA_SortName,
    PA_SortSize,
    PA_SortType,
    PA_SortDate,
    PA_SortUnsorted,
    PA_Cancel,
    PA_Reload,
    PA_Hidden
    };

    void init();
    bool trySetSelection( bool isDir, const QUrlOperator &, bool );
    void deleteFile( const QString &filename );
    void popupContextMenu( const QString &filename, bool withSort,
               PopupAction &action, const QPoint &p );

    QDir reserved; // was cwd
    QString fileName;

    friend class QFileDialogQFileListView;
    friend class QFileListBox;

    QFileDialogPrivate *d;
    QFileDialogQFileListView  *files;

    QLineEdit  *nameEdit; // also filter
    QPushButton *okB;
    QPushButton *cancelB;

#if defined(Q_WS_WIN)
    static QString winGetOpenFileName( const QString &initialSelection,
                       const QString &filter,
                       QString* workingDirectory,
                       QWidget *parent = 0,
                       const char* name = 0,
                       const QString& caption = QString::null,
                       QString* selectedFilter = 0 );
    static QString winGetSaveFileName( const QString &initialSelection,
                       const QString &filter,
                       QString* workingDirectory,
                       QWidget *parent = 0,
                       const char* name = 0,
                       const QString& caption = QString::null,
                           QString* selectedFilter = 0 );
    static QStringList winGetOpenFileNames( const QString &filter,
                        QString* workingDirectory,
                        QWidget *parent = 0,
                        const char* name = 0,
                        const QString& caption = QString::null,
                        QString* selectedFilter = 0 );
    static QString winGetExistingDirectory( const QString &initialDirectory,
                        QWidget* parent = 0,
                        const char* name = 0,
                        const QString& caption = QString::null);
    static QString resolveLinkFile( const QString& linkfile );
#endif
#if defined(Q_WS_MACX) || defined(Q_WS_MAC9)
    static QString macGetSaveFileName( const QString &, const QString &,
                       QString *, QWidget *, const char*,
                       const QString& );
    static QStringList macGetOpenFileNames( const QString &, QString*,
                        QWidget *, const char *,
                        const QString&, bool = TRUE,
                        bool = FALSE );
#endif

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QFileDialog( const QFileDialog & );
    QFileDialog &operator=( const QFileDialog & );
#endif
};

#endif

#endif // QFILEDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFileDialog成员列表

完整的QFileDialog成员列表

这里是QFileDialog成员函数的完整列表，包括继承的成员。

  • QFileDialog()
  • ~QFileDialog()
  • accept()
  • acceptDrops()
  • addFilter()
  • addLeftWidget()
  • addRightWidget()
  • addToolButton()
  • addWidgets()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • dir()
  • dirEntered()
  • dirPath()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • fileHighlighted()
  • fileSelected()
  • filesSelected()
  • filterSelected()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getExistingDirectory()
  • getOpenFileName()
  • getOpenFileNames()
  • getSaveFileName()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconProvider()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isContentsPreviewEnabled()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isInfoPreviewEnabled()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mode()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • previewMode()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • rereadDir()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • resortDir()
  • result()
  • scroll()
  • selectAll()
  • selectedFile()
  • selectedFiles()
  • selectedFilter()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setContentsPreview()
  • setContentsPreviewEnabled()
  • setCursor()
  • setDir()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFilter()
  • setFilters()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconProvider()
  • setIconText()
  • setInfoPreview()
  • setInfoPreviewEnabled()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMode()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPreviewMode()
  • setProperty()
  • setResult()
  • setSelectedFilter()
  • setSelection()
  • setShowHiddenFiles()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setUrl()
  • setViewMode()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showHiddenFiles()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • url()
  • viewMode()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFileIconProvider Class

QFileIconProvider Class Reference

The QFileIconProvider class provides icons for QFileDialog to use. More...

#include <qfiledialog.h>

Inherits QObject.

List of all member functions.

Public Members

  • QFileIconProvider ( QObject * parent = 0, const char * name = 0 )
  • virtual const QPixmap * pixmap ( const QFileInfo & info )

Detailed Description

The QFileIconProvider class provides icons for QFileDialog to use.

By default QFileIconProvider is not used, but any application or library can subclass it, reimplement pixmap() to return a suitable icon, and make all QFileDialog objects use it by calling the static function QFileDialog::setIconProvider().

It is advisable to make all the icons that QFileIconProvider returns be the same size or at least the same width. This makes the list view look much better.

See also QFileDialog and Miscellaneous Classes.

Member Function Documentation

QFileIconProvider::QFileIconProvider ( QObject * parent = 0, const char * name = 0 )

Constructs an empty file icon provider called name, with the parent parent.

const QPixmap * QFileIconProvider::pixmap ( const QFileInfo & info ) [virtual]

Returns a pointer to a pixmap that should be used to signify the file with the information info.

If pixmap() returns 0, QFileDialog draws the default pixmap.

The default implementation returns particular icons for files, directories, link-files and link-directories. It returns a blank "icon" for other types.

If you return a pixmap here, it should measure 16x16 pixels.

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


QFileIconProvider Member List

Complete Member List for QFileIconProvider

This is the complete list of member functions for QFileIconProvider, including inherited members.

  • QFileIconProvider()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QFileInfo Class

QFileInfo Class Reference

The QFileInfo class provides system-independent file information. More...

#include <qfileinfo.h>

List of all member functions.

Public Members

  • enum PermissionSpec { ReadUser = 0400, WriteUser = 0200, ExeUser = 0100, ReadGroup = 0040, WriteGroup = 0020, ExeGroup = 0010, ReadOther = 0004, WriteOther = 0002, ExeOther = 0001 }
  • QFileInfo ()
  • QFileInfo ( const QString & file )
  • QFileInfo ( const QFile & file )
  • QFileInfo ( const QDir & d, const QString & fileName )
  • QFileInfo ( const QFileInfo & fi )
  • ~QFileInfo ()
  • QFileInfo & operator= ( const QFileInfo & fi )
  • void setFile ( const QString & file )
  • void setFile ( const QFile & file )
  • void setFile ( const QDir & d, const QString & fileName )
  • bool exists () const
  • void refresh () const
  • bool caching () const
  • void setCaching ( bool enable )
  • QString filePath () const
  • QString fileName () const
  • QString absFilePath () const
  • QString baseName ( bool complete = FALSE ) const
  • QString extension ( bool complete = TRUE ) const
  • QString dirPath ( bool absPath = FALSE ) const
  • QDir dir ( bool absPath = FALSE ) const
  • bool isReadable () const
  • bool isWritable () const
  • bool isExecutable () const
  • bool isRelative () const
  • bool convertToAbs ()
  • bool isFile () const
  • bool isDir () const
  • bool isSymLink () const
  • QString readLink () const
  • QString owner () const
  • uint ownerId () const
  • QString group () const
  • uint groupId () const
  • bool permission ( int permissionSpec ) const
  • uint size () const
  • QDateTime created () const
  • QDateTime lastModified () const
  • QDateTime lastRead () const

Detailed Description

The QFileInfo class provides system-independent file information.

QFileInfo provides information about a file's name and position (path) in the file system, its access rights and whether it is a directory or symbolic link, etc. The file's size and last modified/read times are also available.

A QFileInfo can point to a file with either a relative or an absolute file path. Absolute file paths begin with the directory separator "/" or a drive specification (except on Unix). Relative file names begin with a directory name or a file name and specify a path relative to the current working directory. An example of an absolute path is the string "/tmp/quartz". A relative path might look like "src/fatlib". You can use the function isRelative() to check whether a QFileInfo is using a relative or an absolute file path. You can call the function convertToAbs() to convert a relative QFileInfo's path to an absolute path.

The file that the QFileInfo works on is set in the constructor or later with setFile(). Use exists() to see if the file exists and size() to get its size.

To speed up performance, QFileInfo caches information about the file. Because files can be changed by other users or programs, or even by other parts of the same program, there is a function that refreshes the file information: refresh(). If you want to switch off a QFileInfo's caching and force it to access the file system every time you request information from it call setCaching(FALSE).

The file's type is obtained with isFile(), isDir() and isSymLink(). The readLink() function provides the name of the file the symlink points to.

Elements of the file's name can be extracted with dirPath() and fileName(). The fileName()'s parts can be extracted with baseName() and extension().

The file's dates are returned by created(), lastModified() and lastRead(). Information about the file's access permissions is obtained with isReadable(), isWritable() and isExecutable(). The file's ownership is available from owner(), ownerId(), group() and groupId(). You can examine a file's permissions and ownership in a single statement using the permission() function.

If you need to read and traverse directories, see the QDir class.

See also Input/Output and Networking.

Member Type Documentation

QFileInfo::PermissionSpec

This enum is used by the permission() function to report the permissions and ownership of a file. The values may be OR-ed together to test multiple permissions and ownership values.

  • QFileInfo::ReadUser - The file is readable by the user.
  • QFileInfo::WriteUser - The file is writable by the user.
  • QFileInfo::ExeUser - The file is executable by the user.
  • QFileInfo::ReadGroup - The file is readable by the group.
  • QFileInfo::WriteGroup - The file is writable by the group.
  • QFileInfo::ExeGroup - The file is executable by the group.
  • QFileInfo::ReadOther - The file is readable by anyone.
  • QFileInfo::WriteOther - The file is writable by anyone.
  • QFileInfo::ExeOther - The file is executable by anyone.

Member Function Documentation

QFileInfo::QFileInfo ()

Constructs a new empty QFileInfo.

QFileInfo::QFileInfo ( const QString & file )

Constructs a new QFileInfo that gives information about the given file. The file can be an absolute or a relative file path.

See also setFile(), isRelative(), QDir::setCurrent() and QDir::isRelativePath().

QFileInfo::QFileInfo ( const QFile & file )

Constructs a new QFileInfo that gives information about file file.

If the file has a relative path, the QFileInfo will also have a relative path.

See also isRelative().

QFileInfo::QFileInfo ( const QDir & d, const QString & fileName )

Constructs a new QFileInfo that gives information about the file named fileName in the directory d.

If the directory has a relative path, the QFileInfo will also have a relative path.

See also isRelative().

QFileInfo::QFileInfo ( const QFileInfo & fi )

Constructs a new QFileInfo that is a copy of fi.

QFileInfo::~QFileInfo ()

Destroys the QFileInfo and frees its resources.

QString QFileInfo::absFilePath () const

Returns the absolute path including the file name.

The absolute path name consists of the full path and the file name. On Unix this will always begin with the root, '/', directory. On Windows this will always begin 'D:/' where D is a drive letter, except for network shares that are not mapped to a drive letter, in which case the path will begin '//sharename/'.

This function returns the same as filePath(), unless isRelative() is TRUE.

This function can be time consuming under Unix (in the order of milliseconds).

See also isRelative() and filePath().

Examples: biff/biff.cpp and fileiconview/qfileiconview.cpp.

QString QFileInfo::baseName ( bool complete = FALSE ) const

Returns the base name of the file.

If complete is FALSE (the default) the base name consists of all characters in the file name up to (but not including) the first '.' character.

If complete is TRUE the base name consists of all characters in the file up to (but not including) the last '.' character.

The path is not included in either case.

Example:

     QFileInfo fi( "/tmp/archive.tar.gz" );
     QString base = fi.baseName();  // base = "archive"
     base = fi.baseName( TRUE );    // base = "archive.tar"

See also fileName() and extension().

bool QFileInfo::caching () const

Returns TRUE if caching is enabled; otherwise returns FALSE.

See also setCaching() and refresh().

bool QFileInfo::convertToAbs ()

Converts the file path name to an absolute path.

If it is already absolute, nothing is done.

See also filePath() and isRelative().

QDateTime QFileInfo::created () const

Returns the date and time when the file was created.

On platforms where this information is not available, returns the same as lastModified().

See also lastModified() and lastRead().

QDir QFileInfo::dir ( bool absPath = FALSE ) const

Returns the directory path of the file.

If the QFileInfo is relative and absPath is FALSE, the QDir will be relative; otherwise it will be absolute.

See also dirPath(), filePath(), fileName() and isRelative().

Example: fileiconview/qfileiconview.cpp.

QString QFileInfo::dirPath ( bool absPath = FALSE ) const

Returns the directory path of the file.

If absPath is TRUE an absolute path is returned.

See also dir(), filePath(), fileName() and isRelative().

Example: fileiconview/qfileiconview.cpp.

bool QFileInfo::exists () const

Returns TRUE if the file exists; otherwise returns FALSE.

Examples: biff/biff.cpp and i18n/main.cpp.

QString QFileInfo::extension ( bool complete = TRUE ) const

Returns the file's extension name.

If complete is TRUE (the default), extension() returns the string of all characters in the file name after (but not including) the first '.' character.

If complete is FALSE, extension() returns the string of all characters in the file name after (but not including) the last '.' character.

Example:

     QFileInfo fi( "/tmp/archive.tar.gz" );
     QString ext = fi.extension();  // ext = "tar.gz"
     ext = fi.extension( FALSE );   // ext = "gz"

See also fileName() and baseName().

Example: qdir/qdir.cpp.

QString QFileInfo::fileName () const

Returns the name of the file, the file path is not included.

Example:

     QFileInfo fi( "/tmp/archive.tar.gz" );
     QString name = fi.fileName();              // name = "archive.tar.gz"

See also isRelative(), filePath(), baseName() and extension().

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

QString QFileInfo::filePath () const

Returns the file name, including the path (which may be absolute or relative).

See also isRelative() and absFilePath().

Examples: dirview/main.cpp and fileiconview/qfileiconview.cpp.

QString QFileInfo::group () const

Returns the group of the file. On Windows, on systems where files do not have groups, or if an error occurs, a null string is returned.

This function can be time consuming under Unix (in the order of milliseconds).

See also groupId(), owner() and ownerId().

uint QFileInfo::groupId () const

Returns the id of the group the file belongs to.

On Windows and on systems where files do not have groups this function always returns (uint) -2.

See also group(), owner() and ownerId().

bool QFileInfo::isDir () const

Returns TRUE if this object points to a directory or to a symbolic link to a directory; otherwise returns FALSE.

See also isFile() and isSymLink().

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

bool QFileInfo::isExecutable () const

Returns TRUE if the file is executable; otherwise returns FALSE.

See also isReadable(), isWritable() and permission().

bool QFileInfo::isFile () const

Returns TRUE if this object points to a file. Returns FALSE if the object points to something which isn't a file, e.g. a directory or a symlink.

See also isDir() and isSymLink().

Examples: dirview/dirview.cpp, fileiconview/qfileiconview.cpp and qdir/qdir.cpp.

bool QFileInfo::isReadable () const

Returns TRUE if the file is readable; otherwise returns FALSE.

See also isWritable(), isExecutable() and permission().

bool QFileInfo::isRelative () const

Returns TRUE if the file path name is relative. Returns FALSE if the path is absolute (e.g. under Unix a path is absolute if it begins with a "/").

bool QFileInfo::isSymLink () const

Returns TRUE if this object points to a symbolic link (or to a shortcut on Windows); otherwise returns FALSE.

See also isFile(), isDir() and readLink().

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

bool QFileInfo::isWritable () const

Returns TRUE if the file is writable; otherwise returns FALSE.

See also isReadable(), isExecutable() and permission().

QDateTime QFileInfo::lastModified () const

Returns the date and time when the file was last modified.

See also created() and lastRead().

Example: biff/biff.cpp.

QDateTime QFileInfo::lastRead () const

Returns the date and time when the file was last read (accessed).

On platforms where this information is not available, returns the same as lastModified().

See also created() and lastModified().

Example: biff/biff.cpp.

QFileInfo & QFileInfo::operator= ( const QFileInfo & fi )

Makes a copy of fi and assigns it to this QFileInfo.

QString QFileInfo::owner () const

Returns the owner of the file. On Windows, on systems where files do not have owners, or if an error occurs, a null string is returned.

This function can be time consuming under Unix (in the order of milliseconds).

See also ownerId(), group() and groupId().

uint QFileInfo::ownerId () const

Returns the id of the owner of the file.

On Windows and on systems where files do not have owners this function returns ((uint) -2).

See also owner(), group() and groupId().

bool QFileInfo::permission ( int permissionSpec ) const

Tests for file permissions. The permissionSpec argument can be several flags of type PermissionSpec OR-ed together to check for permission combinations.

On systems where files do not have permissions this function always returns TRUE.

Example:

    QFileInfo fi( "/tmp/archive.tar.gz" );
    if ( fi.permission( QFileInfo::WriteUser | QFileInfo::ReadGroup ) )
        qWarning( "I can change the file; my group can read the file.");
    if ( fi.permission( QFileInfo::WriteGroup | QFileInfo::WriteOther ) )
        qWarning( "The group or others can change the file!" );

See also isReadable(), isWritable() and isExecutable().

QString QFileInfo::readLink () const

Returns the name a symlink (or shortcut on Windows) points to, or a null QString if the object isn't a symbolic link.

This name may not represent an existing file; it is only a string. QFileInfo::exists() returns TRUE if the symlink points to an existing file.

See also exists(), isSymLink(), isDir() and isFile().

void QFileInfo::refresh () const

Refreshes the information about the file, i.e. reads in information from the file system the next time a cached property is fetched.

See also setCaching().

void QFileInfo::setCaching ( bool enable )

If enable is TRUE, enables caching of file information. If enable is FALSE caching is disabled.

When caching is enabled, QFileInfo reads the file information from the file system the first time it's needed, but generally not later.

Caching is enabled by default.

See also refresh() and caching().

void QFileInfo::setFile ( const QString & file )

Sets the file that the QFileInfo provides information about to file.

The string given can be an absolute or a relative file path. Absolute paths begin with the directory separator (e.g. "/" under Unix) or a drive specification (not applicable to Unix). Relative file names begin with a directory name or a file name and specify a path relative to the current directory.

Example:

    QString absolute = "/local/bin";
    QString relative = "local/bin";
    QFileInfo absFile( absolute );
    QFileInfo relFile( relative );

    QDir::setCurrent( QDir::rootDirPath() );
    // absFile and relFile now point to the same file

    QDir::setCurrent( "/tmp" );
    // absFile now points to "/local/bin",
    // while relFile points to "/tmp/local/bin"

See also isRelative(), QDir::setCurrent() and QDir::isRelativePath().

Example: biff/biff.cpp.

void QFileInfo::setFile ( const QFile & file )

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

Sets the file that the QFileInfo provides information about to file.

If the file has a relative path, the QFileInfo will also have a relative path.

See also isRelative().

void QFileInfo::setFile ( const QDir & d, const QString & fileName )

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

Sets the file that the QFileInfo provides information about to fileName in directory d.

If the file has a relative path, the QFileInfo will also have a relative path.

See also isRelative().

uint QFileInfo::size () const

Returns the file size in bytes, or 0 if the file does not exist or if the size is 0 or if the size cannot be fetched.

Example: qdir/qdir.cpp.

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


qfileinfo.h Include File

qfileinfo.h

This is the verbatim text of the qfileinfo.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QFileInfo class
**
** Created : 950628
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFILEINFO_H
#define QFILEINFO_H

#ifndef QT_H
#include "qfile.h"
#include "qdatetime.h"
#endif // QT_H

class QDir;
struct QFileInfoCache;

class Q_EXPORT QFileInfo				   // file information class
{
public:
    enum PermissionSpec {
    ReadUser  = 0400, WriteUser  = 0200, ExeUser  = 0100,
    ReadGroup = 0040, WriteGroup = 0020, ExeGroup = 0010,
    ReadOther = 0004, WriteOther = 0002, ExeOther = 0001 };

    QFileInfo();
    QFileInfo( const QString &file );
    QFileInfo( const QFile & );
#ifndef QT_NO_DIR
    QFileInfo( const QDir &, const QString &fileName );
#endif
    QFileInfo( const QFileInfo & );
   ~QFileInfo();

    QFileInfo  &operator=( const QFileInfo & );

    void	setFile( const QString &file );
    void	setFile( const QFile & );
#ifndef QT_NO_DIR
    void	setFile( const QDir &, const QString &fileName );
#endif
    bool	exists()	const;
    void	refresh()	const;
    bool	caching()	const;
    void	setCaching( bool );

    QString	filePath()	const;
    QString	fileName()	const;
#ifndef QT_NO_DIR //###
    QString	absFilePath()	const;
#endif
    QString	baseName( bool complete = FALSE ) const;
    QString	extension( bool complete = TRUE ) const;

#ifndef QT_NO_DIR //###
    QString	dirPath( bool absPath = FALSE ) const;
#endif
#ifndef QT_NO_DIR
    QDir	dir( bool absPath = FALSE )	const;
#endif
    bool	isReadable()	const;
    bool	isWritable()	const;
    bool	isExecutable()	const;

#ifndef QT_NO_DIR //###
    bool	isRelative()	const;
    bool	convertToAbs();
#endif

    bool	isFile()	const;
    bool	isDir()		const;
    bool	isSymLink()	const;

    QString	readLink()	const;

    QString	owner()		const;
    uint	ownerId()	const;
    QString	group()		const;
    uint	groupId()	const;

    bool	permission( int permissionSpec ) const;

    uint	size()		const;

    QDateTime	created()	const;
    QDateTime	lastModified()	const;
    QDateTime	lastRead()	const;

private:
    void	doStat() const;
    static void slashify( QString & );
    static void makeAbs( QString & );

    QString	fn;
    QFileInfoCache *fic;
    bool	cache;
#if defined(Q_OS_UNIX)
    bool        symLink;
#endif

};

inline bool QFileInfo::caching() const
{
    return cache;
}

#endif // QFILEINFO_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFileInfo Member List

Complete Member List for QFileInfo

This is the complete list of member functions for QFileInfo, including inherited members.

  • QFileInfo()
  • ~QFileInfo()
  • absFilePath()
  • baseName()
  • caching()
  • convertToAbs()
  • created()
  • dir()
  • dirPath()
  • exists()
  • extension()
  • fileName()
  • filePath()
  • group()
  • groupId()
  • isDir()
  • isExecutable()
  • isFile()
  • isReadable()
  • isRelative()
  • isSymLink()
  • isWritable()
  • lastModified()
  • lastRead()
  • operator=()
  • owner()
  • ownerId()
  • permission()
  • readLink()
  • refresh()
  • setCaching()
  • setFile()
  • size()


QFilePreview Class

QFilePreview Class Reference

The QFilePreview class provides file previewing in QFileDialog. More...

#include <qfiledialog.h>

List of all member functions.

Public Members

  • QFilePreview ()
  • virtual void previewUrl ( const QUrl & url ) = 0

Detailed Description

The QFilePreview class provides file previewing in QFileDialog.

This class is an abstract base class which is used to implement widgets that can display a preview of a file in a QFileDialog.

You must derive the preview widget from both QWidget and from this class. Then you must reimplement this class's previewUrl() function, which is called by the file dialog if the preview of a file (specified as a URL) should be shown.

 See also QFileDialog::setPreviewMode(), QFileDialog::setContentsPreview(),
QFileDialog::setInfoPreview(), QFileDialog::setInfoPreviewEnabled(),
QFileDialog::setContentsPreviewEnabled().

For an example of a preview widget see qt/examples/qdir/qdir.cpp.

See also Miscellaneous Classes.

Member Function Documentation

QFilePreview::QFilePreview ()

Constructs the QFilePreview.

void QFilePreview::previewUrl ( const QUrl & url ) [pure virtual]

This function is called by QFileDialog if a preview for the url should be shown. Reimplement this function to provide file previewing.

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


QFilePreview Member List

Complete Member List for QFilePreview

This is the complete list of member functions for QFilePreview, including inherited members.

  • QFilePreview()
  • previewUrl()


QFocusData Class

QFocusData Class Reference

The QFocusData class maintains the list of widgets in the focus chain. More...

#include <qfocusdata.h>

List of all member functions.

Public Members

  • QWidget * focusWidget () const
  • QWidget * home ()
  • QWidget * next ()
  • QWidget * prev ()
  • int count () const

Detailed Description

The QFocusData class maintains the list of widgets in the focus chain.

This read-only list always contains at least one widget (i.e. the top-level widget). It provides a simple cursor which can be reset to the current focus widget using home(), or moved to its neighboring widgets using next() and prev(). You can also retrieve the count() of the number of widgets in the list. The list is a loop, so if you keep iterating, for example using next(), you will never come to the end.

Some widgets in the list may not accept focus. Widgets are added to the list as necessary, but not removed from it. This lets widgets change focus policy dynamically without disrupting the focus chain the user experiences. When a widget disables and re-enables tab focus, its position in the focus chain does not change.

When reimplementing QWidget::focusNextPrevChild() to provide special focus flow, you will usually call QWidget::focusData() to retrieve the focus data stored at the top-level widget. A top-level widget's focus data contains the focus list for its hierarchy of widgets.

The cursor may change at any time.

This class is not thread-safe.

See also QWidget::focusNextPrevChild(), QWidget::setTabOrder(), QWidget::focusPolicy and Miscellaneous Classes.

Member Function Documentation

int QFocusData::count () const

Returns the number of widgets in the focus chain.

QWidget * QFocusData::focusWidget () const

Returns the widgets in the hierarchy that are in the focus chain.

QWidget * QFocusData::home ()

Moves the cursor to the focusWidget() and returns that widget. You must call this before next() or prev() to iterate meaningfully.

QWidget * QFocusData::next ()

Moves the cursor to the next widget in the focus chain. There is always a next widget because the list is a loop.

QWidget * QFocusData::prev ()

Moves the cursor to the previous widget in the focus chain. There is always a previous widget because the list is a loop.

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


qfocusdata.h Include File

qfocusdata.h

This is the verbatim text of the qfocusdata.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qfocusdata.h   3.0.5   edited Nov 1 2001 $
**
** Definition of internal QFocusData class
**
** Created : 980405
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFOCUSDATA_H
#define QFOCUSDATA_H

#ifndef QT_H
#include "qwidgetlist.h"
#endif // QT_H

class Q_EXPORT QFocusData {
public:
    QWidget* focusWidget() const { return it.current(); }

    QWidget* home();
    QWidget* next();
    QWidget* prev();
    int count() const { return focusWidgets.count(); }

private:
    friend class QWidget;

    QFocusData()
    : it(focusWidgets) {}
    QWidgetList	  focusWidgets;
    QWidgetListIt it;
};

#endif // QFOCUSDATA_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFocusData Member List

Complete Member List for QFocusData

This is the complete list of member functions for QFocusData, including inherited members.

  • count()
  • focusWidget()
  • home()
  • next()
  • prev()


QFocusEvent Class

QFocusEvent Class Reference

The QFocusEvent class contains event parameters for widget focus events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QFocusEvent ( Type type )
  • bool gotFocus () const
  • bool lostFocus () const
  • enum Reason { Mouse, Tab, Backtab, ActiveWindow, Popup, Shortcut, Other }

Static Public Members

  • Reason reason ()
  • void setReason ( Reason reason )
  • void resetReason ()

Detailed Description

The QFocusEvent class contains event parameters for widget focus events.

Focus events are sent to widgets when the keyboard input focus changes. Focus events occur due to mouse actions, keypresses (e.g. Tab or Backtab), the window system, popup menus, keyboard shortcuts or other application specific reasons. The reason for a particular focus event is returned by reason() in the appropriate event handler.

The event handlers QWidget::focusInEvent() and QWidget::focusOutEvent() receive focus events.

Use setReason() to set the reason for all focus events, and resetReason() to set the reason for all focus events to the reason in force before the last setReason() call.

See also QWidget::setFocus(), QWidget::focusPolicy and Event Classes.

Member Type Documentation

QFocusEvent::Reason

This enum specifies why the focus changed.

  • QFocusEvent::Mouse - because of a mouse action.
  • QFocusEvent::Tab - because of a Tab press.
  • QFocusEvent::Backtab - because of a Backtab press (possibly including Shift/Control, e.g. Shift+Tab).
  • QFocusEvent::ActiveWindow - because the window system made this window (in)active.
  • QFocusEvent::Popup - because the application opened/closed a popup that grabbed/released focus.
  • QFocusEvent::Shortcut - because of a keyboard shortcut.
  • QFocusEvent::Other - any other reason, usually application-specific.

See the keyboard focus overview for more about focus.

Member Function Documentation

QFocusEvent::QFocusEvent ( Type type )

Constructs a focus event object.

The type parameter must be either QEvent::FocusIn or QEvent::FocusOut.

bool QFocusEvent::gotFocus () const

Returns TRUE if the widget received the text input focus; otherwise returns FALSE.

bool QFocusEvent::lostFocus () const

Returns TRUE if the widget lost the text input focus; otherwise returns FALSE.

Reason QFocusEvent::reason () [static]

Returns the reason for this focus event.

See also setReason().

void QFocusEvent::resetReason () [static]

Resets the reason for all future focus events to the value before the last setReason() call.

See also reason() and setReason().

void QFocusEvent::setReason ( Reason reason ) [static]

Sets the reason for all future focus events to reason.

See also reason() and resetReason().

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


QFocusEvent Member List

Complete Member List for QFocusEvent

This is the complete list of member functions for QFocusEvent, including inherited members.

  • QFocusEvent()
  • gotFocus()
  • lostFocus()
  • reason()
  • resetReason()
  • setReason()
  • spontaneous()
  • type()


QFont Class

QFont Class Reference

The QFont class specifies a font used for drawing text. More...

#include <qfont.h>

List of all member functions.

Public Members

  • enum StyleHint { Helvetica, SansSerif = Helvetica, Times, Serif = Times, Courier, TypeWriter = Courier, OldEnglish, Decorative = OldEnglish, System, AnyStyle }
  • enum StyleStrategy { PreferDefault = 0x0001, PreferBitmap = 0x0002, PreferDevice = 0x0004, PreferOutline = 0x0008, ForceOutline = 0x0010, PreferMatch = 0x0020, PreferQuality = 0x0040, PreferAntialias = 0x0080, NoAntialias = 0x0100 }
  • enum Weight { Light = 25, Normal = 50, DemiBold = 63, Bold = 75, Black = 87 }
  • QFont ()
  • QFont ( const QString & family, int pointSize = 12, int weight = Normal, bool italic = FALSE )
  • QFont ( const QFont & font )
  • ~QFont ()
  • QString family () const
  • void setFamily ( const QString & family )
  • int pointSize () const
  • float pointSizeFloat () const
  • void setPointSize ( int pointSize )
  • void setPointSizeFloat ( float pointSize )
  • int pixelSize () const
  • void setPixelSize ( int pixelSize )
  • void setPixelSizeFloat ( float pixelSize ) (obsolete)
  • int weight () const
  • void setWeight ( int weight )
  • bool bold () const
  • void setBold ( bool enable )
  • bool italic () const
  • void setItalic ( bool enable )
  • bool underline () const
  • void setUnderline ( bool enable )
  • bool strikeOut () const
  • void setStrikeOut ( bool enable )
  • bool fixedPitch () const
  • void setFixedPitch ( bool enable )
  • StyleHint styleHint () const
  • StyleStrategy styleStrategy () const
  • void setStyleHint ( StyleHint hint, StyleStrategy strategy = PreferDefault )
  • void setStyleStrategy ( StyleStrategy s )
  • bool rawMode () const
  • void setRawMode ( bool enable )
  • bool exactMatch () const
  • QFont & operator= ( const QFont & font )
  • bool operator== ( const QFont & f ) const
  • bool operator!= ( const QFont & f ) const
  • bool isCopyOf ( const QFont & f ) const
  • HFONT handle () const
  • void setRawName ( const QString & name )
  • QString rawName () const
  • QString key () const
  • QString toString () const
  • bool fromString ( const QString & descrip )
  • void qwsRenderToDisk ( bool all = TRUE )
  • enum Script { Latin, Greek, Cyrillic, Armenian, Georgian, Runic, Ogham, SpacingModifiers, CombiningMarks, Hebrew, Arabic, Syriac, Thaana, Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Sinhala, Thai, Lao, Tibetan, Myanmar, Khmer, Han, Hiragana, Katakana, Hangul, Bopomofo, Yi, Ethiopic, Cherokee, CanadianAboriginal, Mongolian, CurrencySymbols, LetterlikeSymbols, NumberForms, MathematicalOperators, TechnicalSymbols, GeometricSymbols, MiscellaneousSymbols, EnclosedAndSquare, Braille, Unicode, NScripts, UnknownScript = NScripts, NoScript, HanX11, LatinBasic = Latin, LatinExtendedA_2 = HanX11 + 1, LatinExtendedA_3, LatinExtendedA_4, LatinExtendedA_14, LatinExtendedA_15, LastPrivateScript }
  • QString defaultFamily () const
  • QString lastResortFamily () const
  • QString lastResortFont () const

Static Public Members

  • QString substitute ( const QString & familyName )
  • QStringList substitutes ( const QString & familyName )
  • QStringList substitutions ()
  • void insertSubstitution ( const QString & familyName, const QString & substituteName )
  • void insertSubstitutions ( const QString & familyName, const QStringList & substituteNames )
  • void removeSubstitution ( const QString & familyName )
  • QFont defaultFont () (obsolete)
  • void setDefaultFont ( const QFont & f ) (obsolete)

Protected Members

  • bool dirty () const
  • int deciPointSize () const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QFont & font )
  • QDataStream & operator>> ( QDataStream & s, QFont & font )

Detailed Description

The QFont class specifies a font used for drawing text.

When you create a QFont object you specify various attributes that you want the font to have. Qt will use the font with the specified attributes, or if no matching font exists, Qt will use the closest matching installed font. The attributes of the font that is actually used are retrievable from a QFontInfo object. If the window system provides an exact match exactMatch() returns TRUE. Use QFontMetrics to get measurements, e.g. the pixel length of a string using QFontMetrics::width().

Use QApplication::setFont() to set the application's default font.

If a choosen X11 font does not include all the characters that need to be displayed, QFont will try to find the characters in the nearest equivalent fonts. When a QPainter draws a character from a font the QFont will report whether or not it has the character; if it does not, QPainter will draw an unfilled square.

Create QFonts like this:

    QFont serifFont( "Times", 10, Bold );
    QFont sansFont( "Helvetica [Cronyx]", 12 );

The attributes set in the constructor can also be set later, e.g. setFamily(), setPointSize(), setPointSizeFloat(), setWeight() and setItalic(). The remaining attributes must be set after contstruction, e.g. setBold(), setUnderline(), setStrikeOut() and setFixedPitch(). QFontInfo objects should be created after the font's attributes have been set. A QFontInfo object will not change, even if you change the font's attributes. The corresponding "get" functions, e.g. family(), pointSize(), etc., return the values that were set, even though the values used may differ. The actual values are available from a QFontInfo object.

If the requested font family is unavailable you can influence the font matching algorithm by choosing a particular QFont::StyleHint and QFont::StyleStrategy with setStyleHint(). The default family (corresponding to the current style hint) is returned by defaultFamily().

The font-matching algorithm has a lastResortFamily() and lastResortFont() in cases where a suitable match cannot be found. You can provide substitutions for font family names using insertSubstitution() and insertSubstitutions(). Substitutions can be removed with removeSubstitution(). Use substitute() to retrieve a family's first substitute, or the family name itself if it has no substitutes. Use substitutes() to retrieve a list of a family's substitutes (which may be empty).

Every QFont has a key() which you can use, for example, as the key in a cache or dictionary. If you want to store a user's font preferences you could use QSettings, writing the font information with toString() and reading it back with fromString(). The operator<<() and operator>>() functions are also available, but they work on a data stream.

It is possible to set the height of characters shown on the screen to a specified number of pixels with setPixelSize(); however using setPointSize() has a similar effect and provides device independence.

Under the X Window System you can set a font using its system specific name with setRawName().

Loading fonts can be expensive, especially on X11. QFont contains extensive optimizations to make the copying of QFont objects fast, and to cache the results of the slow window system functions it depends upon.

The font matching algorithm works as follows:

  1. The specified font family is searched for.
  2. If not found, the styleHint() is used to select a replacement family.
  3. Each replacement font family is searched for.
  4. If none of these are found or there was no styleHint(), "helvetica" will be searched for.
  5. If "helvetica" isn't found Qt will try the lastResortFamily().
  6. If the lastResortFamily() isn't found Qt will try the lastResortFont() which will always return a name of some kind.

Once a font is found, the remaining attributes are matched in order of priority:

  1. fixedPitch()
  2. pointSize() (see below)
  3. weight()
  4. italic()

If you have a font which matches on family, even if none of the other attributes match, this font will be chosen in preference to a font which doesn't match on family but which does match on the other attributes. This is because font family is the dominant search criteria.

The point size is defined to match if it is within 20% of the requested point size. When several fonts match and are only distinguished by point size, the font with the closest point size to the one requested will be chosen.

The actual family, font size, weight and other font attributes used for drawing text will depend on what's available for the chosen family under the window system. A QFontInfo object can be used to determine the actual values used for drawing the text.

Examples:

    QFont f("Helvetica");
If you had both an Adobe and a Cronyx Helvetica, you might get either.

    QFont f1( "Helvetica [Cronyx]" );  // Qt 3.x
    QFont f2( "Cronyx-Helvetica" );    // Qt 2.x compatibility
You can specify the foundry you want in the family name. Both fonts, f1 and f2, in the above example will be set to "Helvetica [Cronyx]".

To determine the attributes of the font actually used in the window system, use a QFontInfo object, e.g.

    QFontInfo info( f1 );
    QString family = info.family();

To find out font metrics use a QFontMetrics object, e.g.

    QFontMetrics fm( f1 );
    int pixelWidth = fm.width( "How many pixels wide is this text?" );
    int pixelHeight = fm.height();

For more general information on fonts, see the comp.fonts FAQ. Information on encodings can be found from Roman Czyborra's page.

See also QFontMetrics, QFontInfo, QFontDatabase, QApplication::setFont(), QWidget::font, QPainter::setFont(), QFont::StyleHint, QFont::Weight, Widget Appearance and Style, Graphics Classes and Implicitly and Explicitly Shared Classes.

Member Type Documentation

QFont::Script

This enum represents Unicode allocated scripts. For exhaustive coverage see The Unicode Standard Version 3.0. The following scripts are supported:

Modern European alphabetic scripts (left to right):

  • QFont::Latin - consists of most alphabets based on the original Latin alphabet.
  • QFont::Greek - covers ancient and modern Greek and Coptic.
  • QFont::Cyrillic - covers the Slavic and non-Slavic languages using cyrillic alphabets.
  • QFont::Armenian - contains the Armenian alphabet used with the Armenian language.
  • QFont::Georgian - covers at least the language Georgian.
  • QFont::Runic - covers the known constituents of the Runic alphabets used by the early and medieval societies in the Germanic, Scandinavian, and Anglo-Saxon areas.
  • QFont::Ogham - is an alphabetical script used to write a very early form of Irish.
  • QFont::SpacingModifiers - are small signs indicating modifications to the preceeding letter.
  • QFont::CombiningMarks - consist of diacritical marks not specific to a particular alphabet, diacritical marks used in combination with mathematical and technical symbols, and glyph encodings applied to multiple letterforms.

Middle Eastern scripts (right to left):

  • QFont::Hebrew - is used for writing Hebrew, Yiddish, and some other languages.
  • QFont::Arabic - covers the Arabic language as well as Persian, Urdu, Kurdish and some others.
  • QFont::Syriac - is used to write the active liturgical languages and dialects of several Middle Eastern and Southeast Indian communities.
  • QFont::Thaana - is used to write the Maledivian Dhivehi language.

South and Southeast Asian scripts (left to right with few historical exceptions):

  • QFont::Devanagari - covers classical Sanskrit and modern Hindi as well as several other languages.
  • QFont::Bengali - is a relative to Devanagari employed to write the Bengali language used in West Bengal/India and Bangladesh as well as several minority languages.
  • QFont::Gurmukhi - is another Devanagari relative used to write Punjabi.
  • QFont::Gujarati - is closely related to Devanagari and used to write the Gujarati language of the Gujarat state in India.
  • QFont::Oriya - is used to write the Oriya language of Orissa state/India.
  • QFont::Tamil - is used to write the Tamil language of Tamil Nadu state/India, Sri Lanka, Singapore and parts of Malaysia as well as some minority languages.
  • QFont::Telugu - is used to write the Telugu language of Andhra Pradesh state/India and some minority languages.
  • QFont::Kannada - is another South Indian script used to write the Kannada language of Karnataka state/India and some minority languages.
  • QFont::Malayalam - is used to write the Malayalam language of Kerala state/India.
  • QFont::Sinhala - is used for Sri Lanka's majority language Sinhala and is also employed to write Pali, Sanskrit, and Tamil.
  • QFont::Thai - is used to write Thai and other Southeast Asian languages.
  • QFont::Lao - is a language and script quite similar to Thai.
  • QFont::Tibetan - is the script used to write Tibetan in several countries like Tibet, the bordering Indian regions and Nepal. It is also used in the Buddist philosophy and liturgy of the Mongolian cultural area.
  • QFont::Myanmar - is mainly used to write the Burmese language of Myanmar (former Burma).
  • QFont::Khmer - is the official language of Kampuchea.

East Asian scripts (traditionally top-down, right to left, modern often horizontal left to right):

  • QFont::Han - consists of the CJK (Chinese, Japanese, Korean) idiographic characters.
  • QFont::Hiragana - is a cursive syllabary used to indicate phonetics and pronounciation of Japanese words.
  • QFont::Katakana - is a non-cursive syllabic script used to write Japanese words with visual emphasis and non-Japanese words in a phonetical manner.
  • QFont::Hangul - is a Korean script consisting of alphabetic components.
  • QFont::Bopomofo - is a phonetic alphabet for Chinese (mainly Mandarin).
  • QFont::Yi - (also called Cuan or Wei) is a syllabary used to write the Yi language of Southwestern China, Myanmar, Laos, and Vietnam.

Additional scripts that do not fit well into the script categories above:

  • QFont::Ethiopic - is a syllabary used by several Central East African languages.
  • QFont::Cherokee - is a left-to-right syllabic script used to write the Cherokee language.
  • QFont::CanadianAboriginal - consists of the syllabics used by some Canadian aboriginal societies.
  • QFont::Mongolian - is the traditional (and recently reintroduced) script used to write Mongolian.

Symbols:

  • QFont::CurrencySymbols - contains currency symbols not encoded in other scripts.
  • QFont::LetterlikeSymbols - consists of symbols derived from ordinary letters of an alphabetical script.
  • QFont::NumberForms - are provided for compatibility with other existing character sets.
  • QFont::MathematicalOperators - consists of encodings for operators, relations and other symbols like arrows used in a mathematical context.
  • QFont::TechnicalSymbols - contains representations for control codes, the space symbol, APL symbols and other symbols mainly used in the context of electronic data processing.
  • QFont::GeometricSymbols - covers block elements and geometric shapes.
  • QFont::MiscellaneousSymbols - consists of a heterogeneous collection of symbols that do not fit any other Unicode character block, e.g. Dingbats.
  • QFont::EnclosedAndSquare - is provided for compatibility with some East Asian standards.
  • QFont::Braille - is an international writing system used by blind people. This script encodes the 256 eight-dot patterns with the 64 six-dot patterns as a subset.

  • QFont::Unicode - includes all the above scripts.

The values below are provided for completeness and must not be used in user programs.

  • QFont::HanX11 - For internal use only.
  • QFont::LatinBasic - For internal use only.
  • QFont::LatinExtendedA_2 - For internal use only.
  • QFont::LatinExtendedA_3 - For internal use only.
  • QFont::LatinExtendedA_4 - For internal use only.
  • QFont::LatinExtendedA_14 - For internal use only.
  • QFont::LatinExtendedA_15 - For internal use only.
  • QFont::LastPrivateScript - For internal use only.
  • QFont::NScripts - For internal use only.
  • QFont::NoScript - For internal use only.
  • QFont::UnknownScript - For internal use only.

QFont::StyleHint

Style hints are used by the font matching algorithm to find an appropriate default family if a selected font family is not available.

  • QFont::AnyStyle - leaves the font matching algorithm to choose the family. This is the default.
  • QFont::SansSerif - the font matcher prefer sans serif fonts.
  • QFont::Helvetica - is a synonym for SansSerif.
  • QFont::Serif - the font matcher prefers serif fonts.
  • QFont::Times - is a synonym for Serif.
  • QFont::TypeWriter - the font matcher prefers fixed pitch fonts.
  • QFont::Courier - a synonym for TypeWriter.
  • QFont::OldEnglish - the font matcher prefers decorative fonts.
  • QFont::Decorative - is a synonym for OldEnglish.
  • QFont::System - the font matcher prefers system fonts.

QFont::StyleStrategy

The style strategy tells the font matching algorithm what type of fonts should be used to find an appropriate default family.

The following strategies are available:

  • QFont::PreferDefault - the default style strategy. It does not prefer any type of font.
  • QFont::PreferBitmap - prefers bitmap fonts (as opposed to outline fonts). On X11, this will cause Qt to disregard fonts from the Xft font extension.
  • QFont::PreferDevice - prefers device fonts.
  • QFont::PreferOutline - prefers outline fonts (as opposed to bitmap fonts).
  • QFont::ForceOutline - forces the use of outline fonts.
  • QFont::NoAntialias - don't antialias the fonts.
  • QFont::PreferAntialias - antialias if possible.

Any of these may be OR-ed with one of these flags:

  • QFont::PreferMatch - prefer an exact match. The font matcher will try to use the exact font size that has been specified.
  • QFont::PreferQuality - prefer the best quality font. The font matcher will use the nearest standard point size that the font supports.

QFont::Weight

Qt uses a weighting scale from 0 to 99 similar to, but not the same as, the scales used in Windows or CSS. A weight of 0 is ultralight, whilst 99 will be an extremely black.

This enum contains the predefined font weights:

  • QFont::Light - 25
  • QFont::Normal - 50
  • QFont::DemiBold - 63
  • QFont::Bold - 75
  • QFont::Black - 87

Member Function Documentation

QFont::QFont ()

Constructs a font object that uses the application's default font.

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

QFont::QFont ( const QString & family, int pointSize = 12, int weight = Normal, bool italic = FALSE )

Constructs a font object with the specified family, pointSize, weight and italic settings.

If pointSize is <= 0 it is set to 1.

The family name may optionally also include a foundry name, e.g. "Helvetica [Cronyx]". (The Qt 2.x syntax, i.e. "Cronyx-Helvetica", is also supported.) If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm.

See also Weight, setFamily(), setPointSize(), setWeight(), setItalic(), setStyleHint() and QApplication::font().

QFont::QFont ( const QFont & font )

Constructs a font that is a copy of font.

QFont::~QFont ()

Destroys the font object and frees all allocated resources.

bool QFont::bold () const

Returns TRUE if weight() is a value greater than QFont::Normal; otherwise returns FALSE.

See also weight(), setBold() and QFontInfo::bold().

Example: chart/optionsform.cpp.

int QFont::deciPointSize () const [protected]

Returns the point size in 1/10ths of a point.

The returned value will be -1 if the font size has been specified in pixels.

See also pointSize() and pointSizeFloat().

QString QFont::defaultFamily () const

Returns the family name that corresponds to the current style hint.

See also StyleHint, styleHint() and setStyleHint().

QFont QFont::defaultFont () [static]

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

Please use QApplication::font() instead.

bool QFont::dirty () const [protected]

Returns TRUE if the font attributes have been changed and the font has to be (re)loaded; otherwise returns FALSE.

bool QFont::exactMatch () const

Returns TRUE if a window system font exactly matching the settings of this font is available.

See also QFontInfo.

QString QFont::family () const

Returns the requested font family name, i.e. the name set in the constructor or the last setFont() call.

See also setFamily(), substitutes() and substitute().

Examples: chart/optionsform.cpp and fonts/simple-qfont-demo/viewer.cpp.

bool QFont::fixedPitch () const

Returns TRUE if fixed pitch has been set; otherwise returns FALSE.

See also setFixedPitch() and QFontInfo::fixedPitch().

bool QFont::fromString ( const QString & descrip )

Sets this font to match the description descrip. The description is a comma-separated list of the font attributes, as returned by toString().

See also toString() and operator>>().

HFONT QFont::handle () const

Returns the window system handle to the font, for low-level access. Using this function is not portable.

void QFont::insertSubstitution ( const QString & familyName, const QString & substituteName ) [static]

Inserts the family name substituteName into the substitution table for familyName.

See also insertSubstitutions(), removeSubstitution(), substitutions(), substitute() and substitutes().

Example: fonts/simple-qfont-demo/viewer.cpp.

void QFont::insertSubstitutions ( const QString & familyName, const QStringList & substituteNames ) [static]

Inserts the list of families substituteNames into the substitution list for familyName.

See also insertSubstitution(), removeSubstitution(), substitutions() and substitute().

Example: fonts/simple-qfont-demo/viewer.cpp.

bool QFont::isCopyOf ( const QFont & f ) const

Returns TRUE if this font and f are copies of each other, i.e. one of them was created as a copy of the other and neither has been modified since. This is much stricter than equality.

See also operator=() and operator==().

bool QFont::italic () const

Returns TRUE if italic has been set; otherwise returns FALSE.

See also setItalic().

Example: chart/optionsform.cpp.

QString QFont::key () const

Returns the font's key, a textual representation of a font. It is typically used as the key for a cache or dictionary of fonts.

See also QMap.

QString QFont::lastResortFamily () const

Returns the "last resort" font family name.

The current implementation tries a wide variety of common fonts, returning the first one it finds. Is is possible that no family is found in which case a null string is returned.

See also lastResortFont().

QString QFont::lastResortFont () const

Returns a "last resort" font name for the font matching algorithm. This is used if the last resort family is not available. It will always return a name, if necessary returning something like "fixed" or "system".

The current implementation tries a wide variety of common fonts, returning the first one it finds. The implementation may change at any time, but this function will always return a string containing something.

It is theoretically possible that there really isn't a lastResortFont() in which case Qt will abort with an error message. We have not been able to identify a case where this happens. Please report it as a bug if it does, preferably with a list of the fonts you have installed.

See also lastResortFamily() and rawName().

bool QFont::operator!= ( const QFont & f ) const

Returns TRUE if this font is different from f; otherwise returns FALSE.

Two QFonts are considered to be different if their font attributes are different. If rawMode() is enabled for both fonts, only the family fields are compared.

See also operator==().

QFont & QFont::operator= ( const QFont & font )

Assigns font to this font and returns a reference to it.

bool QFont::operator== ( const QFont & f ) const

Returns TRUE if this font is equal to f; otherwise returns FALSE.

Two QFonts are considered equal if their font attributes are equal. If rawMode() is enabled for both fonts, only the family fields are compared.

See also operator!=() and isCopyOf().

int QFont::pixelSize () const

Returns the pixel size of the font if it was set with setPixelSize(). Returns -1 if the size was set with setPointSize() or setPointSizeFloat().

See also setPixelSize(), pointSize(), QFontInfo::pointSize() and QFontInfo::pixelSize().

int QFont::pointSize () const

Returns the point size of the font. Returns -1 if the font size was specified in pixels.

See also setPointSize(), deciPointSize() and pointSizeFloat().

Examples: chart/optionsform.cpp and fonts/simple-qfont-demo/viewer.cpp.

float QFont::pointSizeFloat () const

Returns the point size of the font. Returns -1 if the font size was specified in pixels.

See also pointSize(), setPointSizeFloat(), pixelSize(), QFontInfo::pointSize() and QFontInfo::pixelSize().

void QFont::qwsRenderToDisk ( bool all = TRUE )

Saves the glyphs in the font that have previously been accessed as a QPF file. If all is TRUE (the default), then before saving, all glyphs are marked as used.

If the font is large and you are sure that only a subset of characters will ever be required on the target device, passing FALSE for the all parameter can save a significant amount of disk space.

Note that this function is only applicable on Qt/Embedded.

bool QFont::rawMode () const

Returns TRUE if raw mode is used for font name matching; otherwise returns FALSE.

See also setRawMode() and rawName().

QString QFont::rawName () const

Returns the name of the font within the underlying window system. On Windows, this is usually just the family name of a TrueType font. Under X, it is an XLFD (X Logical Font Description). Using the return value of this function is usually not portable.

See also setRawName().

void QFont::removeSubstitution ( const QString & familyName ) [static]

Removes all the substitutions for familyName.

See also insertSubstitutions(), insertSubstitution(), substitutions() and substitute().

void QFont::setBold ( bool enable )

If enable is true sets the font's weight to QFont::Bold; otherwise sets the weight to QFont::Normal.

For finer boldness control use setWeight().

See also bold() and setWeight().

Examples: menu/menu.cpp and themes/metal.cpp.

void QFont::setDefaultFont ( const QFont & f ) [static]

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

Please use QApplication::setFont() instead.

void QFont::setFamily ( const QString & family )

Sets the family name of the font. The name is case insensitive and may include a foundry name.

The family name may optionally also include a foundry name, e.g. "Helvetica [Cronyx]". (The Qt 2.x syntax, i.e. "Cronyx-Helvetica", is also supported.) If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm.

See also family(), setStyleHint() and QFontInfo.

void QFont::setFixedPitch ( bool enable )

If enable is TRUE, sets fixed pitch on; otherwise sets fixed pitch off.

See also fixedPitch() and QFontInfo.

void QFont::setItalic ( bool enable )

If enable is TRUE, italic is set on; otherwise italic is set off.

See also italic() and QFontInfo.

Examples: fileiconview/qfileiconview.cpp, fonts/simple-qfont-demo/viewer.cpp and themes/metal.cpp.

void QFont::setPixelSize ( int pixelSize )

Sets the font size to pixelSize pixels.

Using this function makes the font device dependent. Use setPointSize() or setPointSizeFloat() to set the size of the font in a device independent manner.

See also pixelSize().

Example: qwerty/qwerty.cpp.

void QFont::setPixelSizeFloat ( float pixelSize )

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

Sets the logical pixel height of font characters when shown on the screen to pixelSize.

void QFont::setPointSize ( int pointSize )

Sets the point size to pointSize. The point size must be greater than zero.

See also pointSize() and setPointSizeFloat().

Example: fonts/simple-qfont-demo/viewer.cpp.

void QFont::setPointSizeFloat ( float pointSize )

Sets the point size to pointSize. The point size must be greater than zero. The requested precision may not be achieved on all platforms.

See also pointSizeFloat(), setPointSize() and setPixelSize().

void QFont::setRawMode ( bool enable )

If enable is TRUE, turns raw mode on; otherwise turns raw mode off. This function only has an effect under X11.

If raw mode is enabled, Qt will search for an X font with a complete font name matching the family name, ignoring all other values set for the QFont. If the font name matches several fonts, Qt will use the first font returned by X. QFontInfo cannot be used to fetch information about a QFont using raw mode (it will return the values set in the QFont for all parameters, including the family name).

Warning: Do not use raw mode unless you really, really need it! In most (if not all) cases, setRawName() is a much better choice.

See also rawMode() and setRawName().

void QFont::setRawName ( const QString & name )

Sets a font by its system specific name. The function is particularly useful under X, where system font settings (for example X resources) are usually available in XLFD (X Logical Font Description) form only. You can pass an XLFD as name to this function.

In Qt 2.0 and later, a font set with setRawName() is still a full-featured QFont. It can be queried (for example with italic()) or modified (for example with setItalic()) and is therefore also suitable for rendering rich text.

If Qt's internal font database cannot resolve the raw name, the font becomes a raw font with name as its family.

Note that the present implementation does not handle wildcards in XLFDs well, and that font aliases (file fonts.alias in the font directory on X11) are not supported.

See also rawName(), setRawMode() and setFamily().

void QFont::setStrikeOut ( bool enable )

If enable is TRUE, sets strikeout on; otherwise sets strikeout off.

See also strikeOut() and QFontInfo.

void QFont::setStyleHint ( StyleHint hint, StyleStrategy strategy = PreferDefault )

Sets the style hint and strategy to hint and strategy, respectively.

If these aren't set explicitly the style hint will default to AnyStyle and the style strategy to PreferDefault.

See also StyleHint, styleHint(), StyleStrategy, styleStrategy() and QFontInfo.

Examples: desktop/desktop.cpp and fonts/simple-qfont-demo/viewer.cpp.

void QFont::setStyleStrategy ( StyleStrategy s )

Sets the style strategy for the font to s.

See also QFont::StyleStrategy.

void QFont::setUnderline ( bool enable )

If enable is TRUE, sets underline on; otherwise sets underline off.

See also underline() and QFontInfo.

Examples: fonts/simple-qfont-demo/viewer.cpp and menu/menu.cpp.

void QFont::setWeight ( int weight )

Sets the weight the font to weight, which should be a value from the QFont::Weight enumeration.

See also weight() and QFontInfo.

Example: fonts/simple-qfont-demo/viewer.cpp.

bool QFont::strikeOut () const

Returns TRUE if strikeout has been set; otherwise returns FALSE.

See also setStrikeOut().

StyleHint QFont::styleHint () const

Returns the StyleHint.

The style hint affects the font matching algorithm. See QFont::StyleHint for the list of strategies.

See also setStyleHint(), QFont::StyleStrategy and QFontInfo::styleHint().

StyleStrategy QFont::styleStrategy () const

Returns the StyleStrategy.

The style strategy affects the font matching algorithm. See QFont::StyleStrategy for the list of strategies.

See also setStyleHint() and QFont::StyleHint.

QString QFont::substitute ( const QString & familyName ) [static]

Returns the first family name to be used whenever familyName is specified. The lookup is case insensitive.

If there is no substitution for familyName, familyName is returned.

To obtain a list of substitutions use substitutes().

See also setFamily(), insertSubstitutions(), insertSubstitution() and removeSubstitution().

QStringList QFont::substitutes ( const QString & familyName ) [static]

Returns a list of family names to be used whenever familyName is specified. The lookup is case insensitive.

If there is no substitution for familyName, an empty list is returned.

See also substitute(), insertSubstitutions(), insertSubstitution() and removeSubstitution().

Example: fonts/simple-qfont-demo/viewer.cpp.

QStringList QFont::substitutions () [static]

Returns a sorted list of substituted family names.

See also insertSubstitution(), removeSubstitution() and substitute().

QString QFont::toString () const

Returns a description of the font. The description is a comma-separated list of the attributes, perfectly suited for use in QSettings.

See also fromString() and operator<<().

bool QFont::underline () const

Returns TRUE if underline has been set; otherwise returns FALSE.

See also setUnderline().

int QFont::weight () const

Returns the weight of the font which is one of the enumerated values from QFont::Weight.

See also setWeight(), Weight and QFontInfo.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QFont & font )

Writes the font font to the data stream s. (toString() writes to a text stream.)

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QFont & font )

Reads the font font from the data stream s. (fromString() reads from a text stream.)

See also Format of the QDataStream operators.

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


QFont Examples

The following example programs show how to use the classes QFont, QFontMetrics, QFontInfo, and QFontDatabase.

A simple demonstration of QFont member functions


qfont.h Include File

qfont.h

This is the verbatim text of the qfont.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QFont class
**
** Created : 940514
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONT_H
#define QFONT_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qstring.h"
#endif // QT_H

class QFontPrivate;                                     /* don't touch */
class QStringList;

class Q_EXPORT QFont
{
public:
    enum StyleHint {
    Helvetica,  SansSerif = Helvetica,
    Times,      Serif = Times,
    Courier,    TypeWriter = Courier,
    OldEnglish, Decorative = OldEnglish,
    System,
    AnyStyle
    };

    enum StyleStrategy {
    PreferDefault = 0x0001,
    PreferBitmap  = 0x0002,
    PreferDevice  = 0x0004,
    PreferOutline = 0x0008,
    ForceOutline  = 0x0010,
    PreferMatch   = 0x0020,
    PreferQuality = 0x0040,
    PreferAntialias = 0x0080,
    NoAntialias = 0x0100
    };

    enum Weight {
    Light    = 25,
    Normal   = 50,
    DemiBold = 63,
    Bold     = 75,
    Black	 = 87
    };

    // default font
    QFont();
    // specific font
    QFont( const QString &family, int pointSize = 12, int weight = Normal,
       bool italic = FALSE );
    // copy constructor
    QFont( const QFont & );

    ~QFont();

    QString family() const;
    void setFamily( const QString &);

    int pointSize() const;
    float pointSizeFloat() const;
    void setPointSize( int );
    void setPointSizeFloat( float );

    int pixelSize() const;
    void setPixelSize( int );
    void setPixelSizeFloat( float );

    int weight() const;
    void setWeight( int );

    bool bold() const;
    void setBold( bool );

    bool italic() const;
    void setItalic( bool );

    bool underline() const;
    void setUnderline( bool );

    bool strikeOut() const;
    void setStrikeOut( bool );

    bool fixedPitch() const;
    void setFixedPitch( bool );

    StyleHint styleHint() const;
    StyleStrategy styleStrategy() const;
    void setStyleHint( StyleHint, StyleStrategy = PreferDefault );
    void setStyleStrategy( StyleStrategy s );

    // is raw mode still needed?
    bool rawMode() const;
    void setRawMode( bool );

    // dupicated from QFontInfo
    bool exactMatch() const;

    QFont &operator=( const QFont & );
    bool operator==( const QFont & ) const;
    bool operator!=( const QFont & ) const;
    bool isCopyOf( const QFont & ) const;

#ifdef Q_WS_WIN
    HFONT handle() const;
#else // !Q_WS_WIN
    Qt::HANDLE handle() const;
#endif // Q_WS_WIN

    // needed for X11
    void setRawName( const QString & );
    QString rawName() const;

    QString key() const;

#ifndef QT_NO_STRINGLIST
    QString toString() const;
    bool fromString(const QString &);

    static QString substitute(const QString &);
    static QStringList substitutes(const QString &);
    static QStringList substitutions();
    static void insertSubstitution(const QString&, const QString &);
    static void insertSubstitutions(const QString&, const QStringList &);
    static void removeSubstitution(const QString &);
#endif //QT_NO_STRINGLIST
    static void initialize();
    static void cleanup();
    static void cacheStatistics();

#if defined(Q_WS_QWS)
    void qwsRenderToDisk(bool all=TRUE);
#endif

    enum Script {
    // European Alphabetic Scripts
    Latin,
    Greek,
    Cyrillic,
    Armenian,
    Georgian,
    Runic,
    Ogham,
    SpacingModifiers,
    CombiningMarks,

    // Middle Eastern Scripts
    Hebrew,
    Arabic,
    Syriac,
    Thaana,

    // South and Southeast Asian Scripts
    Devanagari,
    Bengali,
    Gurmukhi,
    Gujarati,
    Oriya,
    Tamil,
    Telugu,
    Kannada,
    Malayalam,
    Sinhala,
    Thai,
    Lao,
    Tibetan,
    Myanmar,
    Khmer,

    // East Asian Scripts
    Han,
    Hiragana,
    Katakana,
    Hangul,
    Bopomofo,
    Yi,

    // Additional Scripts
    Ethiopic,
    Cherokee,
    CanadianAboriginal,
    Mongolian,

    // Symbols
    CurrencySymbols,
    LetterlikeSymbols,
    NumberForms,
    MathematicalOperators,
    TechnicalSymbols,
    GeometricSymbols,
    MiscellaneousSymbols,
    EnclosedAndSquare,
    Braille,

    Unicode,

    // End
    NScripts,
    UnknownScript = NScripts,

    NoScript,

    // ----------------------------------------
    // Dear User, you can see values > Unicode,
    // but they are internal - do not touch.

           // only used on X11 to get some char displayed for all of the Han area.
    HanX11,

    LatinBasic = Latin,             // from ISO-8859-1
    LatinExtendedA_2 = HanX11 + 1,  // from ISO-8859-2
    LatinExtendedA_3,               // from ISO-8859-3
    LatinExtendedA_4,               // from ISO-8859-4
    LatinExtendedA_14,              // from ISO-8859-14
    LatinExtendedA_15,              // from ISO-8859-15

    LastPrivateScript
    };

    QString defaultFamily() const;
    QString lastResortFamily() const;
    QString lastResortFont() const;

#ifndef QT_NO_COMPAT

    static QFont defaultFont();
    static void setDefaultFont( const QFont & );

#endif // QT_NO_COMPAT

protected:
    // why protected?
    bool dirty() const;
    int deciPointSize() const;

private:
    QFont( QFontPrivate *, bool deep = TRUE );
    QFont( QFontPrivate *, QPaintDevice *pd );

    void detach();

#if defined(Q_WS_MAC)
    void macSetFont(QPaintDevice *);
#endif

#if defined(Q_WS_WIN)
    void *textMetric() const;
#endif

    friend class QFontMetrics;
    friend class QFontInfo;
    friend class QPainter;
    friend class QPSPrinterFont;

#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QFont & );
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QFont & );
#endif

    QFontPrivate *d;
};

inline bool QFont::bold() const
{ return weight() > Normal; }

inline void QFont::setBold( bool enable )
{ setWeight( enable ? Bold : Normal ); }

/*****************************************************************************
  QFont stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QFont & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QFont & );
#endif

#endif // QFONT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFont Member List

Complete Member List for QFont

This is the complete list of member functions for QFont, including inherited members.

  • QFont()
  • ~QFont()
  • bold()
  • deciPointSize()
  • defaultFamily()
  • defaultFont()
  • dirty()
  • exactMatch()
  • family()
  • fixedPitch()
  • fromString()
  • handle()
  • insertSubstitution()
  • insertSubstitutions()
  • isCopyOf()
  • italic()
  • key()
  • lastResortFamily()
  • lastResortFont()
  • operator!=()
  • operator=()
  • operator==()
  • pixelSize()
  • pointSize()
  • pointSizeFloat()
  • qwsRenderToDisk()
  • rawMode()
  • rawName()
  • removeSubstitution()
  • setBold()
  • setDefaultFont()
  • setFamily()
  • setFixedPitch()
  • setItalic()
  • setPixelSize()
  • setPixelSizeFloat()
  • setPointSize()
  • setPointSizeFloat()
  • setRawMode()
  • setRawName()
  • setStrikeOut()
  • setStyleHint()
  • setStyleStrategy()
  • setUnderline()
  • setWeight()
  • strikeOut()
  • styleHint()
  • styleStrategy()
  • substitute()
  • substitutes()
  • substitutions()
  • toString()
  • underline()
  • weight()


QFontDatabase Class

QFontDatabase Class Reference

The QFontDatabase class provides information about the fonts available in the underlying window system. More...

#include <qfontdatabase.h>

List of all member functions.

Public Members

  • QFontDatabase ()
  • QStringList families () const
  • QStringList styles ( const QString & family ) const
  • QValueList<int> pointSizes ( const QString & family, const QString & style = QString::null )
  • QValueList<int> smoothSizes ( const QString & family, const QString & style )
  • QString styleString ( const QFont & f )
  • QFont font ( const QString & family, const QString & style, int pointSize )
  • bool isBitmapScalable ( const QString & family, const QString & style = QString::null ) const
  • bool isSmoothlyScalable ( const QString & family, const QString & style = QString::null ) const
  • bool isScalable ( const QString & family, const QString & style = QString::null ) const
  • bool isFixedPitch ( const QString & family, const QString & style = QString::null ) const
  • bool italic ( const QString & family, const QString & style ) const
  • bool bold ( const QString & family, const QString & style ) const
  • int weight ( const QString & family, const QString & style ) const
  • QStringList families ( bool ) const (obsolete)
  • QStringList styles ( const QString & family, const QString & ) const (obsolete)
  • QValueList<int> pointSizes ( const QString & family, const QString & style, const QString & ) (obsolete)
  • QValueList<int> smoothSizes ( const QString & family, const QString & style, const QString & ) (obsolete)
  • QFont font ( const QString & familyName, const QString & style, int pointSize, const QString & ) (obsolete)
  • bool isBitmapScalable ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • bool isSmoothlyScalable ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • bool isScalable ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • bool isFixedPitch ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • bool italic ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • bool bold ( const QString & family, const QString & style, const QString & ) const (obsolete)
  • int weight ( const QString & family, const QString & style, const QString & ) const (obsolete)

Static Public Members

  • QValueList<int> standardSizes ()
  • QString scriptName ( QFont::Script script )
  • QString scriptSample ( QFont::Script script )

Detailed Description

The QFontDatabase class provides information about the fonts available in the underlying window system.

The most common uses of this class are to query the database for the list of font families() and for the pointSizes() and styles() that are available for each family. An alternative to pointSizes() is smoothSizes() which returns the sizes at which a given family and style will look attractive.

If the font family is available from two or more foundries the foundry name is included in the family name, e.g. "Helvetica [Adobe]" and "Helvetica [Cronyx]". When you specify a family you can either use the old hyphenated Qt 2.x "foundry-family" format, e.g. "Cronyx-Helvetica", or the new bracketed Qt 3.x "family [foundry]" format e.g. "Helvetica [Cronyx]". If the family has a foundry it is always returned, e.g. by families(), using the bracketed format.

The font() function returns a QFont given a family, style and point size.

A family and style combination can be checked to see if it is italic() or bold(), and to retrieve its weight(). Similarly we can call isBitmapScalable(), isSmoothlyScalable(), isScalable() and isFixedPitch().

A text version of a style is given by styleString().

The QFontDatabase class also supports some static functions, for example, standardSizes(). You can retrieve the Unicode 3.0 description of a script using scriptName(), and a sample of characters in a script with scriptSample().

Example:

#include <qapplication.h>
#include <qfontdatabase.h>

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    QFontDatabase fdb;
    QStringList families = fdb.families();
    for ( QStringList::Iterator f = families.begin(); f != families.end(); ++f ) {
        QString family = *f;
        qDebug( family );
        QStringList styles = fdb.styles( family );
        for ( QStringList::Iterator s = styles.begin(); s != styles.end(); ++s ) {
            QString style = *s;
            QString dstyle = "\t" + style + " (";
            QValueList<int> smoothies = fdb.smoothSizes( family, style );
            for ( QValueList<int>::Iterator points = smoothies.begin();
                  points != smoothies.end(); ++points ) {
                dstyle += QString::number( *points ) + " ";
            }
            dstyle = dstyle.left( dstyle.length() - 1 ) + ")";
            qDebug( dstyle );
        }
    }
    return 0;
}
This example gets the list of font families, then the list of styles for each family and the point sizes that are available for each family/style combination.

See also Environment Classes and Graphics Classes.

Member Function Documentation

QFontDatabase::QFontDatabase ()

Creates a font database object.

bool QFontDatabase::bold ( const QString & family, const QString & style ) const

Returns TRUE if the font that has family family and style style is bold; otherwise returns FALSE.

See also italic() and weight().

bool QFontDatabase::bold ( const QString & family, const QString & style, const QString & ) const

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

QStringList QFontDatabase::families () const

Returns a list of the names of the available font families.

If a family exists in several foundries, the returned name for that font is in the form "family [foundry]". Examples: "Times [Adobe]", "Times [Cronyx]", "Palatino".

QStringList QFontDatabase::families ( bool ) const

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

QFont QFontDatabase::font ( const QString & family, const QString & style, int pointSize )

Returns a QFont object that has family family, style style and point size pointSize. If no matching font could be created, a QFont object that uses the application's default font is returned.

QFont QFontDatabase::font ( const QString & familyName, const QString & style, int pointSize, const QString & )

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

bool QFontDatabase::isBitmapScalable ( const QString & family, const QString & style = QString::null ) const

Returns TRUE if the font that has family family and style style is a scalable bitmap font; otherwise returns FALSE. Scaling a bitmap font usually produces an unattractive hardly readable result, because the pixels of the font are scaled. If you need to scale a bitmap font it is better to scale it to one of the fixed sizes returned by smoothSizes().

See also isScalable() and isSmoothlyScalable().

bool QFontDatabase::isBitmapScalable ( const QString & family, const QString & style, const QString & ) const

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

bool QFontDatabase::isFixedPitch ( const QString & family, const QString & style = QString::null ) const

Returns TRUE if the font that has family family and style style is fixed pitch; otherwise returns FALSE.

bool QFontDatabase::isFixedPitch ( const QString & family, const QString & style, const QString & ) const

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

bool QFontDatabase::isScalable ( const QString & family, const QString & style = QString::null ) const

Returns TRUE if the font that has family family and style style is scalable; otherwise returns FALSE.

See also isBitmapScalable() and isSmoothlyScalable().

bool QFontDatabase::isScalable ( const QString & family, const QString & style, const QString & ) const

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

bool QFontDatabase::isSmoothlyScalable ( const QString & family, const QString & style = QString::null ) const

Returns TRUE if the font that has family family and style style is smoothly scalable; otherwise returns FALSE. If this function returns TRUE, it's safe to scale this font to any size, and the result will always look attractive.

See also isScalable() and isBitmapScalable().

bool QFontDatabase::isSmoothlyScalable ( const QString & family, const QString & style, const QString & ) const

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

bool QFontDatabase::italic ( const QString & family, const QString & style ) const

Returns TRUE if the font that has family family and style style is italic; otherwise returns FALSE.

See also weight() and bold().

bool QFontDatabase::italic ( const QString & family, const QString & style, const QString & ) const

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

QValueList<int> QFontDatabase::pointSizes ( const QString & family, const QString & style = QString::null )

Returns a list of the point sizes available for the font that has family family and style style. The list may be empty.

See also smoothSizes() and standardSizes().

QValueList<int> QFontDatabase::pointSizes ( const QString & family, const QString & style, const QString & )

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

QString QFontDatabase::scriptName ( QFont::Script script ) [static]

Returns a string that gives a default description of the script (e.g. for displaying to the user in a dialog). The name matches the name of the script as defined by the Unicode 3.0 standard.

See also QFont::Script.

QString QFontDatabase::scriptSample ( QFont::Script script ) [static]

Returns a string with sample characters from script.

See also QFont::Script.

QValueList<int> QFontDatabase::smoothSizes ( const QString & family, const QString & style )

Returns the point sizes of a font that has family family and style style that will look attractive. The list may be empty. For non-scalable fonts and smoothly scalable fonts, this function is equivalent to pointSizes().

See also pointSizes() and standardSizes().

QValueList<int> QFontDatabase::smoothSizes ( const QString & family, const QString & style, const QString & )

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

QValueList<int> QFontDatabase::standardSizes () [static]

Returns a list of standard font sizes.

See also smoothSizes() and pointSizes().

QString QFontDatabase::styleString ( const QFont & f )

Returns a string that describes the style of the font f. For example, "Bold Italic", "Bold", "Italic" or "Normal". An empty string may be returned.

QStringList QFontDatabase::styles ( const QString & family ) const

Returns a list of the styles available for the font family, family. Some example styles: "Light", "Light Italic", "Bold", "Oblique", "Demi". The list may be empty.

QStringList QFontDatabase::styles ( const QString & family, const QString & ) const

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

int QFontDatabase::weight ( const QString & family, const QString & style ) const

Returns the weight of the font that has family family and style style. If there is no such family and style combination, returns -1.

See also italic() and bold().

int QFontDatabase::weight ( const QString & family, const QString & style, const QString & ) const

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

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


qfontdatabase.h Include File

qfontdatabase.h

This is the verbatim text of the qfontdatabase.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qfontdatabase.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the QFontDatabase class
**
** Created : 981126
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONTDATABASE_H
#define QFONTDATABASE_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qstring.h"
#include "qstringlist.h"
#include "qfont.h"
#include "qvaluelist.h"
#endif // QT_H

#ifndef QT_NO_FONTDATABASE

class QFontStylePrivate; /* Don't touch! */
class QtFontStyle;
class QtFontFamily;
class QtFontFoundry;
#ifdef Q_WS_QWS
class QDiskFont;
#endif

class QFontDatabasePrivate;

class Q_EXPORT QFontDatabase
{
public:
    static QValueList<int> standardSizes();

    QFontDatabase();

    QStringList families() const;
    QStringList styles( const QString & ) const;
    QValueList<int> pointSizes( const QString &, const QString & = QString::null);
    QValueList<int> smoothSizes( const QString &, const QString &);
    QString styleString( const QFont &);

    QFont font( const QString &, const QString &, int);

    bool isBitmapScalable( const QString &, const QString & = QString::null) const;
    bool isSmoothlyScalable( const QString &, const QString & = QString::null) const;
    bool isScalable( const QString &, const QString & = QString::null) const;
    bool isFixedPitch( const QString &, const QString & = QString::null) const;

    bool italic( const QString &, const QString &) const;
    bool bold( const QString &, const QString &) const;
    int weight( const QString &, const QString &) const;

    static QString scriptName(QFont::Script);
    static QString scriptSample(QFont::Script);

#ifdef Q_WS_QWS
    static void qwsAddDiskFont( QDiskFont *qdf );
#endif

    // For source compatibility with < 3.0
#ifndef QT_NO_COMPAT

    QStringList families(bool) const;
    QStringList styles( const QString &, const QString & ) const;
    QValueList<int> pointSizes( const QString &, const QString &, const QString & );
    QValueList<int> smoothSizes( const QString &, const QString &, const QString & );

    QFont font( const QString &, const QString &, int, const QString &);

    bool isBitmapScalable( const QString &, const QString &, const QString & ) const;
    bool isSmoothlyScalable( const QString &, const QString &, const QString & ) const;
    bool isScalable( const QString &, const QString &, const QString & ) const;
    bool isFixedPitch( const QString &, const QString &, const QString & ) const;

    bool italic( const QString &, const QString &, const QString & ) const;
    bool bold( const QString &, const QString &, const QString & ) const;
    int weight( const QString &, const QString &, const QString & ) const;

#endif // QT_NO_COMPAT

private:
    static void createDatabase();

    static void parseFontName(const QString &, QString &, QString &);

    friend class QtFontStyle;
    friend class QtFontFamily;
    friend class QtFontFoundry;
    friend class QFontDatabasePrivate;

    // for parseFontName
    friend class QFontPrivate;
    friend class QFontDialog;
    friend QString qt_makePSFontName( const QFont &f, int *listpos = 0, int *ftype = 0 );

    QFontDatabasePrivate *d;
};

#ifndef QT_NO_COMPAT

inline QStringList QFontDatabase::families( bool ) const
{
    return families();
}

inline QStringList QFontDatabase::styles( const QString &family,
                      const QString & ) const
{
    return styles(family);
}

inline QValueList<int> QFontDatabase::pointSizes( const QString &family,
                          const QString &style ,
                          const QString & )
{
    return pointSizes(family, style);
}

inline QValueList<int> QFontDatabase::smoothSizes( const QString &family,
                           const QString &style,
                           const QString & )
{
    return smoothSizes(family, style);
}

inline QFont QFontDatabase::font( const QString &familyName,
                  const QString &style,
                  int pointSize,
                  const QString &)
{
    return font(familyName, style, pointSize);
}

inline bool QFontDatabase::isBitmapScalable( const QString &family,
                         const QString &style,
                         const QString & ) const
{
    return isBitmapScalable(family, style);
}

inline bool QFontDatabase::isSmoothlyScalable( const QString &family,
                           const QString &style,
                           const QString & ) const
{
    return isSmoothlyScalable(family, style);
}

inline bool QFontDatabase::isScalable( const QString &family,
                       const QString &style,
                       const QString & ) const
{
    return isScalable(family, style);
}

inline bool QFontDatabase::isFixedPitch( const QString &family,
                     const QString &style,
                     const QString & ) const
{
    return isFixedPitch(family, style);
}

inline bool QFontDatabase::italic( const QString &family,
                   const QString &style,
                   const QString & ) const
{
    return italic(family, style);
}

inline bool QFontDatabase::bold( const QString &family,
                 const QString &style,
                 const QString & ) const
{
    return bold(family, style);
}

inline int QFontDatabase::weight( const QString &family,
                  const QString &style,
                  const QString & ) const
{
    return weight(family, style);
}

#endif // QT_NO_COMPAT

#endif // QT_NO_FONTDATABASE

#endif // QFONTDATABASE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFontDatabase Member List

Complete Member List for QFontDatabase

This is the complete list of member functions for QFontDatabase, including inherited members.

  • QFontDatabase()
  • bold()
  • families()
  • font()
  • isBitmapScalable()
  • isFixedPitch()
  • isScalable()
  • isSmoothlyScalable()
  • italic()
  • pointSizes()
  • scriptName()
  • scriptSample()
  • smoothSizes()
  • standardSizes()
  • styleString()
  • styles()
  • weight()


QFontDialog类

QFontDialog类参考

QFontDialog类提供了可以选择字体的对话框窗口部件。 详情请见……

#include <qfontdialog.h>

继承了QDialog。

所有成员函数的列表。

静态公有成员

  • QFont getFont ( bool * ok, const QFont & initial, QWidget * parent = 0, const char * name = 0 )
  • QFont getFont ( bool * ok, QWidget * parent = 0, const char * name = 0 )

详细描述

QFontDialog类提供了可以选择字体的对话框窗口部件。

使用这个类的常用方法是调用静态函数中的一个，比如，getFont()。

实例：

    bool ok;
    QFont font = QFontDialog::getFont(
                    &ok, QFont( "Helvetica [Cronyx]", 10 ), this );
    if ( ok ) {
        // font被设置为用户选择的字体
    } else {
        // 用户取消这个对话框，font被设置为初始值，在这里就是Helvetica [Cronyx], 10
    }

对话框也可以被用来直接设置窗口部件的字体：

    myWidget.setFont( QFontDialog::getFont( 0, myWidget.font() ) );
如果用户点击OK，它们选择的字体将被myWidget使用，并且如果点击Cancel，最初的字体被使用。

也可以参考QFont、QFontInfo、QFontMetrics和对话框类。

成员函数文档

QFont QFontDialog::getFont ( bool * ok, const QFont & initial, QWidget * parent = 0, const char * name = 0 ) [静态]

执行一个模式字体对话框并且返回一个字体。

如果用户点击OK，被选择的字体将被返回，并且如果点击Cancel，initial字体被返回。

对话框的父对象为parent、名称为name。initial是初始选择的字体。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。

这个静态函数没有完整的QFontDialog对象灵活，但是要方便并且容易使用。

实例：

    bool ok;
    QFont font = QFontDialog::getFont( &ok, QFont( "Times", 12 ), this );
    if ( ok ) {
        // font被设置为用户选择的字体
    } else {
        // 用户取消这个对话框，font被设置为初始值，在这里就是Times, 12
    }

对话框也可以被用来直接设置窗口部件的字体：

    myWidget.setFont( QFontDialog::getFont( 0, myWidget.font() ) );
在这个实例中，如果用户点击OK，它们选择的字体将被使用，并且如果点击Cancel，最初的字体被使用。

实例：chart/chartform.cpp、chart/optionsform.cpp、qfd/fontdisplayer.cpp、qwerty/qwerty.cpp和xform/xform.cpp。

QFont QFontDialog::getFont ( bool * ok, QWidget * parent = 0, const char * name = 0 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

执行一个模式字体对话框并且返回一个字体。

如果用户点击OK，被选择的字体将被返回，并且如果点击Cancel，Qt默认字体被返回。

对话框的父对象为parent、名称为name。initial是初始选择的字体。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。

这个静态函数没有完整的QFontDialog对象灵活，但是要方便并且容易使用。

实例：

    bool ok;
    QFont font = QFontDialog::getFont( &ok, this );
    if ( ok ) {
        // font被设置为用户选择的字体
    } else {
        // 用户取消这个对话框，font被设置为默认应用程序字体，QApplication::font()
    }

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qfontdialog.h包含文件

qfontdialog.h

这里是qfontdialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qfontdialog.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QFontDialog
**
** Created : 970605
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONTDIALOG_H
#define QFONTDIALOG_H

#include "qwindowdefs.h"

#ifndef QT_NO_FONTDIALOG

//
//  W A R N I N G
//  -------------
//
//  This class is under development and has private constructors.
//
//  You may use the public static getFont() functions which are guaranteed
//  to be available in the future.
//

#ifndef QT_H
#include "qdialog.h"
#include "qfont.h"
#endif // QT_H

class  QListBox;
class  QComboBox;
class QFontDialogPrivate;

class Q_EXPORT QFontDialog: public QDialog
{
    Q_OBJECT

public:
    static QFont getFont( bool *ok, const QFont &def,
              QWidget* parent=0, const char* name=0);
    static QFont getFont( bool *ok, QWidget* parent=0, const char* name=0);

private:
    QFontDialog( QWidget* parent=0, const char* name=0, bool modal=FALSE,
         WFlags f=0 );
    ~QFontDialog();

    QFont font() const;
    void setFont( const QFont &font );

signals:
    void fontSelected( const QFont &font );
    void fontHighlighted( const QFont &font );

protected:
    bool eventFilter( QObject *, QEvent * );

    QListBox * familyListBox() const;
    virtual void updateFamilies();

    QListBox * styleListBox() const;
    virtual void updateStyles();

    QListBox * sizeListBox() const;
    virtual void updateSizes();

    QComboBox * scriptCombo() const;
    virtual void updateScripts();

#if 0
    QString family() const;
    QString script() const;
    QString style() const;
    QString size() const;
#endif

protected slots:
    void sizeChanged( const QString &);

private slots:
    void familyHighlighted( const QString &);
    void familyHighlighted( int );
    void scriptHighlighted( const QString &);
    void scriptHighlighted( int );
    void styleHighlighted( const QString &);
    void sizeHighlighted( const QString &);
    void updateSample();
    void emitSelectedFont();

private:
    static QFont getFont( bool *ok, const QFont *def,
              QWidget* parent=0, const char* name=0);

    QFontDialogPrivate * d;
    friend class QFontDialogPrivate;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QFontDialog( const QFontDialog & );
    QFontDialog& operator=( const QFontDialog & );
#endif
};

#endif

#endif // QFONTDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFontDialog成员列表

完整的QFontDialog成员列表

这里是QFontDialog成员函数的完整列表，包括继承的成员。

  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getFont()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFontInfo Class

QFontInfo Class Reference

The QFontInfo class provides general information about fonts. More...

#include <qfontinfo.h>

List of all member functions.

Public Members

  • QFontInfo ( const QFont & font )
  • QFontInfo ( const QFontInfo & fi )
  • ~QFontInfo ()
  • QFontInfo & operator= ( const QFontInfo & fi )
  • QString family () const
  • int pixelSize () const
  • int pointSize () const
  • bool italic () const
  • int weight () const
  • bool bold () const
  • bool fixedPitch () const
  • QFont::StyleHint styleHint () const
  • bool rawMode () const
  • bool exactMatch () const

Detailed Description

The QFontInfo class provides general information about fonts.

The QFontInfo class provides the same access functions as QFont, e.g. family(), pointSize(), italic(), weight(), fixedPitch(), styleHint() etc. But whilst the QFont access functions return the values that were set, a QFontInfo object returns the values that apply to the font that will actually be used to draw the text.

For example, when the program asks for a 25pt Courier font on a machine that has a non-scalable 24pt Courier font, QFont will (normally) use the 24pt Courier for rendering. In this case, QFont::pointSize() returns 25 and QFontInfo::pointSize() returns 24.

There are three ways to create a QFontInfo object.

  1. Calling the QFontInfo constructor with a QFont creates a font info object for a screen-compatible font, i.e. the font cannot be a printer font*. If the font is changed later, the font info object is not updated.

  2. QWidget::fontInfo() returns the font info for a widget's font. This is equivalent to calling QFontInfo(widget->font()). If the widget's font is changed later, the font info object is not updated.

  3. QPainter::fontInfo() returns the font info for a painter's current font. The font info object is automatically updated if you set a new painter font.

* If you use a printer font the values returned will almost certainly be inaccurate. Printer fonts are not always accessible so the nearest screen font is used if a printer font is supplied.

See also QFont, QFontMetrics, QFontDatabase, Graphics Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QFontInfo::QFontInfo ( const QFont & font )

Constructs a font info object for font.

The font must be screen-compatible, i.e. a font you use when drawing text in widgets or pixmaps, not QPicture or QPrinter.

The font info object holds the information for the font that is passed in the constructor at the time it is created, and is not updated if the font's attributes are changed later.

Use the QPainter::fontInfo() function to get the font info when painting. This is a little slower than using this constructor, but it always gives correct results because the font info data is updated.

QFontInfo::QFontInfo ( const QFontInfo & fi )

Constructs a copy of fi.

QFontInfo::~QFontInfo ()

Destroys the font info object.

bool QFontInfo::bold () const

Returns TRUE if weight() would return a value greater than QFont::Normal; otherwise returns FALSE.

See also weight() and QFont::bold().

bool QFontInfo::exactMatch () const

Returns TRUE if the matched window system font is exactly the same as the one specified by the font; otherwise returns FALSE.

See also QFont::exactMatch().

QString QFontInfo::family () const

Returns the family name of the matched window system font.

See also QFont::family().

Example: fonts/simple-qfont-demo/viewer.cpp.

bool QFontInfo::fixedPitch () const

Returns the fixed pitch value of the matched window system font.

See also QFont::fixedPitch().

bool QFontInfo::italic () const

Returns the italic value of the matched window system font.

See also QFont::italic().

QFontInfo & QFontInfo::operator= ( const QFontInfo & fi )

Assigns the font info in fi.

int QFontInfo::pixelSize () const

Returns the pixel size of the matched window system font.

See also QFont::pointSize().

int QFontInfo::pointSize () const

Returns the point size of the matched window system font.

See also QFont::pointSize().

Example: fonts/simple-qfont-demo/viewer.cpp.

bool QFontInfo::rawMode () const

Returns TRUE if the font is a raw mode font; otherwise returns FALSE.

If it is a raw mode font, all other functions in QFontInfo will return the same values set in the QFont, regardless of the font actually used.

See also QFont::rawMode().

QFont::StyleHint QFontInfo::styleHint () const

Returns the style of the matched window system font.

Currently only returns the style hint set in QFont.

See also QFont::styleHint() and QFont::StyleHint.

int QFontInfo::weight () const

Returns the weight of the matched window system font.

See also QFont::weight() and bold().

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


qfontinfo.h Include File

qfontinfo.h

This is the verbatim text of the qfontinfo.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qfontinfo.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QFontInfo class
**
** Created : 950131
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONTINFO_H
#define QFONTINFO_H

#ifndef QT_H
#include "qfont.h"
#endif // QT_H

class Q_EXPORT QFontInfo
{
public:
    QFontInfo( const QFont & );
    QFontInfo( const QFontInfo & );
    ~QFontInfo();

    QFontInfo	       &operator=( const QFontInfo & );

    QString   	        family()	const;
    int			pixelSize()	const;
    int			pointSize()	const;
    bool		italic()	const;
    int			weight()	const;
    bool		bold()		const;
    bool		underline()	const;
    bool		strikeOut()	const;
    bool		fixedPitch()	const;
    QFont::StyleHint	styleHint()	const;
    bool		rawMode()	const;

    bool		exactMatch()	const;

private:
    QFontInfo( const QPainter * );
    static void reset( const QPainter * );

    QFontPrivate *d;
    QPainter *painter;
    int flags;

    bool    underlineFlag()  const { return (flags & 0x1) != 0; }
    bool    strikeOutFlag()  const { return (flags & 0x2) != 0; }
    bool    exactMatchFlag() const { return (flags & 0x4) != 0; }
    void    setUnderlineFlag()	   { flags |= 0x1; }
    void    setStrikeOutFlag()	   { flags |= 0x2; }
    void    setExactMatchFlag()	   { flags |= 0x4; }

    friend class QWidget;
    friend class QPainter;
};

inline bool QFontInfo::bold() const
{ return weight() > QFont::Normal; }

#endif // QFONTINFO_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFontInfo Member List

Complete Member List for QFontInfo

This is the complete list of member functions for QFontInfo, including inherited members.

  • QFontInfo()
  • ~QFontInfo()
  • bold()
  • exactMatch()
  • family()
  • fixedPitch()
  • italic()
  • operator=()
  • pixelSize()
  • pointSize()
  • rawMode()
  • styleHint()
  • weight()


QFontManager Class

QFontManager Class Reference

The QFontManager class implements font management in Qt/Embedded. More...

#include <qfontmanager_qws.h>

List of all member functions.

Public Members

  • QFontManager ()
  • ~QFontManager ()
  • QDiskFont * get ( const QFontDef & f )

Static Public Members

  • void initialize ()
  • void cleanup ()

Detailed Description

The QFontManager class implements font management in Qt/Embedded.

There is one and only one QFontManager per Qt/Embedded application (qt_fontmanager is a global variable that points to it). It keeps a list of font factories, a cache of rendered fonts and a list of fonts available on disk. QFontManager is called when a new font needs to be rendered from a Freetype-compatible or BDF font on disk; this only happens if there isn't an appropriate QPF font already available.

See also Qt/Embedded.

Member Function Documentation

QFontManager::QFontManager ()

Creates a font manager. This method reads in the font definition file from $QTDIR/lib/fonts/fontdir (or /usr/local/qt-embedded/lib/fonts/fontdir if QTDIR isn't defined) and creates a list of QDiskFonts to hold the information in the file. It also constructs any defined font factories.

QFontManager::~QFontManager ()

Destroys the QFontManager and sets qt_fontmanager to 0.

void QFontManager::cleanup () [static]

Destroys the font manager

QDiskFont * QFontManager::get ( const QFontDef & f )

Returns the QDiskFont that best matches f, based on family, weight, italicity and font size.

void QFontManager::initialize () [static]

Creates a new QFontManager and points qt_fontmanager to it

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


QFontManager Member List

Complete Member List for QFontManager

This is the complete list of member functions for QFontManager, including inherited members.

  • QFontManager()
  • ~QFontManager()
  • cleanup()
  • get()
  • initialize()


qfontmanager_qws.h Include File

qfontmanager_qws.h

This is the verbatim text of the qfontmanager_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qfontmanager_qws.h   3.0.5   edited Oct 12 2001 $
**
** Definition of font rendering infrastructure for Embedded Qt
**
** Created : 940721
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONTMANAGER_QWS_H
#define QFONTMANAGER_QWS_H

#ifndef QT_H
#include "qfont.h"
#include "qptrlist.h"
#endif // QT_H

// These are stored in the shared memory segment in front of their
// data, and indexed at the start of the segment

// This needs to be a multiple of 64 bits

class QFontDef;

class Q_PACKED QGlyphMetrics {

public:
    Q_UINT8 linestep;
    Q_UINT8 width;
    Q_UINT8 height;
    Q_UINT8 padding;

    Q_INT8 bearingx;      // Difference from pen position to glyph's left bbox
    Q_UINT8 advance;       // Difference between pen positions
    Q_INT8 bearingy;      // Used for putting characters on baseline

    Q_INT8 reserved;      // Do not use
};

class QGlyph {
public:
    QGlyph() { }
    QGlyph(QGlyphMetrics* m, uchar* d) :
    metrics(m), data(d) { }

    QGlyphMetrics* metrics;
    uchar* data;
};

class QFontFactory;
class QDiskFont;

// This is a particular font instance at a particular resolution
// e.g. Truetype Times, 10 point. There's only one of these though;
// we want to share generated glyphs

class QRenderedFont {

public:

    // Normal font-type is monochrome; glyph data is a
    //   bitmap, which doesn't use much memory

    // Initialise for name A, renderer B, font type C, D glyphs

    QRenderedFont(QDiskFont *,const QFontDef&);
    virtual ~QRenderedFont();

    int refcount;

    int ptsize;

    bool italic;
    unsigned int weight;

    void ref() { refcount++; }
    bool deref() { refcount--; return (refcount<1); }

    QDiskFont* diskfont;
    int fascent,fdescent;
    int fleftbearing,frightbearing;
    int fmaxwidth;
    int fleading;
    int funderlinepos;
    int funderlinewidth;
    bool smooth;
    int maxchar;

    int ascent() { return fascent; }
    int descent() { return fdescent; }
    int width(int);
    int width( const QString&, int =-1 );
    int leftBearing(int);
    int rightBearing(int);

    // Calling any of these can trigger a full-font metrics check
    // which can be expensive
    int minLeftBearing();
    int minRightBearing();
    int maxWidth();

    virtual bool inFont(QChar ch) const=0;
    virtual QGlyph render(QChar)=0;

private:

};

// Keeps track of available renderers and which font is which

class QDiskFontPrivate {};

class QDiskFont {

public:
    QDiskFont(QFontFactory *f, const QString& n, bool i, int w, int s,
          const QString &fl, const QString& fi) :
    factory(f), name(n), italic(i), weight(w), size(s), flags(fl), file(fi)
    {
    loaded=false;
    p=0;
    }

    QRenderedFont* load(const QFontDef &);

    QFontDef fontDef() const;

    QFontFactory *factory;
    QString name;
    bool italic;
    int weight;
    int size;
    QString flags;
    QString file;
    bool loaded;

    QDiskFontPrivate * p;
};

class QFontManager {

public:

    QPtrList<QFontFactory> factories;
    QPtrList<QRenderedFont> cachedfonts;
    QPtrList<QDiskFont> diskfonts;

    QFontManager();
    ~QFontManager();

    // Font definition, type and color

    QDiskFont * get(const QFontDef &);

    static int cmpFontDef(const QFontDef & goal, const QFontDef & choice);

    static void initialize();
    static void cleanup();
};

class QFontFactory {

public:

    QFontFactory() {}
    virtual ~QFontFactory() {}

    virtual QRenderedFont * get(const QFontDef &,QDiskFont *)=0;
    virtual void load(QDiskFont *) const=0;
    virtual QString name()=0;
};

void qt_init_fonts();

extern QFontManager * qt_fontmanager;

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFontMetrics Class

QFontMetrics Class Reference

The QFontMetrics class provides font metrics information. More...

#include <qfontmetrics.h>

List of all member functions.

Public Members

  • QFontMetrics ( const QFont & font )
  • QFontMetrics ( const QFontMetrics & fm )
  • ~QFontMetrics ()
  • QFontMetrics & operator= ( const QFontMetrics & fm )
  • int ascent () const
  • int descent () const
  • int height () const
  • int leading () const
  • int lineSpacing () const
  • int minLeftBearing () const
  • int minRightBearing () const
  • int maxWidth () const
  • bool inFont ( QChar ch ) const
  • int leftBearing ( QChar ch ) const
  • int rightBearing ( QChar ch ) const
  • int width ( const QString & str, int len = -1 ) const
  • int width ( QChar ch ) const
  • int width ( char c ) const (obsolete)
  • int charWidth ( const QString & str, int pos ) const
  • QRect boundingRect ( const QString & str, int len = -1 ) const
  • QRect boundingRect ( QChar ch ) const
  • QRect boundingRect ( int x, int y, int w, int h, int flgs, const QString & str, int len = -1, int tabstops = 0, int * tabarray = 0, QTextParag ** intern = 0 ) const
  • QSize size ( int flgs, const QString & str, int len = -1, int tabstops = 0, int * tabarray = 0, QTextParag ** intern = 0 ) const
  • int underlinePos () const
  • int strikeOutPos () const
  • int lineWidth () const

Detailed Description

The QFontMetrics class provides font metrics information.

QFontMetrics functions calculate the size of characters and strings for a given font. There are three ways you can create a QFontMetrics object:

  1. Calling the QFontMetrics constructor with a QFont creates a font metrics object for a screen-compatible font, i.e. the font cannot be a printer font*. If the font is changed later, the font metrics object is not updated.

  2. QWidget::fontMetrics() returns the font metrics for a widget's font. This is equivalent to QFontMetrics(widget->font()). If the widget's font is changed later, the font metrics object is not updated.

  3. QPainter::fontMetrics() returns the font metrics for a painter's current font. The font metrics object is automatically updated if you set a new painter font.

* If you use a printer font the values returned will almost certainly be inaccurate. Printer fonts are not always accessible so the nearest screen font is used if a printer font is supplied.

Once created, the object provides functions to access the individual metrics of the font, its characters, and for strings rendered in the font.

There are several functions that operate on the font: ascent(), descent(), height(), leading() and lineSpacing() return the basic size properties of the font. The underlinePos(), strikeOutPos() and lineWidth() functions, return the properties of the line that underlines or strikes out the characters. These functions are all fast.

There are also some functions that operate on the set of glyphs in the font: minLeftBearing(), minRightBearing() and maxWidth(). These are by necessity slow, and we recommend avoiding them if possible.

For each character, you can get its width(), leftBearing() and rightBearing() and find out whether it is in the font using inFont(). You can also treat the character as a string, and use the string functions on it.

The string functions include width(), to return the width of a string in pixels (or points, for a printer), boundingRect(), to return a rectangle large enough to contain the rendered string, and size(), to return the size of that rectangle.

Example:

    QFont font( "times", 24 );
    QFontMetrics fm( font );
    int pixelsWide = fm.width( "What's the width of this text?" );
    int pixelsHigh = fm.height();

See also QFont, QFontInfo, QFontDatabase, Graphics Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QFontMetrics::QFontMetrics ( const QFont & font )

Constructs a font metrics object for font.

The font must be screen-compatible, i.e. a font you use when drawing text in widgets or pixmaps, not QPicture or QPrinter.

The font metrics object holds the information for the font that is passed in the constructor at the time it is created, and is not updated if the font's attributes are changed later.

Use QPainter::fontMetrics() to get the font metrics when painting. This is a little slower than using this constructor, but it always gives correct results because the font info data is updated.

QFontMetrics::QFontMetrics ( const QFontMetrics & fm )

Constructs a copy of fm.

QFontMetrics::~QFontMetrics ()

Destroys the font metrics object and frees all allocated resources.

int QFontMetrics::ascent () const

Returns the ascent of the font.

The ascent of a font is the distance from the baseline to the highest position characters extend to. In practice, some font designers break this rule, e.g. when they put more than one accent on top of a character, or to accommodate an unusual character in an exotic language, so it is possible (though rare) that this value will be too small.

See also descent().

Examples: drawdemo/drawdemo.cpp and scrollview/scrollview.cpp.

QRect QFontMetrics::boundingRect ( const QString & str, int len = -1 ) const

Returns the bounding rectangle of the first len characters of str, which is the set of pixels the text would cover if drawn at (0, 0).

If len is negative (the default), the entire string is used.

Note that the bounding rectangle may extend to the left of (0, 0), e.g. for italicized fonts, and that the text output may cover all pixels in the bounding rectangle.

Newline characters are processed as normal characters, not as linebreaks.

Due to the different actual character heights, the height of the bounding rectangle of e.g. "Yes" and "yes" may be different.

See also width() and QPainter::boundingRect().

Example: xform/xform.cpp.

QRect QFontMetrics::boundingRect ( QChar ch ) const

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

Returns the bounding rectangle of the character ch relative to the left-most point on the base line.

Note that the bounding rectangle may extend to the left of (0, 0), e.g. for italicized fonts, and that the text output may cover all pixels in the bounding rectangle.

Note that the rectangle usually extends both above and below the base line.

See also width().

QRect QFontMetrics::boundingRect ( int x, int y, int w, int h, int flgs, const QString & str, int len = -1, int tabstops = 0, int * tabarray = 0, QTextParag ** intern = 0 ) const

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

Returns the bounding rectangle of the first len characters of str, which is the set of pixels the text would cover if drawn at (0, 0). The drawing, and hence the bounding rectangle, is constrained to the rectangle (x, y, w, h).

If len is negative (which is the default), the entire string is used.

The flgs argument is the bitwise OR of the following flags:

  • AlignAuto aligns to the left border for all languages except Arabic and Hebrew where it aligns to the right.
  • AlignLeft aligns to the left border.
  • AlignRight aligns to the right border.
  • AlignJustify produces justified text.
  • AlignHCenter aligns horizontally centered.
  • AlignTop aligns to the top border.
  • AlignBottom aligns to the bottom border.
  • AlignVCenter aligns vertically centered
  • AlignCenter (== AlignHCenter | AlignVCenter)
  • SingleLine ignores newline characters in the text.
  • ExpandTabs expands tabs (see below)
  • ShowPrefix interprets "&x" as "x", i.e. underlined.
  • WordBreak breaks the text to fit the rectangle.

Horizontal alignment defaults to AlignAuto and vertical alignment defaults to AlignTop.

If several of the horizontal or several of the vertical alignment flags are set, the resulting alignment is undefined.

These flags are defined in qnamespace.h.

If ExpandTabs is set in flgs, then: if tabarray is non-null, it specifies a 0-terminated sequence of pixel-positions for tabs; otherwise if tabstops is non-zero, it is used as the tab spacing (in pixels).

Note that the bounding rectangle may extend to the left of (0, 0), e.g. for italicized fonts, and that the text output may cover all pixels in the bounding rectangle.

Newline characters are processed as linebreaks.

Despite the different actual character heights, the heights of the bounding rectangles of "Yes" and "yes" are the same.

The bounding rectangle given by this function is somewhat larger than that calculated by the simpler boundingRect() function. This function uses the maximum left and right font bearings as is necessary for multi-line text to align correctly. Also, fontHeight() and lineSpacing() are used to calculate the height, rather than individual character heights.

The intern argument should not be used.

See also width(), QPainter::boundingRect() and Qt::AlignmentFlags.

int QFontMetrics::charWidth ( const QString & str, int pos ) const

Returns the width of the character at position pos in the string str.

The whole string is needed, as the glyph drawn may change depending on the context (the letter before and after the current one) for some languages (e.g. Arabic).

This function also takes non spacing marks and ligatures into account.

int QFontMetrics::descent () const

Returns the descent of the font.

The descent is the distance from the base line to the lowest point characters extend to. (Note that this is different from X, which adds 1 pixel.) In practice, some font designers break this rule, e.g. to accommodate an unusual character in an exotic language, so it is possible (though rare) that this value will be too small.

See also ascent().

Examples: drawdemo/drawdemo.cpp and hello/hello.cpp.

int QFontMetrics::height () const

Returns the height of the font.

This is always equal to ascent()+descent()+1 (the 1 is for the base line).

See also leading() and lineSpacing().

Examples: grapher/grapher.cpp, hello/hello.cpp and qfd/fontdisplayer.cpp.

bool QFontMetrics::inFont ( QChar ch ) const

Returns TRUE if character ch is a valid character in the font; otherwise returns FALSE.

Example: qfd/fontdisplayer.cpp.

int QFontMetrics::leading () const

Returns the leading of the font.

This is the natural inter-line spacing.

See also height() and lineSpacing().

int QFontMetrics::leftBearing ( QChar ch ) const

Returns the left bearing of character ch in the font.

The left bearing is the right-ward distance of the left-most pixel of the character from the logical origin of the character. This value is negative if the pixels of the character extend to the left of the logical origin.

See width(QChar) for a graphical description of this metric.

See also rightBearing(), minLeftBearing() and width().

Example: qfd/fontdisplayer.cpp.

int QFontMetrics::lineSpacing () const

Returns the distance from one base line to the next.

This value is always equal to leading()+height().

See also height() and leading().

Examples: action/application.cpp, application/application.cpp, mdi/application.cpp, qfd/fontdisplayer.cpp, qwerty/qwerty.cpp and scrollview/scrollview.cpp.

int QFontMetrics::lineWidth () const

Returns the width of the underline and strikeout lines, adjusted for the point size of the font.

See also underlinePos() and strikeOutPos().

int QFontMetrics::maxWidth () const

Returns the width of the widest character in the font.

Example: qfd/fontdisplayer.cpp.

int QFontMetrics::minLeftBearing () const

Returns the minimum left bearing of the font.

This is the smallest leftBearing(char) of all characters in the font.

Note that this function can be very slow if the font is large.

See also minRightBearing() and leftBearing().

Example: qfd/fontdisplayer.cpp.

int QFontMetrics::minRightBearing () const

Returns the minimum right bearing of the font.

This is the smallest rightBearing(char) of all characters in the font.

Note that this function can be very slow if the font is large.

See also minLeftBearing() and rightBearing().

Example: qfd/fontdisplayer.cpp.

QFontMetrics & QFontMetrics::operator= ( const QFontMetrics & fm )

Assigns the font metrics fm.

int QFontMetrics::rightBearing ( QChar ch ) const

Returns the right bearing of character ch in the font.

The right bearing is the left-ward distance of the right-most pixel of the character from the logical origin of a subsequent character. This value is negative if the pixels of the character extend to the right of the width() of the character.

See width() for a graphical description of this metric.

See also leftBearing(), minRightBearing() and width().

Example: qfd/fontdisplayer.cpp.

QSize QFontMetrics::size ( int flgs, const QString & str, int len = -1, int tabstops = 0, int * tabarray = 0, QTextParag ** intern = 0 ) const

Returns the size in pixels of the first len characters of str.

If len is negative (the default), the entire string is used.

The flgs argument is the bitwise OR of the following flags:

  • SingleLine ignores newline characters.
  • ExpandTabs expands tabs (see below)
  • ShowPrefix interprets "&x" as "x", i.e. underlined.
  • WordBreak breaks the text to fit the rectangle.

These flags are defined in qnamespace.h.

If ExpandTabs is set in flgs, then: if tabarray is non-null, it specifies a 0-terminated sequence of pixel-positions for tabs; otherwise if tabstops is non-zero, it is used as the tab spacing (in pixels).

Newline characters are processed as linebreaks.

Despite the different actual character heights, the heights of the bounding rectangles of "Yes" and "yes" are the same.

The intern argument should not be used.

See also boundingRect().

int QFontMetrics::strikeOutPos () const

Returns the distance from the base line to where the strikeout line should be drawn.

See also underlinePos() and lineWidth().

int QFontMetrics::underlinePos () const

Returns the distance from the base line to where an underscore should be drawn.

See also strikeOutPos() and lineWidth().

int QFontMetrics::width ( const QString & str, int len = -1 ) const

Returns the width in pixels of the first len characters of str. If len is negative (the default), the entire string is used.

Note that this value is not equal to boundingRect().width(); boundingRect() returns a rectangle describing the pixels this string will cover whereas width() returns the distance to where the next string should be drawn.

See also boundingRect().

Examples: drawdemo/drawdemo.cpp, hello/hello.cpp, movies/main.cpp, qfd/fontdisplayer.cpp and scrollview/scrollview.cpp.

int QFontMetrics::width ( QChar ch ) const

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

Returns the logical width of character ch in pixels. This is a distance appropriate for drawing a subsequent character after ch.

Some of the metrics are described in the image to the right. The central dark rectangles cover the logical width() of each character. The outer pale rectangles cover the leftBearing() and rightBearing() of each character. Notice that the bearings of "f" in this particular font are both negative, while the bearings of "o" are both positive.

Warning: This function will produce incorrect results for Arabic characters or non spacing marks in the middle of a string, as the glyph shaping and positioning of marks that happens when processing strings cannot be taken into account. Use charWidth() instead if you aren't looking for the width of isolated characters.

See also boundingRect() and charWidth().

int QFontMetrics::width ( char c ) const

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

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

Provided to aid porting from Qt 1.x.

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


qfontmetrics.h Include File

qfontmetrics.h

This is the verbatim text of the qfontmetrics.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qfontmetrics.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QFontMetrics class
**
** Created : 940514
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFONTMETRICS_H
#define QFONTMETRICS_H

#ifndef QT_H
#include "qfont.h"
#include "qrect.h"
#endif // QT_H

class QFontStruct;
class QTextCodec;
class QTextParag;

class Q_EXPORT QFontMetrics
{
public:
    QFontMetrics( const QFont & );
    QFontMetrics( const QFontMetrics & );
    ~QFontMetrics();

    QFontMetrics &operator=( const QFontMetrics & );

    int		ascent()	const;
    int		descent()	const;
    int		height()	const;
    int		leading()	const;
    int		lineSpacing()	const;
    int		minLeftBearing() const;
    int		minRightBearing() const;
    int		maxWidth()	const;

    bool	inFont(QChar)	const;

    int		leftBearing(QChar) const;
    int		rightBearing(QChar) const;
    int		width( const QString &, int len = -1 ) const;

    int		width( QChar ) const;
#ifndef QT_NO_COMPAT
    int		width( char c ) const { return width( (QChar) c ); }
#endif

    int 		charWidth( const QString &str, int pos ) const;
    QRect	boundingRect( const QString &, int len = -1 ) const;
    QRect	boundingRect( QChar ) const;
    QRect	boundingRect( int x, int y, int w, int h, int flags,
                  const QString& str, int len=-1, int tabstops=0,
                  int *tabarray=0, QTextParag **intern=0 ) const;
    QSize	size( int flags,
              const QString& str, int len=-1, int tabstops=0,
              int *tabarray=0, QTextParag **intern=0 ) const;

    int		underlinePos()	const;
    int		strikeOutPos()	const;
    int		lineWidth()	const;

private:
    QFontMetrics( const QPainter * );
    static void reset( const QPainter * );

#if defined(Q_WS_WIN)
    void   *textMetric() const;
    HDC	    hdc() const;
#elif defined(Q_WS_QWS)
    QFontStruct *internal();
#endif

    friend class QWidget;
    friend class QPainter;
#if defined( Q_WS_MAC )
    friend class QFontPrivate;
#endif

    QFontPrivate  *d;
    QPainter      *painter;
    int		   flags;

    bool    underlineFlag()  const { return (flags & 0x1) != 0; }
    bool    strikeOutFlag()  const { return (flags & 0x2) != 0; }
    void    setUnderlineFlag()	   { flags |= 0x1; }
    void    setStrikeOutFlag()	   { flags |= 0x2; }
};

#endif // QFONTMETRICS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QFontMetrics Member List

Complete Member List for QFontMetrics

This is the complete list of member functions for QFontMetrics, including inherited members.

  • QFontMetrics()
  • ~QFontMetrics()
  • ascent()
  • boundingRect()
  • charWidth()
  • descent()
  • height()
  • inFont()
  • leading()
  • leftBearing()
  • lineSpacing()
  • lineWidth()
  • maxWidth()
  • minLeftBearing()
  • minRightBearing()
  • operator=()
  • rightBearing()
  • size()
  • strikeOutPos()
  • underlinePos()
  • width()


QFrame类

QFrame类参考

QFrame类是有框架的窗口部件的基类。 详情请见……

#include <qframe.h>

继承了QWidget。

被QGroupBox、QScrollView、QDockWindow、QGrid、QHBox、QLabel、QLCDNumber、QLineEdit、QMenuBar、QPopupMenu、QProgressBar、QSplitter、QtTableView和QWidgetStack继承。

所有成员函数的列表。

公有成员

  • QFrame ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • int frameStyle () const
  • virtual void setFrameStyle ( int style )
  • int frameWidth () const
  • QRect contentsRect () const
  • enum Shape { NoFrame = 0, Box = 0x0001, Panel = 0x0002, WinPanel = 0x0003, HLine = 0x0004, VLine = 0x0005, StyledPanel = 0x0006, PopupPanel = 0x0007, MenuBarPanel = 0x0008, ToolBarPanel = 0x0009, LineEditPanel = 0x000a, TabWidgetPanel = 0x000b, MShape = 0x000f }
  • enum Shadow { Plain = 0x0010, Raised = 0x0020, Sunken = 0x0030, MShadow = 0x00f0 }
  • Shape frameShape () const
  • void setFrameShape ( Shape )
  • Shadow frameShadow () const
  • void setFrameShadow ( Shadow )
  • int lineWidth () const
  • virtual void setLineWidth ( int )
  • int margin () const
  • virtual void setMargin ( int )
  • int midLineWidth () const
  • virtual void setMidLineWidth ( int )
  • QRect frameRect () const
  • virtual void setFrameRect ( const QRect & )

属性

  • QRect contentsRect - 框架内的矩形 （只读）
  • QRect frameRect - 框架矩形
  • Shadow frameShadow - 来自框架风格的框架阴影值
  • Shape frameShape - 来自框架风格的框架外形值
  • int frameWidth - 被绘制的框架的宽度 （只读）
  • int lineWidth - 线宽
  • int margin - 边白的宽度
  • int midLineWidth - 中间的线的宽度

保护成员

  • virtual void paintEvent ( QPaintEvent * event )
  • virtual void resizeEvent ( QResizeEvent * e )
  • virtual void drawFrame ( QPainter * p )
  • virtual void drawContents ( QPainter * )
  • virtual void frameChanged ()

详细描述

QFrame类是有框架的窗口部件的基类。

它绘制框架并且调用一个虚函数drawContents()来填充这个框架。这个函数是被子类重新实现的。这里至少还有两个有用的函数：drawFrame()和frameChanged()。

QPopupMenu使用这个来把菜单“升高”，高于周围屏幕。QProgressBar有“凹陷”的外观。QLabel有平坦的外观。这些有框架的窗口部件可以被改变。

    QLabel label(...);
    label.setFrameStyle( QFrame::Panel | QFrame::Raised );
    label.setLineWidth( 2 );

    QProgressBar pbar(...);
    label.setFrameStyle( QFrame::NoFrame );

QFrame类也能够直接被用来创建没有任何内容的简单框架，尽管通常情况下，你要用到QHBox或QVBox，因为它们可以自动的布置你放到框架中的窗口部件。

框架窗口部件有四个属性：frameStyle()、lineWidth()、midLineWidth()和margin()。

框架风格由框架外形和阴影风格决定。框架外形有NoFrame、Box、Panel、StyledPanel、PopupPanel、WinPanel、ToolBarPanel、MenuBarPanel、HLine和VLine，阴影风格有Plain、Raised和Sunken。

线宽就是框架边界的宽度。

中间线宽指定的是在框架中间的另外一条线的宽度，它使用第三种颜色来得到一个三维的效果。注意中间线只有在Box、HLine和VLine这些凸起和凹陷的框架中才被绘制。

边白就是框架和框架内容之间的间隙。

这个表显示的是风格和宽度的绝大多数有用的组合（和一些没有用处的）：

也可以参考抽象窗口部件类。

成员类型文档

QFrame::Shadow

这个枚举类型定义了QFrame的框架所使用的三维效果。当前定义的效果有：

  • QFrame::Plain - 框架和内容看来和周围一样高
  • QFrame::Raised - 框架和内容看起来凸起
  • QFrame::Sunken - 框架和内容看起来凹陷
  • QFrame::MShadow - 内部的，对于阴影的掩码

Shadow和QFrame::Shape、lineWidth()和midLineWidth()相互作用。类文档中的框架的图片描绘的比这些词语更好。

也可以参考QFrame::Shape、lineWidth和midLineWidth。

QFrame::Shape

这个枚举类型定义了QFrame的框架所使用的外形。当前定义的效果有：

  • NoFrame - QFrame不画任何东西
  • Box - QFrame在它的内容周围画一个框
  • Panel - QFrame画一个平板使内容看起来凸起或者凹陷
  • WinPanel - 像Panel，但QFrame绘制三维效果的方式和Microsoft Windows 95（及其它）的一样
  • ToolBarPanel - QFrame调用QStyle::drawToolBarPanel()
  • MenuBarPanel - QFrame调用QStyle::drawMenuBarPanel()
  • HLine - QFrame绘制一个水平线，但没有框任何东西（作为分隔是有用的）
  • VLine - QFrame绘制一个竖直线，但没有框任何东西（作为分隔是有用的）
  • StyledPanel - QFrame调用QStyle::drawPanel()
  • PopupPanel - QFrame调用QStyle::drawPopupPanel()

当它不调用QStyle时，Shape和QFrame::Shadow、lineWidth()和midLineWidth()相互作用来创建整个结果。类文档中的框架的图片描绘的比这些词语更好。

也可以参考QFrame::Shadow、QFrame::style()和QStyle::drawPrimitive()。

成员函数文档

QFrame::QFrame ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个框架风格为NoFrame并且1像素框架宽度的框架窗口部件。

parent、name和f参数被传递给QWidget的构造函数。

QRect QFrame::contentsRect () const

返回框架内的矩形。详细情况请参考“contentsRect”属性。

void QFrame::drawContents ( QPainter * ) [虚 保护]

绘制框架内容的虚函数。

当你得到QPainter时，它已经被打开，并且在你离开时，它也必须是打开的。绘制工具的转换在真个过程中是被关闭的。如果你转换绘制工具，记得考虑框架并且在返回前重置转换。

这个函数在子类中被重新实现用来绘制框架中的一些东西。它只能在contentsRect()内绘制。默认函数什么都不做。

也可以参考contentsRect和QPainter::setClipRect()。

在QLabel、a href="qlcdnumber.html#drawContents">QLCDNumber、QMenuBar和QPopupMenu中重新实现。

void QFrame::drawFrame ( QPainter * p ) [虚 保护]

使用绘制工具p和当前框架属性和颜色组绘制框架。框架内的矩形不受影响。

这个函数是虚函数，但通常情况下你不需要重新实现它。如果你要做，注意QPainter已经被打开并且必须保持打开的状态。

也可以参考frameRect、contentsRect、drawContents()、a href="#frameStyle">frameStyle()和palette。

void QFrame::frameChanged () [虚 保护]

当框架风格、线宽和中间线宽发生改变时，这个虚函数被调用。

这个函数在子类中可以被重新实现，它需要知道什么时候框架属性发生变化。

默认实现是调用update()。

QRect QFrame::frameRect () const

返回框架矩形。详细情况请参考“frameRect”属性。

Shadow QFrame::frameShadow () const

返回来自框架风格的框架阴影值。详细情况请参考“frameShadow”属性。

Shape QFrame::frameShape () const

返回来自框架风格的框架外形值。详细情况请参考“frameShape”属性。

int QFrame::frameStyle () const

返回框架风格。

默认值是QFrame::NoFrame。

也可以参考setFrameStyle()、frameShape和frameShadow。

实例：scrollview/scrollview.cpp。

int QFrame::frameWidth () const

返回所绘制的框架的宽度。详细情况请参考“frameWidth”属性。

int QFrame::lineWidth () const

返回线宽。详细情况请参考“lineWidth”属性。

int QFrame::margin () const

返回边白的宽度。详细情况请参考“margin”属性。

int QFrame::midLineWidth () const

返回中间线的宽度。详细情况请参考“midLineWidth”属性。

void QFrame::paintEvent ( QPaintEvent * event ) [虚 保护]

处理绘制事件event。

绘制框架和内容。

打开框架上的绘制工具并且调用drawFrame()，然后是drawContents()。

实例：life/life.cpp和qfd/fontdisplayer.cpp。

从QWidget中重新实现的。

在a href="qttableview.html#paintEvent">QtTableView中被重新实现。

void QFrame::resizeEvent ( QResizeEvent * e ) [虚 保护]

处理重定义大小事件e。

对于被重新定义大小的窗口部件，调整框架矩形。框架矩形是弹性的，并且周围的区域是固定的。

结果框架矩形也许是零或者无效。你可以使用setMinimumSize()来避免这种可能。

如果框架矩形已经是一个零矩形，那么将不会做任何事。

实例：life/life.cpp。

从QWidget中重新实现的。

void QFrame::setFrameRect ( const QRect & ) [虚]

设置框架矩形。详细情况请参考“frameRect”属性。

void QFrame::setFrameShadow ( Shadow )

设置来自框架风格的框架阴影值。详细情况请参考“frameShadow”属性。

void QFrame::setFrameShape ( Shape )

设置来自框架风格的框架外形值。详细情况请参考“frameShape”属性。

void QFrame::setFrameStyle ( int style ) [虚]

设置框架风格为style。

style是框架外形和框架阴影风格的位或操作。详细情况请参考类文档中的框架的图片。

框架外形有：

  • NoFrame不绘制任何东西。自然地，如果你使用这个，你就不用指定阴影风格。
  • Box绘制矩形框。内容看起来和周围的屏幕一样高，但是边界本身也许凸起或凹陷。
  • Panel绘制矩形凸起或凹陷的平板。
  • StyledPanel绘制一个依赖于当前GUI风格的矩形平板。它可能是凸起的，也可能是凹陷的。
  • PopupPanel是用来绘制用于弹出窗口的框架。它的外观也依赖于当前GUI风格，通常和StyledPanel一样。
  • ToolBarPanel是用来绘制用于工具条的框架。它的外观也依赖于当前GUI风格。
  • MenuBarPanel是用来绘制用于菜单条的框架。它的外观也依赖于当前GUI风格。
  • LineEditPanel是用来绘制用于行编辑的框架。它的外观也依赖于当前GUI风格。
  • TabWidgetPanel是用来绘制用于Tab窗口部件的框架。它的外观也依赖于当前GUI风格。
  • WinPanel绘制一个和Windows 95中一样的凸起或凹陷的矩形平板。指定这个外形设置线宽为2像素。WinPanel的提供是为了兼容性。为了使GUI风格独立，我们建议使用StyledPanel替换它。
  • HLine绘制一条水平线（垂直中央）。
  • VLine绘制一条垂直线（水平中央）。

阴影风格有：

  • Plain使用调色板的前景颜色绘制（没有任何三维效果）。
  • Raised使用当前颜色组的亮和暗颜色绘制三维的凸起线。
  • Sunken使用当前颜色组的亮和暗颜色绘制三维的凹陷线。

如果被指定的中间线宽大于0，在Raised或Sunken、Box÷HLine和VLine框架中会被绘制一条另外的线。当前颜色组的中间颜色被用于绘制中间线。

也可以参考Illustration、frameStyle()、colorGroup和QColorGroup。

实例：cursor/cursor.cpp、layout/layout.cpp、listboxcombo/listboxcombo.cpp、rangecontrols/rangecontrols.cpp、scrollview/scrollview.cpp、tabdialog/tabdialog.cpp和tictac/tictac.cpp。

void QFrame::setLineWidth ( int ) [虚]

设置线宽。详细情况请参考“lineWidth”属性。

void QFrame::setMargin ( int ) [虚]

设置边白的宽度。详细情况请参考“margin”属性。

void QFrame::setMidLineWidth ( int ) [虚]

设置中间线的宽度。详细情况请参考“midLineWidth”属性。

属性文档

QRect contentsRect

这个属性保存的是框架内的矩形。

使用contentsRect()来得到这个属性值。

也可以参考frameRect和drawContents()。

QRect frameRect

这个属性保存的是框架矩形。

框架矩形是被画的框架所在的矩形。默认情况下，这是整个窗口部件。设置这个属性不会导致窗口部件更新。

如果这个属性被设置为零矩形（比如QRect(0, 0, 0, 0)），那么框架矩形将会等于窗口部件矩形。

也可以参考contentsRect。

使用setFrameRect()来设置这个属性值并且使用frameRect()来得到这个属性值。

Shadow frameShadow

这个属性保存的是来自框架风格的框架阴影值。

使用setFrameShadow()来设置这个属性值并且使用frameShadow()来得到这个属性值。

也可以参考frameStyle()和frameShape。

Shape frameShape

这个属性用来操存的是来自框架风格的框架外形值。

使用setFrameShape()来设置这个属性值并且使用frameShape()来得到这个属性值。

也可以参考frameStyle()和frameShadow。

int frameWidth

这个属性保存的是被绘制的框架的宽度。

注意框架宽度依赖于框架风格，线宽和中间线宽。比如，NoFrame风格下，框架宽度为0，而Panel风格下，框架宽度和线宽相同。框架宽度也包括边白。

也可以参考lineWidth、midLineWidth、frameStyle()和margin。

使用frameWidth()来得到这个属性值。

int lineWidth

This property holds the line width. 这个属性保存的是线宽。

注意HLine和VLine的总线宽由frameWidth()给定，而不是lineWidth()。

默认值为1。

也可以参考midLineWidth和frameWidth。

使用setLineWidth()来设置这个属性值并且使用lineWidth()来得到这个属性值。

int margin

这个属性保存的是边白的宽度。

边白是框架最里面的像素和contentsRect()最外面的像素之间的区域。它被包含在frameWidth()中。

边白是根据backgroundMode()被填充的。

默认值为0。

也可以参考lineWidth和frameWidth。

使用setMargin()来设置这个属性值并且使用margin()来得到这个属性值。

int midLineWidth

这个属性保存的是中间线的宽度。

默认值为0。

也可以参考lineWidth和frameWidth。

使用setMidLineWidth()来设置这个属性值并且使用midLineWidth()来得到这个属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qframe.h包含文件

qframe.h

这里是qframe.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qframe.h   3.0.5   edited Nov 15 2001 $
**
** Definition of QFrame widget class
**
** Created : 950201
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFRAME_H
#define QFRAME_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_FRAME

class Q_EXPORT QFrame : public QWidget
{
    Q_OBJECT
    Q_ENUMS( Shape Shadow )
    Q_PROPERTY( int frameWidth READ frameWidth )
    Q_PROPERTY( QRect contentsRect READ contentsRect )
    Q_PROPERTY( Shape frameShape READ frameShape WRITE setFrameShape )
    Q_PROPERTY( Shadow frameShadow READ frameShadow WRITE setFrameShadow )
    Q_PROPERTY( int lineWidth READ lineWidth WRITE setLineWidth )
    Q_PROPERTY( int margin READ margin WRITE setMargin )
    Q_PROPERTY( int midLineWidth READ midLineWidth WRITE setMidLineWidth )
    Q_PROPERTY( QRect frameRect READ frameRect WRITE setFrameRect DESIGNABLE false )

public:
    QFrame( QWidget* parent=0, const char* name=0, WFlags f=0 );

    int         frameStyle()    const;
    virtual void setFrameStyle( int );

    int         frameWidth()    const;
    QRect       contentsRect()  const;

#ifndef Q_QDOC
    bool        lineShapesOk()  const { return TRUE; }
#endif

    QSize       sizeHint() const;

    enum Shape { NoFrame  = 0,                  // no frame
                 Box      = 0x0001,             // rectangular box
                 Panel    = 0x0002,             // rectangular panel
                 WinPanel = 0x0003,             // rectangular panel (Windows)
                 HLine    = 0x0004,             // horizontal line
                 VLine    = 0x0005,             // vertical line
                 StyledPanel = 0x0006,          // rectangular panel depending on the GUI style
                 PopupPanel = 0x0007,           // rectangular panel depending on the GUI style
                 MenuBarPanel = 0x0008,
                 ToolBarPanel = 0x0009,
         LineEditPanel = 0x000a,
         TabWidgetPanel = 0x000b,
                 MShape   = 0x000f              // mask for the shape
    };
    enum Shadow { Plain    = 0x0010,            // plain line
                  Raised   = 0x0020,            // raised shadow effect
                  Sunken   = 0x0030,            // sunken shadow effect
                  MShadow  = 0x00f0 };          // mask for the shadow

    Shape       frameShape()    const;
    void        setFrameShape( Shape );
    Shadow      frameShadow()   const;
    void        setFrameShadow( Shadow );

    int         lineWidth()     const;
    virtual void setLineWidth( int );

    int         margin()        const;
    virtual void setMargin( int );

    int         midLineWidth()  const;
    virtual void setMidLineWidth( int );

    QRect       frameRect()     const;
    virtual void setFrameRect( const QRect & );

protected:
    void        paintEvent( QPaintEvent * );
    void        resizeEvent( QResizeEvent * );
    virtual void drawFrame( QPainter * );
    virtual void drawContents( QPainter * );
    virtual void frameChanged();

private:
    void        updateFrameWidth();
    QRect       frect;
    int         fstyle;
    short       lwidth;
    short       mwidth;
    short       mlwidth;
    short       fwidth;

    void * d;
private:        // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QFrame( const QFrame & );
    QFrame &operator=( const QFrame & );
#endif
};

inline int QFrame::frameStyle() const
{ return fstyle; }

inline QFrame::Shape QFrame::frameShape() const
{ return (Shape) ( fstyle & MShape ); }

inline QFrame::Shadow QFrame::frameShadow() const
{ return (Shadow) ( fstyle & MShadow ); }

inline void QFrame::setFrameShape( QFrame::Shape s )
{ setFrameStyle( ( fstyle & MShadow ) | s ); }

inline void QFrame::setFrameShadow( QFrame::Shadow s )
{ setFrameStyle( ( fstyle & MShape ) | s ); }

inline int QFrame::lineWidth() const
{ return lwidth; }

inline int QFrame::midLineWidth() const
{ return mlwidth; }

inline int QFrame::margin() const
{ return mwidth; }

inline int QFrame::frameWidth() const
{ return fwidth; }

#endif // QT_NO_FRAME

#endif // QFRAME_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFrame成员列表

完整的QFrame成员列表

这里是QFrame成员函数的完整列表，包括继承的成员。

  • QFrame()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QFtp类

QFtp类参考
[网络模块]

QFtp是一个用来实现FTP协议的类。 详情请见……

#include <qftp.h>

继承了QNetworkProtocol。

所有成员函数的列表。

公有成员

  • QFtp ()
  • virtual ~QFtp ()

保护成员

  • void parseDir ( const QString & buffer, QUrlInfo & info )

保护槽

  • void readyRead ()
  • void dataConnected ()
  • void dataClosed ()
  • void dataReadyRead ()
  • void dataBytesWritten ( int nbytes )

详细描述

QFtp是一个用来实现FTP协议的类。

这个类派生于QNetworkProtocol。QFtp一般情况下并不是直接使用，而是通过QUrlOperator来实现的，举例如下：

  QUrlOperator op( "ftp://ftp.trolltech.com" );
  op.listChildren(); // 请求服务器提供一个文件列表

这段代码只能在QFtp类已经注册的情况下才能正常工作；要注册这个类，你必须在QFtp使用QUrlOperator之前注册qInitNetworkProtocols()。

如果你真的想要直接使用QFtp，不要忘了使用setUrl()设定它的QUrlOperator。

也可以参考Qt网络文档、QNetworkProtocol、QUrlOperator和输入/输出和网络。

成员函数文档

QFtp::QFtp ()

构造一个QFtp对象。

QFtp::~QFtp () [虚]

析构函数。

void QFtp::dataBytesWritten ( int nbytes ) [保护 槽]

当nbytes已经被成功地写到数据套接字的时候，这个函数被调用。

void QFtp::dataClosed () [保护 槽]

当一个数据连接被关闭时调用。

void QFtp::dataConnected () [保护 槽]

一些事务需要同服务器建立一个数据连接，如果这个连接能够成功，这个函数将处理数据连接。

void QFtp::dataReadyRead () [保护 槽]

当新的数据到达数据套接字时，这个函数被调用。

void QFtp::parseDir ( const QString & buffer, QUrlInfo & info ) [保护]

分析字符串，buffer，来自FTP服务器的目录列表的一行, 并且设定值为从url信息对象解析出来的值，info。

void QFtp::readyRead () [保护 槽]

当数据到达到这个命令套接字时，这个槽被调用。这个函数监视数据并且把数据提交给能够处理它的函数上。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:云飞扬
Qt 3.0.5版


qftp.h包含文件

qftp.h

这里是qftp.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qftp.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QFtp class.
**
** Created : 970521
**
** Copyright (C) 1997-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QFTP_H
#define QFTP_H

#ifndef QT_H
#include "qstring.h" // char*->QString conversion
#include "qurlinfo.h"
#include "qnetworkprotocol.h"
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_FTP
#else
#define QM_EXPORT_FTP Q_EXPORT
#endif

#ifndef QT_NO_NETWORKPROTOCOL_FTP

class QSocket;

class QM_EXPORT_FTP QFtp : public QNetworkProtocol
{
    Q_OBJECT

public:
    QFtp();
    virtual ~QFtp();
    int supportedOperations() const;

protected:
    void parseDir( const QString &buffer, QUrlInfo &info );
    void operationListChildren( QNetworkOperation *op );
    void operationMkDir( QNetworkOperation *op );
    void operationRemove( QNetworkOperation *op );
    void operationRename( QNetworkOperation *op );
    void operationGet( QNetworkOperation *op );
    void operationPut( QNetworkOperation *op );

    QSocket *commandSocket, *dataSocket;
    bool connectionReady, passiveMode;
    int getTotalSize, getDoneSize;
    bool startGetOnFail;
    int putToWrite, putWritten;
    bool errorInListChildren;

private:
    bool checkConnection( QNetworkOperation *op );
    void close();
    void reinitCommandSocket();
    void okButTryLater( int code, const QCString &data );
    void okGoOn( int code, const QCString &data );
    void okButNeedMoreInfo( int code, const QCString &data );
    void errorForNow( int code, const QCString &data );
    void errorForgetIt( int code, const QCString &data );

protected slots:
    void hostFound();
    void connected();
    void closed();
    void readyRead();
    void dataHostFound();
    void dataConnected();
    void dataClosed();
    void dataReadyRead();
    void dataBytesWritten( int nbytes );
    void error( int );

};

#endif // QT_NO_NETWORKPROTOCOL_FTP

#endif // QFTP_H

Copyright © 2002 Trolltech Trademarks 译者:云飞扬
Qt 3.0.5版


QFtp成员列表

完整的QFtp成员列表

这里是QFtp成员函数的完整列表，包括继承的成员。

  • QFtp()
  • ~QFtp()
  • addOperation()
  • autoDelete()
  • blockSignals()
  • checkConnectArgs()
  • checkConnection()
  • child()
  • childEvent()
  • children()
  • className()
  • clearOperationQueue()
  • connect()
  • connectNotify()
  • connectionStateChanged()
  • createdDirectory()
  • customEvent()
  • data()
  • dataBytesWritten()
  • dataClosed()
  • dataConnected()
  • dataReadyRead()
  • dataTransferProgress()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • finished()
  • getNetworkProtocol()
  • hasOnlyLocalFileSystem()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemChanged()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • newChild()
  • newChildren()
  • normalizeSignalSlot()
  • objectTrees()
  • operationGet()
  • operationInProgress()
  • operationListChildren()
  • operationMkDir()
  • operationPut()
  • operationRemove()
  • operationRename()
  • parent()
  • parseDir()
  • property()
  • queryList()
  • readyRead()
  • registerNetworkProtocol()
  • removeChild()
  • removeEventFilter()
  • removed()
  • sender()
  • setAutoDelete()
  • setName()
  • setProperty()
  • setUrl()
  • signalsBlocked()
  • start()
  • startTimer()
  • stop()
  • supportedOperations()
  • timerEvent()
  • tr()
  • trUtf8()
  • url()

Copyright © 2002 Trolltech Trademarks 译者:云飞扬
Qt 3.0.5版


QGb18030Codec Class

QGb18030Codec Class Reference

The QGb18030Codec class provides conversion to and from the Chinese GB18030/GBK/GB2312 encoding. More...

#include <qgb18030codec.h>

Inherits QTextCodec.

Inherited by QGbkCodec.

List of all member functions.

Detailed Description

The QGb18030Codec class provides conversion to and from the Chinese GB18030/GBK/GB2312 encoding.

GBK, formally the Chinese Internal Code Specification, is a commonly used extension of GB 2312-80. Microsoft Windows uses it under the name codepage 936.

GBK has been superceded by the new Chinese national standard GB 18030-2000, which added a 4-byte encoding while remaining compatible with GB2312 and GBK. The new GB18030-2000 may be described as a special encoding of Unicode 3.x and ISO-10646-1.

Special thanks to charset gurus Markus Scherer (IBM), Dirk Meyer (Adobe Systems) and Ken Lunde (Adobe Systems) for publishing an excellent GB 18030-200 summary and specification on the Internet. Some must-read documents are:

  • ftp://ftp.oreilly.com/pub/examples/nutshell/cjkv/pdf/GB18030_Summary.pdf
  • http://oss.software.ibm.com/cvs/icu/~checkout~/charset/source/gb18030/gb18030.html
  • http://oss.software.ibm.com/cvs/icu/~checkout~/charset/data/xml/gb-18030-2000.xml

The GBK codec was contributed to Qt by Justin Yu <justiny@turbolinux.com.cn> and Sean Chen <seanc@turbolinux.com.cn>. They may also be reached at Yu Mingjian <yumj@sun.ihep.ac.cn>, <yumingjian@china.com> Chen Xiangyang <chenxy@sun.ihep.ac.cn>

The GB18030 codec Qt functions were contributed to Qt by James Su <suzhe@gnuchina.org>, <suzhe@turbolinux.com.cn> who pioneered much of GB18030 development on GNU/Linux systems.

The GB18030 codec was contributed to Qt by Anthony Fok <anthony@thizlinux.com>, <foka@debian.org> using a Perl script to generate C++ tables from gb-18030-2000.xml while merging contributions from James Su, Justin Yu and Sean Chen. A copy of the source Perl script is available at:

http://people.debian.org/~foka/gb18030/gen-qgb18030codec.pl

The copyright notice for their code follows:

Copyright (C) 2000 TurboLinux, Inc. Written by Justin Yu and Sean Chen. Copyright (C) 2001 Turbolinux, Inc. Written by James Su. Copyright (C) 2001 ThizLinux Laboratory Ltd. Written by Anthony Fok.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

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


qgb18030codec.h Include File

qgb18030codec.h

This is the verbatim text of the qgb18030codec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QGb18030Codec class
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

// Contributed by James Su <suzhe@gnuchina.org>

#ifndef QGB18030CODEC_H
#define QGB18030CODEC_H

#ifndef QT_H
#include "qglobal.h"
#include "qtextcodec.h"
#endif // QT_H

#ifndef QT_NO_BIG_CODECS

#if defined(QT_PLUGIN)
#define Q_EXPORT_CODECS_CN
#else
#define Q_EXPORT_CODECS_CN Q_EXPORT
#endif

class Q_EXPORT_CODECS_CN QGb18030Codec : public QTextCodec {
public:
    QGb18030Codec();

    int mibEnum() const;
    const char* name() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;
};

class Q_EXPORT_CODECS_CN QGbkCodec : public QGb18030Codec {
public:
    QGbkCodec();

    int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGb18030Codec Member List

Complete Member List for QGb18030Codec

This is the complete list of member functions for QGb18030Codec, including inherited members.

  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QGbkCodec Class

QGbkCodec Class Reference

The QGbkCodec class provides conversion to and from the Chinese GBK encoding. More...

#include <qgb18030codec.h>

Inherits QGb18030Codec.

List of all member functions.

Public Members

  • QGbkCodec ()
  • virtual const char * mimeName () const

Detailed Description

The QGbkCodec class provides conversion to and from the Chinese GBK encoding.

GBK, formally the Chinese Internal Code Specification, is a commonly used extension of GB 2312-80. Microsoft Windows uses it under the name code page 936.

The GBK encoding has been superceded by the GB18030 encoding and GB18030 is compatible to GBK. For this reason the QGbkCodec class is implemented in terms of the GB18030 codec and uses it for conversion from and to Unicode.

The QGbkCodec is kept mainly for compatibility reasons with older software.

See also Internationalization with Qt.

Member Function Documentation

QGbkCodec::QGbkCodec ()

reimp

const char * QGbkCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


QGbkCodec Member List

Complete Member List for QGbkCodec

This is the complete list of member functions for QGbkCodec, including inherited members.

  • QGbkCodec()
  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


qgfx_qws.h Include File

qgfx_qws.h

This is the verbatim text of the qgfx_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qgfx_qws.h   3.0.5   edited Feb 21 1999 $
**
** Definition of QGfx (graphics context) class
**
** Created : 940721
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGFX_H
#define QGFX_H

#ifndef QT_H
#include "qwidget.h"
#include "qnamespace.h"
#include "qimage.h"
#include "qfontmanager_qws.h"
#include "qpoint.h"
#endif // QT_H

class QScreenCursor;

#if !defined( QT_NO_IMAGE_16_BIT ) || !defined( QT_NO_QWS_DEPTH_16 )
# ifndef QT_QWS_DEPTH16_RGB
#  define QT_QWS_DEPTH16_RGB 565
# endif
static const int qt_rbits = (QT_QWS_DEPTH16_RGB/100);
static const int qt_gbits = (QT_QWS_DEPTH16_RGB/10%10);
static const int qt_bbits = (QT_QWS_DEPTH16_RGB%10);
static const int qt_red_shift = qt_bbits+qt_gbits-(8-qt_rbits);
static const int qt_green_shift = qt_bbits-(8-qt_gbits);
static const int qt_neg_blue_shift = 8-qt_bbits;
static const int qt_blue_mask = (1<<qt_bbits)-1;
static const int qt_green_mask = (1<<(qt_gbits+qt_bbits))-((1<<qt_bbits)-1);
static const int qt_red_mask = (1<<(qt_rbits+qt_gbits+qt_bbits))-(1<<(qt_gbits+qt_bbits));

inline ushort qt_convRgbTo16( const int r, const int g, const int b )
{
    const int tr = r << qt_red_shift;
    const int tg = g << qt_green_shift;
    const int tb = b >> qt_neg_blue_shift;

    return (tb & qt_blue_mask) | (tg & qt_green_mask) | (tr & qt_red_mask);
}

inline ushort qt_convRgbTo16( QRgb c )
{
    const int tr = qRed(c) << qt_red_shift;
    const int tg = qGreen(c) << qt_green_shift;
    const int tb = qBlue(c) >> qt_neg_blue_shift;

    return (tb & qt_blue_mask) | (tg & qt_green_mask) | (tr & qt_red_mask);
}

inline QRgb qt_conv16ToRgb( ushort c )
{
    const int r=(c & qt_red_mask);
    const int g=(c & qt_green_mask);
    const int b=(c & qt_blue_mask);
    const int tr = r >> qt_red_shift;
    const int tg = g >> qt_green_shift;
    const int tb = b << qt_neg_blue_shift;

    return qRgb(tr,tg,tb);
}

inline void qt_conv16ToRgb( ushort c, int& r, int& g, int& b )
{
    const int tr=(c & qt_red_mask);
    const int tg=(c & qt_green_mask);
    const int tb=(c & qt_blue_mask);
    r = tr >> qt_red_shift;
    g = tg >> qt_green_shift;
    b = tb << qt_neg_blue_shift;
}
#endif

const int SourceSolid=0;
const int SourcePixmap=1;

#ifndef QT_NO_QWS_CURSOR

extern bool qt_sw_cursor;

class QGfxRasterBase;

#define SW_CURSOR_DATA_SIZE	4096  // 64x64 8-bit cursor

class SWCursorData;

class QScreenCursor
{
public:
    QScreenCursor( );
    virtual ~QScreenCursor();

    virtual void init(SWCursorData *da, bool init = FALSE);

    virtual void set( const QImage &image, int hotx, int hoty );
    virtual void move( int x, int y );
    virtual void show();
    virtual void hide();

    virtual bool restoreUnder( const QRect &r, QGfxRasterBase *g = 0 );
    virtual void saveUnder();
    virtual void drawCursor();
    //void draw();
    virtual bool supportsAlphaCursor();

    static bool enabled() { return qt_sw_cursor; }

protected:
    QGfxRasterBase *gfx;
    QGfxRasterBase *gfxunder;

    QImage *imgunder;
    QImage *cursor;

    uchar *fb_start;
    uchar *fb_end;
    bool save_under;
    SWCursorData *data;

    int clipWidth;
    int clipHeight;
    int myoffset;

};

extern QScreenCursor * qt_screencursor;

#endif // QT_NO_QWS_CURSOR

struct fb_cmap;

// A (used) chunk of offscreen memory

class QPoolEntry {

public:

    unsigned int start;
    unsigned int end;

};

class QScreen {

public:

    QScreen( int display_id );
    virtual ~QScreen();
    virtual bool initDevice() = 0;
    virtual bool connect( const QString &displaySpec ) = 0;
    virtual void disconnect() = 0;
    virtual int initCursor(void *, bool=FALSE);
    virtual void shutdownDevice();
    virtual void setMode(int,int,int) = 0;
    virtual bool supportsDepth(int) const;
    virtual QGfx * createGfx(unsigned char *,int,int,int,int);
    virtual QGfx * screenGfx();
    virtual void save();
    virtual void restore();
    virtual void blank(bool on);

    virtual int pixmapOffsetAlignment() { return 64; }
    virtual int pixmapLinestepAlignment() { return 64; }

    virtual bool onCard(unsigned char *) const;
    virtual bool onCard(unsigned char *, ulong& out_offset) const;

    // sets a single color in the colormap
    virtual void set(unsigned int,unsigned int,unsigned int,unsigned int);
    // allocates a color
    virtual int alloc(unsigned int,unsigned int,unsigned int);

    int width() const { return w; }
    int height() const { return h; }
    int depth() const { return d; }
    virtual int pixmapDepth() const;
    int pixelType() const { return pixeltype; }
    int linestep() const { return lstep; }
    int deviceWidth() const { return dw; }
    int deviceHeight() const { return dh; }
    uchar * base() const { return data; }
    // Ask for memory from card cache with alignment
    virtual uchar * cache(int,int) { return 0; }
    virtual void uncache(uchar *) {}

    int screenSize() const { return size; }
    int totalSize() const { return mapsize; }

    QRgb * clut() { return screenclut; }
    int numCols() { return screencols; }

    virtual QSize mapToDevice( const QSize & ) const;
    virtual QSize mapFromDevice( const QSize & ) const;
    virtual QPoint mapToDevice( const QPoint &, const QSize & ) const;
    virtual QPoint mapFromDevice( const QPoint &, const QSize & ) const;
    virtual QRect mapToDevice( const QRect &, const QSize & ) const;
    virtual QRect mapFromDevice( const QRect &, const QSize & ) const;
    virtual QImage mapToDevice( const QImage & ) const;
    virtual QImage mapFromDevice( const QImage & ) const;
    virtual QRegion mapToDevice( const QRegion &, const QSize & ) const;
    virtual QRegion mapFromDevice( const QRegion &, const QSize & ) const;
    virtual int transformOrientation() const;
    virtual bool isTransformed() const;

    virtual bool isInterlaced() const;

    virtual void setDirty( const QRect& );

#ifndef QT_NO_QWS_REPEATER
    int * opType() { return screen_optype; }
    int * lastOp() { return screen_lastop; }
#endif

protected:

    // Only used without QT_NO_QWS_REPEATER, but included so that
    // it's binary compatible regardless.
    int * screen_optype;
    int * screen_lastop;

    QRgb screenclut[256];
    int screencols;

    bool initted;

    uchar * data;

    // Table of allocated lumps, kept in sorted highest-to-lowest order
    // The table itself is allocated at the bottom of offscreen memory
    // i.e. it's similar to having a stack (the table) and a heap
    // (the allocated blocks). Freed space is implicitly described
    // by the gaps between the allocated lumps (this saves entries and
    // means we don't need to worry about coalescing freed lumps)

    QPoolEntry * entries;
    int * entryp;
    unsigned int * lowest;

    int w;
    int lstep;
    int h;
    int d;
    int pixeltype;

    int dw;
    int dh;

    int hotx;
    int hoty;
    QImage cursor;

    int size;	       // Screen size
    int mapsize;       // Total mapped memory

    int displayId;
};

extern QScreen * qt_screen;

class Q_EXPORT QGfx : public Qt {
public:
    // With loadable drivers, do probe here
    static QGfx *createGfx( int depth, unsigned char *buffer,
                int w, int h, int linestep );

    virtual ~QGfx() {}

    virtual void setPen( const QPen & )=0;
    virtual void setFont( const QFont & )=0;
    virtual void setBrush( const QBrush & )=0;
    virtual void setBrushPixmap( const QPixmap * )=0;
    virtual void setBrushOffset( int, int ) = 0;
    virtual void setClipRect( int,int,int,int )=0;
    virtual void setClipRegion( const QRegion & )=0;
    virtual void setClipDeviceRegion( const QRegion & )=0;
    virtual void setClipping (bool)=0;
    // These will be called from qwidget_qws or qwidget_mac
    // to update the drawing area when a widget is moved
    virtual void setOffset( int,int )=0;
    virtual void setWidgetRect( int,int,int,int )=0;
    virtual void setWidgetRegion( const QRegion & )=0;
    virtual void setWidgetDeviceRegion( const QRegion & )=0;
    virtual void setSourceWidgetOffset(int x, int y) = 0;
    virtual void setGlobalRegionIndex( int idx ) = 0;

    virtual void setDashedLines(bool d) = 0;
    virtual void setDashes(char *, int) = 0;

    virtual void setOpaqueBackground(bool b)=0;
    virtual void setBackgroundColor(QColor c)=0;

    // Drawing operations
    virtual void drawPoint( int,int )=0;
    virtual void drawPoints( const QPointArray &,int,int )=0;
    virtual void moveTo( int,int )=0;
    virtual void lineTo( int,int )=0;
    virtual void drawLine( int,int,int,int )=0;
    virtual void drawPolyline( const QPointArray &,int,int )=0;

    // current position
    virtual QPoint pos() const = 0;

    // Fill operations - these use the current source (pixmap,
    // color, etc), and draws outline
    virtual void fillRect( int,int,int,int )=0;
    virtual void drawPolygon( const QPointArray &,bool,int,int )=0;

    virtual void setLineStep(int)=0;

    // Special case of rect-with-pixmap-fill for speed/hardware acceleration
    virtual void blt( int,int,int,int,int,int )=0;
    virtual void scroll( int,int,int,int,int,int )=0;

#if !defined(QT_NO_MOVIE) || !defined(QT_NO_TRANSFORMATIONS) || !defined(QT_NO_PIXMAP_TRANSFORMATION)
    virtual void stretchBlt( int,int,int,int,int,int )=0;
#endif
    virtual void tiledBlt( int,int,int,int )=0;

    enum SourceType { SourcePen, SourceImage, SourceAccel };
    enum PixelType { NormalPixel, BGRPixel };

    // Setting up source data - can be solid color or pixmap data
    virtual void setSource(const QPaintDevice *)=0;
    virtual void setSource(const QImage *)=0;
    virtual void setSource(unsigned char *,int,int,int,int,QRgb *,int);
    // This one is pen
    virtual void setSourcePen()=0;

    virtual void drawAlpha(int,int,int,int,int,int,int,int) {}

    virtual void hsync(int) {}

    // These apply only to blt's. For alpha values for general
    // drawing operations we should probably have a separate QGfx
    // class. It's not a high priority though.

    // Enum values: Ignore alpha information, alpha information encoded in
    // 32-bit rgba along with colors, alpha information in 8bpp
    // format in alphabits

    enum AlphaType { IgnoreAlpha, InlineAlpha, SeparateAlpha,
                     LittleEndianMask, BigEndianMask, SolidAlpha };

    // Can be no alpha, inline (32bit data), separate (for images),
    // LittleEndianMask/BigEndianMask 1bpp masks, constant alpha
    // value
    virtual void setAlphaType(AlphaType)=0;
    // Pointer to data, linestep
    virtual void setAlphaSource(unsigned char *,int)=0;
    virtual void setAlphaSource(int,int=-1,int=-1,int=-1)=0;

    virtual void drawText( int,int,const QString & )=0;

    virtual void setClut(QRgb *,int)=0;

    // Save and restore pen and brush state - necessary when setting
    // up a bitBlt for example
    virtual void save()=0;
    virtual void restore()=0;

    virtual void setRop(RasterOp)=0;
    virtual void setScreen(QScreen *,QScreenCursor *,bool,int *,int *);

    bool isScreenGfx() { return is_screen_gfx; } //for cursor..

protected:
    bool is_screen_gfx;

};

// This lives in loadable modules

#ifndef QT_LOADABLE_MODULES
extern "C" QScreen * qt_get_screen( int display_id, const char* spec );
#endif

// This is in main lib, loads the right module, calls qt_get_screen
// In non-loadable cases just aliases to qt_get_screen

const unsigned char * qt_probe_bus();

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGL Class

QGL Class Reference
[OpenGL module]

The QGL class is a namespace for miscellaneous identifiers in the Qt OpenGL module. More...

#include <qgl.h>

Inherited by QGLFormat, QGLContext and QGLWidget.

List of all member functions.

Public Members

  • enum FormatOption { DoubleBuffer = 0x0001, DepthBuffer = 0x0002, Rgba = 0x0004, AlphaChannel = 0x0008, AccumBuffer = 0x0010, StencilBuffer = 0x0020, StereoBuffers = 0x0040, DirectRendering = 0x0080, HasOverlay = 0x0100, SingleBuffer = DoubleBuffer<<16, NoDepthBuffer = DepthBuffer<<16, ColorIndex = Rgba<<16, NoAlphaChannel = AlphaChannel<<16, NoAccumBuffer = AccumBuffer<<16, NoStencilBuffer = StencilBuffer<<16, NoStereoBuffers = StereoBuffers<<16, IndirectRendering = DirectRendering<<16, NoOverlay = HasOverlay<<16 }

Detailed Description

The QGL class is a namespace for miscellaneous identifiers in the Qt OpenGL module.

Normally you can ignore this class. QGLWidget and the other OpenGL* module classes inherit it, so when you make your own QGLWidget subclass you can use the identifiers in the QGL namespace without qualification.

However, you may occasionally find yourself in situations where you need to refer to these identifiers from outside the QGL namespace's scope, e.g. in static functions. In such cases, simply write e.g. QGL::DoubleBuffer instead of just DoubleBuffer.

* OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.

See also Graphics Classes and Image Processing Classes.

Member Type Documentation

QGL::FormatOption

This enum specifies the format options.

  • QGL::DoubleBuffer
  • QGL::DepthBuffer
  • QGL::Rgba
  • QGL::AlphaChannel
  • QGL::AccumBuffer
  • QGL::StencilBuffer
  • QGL::StereoBuffers
  • QGL::DirectRendering
  • QGL::HasOverlay
  • QGL::SingleBuffer
  • QGL::NoDepthBuffer
  • QGL::ColorIndex
  • QGL::NoAlphaChannel
  • QGL::NoAccumBuffer
  • QGL::NoStencilBuffer
  • QGL::NoStereoBuffers
  • QGL::IndirectRendering
  • QGL::NoOverlay

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


qgl.h Include File

qgl.h

This is the verbatim text of the qgl.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qgl.h   3.0.5   edited Oct 12 2001 $
**
** Definition of OpenGL classes for Qt
**
** Created : 970112
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the opengl module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGL_H
#define QGL_H

#ifndef QT_H
#include <qwidget.h>
#include "qglcolormap.h"
#endif // QT_H

#if !defined( QT_MODULE_OPENGL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_OPENGL
#else
#define QM_EXPORT_OPENGL Q_EXPORT
#endif

#ifndef QT_NO_COMPAT
#define QGL_VERSION	450
#define QGL_VERSION_STR	"4.5"
QM_EXPORT_OPENGL inline const char *qGLVersion() {
    qObsolete( 0, "qGLVersion", "qVersion" );
    return QGL_VERSION_STR;
}
#endif

#if defined(Q_WS_WIN)
# include <qt_windows.h>
#endif

#if defined(Q_WS_MAC)
#ifndef QMAC_OPENGL_DOUBLEBUFFER
#define QMAC_OPENGL_DOUBLEBUFFER
#endif
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
#else
# include <GL/gl.h>
# include <GL/glu.h>
#endif

#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
class QGLCmap;
#endif

class QPixmap;
#if defined(Q_WS_X11)
class QGLOverlayWidget;
#endif

// Namespace class:
class QM_EXPORT_OPENGL QGL
{
public:
    enum FormatOption {
    DoubleBuffer		= 0x0001,
    DepthBuffer		= 0x0002,
    Rgba			= 0x0004,
    AlphaChannel		= 0x0008,
    AccumBuffer		= 0x0010,
    StencilBuffer		= 0x0020,
    StereoBuffers		= 0x0040,
    DirectRendering		= 0x0080,
    HasOverlay		= 0x0100,
    SingleBuffer            = DoubleBuffer  << 16,
    NoDepthBuffer           = DepthBuffer   << 16,
    ColorIndex              = Rgba          << 16,
    NoAlphaChannel          = AlphaChannel  << 16,
    NoAccumBuffer           = AccumBuffer   << 16,
    NoStencilBuffer         = StencilBuffer << 16,
    NoStereoBuffers         = StereoBuffers << 16,
    IndirectRendering       = DirectRendering << 16,
    NoOverlay       	= HasOverlay << 16
    };
};

class QM_EXPORT_OPENGL QGLFormat : public QGL
{
public:
    QGLFormat();
    QGLFormat( int options, int plane = 0 );

    bool    		doubleBuffer() const;
    void    		setDoubleBuffer( bool enable );
    bool    		depth() const;
    void    		setDepth( bool enable );
    bool    		rgba() const;
    void    		setRgba( bool enable );
    bool    		alpha() const;
    void    		setAlpha( bool enable );
    bool    		accum() const;
    void    		setAccum( bool enable );
    bool    		stencil() const;
    void    		setStencil( bool enable );
    bool    		stereo() const;
    void    		setStereo( bool enable );
    bool    		directRendering() const;
    void    		setDirectRendering( bool enable );
    bool    		hasOverlay() const;
    void    		setOverlay( bool enable );

    int			plane() const;
    void		setPlane( int plane );

    void		setOption( FormatOption opt );
    bool		testOption( FormatOption opt ) const;

    static QGLFormat	defaultFormat();
    static void		setDefaultFormat( const QGLFormat& f );

    static QGLFormat	defaultOverlayFormat();
    static void		setDefaultOverlayFormat( const QGLFormat& f );

    static bool		hasOpenGL();
    static bool		hasOpenGLOverlays();

    friend QM_EXPORT_OPENGL bool operator==( const QGLFormat&, const QGLFormat& );
    friend QM_EXPORT_OPENGL bool operator!=( const QGLFormat&, const QGLFormat& );

private:
    uint opts;
    int pln;
};

QM_EXPORT_OPENGL bool operator==( const QGLFormat&, const QGLFormat& );
QM_EXPORT_OPENGL bool operator!=( const QGLFormat&, const QGLFormat& );

class QM_EXPORT_OPENGL QGLContext : public QGL
{
public:
    QGLContext( const QGLFormat& format, QPaintDevice* device );
    virtual ~QGLContext();

    virtual bool	create( const QGLContext* shareContext = 0 );
    bool		isValid() const;
    bool		isSharing() const;
    virtual void	reset();

    QGLFormat		format() const;
    QGLFormat		requestedFormat() const;
    virtual void	setFormat( const QGLFormat& format );

    virtual void	makeCurrent();
    virtual void	swapBuffers() const;

    QPaintDevice*	device() const;

    QColor		overlayTransparentColor() const;

    static const QGLContext*	currentContext();

protected:
    virtual bool	chooseContext( const QGLContext* shareContext = 0 );
    virtual void	doneCurrent();

#if defined(Q_WS_WIN)
    virtual int		choosePixelFormat( void* pfd, HDC pdc );
#elif defined(Q_WS_X11)
    virtual void*	tryVisual( const QGLFormat& f, int bufDepth = 1 );
    virtual void*	chooseVisual();
#elif defined(Q_WS_MAC)
    virtual void*	chooseMacVisual(GDHandle);
#endif

    bool		deviceIsPixmap() const;
    bool		windowCreated() const;
    void		setWindowCreated( bool on );
    bool		initialized() const;
    void		setInitialized( bool on );

    uint		colorIndex( const QColor& c ) const;

protected:
#if  defined(Q_WS_WIN)
    HGLRC		rc;
    HDC			dc;
    WId	win;
    int			pixelFormatId;
    QGLCmap*		cmap;
#elif defined(Q_WS_X11)
    void*		vi;
    void*		cx;
    Q_UINT32		gpm;
#elif defined(Q_WS_MAC)
    void*               vi;
    void*		cx;
#endif

    QGLFormat		glFormat;
    QGLFormat		reqFormat;

private:
    class Private {
    public:
    bool		valid;
    bool		sharing;
    bool		initDone;
    bool		crWin;
    QPaintDevice*	paintDevice;
    QColor		transpColor;
    };
    Private* d;
    static QGLContext*	currentCtx;

    friend class QGLWidget;
#ifdef Q_WS_MAC
    void fixBufferRect();
#endif

private:	// Disabled copy constructor and operator=
    QGLContext() {}
    QGLContext( const QGLContext& ) {}
    QGLContext&		operator=( const QGLContext& ) { return *this; }
};

class QM_EXPORT_OPENGL QGLWidget : public QWidget, public QGL
{
    Q_OBJECT
public:
    QGLWidget( QWidget* parent=0, const char* name=0,
           const QGLWidget* shareWidget = 0, WFlags f=0 );
    QGLWidget( const QGLFormat& format, QWidget* parent=0, const char* name=0,
           const QGLWidget* shareWidget = 0, WFlags f=0 );
    ~QGLWidget();

    void		qglColor( const QColor& c ) const;
    void		qglClearColor( const QColor& c ) const;

    bool		isValid() const;
    bool		isSharing() const;
    virtual void	makeCurrent();

    bool		doubleBuffer() const;
    virtual void	swapBuffers();

    QGLFormat		format() const;
#ifndef Q_QDOC
    virtual void	setFormat( const QGLFormat& format );
#endif

    const QGLContext*	context() const;
#ifndef Q_QDOC
    virtual void	setContext( QGLContext* context,
                    const QGLContext* shareContext = 0,
                    bool deleteOldContext = TRUE );
#endif

    virtual QPixmap	renderPixmap( int w = 0, int h = 0,
                      bool useContext = FALSE );
    virtual QImage	grabFrameBuffer( bool withAlpha = FALSE );

    virtual void	makeOverlayCurrent();
    const QGLContext*	overlayContext() const;

    static QImage	convertToGLFormat( const QImage& img );

    void		setMouseTracking( bool enable );
    virtual void 	reparent( QWidget* parent, WFlags f, const QPoint& p,
                  bool showIt = FALSE );

    const QGLColormap & colormap() const;
    void                setColormap( const QGLColormap & map );

public slots:
    virtual void	updateGL();
    virtual void	updateOverlayGL();

protected:
    virtual void	initializeGL();
    virtual void	resizeGL( int w, int h );
    virtual void	paintGL();

    virtual void	initializeOverlayGL();
    virtual void	resizeOverlayGL( int w, int h );
    virtual void	paintOverlayGL();

    void		setAutoBufferSwap( bool on );
    bool		autoBufferSwap() const;

    void		paintEvent( QPaintEvent* );
    void		resizeEvent( QResizeEvent* );

    virtual void	glInit();
    virtual void	glDraw();

private:
    void                cleanupColormaps();
    void		init( const QGLFormat& fmt,
                  const QGLWidget* shareWidget );
    bool		renderCxPm( QPixmap* pm );
    QGLContext*		glcx;
    bool		autoSwap;

    QGLColormap         cmap;

#if  defined(Q_WS_WIN)
    QGLContext*		olcx;
#elif defined(Q_WS_X11)
    QGLOverlayWidget*	olw;
    friend class QGLOverlayWidget;
#elif defined(Q_WS_MAC)
    QGLContext*		olcx;
#endif

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QGLWidget( const QGLWidget& );
    QGLWidget&		operator=( const QGLWidget& );
#endif

#ifdef Q_WS_MAC
private:
#ifdef QMAC_OPENGL_DOUBLEBUFFER
    QPaintDevice *gl_pix;
    QGLFormat req_format;
#endif
    friend class QWidget;
    void fixReparented();
    void fixBufferRect();
#endif
};

//
// QGLFormat inline functions
//

inline bool QGLFormat::doubleBuffer() const
{
    return testOption( DoubleBuffer );
}

inline bool QGLFormat::depth() const
{
    return testOption( DepthBuffer );
}

inline bool QGLFormat::rgba() const
{
    return testOption( Rgba );
}

inline bool QGLFormat::alpha() const
{
    return testOption( AlphaChannel );
}

inline bool QGLFormat::accum() const
{
    return testOption( AccumBuffer );
}

inline bool QGLFormat::stencil() const
{
    return testOption( StencilBuffer );
}

inline bool QGLFormat::stereo() const
{
    return testOption( StereoBuffers );
}

inline bool QGLFormat::directRendering() const
{
    return testOption( DirectRendering );
}

inline bool QGLFormat::hasOverlay() const
{
    return testOption( HasOverlay );
}

//
// QGLContext inline functions
//

inline bool QGLContext::isValid() const
{
    return d->valid;
}

inline bool QGLContext::isSharing() const
{
    return d->sharing;
}

inline QGLFormat QGLContext::format() const
{
    return glFormat;
}

inline QGLFormat QGLContext::requestedFormat() const
{
    return reqFormat;
}

inline QPaintDevice* QGLContext::device() const
{
    return d->paintDevice;
}

inline bool QGLContext::deviceIsPixmap() const
{
    return d->paintDevice->devType() == QInternal::Pixmap;
}

inline bool QGLContext::windowCreated() const
{
    return d->crWin;
}

inline void QGLContext::setWindowCreated( bool on )
{
    d->crWin = on;
}

inline bool QGLContext::initialized() const
{
    return d->initDone;
}

inline void QGLContext::setInitialized( bool on )
{
    d->initDone = on;
}

inline const QGLContext* QGLContext::currentContext()
{
    return currentCtx;
}

//
// QGLWidget inline functions
//

inline QGLFormat QGLWidget::format() const
{
    return glcx->format();
}

inline const QGLContext *QGLWidget::context() const
{
    return glcx;
}

inline bool QGLWidget::doubleBuffer() const
{
    return glcx->format().doubleBuffer();
}

inline void QGLWidget::setAutoBufferSwap( bool on )
{
    autoSwap = on;
}

inline bool QGLWidget::autoBufferSwap() const
{
    return autoSwap;
}

#ifdef Q_WS_MAC
inline void QGLWidget::fixBufferRect()
{
    glcx->fixBufferRect();
}
#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGL Member List

Complete Member List for QGL

This is the complete list of member functions for QGL, including inherited members.


QGLayoutIterator Class

QGLayoutIterator Class Reference

The QGLayoutIterator class is an abstract base class of internal layout iterators. More...

#include <qlayout.h>

List of all member functions.

Public Members

  • virtual ~QGLayoutIterator ()
  • virtual QLayoutItem * next () = 0
  • virtual QLayoutItem * current () = 0
  • virtual QLayoutItem * takeCurrent () = 0

Detailed Description

The QGLayoutIterator class is an abstract base class of internal layout iterators.

(This class is not OpenGL related, it just happens to start with the letters QGL...)

Subclass this class to create a custom layout. The functions that must be implemented are next(), current(), and takeCurrent().

The QGLayoutIterator implements the functionality of QLayoutIterator. Each subclass of QLayout needs a QGLayoutIterator subclass.

See also Widget Appearance and Style and Layout Management.

Member Function Documentation

QGLayoutIterator::~QGLayoutIterator () [virtual]

Destroys the iterator

QLayoutItem * QGLayoutIterator::current () [pure virtual]

Implemented in subclasses to return the current item, or 0 if there is no current item.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

QLayoutItem * QGLayoutIterator::next () [pure virtual]

Implemented in subclasses to move the iterator to the next item and return that item, or 0 if there is no next item.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

QLayoutItem * QGLayoutIterator::takeCurrent () [pure virtual]

Implemented in subclasses. The function must remove the current item from the layout without deleting it, move the iterator to the next item and return the removed item, or 0 if no item was removed.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

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


QGLayoutIterator Member List

Complete Member List for QGLayoutIterator

This is the complete list of member functions for QGLayoutIterator, including inherited members.

  • ~QGLayoutIterator()
  • current()
  • next()
  • takeCurrent()


QGLColormap Class

QGLColormap Class Reference

The QGLColormap class is used for installing custom colormaps into QGLWidgets. More...

#include <qglcolormap.h>

List of all member functions.

Public Members

  • QGLColormap ()
  • QGLColormap ( const QGLColormap & map )
  • ~QGLColormap ()
  • QGLColormap & operator= ( const QGLColormap & map )
  • bool isEmpty () const
  • int size () const
  • void detach ()
  • void setEntries ( int count, const QRgb * colors, int base = 0 )
  • void setEntry ( int idx, QRgb color )
  • void setEntry ( int idx, const QColor & color )
  • QRgb entryRgb ( int idx ) const
  • QColor entryColor ( int idx ) const
  • int find ( QRgb color ) const
  • int findNearest ( QRgb color ) const

Detailed Description

The QGLColormap class is used for installing custom colormaps into QGLWidgets.

QGLColormap provides a platform independent way of specifying and installing indexed colormaps into QGLWidgets. QGLColormap is especially useful when using the OpenGL color-index mode.

Under X11 you will have to use an X server that supports either a PseudoColor or DirectColor visual class. If your X server currently only provides a GrayScale, TrueColor, StaticColor or StaticGray visual, you will not be able to allocate colorcells for writing. If this is the case, try setting your X server in 8 bit mode. It should then provide you with at least a PseudoColor visual. Note that you may experience colormap flashing if your X server is running in 8 bit mode.

Under Windows the size of the colormap is always set to 256 colors. Note that under Windows you are allowed to install colormaps into child widgets.

This class uses explicit sharing (see Shared Classes).

Example of use:

  #include <qapplication.h>
  #include <qglcolormap.h>

  int main()
  {
      QApplication a( argc, argv );

      MySuperGLWidget widget( 0 ); // A QGLWidget in color-index mode
      QGLColormap colormap;

      // This will fill the colormap with colors ranging from
      // black to white.
      for ( int i = 0; i < colormap.size(); i++ )
          colormap.setEntry( i, qRgb( i, i, i ) );

      widget.setColormap( colormap );
      widget.show();
      return a.exec();
  }

See also QGLWidget::setColormap(), QGLWidget::colormap(), Graphics Classes and Image Processing Classes.

Member Function Documentation

QGLColormap::QGLColormap ()

Construct a QGLColormap.

QGLColormap::QGLColormap ( const QGLColormap & map )

Construct a shallow copy of map.

QGLColormap::~QGLColormap ()

Dereferences the QGLColormap and deletes it if this was the last reference to it.

void QGLColormap::detach ()

Detaches this QGLColormap from the shared block.

QColor QGLColormap::entryColor ( int idx ) const

Returns the QRgb value in the colorcell with index idx.

QRgb QGLColormap::entryRgb ( int idx ) const

Returns the QRgb value in the colorcell with index idx.

int QGLColormap::find ( QRgb color ) const

Returns the index of the color color. If color is not in the map, -1 is returned.

int QGLColormap::findNearest ( QRgb color ) const

Returns the index of the color that is the closest match to color color.

bool QGLColormap::isEmpty () const

Returns TRUE if the colormap is empty; otherwise returns FALSE. A colormap with no color values set is considered to be empty.

QGLColormap & QGLColormap::operator= ( const QGLColormap & map )

Assign a shallow copy of map to this QGLColormap.

void QGLColormap::setEntries ( int count, const QRgb * colors, int base = 0 )

Set an array of cells in this colormap. count is the number of colors that should be set, colors is the array of colors, and base is the starting index.

void QGLColormap::setEntry ( int idx, QRgb color )

Set cell idx in the colormap to color color.

void QGLColormap::setEntry ( int idx, const QColor & color )

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

Set cell with index idx in the colormap to color color.

int QGLColormap::size () const

Returns the number of colorcells in the colormap.

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


qglcolormap.h Include File

qglcolormap.h

This is the verbatim text of the qglcolormap.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QGLColormap class
**
** Created : 20010326
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the opengl module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGLCOLORMAP_H
#define QGLCOLORMAP_H

#ifndef QT_H
#include "qcolor.h"
#include "qmemarray.h"
#include "qshared.h"
#endif // QT_H

#if !defined( QT_MODULE_OPENGL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_OPENGL
#else
#define QM_EXPORT_OPENGL Q_EXPORT
#endif

class QWidget;
class QM_EXPORT_OPENGL QGLColormap
{
public:
    QGLColormap();
    QGLColormap( const QGLColormap & );
    ~QGLColormap();

    QGLColormap &operator=( const QGLColormap & );

    bool   isEmpty() const;
    int    size() const;
    void   detach();

    void   setEntries( int count, const QRgb * colors, int base = 0 );
    void   setEntry( int idx, QRgb color );
    void   setEntry( int idx, const QColor & color );
    QRgb   entryRgb( int idx ) const;
    QColor entryColor( int idx ) const;
    int    find( QRgb color ) const;
    int    findNearest( QRgb color ) const;

private:
    class Private : public QShared
    {
    public:
    Private() {
        cells.resize( 256 ); // ### hardcoded to 256 entries for now
        cmapHandle = 0;
    }

    ~Private() {
    }

    QMemArray<QRgb> cells;
    Qt::HANDLE      cmapHandle;
    };

    Private * d;

    friend class QGLWidget;
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGLColormap Member List

Complete Member List for QGLColormap

This is the complete list of member functions for QGLColormap, including inherited members.

  • QGLColormap()
  • ~QGLColormap()
  • detach()
  • entryColor()
  • entryRgb()
  • find()
  • findNearest()
  • isEmpty()
  • operator=()
  • setEntries()
  • setEntry()
  • size()


QGLContext Class

QGLContext Class Reference
[OpenGL module]

The QGLContext class encapsulates an OpenGL rendering context. More...

#include <qgl.h>

Inherits QGL.

List of all member functions.

Public Members

  • QGLContext ( const QGLFormat & format, QPaintDevice * device )
  • virtual ~QGLContext ()
  • virtual bool create ( const QGLContext * shareContext = 0 )
  • bool isValid () const
  • bool isSharing () const
  • virtual void reset ()
  • QGLFormat format () const
  • QGLFormat requestedFormat () const
  • virtual void setFormat ( const QGLFormat & format )
  • virtual void makeCurrent ()
  • virtual void swapBuffers () const
  • QPaintDevice * device () const
  • QColor overlayTransparentColor () const

Static Public Members

  • const QGLContext * currentContext ()

Protected Members

  • virtual bool chooseContext ( const QGLContext * shareContext = 0 )
  • virtual void doneCurrent ()
  • virtual int choosePixelFormat ( void * dummyPfd, HDC pdc )
  • virtual void * chooseMacVisual ( GDHandle )
  • bool deviceIsPixmap () const
  • bool windowCreated () const
  • void setWindowCreated ( bool on )
  • bool initialized () const
  • void setInitialized ( bool on )

Detailed Description

The QGLContext class encapsulates an OpenGL rendering context.

An OpenGL* rendering context is a complete set of OpenGL state variables.

The context's format is set in the constructor or later with setFormat(). The format options that are actually set are returned by format(); the options you asked for are returned by requestedFormat(). Note that after a QGLContext object have been constructed, the actual OpenGL context have to be created by explicitly calling the create() function. The makeCurrent() function makes this context the current rendering context. You can make no context current using doneCurrent(). The reset() function will reset the context and make it invalid.

You can examine properties of the context with, e.g. isValid(), isSharing(), initialized(), windowCreated() and overlayTransparentColor().

If you're using double buffering you can swap the screen contents with the off-screen buffer using swapBuffers().

Please note that QGLContext is not thread safe.

* OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QGLContext::QGLContext ( const QGLFormat & format, QPaintDevice * device )

Constructs an OpenGL context for the paint device device, which can be a widget or a pixmap. The format specifies several display options for the context.

If the underlying OpenGL/Window system cannot satisfy all the features requested in format, the nearest subset of features will be used. After creation, the format() method will return the actual format obtained.

Note that after a QGLContext object have been constructed, create() have to be called explicitly to create the actual OpenGL context. The context will be invalid if it was not possible to obtain a GL context at all.

See also format() and isValid().

QGLContext::~QGLContext () [virtual]

Destroys the OpenGL context and frees its resources.

bool QGLContext::chooseContext ( const QGLContext * shareContext = 0 ) [virtual protected]

This semi-internal function is called by create(). It creates a system-dependent OpenGL handle that matches the format() of shareContext as closely as possible.

On Windows, it calls the virtual function choosePixelFormat(), which finds a matching pixel format identifier. On X11, it calls the virtual function chooseVisual() which finds an appropriate X visual. On other platforms it may work differently.

int QGLContext::choosePixelFormat ( void * dummyPfd, HDC pdc ) [virtual protected]

Win32 only This virtual function chooses a pixel format that matches the OpenGL format. Reimplement this function in a subclass if you need a custom context.

Warning: The dummyPfd pointer and pdc are used as a PIXELFORMATDESCRIPTOR*. We use void to avoid using Windows-specific types in our header files.

See also chooseContext().

bool QGLContext::create ( const QGLContext * shareContext = 0 ) [virtual]

Creates the GL context. Returns TRUE if it was successful in creating a GL rendering context on the paint device specified in the constructor; otherwise returns FALSE (i.e. the context is invalid).

After successful creation, format() returns the set of features of the created GL rendering context.

If shareContext points to a valid QGLContext, this method will try to establish OpenGL display list sharing between this context and the shareContext. Note that this may fail if the two contexts have different formats. Use isSharing() to see if sharing succeeded.

Implementation note: initialization of C++ class members usually takes place in the class constructor. QGLContext is an exception because it must be simple to customize. The virtual functions chooseContext() (and chooseVisual() for X11) can be reimplemented in a subclass to select a particular context. The problem is that virtual functions are not properly called during construction (even though this is correct C++) because C++ constructs class hierarchies from the bottom up. For this reason we need a create() function.

See also chooseContext(), format() and isValid().

const QGLContext * QGLContext::currentContext () [static]

Returns the current context, i.e. the context to which any OpenGL commands will currently be directed. Returns 0 if no context is current.

See also makeCurrent().

QPaintDevice * QGLContext::device () const

Returns the paint device set for this context.

See also QGLContext::QGLContext().

bool QGLContext::deviceIsPixmap () const [protected]

Returns TRUE if the paint device of this context is a pixmap; otherwise returns FALSE.

void QGLContext::doneCurrent () [virtual protected]

Makes no GL context the current context. Normally, you do not need to call this function; QGLContext calls it as necessary.

QGLFormat QGLContext::format () const

Returns the frame buffer format that was obtained (this may be a subset of what was requested).

See also requestedFormat().

bool QGLContext::initialized () const [protected]

Returns TRUE if this context has been initialized, i.e. if QGLWidget::initializeGL() has been performed on it; otherwise returns FALSE.

See also setInitialized().

bool QGLContext::isSharing () const

Returns TRUE if display list sharing with another context was requested in the create() call and the GL system was able to fulfill this request; otherwise returns FALSE. Note that display list sharing might not be supported between contexts with different formats.

bool QGLContext::isValid () const

Returns TRUE if a GL rendering context has been successfully created; otherwise returns FALSE.

void QGLContext::makeCurrent () [virtual]

Makes this context the current OpenGL rendering context. All GL functions you call operate on this context until another context is made current.

Note that under special circumstances the underlying call may fail, in which case this will not be reported back to the caller. However, a message is printed to stderr stating this.

QColor QGLContext::overlayTransparentColor () const

If this context is a valid context in an overlay plane, returns the plane's transparent color. Otherwise returns an invalid color.

The returned color's pixel value is the index of the transparent color in the colormap of the overlay plane. (Naturally, the color's RGB values are meaningless.)

The returned QColor object will generally work as expected only when passed as the argument to QGLWidget::qglColor() or QGLWidget::qglClearColor(). Under certain circumstances it can also be used to draw transparent graphics with a QPainter. See the examples/opengl/overlay_x11 example for details.

QGLFormat QGLContext::requestedFormat () const

Returns the frame buffer format that was originally requested in the constructor or setFormat().

See also format().

void QGLContext::reset () [virtual]

Resets the context and makes it invalid.

See also create() and isValid().

void QGLContext::setFormat ( const QGLFormat & format ) [virtual]

Sets a format for this context. The context is reset.

Call create() to create a new GL context that tries to match the new format.

    QGLContext *cx;
    //  ...
    QGLFormat f;
    f.setStereo( TRUE );
    cx->setFormat( f );
    if ( !cx->create() )
        exit(); // no OpenGL support, or cannot render on the specified paintdevice
    if ( !cx->format().stereo() )
        exit(); // could not create stereo context

See also format(), reset() and create().

void QGLContext::setInitialized ( bool on ) [protected]

If on is TRUE the context has been initialized, i.e. QGLContext::setInitialized() has been called on it. If on is FALSE the context has not been initialized.

See also initialized().

void QGLContext::setWindowCreated ( bool on ) [protected]

If on is TRUE the context has had a window created for it. If on is FALSE no window has been created for the context.

See also windowCreated().

void QGLContext::swapBuffers () const [virtual]

Swaps the screen contents with an off-screen buffer. Works only if the context is in double buffer mode.

See also QGLFormat::setDoubleBuffer().

bool QGLContext::windowCreated () const [protected]

Returns TRUE if a window has been created for this context; otherwise returns FALSE.

See also setWindowCreated().

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


QGLContext Member List

Complete Member List for QGLContext

This is the complete list of member functions for QGLContext, including inherited members.

  • QGLContext()
  • ~QGLContext()
  • chooseContext()
  • choosePixelFormat()
  • create()
  • currentContext()
  • device()
  • deviceIsPixmap()
  • doneCurrent()
  • format()
  • initialized()
  • isSharing()
  • isValid()
  • makeCurrent()
  • overlayTransparentColor()
  • requestedFormat()
  • reset()
  • setFormat()
  • setInitialized()
  • setWindowCreated()
  • swapBuffers()
  • windowCreated()


QGLFormat Class

QGLFormat Class Reference
[OpenGL module]

The QGLFormat class specifies the display format of an OpenGL rendering context. More...

#include <qgl.h>

Inherits QGL.

List of all member functions.

Public Members

  • QGLFormat ()
  • QGLFormat ( int options, int plane = 0 )
  • bool doubleBuffer () const
  • void setDoubleBuffer ( bool enable )
  • bool depth () const
  • void setDepth ( bool enable )
  • bool rgba () const
  • void setRgba ( bool enable )
  • bool alpha () const
  • void setAlpha ( bool enable )
  • bool accum () const
  • void setAccum ( bool enable )
  • bool stencil () const
  • void setStencil ( bool enable )
  • bool stereo () const
  • void setStereo ( bool enable )
  • bool directRendering () const
  • void setDirectRendering ( bool enable )
  • bool hasOverlay () const
  • void setOverlay ( bool enable )
  • int plane () const
  • void setPlane ( int plane )
  • void setOption ( FormatOption opt )
  • bool testOption ( FormatOption opt ) const

Static Public Members

  • QGLFormat defaultFormat ()
  • void setDefaultFormat ( const QGLFormat & f )
  • QGLFormat defaultOverlayFormat ()
  • void setDefaultOverlayFormat ( const QGLFormat & f )
  • bool hasOpenGL ()
  • bool hasOpenGLOverlays ()

Detailed Description

The QGLFormat class specifies the display format of an OpenGL rendering context.

A display format has several characteristics:

  • Double or single buffering.
  • Depth buffer.
  • RGBA or color index mode.
  • Alpha channel.
  • Accumulation buffer.
  • Stencil buffer.
  • Stereo buffers.
  • Direct rendering.
  • Presence of an overlay.
  • The plane of an overlay format.

You create and tell a QGLFormat object what rendering options you want from an OpenGL* rendering context.

OpenGL drivers or accelerated hardware may or may not support advanced features such as alpha channel or stereographic viewing. If you request some features that the driver/hardware does not provide when you create a QGLWidget, you will get a rendering context with the nearest subset of features.

There are different ways to define the display characteristics of a rendering context. One is to create a QGLFormat and make it default for the entire application:

    QGLFormat f;
    f.setAlpha( TRUE );
    f.setStereo( TRUE );
    QGLFormat::setDefaultFormat( f );

Or you can specify the desired format when creating an object of your QGLWidget subclass:

    QGLFormat f;
    f.setDoubleBuffer( FALSE );                 // single buffer
    f.setDirectRendering( FALSE );              // software rendering
    MyGLWidget* myWidget = new MyGLWidget( f, ... );

After the widget has been created, you can find out which of the requested features the system was able to provide:

    QGLFormat f;
    f.setOverlay( TRUE );
    f.setStereo( TRUE );
    MyGLWidget* myWidget = new MyGLWidget( f, ... );
    if ( !w->format().stereo() ) {
        // ok, goggles off
        if ( !w->format().hasOverlay() ) {
            qFatal( "Cool hardware required" );
        }
    }

* OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.

See also QGLContext, QGLWidget, Graphics Classes and Image Processing Classes.

Member Function Documentation

QGLFormat::QGLFormat ()

Constructs a QGLFormat object with the factory default settings:
  • Double buffer: Enabled.
  • Depth buffer: Enabled.
  • RGBA: Enabled (i.e., color index disabled).
  • Alpha channel: Disabled.
  • Accumulator buffer: Disabled.
  • Stencil buffer: Disabled.
  • Stereo: Disabled.
  • Direct rendering: Enabled.
  • Overlay: Disabled.
  • Plane: 0 (i.e., normal plane).

QGLFormat::QGLFormat ( int options, int plane = 0 )

Creates a QGLFormat object that is a copy of the current application default format.

If options is not 0, this copy is modified by these format options. The options parameter should be FormatOption values OR'ed together.

This constructor makes it easy to specify a certain desired format in classes derived from QGLWidget, for example:

    // The rendering in MyGLWidget depends on using
    // stencil buffer and alpha channel
    MyGLWidget::MyGLWidget( QWidget* parent, const char* name )
        : QGLWidget( QGLFormat( StencilBuffer | AlphaChannel ), parent, name )
    {
      if ( !format().stencil() )
        qWarning( "Could not get stencil buffer; results will be suboptimal" );
      if ( !format().alphaChannel() )
        qWarning( "Could not get alpha channel; results will be suboptimal" );
      ...
   }

Note that there are FormatOption values to turn format settings both on and off, e.g. DepthBuffer and NoDepthBuffer, DirectRendering and IndirectRendering, etc.

The plane parameter defaults to 0 and is the plane which this format should be associated with. Not all OpenGL implmentations supports overlay/underlay rendering planes.

See also defaultFormat() and setOption().

bool QGLFormat::accum () const

Returns TRUE if the accumulation buffer is enabled; otherwise returns FALSE. The accumulation buffer is disabled by default.

See also setAccum().

bool QGLFormat::alpha () const

Returns TRUE if the alpha channel of the framebuffer is enabled; otherwise returns FALSE. The alpha channel is disabled by default.

See also setAlpha().

QGLFormat QGLFormat::defaultFormat () [static]

Returns the default QGLFormat for the application. All QGLWidgets that are created use this format unless another format is specified, e.g. when they are constructed.

If no special default format has been set using setDefaultFormat(), the default format is the same as that created with QGLFormat().

See also setDefaultFormat().

QGLFormat QGLFormat::defaultOverlayFormat () [static]

Returns the default QGLFormat for overlay contexts.

The factory default overlay format is:

  • Double buffer: Disabled.
  • Depth buffer: Disabled.
  • RGBA: Disabled (i.e., color index enabled).
  • Alpha channel: Disabled.
  • Accumulator buffer: Disabled.
  • Stencil buffer: Disabled.
  • Stereo: Disabled.
  • Direct rendering: Enabled.
  • Overlay: Disabled.
  • Plane: 1 (i.e., first overlay plane).

See also setDefaultFormat().

bool QGLFormat::depth () const

Returns TRUE if the depth buffer is enabled; otherwise returns FALSE. The depth buffer is enabled by default.

See also setDepth().

bool QGLFormat::directRendering () const

Returns TRUE if direct rendering is enabled; otherwise returns FALSE.

Direct rendering is enabled by default.

See also setDirectRendering().

bool QGLFormat::doubleBuffer () const

Returns TRUE if double buffering is enabled; otherwise returns FALSE. Double buffering is enabled by default.

See also setDoubleBuffer().

bool QGLFormat::hasOpenGL () [static]

Returns TRUE if the window system has any OpenGL support; otherwise returns FALSE.

Note: this function must not be called until the QApplication object has been created.

bool QGLFormat::hasOpenGLOverlays () [static]

Returns TRUE if the window system supports OpenGL overlays; otherwise returns FALSE.

Note: this function must not be called until the QApplication object has been created.

bool QGLFormat::hasOverlay () const

Returns TRUE if overlay plane is enabled; otherwise returns FALSE.

Overlay is disabled by default.

See also setOverlay().

int QGLFormat::plane () const

Returns the plane of this format. The default for normal formats is 0, which means the normal plane. The default for overlay formats is 1, which is the first overlay plane.

See also setPlane().

bool QGLFormat::rgba () const

Returns TRUE if RGBA color mode is set. Returns FALSE if color index mode is set. The default color mode is RGBA.

See also setRgba().

void QGLFormat::setAccum ( bool enable )

If enable is TRUE enables the accumulation buffer; otherwise disables the accumulation buffer.

The accumulation buffer is disabled by default.

The accumulation buffer is used for create blur effects and multiple exposures.

See also accum().

void QGLFormat::setAlpha ( bool enable )

If enable is TRUE enables the alpha channel; otherwise disables the alpha channel.

The alpha buffer is disabled by default.

The alpha channel is typically used for implementing transparency or translucency. The A in RGBA specifies the transparency of a pixel.

See also alpha().

void QGLFormat::setDefaultFormat ( const QGLFormat & f ) [static]

Sets a new default QGLFormat for the application to f. For example, to set single buffering as the default instead of double buffering, your main() can contain code like this:
    QApplication a(argc, argv);
    QGLFormat f;
    f.setDoubleBuffer( FALSE );
    QGLFormat::setDefaultFormat( f );

See also defaultFormat().

void QGLFormat::setDefaultOverlayFormat ( const QGLFormat & f ) [static]

Sets a new default QGLFormat for overlay contexts to f. This format is used whenever a QGLWidget is created with a format that hasOverlay() enabled.

For example, to get a double buffered overlay context (if available), use code like this:

    QGLFormat f = QGLFormat::defaultOverlayFormat();
    f.setDoubleBuffer( TRUE );
    QGLFormat::setDefaultOverlayFormat( f );

As usual, you can find out after widget creation whether the underlying OpenGL system was able to provide the requested specification:

    // ...continued from above
    MyGLWidget* myWidget = new MyGLWidget( QGLFormat( QGL::HasOverlay ), ... );
    if ( myWidget->format().hasOverlay() ) {
      // Yes, we got an overlay, let's check _its_ format:
      QGLContext* olContext = myWidget->overlayContext();
      if ( olContext->format().doubleBuffer() )
         ; // yes, we got a double buffered overlay
      else
         ; // no, only single buffered overlays are available
    }

See also defaultOverlayFormat().

void QGLFormat::setDepth ( bool enable )

If enable is true enables the depth buffer; otherwise disables the depth buffer.

The depth buffer is enabled by default.

The purpose of a depth buffer (or z-buffering) is to remove hidden surfaces. Pixels are assigned z values based on the distance to the viewer. A pixel with a high z value is closer to the viewer than a pixel with a low z value. This information is used to decide whether to draw a pixel or not.

See also depth().

void QGLFormat::setDirectRendering ( bool enable )

If enable is TRUE enables direct rendering; otherwise disables direct rendering.

Direct rendering is enabled by default.

Enabling this option will make OpenGL bypass the underlying window system and render directly from hardware to the screen, if this is supported by the system.

See also directRendering().

void QGLFormat::setDoubleBuffer ( bool enable )

If enable is true sets double buffering; otherwise sets single buffering.

Double buffering is enabled by default.

Double buffering is a technique where graphics are rendered on an off-screen buffer and not directly to the screen. When the drawing has been completed, the program calls a swapBuffers function to exchange the screen contents with the buffer. The result is flicker-free drawing and often better performance.

See also doubleBuffer(), QGLContext::swapBuffers() and QGLWidget::swapBuffers().

void QGLFormat::setOption ( FormatOption opt )

Sets the format option to opt.

See also testOption().

void QGLFormat::setOverlay ( bool enable )

If enable is TRUE enables an overlay plane; otherwise disables the overlay plane.

Enabling the overlay plane will cause QGLWidget to create an additional context in an overlay plane. See the QGLWidget documentation for further information.

See also hasOverlay().

void QGLFormat::setPlane ( int plane )

Sets the requested plane to plane. 0 is the normal plane, 1 is the first overlay plane, 2 is the second overlay plane, etc.; -1, -2, etc. are underlay planes.

Note that in contrast to other format specifications, the plane specifications will be matched exactly. This means that if you specify a plane that the underlying OpenGL system cannot provide, an invalid QGLWidget will be created.

See also plane().

void QGLFormat::setRgba ( bool enable )

If enable is TRUE sets RGBA mode. If enable is FALSE sets color index mode.

The default color mode is RGBA.

RGBA is the preferred mode for most OpenGL applications. In RGBA color mode you specify colors as red + green + blue + alpha quadruplets.

In color index mode you specify an index into a color lookup table.

See also rgba().

void QGLFormat::setStencil ( bool enable )

If enable is TRUE enables the stencil buffer; otherwise disables the stencil buffer.

The stencil buffer is disabled by default.

The stencil buffer masks certain parts of the drawing area so that masked parts are not drawn on.

See also stencil().

void QGLFormat::setStereo ( bool enable )

If enable is TRUE enables stereo buffering; otherwise disables stereo buffering.

Stereo buffering is disabled by default.

Stereo buffering provides extra color buffers to generate left-eye and right-eye images.

See also stereo().

bool QGLFormat::stencil () const

Returns TRUE if the stencil buffer is enabled; otherwise returns FALSE. The stencil buffer is disabled by default.

See also setStencil().

bool QGLFormat::stereo () const

Returns TRUE if stereo buffering is enabled; otherwise returns FALSE. Stereo buffering is disabled by default.

See also setStereo().

bool QGLFormat::testOption ( FormatOption opt ) const

Returns TRUE if format option opt is set; otherwise returns FALSE.

See also setOption().

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


QGLFormat Member List

Complete Member List for QGLFormat

This is the complete list of member functions for QGLFormat, including inherited members.

  • QGLFormat()
  • accum()
  • alpha()
  • defaultFormat()
  • defaultOverlayFormat()
  • depth()
  • directRendering()
  • doubleBuffer()
  • hasOpenGL()
  • hasOpenGLOverlays()
  • hasOverlay()
  • plane()
  • rgba()
  • setAccum()
  • setAlpha()
  • setDefaultFormat()
  • setDefaultOverlayFormat()
  • setDepth()
  • setDirectRendering()
  • setDoubleBuffer()
  • setOption()
  • setOverlay()
  • setPlane()
  • setRgba()
  • setStencil()
  • setStereo()
  • stencil()
  • stereo()
  • testOption()


qglobal.h Include File

qglobal.h

This is the verbatim text of the qglobal.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Global type declarations and definitions
**
** Created : 920529
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGLOBAL_H
#define QGLOBAL_H

#define QT_VERSION_STR   "3.0.5"
/*
   QT_VERSION is ( MAJOR<<16+MINOR<<8+_PATCH)
 */
#define QT_VERSION 0x030005

/*
   The operating system, must be one of: (Q_OS_x)

     MACX	  - Mac OS X
     MAC9	  - Mac OS 9
     MSDOS  - MS-DOS and Windows
     OS2	  - OS/2
     OS2EMX - XFree86 on OS/2 (not PM)
     WIN32  - Win32 (Windows 95/98/ME and Windows NT/2000/XP)
     SUN	  - SunOS
     SOLARIS	 - Sun Solaris
     HPUX	  - HP-UX
     ULTRIX - DEC Ultrix
     LINUX  - Linux
     FREEBSD	 - FreeBSD
     NETBSD - NetBSD
     OPENBSD    - OpenBSD
     BSDI	  - BSD/OS
     IRIX	  - SGI Irix
     OSF	  - Compaq Tru64
     UNIXWARE	 - SCO UnixWare 2
     SCO	  - SCO OpenServer, UnixWare 7, Open UNIX
     AIX	  - AIX
     HURD	  - GNU Hurd
     DGUX	  - DG/UX
     DYNIX  - DYNIX/ptx
     RELIANT	 - Reliant UNIX
     QNX6   - QNX RTP 6.1
     QNX4   - QNX 4.24
     LYNX	  - LynxOS
     BSD4	  - Any BSD 4.4 system
     UNIX	  - Any UNIX BSD/SYSV system
*/

#if defined(__APPLE__) && defined(__GNUC__)
#  define Q_OS_MACX
#elif defined(__MACOSX__)
#  define Q_OS_MACX
#elif defined(macintosh)
#  define Q_OS_MAC9
#elif defined(MSDOS) || defined(_MSDOS) || defined(__MSDOS__)
#  define Q_OS_MSDOS
#elif defined(OS2) || defined(_OS2) || defined(__OS2__)
#  if defined(__EMX__)
#    define Q_OS_OS2EMX
#  else
#    define Q_OS_OS2
#  endif
#elif !defined(SAG_COM) && (defined(WIN64) || defined(_WIN64) || defined(__WIN64__))
#  define Q_OS_WIN32
#  define Q_OS_WIN64
#elif !defined(SAG_COM) && (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__))
#  define Q_OS_WIN32
#elif defined(__MWERKS__) && defined(__INTEL__)
#  define Q_OS_WIN32
#elif defined(sun) || defined(__sun) || defined(__sun__)
#  if defined(__SVR4)
#    define Q_OS_SOLARIS
#  else
#    define Q_OS_SUN
#    define Q_OS_BSD4
#  endif
#elif defined(hpux) || defined(__hpux) || defined(__hpux__)
#  define Q_OS_HPUX
#elif defined(ultrix) || defined(__ultrix) || defined(__ultrix__)
#  define Q_OS_ULTRIX
#elif defined(sinix)
#  define Q_OS_RELIANT
#elif defined(linux) || defined(__linux) || defined(__linux__)
#  define Q_OS_LINUX
#elif defined(__FreeBSD__)
#  define Q_OS_FREEBSD
#  define Q_OS_BSD4
#elif defined(__NetBSD__)
#  define Q_OS_NETBSD
#  define Q_OS_BSD4
#elif defined(__OpenBSD__)
#  define Q_OS_OPENBSD
#  define Q_OS_BSD4
#elif defined(bsdi) || defined(__bsdi__)
#  define Q_OS_BSDI
#  define Q_OS_BSD4
#elif defined(sgi) || defined(__sgi)
#  define Q_OS_IRIX
#elif defined(__osf__)
#  define Q_OS_OSF
#elif defined(_AIX)
#  define Q_OS_AIX
#elif defined(__Lynx__)
#  define Q_OS_LYNX
#elif defined(_UNIXWARE)
#  define Q_OS_UNIXWARE
#elif defined(__GNU__)
#  define Q_OS_HURD
#elif defined(DGUX)
#  define Q_OS_DGUX
#elif defined(__QNXNTO__)
#  define Q_OS_QNX6
#elif defined(__QNX__)
#  define Q_OS_QNX4
#elif defined(_SCO_DS) || defined(M_UNIX) || defined(M_XENIX)
#  define Q_OS_SCO
#elif defined(sco) || defined(_UNIXWARE7)
#  define Q_OS_UNIXWARE7
#elif !defined(_SCO_DS) && defined(__USLC__) && defined(__SCO_VERSION__)
#  define Q_OS_UNIXWARE7
#elif defined(_SEQUENT_)
#  define Q_OS_DYNIX
#elif defined(__svr4__)
/*   generic fallback for the rest of svr4 systems, e.g. g++ on UnixWare7.*/
#  define Q_OS_SVR4
#else
#  error "Qt has not been ported to this OS - talk to qt-bugs@trolltech.com"
#endif

#if defined(Q_OS_MAC9) || defined(Q_OS_MACX)
#  define Q_OS_MAC
#endif

#if defined(Q_OS_MAC9) || defined(Q_OS_MSDOS) || defined(Q_OS_OS2) || defined(Q_OS_WIN32) || defined(Q_OS_WIN64)
#  undef Q_OS_UNIX
#elif !defined(Q_OS_UNIX)
#  define Q_OS_UNIX
#endif

/*
   The compiler, must be one of: (Q_CC_x)

     SYM - Symantec C++ for both PC and Macintosh
     MPW - MPW C++
     MWERKS - Metrowerks CodeWarrior
     MSVC - Microsoft Visual C/C++
     BOR - Borland/Turbo C++
     WAT - Watcom C++
     GNU - GNU C++
     COMEAU - Comeau C++
     EDG - Edison Design Group C++
     OC - CenterLine C++
     SUN - Sun C++
     MIPS - MIPSpro C++
     DEC - DEC C++
     HP - HPUX C++
     HPACC - HPUX ANSI C++
     USLC - SCO UnixWare C++
     CDS - Reliant C++
     KAI - KAI C++
     INTEL - Intel C++
     HIGHC - MetaWare High C/C++
     PGI - Portland Group C++

   Should be sorted most to least authoritative.
*/

/* Symantec C++ is now Digital Mars? */
#if defined(__SC__)
#  define Q_CC_SYM

#elif defined(applec)
#  define Q_CC_MPW
#  define Q_NO_BOOL_TYPE

#elif defined(__MWERKS__)
#  define Q_CC_MWERKS
#  define QMAC_PASCAL pascal

#elif defined(_MSC_VER)
#  define Q_CC_MSVC
/* proper support of bool for _MSC_VER >= 1100 */
#  define Q_CANNOT_DELETE_CONSTANT
#  define Q_INLINE_TEMPLATES inline
#elif defined(__BORLANDC__) || defined(__TURBOC__)
#  define Q_CC_BOR
#  if __BORLANDC__ < 0x500
#    define Q_NO_BOOL_TYPE
#  endif

#elif defined(__WATCOMC__)
#  define Q_CC_WAT
#ifdef Q_OS_QNX4
//compiler flags
#define Q_TYPENAME
#define Q_NO_BOOL_TYPE
#define Q_CANNOT_DELETE_CONSTANT
#define mutable

// XXX
#define Q_BROKEN_TEMPLATE_SPECIALIZATION
// No Template classes in QVariant
#define QT_NO_TEMPLATE_VARIANT
// Wcc does not fill in functions needed by valuelists
// maps, and valuestacks implicitly
#define Q_FULL_TEMPLATE_INSTANTIATION
// can we just compare the structures?
#define Q_FULL_TEMPLATE_INSTANTIATION_MEMCMP

//these are not useful to our customers
#define QT_QWS_NO_SHM
#define QT_NO_QWS_MULTIPROCESS
#define QT_NO_SQL
#define QT_NO_QWS_CURSOR
#endif

/* Never tested! */
#elif defined(__HIGHC__)
#  define Q_CC_HIGHC

#elif defined(__GNUC__)
#  define Q_CC_GNU
#  define Q_C_CALLBACKS
#  if __GNUC__ == 2 && __GNUC_MINOR__ <= 7
#    define Q_FULL_TEMPLATE_INSTANTIATION
#  endif
#  if (defined(__arm__) || defined(__ARMEL__)) && !defined(QT_MOC_CPP)
#    define Q_PACKED __attribute__ ((packed))
#  endif

/* IBM compiler versions are a bit messy. There are actually two products:
   the C product, and the C++ product. The C++ compiler is always packaged
   with the latest version of the C compiler. Version numbers do not always
   match. This little table (I'm not sure it's accurate) should be helpful:

       C++ product               C product

        C Set 3.1              C Compiler 3.0
         ...                       ...
    C++ Compiler 3.6.6         C Compiler 4.3
         ...                       ...
    Visual Age C++ 4.0              ...
         ...                       ...
    Visual Age C++ 5.0         C Compiler 5.0

   Now:
   __xlC__    is the version of the C compiler in hexadecimal notation
              - it's only an approximation of the C++ compiler version
   __IBMCPP__ is the version of the C++ compiler in decimal notation
              - but it's not defined on older compilers like C Set 3.1 */
#elif defined(__xlC__)
#  define Q_CC_XLC
#  define Q_FULL_TEMPLATE_INSTANTIATION
#  if __xlC__ < 0x400
#    define Q_NO_BOOL_TYPE
#    define Q_BROKEN_TEMPLATE_SPECIALIZATION
#    define Q_CANNOT_DELETE_CONSTANT
#  endif

/* Compilers with EDG front end are similar. To detect them we test:
   __EDG documented by SGI, observed on MIPSpro 7.3.1.1 and KAI C++ 4.0b
   __EDG__ documented in EDG online docs, observed on Compaq C++ V6.3-002 */
#elif defined(__EDG) || defined(__EDG__) || defined(Q_CC_EDG)
#  if !defined(Q_CC_EDG)
#    define Q_CC_EDG
#  endif
/* Compaq have disabled EDG's _BOOL macro - observed on Compaq C++ V6.3-002. */
#  if defined(__DECCXX)
#    define Q_CC_DEC
/* Compaq use _BOOL_EXISTS instead of _BOOL. */
#    if defined(_BOOL_EXISTS)
/* Well, at least macro _BOOL_EXISTS is documented for Compaq C++ V6.3.
   In any case versions prior to Compaq C++ V6.0-005 do not have bool. */
#    elif __DECCXX_VER < 60060005
#      define Q_NO_BOOL_TYPE
#    endif
/* Apart from Compaq, from the EDG documentation:
   _BOOL
    Defined in C++ mode when bool is a keyword. The name of this predefined
    macro is specified by a configuration flag. _BOOL is the default.
   __BOOL_DEFINED
    Defined in Microsoft C++ mode when bool is a keyword. */
#  else
#    if !defined(_BOOL) && !defined(__BOOL_DEFINED)
#      define Q_NO_BOOL_TYPE
#    endif
#    if defined(__COMO__)
#      define Q_CC_COMEAU
#      define Q_C_CALLBACKS
#    elif defined(__KCC)
#      define Q_CC_KAI
#    elif defined(__INTEL_COMPILER)
#      define Q_CC_INTEL
/* The Portland Group compiler is based on EDG and does define __EDG__ */
#    elif defined(__PGI)
#      define Q_CC_PGI
/* The new UnixWare 7 compiler is based on EDG and does define __EDG__ */
#    elif defined(__USLC__)
#      define Q_CC_EDG
#      define Q_CC_USLC
/* Never tested! */
#    elif defined(CENTERLINE_CLPP) || defined(OBJECTCENTER)
#      define Q_CC_OC
/* The MIPSpro compiler in o32 mode is based on EDG but disables features
   such as template specialization nevertheless */
#    elif defined(sgi) || defined(__sgi)
#      define Q_CC_MIPS
#      if defined(_MIPS_SIM) && (_MIPS_SIM == _ABIO32) /* o32 ABI */
#        define Q_BROKEN_TEMPLATE_SPECIALIZATION
#      elif defined(_COMPILER_VERSION) && (_COMPILER_VERSION < 730) /* 7.2 */
#        define Q_BROKEN_TEMPLATE_SPECIALIZATION
#      endif
#    endif
#  endif

/* the older UnixWare compiler is not based on EDG */
#elif defined(__USLC__)
#  define Q_CC_USLC
#  define Q_NO_BOOL_TYPE

#elif defined(__SUNPRO_CC)
#  define Q_CC_SUN
/* 5.0 compiler or better
    'bool' is enabled by default but can be disabled using -features=nobool
    in which case _BOOL is not defined
        this is the default in 4.2 compatibility mode triggered by -compat=4 */
#  if __SUNPRO_CC >= 0x500
#    if !defined(_BOOL)
#      define Q_NO_BOOL_TYPE
#    endif
#    define Q_C_CALLBACKS
/* 4.2 compiler or older */
#  else
#    define Q_NO_BOOL_TYPE
#  endif

/* CDS++ does not seem to define __EDG__ or __EDG according to Reliant
   documentation but nevertheless uses EDG conventions like _BOOL */
#elif defined(sinix)
#  define Q_CC_EDG
#  define Q_CC_CDS
#  if !defined(_BOOL)
#    define Q_NO_BOOL_TYPE
#  endif

#elif defined(Q_OS_HPUX)
/* __HP_aCC was not defined in first aCC releases */
#  if defined(__HP_aCC) || __cplusplus >= 199707L
#    define Q_CC_HPACC
#  else
#    define Q_CC_HP
#    define Q_NO_BOOL_TYPE
#    define Q_FULL_TEMPLATE_INSTANTIATION
#    define Q_BROKEN_TEMPLATE_SPECIALIZATION
#  endif

#else
#  error "Qt has not been tested with this compiler - talk to qt-bugs@trolltech.com"
#endif

#ifndef Q_PACKED
#  define Q_PACKED
#endif

/*
   The window system, must be one of: (Q_WS_x)

     MACX	  - Mac OS X
     MAC9	  - Mac OS 9
     QWS	  - Qt/Embedded
     WIN32  - Windows
     X11	  - X Window System
     PM	  - unsupported
     WIN16  - unsupported
*/

#if defined(Q_OS_MACX)
#  define Q_WS_MACX
#elif defined(Q_OS_MAC9)
#  define Q_WS_MAC9
#elif defined(Q_OS_MSDOS)
#  define Q_WS_WIN16
#  error "Qt requires Win32 and does not work with Windows 3.x"
#elif defined(_WIN32_X11_)
#  define Q_WS_X11
#elif defined(Q_OS_WIN32)
#  define Q_WS_WIN32
#  if defined(Q_OS_WIN64)
#    define Q_WS_WIN64
#  endif
#elif defined(Q_OS_OS2)
#  define Q_WS_PM
#  error "Qt does not work with OS/2 Presentation Manager or Workplace Shell"
#elif defined(Q_OS_UNIX)
#  ifdef QWS
#    define Q_WS_QWS
#  else
#    define Q_WS_X11
#  endif
#endif
#if defined(Q_OS_MAC) && !defined(QMAC_PASCAL)
#  define QMAC_PASCAL
#endif

#if defined(Q_WS_WIN16) || defined(Q_WS_WIN32)
#  define Q_WS_WIN
#endif

#if defined(Q_WS_MAC9) || defined(Q_WS_MACX)
#  define Q_WS_MAC
#endif

/*
   Some classes do not permit copies to be made of an object.
   These classes contains a private copy constructor and operator=
   to disable copying (the compiler gives an error message).
   Undefine Q_DISABLE_COPY to turn off this checking.
*/

#define Q_DISABLE_COPY

#if defined(__cplusplus)

//
// Useful type definitions for Qt
//

#if defined(Q_NO_BOOL_TYPE)
#if defined(Q_CC_HP)
// bool is an unsupported reserved keyword in later versions
#define bool int
#else
typedef int bool;
#endif
#endif

typedef unsigned char   uchar;
typedef unsigned short  ushort;
typedef unsigned	uint;
typedef unsigned long   ulong;
typedef char		   *pchar;
typedef uchar		   *puchar;
typedef const char     *pcchar;

//
// Constant bool values
//

#ifndef TRUE
const bool FALSE = 0;
const bool TRUE = !0;
#endif
#if defined(__WATCOMC__)
#ifdef Q_OS_QNX4
const bool false = FALSE;
const bool true = TRUE;
#endif
#endif

//
// Workaround for static const members on MSVC++.
//

#if defined(Q_CC_MSVC)
#  define QT_STATIC_CONST static
#  define QT_STATIC_CONST_IMPL
#else
#  define QT_STATIC_CONST static const
#  define QT_STATIC_CONST_IMPL const
#endif

//
// Utility macros and inline functions
//

#define QMAX(a, b)	((b) < (a) ? (a) : (b))
#define QMIN(a, b)	((a) < (b) ? (a) : (b))
#define QABS(a)	((a) >= 0  ? (a) : -(a))

inline int qRound( double d )
{
    return int( d >= 0.0 ? d + 0.5 : d - 0.5 );
}

//
// Size-dependent types (architechture-dependent byte order)
//

#if !defined(QT_CLEAN_NAMESPACE)
// source compatibility with Qt 1.x
typedef signed char	    INT8;		 // 8 bit signed
typedef unsigned char	   UINT8;		// 8 bit unsigned
typedef short		    INT16;	 // 16 bit signed
typedef unsigned short	   UINT16;	// 16 bit unsigned
typedef int		INT32;	  // 32 bit signed
typedef unsigned int	   UINT32;	// 32 bit unsigned
#endif

typedef signed char	    Q_INT8;	 // 8 bit signed
typedef unsigned char	   Q_UINT8;	// 8 bit unsigned
typedef short		    Q_INT16;	 // 16 bit signed
typedef unsigned short	   Q_UINT16;	// 16 bit unsigned
typedef int		Q_INT32;	  // 32 bit signed
typedef unsigned int	   Q_UINT32;	// 32 bit unsigned
#if defined(Q_OS_WIN64)
// LLP64 64-bit model on Windows
typedef __int64	    Q_LONG;	 // word up to 64 bit signed
typedef unsigned __int64	   Q_ULONG;	// word up to 64 bit unsigned
#else
// LP64 64-bit model on Linux
typedef long		    Q_LONG;
typedef unsigned long	   Q_ULONG;
#endif

#if !defined(QT_CLEAN_NAMESPACE)
// mininum size of 64 bits is not guaranteed
#define Q_INT64	    Q_LONG
#define Q_UINT64	    Q_ULONG
#endif

//
// Data stream functions is provided by many classes (defined in qdatastream.h)
//

class QDataStream;

//
// Some platform specific stuff
//

#ifdef Q_WS_WIN
extern bool qt_winunicode;
#endif

//
// feature seubsetting
//
// Note that disabling some features will produce a libqt that is not
// compatible with other libqt builds. Such modifications are only
// supported on Qt/Embedded where reducing the library size is important
// and where the application-suite is often a fixed set.
//
#if !defined(QT_MOC)
#if defined(QCONFIG_LOCAL)
#include <qconfig-local.h>
#elif defined(QCONFIG_MINIMAL)
#include <qconfig-minimal.h>
#elif defined(QCONFIG_SMALL)
#include <qconfig-small.h>
#elif defined(QCONFIG_MEDIUM)
#include <qconfig-medium.h>
#elif defined(QCONFIG_LARGE)
#include <qconfig-large.h>
#else // everything...
#include <qconfig.h>
#endif
#endif

#ifndef QT_BUILD_KEY
#define QT_BUILD_KEY "unspecified"
#endif

// prune to local config
#include "qmodules.h"
#ifndef QT_MODULE_ICONVIEW
# define QT_NO_ICONVIEW
#endif
#ifndef QT_MODULE_WORKSPACE
# define QT_NO_WORKSPACE
#endif
#ifndef QT_MODULE_NETWORK
#define QT_NO_NETWORK
#endif
#ifndef QT_MODULE_CANVAS
# define QT_NO_CANVAS
#endif
#ifndef QT_MODULE_TABLE
#define QT_NO_TABLE
#endif
#ifndef QT_MODULE_XML
# define QT_NO_XML
#endif
#ifndef QT_MODULE_OPENGL
# define QT_NO_OPENGL
#endif
#if !defined(QT_MODULE_SQL)
# define QT_NO_SQL
#endif

#ifdef Q_WS_MAC9
//No need for menu merging
#  ifndef QMAC_QMENUBAR_NO_MERGE
#    define QMAC_QMENUBAR_NO_MERGE
#  endif
//Mac9 does not use quartz
#  ifndef QMAC_NO_QUARTZ
#    define QMAC_NO_QUARTZ
#  endif
#  ifndef QMAC_QMENUBAR_NO_EVENT
#    define QMAC_QMENUBAR_NO_EVENT
#  endif
#endif
#ifdef Q_WS_MACX //for no nobody uses quartz, just putting in first level hooks
#  ifndef QMAC_NO_QUARTZ
#    define QMAC_NO_QUARTZ
#  endif
#  ifndef QMAC_QMENUBAR_NO_EVENT
#    define QMAC_QMENUBAR_NO_EVENT
#  endif
#endif

#ifndef QT_H
#include <qfeatures.h>
#endif // QT_H

//
// Create Qt DLL if QT_DLL is defined (Windows only)
//

#if defined(Q_OS_WIN32) || defined(Q_OS_WIN64)
#  if defined(QT_NODLL)
#    undef QT_MAKEDLL
#    undef QT_DLL
#  elif defined(QT_MAKEDLL) /* create a Qt DLL library */
#    if defined(QT_DLL)
#      undef QT_DLL
#    endif
#    define Q_EXPORT  __declspec(dllexport)
#    define Q_TEMPLATEDLL
#    define Q_TEMPLATE_EXTERN
#    undef  Q_DISABLE_COPY  /* avoid unresolved externals */
#  elif defined(QT_DLL)	   /* use a Qt DLL library */
#    define Q_EXPORT  __declspec(dllimport)
#    define Q_TEMPLATEDLL
#    if defined(Q_CC_MSVC)
#      define Q_TEMPLATE_EXTERN /*extern*/ //### too many warnings, even though disabled
#    else
#      define Q_TEMPLATE_EXTERN
#    endif
#    undef  Q_DISABLE_COPY  /* avoid unresolved externals */
#  endif
#else
#  undef QT_MAKEDLL	    /* ignore these for other platforms */
#  undef QT_DLL
#endif

#ifndef Q_EXPORT
#  define Q_EXPORT
#endif

//
// System information
//

Q_EXPORT const char *qVersion();
Q_EXPORT bool qSysInfo( int *wordSize, bool *bigEndian );
#if defined(Q_WS_WIN)
Q_EXPORT int qWinVersion();
#endif

//
// Avoid some particularly useless warnings from some stupid compilers.
// To get ALL C++ compiler warnings, define QT_CC_WARNINGS or comment out
// the line "#define QT_NO_WARNINGS"
//

#if !defined(QT_CC_WARNINGS)
#  define QT_NO_WARNINGS
#endif
#if defined(QT_NO_WARNINGS)
#  if defined(Q_CC_MSVC)
#    pragma warning(disable: 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data
#    pragma warning(disable: 4275) // non - DLL-interface classkey 'identifier' used as base for DLL-interface classkey 'identifier'
#    pragma warning(disable: 4514) // unreferenced inline/local function has been removed
#    pragma warning(disable: 4800) // 'type' : forcing value to bool 'true' or 'false' (performance warning)
#    pragma warning(disable: 4097) // typedef-name 'identifier1' used as synonym for class-name 'identifier2'
#    pragma warning(disable: 4706) // assignment within conditional expression
#    pragma warning(disable: 4786) // truncating debug info after 255 characters
#    pragma warning(disable: 4660) // template-class specialization 'identifier' is already instantiated
#    pragma warning(disable: 4355) // 'this' : used in base member initializer list
#    pragma warning(disable: 4231) // nonstandard extension used : 'extern' before template explicit instantiation
#  elif defined(Q_CC_BOR)
#    pragma option -w-inl
#    pragma option -w-aus
#    pragma warn -inl
#    pragma warn -pia
#    pragma warn -ccc
#    pragma warn -rch
#    pragma warn -sig
#  elif defined(Q_CC_MWERKS)
#    pragma warn_possunwant off
#  endif
#endif

#ifndef Q_INLINE_TEMPLATES
#  define Q_INLINE_TEMPLATES
#endif

#ifndef Q_TYPENAME
#  define Q_TYPENAME typename
#endif

//
// Use to avoid "unused parameter" warnings
//

#define Q_UNUSED(x) (void)x;

//
// Debugging and error handling
//

#if !defined(QT_NO_CHECK)
#  define QT_CHECK_STATE			 // check state of objects etc.
#  define QT_CHECK_RANGE			 // check range of indexes etc.
#  define QT_CHECK_NULL			 // check null pointers
#  define QT_CHECK_MATH			 // check math functions
#endif

#if !defined(QT_NO_DEBUG) && !defined(QT_DEBUG)
#  define QT_DEBUG			  // display debug messages
#  if !defined(QT_NO_COMPAT)
// source compatibility with Qt 2.x
#    if !defined(NO_DEBUG) && !defined(DEBUG)
#      if !defined(Q_OS_MACX)			// clash with MacOS X headers
#        define DEBUG
#      endif
#    endif
#  endif
#endif

Q_EXPORT void qDebug( const char *, ... )   // print debug message
#if defined(Q_CC_GNU) && !defined(__INSURE__)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

Q_EXPORT void qWarning( const char *, ... ) // print warning message
#if defined(Q_CC_GNU) && !defined(__INSURE__)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

Q_EXPORT void qFatal( const char *, ... )   // print fatal message and exit
#if defined(Q_CC_GNU)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

Q_EXPORT void qSystemWarning( const char *, int code = -1 );

#if !defined(QT_CLEAN_NAMESPACE)
// source compatibility with Qt 1.x

Q_EXPORT void debug( const char *, ... )    // print debug message
#if defined(Q_CC_GNU) && !defined(__INSURE__)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

Q_EXPORT void warning( const char *, ... )  // print warning message
#if defined(Q_CC_GNU) && !defined(__INSURE__)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

Q_EXPORT void fatal( const char *, ... )    // print fatal message and exit
#if defined(Q_CC_GNU) && !defined(__INSURE__)
    __attribute__ ((format (printf, 1, 2)))
#endif
;

#endif // QT_CLEAN_NAMESPACE

#if !defined(Q_ASSERT)
#if defined(QT_CHECK_STATE)
#if defined(QT_FATAL_ASSERT)
#define Q_ASSERT(x)  ((x) ? (void)0 : qFatal("ASSERT: \"%s\" in %s (%d)",#x,__FILE__,__LINE__))
#else
#define Q_ASSERT(x)  ((x) ? (void)0 : qWarning("ASSERT: \"%s\" in %s (%d)",#x,__FILE__,__LINE__))
#endif
#else
#define Q_ASSERT(x)
#endif
#endif

#if !defined(QT_NO_COMPAT)
// source compatibility with Qt 2.x
#ifndef Q_OS_TEMP
#  if !defined(ASSERT)
#    define ASSERT(x) Q_ASSERT(x)
#  endif
#endif // Q_OS_TEMP
#endif // QT_NO_COMPAT

Q_EXPORT bool qt_check_pointer( bool c, const char *, int );

#if defined(QT_CHECK_NULL)
#  define Q_CHECK_PTR(p) (qt_check_pointer((p)==0,__FILE__,__LINE__))
#else
#  define Q_CHECK_PTR(p)
#endif

#if !defined(QT_NO_COMPAT)
// source compatibility with Qt 2.x
#  if !defined(CHECK_PTR)
#    define CHECK_PTR(x) Q_CHECK_PTR(x)
#  endif
#endif // QT_NO_COMPAT

enum QtMsgType { QtDebugMsg, QtWarningMsg, QtFatalMsg };

typedef void (*QtMsgHandler)(QtMsgType, const char *);
Q_EXPORT QtMsgHandler qInstallMsgHandler( QtMsgHandler );

#if !defined(QT_NO_COMPAT)
// source compatibility with Qt 2.x
typedef QtMsgHandler msg_handler;
#endif

Q_EXPORT void qSuppressObsoleteWarnings( bool = TRUE );

Q_EXPORT void qObsolete( const char *obj, const char *oldfunc,
           const char *newfunc );
Q_EXPORT void qObsolete( const char *obj, const char *oldfunc );
Q_EXPORT void qObsolete( const char *message );

#endif // __cplusplus

#endif // QGLOBAL_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGLWidget Class

QGLWidget Class Reference
[OpenGL module]

The QGLWidget class is a widget for rendering OpenGL graphics. More...

#include <qgl.h>

Inherits QWidget and QGL.

List of all member functions.

Public Members

  • QGLWidget ( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 )
  • QGLWidget ( const QGLFormat & format, QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 )
  • ~QGLWidget ()
  • void qglColor ( const QColor & c ) const
  • void qglClearColor ( const QColor & c ) const
  • bool isValid () const
  • bool isSharing () const
  • virtual void makeCurrent ()
  • bool doubleBuffer () const
  • virtual void swapBuffers ()
  • QGLFormat format () const
  • const QGLContext * context () const
  • virtual QPixmap renderPixmap ( int w = 0, int h = 0, bool useContext = FALSE )
  • virtual QImage grabFrameBuffer ( bool withAlpha = FALSE )
  • virtual void makeOverlayCurrent ()
  • const QGLContext * overlayContext () const
  • const QGLColormap & colormap () const
  • void setColormap ( const QGLColormap & cmap )

Public Slots

  • virtual void updateGL ()
  • virtual void updateOverlayGL ()

Static Public Members

  • QImage convertToGLFormat ( const QImage & img )

Protected Members

  • virtual void initializeGL ()
  • virtual void resizeGL ( int width, int height )
  • virtual void paintGL ()
  • virtual void initializeOverlayGL ()
  • virtual void resizeOverlayGL ( int width, int height )
  • virtual void paintOverlayGL ()
  • void setAutoBufferSwap ( bool on )
  • bool autoBufferSwap () const
  • virtual void paintEvent ( QPaintEvent * )
  • virtual void resizeEvent ( QResizeEvent * )
  • virtual void glInit ()
  • virtual void glDraw ()

Detailed Description

The QGLWidget class is a widget for rendering OpenGL graphics.

QGLWidget provides functionality for displaying OpenGL* graphics integrated into a Qt application. It is very simple to use. You inherit from it and use the subclass like any other QWidget, except that instead of drawing the widget's contents using QPainter etc. you use the standard OpenGL rendering commands.

QGLWidget provides three convenient virtual functions that you can reimplement in your subclass to perform the typical OpenGL tasks:

  • paintGL() - Renders the OpenGL scene. Gets called whenever the widget needs to be updated.
  • resizeGL() - Sets up the OpenGL viewport, projection, etc. Gets called whenever the the widget has been resized (and also when it shown for the first time because all newly created widgets get a resize event automatically).
  • initializeGL() - Sets up the OpenGL rendering context, defines display lists, etc. Gets called once before the first time resizeGL() or paintGL() is called.

Here is a rough outline of how your QGLWidget subclass may look:

    class MyGLDrawer : public QGLWidget
    {
        Q_OBJECT        // must include this if you use Qt signals/slots

    public:
        MyGLDrawer( QWidget *parent, const char *name )
            : QGLWidget(parent,name) {}

    protected:

        void initializeGL()
        {
          // Set up the rendering context, define display lists etc.:
          ...
          glClearColor( 0.0, 0.0, 0.0, 0.0 );
          glEnable(GL_DEPTH_TEST);
          ...
        }

        void resizeGL( int w, int h )
        {
          // setup viewport, projection etc.:
          glViewport( 0, 0, (GLint)w, (GLint)h );
          ...
          glFrustum( ... );
          ...
        }

        void paintGL()
        {
          // draw the scene:
          ...
          glRotatef( ... );
          glMaterialfv( ... );
          glBegin( GL_QUADS );
          glVertex3f( ... );
          glVertex3f( ... );
          ...
          glEnd();
          ...
        }

    };

If you need to trigger a repaint from places other than paintGL() (a typical example is when using timers to animate scenes), you should call the widget's updateGL() function.

Your widget's OpenGL rendering context is made current when paintGL(), resizeGL(), or initializeGL() is called. If you need to call the standard OpenGL API functions from other places (e.g. in your widget's constructor or in your own paint functions), you must call makeCurrent() first.

QGLWidget provides advanced functions for requesting a new display format and you can even set a new rendering context.

You can achieve sharing of OpenGL display lists between QGLWidgets (see the documentation of the QGLWidget constructors for details).

Overlays

The QGLWidget creates a GL overlay context in addition to the normal context if overlays are supported by the underlying system.

If you want to use overlays, you specify it in the format. (Note: Overlay must be requested in the format passed to the QGLWidget constructor.) Your GL widget should also implement some or all of these virtual methods:

  • paintOverlayGL()
  • resizeOverlayGL()
  • initializeOverlayGL()

These methods work in the same way as the normal paintGL() etc. functions, except that they will be called when the overlay context is made current. You can explicitly make the overlay context current by using makeOverlayCurrent(), and you can access the overlay context directly (e.g. to ask for its transparent color) by calling overlayContext().

On X servers in which the default visual is in an overlay plane, non-GL Qt windows can also be used for overlays. See the examples/opengl/overlay_x11 example program for details.

* OpenGL is a trademark of Silicon Graphics, Inc. in the United States and other countries.

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QGLWidget::QGLWidget ( QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 )

Constructs an OpenGL widget with a parent widget and a name.

The default format is used. The widget will be invalid if the system has no OpenGL support.

The parent, name and widget flag, f, arguments are passed to the QWidget constructor.

If the shareWidget parameter points to a valid QGLWidget, this widget will share OpenGL display lists with shareWidget. If this widget and shareWidget have different formats, display list sharing may fail. You can check whether display list sharing succeeded by calling isSharing().

The initialization of OpenGL rendering state, etc. should be done by overriding the initializeGL() function, rather than in the constructor of your QGLWidget subclass.

See also QGLFormat::defaultFormat().

QGLWidget::QGLWidget ( const QGLFormat & format, QWidget * parent = 0, const char * name = 0, const QGLWidget * shareWidget = 0, WFlags f = 0 )

Constructs an OpenGL widget with parent parent, called name.

The format argument specifies the desired rendering options. If the underlying OpenGL/Window system cannot satisfy all the features requested in format, the nearest subset of features will be used. After creation, the format() method will return the actual format obtained.

The widget will be invalid if the system has no OpenGL support.

The parent, name and widget flag, f, arguments are passed to the QWidget constructor.

If the shareWidget parameter points to a valid QGLWidget, this widget will share OpenGL display lists with shareWidget. If this widget and shareWidget have different formats, display list sharing may fail. You can check whether display list sharing succeeded by calling isSharing().

The initialization of OpenGL rendering state, etc. should be done by overriding the initializeGL() function, rather than in the constructor of your QGLWidget subclass.

See also QGLFormat::defaultFormat() and isValid().

QGLWidget::~QGLWidget ()

Destroys the widget.

bool QGLWidget::autoBufferSwap () const [protected]

Returns TRUE if the widget is doing automatic GL buffer swapping; otherwise returns FALSE.

See also setAutoBufferSwap().

const QGLColormap & QGLWidget::colormap () const

Returns the colormap for this widget.

Usually it is only top-level widgets that can have different colormaps installed. Asking for the colormap of a child widget will return the colormap for the child's top-level widget.

If no colormap has been set for this widget, the QColormap returned will be empty.

See also setColormap().

const QGLContext * QGLWidget::context () const

Returns the context of this widget.

It is possible that the context is not valid (see isValid()), for example, if the underlying hardware does not support the format attributes that were requested.

QImage QGLWidget::convertToGLFormat ( const QImage & img ) [static]

Converts the image img into the unnamed format expected by OpenGL functions such as glTexImage2D(). The returned image is not usable as a QImage, but QImage::width(), QImage::height() and QImage::bits() may be used with OpenGL. The following few lines are from the texture example. Most of the code is irrelevant, so we just quote the few lines we want:

        QImage tex1, tex2, buf;
        if ( !buf.load( "gllogo.bmp" ) ) {  // Load first image from file

We create tex1 (and another variable) for OpenGL, and load a real image into buf.

        tex1 = QGLWidget::convertToGLFormat( buf );  // flipped 32bit RGBA

A few lines later, we convert buf into OpenGL format and store it in tex1.

        glTexImage2D( GL_TEXTURE_2D, 0, 3, tex1.width(), tex1.height(), 0,
                      GL_RGBA, GL_UNSIGNED_BYTE, tex1.bits() );

Another function in the same example uses tex1 with OpenGL.

Example: opengl/texture/gltexobj.cpp.

bool QGLWidget::doubleBuffer () const

Returns TRUE if the contained GL rendering context has double buffering; otherwise returns FALSE.

See also QGLFormat::doubleBuffer().

QGLFormat QGLWidget::format () const

Returns the format of the contained GL rendering context.

void QGLWidget::glDraw () [virtual protected]

Executes the virtual function paintGL().

The widget's rendering context will become the current context and initializeGL() will be called if it hasn't already been called.

void QGLWidget::glInit () [virtual protected]

Initializes OpenGL for this widget's context. Calls the virtual function initializeGL().

QImage QGLWidget::grabFrameBuffer ( bool withAlpha = FALSE ) [virtual]

Returns an image of the frame buffer. If withAlpha is TRUE the alpha channel is included.

void QGLWidget::initializeGL () [virtual protected]

This virtual function is called once before the first call to paintGL() or resizeGL(), and then once whenever the widget has been assigned a new QGLContext. Reimplement it in a subclass.

This function should set up any required OpenGL context rendering flags, defining display lists, etc.

There is no need to call makeCurrent() because this has already been done when this function is called.

void QGLWidget::initializeOverlayGL () [virtual protected]

This virtual function is used in the same manner as initializeGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that initializeOverlayGL() is called once before the first call to paintOverlayGL() or resizeOverlayGL(). Reimplement it in a subclass.

This function should set up any required OpenGL context rendering flags, defining display lists, etc. for the overlay context.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

bool QGLWidget::isSharing () const

Returns TRUE if display list sharing with another QGLWidget was requested in the constructor, and the GL system was able to provide it; otherwise returns FALSE. The GL system may fail to provide display list sharing if the two QGLWidgets use different formats.

See also format().

bool QGLWidget::isValid () const

Returns TRUE if the widget has a valid GL rendering context; otherwise returns FALSE. A widget will be invalid if the system has no OpenGL support.

void QGLWidget::makeCurrent () [virtual]

Makes this widget the current widget for OpenGL operations, i.e. makes the widget's rendering context the current OpenGL rendering context.

void QGLWidget::makeOverlayCurrent () [virtual]

Makes the overlay context of this widget current. Use this if you need to issue OpenGL commands to the overlay context outside of initializeOverlayGL(), resizeOverlayGL(), and paintOverlayGL().

Does nothing if this widget has no overlay.

See also makeCurrent().

const QGLContext * QGLWidget::overlayContext () const

Returns the overlay context of this widget, or 0 if this widget has no overlay.

See also context().

void QGLWidget::paintEvent ( QPaintEvent * ) [virtual protected]

Handles paint events. Will cause the virtual paintGL() function to be called.

The widget's rendering context will become the current context and initializeGL() will be called if it hasn't already been called.

Reimplemented from QWidget.

void QGLWidget::paintGL () [virtual protected]

This virtual function is called whenever the widget needs to be painted. Reimplement it in a subclass.

There is no need to call makeCurrent() because this has already been done when this function is called.

void QGLWidget::paintOverlayGL () [virtual protected]

This virtual function is used in the same manner as paintGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that paintOverlayGL() is called whenever the widget's overlay needs to be painted. Reimplement it in a subclass.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

void QGLWidget::qglClearColor ( const QColor & c ) const

Convenience function for specifying the clearing color to OpenGL. Calls glClearColor (in RGBA mode) or glClearIndex (in color-index mode) with the color c. Applies to the current GL context.

See also qglColor(), QGLContext::currentContext() and QColor.

void QGLWidget::qglColor ( const QColor & c ) const

Convenience function for specifying a drawing color to OpenGL. Calls glColor3 (in RGBA mode) or glIndex (in color-index mode) with the color c. Applies to the current GL context.

See also qglClearColor(), QGLContext::currentContext() and QColor.

QPixmap QGLWidget::renderPixmap ( int w = 0, int h = 0, bool useContext = FALSE ) [virtual]

Renders the current scene on a pixmap and returns the pixmap.

You may use this method on both visible and invisible QGLWidgets.

This method will create a pixmap and a temporary QGLContext to render on the pixmap. It will then call initializeGL(), resizeGL(), and paintGL() on this context. Finally, the widget's original GL context is restored.

The size of the pixmap will be w pixels wide and h pixels high unless one of these parameters is 0 (the default), in which case the pixmap will have the same size as the widget.

If useContext is TRUE, this method will try to be more efficient by using the existing GL context to render the pixmap. The default is FALSE. Only use TRUE if you understand the risks.

Overlays are not rendered onto the pixmap.

If the GL rendering context and the desktop have different bit depths, the result will most likely look surprising.

Note that the creation of display lists, modifications of the view frustum etc. should be done from within initializeGL(). If this is not done, the temporary QGLContext will not be initialized properly, and the rendered pixmap may be incomplete/corrupted.

void QGLWidget::resizeEvent ( QResizeEvent * ) [virtual protected]

Handles resize events. Calls the virtual function resizeGL().

Reimplemented from QWidget.

void QGLWidget::resizeGL ( int width, int height ) [virtual protected]

This virtual function is called whenever the widget has been resized. The new size is passed in width and height. Reimplement it in a subclass.

There is no need to call makeCurrent() because this has already been done when this function is called.

void QGLWidget::resizeOverlayGL ( int width, int height ) [virtual protected]

This virtual function is used in the same manner as paintGL() except that it operates on the widget's overlay context instead of the widget's main context. This means that resizeOverlayGL() is called whenever the widget has been resized. The new size is passed in width and height. Reimplement it in a subclass.

There is no need to call makeOverlayCurrent() because this has already been done when this function is called.

void QGLWidget::setAutoBufferSwap ( bool on ) [protected]

If on is TRUE automatic GL buffer swapping is switched on; otherwise it is switched off.

If on is TRUE and the widget is using a double-buffered format, the background and foreground GL buffers will automatically be swapped after each time the paintGL() function has been called.

The buffer auto-swapping is on by default.

See also autoBufferSwap(), doubleBuffer() and swapBuffers().

void QGLWidget::setColormap ( const QGLColormap & cmap )

Set the colormap for this widget to cmap. Usually it is only top-level widgets that can have colormaps installed.

See also colormap().

void QGLWidget::swapBuffers () [virtual]

Swaps the screen contents with an off-screen buffer. This only works if the widget's format specifies double buffer mode.

Normally, there is no need to explicitly call this function because it is done automatically after each widget repaint, i.e. each time after paintGL() has been executed.

See also doubleBuffer(), setAutoBufferSwap() and QGLFormat::setDoubleBuffer().

void QGLWidget::updateGL () [virtual slot]

Updates the widget by calling glDraw().

void QGLWidget::updateOverlayGL () [virtual slot]

Updates the widget's overlay (if any). Will cause the virtual function paintOverlayGL() to be executed.

The widget's rendering context will become the current context and initializeGL() will be called if it hasn't already been called.

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


QGLWidget Member List

Complete Member List for QGLWidget

This is the complete list of member functions for QGLWidget, including inherited members.

  • QGLWidget()
  • ~QGLWidget()
  • acceptDrops()
  • adjustSize()
  • autoBufferSwap()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • colormap()
  • connect()
  • connectNotify()
  • constPolish()
  • context()
  • contextMenuEvent()
  • convertToGLFormat()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doubleBuffer()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • format()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • glDraw()
  • glInit()
  • grabFrameBuffer()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • initializeGL()
  • initializeOverlayGL()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSharing()
  • isTopLevel()
  • isUpdatesEnabled()
  • isValid()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • makeCurrent()
  • makeOverlayCurrent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • overlayContext()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintGL()
  • paintOverlayGL()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • qglClearColor()
  • qglColor()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • renderPixmap()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • resizeGL()
  • resizeOverlayGL()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoBufferSwap()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setColormap()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • swapBuffers()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGL()
  • updateGeometry()
  • updateMask()
  • updateOverlayGL()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QGrid类

QGrid类参考

QGrid类提供了一些简单的对它的子对象的几何位置管理。 详情请见……

#include <qgrid.h>

继承了QFrame。

所有成员函数的列表。

公有成员

  • QGrid ( int n, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • QGrid ( int n, Orientation orient, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • void setSpacing ( int space )

详细描述

QGrid类提供了一些简单的对它的子对象的几何位置管理。

这个网格把它的子窗口部件放到一个单行或者单列中。如果你想有一个多行多列的网格，请使用QGridLayout。

行或者列的数量在构造函数中规定了。这个网格的所有子对象将会被遵循它们的sizeHint()和sizePolicy()来被放置和规定大小。

使用setMargin()来为网格自身添加四周的空间，并且使用setSpacing()为窗口部件之间增加空间。

也可以参考QVBox、QHBox、QGridLayout、窗口部件的外观和风格和布局管理器。

成员函数文档

QGrid::QGrid ( int n, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个父对象为parent、名称为name、列数为n的网格窗口部件。窗口部件标记f被传递给QFrame的构造函数。

QGrid::QGrid ( int n, Orientation orient, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个父对象为parent、名称为name的网格窗口部件。如果orient是Horizontal，n指定的是列数。如果orient是Vertical，n指定的是行数。窗口部件标记f被传递给QFrame的构造函数。

void QGrid::setSpacing ( int space )

设置子窗口部件之间的空间为space。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qgrid.h包含文件

qgrid.h

这里是qgrid.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qgrid.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGRID_H
#define QGRID_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_GRID

class QGridLayout;

class Q_EXPORT QGrid : public QFrame
{
    Q_OBJECT
public:
    QGrid( int n, QWidget* parent=0, const char* name=0, WFlags f = 0 );
    QGrid( int n, Orientation orient, QWidget* parent=0, const char* name=0,
       WFlags f = 0 );

    void setSpacing( int );
    QSize sizeHint() const;

#ifndef QT_NO_COMPAT
    typedef Orientation Direction;
#endif

protected:
    void frameChanged();

private:
    QGridLayout *lay;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QGrid( const QGrid & );
    QGrid& operator=( const QGrid & );
#endif
};

#endif // QT_NO_GRID

#endif // QGRID_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QGrid成员列表

完整的QGrid成员列表

这里是QGrid成员函数的完整列表，包括继承的成员。

  • QGrid()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setSpacing()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QGridLayout Class

QGridLayout Class Reference

The QGridLayout class lays out widgets in a grid. More...

#include <qlayout.h>

Inherits QLayout.

List of all member functions.

Public Members

  • QGridLayout ( QWidget * parent, int nRows = 1, int nCols = 1, int margin = 0, int space = -1, const char * name = 0 )
  • QGridLayout ( int nRows = 1, int nCols = 1, int spacing = -1, const char * name = 0 )
  • QGridLayout ( QLayout * parentLayout, int nRows = 1, int nCols = 1, int spacing = -1, const char * name = 0 )
  • ~QGridLayout ()
  • virtual QSize sizeHint () const
  • virtual QSize minimumSize () const
  • virtual QSize maximumSize () const
  • virtual void setRowStretch ( int row, int stretch )
  • virtual void setColStretch ( int col, int stretch )
  • int rowStretch ( int row ) const
  • int colStretch ( int col ) const
  • int numRows () const
  • int numCols () const
  • QRect cellGeometry ( int row, int col ) const
  • virtual bool hasHeightForWidth () const
  • virtual int heightForWidth ( int w ) const
  • virtual QSizePolicy::ExpandData expanding () const
  • virtual void invalidate ()
  • virtual void addItem ( QLayoutItem * item )
  • void addItem ( QLayoutItem * item, int row, int col )
  • void addMultiCell ( QLayoutItem * item, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )
  • void addWidget ( QWidget * w, int row, int col, int alignment = 0 )
  • void addMultiCellWidget ( QWidget * w, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )
  • void addLayout ( QLayout * layout, int row, int col )
  • void addMultiCellLayout ( QLayout * layout, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )
  • void addRowSpacing ( int row, int minsize )
  • void addColSpacing ( int col, int minsize )
  • void expand ( int nRows, int nCols )
  • enum Corner { TopLeft, TopRight, BottomLeft, BottomRight }
  • void setOrigin ( Corner c )
  • Corner origin () const
  • virtual void setGeometry ( const QRect & r )

Protected Members

  • bool findWidget ( QWidget * w, int * row, int * col )
  • void add ( QLayoutItem * item, int row, int col )

Detailed Description

The QGridLayout class lays out widgets in a grid.

QGridLayout takes the space made available to it (by its parent layout or by the mainWidget()), divides it up into rows and columns, and puts each widget it manages into the correct cell.

Columns and rows behave identically; we will discuss columns, but there are equivalent functions for rows.

Each column has a minimum width and a stretch factor. The minimum width is the greatest of that set using addColSpacing() and the minimum width of each widget in that column. The stretch factor is set using setColStretch() and determines how much of the available space the column will get over and above its necessary minimum.

Normally, each managed widget or layout is put into a cell of its own using addWidget(), addLayout() or by the auto-add facility. It is also possible for a widget to occupy multiple cells using addMultiCellWidget(). If you do this, QGridLayout will guess how to distribute the size over the columns/rows (based on the stretch factors).

To remove a widget from a layout, either delete it or reparent it with QWidget::reparent(). Hiding a widget with QWidget::hide() also effectively removes the widget from the layout, until QWidget::show() is called.

This illustration shows a fragment of a dialog with a five-column, three-row grid (the grid is shown overlaid in magenta):

Columns 0, 2 and 4 in this dialog fragment are made up of a QLabel, a QLineEdit, and a QListBox. Columns 1 and 3 are placeholders made with addColSpacing(). Row 0 consists of three QLabel objects, row 1 of three QLineEdit objects and row 2 of three QListBox objects. We used placeholder columns (1 and 3) to get the right amount of space between the columns.

Note that the columns and rows are not equally wide or tall. If you want two columns to have the same width, you must set their minimum widths and stretch factors to be the same yourself. You do this using addColSpacing() and setColStretch().

If the QGridLayout is not the top-level layout (i.e. does not manage all of the widget's area and children), you must add it to its parent layout when you create it, but before you do anything with it. The normal way to add a layout is by calling parentLayout->addLayout().

Once you have added your layout you can start putting widgets and other layouts into the cells of your grid layout using addWidget(), addLayout() and addMultiCellWidget().

QGridLayout also includes two margin widths: the border and the spacing. The border is the width of the reserved space along each of the QGridLayout's four sides. The spacing is the width of the automatically allocated spacing between neighboring boxes.

Both the border and the spacing are parameters of the constructor and default to 0.

See also QGrid, Layout Overview, Widget Appearance and Style and Layout Management.

Member Type Documentation

QGridLayout::Corner

This enum identifies which corner is the origin (0, 0) of the layout.

  • QGridLayout::TopLeft - the top-left corner
  • QGridLayout::TopRight - the top-right corner
  • QGridLayout::BottomLeft - the bottom-left corner
  • QGridLayout::BottomRight - the bottom-right corner

Member Function Documentation

QGridLayout::QGridLayout ( QWidget * parent, int nRows = 1, int nCols = 1, int margin = 0, int space = -1, const char * name = 0 )

Constructs a new QGridLayout with nRows rows, nCols columns and parent widget, parent. parent may not be 0. The grid layout is called name.

margin is the number of pixels between the edge of the widget and its managed children. space is the default number of pixels between cells. If space is -1, the value of margin is used.

QGridLayout::QGridLayout ( int nRows = 1, int nCols = 1, int spacing = -1, const char * name = 0 )

Constructs a new grid with nRows rows and nCols columns. If spacing is -1, this QGridLayout inherits its parent's spacing(); otherwise spacing is used. The grid layout is called name.

You must insert this grid into another layout. You can insert widgets and layouts into this layout at any time, but laying out will not be performed before this is inserted into another layout.

QGridLayout::QGridLayout ( QLayout * parentLayout, int nRows = 1, int nCols = 1, int spacing = -1, const char * name = 0 )

Constructs a new grid that is placed inside parentLayout with nRows rows and nCols columns. If spacing is -1, this QGridLayout inherits its parent's spacing(); otherwise spacing is used. The grid layout is called name.

This grid is placed according to parentLayout's default placement rules.

QGridLayout::~QGridLayout ()

Destroys the grid layout. Geometry management is terminated if this is a top-level grid.

The layout's widgets are not destroyed.

void QGridLayout::add ( QLayoutItem * item, int row, int col ) [protected]

Adds item at position row, col. The layout takes ownership of the item.

void QGridLayout::addColSpacing ( int col, int minsize )

Sets the minimum width of column col to minsize pixels.

void QGridLayout::addItem ( QLayoutItem * item, int row, int col )

Adds item at position row, col. The layout takes ownership of the item.

void QGridLayout::addItem ( QLayoutItem * item ) [virtual]

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

Adds item to the next free position of this layout.

Reimplemented from QLayout.

void QGridLayout::addLayout ( QLayout * layout, int row, int col )

Places the layout at position (row, col) in the grid. The top-left position is (0, 0).

Examples: listbox/listbox.cpp, progressbar/progressbar.cpp, t10/main.cpp and t13/gamebrd.cpp.

void QGridLayout::addMultiCell ( QLayoutItem * item, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )

Adds the item to the cell grid, spanning multiple rows/columns.

The cell will span from fromRow, fromCol to toRow, toCol. Alignment is specified by alignment, which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

void QGridLayout::addMultiCellLayout ( QLayout * layout, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )

Adds the layout layout to the cell grid, spanning multiple rows/columns. The cell will span from fromRow, fromCol to toRow, toCol.

Alignment is specified by alignment, which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

A non-zero alignment indicates that the layout should not grow to fill the available space but should be sized according to sizeHint().

void QGridLayout::addMultiCellWidget ( QWidget * w, int fromRow, int toRow, int fromCol, int toCol, int alignment = 0 )

Adds the widget w to the cell grid, spanning multiple rows/columns. The cell will span from fromRow, fromCol to toRow, toCol.

Alignment is specified by alignment, which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

A non-zero alignment indicates that the widget should not grow to fill the available space but should be sized according to sizeHint().

Examples: cursor/cursor.cpp, layout/layout.cpp and progressbar/progressbar.cpp.

void QGridLayout::addRowSpacing ( int row, int minsize )

Sets the minimum height of row row to minsize pixels.

void QGridLayout::addWidget ( QWidget * w, int row, int col, int alignment = 0 )

Adds the widget w to the cell grid at row, col. The top-left position is (0, 0) by default.

Alignment is specified by alignment, which is a bitwise OR of Qt::AlignmentFlags values. The default alignment is 0, which means that the widget fills the entire cell.

  • You should not call this if you have enabled the auto-add facility of the layout.

  • From Qt 3.0, the alignment parameter is interpreted more aggressively than in previous versions of Qt. A non-default alignment now indicates that the widget should not grow to fill the available space, but should be sized according to sizeHint().

Examples: addressbook/centralwidget.cpp, layout/layout.cpp, rot13/rot13.cpp, sql/overview/form1/main.cpp, sql/overview/form2/main.cpp, t14/gamebrd.cpp and t8/main.cpp.

QRect QGridLayout::cellGeometry ( int row, int col ) const

Returns the geometry of the cell with row row and column col in the grid. Returns an invalid rectangle if row or col is outside the grid.

Warning: in the current version of Qt this function does not return valid results until setGeometry() has been called, i.e. after the mainWidget() is visible.

int QGridLayout::colStretch ( int col ) const

Returns the stretch factor for column col.

See also setColStretch().

void QGridLayout::expand ( int nRows, int nCols )

Expands this grid so that it will have nRows rows and nCols columns. Will not shrink the grid. You should not need to call this function because QGridLayout expands automatically as new items are inserted.

QSizePolicy::ExpandData QGridLayout::expanding () const [virtual]

Returns the expansiveness of this layout.

Reimplemented from QLayout.

bool QGridLayout::findWidget ( QWidget * w, int * row, int * col ) [protected]

Searches for widget w in this layout (not including child layouts). If w is found, it sets *<em>row</em> and *<em>col</em> to the row and column and returns TRUE; otherwise returns FALSE.

Note: if a widget spans multiple rows/columns, the top-left cell is returned.

bool QGridLayout::hasHeightForWidth () const [virtual]

Returns TRUE if this layout's preferred height depends on its width; otherwise returns FALSE.

Reimplemented from QLayoutItem.

int QGridLayout::heightForWidth ( int w ) const [virtual]

Returns the layout's preferred height when it is w pixels wide.

Reimplemented from QLayoutItem.

void QGridLayout::invalidate () [virtual]

Resets cached information.

Reimplemented from QLayout.

QSize QGridLayout::maximumSize () const [virtual]

Returns the maximum size needed by this grid.

Reimplemented from QLayout.

QSize QGridLayout::minimumSize () const [virtual]

Returns the minimum size needed by this grid.

Reimplemented from QLayout.

int QGridLayout::numCols () const

Returns the number of columns in this grid.

int QGridLayout::numRows () const

Returns the number of rows in this grid.

Corner QGridLayout::origin () const

Returns the corner that's used for the grid's origin, i.e. for position (0, 0).

int QGridLayout::rowStretch ( int row ) const

Returns the stretch factor for row row.

See also setRowStretch().

void QGridLayout::setColStretch ( int col, int stretch ) [virtual]

Sets the stretch factor of column col to stretch. The first column is number 0.

The stretch factor is relative to the other columns in this grid. Columns with a higher stretch factor take more of the available space.

The default stretch factor is 0. If the stretch factor is 0 and no other column in this table can grow at all, the column may still grow.

See also colStretch(), addColSpacing() and setRowStretch().

Examples: layout/layout.cpp, t14/gamebrd.cpp and t8/main.cpp.

void QGridLayout::setGeometry ( const QRect & r ) [virtual]

Resizes managed widgets within the rectangle r.

Reimplemented from QLayout.

void QGridLayout::setOrigin ( Corner c )

Sets the grid's origin corner, i.e. position (0, 0), to c.

void QGridLayout::setRowStretch ( int row, int stretch ) [virtual]

Sets the stretch factor of row row to stretch. The first row is number 0.

The stretch factor is relative to the other rows in this grid. Rows with a higher stretch factor take more of the available space.

The default stretch factor is 0. If the stretch factor is 0 and no other row in this table can grow at all, the row may still grow.

See also rowStretch(), addRowSpacing() and setColStretch().

Example: addressbook/centralwidget.cpp.

QSize QGridLayout::sizeHint () const [virtual]

Returns the preferred size of this grid.

Reimplemented from QLayoutItem.

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


QGridLayout Member List

Complete Member List for QGridLayout

This is the complete list of member functions for QGridLayout, including inherited members.

  • QGridLayout()
  • ~QGridLayout()
  • activate()
  • add()
  • addChildLayout()
  • addColSpacing()
  • addItem()
  • addLayout()
  • addMultiCell()
  • addMultiCellLayout()
  • addMultiCellWidget()
  • addRowSpacing()
  • addWidget()
  • alignment()
  • alignmentRect()
  • autoAdd()
  • blockSignals()
  • cellGeometry()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • colStretch()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteAllItems()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • expand()
  • expanding()
  • findWidget()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • invalidate()
  • isA()
  • isEmpty()
  • isEnabled()
  • isTopLevel()
  • isWidgetType()
  • iterator()
  • killTimer()
  • killTimers()
  • layout()
  • mainWidget()
  • margin()
  • maximumSize()
  • menuBar()
  • metaObject()
  • minimumSize()
  • name()
  • normalizeSignalSlot()
  • numCols()
  • numRows()
  • objectTrees()
  • origin()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • resizeMode()
  • rowStretch()
  • sender()
  • setAlignment()
  • setAutoAdd()
  • setColStretch()
  • setEnabled()
  • setGeometry()
  • setMargin()
  • setMenuBar()
  • setName()
  • setOrigin()
  • setProperty()
  • setResizeMode()
  • setRowStretch()
  • setSpacing()
  • setSupportsMargin()
  • signalsBlocked()
  • sizeHint()
  • spacerItem()
  • spacing()
  • startTimer()
  • supportsMargin()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()


QGridView Class

QGridView Class Reference

The QGridView class provides an abstract base for fixed-size grids. More...

#include <qgridview.h>

Inherits QScrollView.

List of all member functions.

Public Members

  • QGridView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QGridView ()
  • int numRows () const
  • virtual void setNumRows ( int )
  • int numCols () const
  • virtual void setNumCols ( int )
  • int cellWidth () const
  • virtual void setCellWidth ( int )
  • int cellHeight () const
  • virtual void setCellHeight ( int )
  • QRect cellRect () const
  • QRect cellGeometry ( int row, int column )
  • QSize gridSize () const
  • int rowAt ( int y ) const
  • int columnAt ( int x ) const
  • void repaintCell ( int row, int column, bool erase = TRUE )
  • void updateCell ( int row, int column )
  • void ensureCellVisible ( int row, int column )

Properties

  • int cellHeight - the height of a grid row
  • int cellWidth - the width of a grid column
  • int numCols - the number of columns in the grid
  • int numRows - the number of rows in the grid

Protected Members

  • virtual void paintCell ( QPainter * p, int row, int col ) = 0
  • virtual void paintEmptyArea ( QPainter * p, int cx, int cy, int cw, int ch )
  • virtual void dimensionChange ( int oldNumRows, int oldNumCols )

Detailed Description

The QGridView class provides an abstract base for fixed-size grids.

A grid view consists of a number of abstract cells organized in rows and columns. The cells have a fixed size and are identified with a row index and a column index. The top-left cell is in row 0, column 0. The bottom-right cell is in row numRows()-1, column numCols()-1.

You can define numRows, numCols, cellWidth and cellHeight. Reimplement the pure virtual function paintCell() to draw the content of a cell.

With ensureCellVisible(), you can ensure a certain cell is visible. With rowAt() and columnAt() you can find a cell based on the given x- and y-coordinates.

If you need to monitor changes to the grid's dimensions (i.e. when numRows or numCols is changed), reimplement the dimensionChange() change handler.

Note: the row, column indices are always given in the order, row (vertical offset) then column (horizontal offset). This order is the opposite of all pixel operations, which are given in the order x (horizontal offset), y (vertical offset).

QGridView is a very simple abstract class based on QScrollView. It is designed to simplify the task of drawing many cells of the same size in a potentially scrollable canvas. If you need rows and columns in different sizes, use a QTable instead. If you need a simple list of items, use a QListBox. If you need to present hierachical data use a QListView, and if you need random objects at random positions, consider using either a QIconView or a QCanvas.

See also Abstract Widget Classes.

Member Function Documentation

QGridView::QGridView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a grid view.

The parent, name and widget flag, f, arguments are passed to the QScrollView constructor.

QGridView::~QGridView ()

Destroys the grid view.

QRect QGridView::cellGeometry ( int row, int column )

Returns the geometry of cell (row, column) in the content coordinate system.

See also cellRect().

int QGridView::cellHeight () const

Returns the height of a grid row. See the "cellHeight" property for details.

QRect QGridView::cellRect () const

Returns the geometry of a cell in a cell's coordinate system. This is a convenience function useful in paintCell(). It is equivalent to QRect( 0, 0, cellWidth(), cellHeight() ).

See also cellGeometry().

int QGridView::cellWidth () const

Returns the width of a grid column. See the "cellWidth" property for details.

int QGridView::columnAt ( int x ) const

Returns the number of the column at position x. x must be given in content coordinates.

See also rowAt().

void QGridView::dimensionChange ( int oldNumRows, int oldNumCols ) [virtual protected]

This change handler is called whenever any of the grid's dimensions changes. oldNumRows and oldNumCols contain the old dimensions, numRows() and numCols() contain the new dimensions.

void QGridView::ensureCellVisible ( int row, int column )

Ensure cell (row, column) is visible, scrolling the grid view if necessary.

QSize QGridView::gridSize () const

Returns the size of the grid in pixels.

int QGridView::numCols () const

Returns the number of columns in the grid. See the "numCols" property for details.

int QGridView::numRows () const

Returns the number of rows in the grid. See the "numRows" property for details.

void QGridView::paintCell ( QPainter * p, int row, int col ) [pure virtual protected]

This pure virtual function is called to paint the single cell at (row, col) using painter p. The painter must be open when paintCell() is called and must remain open.

The coordinate system is translated so that the origin is at the top-left corner of the cell to be painted, i.e. cell coordinates. Do not scale or shear the coordinate system (or if you do, restore the transformation matrix before you return).

The painter is not clipped by default in order to get maximum efficiency. If you want clipping, use

    p->setClipRect( cellRect(), QPainter::CoordPainter );
    //... your drawing code
    p->setClipping( FALSE );

void QGridView::paintEmptyArea ( QPainter * p, int cx, int cy, int cw, int ch ) [virtual protected]

This function fills the cw pixels wide and ch pixels high rectangle starting at position (cx, cy) with the background color using the painter p.

paintEmptyArea() is invoked by drawContents() to erase or fill unused areas.

void QGridView::repaintCell ( int row, int column, bool erase = TRUE )

Repaints cell (row, column).

If erase is TRUE, Qt erases the area of the cell before the paintCell() call; otherwise no erasing takes place.

See also QWidget::repaint().

int QGridView::rowAt ( int y ) const

Returns the number of the row at position y. y must be given in content coordinates.

See also columnAt().

void QGridView::setCellHeight ( int ) [virtual]

Sets the height of a grid row. See the "cellHeight" property for details.

void QGridView::setCellWidth ( int ) [virtual]

Sets the width of a grid column. See the "cellWidth" property for details.

void QGridView::setNumCols ( int ) [virtual]

Sets the number of columns in the grid. See the "numCols" property for details.

void QGridView::setNumRows ( int ) [virtual]

Sets the number of rows in the grid. See the "numRows" property for details.

void QGridView::updateCell ( int row, int column )

Updates cell (row, column).

See also QWidget::update().

Property Documentation

int cellHeight

This property holds the height of a grid row.

All rows in a grid view have the same height.

See also cellWidth.

Set this property's value with setCellHeight() and get this property's value with cellHeight().

int cellWidth

This property holds the width of a grid column.

All columns in a grid view have the same width.

See also cellHeight.

Set this property's value with setCellWidth() and get this property's value with cellWidth().

int numCols

This property holds the number of columns in the grid.

Set this property's value with setNumCols() and get this property's value with numCols().

See also numRows.

int numRows

This property holds the number of rows in the grid.

Set this property's value with setNumRows() and get this property's value with numRows().

See also numCols.

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


qgridview.h Include File

qgridview.h

This is the verbatim text of the qgridview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id$
**
** Definition of QGridView class
**
** Created: 2001.05.23
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGRIDVIEW_H
#define QGRIDVIEW_H

#ifndef QT_H
#include "qscrollview.h"
#endif // QT_H

#ifndef QT_NO_GRIDVIEW

class QGridViewPrivate;

class Q_EXPORT QGridView : public QScrollView
{
    Q_OBJECT
    Q_PROPERTY( int numRows READ numRows WRITE setNumRows )
    Q_PROPERTY( int numCols READ numCols WRITE setNumCols )
    Q_PROPERTY( int cellWidth READ cellWidth WRITE setCellWidth )
    Q_PROPERTY( int cellHeight READ cellHeight WRITE setCellHeight )
public:

    QGridView( QWidget *parent=0, const char *name=0, WFlags f=0 );
   ~QGridView();

    int numRows() const;
    virtual void setNumRows( int );
    int numCols() const;
    virtual void setNumCols( int );

    int cellWidth() const;
    virtual void setCellWidth( int );
    int cellHeight() const;
    virtual void setCellHeight( int );

    QRect cellRect() const;
    QRect cellGeometry( int row, int column );
    QSize gridSize() const;

    int rowAt( int y ) const;
    int columnAt( int x ) const;

    void repaintCell( int row, int column, bool erase=TRUE );
    void updateCell( int row, int column );
    void ensureCellVisible( int row, int column );

protected:
    virtual void paintCell( QPainter *, int row, int col ) = 0;
    virtual void paintEmptyArea( QPainter *p, int cx, int cy, int cw, int ch );

    void drawContents( QPainter *p, int cx, int cy, int cw, int ch );

    virtual void dimensionChange( int, int );

private:
    void drawContents( QPainter* );
    void updateGrid();

    int nrows;
    int ncols;
    int cellw;
    int cellh;
    QGridViewPrivate* d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QGridView( const QGridView & );
    QGridView &operator=( const QGridView & );
#endif
};

inline int QGridView::cellWidth() const
{ return cellw; }

inline int QGridView::cellHeight() const
{ return cellh; }

inline int QGridView::rowAt( int y ) const
{ return y / cellh; }

inline int QGridView::columnAt( int x ) const
{ return x / cellw; }

inline int QGridView::numRows() const
{ return nrows; }

inline int QGridView::numCols() const
{return ncols; }

inline QRect QGridView::cellRect() const
{ return QRect( 0, 0, cellw, cellh ); }

inline QSize QGridView::gridSize() const
{ return QSize( ncols * cellw, nrows * cellh ); }

#endif // QT_NO_GRIDVIEW

#endif // QTABLEVIEW_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QGridView Member List

Complete Member List for QGridView

This is the complete list of member functions for QGridView, including inherited members.

  • QGridView()
  • ~QGridView()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • caption()
  • cellGeometry()
  • cellHeight()
  • cellRect()
  • cellWidth()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columnAt()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • cornerWidget()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • dimensionChange()
  • disconnect()
  • disconnectNotify()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureCellVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • gridSize()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numCols()
  • numRows()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintCell()
  • paintEmptyArea()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintCell()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • rightMargin()
  • rowAt()
  • scroll()
  • scrollBy()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellHeight()
  • setCellWidth()
  • setContentsPos()
  • setCornerWidget()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNumCols()
  • setNumRows()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizePolicy()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateCell()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QGroupBox类

QGroupBox类参考

QGroupBox窗口部件提供了一个有标题的组合框。 详情请见……

#include <qgroupbox.h>

继承了QFrame。

被QButtonGroup、QHGroupBox和QVGroupBox继承。

所有成员函数的列表。

公有成员

  • QGroupBox ( QWidget * parent = 0, const char * name = 0 )
  • QGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • QGroupBox ( int strips, Orientation orientation, QWidget * parent = 0, const char * name = 0 )
  • QGroupBox ( int strips, Orientation orientation, const QString & title, QWidget * parent = 0, const char * name = 0 )
  • virtual void setColumnLayout ( int strips, Orientation direction )
  • QString title () const
  • virtual void setTitle ( const QString & )
  • int alignment () const
  • virtual void setAlignment ( int )
  • int columns () const
  • void setColumns ( int )
  • Orientation orientation () const
  • void setOrientation ( Orientation )
  • int insideMargin () const
  • int insideSpacing () const
  • void setInsideMargin ( int m )
  • void setInsideSpacing ( int s )
  • void addSpace ( int size )

属性

  • Alignment alignment - 组合框标题的对齐方式
  • int columns - 组合框中的列数或者行数（依赖orientation）
  • Orientation orientation - 组合框的当前方向
  • QString title - 组合框的标题文本

详细描述

QGroupBox窗口部件提供了一个有标题的组合框。

组合框提供一个框架、一个标题和一个键盘快捷键，并且显示在它里面地其它不同窗口部件。标题在上面，键盘快捷键移动键盘焦点到组合框的一个子窗口部件，并且子窗口部件将会排列在这个框架中地一个数组中。

使用它的最简单方式是创建一个为你所想要的列数（或者行数）和方向的组合框，并且然后创建其它窗口部件时，把这个组合框作为父对象。

然而，也可以在构造函数之后改变方向（orientation()）和列数（或者行数，columns()），或者忽略所有自动布局支持并且自己来管理所有的这一切。你也可以通过addSpace()把“空白”添加到组合框中。

QGroupBox也让你设置标题（title()，通常在构造函数中设置）和标题对齐方式（alignment()）。

你可以通过setInsideMargin()和setInsideSpacing()改变组合框所用的空白。

也可以参考QButtonGroup、窗口部件外观和风格、布局管理和组织者。

成员函数文档

QGroupBox::QGroupBox ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的组合框。

parent和name参数被传递给QWidget构造函数。

这个构造函数不做自动布局。

QGroupBox::QGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的组合框。

parent和name参数被传递给QWidget构造函数。

这个构造函数不做自动布局。

QGroupBox::QGroupBox ( int strips, Orientation orientation, QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的组合框。子窗口部件会被排列在strips列或者行中（依赖orientation）。

parent和name参数被传递给QWidget构造函数。

QGroupBox::QGroupBox ( int strips, Orientation orientation, const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的组合框。子窗口部件会被排列在strips列或者行中（依赖orientation）。

parent和name参数被传递给QWidget构造函数。

void QGroupBox::addSpace ( int size )

在下一个的自由位置添加一个空白单元格。如果size大于0，空白单元格就有固定的高度或宽度。如果组合框是水平方向，这个空白单元格就有固定的高度，如果组合框是垂直方向，这个空白单元格就有固定的宽度。

使用这个方法来分隔组合框中的窗口部件或者来略过下一个自由单元格。由于性能的原因，请在调用setColumnLayout()或者改变QGroupBox::columns或QGroupBox::orientation属性之后，调用这个方法。首先调用这些方法（如果需要的话）通常是一个不错的主意，并且在这之后插入窗口部件和间隔。

int QGroupBox::alignment () const

返回组合框标题的对齐方式。详细情况请参考“alignment”属性。

int QGroupBox::columns () const

返回组合框中的列数或者行数（依赖orientation）。详细情况请参考“columns”属性。

int QGroupBox::insideMargin () const

返回组合框中的项和框架之间的空白的宽度。

仅仅适用于组合框有一个定义的方向。

默认大约为11。

也可以参考setInsideMargin()和orientation。

int QGroupBox::insideSpacing () const

返回组合框中各项之间的空白的宽度。

仅仅适用于组合框有一个定义的方向。

默认大约为5。

也可以参考setInsideSpacing()和orientation。

Orientation QGroupBox::orientation () const

返回组合框的当前方向。详细情况请参考“orientation”属性。

void QGroupBox::setAlignment ( int ) [虚]

设置组合框标题的对齐方式。详细情况请参考“alignment”属性。

void QGroupBox::setColumnLayout ( int strips, Orientation direction ) [虚]

改变组合框的布局。这个函数只有和没有使用任何布局信息的默认构造函数联合使用才有用。这个函数会把所有已经存在的子对象放入新的布局中。在已经插入子对象之后再调用这个函数不是很好的Qt编程风格。

也可以参考orientation和columns。

实例：chart/optionsform.cpp。

void QGroupBox::setColumns ( int )

设置组合框中的列数或者行数（依赖orientation）。详细情况请参考“columns”属性。

void QGroupBox::setInsideMargin ( int m )

设置组合框中的项和框架之间的空白的宽度为m象素。

也可以参考insideSpacing()。

void QGroupBox::setInsideSpacing ( int s )

设置组合框中各项之间的空白的宽度为m象素。

void QGroupBox::setOrientation ( Orientation )

设置组合框的当前方向。详细情况请参考“orientation”属性。

void QGroupBox::setTitle ( const QString & ) [虚]

设置组合框的标题文本。详细情况请参考“title”属性。

QString QGroupBox::title () const

返回组合框的标题文本。详细情况请参考“title”属性。

属性文档

Alignment alignment

这个属性保存的是组合框标题的对齐方式。

标题总是被放在框架上面的那行中，可是，水平对齐方式可以由这个对齐参数指定。

对齐方式是下述标记之一：

  • AlignAuto根据语言对齐标题，通常为左。
  • AlignLeft左对齐标题。
  • AlignRight右对齐标题。
  • AlignHCenter中间对齐标题。

默认的对齐方式是AlignAuto。

也可以参考Qt::AlignmentFlags。

通过setAlignment()设置属性值并且通过alignment()来获得属性值。

int columns

这个属性保存的是组合框中的列数或者行数（依赖orientation）。

通常设置这个属性不是一个好主意，因为这会使它变慢（它是一个完全的布局）。最好在构造函数中直接设置列数或者行数。

通过setColumns()设置属性值并且通过columns()来获得属性值。

Orientation orientation

这个属性保存的是组合框的当前方向。

水平组合框把它的子对象按列排列，而垂直组合框会按行排列它们。因此只有一列的水平组合框会把它的子对象垂直地排列在这列中。

通常设置这个属性不是一个好主意，因为这会使它变慢（它是一个完全的布局）。最好在构造函数中直接设置方向。

通过setOrientation()设置属性值并且通过orientation()来获得属性值。

QString title

这个属性保存的是组合框的标题文本。

如果这个标题包含一个&，后面还有一个字母，这个组合框标题文本将会又一个焦点改变键盘快捷键。

      g->setTitle( "&User information" );
这将会产生“User information”并且U下面有下划线。Alt+U会移动键盘焦点到这个组合框。

没有默认标题文本。

通过setTitle()设置属性值并且通过title()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qgroupbox.h包含文件

qgroupbox.h

这里是qgroupbox.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/**********************************************************************
** $Id:  qt/qgroupbox.h   3.0.5   edited Mar 18 12:51 $
**
** Definition of QGroupBox widget class
**
** Created : 950203
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGROUPBOX_H
#define QGROUPBOX_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_GROUPBOX

class QAccel;
class QGroupBoxPrivate;
class QVBoxLayout;
class QGridLayout;
class QSpacerItem;

class Q_EXPORT QGroupBox : public QFrame
{
    Q_OBJECT
    Q_PROPERTY( QString title READ title WRITE setTitle )
    Q_PROPERTY( Alignment alignment READ alignment WRITE setAlignment )
    Q_PROPERTY( Orientation orientation READ orientation WRITE setOrientation DESIGNABLE false )
    Q_PROPERTY( int columns READ columns WRITE setColumns DESIGNABLE false )

public:
    QGroupBox( QWidget* parent=0, const char* name=0 );
    QGroupBox( const QString &title,
           QWidget* parent=0, const char* name=0 );
    QGroupBox( int strips, Orientation o,
           QWidget* parent=0, const char* name=0 );
    QGroupBox( int strips, Orientation o, const QString &title,
           QWidget* parent=0, const char* name=0 );

    virtual void setColumnLayout(int strips, Orientation o);

    QString title() const { return str; }
    virtual void setTitle( const QString &);

    int alignment() const { return align; }
    virtual void setAlignment( int );

    int columns() const;
    void setColumns( int );

    Orientation orientation() const { return dir; }
    void setOrientation( Orientation );

    int insideMargin() const;
    int insideSpacing() const;
    void setInsideMargin( int m );
    void setInsideSpacing( int s );

    void addSpace( int );
    QSize sizeHint() const;

protected:
    bool event( QEvent * );
    void childEvent( QChildEvent * );
    void resizeEvent( QResizeEvent * );
    void paintEvent( QPaintEvent * );
    void focusInEvent( QFocusEvent * );
    void fontChange( const QFont & );

private slots:
    void fixFocus();

private:
    void skip();
    void init();
    void calculateFrame();
    void insertWid( QWidget* );
    void setTextSpacer();

    QString str;
    int align;
    int lenvisible;
#ifndef QT_NO_ACCEL
    QAccel * accel;
#endif
    QGroupBoxPrivate * d;

    QVBoxLayout *vbox;
    QGridLayout *grid;
    int row;
    int col;
    int nRows, nCols;
    Orientation dir;
    int spac, marg;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QGroupBox( const QGroupBox & );
    QGroupBox &operator=( const QGroupBox & );
#endif
};

#endif // QT_NO_GROUPBOX

#endif // QGROUPBOX_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QGroupBox成员列表

完整的QGroupBox成员列表

这里是QGroupBox成员函数的完整列表，包括继承的成员。

  • QGroupBox()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QGuardedPtr类

QGuardedPtr类参考

QGuardedPtr类是一个提供被监视的QObject的指针的模板类。 详情请见……

#include <qguardedptr.h>

所有成员函数的列表。

公有成员

  • QGuardedPtr ()
  • QGuardedPtr ( T * p )
  • QGuardedPtr ( const QGuardedPtr<T> & p )
  • ~QGuardedPtr ()
  • QGuardedPtr<T> & operator= ( const QGuardedPtr<T> & p )
  • QGuardedPtr<T> & operator= ( T * p )
  • bool operator== ( const QGuardedPtr<T> & p ) const
  • bool operator!= ( const QGuardedPtr<T> & p ) const
  • bool isNull () const
  • T * operator-> () const
  • T & operator* () const
  • operator T * () const

详细描述

QGuardedPtr类是一个提供被监视的QObject的指针的模板类。

一个被监视的指针，QGuardedPtr<X>行为就和一个普通的C++指针X*一样，除了当被引用的对象被销毁时，它能够自动地被设置为0（不像普通的C++指针，在这种情况下就变成了“摇摆的指针”）。X必须是QObject的子类。

只要你需要存储一个被其它的所拥有的并且有可能在你还保留它的引用的时候它已经被销毁了的QObject的指针的时候，被监视的指针就是有用的。你可以安全地测试指针的有效性。

实例：

        QGuardedPtr<QFrame> label = new QLabel( 0,"label" );
        label->setText( "I like guarded pointers" );

        delete (QLabel*) label; // 模拟某人销毁了这个标签

        if ( label)
            label->show();
        else
            qDebug("The label has been destroyed");

这个程序将会输出

        The label has been destroyed
而不是解除引用的label->show()的一个无效地址。

QGuardedPtr提供的函数和操作符和普通的未被监视的指针提供的一样，除了指针的算术运算（++、--、-和+），它们通常只对数组对象有用。把它们用作普通的指针，你就不需要再都这份类文档了。

为了创建被监视的指针，你可以通过一个X*或者另一个同类型的被监视的指针来构造和赋值。你可以用operator==()来比较它们是不是相等，用operator!=()来比较它们是不是不等，或者用isNull()来测试它是否为零。并且你可以使用*x或x->member符号来解除引用。

被监视的指针会自动地抛出X*，所以你可以自由地混合被监视的和未被监视的指针。这也就是说如果你有一个QGuardedPtr，你可以把它传递给一个需要QWidget*的函数。因为这个原因，在声明函数中使用一个QGuardedPtr作为参数，没有多少价值，所以请使用普通的指针。当你长时间保存一个指针的时候，请使用QGuardedPtr。

请再次注意X类必须继承QObject，否则会得到一个编译或者链接错误。

也可以参考对象模型。

成员函数文档

QGuardedPtr::QGuardedPtr ()

构造一个为0的被监视的指针。

也可以参考isNull()。

QGuardedPtr::QGuardedPtr ( T * p )

构造一个和p指向相同对象的被监视的指针。

QGuardedPtr::QGuardedPtr ( const QGuardedPtr<T> & p )

从另一个被监视的指针复制过来。被构造的被监视指针和p指向相同对象（也许它为0）。

QGuardedPtr::~QGuardedPtr ()

销毁这个被监视的指针。就像一个普通的指针一样，销毁被监视的指针并不销毁所指向的对象。

bool QGuardedPtr::isNull () const

如果被引用的对象已经被销毁或者没有被引用的对象，返回真，否则返回假。

QGuardedPtr::operator T * () const

抛出操作符，实现了指针语义。因为这个函数，你可以通过把一个QGuardedPtr<X>传递给一个需要X*的函数。

bool QGuardedPtr::operator!= ( const QGuardedPtr<T> & p ) const

不等于操作符，实现了指针语义。和operator==()相反。如果p和这个被监视的指针指向的不是同一个对象，返回真，否则返回假。

T & QGuardedPtr::operator* () const

解除引用操作符，实现了指针语义。使用这个操作符就像你对普通的C++指针做的一样。

T * QGuardedPtr::operator-> () const

重载箭头操作符，实现了指针语义。使用这个操作符就像你对普通的C++指针做的一样。

QGuardedPtr<T> & QGuardedPtr::operator= ( const QGuardedPtr<T> & p )

赋值操作符。这个被监视的指针就会和p一样指向相同的对象。

QGuardedPtr<T> & QGuardedPtr::operator= ( T * p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

赋值操作符。这个被监视的指针就会和p一样指向相同的对象。

bool QGuardedPtr::operator== ( const QGuardedPtr<T> & p ) const

等于操作符，实现了传统的指针语义。如果p和这个被监视的指针都是0，或者如果p和这个被监视的指针都指向相同的对象，返回真，否则返回假。

也可以参考operator!=().

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qguardedptr.h包含文件

qguardedptr.h

这里是qguardedptr.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QGuardedPtr class
**
** Created : 990929
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QGUARDEDPTR_H
#define QGUARDEDPTR_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

class Q_EXPORT QGuardedPtrPrivate : public QObject, public QShared
{
    Q_OBJECT
public:
    QGuardedPtrPrivate( QObject* );
    ~QGuardedPtrPrivate();

    QObject* object() const;
    void reconnect( QObject* );

private slots:
    void objectDestroyed();

private:
    QObject* obj;
};

template <class T>
class QGuardedPtr
{
public:
    QGuardedPtr() : priv( new QGuardedPtrPrivate( 0 ) ) {}

    QGuardedPtr( T* o) {
    priv = new QGuardedPtrPrivate( (QObject*)o );
    }

    QGuardedPtr(const QGuardedPtr<T> &p) {
    priv = p.priv;
    ref();
    }

    ~QGuardedPtr() { deref(); }

    QGuardedPtr<T> &operator=(const QGuardedPtr<T> &p) {
    if ( priv != p.priv ) {
        deref();
        priv = p.priv;
        ref();
    }
    return *this;
    }

    QGuardedPtr<T> &operator=(T* o) {
    if ( priv->count == 1 ) {
        priv->reconnect( (QObject*)o );
    } else {
        deref();
        priv = new QGuardedPtrPrivate( (QObject*)o );
    }
    return *this;
    }

    bool operator==( const QGuardedPtr<T> &p ) const {
    return priv->object() == p.priv->object();
    }

    bool operator!= ( const QGuardedPtr<T>& p ) const {
    return !( *this == p );
    }

    bool isNull() const { return !priv->object(); }

    T* operator->() const { return (T*) priv->object(); }

    T& operator*() const { return *( (T*)priv->object() ); }

    operator T*() const { return (T*) priv->object(); }

private:

    void ref() { priv->ref(); }

    void deref() {
    if ( priv->deref() )
        delete priv;
    }

    QGuardedPtrPrivate* priv;
};

inline QObject* QGuardedPtrPrivate::object() const
{
    return obj;
}

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QGuardedPtr成员列表

完整的QGuardedPtr成员列表

这里是QGuardedPtr成员函数的完整列表，包括继承的成员。

  • QGuardedPtr()
  • ~QGuardedPtr()
  • isNull()
  • operator T *()
  • operator!=()
  • operator*()
  • operator->()
  • operator=()
  • operator==()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QHBox Class

QHBox Class Reference

The QHBox widget provides horizontal geometry management for its child widgets. More...

#include <qhbox.h>

Inherits QFrame.

Inherited by QVBox.

List of all member functions.

Public Members

  • QHBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • void setSpacing ( int space )
  • bool setStretchFactor ( QWidget * w, int stretch )

Protected Members

  • QHBox ( bool horizontal, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Detailed Description

The QHBox widget provides horizontal geometry management for its child widgets.

All the horizontal box's child widgets will be placed alongside each other and sized according to their sizeHint()s.

Use setMargin() to add space around the edge, and use setSpacing() to add space between the widgets. Use setStretchFactor() if you want the widgets to be different sizes in proportion to one another.

See also QHBoxLayout, QVBox, QGrid, Widget Appearance and Style, Layout Management and Organizers.

Member Function Documentation

QHBox::QHBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs an hbox widget with parent parent and name name. The parent, name and widget flags, f, are passed to the QFrame constructor.

QHBox::QHBox ( bool horizontal, QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) [protected]

Constructs a horizontal hbox if horizontal is TRUE, otherwise constructs a vertical hbox (also known as a vbox).

This constructor is provided for the QVBox class. You should never need to use it directly.

The parent, name and widget flags, f, are passed to the QFrame constructor.

void QHBox::setSpacing ( int space )

Sets the spacing between the child widgets to space.

Examples: i18n/mywidget.cpp, listboxcombo/listboxcombo.cpp, network/ftpclient/ftpmainwindow.cpp, qdir/qdir.cpp, tabdialog/tabdialog.cpp, wizard/wizard.cpp and xform/xform.cpp.

bool QHBox::setStretchFactor ( QWidget * w, int stretch )

Sets the stretch factor of widget w to stretch.

See also QBoxLayout::setStretchFactor().

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


qhbox.h Include File

qhbox.h

This is the verbatim text of the qhbox.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qhbox.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHBOX_H
#define QHBOX_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_HBOX

#include "qframe.h"

class QBoxLayout;

class Q_EXPORT QHBox : public QFrame
{
    Q_OBJECT
public:
    QHBox( QWidget* parent=0, const char* name=0, WFlags f=0 );

    void setSpacing( int );
    bool setStretchFactor( QWidget*, int stretch );
    QSize sizeHint() const;

protected:
    QHBox( bool horizontal, QWidget* parent=0, const char* name=0, WFlags f=0 );
    void frameChanged();

private:
    QBoxLayout *lay;
};

#endif // QT_NO_HBOX

#endif // QHBOX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QHBox Member List

Complete Member List for QHBox

This is the complete list of member functions for QHBox, including inherited members.

  • QHBox()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setSpacing()
  • setStretchFactor()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QHBoxLayout Class

QHBoxLayout Class Reference

The QHBoxLayout class lines up widgets horizontally. More...

#include <qlayout.h>

Inherits QBoxLayout.

List of all member functions.

Public Members

  • QHBoxLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )
  • QHBoxLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )
  • QHBoxLayout ( int spacing = -1, const char * name = 0 )
  • ~QHBoxLayout ()

Detailed Description

The QHBoxLayout class lines up widgets horizontally.

This class is used to construct horizontal box layout objects. See QBoxLayout for more details.

The simplest use of the class is like this:

        QBoxLayout * l = new QHBoxLayout( widget );
        l->setAutoAdd( TRUE );
        new QSomeWidget( widget );
        new QSomeOtherWidget( widget );
        new QAnotherWidget( widget );

or like this:

        QBoxLayout * l = new QHBoxLayout( widget );
        l->addWidget( existingChildOfWidget );
        l->addWidget( anotherChildOfWidget );

See also QVBoxLayout, QGridLayout, the Layout overview, Widget Appearance and Style and Layout Management.

Member Function Documentation

QHBoxLayout::QHBoxLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )

Constructs a new top-level horizontal box called name, with parent parent.

The margin is the number of pixels between the edge of the widget and its managed children. The spacing is the default number of pixels between neighboring children. If spacing is -1 the value of margin is used for spacing.

QHBoxLayout::QHBoxLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )

Constructs a new horizontal box called name name and adds it to parentLayout.

The spacing is the default number of pixels between neighboring children. If spacing is -1, this QHBoxLayout will inherit its parent's spacing().

QHBoxLayout::QHBoxLayout ( int spacing = -1, const char * name = 0 )

Constructs a new horizontal box called name name. You must add it to another layout.

The spacing is the default number of pixels between neighboring children. If spacing is -1, this QHBoxLayout will inherit its parent's spacing().

QHBoxLayout::~QHBoxLayout ()

Destroys this box layout.

The layout's widgets are not destroyed.

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


QHBoxLayout Member List

Complete Member List for QHBoxLayout

This is the complete list of member functions for QHBoxLayout, including inherited members.

  • QHBoxLayout()
  • ~QHBoxLayout()
  • activate()
  • add()
  • addChildLayout()
  • addItem()
  • addLayout()
  • addSpacing()
  • addStretch()
  • addStrut()
  • addWidget()
  • alignment()
  • alignmentRect()
  • autoAdd()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteAllItems()
  • deleteLater()
  • destroyed()
  • direction()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • expanding()
  • findWidget()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • highPriority()
  • inherits()
  • insertChild()
  • insertItem()
  • insertLayout()
  • insertSpacing()
  • insertStretch()
  • insertWidget()
  • installEventFilter()
  • invalidate()
  • isA()
  • isEmpty()
  • isEnabled()
  • isTopLevel()
  • isWidgetType()
  • iterator()
  • killTimer()
  • killTimers()
  • layout()
  • mainWidget()
  • margin()
  • maximumSize()
  • menuBar()
  • metaObject()
  • minimumSize()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • resizeMode()
  • sender()
  • setAlignment()
  • setAutoAdd()
  • setDirection()
  • setEnabled()
  • setGeometry()
  • setMargin()
  • setMenuBar()
  • setName()
  • setProperty()
  • setResizeMode()
  • setSpacing()
  • setStretchFactor()
  • setSupportsMargin()
  • signalsBlocked()
  • sizeHint()
  • spacerItem()
  • spacing()
  • startTimer()
  • supportsMargin()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()


QHButtonGroup类

QHButtonGroup类参考

QHButtonGroup窗口部件把QButton窗口部件组织在一个水平行中。 详情请见……

#include <qhbuttongroup.h>

继承了QButtonGroup。

所有成员函数的列表。

公有成员

  • QHButtonGroup ( QWidget * parent = 0, const char * name = 0 )
  • QHButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • ~QHButtonGroup ()

详细描述

QHButtonGroup窗口部件把QButton窗口部件组织在一个水平行中。

QHButtonGroup是一个在QButtonGroup中提供了一个小布局的方便类。可以把它看作适提供了一个框架和标题的QHBox并且是特别为按钮设计的。

也可以参考QVButtonGroup、窗口部件外观和风格、布局管理和组织者.

成员函数文档

QHButtonGroup::QHButtonGroup ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的水平按钮组。

parent和name参数被传递给QWidget构造函数。

QHButtonGroup::QHButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的水平按钮组。

parent和name参数被传递给QWidget构造函数。

QHButtonGroup::~QHButtonGroup ()

销毁这个水平按钮组，删除它的子窗口部件。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qhbuttongroup.h包含文件

qhbuttongroup.h

这里是qhbuttongroup.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qhbuttongroup.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QHButtonGroup class
**
** Created : 990602
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHBUTTONGROUP_H
#define QHBUTTONGROUP_H

#ifndef QT_H
#include "qbuttongroup.h"
#endif // QT_H

#ifndef QT_NO_HBUTTONGROUP

class Q_EXPORT QHButtonGroup : public QButtonGroup
{
    Q_OBJECT
public:
    QHButtonGroup( QWidget* parent=0, const char* name=0 );
    QHButtonGroup( const QString &title, QWidget* parent=0, const char* name=0 );
    ~QHButtonGroup();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QHButtonGroup( const QHButtonGroup & );
    QHButtonGroup &operator=( const QHButtonGroup & );
#endif
};

#endif // QT_NO_HBUTTONGROUP

#endif // QHBUTTONGROUP_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QHButtonGroup成员列表

完整的QHButtonGroup成员列表

这里是QHButtonGroup成员函数的完整列表，包括继承的成员。

  • QHButtonGroup()
  • ~QHButtonGroup()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • id()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusive()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isRadioButtonExclusive()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • moveFocus()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • remove()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setButton()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExclusive()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRadioButtonExclusive()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QHeader类

QHeader类参考

QHeader类为诸如表格和列表（listview）等提供标题行或者列。 详见……

#include <qheader.h>

继承了QWidget。

所有成员函数的列表。

公共成员

  • QHeader ( QWidget * parent = 0, const char * name = 0 )
  • QHeader ( int n, QWidget * parent = 0, const char * name = 0 )
  • ~QHeader ()
  • int addLabel ( const QString & s, int size = -1 )
  • int addLabel ( const QIconSet & iconset, const QString & s, int size = -1 )
  • void removeLabel ( int section )
  • virtual void setLabel ( int section, const QString & s, int size = -1 )
  • virtual void setLabel ( int section, const QIconSet & iconset, const QString & s, int size = -1 )
  • QString label ( int section ) const
  • QIconSet * iconSet ( int section ) const
  • virtual void setOrientation ( Orientation )
  • Orientation orientation () const
  • virtual void setTracking ( bool enable )
  • bool tracking () const
  • virtual void setClickEnabled ( bool enable, int section = -1 )
  • virtual void setResizeEnabled ( bool enable, int section = -1 )
  • virtual void setMovingEnabled ( bool )
  • virtual void setStretchEnabled ( bool b, int section )
  • void setStretchEnabled ( bool b )
  • bool isClickEnabled ( int section = -1 ) const
  • bool isResizeEnabled ( int section = -1 ) const
  • bool isMovingEnabled () const
  • bool isStretchEnabled () const
  • bool isStretchEnabled ( int section ) const
  • void resizeSection ( int section, int s )
  • int sectionSize ( int section ) const
  • int sectionPos ( int section ) const
  • int sectionAt ( int pos ) const
  • int count () const
  • int headerWidth () const
  • QRect sectionRect ( int section ) const
  • virtual void setCellSize ( int section, int s ) (obsolete)
  • int cellSize ( int i ) const (obsolete)
  • int cellPos ( int i ) const (obsolete)
  • int cellAt ( int pos ) const (obsolete)
  • int offset () const
  • int mapToSection ( int index ) const
  • int mapToIndex ( int section ) const
  • int mapToLogical ( int a ) const (obsolete)
  • int mapToActual ( int l ) const (obsolete)
  • void moveSection ( int section, int toIndex )
  • virtual void moveCell ( int fromIdx, int toIdx ) (obsolete)
  • void setSortIndicator ( int section, bool increasing = TRUE )
  • void adjustHeaderSize ()

公共槽

  • virtual void setOffset ( int pos )

信号

  • void clicked ( int section )
  • void pressed ( int section )
  • void released ( int section )
  • void sizeChange ( int section, int oldSize, int newSize )
  • void indexChange ( int section, int fromIndex, int toIndex )
  • void sectionClicked ( int index ) (obsolete)
  • void moved ( int fromIndex, int toIndex ) (obsolete)

属性

  • int count - 标题中的节（section）数 (read only)
  • bool moving - 标题节是否可以被移动
  • int offset - 标题最左（或者最上）可见的象素
  • Orientation orientation - 标题的物理朝向
  • bool stretching - 标题的节是否总是占据标题的全部宽度（或者高度）
  • bool tracking - 信号sizeChange()是否被连续发送

保护成员

  • QRect sRect ( int index )
  • virtual void paintSection ( QPainter * p, int index, const QRect & fr )
  • virtual void paintSectionLabel ( QPainter * p, int index, const QRect & fr )

详细描述

QHeader类为诸如表格和列表（listview）等提供标题行或者列。

本类提供一个标题，例如一个垂直标题显示行标签，或者一个水平标题显示列标签。它可以用于诸如QTable和QListView中。

标题由一个或者很多节组成，每个节都可以显示一个文本标签和一个图标（iconset）。使用setSortIndicator()，还可以显示排序指示器（箭头）。

使用addLabel()添加节，使用removeLabel()删去节。标签和图标在addLabel()中设置，以后可以用setLabel()来修改。使用count()以得到标题中节的数目。

标题的朝向用setOrientation()来设置。如果setStretchEnabled()为TRUE，节将会占据标题的全部宽度（对于垂直标题则是全部高度）。如果setResizeEnabled()为TRUE，用户可以手动调整节的大小。调用adjustHeaderSize()，可以调整节的大小，占据全部宽度（或者高度）。

可以使用moveSection()以移动节。如果setMovingEnabled()为TRUE，用户可以把节拖来拖去。如果某个节被移动，节被添加（使用addLabel()）时的索引位置就可能与移动之后不同了。实际上你不必担心这一点，因为QHeader的API是使用节的编号（section number）的术语来工作的，某特定的节被移到哪里并没有关系。

如果你想得到一个节的当前索引位置，可以以节编号为参数调用mapToIndex()。（这个节编号是由生成该节的addLabel()调用所返回的数值。）如果你想得到一个具体索引位置的节的编号，可以以索引位置为参数调用mapToSection()。

下面是阐明mapToSection()和mapToIndex()的例子：

索引位置
0 | 1 | 2 | 3
原来的节次序
Sect 0 | Sect 1 | Sect 2 | Sect 3
用户移动一个节之后的次序
Sect 0 | Sect 2 | Sect 3 | Sect 1

k | mapToSection(k) | mapToIndex(k)
0 | 0 | 0
1 | 2 | 3
2 | 3 | 1
3 | 1 | 2

在上面的例子中，如果我们要找出哪个节在索引位置3，可以调用mapToSection(3)，就会得到节编号为1，因为节1被移动到了那里。类似地，如果我们要知道节2占据了哪个索引位置，调用mapToIndex(2)，就会得到索引为1。

QHeader提供了clicked()、pressed()和released()信号。如果用户改变了某个节的大小，sizeChange()信号被发送。如果你希望sizeChange()信号在用户调整大小时持续被发送（而不是只在调整后），使用setTracking()。如果用户移动了节，indexChange()信号被发送。

也参见QListView、QTable和高级部件。

成员函数文档

QHeader::QHeader ( QWidget * parent = 0, const char * name = 0 )

构造一个水平标题，命名为name，父部件为parent。

QHeader::QHeader ( int n, QWidget * parent = 0, const char * name = 0 )

构造一个水平标题，命名为name，由n节组成，父部件为parent。

QHeader::~QHeader ()

销毁标题及其节。

int QHeader::addLabel ( const QString & s, int size = -1 )

增加一个新节，标签文本为s。返回节所加在的索引位置（对于水平标题是在右边，对于垂直标题是在下边）。节的宽度设置为size。若size < 0，则根据文本s来选择合适的大小。

int QHeader::addLabel ( const QIconSet & iconset, const QString & s, int size = -1 )

这是重载的成员函数，为便利而提供。其行为本质上类似上一个函数。

增加一个带有图标iconset和标签文本s的新节。返回节所加在的索引位置（对于水平标题是在右边，对于垂直标题是在下边）。节的宽度设置为size。若size < 0，则根据文本来选择合适的大小。

void QHeader::adjustHeaderSize ()

调整节的大小，以尽可能全部占据标题的大小。只有isStretchEnabled()为TRUE的那些节会被调整大小。

int QHeader::cellAt ( int pos ) const

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用sectionAt()来代替本函数。

Returns the index at which the section is displayed, which contains pos in widget coordinates, or -1 if pos is outside the header sections.

int QHeader::cellPos ( int i ) const

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用sectionPos()来代替本函数。

Returns the position in pixels of the section that is displayed at the index i。 The position is measured from the start of the header.

int QHeader::cellSize ( int i ) const

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用sectionSize()来代替本函数。

Returns the size in pixels of the section that is displayed at the index i。

void QHeader::clicked ( int section ) [信号]

如果isClickEnabled()为TRUE，当用户点击节section时，本信号被发送。

也参见pressed()和released()。

int QHeader::count () const

返回标题中的节的数目。详见"count"属性。

int QHeader::headerWidth () const

返回所有标题列的总宽度。

QIconSet * QHeader::iconSet ( int section ) const

返回节section的图标。如果该节不存在，返回0。

void QHeader::indexChange ( int section, int fromIndex, int toIndex ) [信号]

当用户把节section从索引位置fromIndex移到索引位置toIndex时，本信号被发送。

bool QHeader::isClickEnabled ( int section = -1 ) const

如果节section为可点击，返回TRUE；否则返回FALSE。

在section超出范围时（为负或者大于count() - 1），如果所有节都是可点击，返回TRUE，否则返回FALSE。

也参见setClickEnabled()。

bool QHeader::isMovingEnabled () const

如果标题节可以被移动，返回TRUE；否则返回FALSE。详见"moving"属性。

bool QHeader::isResizeEnabled ( int section = -1 ) const

如果节section为可调整大小，返回TRUE；否则返回FALSE。

如果section为-1，本函数应用于所有节，也就是说，如果所有节都是可调整大小的，返回TRUE；否则返回FALSE。

也参见setResizeEnabled()。

bool QHeader::isStretchEnabled () const

如果标题节总是占据标题的全部宽度（或者高度），返回TRUE；否则返回FALSE。 详见"stretching"属性。

bool QHeader::isStretchEnabled ( int section ) const

如果节section可以调整大小以占据标题的全部宽度（或者高度），返回TRUE；否则返回FALSE。如果至少一个节是可伸缩的，节就总是占据标题的全部宽度。

也参见setStretchEnabled()。

QString QHeader::label ( int section ) const

返回节section的文本。如果该节不存在，返回空字符串。

int QHeader::mapToActual ( int l ) const

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用mapToIndex()来代替本函数。

Translates from logical index l to actual index (index at which the section l is displayed) . Returns -1 if l is outside the legal range.

也参见mapToLogical()。

int QHeader::mapToIndex ( int section ) const

返回节section当前被显示的索引。

更多解释参见mapTo例子。

int QHeader::mapToLogical ( int a ) const

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用mapToSection()来代替本函数。

Translates from actual index a (index at which the section is displayed) to logical index of the section. Returns -1 if a is outside the legal range.

也参见mapToActual()。

int QHeader::mapToSection ( int index ) const

返回显示于索引位置index的节。

更多解释参见mapTo例子。

void QHeader::moveCell ( int fromIdx, int toIdx ) [虚]

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用moveSection()来代替本函数。

Moves the section that is currently displayed at index fromIdx to index toIdx。

void QHeader::moveSection ( int section, int toIndex )

把节section移到索引位置toIndex。

void QHeader::moved ( int fromIndex, int toIndex ) [信号]

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用indexChange()来代替本函数。

This signal is emitted when the user has moved the section which is displayed at the index fromIndex to the index toIndex。

int QHeader::offset () const

返回标题的最左（或者最上）的可见象素。 详见"offset"属性。

Orientation QHeader::orientation () const

返回标题的物理朝向。 详见"orientation"属性。

void QHeader::paintSection ( QPainter * p, int index, const QRect & fr ) [虚 保护]

在矩形fr内（使用部件坐标），使用画具p绘制在位置index的节。

调用了paintSectionLabel()。

void QHeader::paintSectionLabel ( QPainter * p, int index, const QRect & fr ) [虚 保护]

在矩形fr内（使用部件坐标），使用画具p绘制在位置index的节的标签。

被paintSection()所调用。

void QHeader::pressed ( int section ) [信号]

当用户按下节section时，本信号被发送。

也参见released()。

void QHeader::released ( int section ) [信号]

当用户释放节section时，本信号被发送。

也参见pressed()。

void QHeader::removeLabel ( int section )

删去节section。如果该节不存在，什么也不做。

void QHeader::resizeSection ( int section, int s )

调整节section的大小为s象素宽（或者高）。

QRect QHeader::sRect ( int index ) [protected]

返回被索引为index的节所覆盖的矩形。

int QHeader::sectionAt ( int pos ) const

返回包括以象素给出的位置pos的节索引。

也参见offset。

void QHeader::sectionClicked ( int index ) [信号]

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用clicked()来代替本函数。

This signal is emitted when a part of the header is clicked. index is the index at which the section is displayed.

In a list view this signal would typically be connected to a slot that sorts the specified column (or row)。

int QHeader::sectionPos ( int section ) const

返回节section开始的位置（以象素形式）。

也参见offset。

QRect QHeader::sectionRect ( int section ) const

返回被节section所覆盖的矩形。

int QHeader::sectionSize ( int section ) const

以象素形式返回节section的宽度（或者高度）。

void QHeader::setCellSize ( int section, int s ) [虚]

本函数已经废弃。为支持旧代码运行而提供，强烈建议新代码中不要使用。

使用resizeSection()来代替本函数。

Sets the size of the section section to s pixels.

警告： does not repaint or send out signals。

void QHeader::setClickEnabled ( bool enable, int section = -1 ) [虚]

如果enable为TRUE，点击节section就会导致clicked()信号被发送；否则节将忽略点击。

如果section为-1（缺省），那么enable值对所有存在的节都设置，而且也应用到增加的新节上。

也参见moving和setResizeEnabled()。

void QHeader::setLabel ( int section, const QString & s, int size = -1 ) [虚]

设置节section的文本为s。如果size >= 0，节的宽度设置为size；否则不变。该节已经设置的图标保持不变。

如果该节不存在，什么也不做。

例子：chart/setdataform.cpp和table/small-table-demo/main.cpp。

void QHeader::setLabel ( int section, const QIconSet & iconset, const QString & s, int size = -1 ) [虚]

这是重载的成员函数，为便利而提供。其行为本质上类似上一个函数。

把节section的图标设置为iconset，文本设置为s。如果size >= 0，节的宽度设置为size；否则不变。

如果该节不存在，什么也不做。

void QHeader::setMovingEnabled ( bool ) [虚]

设置标题的节是否可以移动。详见"moving"属性。

void QHeader::setOffset ( int pos ) [虚 槽]

设置标题的最左（或者最上）的可见象素为pos。详见"offset"属性。

void QHeader::setOrientation ( Orientation ) [虚]

设置标题的物理朝向。详见"orientation"属性。

void QHeader::setResizeEnabled ( bool enable, int section = -1 ) [虚]

如果enable为TRUE，用户可以调整节section的大小；否则该节不能被手动调整大小。

如果section为负（缺省），那么enable值对所有存在的节都设置，而且也应用到增加的新节上。 例子：

    // Allow resizing of all current and future sections
    header->setResizeEnabled(TRUE);
    // Disable resizing of section 3, (the fourth section added)
    header->setResizeEnabled(FALSE, 3);

如果用户调整了一个节的大小，sizeChange()信号被发送。

也参见moving、setClickEnabled()和tracking。

void QHeader::setSortIndicator ( int section, bool increasing = TRUE )

因为QHeader经常与表格或者列表部件一起使用，它可以显示排序的次序。这可以通过在节的右边显示一个箭头来实现。

如果increasing为TRUE（缺省），箭头指向下；否则向上。

同一时间只能有一个节显示排序指示。如果你不想让任何节显示排序指示器，传入参数section为-1。

void QHeader::setStretchEnabled ( bool b, int section ) [虚]

如果b为TRUE，节section的大小将会随标题的大小调整而调整，以使节占据标题的全部宽度（对于垂直标题则是高度）；否则，节section被设置为不可伸缩，也不会随标题的调整大小而调整大小。

在section为-1时，如果b为TRUE，所有节的大小相等地随标题的大小调整而调整，以使节占据标题的全部宽度（对于垂直标题则是高度）；否则，所有节都被设置为不可伸缩，也不会随标题的调整大小而调整大小。

也参见adjustHeaderSize()。

void QHeader::setStretchEnabled ( bool b )

设置标题的节是否总是占据标题的全部宽度（或者高度）为b。 详见"stretching"属性。

void QHeader::setTracking ( bool enable ) [虚]

设置sizeChange()信号是否持续被发送为enable。 详见"tracking"属性。

void QHeader::sizeChange ( int section, int oldSize, int newSize ) [信号]

当用户把节section的大小从oldSize改为newSize时，本信号被发送。典型地，本信号连接到一个槽上，这个槽重绘包括该标题的表格或者列表。

bool QHeader::tracking () const

如果sizeChange()信号是持续被发送的，返回TRUE；否则返回FALSE。 详见"tracking"属性。

属性文档

int count

本属性决定标题中的节的数目。

用count()来得到本属性值。

bool moving

得到本属性值标题的节是否可以被移动。

如果本属性为TRUE，用户可以移动节。如果用户移动某个节，indexChange()信号被发送。

也参见setClickEnabled()和setResizeEnabled()。

用setMovingEnabled()设置本属性值，用isMovingEnabled()得到本属性值。

int offset

本属性决定标题的最左（或者最上）的可见象素。

设置本属性将滚动标题以使得offset成为最左（或者最上，对于垂直标题）的可见象素。

用setOffset()设置本属性值，用offset()得到本属性值。

Orientation orientation

本属性决定标题的物理朝向。

朝向要么是QHeader::Vertical，要么就是QHeader::Horizontal（缺省）。

如果你没有提供大小参数，就要在添加标签之前调用setOrientation()，否则大小会不正确。

用setOrientation()设置本属性值，用orientation()得到本属性值。

bool stretching

本属性决定标题的节是否总是占据标题的全部宽度（或者高度）。

用setStretchEnabled()设置本属性值，用isStretchEnabled()得到本属性值。

bool tracking

本属性决定sizeChange()信号是否持续地被发送。

如果tracking为打开，当鼠标移动（也就是标题被调整大小）时，sizeChange()信号持续地被发送；否则，只有在大小调整结束鼠标按键释放时，才发送信号。

Tracking缺省为FALSE。

用setTracking()设置本属性值，用tracking()得到本属性值。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


qheader.h包含文件

qheader.h

这里是qheader.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qheader.h   3.0.5   edited May 3 19:39 $
**
** Definition of QHeader widget class (table header)
**
** Created : 961105
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHEADER_H
#define QHEADER_H

#ifndef QT_H
#include "qwidget.h"
#include "qstring.h"
#include "qiconset.h" // conversion QPixmap->QIconset
#endif // QT_H

#ifndef QT_NO_HEADER

class QShowEvent;
class QHeaderData;
class QTable;

class Q_EXPORT QHeader : public QWidget
{
    friend class QTable;
    friend class QTableHeader;

    Q_OBJECT
    Q_PROPERTY( Orientation orientation READ orientation WRITE setOrientation )
    Q_PROPERTY( bool tracking READ tracking WRITE setTracking )
    Q_PROPERTY( int count READ count )
    Q_PROPERTY( int offset READ offset WRITE setOffset )
    Q_PROPERTY( bool moving READ isMovingEnabled WRITE setMovingEnabled )
    Q_PROPERTY( bool stretching READ isStretchEnabled WRITE setStretchEnabled )

public:
    QHeader( QWidget* parent=0, const char* name=0 );
    QHeader( int, QWidget* parent=0, const char* name=0 );
    ~QHeader();

    int		addLabel( const QString &, int size = -1 );
    int		addLabel( const QIconSet&, const QString &, int size = -1 );
    void 	removeLabel( int section );
    virtual void setLabel( int, const QString &, int size = -1 );
    virtual void setLabel( int, const QIconSet&, const QString &, int size = -1 );
    QString 	label( int section ) const;
    QIconSet* 	iconSet( int section ) const;

    virtual void setOrientation( Orientation );
    Orientation orientation() const;
    virtual void setTracking( bool enable );
    bool	tracking() const;

    virtual void setClickEnabled( bool, int section = -1 );
    virtual void setResizeEnabled( bool, int section = -1 );
    virtual void setMovingEnabled( bool );
    virtual void setStretchEnabled( bool b, int section );
    void setStretchEnabled( bool b ) { setStretchEnabled( b, -1 ); }
    bool isClickEnabled( int section = -1 ) const;
    bool isResizeEnabled( int section = -1 ) const;
    bool isMovingEnabled() const;
    bool isStretchEnabled() const;
    bool isStretchEnabled( int section ) const;

    void 	resizeSection( int section, int s );
    int		sectionSize( int section ) const;
    int		sectionPos( int section ) const;
    int		sectionAt( int pos ) const;
    int		count() const;
    int headerWidth() const;
    QRect	sectionRect( int section ) const;

    virtual void setCellSize( int , int ); // obsolete, do not use
    int		cellSize( int i ) const { return sectionSize( mapToSection(i) ); } // obsolete, do not use
    int		cellPos( int ) const; // obsolete, do not use
    int		cellAt( int pos ) const { return mapToIndex( sectionAt(pos + offset()) ); } // obsolete, do not use

    int 	offset() const;

    QSize	sizeHint() const;

    int		mapToSection( int index ) const;
    int		mapToIndex( int section ) const;
    int		mapToLogical( int ) const; // obsolete, do not use
    int		mapToActual( int ) const; // obsolete, do not use

    void 	moveSection( int section, int toIndex );
    virtual void moveCell( int, int); // obsolete, do not use

    void 	setSortIndicator( int section, bool increasing = TRUE );
    void adjustHeaderSize() { adjustHeaderSize( -1 ); }

public slots:
    void setUpdatesEnabled( bool enable );
    virtual void setOffset( int pos );

signals:
    void	clicked( int section );
    void	pressed( int section );
    void	released( int section );
    void	sizeChange( int section, int oldSize, int newSize );
    void	indexChange( int section, int fromIndex, int toIndex );
    void	sectionClicked( int ); // obsolete, do not use
    void	moved( int, int ); // obsolete, do not use

protected:
    void	paintEvent( QPaintEvent * );
    void	showEvent( QShowEvent *e );
    void 	resizeEvent( QResizeEvent *e );
    QRect	sRect( int index );

    virtual void	paintSection( QPainter *p, int index, const QRect& fr);
    virtual void	paintSectionLabel( QPainter* p, int index, const QRect& fr );

    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );

private:
    void adjustHeaderSize( int diff );
    void	init( int );

    void	paintRect( int p, int s );
    void	markLine( int idx );
    void	unMarkLine( int idx );
    int		pPos( int i ) const;
    int		pSize( int i ) const;
    int 	findLine( int );
    bool reverse() const;
    void calculatePositions( bool onlyVisible = FALSE, int start = 0 );
    void	handleColumnResize(int, int, bool, bool = TRUE );
    QSize	sectionSizeHint( int section, const QFontMetrics& fm ) const;
    void	setSectionSizeAndHeight( int section, int size );

    void resizeArrays( int size );
    void setIsATableHeader( bool b );
    int		offs;
    int		handleIdx;
    int		oldHIdxSize;
    int		moveToIdx;
    enum State { Idle, Sliding, Pressed, Moving, Blocked };
    State	state;
    QCOORD	clickPos;
    bool	trackingIsOn;
    int       cachedIdx; // not used
    int	cachedPos; // not used
    Orientation orient;

    QHeaderData *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QHeader( const QHeader & );
    QHeader &operator=( const QHeader & );
#endif
};

inline QHeader::Orientation QHeader::orientation() const
{
    return orient;
}

inline void QHeader::setTracking( bool enable ) { trackingIsOn = enable; }
inline bool QHeader::tracking() const { return trackingIsOn; }

#endif // QT_NO_HEADER

#endif // QHEADER_H

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QHeader成员列表

完整的QHeader成员列表

这里是QHeader成员函数的完整列表，包括继承的成员。

  • QHeader()
  • ~QHeader()
  • acceptDrops()
  • addLabel()
  • adjustHeaderSize()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • cellAt()
  • cellPos()
  • cellSize()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • headerWidth()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconSet()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexChange()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isClickEnabled()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isMovingEnabled()
  • isPopup()
  • isResizeEnabled()
  • isStretchEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • label()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToActual()
  • mapToGlobal()
  • mapToIndex()
  • mapToLogical()
  • mapToParent()
  • mapToSection()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveCell()
  • moveEvent()
  • moveSection()
  • moved()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • offset()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintSection()
  • paintSectionLabel()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • removeLabel()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • resizeSection()
  • sRect()
  • scroll()
  • sectionAt()
  • sectionClicked()
  • sectionPos()
  • sectionRect()
  • sectionSize()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellSize()
  • setClickEnabled()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLabel()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMovingEnabled()
  • setName()
  • setOffset()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setSortIndicator()
  • setStretchEnabled()
  • setStyle()
  • setTabOrder()
  • setTracking()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeChange()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • tracking()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QHebrewCodec Class

QHebrewCodec Class Reference

The QHebrewCodec class provides conversion to and from visually ordered Hebrew. More...

#include <qrtlcodec.h>

Inherits QTextCodec.

List of all member functions.

Public Members

  • virtual const char * mimeName () const
  • virtual QCString fromUnicode ( const QString & uc, int & len_in_out ) const

Detailed Description

The QHebrewCodec class provides conversion to and from visually ordered Hebrew.

Hebrew as a semitic language is written from right to left. Because older computer systems couldn't handle reordering a string so that the first letter appears on the right, many older documents were encoded in visual order, so that the first letter of a line is the rightmost one in the string.

In contrast to this, Unicode defines characters to be in logical order (the order you would read the string). This codec tries to convert visually ordered Hebrew (8859-8) to Unicode. This might not always work perfectly, because reversing the bidi (bi-directional) algorithm that transforms from logical to visual order is non-trivial.

Transformation from Unicode to visual Hebrew (8859-8) is done using the bidi algorithm in Qt, and will produce correct results, so long as the codec is given the text one whole paragraph at a time. Places where newlines are supposed to start can be indicated by a newline character ('\n'). Please be aware, that these newline characters change the reordering behaviour of the algorithm, as the BiDi reordering only takes place within one line of text, whereas linebreaks are determined in visual order.

Visually ordered Hebrew is still used quite often in some places, mainly in email communication (as most email programs still don't understand logically ordered Hebrew) and on web pages. The use on web pages is strongly decreasing however, as there are now a few browsers that correctly support logically ordered Hebrew.

This codec has the name "iso8859-8". If you don't want any bidi reordering to happen during conversion, use the "iso8859-8-i" codec, which assumes logical order for the 8-bit string.

See also Internationalization with Qt.

Member Function Documentation

QCString QHebrewCodec::fromUnicode ( const QString & uc, int & len_in_out ) const [virtual]

Transforms the logically ordered QString, uc, into a visually ordered string in the 8859-8 encoding. Qt's bidi algorithm is used to perform this task. Note that newline characters affect the reordering, as reordering is done on a line by line basis.

The algorithm is designed to work on whole paragraphs of text, so processing a line at a time may produce incorrect results. This approach is taken because the reordering of the contents of a particular line in a paragraph may depend on the previous line in the same paragraph.

Some encodings (for example Japanese or utf8) are multibye (so one input character is mapped to two output characters). The len_in_out argument specifies the number of QChars that should be converted and is set to the number of characters returned.

Reimplemented from QTextCodec.

const char * QHebrewCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


QHebrewCodec Member List

Complete Member List for QHebrewCodec

This is the complete list of member functions for QHebrewCodec, including inherited members.

  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QHGroupBox类

QHGroupBox类参考

QHGroupBox窗口部件把一组窗口部件组织在一个水平行中。 详情请见……

#include <qhgroupbox.h>

继承了QGroupBox。

所有成员函数的列表。

公有成员

  • QHGroupBox ( QWidget * parent = 0, const char * name = 0 )
  • QHGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • ~QHGroupBox ()

详细描述

QHGroupBox窗口部件把一组窗口部件组织在一个水平行中。

QHGroupBox是一个在QGroupBox中提供了一个小布局的方便类。可以把它看作适提供了一个框架和标题的QHBox。

也可以参考QVGroupBox、窗口部件外观和风格、布局管理和组织者。

成员函数文档

QHGroupBox::QHGroupBox ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的水平组合框。

parent和name参数被传递给QWidget构造函数。

QHGroupBox::QHGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的水平组合框。

parent和name参数被传递给QWidget构造函数。

QHGroupBox::~QHGroupBox ()

销毁这个水平组合框，删除它的子窗口部件。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qhgroupbox.h包含文件

qhgroupbox.h

这里是qhgroupbox.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/**********************************************************************
** $Id:  qt/qhgroupbox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QHGroupBox widget class
**
** Created : 990602
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHGROUPBOX_H
#define QHGROUPBOX_H

#ifndef QT_H
#include "qgroupbox.h"
#endif // QT_H

#ifndef QT_NO_HGROUPBOX

class Q_EXPORT QHGroupBox : public QGroupBox
{
    Q_OBJECT
public:
    QHGroupBox( QWidget* parent=0, const char* name=0 );
    QHGroupBox( const QString &title, QWidget* parent=0, const char* name=0 );
    ~QHGroupBox();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QHGroupBox( const QHGroupBox & );
    QHGroupBox &operator=( const QHGroupBox & );
#endif
};

#endif // QT_NO_HGROUPBOX

#endif // QHGROUPBOX_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QHGroupBox成员列表

完整的QHGroupBox成员列表

这里是QHGroupBox成员函数的完整列表，包括继承的成员。

  • QHGroupBox()
  • ~QHGroupBox()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QHideEvent Class

QHideEvent Class Reference

The QHideEvent class provides an event which is sent after a widget is hidden. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QHideEvent ()

Detailed Description

The QHideEvent class provides an event which is sent after a widget is hidden.

This event is sent just before QWidget::hide() returns, and also when a top-level window has been hidden (iconified) by the user.

If spontaneous() is TRUE the event originated outside the application, i.e. the user hid the window using the window manager controls, either by iconifying the window or by switching to another virtual desktop where the window isn't visible. The window will become hidden but not withdrawn. If the window was iconified, QWidget::isMinimized() returns TRUE.

See also QShowEvent and Event Classes.

Member Function Documentation

QHideEvent::QHideEvent ()

Constructs a QHideEvent.

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


QHideEvent Member List

Complete Member List for QHideEvent

This is the complete list of member functions for QHideEvent, including inherited members.

  • QHideEvent()
  • spontaneous()
  • type()


QHostAddress Class

QHostAddress Class Reference
[network module]

The QHostAddress class provides an IP address. More...

#include <qhostaddress.h>

List of all member functions.

Public Members

  • QHostAddress ()
  • QHostAddress ( Q_UINT32 ip4Addr )
  • QHostAddress ( Q_UINT8 * ip6Addr )
  • QHostAddress ( const QHostAddress & address )
  • virtual ~QHostAddress ()
  • QHostAddress & operator= ( const QHostAddress & address )
  • void setAddress ( Q_UINT32 ip4Addr )
  • void setAddress ( Q_UINT8 * ip6Addr )
  • bool setAddress ( const QString & address )
  • bool isIp4Addr () const
  • Q_UINT32 ip4Addr () const
  • QString toString () const
  • bool operator== ( const QHostAddress & other ) const

Detailed Description

The QHostAddress class provides an IP address.

This class contains an IP address in a platform and protocol independent manner. It stores both IPv4 and IPv6 addresses in a way that you can easily access on any platform. (Qt does not currently provide IPv6 support.)

QHostAddress is normally used with the classes QSocket, QServerSocket and QSocketDevice to set up a server or to connect to a host.

Host addresses may be set with setAddress() and retrieved with ip4Addr() or toString().

See also QSocket, QServerSocket, QSocketDevice and Input/Output and Networking.

Member Function Documentation

QHostAddress::QHostAddress ()

Creates a host address object with the IP address 0.0.0.0.

QHostAddress::QHostAddress ( Q_UINT32 ip4Addr )

Creates a host address object for the IPv4 address ip4Addr.

QHostAddress::QHostAddress ( Q_UINT8 * ip6Addr )

Creates a host address object with the specified IPv6 address.

ip6Addr must be a 16 byte array in network byte order (high-order byte first)

QHostAddress::QHostAddress ( const QHostAddress & address )

Creates a copy of address.

QHostAddress::~QHostAddress () [virtual]

Destroys the host address object.

Q_UINT32 QHostAddress::ip4Addr () const

Returns the IPv4 address as a number.

For example, if the address is 127.0.0.1, the returned value is 2130706433 (hex: 7f000001).

This value is only valid when isIp4Addr() returns TRUE.

See also toString().

bool QHostAddress::isIp4Addr () const

Returns TRUE if the host address represents a IPv4 address; otherwise returns FALSE.

QHostAddress & QHostAddress::operator= ( const QHostAddress & address )

Assigns another host address object address to this object and returns a reference to this object.

bool QHostAddress::operator== ( const QHostAddress & other ) const

Returns TRUE if this host address is the same as other; otherwise returns FALSE.

void QHostAddress::setAddress ( Q_UINT32 ip4Addr )

Set the IPv4 address specified by ip4Addr.

void QHostAddress::setAddress ( Q_UINT8 * ip6Addr )

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

Set the IPv6 address specified by ip6Addr.

ip6Addr must be a 16 byte array in network byte order (high-order byte first)

bool QHostAddress::setAddress ( const QString & address )

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

Sets the IPv4 or IPv6 address specified by the string representation address (e.g. "127.0.0.1"). Returns TRUE and sets the address if the address was successfully parsed; otherwise returns FALSE and leaves the address unchanged.

QString QHostAddress::toString () const

Returns the address as a string.

For example, if the address is the IPv4 address 127.0.0.1, the returned string is "127.0.0.1".

See also ip4Addr().

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


qhostaddress.h Include File

qhostaddress.h

This is the verbatim text of the qhostaddress.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qhostaddress.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QHostAddress class.
**
** Created : 979899
**
** Copyright (C) 1997-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHOSTADDRESS_H
#define QHOSTADDRESS_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_NETWORK
#else
#define QM_EXPORT_NETWORK Q_EXPORT
#endif

#ifndef QT_NO_NETWORK
class QHostAddressPrivate;

class QM_EXPORT_NETWORK QHostAddress
{
public:
    QHostAddress();
    QHostAddress( Q_UINT32 ip4Addr );
    QHostAddress( Q_UINT8 *ip6Addr );
    QHostAddress( const QHostAddress & );
    virtual ~QHostAddress();

    QHostAddress & operator=( const QHostAddress & );

    void setAddress( Q_UINT32 ip4Addr );
    void setAddress( Q_UINT8 *ip6Addr );
#ifndef QT_NO_STRINGLIST
    bool setAddress( const QString& address );
#endif
    bool	 isIp4Addr()	 const;
    Q_UINT32	 ip4Addr()	 const;
#ifndef QT_NO_SPRINTF
    QString	 toString() const;
#endif

    bool	 operator==( const QHostAddress & ) const;

private:
    QHostAddressPrivate* d;
};

#endif //QT_NO_NETWORK
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QHostAddress Member List

Complete Member List for QHostAddress

This is the complete list of member functions for QHostAddress, including inherited members.

  • QHostAddress()
  • ~QHostAddress()
  • ip4Addr()
  • isIp4Addr()
  • operator=()
  • operator==()
  • setAddress()
  • toString()


QHttp Class

QHttp Class Reference
[network module]

The QHttp class provides an implementation of the HTTP protocol. More...

#include <qhttp.h>

Inherits QNetworkProtocol.

List of all member functions.

Public Members

  • QHttp ()
  • virtual ~QHttp ()

Detailed Description

The QHttp class provides an implementation of the HTTP protocol.

This class is derived from QNetworkProtocol and can be used with QUrlOperator. In practice this class is used through a QUrlOperator rather than directly, for example:

  QUrlOperator op( "http://www.trolltech.com" );
  op.get( "index.html" );

Note: this code will only work if the QHttp class is registered; to register the class, you must call qInitNetworkProtocols() before using a QUrlOperator with HTTP.

QHttp only supports the operations operationGet() and operationPut(), i.e. QUrlOperator::get() and QUrlOperator::put(), if you use it with a QUrlOperator.

If you really need to use QHttp directly, don't forget to set the QUrlOperator on which it operates using setUrl().

See also Qt Network Documentation, QNetworkProtocol, QUrlOperator and Input/Output and Networking.

Member Function Documentation

QHttp::QHttp ()

Constructs a QHttp object. Usually there is no need to use QHttp directly, since it is more convenient to use it through a QUrlOperator. If you want to use it directly, you must set the QUrlOperator on which it operates using setUrl().

QHttp::~QHttp () [virtual]

Destroys the QHttp object.

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


qhttp.h Include File

qhttp.h

This is the verbatim text of the qhttp.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qhttp.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QHtpp and related classes.
**
** Created : 970521
**
** Copyright (C) 1997-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QHTTP_H
#define QHTTP_H

#ifndef QT_H
#include "qobject.h"
#include "qnetworkprotocol.h"
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_HTTP
#else
#define QM_EXPORT_HTTP Q_EXPORT
#endif

#ifndef QT_NO_NETWORKPROTOCOL_HTTP

class QSocket;
class QTimerEvent;
class QTextStream;
class QIODevice;

class QHttpReplyHeader;
class QHttpClient;
class QHttpPrivate;

class QM_EXPORT_HTTP QHttp : public QNetworkProtocol
{
    Q_OBJECT

public:
    QHttp();
    virtual ~QHttp();

    int supportedOperations() const;

protected:
    void operationGet( QNetworkOperation *op );
    void operationPut( QNetworkOperation *op );

private slots:
    void reply( const QHttpReplyHeader & rep, const QByteArray & dataA );
    void requestFinished();
    void requestFailed( int );
    void connected();
    void closed();
    void hostFound();

private:
    QHttpPrivate *d;
    QHttpClient *client;
    int bytesRead;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QHttp Member List

Complete Member List for QHttp

This is the complete list of member functions for QHttp, including inherited members.

  • QHttp()
  • ~QHttp()
  • addOperation()
  • autoDelete()
  • blockSignals()
  • checkConnectArgs()
  • checkConnection()
  • child()
  • childEvent()
  • children()
  • className()
  • clearOperationQueue()
  • connect()
  • connectNotify()
  • connectionStateChanged()
  • createdDirectory()
  • customEvent()
  • data()
  • dataTransferProgress()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • finished()
  • getNetworkProtocol()
  • hasOnlyLocalFileSystem()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemChanged()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • newChild()
  • newChildren()
  • normalizeSignalSlot()
  • objectTrees()
  • operationGet()
  • operationInProgress()
  • operationListChildren()
  • operationMkDir()
  • operationPut()
  • operationRemove()
  • operationRename()
  • parent()
  • property()
  • queryList()
  • registerNetworkProtocol()
  • removeChild()
  • removeEventFilter()
  • removed()
  • sender()
  • setAutoDelete()
  • setName()
  • setProperty()
  • setUrl()
  • signalsBlocked()
  • start()
  • startTimer()
  • stop()
  • supportedOperations()
  • timerEvent()
  • tr()
  • trUtf8()
  • url()


QIconDrag Class

QIconDrag Class Reference
[iconview module]

The QIconDrag class supports drag and drop operations within a QIconView. More...

#include <qiconview.h>

Inherits QDragObject.

List of all member functions.

Public Members

  • QIconDrag ( QWidget * dragSource, const char * name = 0 )
  • virtual ~QIconDrag ()
  • void append ( const QIconDragItem & i, const QRect & pr, const QRect & tr )
  • virtual QByteArray encodedData ( const char * mime ) const

Static Public Members

  • bool canDecode ( QMimeSource * e )

Detailed Description

The QIconDrag class supports drag and drop operations within a QIconView.

A QIconDrag object is used to maintain information about the positions of dragged items and the data associated with the dragged items. QIconViews are able to use this information to paint the dragged items in the correct positions. Internally QIconDrag stores the data associated with drag items in QIconDragItem objects.

If you want to use the extended drag-and-drop functionality of QIconView, create a QIconDrag object in a reimplementation of QIconView::dragObject(). Then create a QIconDragItem for each item which should be dragged, set the data it represents with QIconDragItem::setData(), and add each QIconDragItem to the drag object using append().

The data in QIconDragItems is stored in a QByteArray and is mime-typed (see QMimeSource and the Drag and Drop overview). If you want to use your own mime-types derive a class from QIconDrag and reimplement format(), encodedData() and canDecode().

The fileiconview example program demonstrates the use of the QIconDrag class including subclassing and reimplementing dragObject(), format(), encodedData() and canDecode(). See the files qt/examples/fileiconview/qfileiconview.h and qt/examples/fileiconview/qfileiconview.cpp.

See also QMimeSource::format() and Drag And Drop Classes.

Member Function Documentation

QIconDrag::QIconDrag ( QWidget * dragSource, const char * name = 0 )

Constructs a drag object called name, which is a child of dragSource.

Note that the drag object will be deleted when dragSource is deleted.

QIconDrag::~QIconDrag () [virtual]

Destructor.

void QIconDrag::append ( const QIconDragItem & i, const QRect & pr, const QRect & tr )

Append the QIconDragItem, i, to the QIconDrag object's list of items. You must also supply the geometry of the pixmap, pr, and the textual caption, tr.

See also QIconDragItem.

Example: fileiconview/qfileiconview.cpp.

bool QIconDrag::canDecode ( QMimeSource * e ) [static]

Returns TRUE if e can be decoded by the QIconDrag, otherwise return FALSE.

Example: fileiconview/qfileiconview.cpp.

QByteArray QIconDrag::encodedData ( const char * mime ) const [virtual]

Returns the encoded data of the drag object if mime is application/x-qiconlist.

Example: fileiconview/qfileiconview.cpp.

Reimplemented from QMimeSource.

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


QIconDrag Member List

Complete Member List for QIconDrag

This is the complete list of member functions for QIconDrag, including inherited members.

  • QIconDrag()
  • ~QIconDrag()
  • append()
  • blockSignals()
  • canDecode()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setName()
  • setPixmap()
  • setProperty()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


QIconDragItem Class

QIconDragItem Class Reference
[iconview module]

The QIconDragItem class encapsulates a drag item. More...

#include <qiconview.h>

List of all member functions.

Public Members

  • QIconDragItem ()
  • virtual ~QIconDragItem ()
  • virtual QByteArray data () const
  • virtual void setData ( const QByteArray & d )

Detailed Description

The QIconDragItem class encapsulates a drag item.

The QIconDrag class uses a list of QIconDragItems to support drag and drop operations.

In practice a QIconDragItem object (or an object of a class derived from QIconDragItem) is created for each icon view item which is dragged. Each of these QIconDragItems is stored in a QIconDrag object.

See QIconView::dragObject() for more information.

See the fileiconview/qfileiconview.cpp and iconview/simple_dd/main.cpp examples.

See also Drag And Drop Classes.

Member Function Documentation

QIconDragItem::QIconDragItem ()

Constructs a QIconDragItem with no data.

QIconDragItem::~QIconDragItem () [virtual]

Destructor.

QByteArray QIconDragItem::data () const [virtual]

Returns the data contained in the QIconDragItem.

void QIconDragItem::setData ( const QByteArray & d ) [virtual]

Sets the data for the QIconDragItem to the data stored in the QByteArray d.

Example: fileiconview/qfileiconview.cpp.

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


QIconDragItem Member List

Complete Member List for QIconDragItem

This is the complete list of member functions for QIconDragItem, including inherited members.

  • QIconDragItem()
  • ~QIconDragItem()
  • data()
  • setData()


QIconSet Class

QIconSet Class Reference

The QIconSet class provides a set of icons with different styles and sizes. More...

#include <qiconset.h>

List of all member functions.

Public Members

  • enum Size { Automatic, Small, Large }
  • enum Mode { Normal, Disabled, Active }
  • enum State { On, Off }
  • QIconSet ()
  • QIconSet ( const QPixmap & pixmap, Size size = Automatic )
  • QIconSet ( const QPixmap & smallPix, const QPixmap & largePix )
  • QIconSet ( const QIconSet & other )
  • virtual ~QIconSet ()
  • void reset ( const QPixmap & pm, Size size )
  • virtual void setPixmap ( const QPixmap & pm, Size size, Mode mode = Normal, State state = Off )
  • virtual void setPixmap ( const QString & fileName, Size size, Mode mode = Normal, State state = Off )
  • QPixmap pixmap ( Size size, Mode mode, State state = Off ) const
  • QPixmap pixmap ( Size size, bool enabled, State state = Off ) const
  • QPixmap pixmap () const
  • bool isGenerated ( Size size, Mode mode, State state = Off ) const
  • void clearGenerated ()
  • bool isNull () const
  • void detach ()
  • QIconSet & operator= ( const QIconSet & other )

Static Public Members

  • void setIconSize ( Size s, const QSize & size )
  • const QSize & iconSize ( Size s )

Detailed Description

The QIconSet class provides a set of icons with different styles and sizes.

A QIconSet can generate smaller, larger, active, and disabled pixmaps from the set of icons it is given. Such pixmaps are used by QToolButton, QHeader, QPopupMenu, etc. to show an icon representing a particular action.

The simplest use of QIconSet is to create one from a QPixmap and then use it, allowing Qt to work out all the required icon styles and sizes. For example:

  QToolButton *tb = new QToolButton( QIconSet( QPixmap("open.xpm") ), ... );

Using whichever pixmap(s) you specify as a base, QIconSet provides a set of six icons, each with a Size and a Mode:

  • Small Normal - can only be calculated from Large Normal.
  • Small Disabled - calculated from Large Disabled or Small Normal.
  • Small Active - same as Small Normal unless you set it.
  • Large Normal - can only be calculated from Small Normal.
  • Large Disabled - calculated from Small Disabled or Large Normal.
  • Large Active - same as Large Normal unless you set it.

An additional set of six icons can be provided for widgets that have an "On" or "Off" state, like checkable menu items or toggleable toolbuttons. If you provide pixmaps for the "On" state, but not for the "Off" state, the QIconSet will provide the "Off" pixmaps. You may specify icons for both states in you wish. For best results for calculated pixmaps, you should supply a 22 x 22 pixel pixmap.

You can set any of the icons using setPixmap().

When you retrieve a pixmap using pixmap(Size,Mode,State), QIconSet will return the icon that has been set or previously generated for that size, mode and state combination. If no pixmap has been set or previously generated for the combination QIconSet will generate a pixmap based on the pixmap(s) it has been given, cache the generated pixmap for later use, and return it. The isGenerated() function returns TRUE if an icon was generated by QIconSet.

The Disabled appearance is computed using a "shadow" algorithm that produces results very similar to those used in Microsoft Windows 95.

The Active appearance is identical to the Normal appearance unless you use setPixmap() to set it to something special.

When scaling icons, QIconSet uses smooth scaling, which can partially blend the color component of pixmaps. If the results look poor, the best solution is to supply pixmaps in both large and small sizes.

You can use the static function setIconSize() to set the preferred size of the generated large/small icons. The default small size is 22x22 (compatible with Qt 2.x), while the default large size is 32x32. Please note that these sizes only affect generated icons.

QIconSet provides a function, isGenerated(), that indicates whether an icon was set by the application programmer or computed by QIconSet itself.

Making Classes that use QIconSet

If you write your own widgets that have an option to set a small pixmap, consider allowing a QIconSet to be set for that pixmap. The Qt class QToolButton is an example of such a widget.

Provide a method to set a QIconSet, and when you draw the icon, choose whichever icon is appropriate for the current state of your widget. For example:

  void MyWidget::drawIcon( QPainter* p, QPoint pos )
  {
      p->drawPixmap( pos, icons->pixmap(QIconSet::Small, isEnabled()) );
  }

You might also make use of the Active mode, perhaps making your widget Active when the mouse is over the widget (see QWidget::enterEvent()), while the mouse is pressed pending the release that will activate the function, or when it is the currently selected item. If the widget can be toggled, the "On" mode might be used to draw a different icon.

See also QPixmap, QLabel, QToolButton, QPopupMenu, QMainWindow::usesBigPixmaps, GUI Design Handbook: Iconic Label, Microsoft Icon Gallery, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Type Documentation

QIconSet::Mode

This enum type describes the mode for which a pixmap is intended to be used. The currently defined modes are:

  • QIconSet::Normal - Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.
  • QIconSet::Disabled - Display the pixmap when the functionality represented by the icon is not available.
  • QIconSet::Active - Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

QIconSet::Size

This enum type describes the size at which a pixmap is intended to be used. The currently defined sizes are:

  • QIconSet::Automatic - The size of the pixmap is determined from its pixel size. This is a useful default.
  • QIconSet::Small - The pixmap is the smaller of two.
  • QIconSet::Large - The pixmap is the larger of two.

If a Small pixmap is not set by QIconSet::setPixmap(), the Large pixmap will be automatically scaled down to the size of a small pixmap to generate the Small pixmap when required. Similarly, a Small pixmap will be automatically scaled up to generate a Large pixmap. The preferred sizes for large/small generated icons can be set using setIconSize().

See also setIconSize(), iconSize(), setPixmap(), pixmap() and QMainWindow::usesBigPixmaps.

QIconSet::State

This enum describes the state for which a pixmap is intended to be used. The state can be:

  • QIconSet::Off - Display the pixmap when the widget is in an "off" state
  • QIconSet::On - Display the pixmap when the widget is in an "on" state

See also setPixmap() and pixmap().

Member Function Documentation

QIconSet::QIconSet ()

Constructs a null icon set. Use setPixmap(), reset(), or operator=() to set some pixmaps.

See also reset().

QIconSet::QIconSet ( const QPixmap & pixmap, Size size = Automatic )

Constructs an icon set for which the Normal pixmap is pixmap, which is assumed to be of size size.

The default for size is Automatic, which means that QIconSet will determine whether the pixmap is Small or Large from its pixel size. Pixmaps less than the width of a small generated icon are considered to be Small. You can use setIconSize() to set the preferred size of a generated icon.

See also setIconSize() and reset().

QIconSet::QIconSet ( const QPixmap & smallPix, const QPixmap & largePix )

Creates an iconset which uses the pixmap smallPix for for displaying a small icon, and the pixmap largePix for displaying a large icon.

QIconSet::QIconSet ( const QIconSet & other )

Constructs a copy of other. This is very fast.

QIconSet::~QIconSet () [virtual]

Destroys the icon set and frees any allocated resources.

void QIconSet::clearGenerated ()

Clears all generated pixmaps.

void QIconSet::detach ()

Detaches this icon set from others with which it may share data.

You will never need to call this function; other QIconSet functions call it as necessary.

const QSize & QIconSet::iconSize ( Size s ) [static]

If s is Small, returns the preferred size of a small generated icon; if s is Large, returns the preferred size of a large generated icon.

See also setIconSize().

bool QIconSet::isGenerated ( Size size, Mode mode, State state = Off ) const

Returns TRUE if the pixmap with size size, mode mode and state state has been generated; otherwise returns FALSE.

bool QIconSet::isNull () const

Returns TRUE if the icon set is empty; otherwise returns FALSE.

QIconSet & QIconSet::operator= ( const QIconSet & other )

Assigns other to this icon set and returns a reference to this icon set.

This is very fast.

See also detach().

QPixmap QIconSet::pixmap ( Size size, Mode mode, State state = Off ) const

Returns a pixmap with size size, mode mode and state state, generating one if necessary. Generated pixmaps are cached.

QPixmap QIconSet::pixmap ( Size size, bool enabled, State state = Off ) const

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

Returns a pixmap with size size, state state and a Mode which is Normal if enabled is TRUE, or Disabled if enabled is FALSE.

QPixmap QIconSet::pixmap () const

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

Returns the pixmap originally provided to the constructor or to reset(). This is the Normal pixmap of unspecified Size.

See also reset().

void QIconSet::reset ( const QPixmap & pm, Size size )

Sets this icon set to use pixmap pm for the Normal pixmap, assuming it to be of size size.

This is equivalent to assigning QIconSet(pm, size) to this icon set.

This function does nothing if pm is a null pixmap.

void QIconSet::setIconSize ( Size s, const QSize & size ) [static]

Set the preferred size for all small or large icons that are generated after this call. If s is Small, sets the preferred size of small generated icons to size. Similarly, if s is Large, sets the preferred size of large generated icons to size.

Note that cached icons will not be regenerated, so it is recommended that you set the preferred icon sizes before generating any icon sets. Also note that the preferred icon sizes will be ignored for icon sets that have been created using both small and large pixmaps.

See also iconSize().

void QIconSet::setPixmap ( const QPixmap & pm, Size size, Mode mode = Normal, State state = Off ) [virtual]

Sets this icon set to provide pixmap pm for size size, mode mode and state state. The icon set may also use pm for generating other pixmaps if they are not explicitly set.

The size can be one of Automatic, Large or Small. If Automatic is used, QIconSet will determine if the pixmap is Small or Large from its pixel size.

Pixmaps less than the width of a small generated icon are considered to be Small. You can use setIconSize() to set the preferred size of a generated icon.

This function does nothing if pm is a null pixmap.

See also reset().

void QIconSet::setPixmap ( const QString & fileName, Size size, Mode mode = Normal, State state = Off ) [virtual]

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

Sets this icon set to load the file called fileName as a pixmap and use it for size size, mode mode and state state. The icon set may also use this pixmap for generating other pixmaps if they are not explicitly set.

The size can be one of Automatic, Large or Small. If Automatic is used, QIconSet will determine if the pixmap is Small or Large from its pixel size. Pixmaps less than the width of a small generated icon are considered to be Small. You can use setIconSize() to set the preferred size of a generated icon.

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


qiconset.h Include File

qiconset.h

This is the verbatim text of the qiconset.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QIconSet class
**
** Created : 980318
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QICONSET_H
#define QICONSET_H

#ifndef QT_H
#include "qpixmap.h"
#endif // QT_H

#ifndef QT_NO_ICONSET

class QIconSetPrivate;

class Q_EXPORT QIconSet
{
public:
    enum Size { Automatic, Small, Large };

    enum Mode { Normal, Disabled, Active };

    enum State { On, Off };

    QIconSet();
    QIconSet( const QPixmap &, Size = Automatic );
    QIconSet( const QPixmap &smallPix, const QPixmap &largePix );
    QIconSet( const QIconSet & );
    virtual ~QIconSet();

    void reset( const QPixmap &, Size );

    virtual void setPixmap( const QPixmap &, Size, Mode = Normal, State = Off );
    virtual void setPixmap( const QString &, Size, Mode = Normal, State = Off );
    QPixmap pixmap( Size, Mode, State = Off ) const;
    QPixmap pixmap( Size s, bool enabled, State = Off ) const;
    QPixmap pixmap() const;
    bool isGenerated( Size, Mode, State = Off ) const;
    void clearGenerated();

    bool isNull() const;

    void detach();

    QIconSet &operator=( const QIconSet & );

    // static functions
    static void setIconSize( Size, const QSize & );
    static const QSize & iconSize( Size );

#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const QIconSet& ) const { return FALSE; }
#endif

private:
    QIconSetPrivate * d;
};

#endif // QT_NO_ICONSET
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QIconSet Member List

Complete Member List for QIconSet

This is the complete list of member functions for QIconSet, including inherited members.

  • QIconSet()
  • ~QIconSet()
  • clearGenerated()
  • detach()
  • iconSize()
  • isGenerated()
  • isNull()
  • operator=()
  • pixmap()
  • reset()
  • setIconSize()
  • setPixmap()


QIconView Class

QIconView Class Reference
[iconview module]

The QIconView class provides an area with movable labelled icons. More...

#include <qiconview.h>

Inherits QScrollView.

List of all member functions.

Public Members

  • enum SelectionMode { Single = 0, Multi, Extended, NoSelection }
  • enum Arrangement { LeftToRight = 0, TopToBottom }
  • enum ResizeMode { Fixed = 0, Adjust }
  • enum ItemTextPos { Bottom = 0, Right }
  • QIconView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • virtual ~QIconView ()
  • virtual void insertItem ( QIconViewItem * item, QIconViewItem * after = 0L )
  • virtual void takeItem ( QIconViewItem * item )
  • int index ( const QIconViewItem * item ) const
  • QIconViewItem * firstItem () const
  • QIconViewItem * lastItem () const
  • QIconViewItem * currentItem () const
  • virtual void setCurrentItem ( QIconViewItem * item )
  • virtual void setSelected ( QIconViewItem * item, bool s, bool cb = FALSE )
  • uint count () const
  • virtual void setSelectionMode ( SelectionMode m )
  • SelectionMode selectionMode () const
  • QIconViewItem * findItem ( const QPoint & pos ) const
  • QIconViewItem * findItem ( const QString & text, ComparisonFlags compare = BeginsWith ) const
  • virtual void selectAll ( bool select )
  • virtual void clearSelection ()
  • virtual void invertSelection ()
  • virtual void repaintItem ( QIconViewItem * item )
  • void ensureItemVisible ( QIconViewItem * item )
  • QIconViewItem * findFirstVisibleItem ( const QRect & r ) const
  • QIconViewItem * findLastVisibleItem ( const QRect & r ) const
  • virtual void clear ()
  • virtual void setGridX ( int rx )
  • virtual void setGridY ( int ry )
  • int gridX () const
  • int gridY () const
  • virtual void setSpacing ( int sp )
  • int spacing () const
  • virtual void setItemTextPos ( ItemTextPos pos )
  • ItemTextPos itemTextPos () const
  • virtual void setItemTextBackground ( const QBrush & b )
  • QBrush itemTextBackground () const
  • virtual void setArrangement ( Arrangement am )
  • Arrangement arrangement () const
  • virtual void setResizeMode ( ResizeMode am )
  • ResizeMode resizeMode () const
  • virtual void setMaxItemWidth ( int w )
  • int maxItemWidth () const
  • virtual void setMaxItemTextLength ( int w )
  • int maxItemTextLength () const
  • virtual void setAutoArrange ( bool b )
  • bool autoArrange () const
  • virtual void setShowToolTips ( bool b )
  • bool showToolTips () const
  • void setSorting ( bool sort, bool ascending = TRUE )
  • bool sorting () const
  • bool sortDirection () const
  • virtual void setItemsMovable ( bool b )
  • bool itemsMovable () const
  • virtual void setWordWrapIconText ( bool b )
  • bool wordWrapIconText () const
  • virtual void sort ( bool ascending = TRUE )
  • bool isRenaming () const

Public Slots

  • virtual void arrangeItemsInGrid ( const QSize & grid, bool update = TRUE )
  • virtual void arrangeItemsInGrid ( bool update = TRUE )

Signals

  • void selectionChanged ()
  • void selectionChanged ( QIconViewItem * item )
  • void currentChanged ( QIconViewItem * item )
  • void clicked ( QIconViewItem * item )
  • void clicked ( QIconViewItem * item, const QPoint & pos )
  • void pressed ( QIconViewItem * item )
  • void pressed ( QIconViewItem * item, const QPoint & pos )
  • void doubleClicked ( QIconViewItem * item )
  • void returnPressed ( QIconViewItem * item )
  • void rightButtonClicked ( QIconViewItem * item, const QPoint & pos )
  • void rightButtonPressed ( QIconViewItem * item, const QPoint & pos )
  • void mouseButtonPressed ( int button, QIconViewItem * item, const QPoint & pos )
  • void mouseButtonClicked ( int button, QIconViewItem * item, const QPoint & pos )
  • void contextMenuRequested ( QIconViewItem * item, const QPoint & pos )
  • void dropped ( QDropEvent * e, const QValueList<QIconDragItem> & lst )
  • void moved ()
  • void onItem ( QIconViewItem * item )
  • void onViewport ()
  • void itemRenamed ( QIconViewItem * item, const QString & name )
  • void itemRenamed ( QIconViewItem * item )

Properties

  • Arrangement arrangement - the arrangement mode of the icon view
  • bool autoArrange - whether the icon view rearranges its items when a new item is inserted
  • uint count - the number of items in the icon view (read only)
  • int gridX - the horizontal grid of the icon view
  • int gridY - the vertical grid of the icon view
  • QBrush itemTextBackground - the brush to use when drawing the background of an item's text
  • ItemTextPos itemTextPos - the position where the text of each item is drawn
  • bool itemsMovable - whether the user is allowed to move items around in the icon view
  • int maxItemTextLength - the maximum length (in characters) that an item's text may have
  • int maxItemWidth - the maximum width that an item may have
  • ResizeMode resizeMode - the resize mode of the icon view
  • SelectionMode selectionMode - the selection mode of the icon view
  • bool showToolTips - whether the icon view will display a tool tip with the complete text for any truncated item text
  • bool sortDirection - whether the sort direction for inserting new items is ascending; (read only)
  • bool sorting - whether the icon view sorts on insertion (read only)
  • int spacing - the space in pixels between icon view items
  • bool wordWrapIconText - whether the item text will be word-wrapped if it is too long

Protected Members

  • virtual void drawRubber ( QPainter * p )
  • virtual QDragObject * dragObject ()
  • virtual void startDrag ()
  • virtual void insertInGrid ( QIconViewItem * item )
  • virtual void drawBackground ( QPainter * p, const QRect & r )
  • void emitSelectionChanged ( QIconViewItem * i = 0 )
  • QIconViewItem * makeRowLayout ( QIconViewItem * begin, int & y, bool & changed )

Protected Slots

  • virtual void doAutoScroll ()
  • virtual void adjustItems ()
  • virtual void slotUpdate ()

Detailed Description

The QIconView class provides an area with movable labelled icons.

A QIconView can display and manage a grid or other 2D layout of labelled icons. Each labelled icon is a QIconViewItem. Items (QIconViewItems) can be added or deleted at any time; items can be moved within the QIconView. Single or multiple items can be selected. Items can be renamed in-place. QIconView also supports drag and drop.

Each item contains a label string, a pixmap or picture (the icon itself) and optionally a sort key. The sort key is used for sorting the items and defaults to the label string. The label string can be displayed below or to the right of the icon (see ItemTextPos).

The simplest way to create a QIconView is to create a QIconView object and create some QIconViewItems with the QIconView as their parent, set the icon view's geometry and show it. For example:

    QIconView *iv = new QIconView( this );
    QDir dir( path, "*.xpm" );
    for ( uint i = 0; i < dir.count(); i++ ) {
        (void) new QIconViewItem( iv, dir[i], QPixmap( path + dir[i] ) );
    }
    iv->resize( 600, 400 );
    iv->show();

The QIconViewItem call passes a pointer to the QIconView we wish to populate, along with the label text and a QPixmap.

When an item is inserted the QIconView allocates a position for it. Existing items are rearranged if autoArrange() is TRUE. The default arrangement is LeftToRight -- the QIconView fills up the left-most column from top to bottom, then moves one column right and fills that from top to bottom and so on. The arrangement can be modified with any of the following approaches:

  • Call setArrangement(), e.g. with TopToBottom which will fill the top-most row from left to right, then moves one row down and fills that row from left to right and so on.
  • Construct each QIconViewItem using a constructor which allows you to specify which item the new one is to follow.
  • Call setSorting() or sort() to sort the items.

The spacing between items is set with setSpacing(). Items can be laid out using a fixed grid using setGridX() and setGridY(); by default the QIconView calculates a grid dynamically. The position of items' label text is set with setItemTextPos(). The text's background can be set with setItemTextBackground(). The maximum width of an item and of its text are set with setMaxItemWidth() and setMaxItemTextLength(). The label text will be word-wrapped if it is too long; this is controlled by setWordWrapIconText(). If the label text is truncated, the user can still see the entire text in a tool tip if they hover the mouse over the item. This is controlled with setShowToolTips().

Items which are selectable may be selected depending on the SelectionMode; the default is Single. Because QIconView offers multiple selection it must display keyboard focus and selection state separately. Therefore there are functions to set the selection state of an item (setSelected()) and to select which item displays keyboard focus (setCurrentItem()). When multiple items may be selected the icon view provides a rubberband, too.

When in-place renaming is enabled (it is disabled by default), the user may change the item's label. They do this by selecting the item (single clicking it or navigating to it with the arrow keys), then single clicking it (or pressing F2), and entering their text. If no key has been set with QIconViewItem::setKey() the new text will also serve as the key. (See QIconViewItem::setRenameEnabled().)

You can control whether users can move items themselves with setItemsMovable().

Because the internal structure used to store the icon view items is linear, no iterator class is needed to iterate over all the items. Instead we iterate by getting the first item from the icon view and then each subsequent (QIconViewItem::nextItem()) from each item in turn:

        for ( QIconViewItem *item = iv->firstItem(); item; item = item->nextItem() )
            do_something( item );
QIconView also provides currentItem(). You can search for an item using findItem() (searching by position or for label text) and with findFirstVisibleItem() and findLastVisibleItem(). The number of items is returned by count(). An item can be removed from an icon view using takeItem(); to delete an item use delete. All the items can be deleted with clear().

The QIconView emits a wide range of useful signals, including selectionChanged(), currentChanged(), clicked(), moved() and itemRenamed().

Drag and Drop

QIconView supports the drag and drop of items within the QIconView itself. It also supports the drag and drop of items out of or into the QIconView and drag and drop onto items themselves. The drag and drop of items outside the QIconView can be achieved in a simple way with basic functionality, or in a more sophisticated way which provides more power and control.

The simple approach to dragging items out of the icon view is to subclass QIconView and reimplement QIconView::dragObject().

    QDragObject *MyIconView::dragObject()
    {
        return new QTextDrag( currentItem()->text(), this );
    }

In this example we create a QTextDrag object, (derived from QDragObject), containing the item's label and return it as the drag object. We could just as easily have created a QImageDrag from the item's pixmap and returned that instead.

QIconViews and their QIconViewItems can also be the targets of drag and drops. To make the QIconView itself able to accept drops connect to the dropped() signal. When a drop occurs this signal will be emitted with a QDragEvent and a QValueList of QIconDragItems. To make a QIconViewItem into a drop target subclass QIconViewItem and reimplement QIconViewItem::acceptDrop() and QIconViewItem::dropped().

    bool MyIconViewItem::acceptDrop( const QMimeSource *mime ) const
    {
        if ( mime->provides( "text/plain" ) )
            return TRUE;
        return FALSE;
    }

    void MyIconViewItem::dropped( QDropEvent *evt, const QValueList<QIconDragItem>& )
    {
        QString label;
        if ( QTextDrag::decode( evt, label ) )
            setText( label );
    }

See iconview/simple_dd/main.h and iconview/simple_dd/main.cpp for a simple drag and drop example which demonstrates drag and drop between a QIconView and a QListBox.

If you want to use extended drag-and-drop or have drag shapes drawn you must take a more sophisticated approach.

The first part is starting drags -- you should use a QIconDrag (or a class derived from it) for the drag object. In dragObject() create the drag object, populate it with QIconDragItems and return it. Normally such a drag should offer each selected item's data. So in dragObject() you should iterate over all the items, and create a QIconDragItem for each selected item, and append these items with QIconDrag::append() to the QIconDrag object. You can use QIconDragItem::setData() to set the data of each item that should be dragged. If you want to offer the data in additional mime-types, it's best to use a class derived from QIconDrag, which implements additional encoding and decoding functions.

When a drag enters the icon view, there is little to do. Simply connect to the dropped() signal and reimplement QIconViewItem::acceptDrop() and QIconViewItem::dropped(). If you've used a QIconDrag (or a subclass of it) the second argument to the dropped signal contains a QValueList of QIconDragItems -- you can access their data by calling QIconDragItem::data() on each one.

For an example implementation of complex drag-and-drop look at the qfileiconview example (qt/examples/qfileiconview).

See also QIconViewItem::setDragEnabled(), QIconViewItem::setDropEnabled(), QIconViewItem::acceptDrop(), QIconViewItem::dropped() and Advanced Widgets.

Member Type Documentation

QIconView::Arrangement

This enum type determines in which direction the items flow when the view runs out of space.

  • QIconView::LeftToRight - Items which don't fit into the view go further down (you get a vertical scrollbar)
  • QIconView::TopToBottom - Items which don't fit into the view go further right (you get a horizontal scrollbar)

QIconView::ItemTextPos

This enum type specifies the position of the item text in relation to the icon.

  • QIconView::Bottom - The text is drawn below the icon.
  • QIconView::Right - The text is drawn to the right of the icon.

QIconView::ResizeMode

This enum type is used to tell QIconView how it should treat the positions of its icons when the widget is resized. The modes are:

  • QIconView::Fixed - The icons' positions are not changed.
  • QIconView::Adjust - The icons' positions are adjusted to be within the new geometry, if possible.

QIconView::SelectionMode

This enumerated type is used by QIconView to indicate how it reacts to selection by the user. It has four values:

  • QIconView::Single - When the user selects an item, any already-selected item becomes unselected and the user cannot unselect the selected item. This means that the user can never clear the selection. (The application programmer can, using QIconView::clearSelection().)
  • QIconView::Multi - When the user selects an item, e.g. by navigating to it with the keyboard arrow keys or by clicking it, the selection status of that item is toggled and the other items are left alone.
  • QIconView::Extended - When the user selects an item the selection is cleared and the new item selected. However, if the user presses the Ctrl key when clicking on an item, the clicked item gets toggled and all other items are left untouched. If the user presses the Shift key while clicking on an item, all items between the current item and the clicked item get selected or unselected, depending on the state of the clicked item. Also, multiple items can be selected by dragging the mouse while the left mouse button stays pressed.
  • QIconView::NoSelection - Items cannot be selected.

To summarise: Single is a real single-selection icon view; Multi a real multi-selection icon view; Extended is an icon view in which users can select multiple items but usually want to select either just one or a range of contiguous items; and NoSelection mode is for an icon view where the user can look but not touch.

Member Function Documentation

QIconView::QIconView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs an empty icon view called name, with parent parent and using the widget flags f.

QIconView::~QIconView () [virtual]

Destroys the icon view and deletes all items.

void QIconView::adjustItems () [virtual protected slot]

Adjusts the positions of the items to the geometry of the icon view.

void QIconView::arrangeItemsInGrid ( const QSize & grid, bool update = TRUE ) [virtual slot]

This variant uses grid instead of (gridX(), gridY()). If grid is invalid (see QSize::isValid()), arrangeItemsInGrid() calculates a valid grid itself and uses that.

If update is TRUE (the default) the viewport is repainted.

Example: fileiconview/qfileiconview.h.

void QIconView::arrangeItemsInGrid ( bool update = TRUE ) [virtual slot]

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

Arranges all the items in the grid given by gridX() and gridY().

Even if sorting() is enabled, the items are not sorted by this function. If you want to sort or rearrange the items, use iconview->sort(iconview->sortDirection()).

If update is TRUE (the default), the viewport is repainted as well.

See also QIconView::gridX, QIconView::gridY and QIconView::sort().

Arrangement QIconView::arrangement () const

Returns the arrangement mode of the icon view. See the "arrangement" property for details.

bool QIconView::autoArrange () const

Returns TRUE if the icon view rearranges its items when a new item is inserted; otherwise returns FALSE. See the "autoArrange" property for details.

void QIconView::clear () [virtual]

Clears the icon view. All items are deleted.

void QIconView::clearSelection () [virtual]

Unselects all the items.

void QIconView::clicked ( QIconViewItem * item ) [signal]

This signal is emitted when the user clicks any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

See also mouseButtonClicked(), rightButtonClicked() and pressed().

void QIconView::clicked ( QIconViewItem * item, const QPoint & pos ) [signal]

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

This signal is emitted when the user clicks any mouse button on an icon view item. item is a pointer to the item that has been clicked.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pos is the position at release time.)

See also mouseButtonClicked(), rightButtonClicked() and pressed().

void QIconView::contextMenuRequested ( QIconViewItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user invokes a context menu with the right mouse button or with special system keys, with item being the item under the mouse cursor or the current item, respectively.

pos is the position for the context menu in the global coordinate system.

uint QIconView::count () const

Returns the number of items in the icon view. See the "count" property for details.

void QIconView::currentChanged ( QIconViewItem * item ) [signal]

This signal is emitted when a new item becomes current. item is the new current item (or 0 if no item is now current).

See also currentItem().

QIconViewItem * QIconView::currentItem () const

Returns a pointer to the current item of the icon view, or 0 if no item is current.

See also setCurrentItem(), firstItem() and lastItem().

void QIconView::doAutoScroll () [virtual protected slot]

Performs autoscrolling when selecting multiple icons with the rubber band.

void QIconView::doubleClicked ( QIconViewItem * item ) [signal]

This signal is emitted when the user double-clicks on item.

QDragObject * QIconView::dragObject () [virtual protected]

Returns the QDragObject that should be used for drag-and-drop. This function is called by the icon view when starting a drag to get the dragobject that should be used for the drag. Subclasses may reimplement this.

See also QIconDrag.

Examples: fileiconview/qfileiconview.cpp and iconview/simple_dd/main.cpp.

void QIconView::drawBackground ( QPainter * p, const QRect & r ) [virtual protected]

This function is called to draw the rectangle r of the background using the painter p.

The default implementation fills r with the viewport's backgroundBrush(). Subclasses may reimplement this to draw custom backgrounds.

See also contentsX, contentsY and drawContents().

void QIconView::drawRubber ( QPainter * p ) [virtual protected]

Draws the rubber band using the painter p.

void QIconView::dropped ( QDropEvent * e, const QValueList<QIconDragItem> & lst ) [signal]

This signal is emitted when a drop event occurs in the viewport (but not on any icon) which the icon view itself can't handle.

e provides all the information about the drop. If the drag object of the drop was a QIconDrag, lst contains the list of the dropped items. You can get the data using QIconDragItem::data() on each item. If the lst is empty, i.e. the drag was not a QIconDrag, you have to decode the data in e and work with that.

Note QIconViewItems may be drop targets; if a drop event occurs on an item the item handles the drop.

Examples: iconview/main.cpp and iconview/simple_dd/main.cpp.

void QIconView::emitSelectionChanged ( QIconViewItem * i = 0 ) [protected]

Emits a signal to indicate selection changes. i is the QIconViewItem that was selected or de-selected.

You should never need to call this function.

void QIconView::ensureItemVisible ( QIconViewItem * item )

Makes sure that item is entirely visible. If necessary, ensureItemVisible() scrolls the icon view.

See also ensureVisible().

QIconViewItem * QIconView::findFirstVisibleItem ( const QRect & r ) const

Finds the first item whose bounding rectangle overlaps r and returns a pointer to that item. r is given in content coordinates. Returns 0 if no item overlaps r.

If you want to find all items that touch r, you will need to use this function and nextItem() in a loop ending at findLastVisibleItem() and test QItem::rect() for each of these items.

See also findLastVisibleItem() and QIconViewItem::rect().

QIconViewItem * QIconView::findItem ( const QPoint & pos ) const

Returns a pointer to the item that contains point pos, which is given in contents coordinates, or 0 if no item contains point pos.

QIconViewItem * QIconView::findItem ( const QString & text, ComparisonFlags compare = BeginsWith ) const

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

Returns a pointer to the first item whose text begins with text, or 0 if no such item could be found. Use the compare flag to control the comparison behaviour. (See Qt::StringComparisonMode.)

QIconViewItem * QIconView::findLastVisibleItem ( const QRect & r ) const

Finds the last item whose bounding rectangle overlaps r and returns a pointer to that item. r is given in content coordinates. Returns 0 if no item overlaps r.

See also findFirstVisibleItem().

QIconViewItem * QIconView::firstItem () const

Returns a pointer to the first item of the icon view, or 0 if there are no items in the icon view.

See also lastItem() and currentItem().

int QIconView::gridX () const

Returns the horizontal grid of the icon view. See the "gridX" property for details.

int QIconView::gridY () const

Returns the vertical grid of the icon view. See the "gridY" property for details.

int QIconView::index ( const QIconViewItem * item ) const

Returns the index of item, or -1 if item doesn't exist in this icon view.

void QIconView::insertInGrid ( QIconViewItem * item ) [virtual protected]

Inserts the QIconViewItem item in the icon view's grid. You should never need to call this function. Instead, insert QIconViewItems by creating them with a pointer to the QIconView that they are to be inserted into.

void QIconView::insertItem ( QIconViewItem * item, QIconViewItem * after = 0L ) [virtual]

Inserts the icon view item item after after. If after is 0, item is appended after the last item.

You should never need to call this function. Instead create QIconViewItem's and associate them with your icon view like this:

        (void) new QIconViewItem( myIconview, "The text of the item", aPixmap );

void QIconView::invertSelection () [virtual]

Inverts the selection. Works only in Multi and Extended selection mode.

bool QIconView::isRenaming () const

Returns TRUE if an iconview item is being renamed; otherwise returns FALSE.

void QIconView::itemRenamed ( QIconViewItem * item, const QString & name ) [signal]

This signal is emitted when item has been renamed to name, usually by in-place renaming.

See also QIconViewItem::setRenameEnabled() and QIconViewItem::rename().

void QIconView::itemRenamed ( QIconViewItem * item ) [signal]

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

This signal is emitted when item has been renamed, usually by in-place renaming.

See also QIconViewItem::setRenameEnabled() and QIconViewItem::rename().

QBrush QIconView::itemTextBackground () const

Returns the brush to use when drawing the background of an item's text. See the "itemTextBackground" property for details.

ItemTextPos QIconView::itemTextPos () const

Returns the position where the text of each item is drawn. See the "itemTextPos" property for details.

bool QIconView::itemsMovable () const

Returns TRUE if the user is allowed to move items around in the icon view; otherwise returns FALSE. See the "itemsMovable" property for details.

QIconViewItem * QIconView::lastItem () const

Returns a pointer to the last item of the icon view, or 0 if there are no items in the icon view.

See also firstItem() and currentItem().

QIconViewItem * QIconView::makeRowLayout ( QIconViewItem * begin, int & y, bool & changed ) [protected]

Lays out a row of icons (if Arrangement == TopToBottom this is a column). Starts laying out with the item begin. y is the starting coordinate. Returns the last item of the row (column) and sets the new starting coordinate to y. The changed parameter is used internally.

Warning: This function may be made private in a future version of Qt. We do not recommend calling it.

int QIconView::maxItemTextLength () const

Returns the maximum length (in characters) that an item's text may have. See the "maxItemTextLength" property for details.

int QIconView::maxItemWidth () const

Returns the maximum width that an item may have. See the "maxItemWidth" property for details.

void QIconView::mouseButtonClicked ( int button, QIconViewItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user clicks mouse button button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pos is the position at release time.)

See also mouseButtonPressed(), rightButtonClicked() and clicked().

void QIconView::mouseButtonPressed ( int button, QIconViewItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user presses mouse button button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()).

See also rightButtonClicked() and pressed().

void QIconView::moved () [signal]

This signal is emitted after successfully dropping one (or more) items of the icon view. If the items should be removed, it's best to do so in a slot connected to this signal.

Example: iconview/main.cpp.

void QIconView::onItem ( QIconViewItem * item ) [signal]

This signal is emitted when the user moves the mouse cursor onto an item, similar to the QWidget::enterEvent() function.

void QIconView::onViewport () [signal]

This signal is emitted when the user moves the mouse cursor from an item to an empty part of the icon view.

See also onItem().

void QIconView::pressed ( QIconViewItem * item ) [signal]

This signal is emitted when the user presses any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

See also mouseButtonPressed(), rightButtonPressed() and clicked().

void QIconView::pressed ( QIconViewItem * item, const QPoint & pos ) [signal]

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

This signal is emitted when the user presses any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pos is the position at release time.)

See also mouseButtonPressed(), rightButtonPressed() and clicked().

void QIconView::repaintItem ( QIconViewItem * item ) [virtual]

Repaints the item.

ResizeMode QIconView::resizeMode () const

Returns the resize mode of the icon view. See the "resizeMode" property for details.

void QIconView::returnPressed ( QIconViewItem * item ) [signal]

This signal is emitted if the user presses the Return or Enter key. item is the currentItem() at the time of the keypress.

void QIconView::rightButtonClicked ( QIconViewItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user clicks the right mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pos is the position at release time.)

See also rightButtonPressed(), mouseButtonClicked() and clicked().

void QIconView::rightButtonPressed ( QIconViewItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user presses the right mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()).

void QIconView::selectAll ( bool select ) [virtual]

In Multi and Extended modes, this function sets all items to be selected if select is TRUE, and to be unselected if select is FALSE.

In Single and NoSelection modes, this function only changes the selection status of currentItem().

void QIconView::selectionChanged () [signal]

This signal is emitted when the selection has been changed. It's emitted in each selection mode.

void QIconView::selectionChanged ( QIconViewItem * item ) [signal]

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

This signal is emitted when the selection changes. item is the newly selected item. This signal is emitted only in single selection mode.

SelectionMode QIconView::selectionMode () const

Returns the selection mode of the icon view. See the "selectionMode" property for details.

void QIconView::setArrangement ( Arrangement am ) [virtual]

Sets the arrangement mode of the icon view to am. See the "arrangement" property for details.

void QIconView::setAutoArrange ( bool b ) [virtual]

Sets whether the icon view rearranges its items when a new item is inserted to b. See the "autoArrange" property for details.

void QIconView::setCurrentItem ( QIconViewItem * item ) [virtual]

Makes item the new current item of the icon view.

void QIconView::setGridX ( int rx ) [virtual]

Sets the horizontal grid of the icon view to rx. See the "gridX" property for details.

void QIconView::setGridY ( int ry ) [virtual]

Sets the vertical grid of the icon view to ry. See the "gridY" property for details.

void QIconView::setItemTextBackground ( const QBrush & b ) [virtual]

Sets the brush to use when drawing the background of an item's text to b. See the "itemTextBackground" property for details.

void QIconView::setItemTextPos ( ItemTextPos pos ) [virtual]

Sets the position where the text of each item is drawn to pos. See the "itemTextPos" property for details.

void QIconView::setItemsMovable ( bool b ) [virtual]

Sets whether the user is allowed to move items around in the icon view to b. See the "itemsMovable" property for details.

void QIconView::setMaxItemTextLength ( int w ) [virtual]

Sets the maximum length (in characters) that an item's text may have to w. See the "maxItemTextLength" property for details.

void QIconView::setMaxItemWidth ( int w ) [virtual]

Sets the maximum width that an item may have to w. See the "maxItemWidth" property for details.

void QIconView::setResizeMode ( ResizeMode am ) [virtual]

Sets the resize mode of the icon view to am. See the "resizeMode" property for details.

void QIconView::setSelected ( QIconViewItem * item, bool s, bool cb = FALSE ) [virtual]

Selects or unselects item depending on s, and may also unselect other items, depending on QIconView::selectionMode() and cb.

If s is FALSE, item is unselected.

If s is TRUE and QIconView::selectionMode() is Single, item is selected, and the item which was selected is unselected.

If s is TRUE and QIconView::selectionMode() is Extended, item is selected. If cb is TRUE, the selection state of the icon view's other items is left unchanged. If cb is FALSE (the default) all other items are unselected.

If s is TRUE and QIconView::selectionMode() is Multi item is selected.

Note that cb is used only if QIconView::selectionMode() is Extended. cb defaults to FALSE.

All items whose selection status is changed repaint themselves.

void QIconView::setSelectionMode ( SelectionMode m ) [virtual]

Sets the selection mode of the icon view to m. See the "selectionMode" property for details.

void QIconView::setShowToolTips ( bool b ) [virtual]

Sets whether the icon view will display a tool tip with the complete text for any truncated item text to b. See the "showToolTips" property for details.

void QIconView::setSorting ( bool sort, bool ascending = TRUE )

If sort is TRUE, this function sets the icon view to sort items when a new item is inserted. If sort is FALSE, the icon view will not be sorted.

Note that autoArrange() must be TRUE for sorting to take place.

If ascending is TRUE (the default), items are sorted in ascending order. If ascending is FALSE, items are sorted in descending order.

QIconViewItem::compare() is used to compare pairs of items. The sorting is based on the items' keys; these default to the items' text unless specifically set to something else.

See also QIconView::autoArrange, QIconView::autoArrange, sortDirection, sort() and QIconViewItem::setKey().

void QIconView::setSpacing ( int sp ) [virtual]

Sets the space in pixels between icon view items to sp. See the "spacing" property for details.

void QIconView::setWordWrapIconText ( bool b ) [virtual]

Sets whether the item text will be word-wrapped if it is too long to b. See the "wordWrapIconText" property for details.

bool QIconView::showToolTips () const

Returns TRUE if the icon view will display a tool tip with the complete text for any truncated item text; otherwise returns FALSE. See the "showToolTips" property for details.

void QIconView::slotUpdate () [virtual protected slot]

This slot is used for a slightly-delayed update.

The icon view is not redrawn immediately after inserting a new item but after a very small delay using a QTimer. This means that when many items are inserted in a loop the icon view is probably redrawn only once at the end of the loop. This makes the insertions both flicker-free and faster.

void QIconView::sort ( bool ascending = TRUE ) [virtual]

Sorts and rearranges all the items in the icon view. If ascending is TRUE, the items are sorted in increasing order, otherwise they are sorted in decreasing order.

QIconViewItem::compare() is used to compare pairs of items. The sorting is based on the items' keys; these default to the items' text unless specifically set to something else.

Note that this function sets the sort order to ascending.

See also QIconViewItem::key(), QIconViewItem::setKey(), QIconViewItem::compare(), QIconView::setSorting() and QIconView::sortDirection.

bool QIconView::sortDirection () const

Returns TRUE if the sort direction for inserting new items is ascending;; otherwise returns FALSE. See the "sortDirection" property for details.

bool QIconView::sorting () const

Returns TRUE if the icon view sorts on insertion; otherwise returns FALSE. See the "sorting" property for details.

int QIconView::spacing () const

Returns the space in pixels between icon view items. See the "spacing" property for details.

void QIconView::startDrag () [virtual protected]

Starts a drag.

void QIconView::takeItem ( QIconViewItem * item ) [virtual]

Takes the icon view item item out of the icon view and causes an update of the screen display. The item is not deleted. You should normally not need to call this function because QIconViewItem::~QIconViewItem() calls it. The normal way to delete an item is to delete it.

bool QIconView::wordWrapIconText () const

Returns TRUE if the item text will be word-wrapped if it is too long; otherwise returns FALSE. See the "wordWrapIconText" property for details.

Property Documentation

Arrangement arrangement

This property holds the arrangement mode of the icon view.

This can be LeftToRight or TopToBottom. The default is LeftToRight.

Set this property's value with setArrangement() and get this property's value with arrangement().

bool autoArrange

This property holds whether the icon view rearranges its items when a new item is inserted.

The default is TRUE.

Note that if the icon view is not visible at the time of insertion, QIconView defers all position-related work until it is shown and then calls arrangeItemsInGrid().

Set this property's value with setAutoArrange() and get this property's value with autoArrange().

uint count

This property holds the number of items in the icon view.

Get this property's value with count().

int gridX

This property holds the horizontal grid of the icon view.

If the value is -1, (the default), QIconView computes suitable column widths based on the icon view's contents.

Note that setting a grid width overrides setMaxItemWidth().

Set this property's value with setGridX() and get this property's value with gridX().

int gridY

This property holds the vertical grid of the icon view.

If the value is -1, (the default), QIconView computes suitable column heights based on the icon view's contents.

Set this property's value with setGridY() and get this property's value with gridY().

QBrush itemTextBackground

This property holds the brush to use when drawing the background of an item's text.

By default this brush is set to NoBrush, meaning that only the normal icon view background is used.

Set this property's value with setItemTextBackground() and get this property's value with itemTextBackground().

ItemTextPos itemTextPos

This property holds the position where the text of each item is drawn.

Valid values are Bottom or Right. The default is Bottom.

Set this property's value with setItemTextPos() and get this property's value with itemTextPos().

bool itemsMovable

This property holds whether the user is allowed to move items around in the icon view.

The default is TRUE.

Set this property's value with setItemsMovable() and get this property's value with itemsMovable().

int maxItemTextLength

This property holds the maximum length (in characters) that an item's text may have.

The default is 255 characters.

Set this property's value with setMaxItemTextLength() and get this property's value with maxItemTextLength().

int maxItemWidth

This property holds the maximum width that an item may have.

The default is 100 pixels.

Note that if the gridX() value is set QIconView will ignore this property.

Set this property's value with setMaxItemWidth() and get this property's value with maxItemWidth().

ResizeMode resizeMode

This property holds the resize mode of the icon view.

This can be Fixed or Adjust. The default is Fixed. See ResizeMode.

Set this property's value with setResizeMode() and get this property's value with resizeMode().

SelectionMode selectionMode

This property holds the selection mode of the icon view.

This can be Single (the default), Extended, Multi or NoSelection.

Set this property's value with setSelectionMode() and get this property's value with selectionMode().

bool showToolTips

This property holds whether the icon view will display a tool tip with the complete text for any truncated item text.

The default is TRUE. Note that this has no effect if setWordWrapIconText() is TRUE, as it is by default.

Set this property's value with setShowToolTips() and get this property's value with showToolTips().

bool sortDirection

This property holds whether the sort direction for inserting new items is ascending;.

The default is TRUE (i.e. ascending). This sort direction is only meaningful if both sorting() and autoArrange() are TRUE.

To set the sort direction, use setSorting()

Get this property's value with sortDirection().

bool sorting

This property holds whether the icon view sorts on insertion.

The default is FALSE, i.e. no sorting on insertion.

To set the soring, use setSorting().

Get this property's value with sorting().

int spacing

This property holds the space in pixels between icon view items.

The default is 5 pixels.

Negative values for spacing are illegal.

Set this property's value with setSpacing() and get this property's value with spacing().

bool wordWrapIconText

This property holds whether the item text will be word-wrapped if it is too long.

The default is TRUE.

If this property is FALSE, icon text that is too long is truncated, and an ellipsis (...) appended to indicate that truncation has occurred. The full text can still be seen by the user if they hover the mouse because the full text is shown in a tooltip; see setShowToolTips().

Set this property's value with setWordWrapIconText() and get this property's value with wordWrapIconText().

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


qiconview.h Include File

qiconview.h

This is the verbatim text of the qiconview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qiconview.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QIconView widget class
**
** Created : 990707
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the iconview module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QICONVIEW_H
#define QICONVIEW_H

#ifndef QT_H
#include <qscrollview.h>
#include <qstring.h>
#include <qrect.h>
#include <qpoint.h>
#include <qsize.h>
#include <qfont.h> // QString->QFont conversion
#include <qdragobject.h>
#include <qbitmap.h>
#include <qpicture.h>
#endif // QT_H

#ifndef QT_NO_ICONVIEW

#if !defined( QT_MODULE_ICONVIEW ) || defined( QT_INTERNAL_ICONVIEW )
#define QM_EXPORT_ICONVIEW
#else
#define QM_EXPORT_ICONVIEW Q_EXPORT
#endif

class QIconView;
class QPainter;
class QMimeSource;
class QMouseEvent;
class QDragEnterEvent;
class QDragMoveEvent;
class QDragLeaveEvent;
class QKeyEvent;
class QFocusEvent;
class QShowEvent;
class QIconViewItem;
class QIconViewItemLineEdit;
class QStringList;
class QIconDragPrivate;

#ifndef QT_NO_DRAGANDDROP

class QM_EXPORT_ICONVIEW QIconDragItem
{
public:
    QIconDragItem();
    virtual ~QIconDragItem();
    virtual QByteArray data() const;
    virtual void setData( const QByteArray &d );
    bool operator== ( const QIconDragItem& ) const;

private:
    QByteArray ba;

};

class QM_EXPORT_ICONVIEW QIconDrag : public QDragObject
{
    Q_OBJECT
public:
    QIconDrag( QWidget * dragSource, const char* name = 0 );
    virtual ~QIconDrag();

    void append( const QIconDragItem &item, const QRect &pr, const QRect &tr );

    virtual const char* format( int i ) const;
    static bool canDecode( QMimeSource* e );
    virtual QByteArray encodedData( const char* mime ) const;

private:
    QIconDragPrivate *d;
    QChar endMark;

    friend class QIconView;
    friend class QIconViewPrivate;
};

#endif

class QIconViewToolTip;
class QIconViewItemPrivate;

class QM_EXPORT_ICONVIEW QIconViewItem : public Qt
{
    friend class QIconView;
    friend class QIconViewToolTip;
    friend class QIconViewItemLineEdit;

public:
    QIconViewItem( QIconView *parent );
    QIconViewItem( QIconView *parent, QIconViewItem *after );
    QIconViewItem( QIconView *parent, const QString &text );
    QIconViewItem( QIconView *parent, QIconViewItem *after, const QString &text );
    QIconViewItem( QIconView *parent, const QString &text, const QPixmap &icon );
    QIconViewItem( QIconView *parent, QIconViewItem *after, const QString &text, const QPixmap &icon );
#ifndef QT_NO_PICTURE
    QIconViewItem( QIconView *parent, const QString &text, const QPicture &picture );
    QIconViewItem( QIconView *parent, QIconViewItem *after, const QString &text, const QPicture &picture );
#endif
    virtual ~QIconViewItem();

    virtual void setRenameEnabled( bool allow );
    virtual void setDragEnabled( bool allow );
    virtual void setDropEnabled( bool allow );

    virtual QString text() const;
    virtual QPixmap *pixmap() const;
#ifndef QT_NO_PICTURE
    virtual QPicture *picture() const;
#endif
    virtual QString key() const;

    bool renameEnabled() const;
    bool dragEnabled() const;
    bool dropEnabled() const;

    QIconView *iconView() const;
    QIconViewItem *prevItem() const;
    QIconViewItem *nextItem() const;

    int index() const;

    virtual void setSelected( bool s, bool cb );
    virtual void setSelected( bool s );
    virtual void setSelectable( bool s );

    bool isSelected() const;
    bool isSelectable() const;

    virtual void repaint();

    virtual bool move( int x, int y );
    virtual void moveBy( int dx, int dy );
    virtual bool move( const QPoint &pnt );
    virtual void moveBy( const QPoint &pnt );

    QRect rect() const;
    int x() const;
    int y() const;
    int width() const;
    int height() const;
    QSize size() const;
    QPoint pos() const;
    QRect textRect( bool relative = TRUE ) const;
    QRect pixmapRect( bool relative = TRUE ) const;
    bool contains( const QPoint& pnt ) const;
    bool intersects( const QRect& r ) const;

    virtual bool acceptDrop( const QMimeSource *mime ) const;

#ifndef QT_NO_TEXTEDIT
    void rename();
#endif

    virtual int compare( QIconViewItem *i ) const;

    virtual void setText( const QString &text );
    virtual void setPixmap( const QPixmap &icon );
#ifndef QT_NO_PICTURE
    virtual void setPicture( const QPicture &icon );
#endif
    virtual void setText( const QString &text, bool recalc, bool redraw = TRUE );
    virtual void setPixmap( const QPixmap &icon, bool recalc, bool redraw = TRUE );
    virtual void setKey( const QString &k );

    virtual int rtti() const;
    static int RTTI;

protected:
#ifndef QT_NO_TEXTEDIT
    virtual void removeRenameBox();
#endif
    virtual void calcRect( const QString &text_ = QString::null );
    virtual void paintItem( QPainter *p, const QColorGroup &cg );
    virtual void paintFocus( QPainter *p, const QColorGroup &cg );
#ifndef QT_NO_DRAGANDDROP
    virtual void dropped( QDropEvent *e, const QValueList<QIconDragItem> &lst );
#endif
    virtual void dragEntered();
    virtual void dragLeft();
    void setItemRect( const QRect &r );
    void setTextRect( const QRect &r );
    void setPixmapRect( const QRect &r );
    void calcTmpText();

private:
    void init( QIconViewItem *after = 0
#ifndef QT_NO_PICTURE
           , QPicture *pic = 0
#endif
           );
#ifndef QT_NO_TEXTEDIT
    void renameItem();
    void cancelRenameItem();
#endif
    void checkRect();

    QIconView *view;
    QString itemText, itemKey;
    QString tmpText;
    QPixmap *itemIcon;
#ifndef QT_NO_PICTURE
    QPicture *itemPic;
#endif
    QIconViewItem *prev, *next;
    uint allow_rename : 1;
    uint allow_drag : 1;
    uint allow_drop : 1;
    uint selected : 1;
    uint selectable : 1;
    uint dirty : 1;
    uint wordWrapDirty : 1;
    QRect itemRect, itemTextRect, itemIconRect;
#ifndef QT_NO_TEXTEDIT
    QIconViewItemLineEdit *renameBox;
#endif
    QRect oldRect;

    QIconViewItemPrivate *d;

};

class QIconViewPrivate;          /* don't touch */

class QM_EXPORT_ICONVIEW QIconView : public QScrollView
{
    friend class QIconViewItem;
    friend class QIconViewPrivate;
    friend class QIconViewToolTip;

    Q_OBJECT
    // #### sorting and sort direction do not work
    Q_ENUMS( SelectionMode ItemTextPos Arrangement ResizeMode )
    Q_PROPERTY( bool sorting READ sorting )
    Q_PROPERTY( bool sortDirection READ sortDirection )
    Q_PROPERTY( SelectionMode selectionMode READ selectionMode WRITE setSelectionMode )
    Q_PROPERTY( int gridX READ gridX WRITE setGridX )
    Q_PROPERTY( int gridY READ gridY WRITE setGridY )
    Q_PROPERTY( int spacing READ spacing WRITE setSpacing )
    Q_PROPERTY( ItemTextPos itemTextPos READ itemTextPos WRITE setItemTextPos )
    Q_PROPERTY( QBrush itemTextBackground READ itemTextBackground WRITE setItemTextBackground )
    Q_PROPERTY( Arrangement arrangement READ arrangement WRITE setArrangement )
    Q_PROPERTY( ResizeMode resizeMode READ resizeMode WRITE setResizeMode )
    Q_PROPERTY( int maxItemWidth READ maxItemWidth WRITE setMaxItemWidth )
    Q_PROPERTY( int maxItemTextLength READ maxItemTextLength WRITE setMaxItemTextLength )
    Q_PROPERTY( bool autoArrange READ autoArrange WRITE setAutoArrange )
    Q_PROPERTY( bool itemsMovable READ itemsMovable WRITE setItemsMovable )
    Q_PROPERTY( bool wordWrapIconText READ wordWrapIconText WRITE setWordWrapIconText )
    Q_PROPERTY( bool showToolTips READ showToolTips WRITE setShowToolTips )
    Q_PROPERTY( uint count READ count )

public:
    enum SelectionMode {
    Single = 0,
    Multi,
    Extended,
    NoSelection
    };
    enum Arrangement {
    LeftToRight = 0,
    TopToBottom
    };
    enum ResizeMode {
    Fixed = 0,
    Adjust
    };
    enum ItemTextPos {
    Bottom = 0,
    Right
    };

    QIconView( QWidget* parent=0, const char* name=0, WFlags f = 0 );
    virtual ~QIconView();

    virtual void insertItem( QIconViewItem *item, QIconViewItem *after = 0L );
    virtual void takeItem( QIconViewItem *item );

    int index( const QIconViewItem *item ) const;

    QIconViewItem *firstItem() const;
    QIconViewItem *lastItem() const;
    QIconViewItem *currentItem() const;
    virtual void setCurrentItem( QIconViewItem *item );
    virtual void setSelected( QIconViewItem *item, bool s, bool cb = FALSE );

    uint count() const;

public:
    virtual void showEvent( QShowEvent * );

    virtual void setSelectionMode( SelectionMode m );
    SelectionMode selectionMode() const;

    QIconViewItem *findItem( const QPoint &pos ) const;
    QIconViewItem *findItem( const QString &text, ComparisonFlags compare = BeginsWith ) const;
    virtual void selectAll( bool select );
    virtual void clearSelection();
    virtual void invertSelection();

    virtual void repaintItem( QIconViewItem *item );

    void ensureItemVisible( QIconViewItem *item );
    QIconViewItem* findFirstVisibleItem( const QRect &r ) const;
    QIconViewItem* findLastVisibleItem( const QRect &r ) const;

    virtual void clear();

    virtual void setGridX( int rx );
    virtual void setGridY( int ry );
    int gridX() const;
    int gridY() const;
    virtual void setSpacing( int sp );
    int spacing() const;
    virtual void setItemTextPos( ItemTextPos pos );
    ItemTextPos itemTextPos() const;
    virtual void setItemTextBackground( const QBrush &b );
    QBrush itemTextBackground() const;
    virtual void setArrangement( Arrangement am );
    Arrangement arrangement() const;
    virtual void setResizeMode( ResizeMode am );
    ResizeMode resizeMode() const;
    virtual void setMaxItemWidth( int w );
    int maxItemWidth() const;
    virtual void setMaxItemTextLength( int w );
    int maxItemTextLength() const;
    virtual void setAutoArrange( bool b );
    bool autoArrange() const;
    virtual void setShowToolTips( bool b );
    bool showToolTips() const;

    void setSorting( bool sort, bool ascending = TRUE );
    bool sorting() const;
    bool sortDirection() const;

    virtual void setItemsMovable( bool b );
    bool itemsMovable() const;
    virtual void setWordWrapIconText( bool b );
    bool wordWrapIconText() const;

    bool eventFilter( QObject * o, QEvent * );

    QSize minimumSizeHint() const;
    QSize sizeHint() const;

    virtual void sort( bool ascending = TRUE );

    virtual void setFont( const QFont & );
    virtual void setPalette( const QPalette & );

    bool isRenaming() const;

public slots:
    virtual void arrangeItemsInGrid( const QSize &grid, bool update = TRUE );
    virtual void arrangeItemsInGrid( bool update = TRUE );
    virtual void setContentsPos( int x, int y );
    virtual void updateContents();

signals:
    void selectionChanged();
    void selectionChanged( QIconViewItem *item );
    void currentChanged( QIconViewItem *item );
    void clicked( QIconViewItem * );
    void clicked( QIconViewItem *, const QPoint & );
    void pressed( QIconViewItem * );
    void pressed( QIconViewItem *, const QPoint & );

    void doubleClicked( QIconViewItem *item );
    void returnPressed( QIconViewItem *item );
    void rightButtonClicked( QIconViewItem* item, const QPoint& pos );
    void rightButtonPressed( QIconViewItem* item, const QPoint& pos );
    void mouseButtonPressed( int button, QIconViewItem* item, const QPoint& pos );
    void mouseButtonClicked( int button, QIconViewItem* item, const QPoint& pos );
    void contextMenuRequested( QIconViewItem* item, const QPoint &pos );

#ifndef QT_NO_DRAGANDDROP
    void dropped( QDropEvent *e, const QValueList<QIconDragItem> &lst );
#endif
    void moved();
    void onItem( QIconViewItem *item );
    void onViewport();
    void itemRenamed( QIconViewItem *item, const QString & );
    void itemRenamed( QIconViewItem *item );

protected slots:
    virtual void doAutoScroll();
    virtual void adjustItems();
    virtual void slotUpdate();

private slots:
    void clearInputString();
    void movedContents( int dx, int dy );

protected:
    void drawContents( QPainter *p, int cx, int cy, int cw, int ch );
    void contentsMousePressEvent( QMouseEvent *e );
    void contentsMouseReleaseEvent( QMouseEvent *e );
    void contentsMouseMoveEvent( QMouseEvent *e );
    void contentsMouseDoubleClickEvent( QMouseEvent *e );
    void contentsContextMenuEvent( QContextMenuEvent *e );

#ifndef QT_NO_DRAGANDDROP
    void contentsDragEnterEvent( QDragEnterEvent *e );
    void contentsDragMoveEvent( QDragMoveEvent *e );
    void contentsDragLeaveEvent( QDragLeaveEvent *e );
    void contentsDropEvent( QDropEvent *e );
#endif

    void resizeEvent( QResizeEvent* e );
    void keyPressEvent( QKeyEvent *e );
    void focusInEvent( QFocusEvent *e );
    void focusOutEvent( QFocusEvent *e );
    void enterEvent( QEvent *e );

    virtual void drawRubber( QPainter *p );
#ifndef QT_NO_DRAGANDDROP
    virtual QDragObject *dragObject();
    virtual void startDrag();
#endif
    virtual void insertInGrid( QIconViewItem *item );
    virtual void drawBackground( QPainter *p, const QRect &r );

    void emitSelectionChanged( QIconViewItem * i = 0 );
    void emitRenamed( QIconViewItem *item );

    QIconViewItem *makeRowLayout( QIconViewItem *begin, int &y, bool &changed );

    void styleChange( QStyle& );
    void windowActivationChange( bool );

private:
    void contentsMousePressEventEx( QMouseEvent *e );
    virtual void drawDragShapes( const QPoint &pnt );
#ifndef QT_NO_DRAGANDDROP
    virtual void initDragEnter( QDropEvent *e );
#endif
    void drawContents( QPainter* );
    void findItemByName( const QString &text );
    void handleItemChange( QIconViewItem *old, bool shift, bool control );

    int calcGridNum( int w, int x ) const;
    QIconViewItem *rowBegin( QIconViewItem *item ) const;
    void updateItemContainer( QIconViewItem *item );
    void appendItemContainer();
    void rebuildContainers();
    QBitmap mask( QPixmap *pix ) const;

    QIconViewPrivate *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QIconView( const QIconView & );
    QIconView& operator=( const QIconView & );
#endif
};

#endif // QT_NO_ICONVIEW

#endif // QICONVIEW_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QIconView Member List

Complete Member List for QIconView

This is the complete list of member functions for QIconView, including inherited members.

  • QIconView()
  • ~QIconView()
  • acceptDrops()
  • addChild()
  • adjustItems()
  • adjustSize()
  • arrangeItemsInGrid()
  • arrangement()
  • autoArrange()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • caption()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearSelection()
  • clearWFlags()
  • clicked()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • contextMenuRequested()
  • cornerWidget()
  • count()
  • create()
  • currentChanged()
  • currentItem()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doAutoScroll()
  • doubleClicked()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • dragObject()
  • drawBackground()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawRubber()
  • drawText()
  • dropEvent()
  • dropped()
  • dumpObjectInfo()
  • dumpObjectTree()
  • emitSelectionChanged()
  • enableClipper()
  • enabledChange()
  • ensureItemVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • findFirstVisibleItem()
  • findItem()
  • findLastVisibleItem()
  • firstItem()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • gridX()
  • gridY()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • index()
  • inherits()
  • insertChild()
  • insertInGrid()
  • insertItem()
  • installEventFilter()
  • invertSelection()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isRenaming()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • itemRenamed()
  • itemTextBackground()
  • itemTextPos()
  • itemsMovable()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • lastItem()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • makeRowLayout()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maxItemTextLength()
  • maxItemWidth()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseButtonClicked()
  • mouseButtonPressed()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • moved()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • onItem()
  • onViewport()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintContents()
  • repaintItem()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizeMode()
  • resizePolicy()
  • returnPressed()
  • rightButtonClicked()
  • rightButtonPressed()
  • rightMargin()
  • scroll()
  • scrollBy()
  • selectAll()
  • selectionChanged()
  • selectionMode()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setArrangement()
  • setAutoArrange()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentItem()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setGridX()
  • setGridY()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItemTextBackground()
  • setItemTextPos()
  • setItemsMovable()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaxItemTextLength()
  • setMaxItemWidth()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeMode()
  • setResizePolicy()
  • setSelected()
  • setSelectionMode()
  • setShowToolTips()
  • setSizeIncrement()
  • setSizePolicy()
  • setSorting()
  • setSpacing()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • setWordWrapIconText()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showToolTips()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • slotUpdate()
  • sort()
  • sortDirection()
  • sorting()
  • spacing()
  • stackUnder()
  • startDrag()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • takeItem()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrapIconText()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QIconViewItem Class

QIconViewItem Class Reference
[iconview module]

The QIconViewItem class provides a single item in a QIconView. More...

#include <qiconview.h>

Inherits Qt.

List of all member functions.

Public Members

  • QIconViewItem ( QIconView * parent )
  • QIconViewItem ( QIconView * parent, QIconViewItem * after )
  • QIconViewItem ( QIconView * parent, const QString & text )
  • QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text )
  • QIconViewItem ( QIconView * parent, const QString & text, const QPixmap & icon )
  • QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text, const QPixmap & icon )
  • QIconViewItem ( QIconView * parent, const QString & text, const QPicture & picture )
  • QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text, const QPicture & picture )
  • virtual ~QIconViewItem ()
  • virtual void setRenameEnabled ( bool allow )
  • virtual void setDragEnabled ( bool allow )
  • virtual void setDropEnabled ( bool allow )
  • virtual QString text () const
  • virtual QPixmap * pixmap () const
  • virtual QPicture * picture () const
  • virtual QString key () const
  • bool renameEnabled () const
  • bool dragEnabled () const
  • bool dropEnabled () const
  • QIconView * iconView () const
  • QIconViewItem * prevItem () const
  • QIconViewItem * nextItem () const
  • int index () const
  • virtual void setSelected ( bool s, bool cb )
  • virtual void setSelected ( bool s )
  • virtual void setSelectable ( bool enable )
  • bool isSelected () const
  • bool isSelectable () const
  • virtual void repaint ()
  • virtual bool move ( int x, int y )
  • virtual void moveBy ( int dx, int dy )
  • virtual bool move ( const QPoint & pnt )
  • virtual void moveBy ( const QPoint & pnt )
  • QRect rect () const
  • int x () const
  • int y () const
  • int width () const
  • int height () const
  • QSize size () const
  • QPoint pos () const
  • QRect textRect ( bool relative = TRUE ) const
  • QRect pixmapRect ( bool relative = TRUE ) const
  • bool contains ( const QPoint & pnt ) const
  • bool intersects ( const QRect & r ) const
  • virtual bool acceptDrop ( const QMimeSource * mime ) const
  • void rename ()
  • virtual int compare ( QIconViewItem * i ) const
  • virtual void setText ( const QString & text )
  • virtual void setPixmap ( const QPixmap & icon )
  • virtual void setPicture ( const QPicture & icon )
  • virtual void setText ( const QString & text, bool recalc, bool redraw = TRUE )
  • virtual void setPixmap ( const QPixmap & icon, bool recalc, bool redraw = TRUE )
  • virtual void setKey ( const QString & k )
  • virtual int rtti () const

Protected Members

  • virtual void removeRenameBox ()
  • virtual void calcRect ( const QString & text_ = QString::null )
  • virtual void paintItem ( QPainter * p, const QColorGroup & cg )
  • virtual void paintFocus ( QPainter * p, const QColorGroup & cg )
  • virtual void dropped ( QDropEvent * e, const QValueList<QIconDragItem> & lst )
  • virtual void dragEntered ()
  • virtual void dragLeft ()
  • void setItemRect ( const QRect & r )
  • void setTextRect ( const QRect & r )
  • void setPixmapRect ( const QRect & r )

Detailed Description

The QIconViewItem class provides a single item in a QIconView.

A QIconViewItem contains an icon, a string and optionally a sort key, and can display itself in a QIconView.

The simplest way to create a QIconViewItem and insert it into a QIconView is to construct the item passing the constructor a pointer to the icon view, a string and an icon:

    (void) new QIconViewItem(
                    iconView,   // A pointer to a QIconView
                    "This is the text of the item",
                    aPixmap );

By default the text of an icon view item may not be edited by the user but calling setRenameEnabled(TRUE) will allow the user to perform in-place editing of the item's text.

When the icon view is deleted all items in it are deleted automatically.

The QIconView::firstItem() and QIconViewItem::nextItem() functions provide a means of iterating over all the items in a QIconView:

    QIconViewItem *item;
    for ( item = iconView->firstItem(); item; item = item->nextItem() )
        do_something_with( item );

The item's icon view is available from iconView(), and its position in the icon view from index().

The item's selection status is available from isSelected() and is set and controlled by setSelected() and isSelectable().

The text and icon can be set with setText() and setPixmap() and retrieved with text() and pixmap(). The item's sort key defaults to text() but may be set with setKey() and retrieved with key(). The comparison function, compare() uses key().

Items may be repositioned with move() and moveBy(). An item's geometry is available from rect(), x(), y(), width(), height(), size(), pos(), textRect() and pixmapRect(). You can also test against the position of a point with contains() and intersects().

To remove an item from an icon view, just delete the item. The QIconViewItem destructor removes it cleanly from its icon view.

Because the icon view is designed to use drag-and-drop, the icon view item also has functions for drag-and-drop which may be reimplemented.

The class is designed to be very similar to QListView and QListBox in use, both via instantiation and subclassing.

See also Advanced Widgets.

Member Function Documentation

QIconViewItem::QIconViewItem ( QIconView * parent )

Constructs a QIconViewItem and inserts it into icon view parent with no text and a default icon.

QIconViewItem::QIconViewItem ( QIconView * parent, QIconViewItem * after )

Constructs a QIconViewItem and inserts it into the icon view parent with no text and a default icon, after the icon view item after.

QIconViewItem::QIconViewItem ( QIconView * parent, const QString & text )

Constructs an icon view item and inserts it into the icon view parent using text as the text and a default icon.

QIconViewItem::QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text )

Constructs an icon view item and inserts it into the icon view parent using text as the text and a default icon, after the icon view item after.

QIconViewItem::QIconViewItem ( QIconView * parent, const QString & text, const QPixmap & icon )

Constructs an icon view item and inserts it into the icon view parent using text as the text and icon as the icon.

QIconViewItem::QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text, const QPixmap & icon )

Constructs an icon view item and inserts it into the icon view parent using text as the text and icon as the icon, after the icon view item after.

QIconViewItem::QIconViewItem ( QIconView * parent, const QString & text, const QPicture & picture )

Constructs an icon view item and inserts it into the icon view parent using text as the text and picture as the icon.

QIconViewItem::QIconViewItem ( QIconView * parent, QIconViewItem * after, const QString & text, const QPicture & picture )

Constructs an icon view item and inserts it into the icon view parent using text as the text and picture as the icon, after the icon view item after.

QIconViewItem::~QIconViewItem () [virtual]

Destroys the icon view item and tells the parent icon view that the item has been destroyed.

bool QIconViewItem::acceptDrop ( const QMimeSource * mime ) const [virtual]

Returns TRUE if you can drop things with a QMimeSource of mime onto this item; otherwise returns FALSE.

The default implementation always returns FALSE. You must subclass QIconViewItem and reimplement acceptDrop() to accept drops.

Examples: fileiconview/qfileiconview.cpp and iconview/simple_dd/main.cpp.

void QIconViewItem::calcRect ( const QString & text_ = QString::null ) [virtual protected]

This virtual function is responsible for calculating the rectangles returned by rect(), textRect() and pixmapRect(). setRect(), setTextRect() and setPixmapRect() are provided mainly for reimplementations of this function.

text_ is an internal parameter which defaults to QString::null.

int QIconViewItem::compare ( QIconViewItem * i ) const [virtual]

Compares this icon view item to i. Returns -1 if this item is less than i, 0 if they are equal, and 1 if this icon view item is greater than i.

The default implementation compares the item keys (key()) using QString::localeAwareCompare(). A reimplementation may use different values and a different comparison function. Here is a reimplementation that uses plain Unicode comparison:

        int MyIconViewItem::compare( QIconViewItem *i ) const
        {
            return key().compare( i->key() );
        }

See also key(), QString::localeAwareCompare() and QString::compare().

bool QIconViewItem::contains ( const QPoint & pnt ) const

Returns TRUE if the item contains the point pnt (in contents coordinates); otherwise returns FALSE.

bool QIconViewItem::dragEnabled () const

Returns TRUE if the user is allowed to drag the icon view item; otherwise returns FALSE.

See also setDragEnabled().

void QIconViewItem::dragEntered () [virtual protected]

This function is called when a drag enters the item's bounding rectangle.

The default implementation does nothing; subclasses may reimplement this function.

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::dragLeft () [virtual protected]

This function is called when a drag leaves the item's bounding rectangle.

The default implementation does nothing; subclasses may reimplement this function.

Example: fileiconview/qfileiconview.cpp.

bool QIconViewItem::dropEnabled () const

Returns TRUE if the user is allowed to drop something onto the item; otherwise returns FALSE.

See also setDropEnabled().

void QIconViewItem::dropped ( QDropEvent * e, const QValueList<QIconDragItem> & lst ) [virtual protected]

This function is called when something is dropped on the item. e provides all the information about the drop. If the drag object of the drop was a QIconDrag, lst contains the list of the dropped items. You can get the data by calling QIconDragItem::data() on each item. If the lst is empty, i.e. the drag was not a QIconDrag, you must decode the data in e and work with that.

The default implementation does nothing; subclasses may reimplement this function.

Examples: fileiconview/qfileiconview.cpp and iconview/simple_dd/main.cpp.

int QIconViewItem::height () const

Returns the height of the item.

QIconView * QIconViewItem::iconView () const

Returns a pointer to this item's icon view parent.

int QIconViewItem::index () const

Returns the index of this item in the icon view, or -1 if an error occurred.

bool QIconViewItem::intersects ( const QRect & r ) const

Returns TRUE if the item intersects the rectangle r (in contents coordinates); otherwise returns FALSE.

bool QIconViewItem::isSelectable () const

Returns TRUE if the item is selectable; otherwise returns FALSE.

See also setSelectable().

bool QIconViewItem::isSelected () const

Returns TRUE if the item is selected; otherwise returns FALSE.

See also setSelected().

Example: fileiconview/qfileiconview.cpp.

QString QIconViewItem::key () const [virtual]

Returns the key of the icon view item or text() if no key has been explicitly set.

See also setKey() and compare().

bool QIconViewItem::move ( int x, int y ) [virtual]

Moves the item to position (x, y) in the icon view (these are contents coordinates).

bool QIconViewItem::move ( const QPoint & pnt ) [virtual]

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

Moves the item to the point pnt.

void QIconViewItem::moveBy ( int dx, int dy ) [virtual]

Moves the item dx pixels in the x-direction and dy pixels in the y-direction.

void QIconViewItem::moveBy ( const QPoint & pnt ) [virtual]

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

Moves the item by the x, y values in point pnt.

QIconViewItem * QIconViewItem::nextItem () const

Returns a pointer to the next item, or 0 if this is the last item in the icon view.

To find the first item use QIconView::firstItem().

Example:

    QIconViewItem *item;
    for ( item = iconView->firstItem(); item; item = item->nextItem() )
        do_something_with( item );

See also prevItem().

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::paintFocus ( QPainter * p, const QColorGroup & cg ) [virtual protected]

Paints the focus rectangle of the item using the painter p and the color group cg.

void QIconViewItem::paintItem ( QPainter * p, const QColorGroup & cg ) [virtual protected]

Paints the item using the painter p and the color group cg. If you want the item to be drawn with a different font or color, reimplement this function, change the values of the color group or the painter's font, and then call the QIconViewItem::paintItem() with the changed values.

Example: fileiconview/qfileiconview.cpp.

QPicture * QIconViewItem::picture () const [virtual]

Returns the icon of the icon view item if it is a picture, or 0 if it is a pixmap. In the latter case use pixmap() instead. Normally you set the picture of the item with setPicture(), but sometimes it's inconvenient to call setPicture() for every item. So you can subclass QIconViewItem, reimplement this function and return a pointer to the item's picture. If you do this, you must call calcRect() manually each time the size of this picture changes.

See also setPicture().

QPixmap * QIconViewItem::pixmap () const [virtual]

Returns the icon of the icon view item if it is a pixmap, or 0 if it is a picture. In the latter case use picture() instead. Normally you set the pixmap of the item with setPixmap(), but sometimes it's inconvenient to call setPixmap() for every item. So you can subclass QIconViewItem, reimplement this function and return a pointer to the item's pixmap. If you do this, you must call calcRect() manually each time the size of this pixmap changes.

See also setPixmap().

Example: fileiconview/qfileiconview.cpp.

QRect QIconViewItem::pixmapRect ( bool relative = TRUE ) const

Returns the bounding rectangle of the item's icon.

If relative is TRUE, (the default), the rectangle is relative to the origin of the item's rectangle. If relative is FALSE, the returned rectangle is relative to the origin of the icon view's contents coordinate system.

Example: fileiconview/qfileiconview.cpp.

QPoint QIconViewItem::pos () const

Returns the position of the item (in contents coordinates).

QIconViewItem * QIconViewItem::prevItem () const

Returns a pointer to the previous item, or 0 if this is the first item in the icon view.

See also nextItem() and QIconView::firstItem().

QRect QIconViewItem::rect () const

Returns the bounding rectangle of the item (in contents coordinates).

void QIconViewItem::removeRenameBox () [virtual protected]

Removes the editbox that is used for in-place renaming.

void QIconViewItem::rename ()

Starts in-place renaming of an icon, if allowed.

This function sets up the icon view so that the user can edit the item text, and then returns. When the user is done, setText() will be called and QIconView::itemRenamed() will be emitted (unless the user cancelled, e.g. by pressing the Escape key).

See also setRenameEnabled().

Example: fileiconview/qfileiconview.cpp.

bool QIconViewItem::renameEnabled () const

Returns TRUE if the item can be renamed by the user with in-place renaming; otherwise returns FALSE.

See also setRenameEnabled().

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::repaint () [virtual]

Repaints the item.

int QIconViewItem::rtti () const [virtual]

Returns 0.

Make your derived classes return their own values for rtti(), so that you can distinguish between icon view item types. You should use values greater than 1000, preferably a large random number, to allow for extensions to this class.

void QIconViewItem::setDragEnabled ( bool allow ) [virtual]

If allow is TRUE, the icon view permits the user to drag the icon view item either to another position within the icon view or to somewhere outside of it. If allow is FALSE, the item cannot be dragged.

void QIconViewItem::setDropEnabled ( bool allow ) [virtual]

If allow is TRUE, the icon view lets the user drop something on this icon view item.

void QIconViewItem::setItemRect ( const QRect & r ) [protected]

Sets the bounding rectangle of the whole item to r. This function is provided for subclasses which reimplement calcRect(), so that they can set the calculated rectangle. Any other use is discouraged.

See also calcRect(), textRect(), setTextRect(), pixmapRect() and setPixmapRect().

void QIconViewItem::setKey ( const QString & k ) [virtual]

Sets k as the sort key of the icon view item. By default text() is used for sorting.

See also compare().

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::setPicture ( const QPicture & icon ) [virtual]

Sets icon as the item's icon in the icon view. This function might be a no-op if you reimplement picture().

See also picture().

void QIconViewItem::setPixmap ( const QPixmap & icon ) [virtual]

Sets icon as the item's icon in the icon view. This function might be a no-op if you reimplement pixmap().

See also pixmap().

void QIconViewItem::setPixmap ( const QPixmap & icon, bool recalc, bool redraw = TRUE ) [virtual]

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

Sets icon as the item's icon in the icon view. If recalc is TRUE, the icon view's layout is recalculated. If redraw is TRUE (the default), the icon view is repainted.

See also pixmap().

void QIconViewItem::setPixmapRect ( const QRect & r ) [protected]

Sets the bounding rectangle of the item's icon to r. This function is provided for subclasses which reimplement calcRect(), so that they can set the calculated rectangle. Any other use is discouraged.

See also calcRect(), pixmapRect(), setItemRect() and setTextRect().

void QIconViewItem::setRenameEnabled ( bool allow ) [virtual]

If allow is TRUE, the user can rename the icon view item by clicking on the text (or pressing F2) while the item is selected (in-place renaming). If allow is FALSE, in-place renaming is not possible.

Examples: fileiconview/qfileiconview.cpp, iconview/main.cpp and iconview/simple_dd/main.cpp.

void QIconViewItem::setSelectable ( bool enable ) [virtual]

Sets this item to be selectable if enable is TRUE (the default) or unselectable if enable is FALSE.

The user is unable to select a non-selectable item using either the keyboard or the mouse. (The application programmer can select an item in code regardless of this setting.)

See also isSelectable().

void QIconViewItem::setSelected ( bool s, bool cb ) [virtual]

Selects or unselects the item, depending on s; it may also unselect other items, depending on QIconView::selectionMode() and cb.

If s is FALSE, the item is unselected.

If s is TRUE and QIconView::selectionMode() is Single, the item is selected and the item previously selected is unselected.

If s is TRUE and QIconView::selectionMode() is Extended, the item is selected. If cb is TRUE, the selection state of the other items is left unchanged. If cb is FALSE (the default) all other items are unselected.

If s is TRUE and QIconView::selectionMode() is Multi, the item is selected.

Note that cb is used only if QIconView::selectionMode() is Extended; cb defaults to FALSE.

All items whose selection status changes repaint themselves.

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::setSelected ( bool s ) [virtual]

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

This variant is equivalent to calling the other variant with cb set to FALSE.

void QIconViewItem::setText ( const QString & text ) [virtual]

Sets text as the text of the icon view item. This function might be a no-op if you reimplement text().

See also text().

Example: fileiconview/qfileiconview.cpp.

void QIconViewItem::setText ( const QString & text, bool recalc, bool redraw = TRUE ) [virtual]

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

Sets text as the text of the icon view item. If recalc is TRUE, the icon view's layout is recalculated. If redraw is TRUE (the default), the icon view is repainted.

See also text().

void QIconViewItem::setTextRect ( const QRect & r ) [protected]

Sets the bounding rectangle of the item's text to r. This function is provided for subclasses which reimplement calcRect(), so that they can set the calculated rectangle. Any other use is discouraged.

See also calcRect(), textRect(), setItemRect() and setPixmapRect().

QSize QIconViewItem::size () const

Returns the size of the item.

QString QIconViewItem::text () const [virtual]

Returns the text of the icon view item. Normally you set the text of the item with setText(), but sometimes it's inconvenient to call setText() for every item; so you can subclass QIconViewItem, reimplement this function, and return the text of the item. If you do this, you must call calcRect() manually each time the text (and therefore its size) changes.

See also setText().

Example: fileiconview/qfileiconview.cpp.

QRect QIconViewItem::textRect ( bool relative = TRUE ) const

Returns the bounding rectangle of the item's text.

If relative is TRUE, (the default), the returned rectangle is relative to the origin of the item's rectangle. If relative is FALSE, the returned rectangle is relative to the origin of the icon view's contents coordinate system.

Example: fileiconview/qfileiconview.cpp.

int QIconViewItem::width () const

Returns the width of the item.

int QIconViewItem::x () const

Returns the x-coordinate of the item (in contents coordinates).

int QIconViewItem::y () const

Returns the y-coordinate of the item (in contents coordinates).

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


QIconViewItem Member List

Complete Member List for QIconViewItem

This is the complete list of member functions for QIconViewItem, including inherited members.

  • QIconViewItem()
  • ~QIconViewItem()
  • acceptDrop()
  • calcRect()
  • compare()
  • contains()
  • dragEnabled()
  • dragEntered()
  • dragLeft()
  • dropEnabled()
  • dropped()
  • height()
  • iconView()
  • index()
  • intersects()
  • isSelectable()
  • isSelected()
  • key()
  • move()
  • moveBy()
  • nextItem()
  • paintFocus()
  • paintItem()
  • picture()
  • pixmap()
  • pixmapRect()
  • pos()
  • prevItem()
  • rect()
  • removeRenameBox()
  • rename()
  • renameEnabled()
  • repaint()
  • rtti()
  • setDragEnabled()
  • setDropEnabled()
  • setItemRect()
  • setKey()
  • setPicture()
  • setPixmap()
  • setPixmapRect()
  • setRenameEnabled()
  • setSelectable()
  • setSelected()
  • setText()
  • setTextRect()
  • size()
  • text()
  • textRect()
  • width()
  • x()
  • y()


QImage Class

QImage Class Reference

The QImage class provides a hardware-independent pixmap representation with direct access to the pixel data. More...

#include <qimage.h>

List of all member functions.

Public Members

  • enum Endian { IgnoreEndian, BigEndian, LittleEndian }
  • QImage ()
  • QImage ( int w, int h, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )
  • QImage ( const QSize & size, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )
  • QImage ( const QString & fileName, const char * format = 0 )
  • QImage ( const char * const xpm[] )
  • QImage ( const QByteArray & array )
  • QImage ( uchar * yourdata, int w, int h, int depth, QRgb * colortable, int numColors, Endian bitOrder )
  • QImage ( uchar * yourdata, int w, int h, int depth, int bpl, QRgb * colortable, int numColors, Endian bitOrder )
  • QImage ( const QImage & image )
  • ~QImage ()
  • QImage & operator= ( const QImage & image )
  • QImage & operator= ( const QPixmap & pixmap )
  • bool operator== ( const QImage & i ) const
  • bool operator!= ( const QImage & i ) const
  • void detach ()
  • QImage copy () const
  • QImage copy ( int x, int y, int w, int h, int conversion_flags = 0 ) const
  • QImage copy ( const QRect & r ) const
  • bool isNull () const
  • int width () const
  • int height () const
  • QSize size () const
  • QRect rect () const
  • int depth () const
  • int numColors () const
  • Endian bitOrder () const
  • QRgb color ( int i ) const
  • void setColor ( int i, QRgb c )
  • void setNumColors ( int numColors )
  • bool hasAlphaBuffer () const
  • void setAlphaBuffer ( bool enable )
  • bool allGray () const
  • bool isGrayscale () const
  • uchar * bits () const
  • uchar * scanLine ( int i ) const
  • uchar ** jumpTable () const
  • QRgb * colorTable () const
  • int numBytes () const
  • int bytesPerLine () const
  • bool create ( int width, int height, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )
  • bool create ( const QSize &, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )
  • void reset ()
  • void fill ( uint pixel )
  • void invertPixels ( bool invertAlpha = TRUE )
  • QImage convertDepth ( int depth ) const
  • QImage convertDepthWithPalette ( int d, QRgb * palette, int palette_count, int conversion_flags = 0 ) const
  • QImage convertDepth ( int depth, int conversion_flags ) const
  • QImage convertBitOrder ( Endian bitOrder ) const
  • enum ScaleMode { ScaleFree, ScaleMin, ScaleMax }
  • QImage smoothScale ( int w, int h, ScaleMode mode = ScaleFree ) const
  • QImage smoothScale ( const QSize & s, ScaleMode mode = ScaleFree ) const
  • QImage scale ( int w, int h, ScaleMode mode = ScaleFree ) const
  • QImage scale ( const QSize & s, ScaleMode mode = ScaleFree ) const
  • QImage scaleWidth ( int w ) const
  • QImage scaleHeight ( int h ) const
  • QImage xForm ( const QWMatrix & matrix ) const
  • QImage createAlphaMask ( int conversion_flags = 0 ) const
  • QImage createHeuristicMask ( bool clipTight = TRUE ) const
  • QImage mirror () const
  • QImage mirror ( bool horizontal, bool vertical ) const
  • QImage swapRGB () const
  • bool load ( const QString & fileName, const char * format = 0 )
  • bool loadFromData ( const uchar * buf, uint len, const char * format = 0 )
  • bool loadFromData ( QByteArray buf, const char * format = 0 )
  • bool save ( const QString & fileName, const char * format, int quality = -1 ) const
  • bool valid ( int x, int y ) const
  • int pixelIndex ( int x, int y ) const
  • QRgb pixel ( int x, int y ) const
  • void setPixel ( int x, int y, uint index_or_rgb )
  • int dotsPerMeterX () const
  • int dotsPerMeterY () const
  • void setDotsPerMeterX ( int x )
  • void setDotsPerMeterY ( int y )
  • QPoint offset () const
  • void setOffset ( const QPoint & p )
  • QValueList<QImageTextKeyLang> textList () const
  • QStringList textLanguages () const
  • QStringList textKeys () const
  • QString text ( const char * key, const char * lang = 0 ) const
  • QString text ( const QImageTextKeyLang & kl ) const
  • void setText ( const char * key, const char * lang, const QString & s )

Static Public Members

  • Endian systemBitOrder ()
  • Endian systemByteOrder ()
  • const char * imageFormat ( const QString & fileName )
  • QStrList inputFormats ()
  • QStrList outputFormats ()
  • QStringList inputFormatList ()
  • QStringList outputFormatList ()

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QImage & image )
  • QDataStream & operator>> ( QDataStream & s, QImage & image )

Detailed Description

The QImage class provides a hardware-independent pixmap representation with direct access to the pixel data.

It is one of the two classes Qt provides for dealing with images, the other being QPixmap. QImage is designed and optimized for I/O and for direct pixel access/manipulation. QPixmap is designed and optimized for drawing. There are (slow) functions to convert between QImage and QPixmap: QPixmap::convertToImage() and QPixmap::convertFromImage().

An image has the parameters width, height and depth (bits per pixel, bpp), a color table and the actual pixels. QImage supports 1-bpp, 8-bpp and 32-bpp image data. 1-bpp and 8-bpp images use a color lookup table; the pixel value is a color table index.

32-bpp images encode an RGB value in 24 bits and ignore the color table. The most significant byte is used for the alpha buffer.

An entry in the color table is an RGB triplet encoded as a uint. Use the qRed(), qGreen() and qBlue() functions (qcolor.h) to access the components, and qRgb to make an RGB triplet (see the QColor class documentation).

1-bpp (monochrome) images have a color table with a most two colors. There are two different formats: big endian (MSB first) or little endian (LSB first) bit order. To access a single bit you will must do some bit shifts:

    QImage image;
    // sets bit at (x,y) to 1
    if ( image.bitOrder() == QImage::LittleEndian )
        *(image.scanLine(y) + (x >> 3)) |= 1 << (x & 7);
    else
        *(image.scanLine(y) + (x >> 3)) |= 1 << (7 -(x & 7));

If this looks complicated, it might be a good idea to convert the 1-bpp image to an 8-bpp image using convertDepth().

8-bpp images are much easier to work with than 1-bpp images because they have a single byte per pixel:

    QImage image;
    // set entry 19 in the color table to yellow
    image.setColor( 19, qRgb(255,255,0) );
    // set 8 bit pixel at (x,y) to value yellow (in color table)
    *(image.scanLine(y) + x) = 19;

32-bpp images ignore the color table; instead, each pixel contains the RGB triplet. 24 bits contain the RGB value; the most significant byte is reserved for the alpha buffer.

    QImage image;
    // sets 32 bit pixel at (x,y) to yellow.
    uint *p = (uint *)image.scanLine(y) + x;
    *p = qRgb(255,255,0);

On Qt/Embedded, scanlines are aligned to the pixel depth and may be padded to any degree, while on all other platforms, the scanlines are 32-bit aligned for all depths. The constructor taking a uchar* argument always expects 32-bit aligned data. On Qt/Embedded, an additional constructor allows the number of bytes-per-line to be specified.

 QImage supports a variety of methods for getting information about
the image, for example, colorTable(), allGray(), isGrayscale(),
bitOrder(), bytesPerLine(), depth(), dotsPerMeterX() and
dotsPerMeterY(), hasAlphaBuffer(), numBytes(), numColors(), and
width() and height().

Pixel colors are retrieved with pixel() and set with setPixel().

QImage also supports a number of functions for creating a new image that is a transformed version of the original. For example, copy(), convertBitOrder(), convertDepth(), createAlphaMask(), createHeuristicMask(), mirror(), scale(), smoothScale(), swapRGB() and xForm(). There are also functions for changing attributes of an image in-place, for example, setAlphaBuffer(), setColor(), setDotsPerMeterX() and setDotsPerMeterY() and setNumColors().

Images can be loaded and saved in the supported formats. Images are saved to a file with save(). Images are loaded from a file with load() (or in the constructor) or from an array of data with loadFromData(). The lists of supported formats are available from inputFormatList() and outputFormatList().

Strings of text may be added to images using setText().

The QImage class uses explicit sharing, similar to that used by QMemArray.

New image formats can be added as plugins.

See also QImageIO, QPixmap, Shared Classes, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Type Documentation

QImage::Endian

This enum type is used to describe the endianness of the CPU and graphics hardware.

  • QImage::IgnoreEndian - Endianness does not matter. Useful for some operations that are independent of endianness.
  • QImage::BigEndian - Network byte order, as on SPARC and Motorola CPUs.
  • QImage::LittleEndian - PC/Alpha byte order.

QImage::ScaleMode

The functions scale() and smoothScale() use different modes for scaling the image. The purpose of these modes is to retain the ratio of the image if this is required.

  • QImage::ScaleFree - The image is scaled freely: the resulting image fits exactly into the specified size; the ratio will not necessarily be preserved.
  • QImage::ScaleMin - The ratio of the image is preserved and the resulting image is guaranteed to fit into the specified size (it is as large as possible within these constraints) - the image might be smaller than the requested size.
  • QImage::ScaleMax - The ratio of the image is preserved and the resulting image fills the whole specified rectangle (it is as small as possible within these constraints) - the image might be larger than the requested size.

Member Function Documentation

QImage::QImage ()

Constructs a null image.

See also isNull().

QImage::QImage ( int w, int h, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Constructs an image with w width, h height, depth bits per pixel, numColors colors and bit order bitOrder.

Using this constructor is the same as first constructing a null image and then calling the create() function.

See also create().

QImage::QImage ( const QSize & size, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Constructs an image with size size pixels, depth depth bits, numColors and bitOrder endianness.

Using this constructor is the same as first constructing a null image and then calling the create() function.

See also create().

QImage::QImage ( const QString & fileName, const char * format = 0 )

Constructs an image and tries to load the image from the file fileName.

If format is specified, the loader attempts to read the image using the specified format. If format is not specified (which is the default), the loader reads a few bytes from the header to guess the file format.

If the loading of the image failed, this object is a null image.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also load(), isNull() and QImageIO.

QImage::QImage ( const char * const xpm[] )

Constructs an image from xpm, which must be a valid XPM image.

Errors are silently ignored.

Note that it's possible to squeeze the XPM variable a little bit by using an unusual declaration:

        static const char * const start_xpm[]={
            "16 15 8 1",
            "a c #cec6bd",
        ....

The extra const makes the entire definition read-only, which is slightly more efficient (e.g. when the code is in a shared library) and ROMable when the application is to be stored in ROM.

QImage::QImage ( const QByteArray & array )

Constructs an image from the binary data array. It tries to guess the file format.

If the loading of the image failed, this object is a null image.

See also loadFromData(), isNull() and imageFormat().

QImage::QImage ( uchar * yourdata, int w, int h, int depth, QRgb * colortable, int numColors, Endian bitOrder )

Constructs an image w pixels wide, h pixels high with a color depth of depth, that uses an existing memory buffer, yourdata. The buffer must remain valid throughout the life of the QImage. The image does not delete the buffer at destruction.

If colortable is 0, a color table sufficient for numColors will be allocated (and destructed later).

Note that yourdata must be 32-bit aligned.

The endianness is given in bitOrder.

QImage::QImage ( uchar * yourdata, int w, int h, int depth, int bpl, QRgb * colortable, int numColors, Endian bitOrder )

Constructs an image that uses an existing memory buffer. The buffer must remain valid for the life of the QImage. The image does not delete the buffer at destruction. The buffer is passed as yourdata. The image's width is w and its height is h. The color depth is depth. bpl specifies the number of bytes per line.

If colortable is 0, a color table sufficient for numColors will be allocated (and destructed later).

The endian-ness is specified by bitOrder.

QImage::QImage ( const QImage & image )

Constructs a shallow copy of image.

QImage::~QImage ()

Destroys the image and cleans up.

bool QImage::allGray () const

Returns TRUE if all the colors in the image are shades of gray (i.e. their red, green and blue components are equal); otherwise returns FALSE.

This function is slow for large 16-bit and 32-bit images.

See also isGrayscale().

Endian QImage::bitOrder () const

Returns the bit order for the image.

If it is a 1-bpp image, this function returns either QImage::BigEndian or QImage::LittleEndian.

If it is not a 1-bpp image, this function returns QImage::IgnoreEndian.

See also depth().

uchar * QImage::bits () const

Returns a pointer to the first pixel data. This is equivalent to scanLine(0).

See also numBytes(), scanLine() and jumpTable().

Example: opengl/texture/gltexobj.cpp.

int QImage::bytesPerLine () const

Returns the number of bytes per image scanline. This is equivalent to numBytes()/height().

See also numBytes() and scanLine().

QRgb QImage::color ( int i ) const

Returns the color in the color table at index i. The first color is at index 0.

A color value is an RGB triplet. Use the qRed(), qGreen() and qBlue() functions (defined in qcolor.h) to get the color value components.

See also setColor(), numColors() and QColor.

Example: themes/wood.cpp.

QRgb * QImage::colorTable () const

Returns a pointer to the color table.

See also numColors().

QImage QImage::convertBitOrder ( Endian bitOrder ) const

Converts the bit order of the image to bitOrder and returns the converted image. The original image is not changed.

Returns *this if the bitOrder is equal to the image bit order, or a null image if this image cannot be converted.

See also bitOrder(), systemBitOrder() and isNull().

QImage QImage::convertDepth ( int depth, int conversion_flags ) const

Converts the depth (bpp) of the image to depth and returns the converted image. The original image is not changed.

The depth argument must be 1, 8, 16 or 32.

Returns *this if depth is equal to the image depth, or a null image if this image cannot be converted.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the conversion_flags to specify how you'd prefer this to happen.

See also Qt::ImageConversionFlags, depth() and isNull().

QImage QImage::convertDepth ( int depth ) const

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

QImage QImage::convertDepthWithPalette ( int d, QRgb * palette, int palette_count, int conversion_flags = 0 ) const

Returns an image with depth d, using the palette_count colors pointed to by palette. If d is 1 or 8, the returned image will have its color table ordered the same as palette.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the conversion_flags to specify how you'd prefer this to happen.

Note: currently no closest-color search is made. If colors are found that are not in the palette, the palette may not be used at all. This result should not be considered valid because it may change in future implementations.

Currently inefficient for non-32-bit images.

See also Qt::ImageConversionFlags.

QImage QImage::copy () const

Returns a deep copy of the image.

See also detach().

QImage QImage::copy ( int x, int y, int w, int h, int conversion_flags = 0 ) const

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

Returns a deep copy of a sub-area of the image.

The returned image is always w by h pixels in size, and is copied from position x, y in this image. In areas beyond this image pixels are filled with pixel 0.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the conversion_flags to specify how you'd prefer this to happen.

See also bitBlt() and Qt::ImageConversionFlags.

QImage QImage::copy ( const QRect & r ) const

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

Returns a deep copy of a sub-area of the image.

The returned image always has the size of the rectangle r. In areas beyond this image pixels are filled with pixel 0.

bool QImage::create ( int width, int height, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Sets the image width, height, depth, its number of colors (in numColors), and bit order. Returns TRUE if successful, or FALSE if the parameters are incorrect or if memory cannot be allocated.

The width and height is limited to 32767. depth must be 1, 8, 16 or 32. If depth is 1, bitOrder must be set to either QImage::LittleEndian or QImage::BigEndian. For other depths bitOrder must be QImage::IgnoreEndian.

This function allocates a color table and a buffer for the image data. The image data is not initialized.

The image buffer is allocated as a single block that consists of a table of scanline pointers (jumpTable()) and the image data (bits()).

See also fill(), width(), height(), depth(), numColors(), bitOrder(), jumpTable(), scanLine(), bits(), bytesPerLine() and numBytes().

bool QImage::create ( const QSize &, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

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

QImage QImage::createAlphaMask ( int conversion_flags = 0 ) const

Builds and returns a 1-bpp mask from the alpha buffer in this image. Returns a null image if alpha buffer mode is disabled.

See QPixmap::convertFromImage() for a description of the conversion_flags argument.

The returned image has little-endian bit order, which you can convert to big-endianness using convertBitOrder().

See also createHeuristicMask(), hasAlphaBuffer() and setAlphaBuffer().

QImage QImage::createHeuristicMask ( bool clipTight = TRUE ) const

Creates and returns a 1-bpp heuristic mask for this image. It works by selecting a color from one of the corners, then chipping away pixels of that color starting at all the edges.

The four corners vote for which color is to be masked away. In case of a draw (this generally means that this function is not applicable to the image), the result is arbitrary.

The returned image has little-endian bit order, which you can convert to big-endianness using convertBitOrder().

If clipTight is TRUE the mask is just large enough to cover the pixels; otherwise, the mask is larger than the data pixels.

This function disregards the alpha buffer.

See also createAlphaMask().

int QImage::depth () const

Returns the depth of the image.

The image depth is the number of bits used to encode a single pixel, also called bits per pixel (bpp) or bit planes of an image.

The supported depths are 1, 8, 16 and 32.

See also convertDepth().

void QImage::detach ()

Detaches from shared image data and makes sure that this image is the only one referring to the data.

If multiple images share common data, this image makes a copy of the data and detaches itself from the sharing mechanism. Nothing is done if there is just a single reference.

See also copy().

Example: themes/wood.cpp.

int QImage::dotsPerMeterX () const

Returns the number of pixels that fit horizontally in a physical meter. This and dotsPerMeterY() define the intended scale and aspect ratio of the image.

See also setDotsPerMeterX().

int QImage::dotsPerMeterY () const

Returns the number of pixels that fit vertically in a physical meter. This and dotsPerMeterX() define the intended scale and aspect ratio of the image.

See also setDotsPerMeterY().

void QImage::fill ( uint pixel )

Fills the entire image with the pixel value pixel.

If the depth of this image is 1, only the lowest bit is used. If you say fill(0), fill(2), etc., the image is filled with 0s. If you say fill(1), fill(3), etc., the image is filled with 1s. If the depth is 8, the lowest 8 bits are used.

If the depth is 32 and the image has no alpha buffer, the pixel value is written to each pixel in the image. If the image has an alpha buffer, only the 24 RGB bits are set and the upper 8 bits (alpha value) are left unchanged.

See also invertPixels(), depth(), hasAlphaBuffer() and create().

bool QImage::hasAlphaBuffer () const

Returns TRUE if alpha buffer mode is enabled; otherwise returns FALSE.

See also setAlphaBuffer().

int QImage::height () const

Returns the height of the image.

See also width(), size() and rect().

Examples: canvas/canvas.cpp and opengl/texture/gltexobj.cpp.

const char * QImage::imageFormat ( const QString & fileName ) [static]

Returns a string that specifies the image format of the file fileName, or 0 if the file cannot be read or if the format is not recognized.

The QImageIO documentation lists the guaranteed supported image formats, or use QImage::inputFormats() and QImage::outputFormats() to get lists that include the installed formats.

See also load() and save().

QStringList QImage::inputFormatList () [static]

Returns a list of image formats that are supported for image input.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myImage.inputFormatList();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also outputFormatList(), inputFormats() and QImageIO.

Example: showimg/showimg.cpp.

QStrList QImage::inputFormats () [static]

Returns a list of image formats that are supported for image input.

See also outputFormats(), inputFormatList() and QImageIO.

void QImage::invertPixels ( bool invertAlpha = TRUE )

Inverts all pixel values in the image.

If the depth is 32: if invertAlpha is TRUE, the alpha bits are also inverted, otherwise they are left unchanged.

If the depth is not 32, the argument invertAlpha has no meaning.

Note that inverting an 8-bit image means to replace all pixels using color index i with a pixel using color index 255 minus i. Similarly for a 1-bit image. The color table is not changed.

See also fill(), depth() and hasAlphaBuffer().

bool QImage::isGrayscale () const

For 16-bit and 32-bit images, this function is equivalent to allGray().

For 8-bpp images, this function returns TRUE if color(i) is QRgb(i,i,i) for all indices of the color table; otherwise returns FALSE.

See also allGray() and depth().

bool QImage::isNull () const

Returns TRUE if it is a null image; otherwise returns FALSE.

A null image has all parameters set to zero and no allocated data.

Examples: qtimage/qtimage.cpp and showimg/showimg.cpp.

uchar ** QImage::jumpTable () const

Returns a pointer to the scanline pointer table.

This is the beginning of the data block for the image.

See also bits() and scanLine().

bool QImage::load ( const QString & fileName, const char * format = 0 )

Loads an image from the file fileName. Returns TRUE if the image was successfully loaded; otherwise returns FALSE.

If format is specified, the loader attempts to read the image using the specified format. If format is not specified (which is the default), the loader reads a few bytes from the header to guess the file format.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also loadFromData(), save(), imageFormat(), QPixmap::load() and QImageIO.

bool QImage::loadFromData ( const uchar * buf, uint len, const char * format = 0 )

Loads an image from the first len bytes of binary data in buf. Returns TRUE if the image was successfully loaded; otherwise returns FALSE.

If format is specified, the loader attempts to read the image using the specified format. If format is not specified (which is the default), the loader reads a few bytes from the header to guess the file format.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also load(), save(), imageFormat(), QPixmap::loadFromData() and QImageIO.

bool QImage::loadFromData ( QByteArray buf, const char * format = 0 )

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

Loads an image from the QByteArray buf.

QImage QImage::mirror () const

Returns a QImage which is a vertically mirrored copy of this image. The original QImage is not changed.

QImage QImage::mirror ( bool horizontal, bool vertical ) const

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

Returns a mirror of the image, mirrored in the horizontal and/or the vertical direction depending on whether horizontal and vertical are set to TRUE or FALSE. The original image is not changed.

See also smoothScale().

int QImage::numBytes () const

Returns the number of bytes occupied by the image data.

See also bytesPerLine() and bits().

int QImage::numColors () const

Returns the size of the color table for the image.

Notice that numColors() returns 0 for 16-bpp and 32-bpp images because these images do not use color tables, but instead encode pixel values as RGB triplets.

See also setNumColors() and colorTable().

Example: themes/wood.cpp.

QPoint QImage::offset () const

Returns the number of pixels by which the image is intended to be offset by when positioning relative to other images.

bool QImage::operator!= ( const QImage & i ) const

Returns TRUE if this image and image i have different contents; otherwise returns FALSE. The comparison can be slow, unless there is some obvious difference, such as different widths, in which case the function will return quickly.

See also operator=().

QImage & QImage::operator= ( const QImage & image )

Assigns a shallow copy of image to this image and returns a reference to this image.

See also copy().

QImage & QImage::operator= ( const QPixmap & pixmap )

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

Sets the image bits to the pixmap contents and returns a reference to the image.

If the image shares data with other images, it will first dereference the shared data.

Makes a call to QPixmap::convertToImage().

bool QImage::operator== ( const QImage & i ) const

Returns TRUE if this image and image i have the same contents; otherwise returns FALSE. The comparison can be slow, unless there is some obvious difference, such as different widths, in which case the function will return quickly.

See also operator=().

QStringList QImage::outputFormatList () [static]

Returns a list of image formats that are supported for image output.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myImage.outputFormatList();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also inputFormatList(), outputFormats() and QImageIO.

QStrList QImage::outputFormats () [static]

Returns a list of image formats that are supported for image output.

See also inputFormats(), outputFormatList() and QImageIO.

Example: showimg/showimg.cpp.

QRgb QImage::pixel ( int x, int y ) const

Returns the color of the pixel at the coordinates (x, y).

If (x, y) is not on the image, the results are undefined.

See also setPixel(), qRed(), qGreen(), qBlue() and valid().

Examples: canvas/canvas.cpp and qmag/qmag.cpp.

int QImage::pixelIndex ( int x, int y ) const

Returns the pixel index at the given coordinates.

If (x, y) is not valid, or if the image is not a paletted image (depth() > 8), the results are undefined.

See also valid() and depth().

QRect QImage::rect () const

Returns the enclosing rectangle (0, 0, width(), height()) of the image.

See also width(), height() and size().

void QImage::reset ()

Resets all image parameters and deallocates the image data.

Example: qtimage/qtimage.cpp.

bool QImage::save ( const QString & fileName, const char * format, int quality = -1 ) const

Saves the image to the file fileName, using the image file format format and a quality factor of quality. quality must be in the range 0..100 or -1. Specify 0 to obtain small compressed files, 100 for large uncompressed files, and -1 (the default) to use the default settings.

Returns TRUE if the image was successfully saved; otherwise returns FALSE.

See also load(), loadFromData(), imageFormat(), QPixmap::save() and QImageIO.

QImage QImage::scale ( int w, int h, ScaleMode mode = ScaleFree ) const

Returns a scaled copy of the image. The returned image has a size of width w by height h pixels if mode is ScaleFree. The modes ScaleMin and ScaleMax may be used to preserve the ratio of the image: if mode is ScaleMin, the returned image is guaranteed to fit into the rectangle specified by w and h (it is as large as possible within the constraints); if mode is ScaleMax, the returned image fits at least into the specified rectangle (it is a small as possible within the constraints).

If either the width w or the height h is 0 or negative, this function returns a null image.

This function uses a rather simple algorithm; if you need better quality, use smoothScale() instead.

See also scaleWidth(), scaleHeight(), smoothScale() and xForm().

QImage QImage::scale ( const QSize & s, ScaleMode mode = ScaleFree ) const

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

The requested size of the image is s.

QImage QImage::scaleHeight ( int h ) const

Returns a scaled copy of the image. The returned image has a height of h pixels. This function automatically calculates the width of the image so that the ratio of the image is preserved.

If h is 0 or negative a null image is returned.

See also scale(), scaleWidth(), smoothScale() and xForm().

Example: table/small-table-demo/main.cpp.

QImage QImage::scaleWidth ( int w ) const

Returns a scaled copy of the image. The returned image has a width of w pixels. This function automatically calculates the height of the image so that the ratio of the image is preserved.

If w is 0 or negative a null image is returned.

See also scale(), scaleHeight(), smoothScale() and xForm().

uchar * QImage::scanLine ( int i ) const

Returns a pointer to the pixel data at the scanline with index i. The first scanline is at index 0.

The scanline data is aligned on a 32-bit boundary.

Warning: If you are accessing 32-bpp image data, cast the returned pointer to QRgb* (QRgb has a 32-bit size) and use it to read/write the pixel value. You cannot use the uchar* pointer directly, because the pixel format depends on the byte order on the underlying platform. Hint: use qRed(), qGreen() and qBlue(), etc. (qcolor.h) to access the pixels.

Warning: If you are accessing 16-bpp image data, you must handle endianness yourself.

See also bytesPerLine(), bits() and jumpTable().

Example: desktop/desktop.cpp.

void QImage::setAlphaBuffer ( bool enable )

Enables alpha buffer mode if enable is TRUE, otherwise disables it. The default setting is disabled.

An 8-bpp image has 8-bit pixels. A pixel is an index into the color table, which contains 32-bit color values. In a 32-bpp image, the 32-bit pixels are the color values.

This 32-bit value is encoded as follows: The lower 24 bits are used for the red, green, and blue components. The upper 8 bits contain the alpha component.

The alpha component specifies the transparency of a pixel. 0 means completely transparent and 255 means opaque. The alpha component is ignored if you do not enable alpha buffer mode.

The alpha buffer is used to set a mask when a QImage is translated to a QPixmap.

See also hasAlphaBuffer() and createAlphaMask().

void QImage::setColor ( int i, QRgb c )

Sets a color in the color table at index i to c.

A color value is an RGB triplet. Use the qRgb() function (defined in qcolor.h) to make RGB triplets.

See also color(), setNumColors() and numColors().

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

void QImage::setDotsPerMeterX ( int x )

Sets the value returned by dotsPerMeterX() to x.

void QImage::setDotsPerMeterY ( int y )

Sets the value returned by dotsPerMeterY() to y.

void QImage::setNumColors ( int numColors )

Resizes the color table to numColors colors.

If the color table is expanded all the extra colors will be set to black (RGB 0,0,0).

See also numColors(), color(), setColor() and colorTable().

void QImage::setOffset ( const QPoint & p )

Sets the value returned by offset() to p.

void QImage::setPixel ( int x, int y, uint index_or_rgb )

Sets the pixel index or color at the coordinates (x, y) to index_or_rgb.

If (x, y) is not valid, the result is undefined.

If the image is a paletted image (depth() <= 8) and index_or_rgb >= numColors(), the result is undefined.

See also pixelIndex(), pixel(), qRgb(), qRgba() and valid().

void QImage::setText ( const char * key, const char * lang, const QString & s )

Records string s for the keyword key. The key should be a portable keyword recognizable by other software - some suggested values can be found in the PNG specification. s can be any text. lang should specify the language code (see RFC 1766) or 0.

QSize QImage::size () const

Returns the size of the image, i.e. its width and height.

See also width(), height() and rect().

QImage QImage::smoothScale ( int w, int h, ScaleMode mode = ScaleFree ) const

Returns a smoothly scaled copy of the image. The returned image has a size of width w by height h pixels if mode is ScaleFree. The modes ScaleMin and ScaleMax may be used to preserve the ratio of the image: if mode is ScaleMin, the returned image is guaranteed to fit into the rectangle specified by w and h (it is as large as possible within the constraints); if mode is ScaleMax, the returned image fits at least into the specified rectangle (it is a small as possible within the constraints).

For 32-bpp images and 1-bpp/8-bpp color images the result will be 32-bpp, whereas all-gray images (including black-and-white 1-bpp) will produce 8-bit grayscale images with the palette spanning 256 grays from black to white.

This function uses code based on pnmscale.c by Jef Poskanzer.

pnmscale.c - read a portable anymap and scale it

Copyright (C) 1989, 1991 by Jef Poskanzer.

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.

See also scale() and mirror().

QImage QImage::smoothScale ( const QSize & s, ScaleMode mode = ScaleFree ) const

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

The requested size of the image is s.

QImage QImage::swapRGB () const

Returns a QImage in which the values of the red and blue components of all pixels have been swapped, effectively converting an RGB image to a BGR image. The original QImage is not changed.

Endian QImage::systemBitOrder () [static]

Determines the bit order of the display hardware. Returns QImage::LittleEndian (LSB first) or QImage::BigEndian (MSB first).

See also systemByteOrder().

Endian QImage::systemByteOrder () [static]

Determines the host computer byte order. Returns QImage::LittleEndian (LSB first) or QImage::BigEndian (MSB first).

See also systemBitOrder().

QString QImage::text ( const char * key, const char * lang = 0 ) const

Returns the string recorded for the keyword key in language lang, or in a default language if lang is 0.

QString QImage::text ( const QImageTextKeyLang & kl ) const

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

Returns the string recorded for the keyword and language kl.

QStringList QImage::textKeys () const

Returns the keywords for which some texts are recorded.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myImage.textKeys();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also textList(), text(), setText() and textLanguages().

QStringList QImage::textLanguages () const

Returns the language identifiers for which some texts are recorded.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myImage.textLanguages();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also textList(), text(), setText() and textKeys().

QValueList<QImageTextKeyLang> QImage::textList () const

Returns a list of QImageTextKeyLang objects that enumerate all the texts key/language pairs set by setText() for this image.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QImageTextKeyLang> list = myImage.textList();
    QValueList<QImageTextKeyLang>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

bool QImage::valid ( int x, int y ) const

Returns TRUE if ( x, y ) is a valid coordinate in the image; otherwise returns FALSE.

See also width(), height() and pixelIndex().

Examples: canvas/canvas.cpp and qmag/qmag.cpp.

int QImage::width () const

Returns the width of the image.

See also height(), size() and rect().

Examples: canvas/canvas.cpp and opengl/texture/gltexobj.cpp.

QImage QImage::xForm ( const QWMatrix & matrix ) const

Returns a copy of the image that is transformed using the transformation matrix, matrix.

The transformation matrix is internally adjusted to compensate for unwanted translation, i.e. xForm() returns the smallest image that contains all the transformed points of the original image.

See also scale(), QPixmap::xForm(), QPixmap::trueMatrix() and QWMatrix.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QImage & image )

Writes the image image to the stream s as a PNG image.

See also QImage::save() and Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QImage & image )

Reads an image from the stream s and stores it in image.

See also QImage::load() and Format of the QDataStream operators.

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


qimage.h Include File

qimage.h

This is the verbatim text of the qimage.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qimage.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QImage and QImageIO classes
**
** Created : 950207
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QIMAGE_H
#define QIMAGE_H

#ifndef QT_H
#include "qpixmap.h"
#include "qstrlist.h"
#include "qstringlist.h"
#endif // QT_H

class QImageDataMisc; // internal
#ifndef QT_NO_IMAGE_TEXT
class Q_EXPORT QImageTextKeyLang {
public:
    QImageTextKeyLang(const char* k, const char* l) : key(k), lang(l) { }
    QImageTextKeyLang() { }

    QCString key;
    QCString lang;

    bool operator< (const QImageTextKeyLang& other) const
    { return key < other.key || key==other.key && lang < other.lang; }
    bool operator== (const QImageTextKeyLang& other) const
    { return key==other.key && lang==other.lang; }
};
#endif //QT_NO_IMAGE_TEXT

class Q_EXPORT QImage
{
public:
    enum Endian { IgnoreEndian, BigEndian, LittleEndian };

    QImage();
    QImage( int width, int height, int depth, int numColors=0,
        Endian bitOrder=IgnoreEndian );
    QImage( const QSize&, int depth, int numColors=0,
        Endian bitOrder=IgnoreEndian );
#ifndef QT_NO_IMAGEIO
    QImage( const QString &fileName, const char* format=0 );
    QImage( const char * const xpm[] );
    QImage( const QByteArray &data );
#endif
    QImage( uchar* data, int w, int h, int depth,
        QRgb* colortable, int numColors,
        Endian bitOrder );
#ifdef Q_WS_QWS
    QImage( uchar* data, int w, int h, int depth, int pbl,
        QRgb* colortable, int numColors,
        Endian bitOrder );
#endif
    QImage( const QImage & );
   ~QImage();

    QImage     &operator=( const QImage & );
    QImage     &operator=( const QPixmap & );
    bool	operator==( const QImage & ) const;
    bool	operator!=( const QImage & ) const;
    void	detach();
    QImage	copy()		const;
    QImage	copy(int x, int y, int w, int h, int conversion_flags=0) const;
    QImage	copy(const QRect&)	const;

    bool	isNull()	const	{ return data->bits == 0; }

    int		width()		const	{ return data->w; }
    int		height()	const	{ return data->h; }
    QSize	size()		const	{ return QSize(data->w,data->h); }
    QRect	rect()		const	{ return QRect(0,0,data->w,data->h); }
    int		depth()		const	{ return data->d; }
    int		numColors()	const	{ return data->ncols; }
    Endian	bitOrder()	const	{ return (Endian) data->bitordr; }

    QRgb	color( int i )	const;
    void	setColor( int i, QRgb c );
    void	setNumColors( int );

    bool	hasAlphaBuffer() const;
    void	setAlphaBuffer( bool );

    bool	allGray() const;
    bool        isGrayscale() const;

    uchar      *bits()		const;
    uchar      *scanLine( int ) const;
    uchar     **jumpTable()	const;
    QRgb       *colorTable()	const;
    int		numBytes()	const;
    int		bytesPerLine()	const;

#ifdef Q_WS_QWS
    QGfx * graphicsContext();
#endif

    bool	create( int width, int height, int depth, int numColors=0,
            Endian bitOrder=IgnoreEndian );
    bool	create( const QSize&, int depth, int numColors=0,
            Endian bitOrder=IgnoreEndian );
    void	reset();

    void	fill( uint pixel );
    void	invertPixels( bool invertAlpha = TRUE );

    QImage	convertDepth( int ) const;
#ifndef QT_NO_IMAGE_TRUECOLOR
    QImage	convertDepthWithPalette( int, QRgb* p, int pc, int cf=0 ) const;
#endif
    QImage	convertDepth( int, int conversion_flags ) const;
    QImage	convertBitOrder( Endian ) const;

    enum ScaleMode {
    ScaleFree,
    ScaleMin,
    ScaleMax
    };
#ifndef QT_NO_IMAGE_SMOOTHSCALE
    QImage smoothScale( int w, int h, ScaleMode mode=ScaleFree ) const;
    QImage smoothScale( const QSize& s, ScaleMode mode=ScaleFree ) const;
#endif
#ifndef QT_NO_IMAGE_TRANSFORMATION
    QImage scale( int w, int h, ScaleMode mode=ScaleFree ) const;
    QImage scale( const QSize& s, ScaleMode mode=ScaleFree ) const;
    QImage scaleWidth( int w ) const;
    QImage scaleHeight( int h ) const;
    QImage xForm( const QWMatrix &matrix ) const;
#endif

#ifndef QT_NO_IMAGE_DITHER_TO_1
    QImage	createAlphaMask( int conversion_flags=0 ) const;
#endif
#ifndef QT_NO_IMAGE_HEURISTIC_MASK
    QImage	createHeuristicMask( bool clipTight=TRUE ) const;
#endif
#ifndef QT_NO_IMAGE_MIRROR
    QImage	mirror() const;
    QImage	mirror(bool horizontally, bool vertically) const;
#endif
    QImage	swapRGB() const;

    static Endian systemBitOrder();
    static Endian systemByteOrder();

#ifndef QT_NO_IMAGEIO
    static const char* imageFormat( const QString &fileName );
    static QStrList inputFormats();
    static QStrList outputFormats();
#ifndef QT_NO_STRINGLIST
    static QStringList inputFormatList();
    static QStringList outputFormatList();
#endif
    bool	load( const QString &fileName, const char* format=0 );
    bool	loadFromData( const uchar *buf, uint len,
                  const char *format=0 );
    bool	loadFromData( QByteArray data, const char* format=0 );
    bool	save( const QString &fileName, const char* format,
              int quality=-1 ) const;
#endif //QT_NO_IMAGEIO

    bool	valid( int x, int y ) const;
    int		pixelIndex( int x, int y ) const;
    QRgb	pixel( int x, int y ) const;
    void	setPixel( int x, int y, uint index_or_rgb );

    // Auxiliary data
    int dotsPerMeterX() const;
    int dotsPerMeterY() const;
    void setDotsPerMeterX(int);
    void setDotsPerMeterY(int);
    QPoint offset() const;
    void setOffset(const QPoint&);
#ifndef QT_NO_IMAGE_TEXT
    QValueList<QImageTextKeyLang> textList() const;
    QStringList textLanguages() const;
    QStringList textKeys() const;
    QString text(const char* key, const char* lang=0) const;
    QString text(const QImageTextKeyLang&) const;
    void setText(const char* key, const char* lang, const QString&);
#endif
private:
    void	init();
    void	reinit();
    void	freeBits();
    static void	warningIndexRange( const char *, int );
    QSize	scaleSize( const QSize &s, ScaleMode mode ) const;

    struct QImageData : public QShared {	// internal image data
    int	w;				// image width
    int	h;				// image height
    int	d;				// image depth
    int	ncols;				// number of colors
    int	nbytes;				// number of bytes data
    int	bitordr;			// bit order (1 bit depth)
    QRgb   *ctbl;				// color table
    uchar **bits;				// image data
    bool	alpha;				// alpha buffer
    int	dpmx;				// dots per meter X (or 0)
    int	dpmy;				// dots per meter Y (or 0)
    QPoint	offset;				// offset in pixels
#ifndef QT_NO_IMAGE_TEXT
    QImageDataMisc* misc;			// less common stuff
#endif
    bool    ctbl_mine;			// this allocated ctbl
    } *data;
#ifndef QT_NO_IMAGE_TEXT
    QImageDataMisc& misc() const;
#endif
    friend Q_EXPORT void bitBlt( QImage* dst, int dx, int dy,
                 const QImage* src, int sx, int sy,
                 int sw, int sh, int conversion_flags );
};

// QImage stream functions

#if !defined(QT_NO_DATASTREAM) && !defined(QT_NO_IMAGEIO)
Q_EXPORT QDataStream &operator<<( QDataStream &, const QImage & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QImage & );
#endif

#ifndef QT_NO_IMAGEIO
class QIODevice;
typedef void (*image_io_handler)( QImageIO * ); // image IO handler

struct QImageIOData;

class Q_EXPORT QImageIO
{
public:
    QImageIO();
    QImageIO( QIODevice	 *ioDevice, const char *format );
    QImageIO( const QString &fileName, const char* format );
   ~QImageIO();

    const QImage &image()	const	{ return im; }
    int		status()	const	{ return iostat; }
    const char *format()	const	{ return frmt; }
    QIODevice  *ioDevice()	const	{ return iodev; }
    QString	fileName()	const	{ return fname; }
    int		quality()	const;
    QString	description()	const	{ return descr; }
    const char *parameters()	const;
    float gamma() const;

    void	setImage( const QImage & );
    void	setStatus( int );
    void	setFormat( const char * );
    void	setIODevice( QIODevice * );
    void	setFileName( const QString & );
    void	setQuality( int );
    void	setDescription( const QString & );
    void	setParameters( const char * );
    void	setGamma( float );

    bool	read();
    bool	write();

    static const char* imageFormat( const QString &fileName );
    static const char *imageFormat( QIODevice * );
    static QStrList inputFormats();
    static QStrList outputFormats();

    static void defineIOHandler( const char *format,
                 const char *header,
                 const char *flags,
                 image_io_handler read_image,
                 image_io_handler write_image );

private:
    void	init();

    QImage	im;				// image
    int		iostat;				// IO status
    QCString	frmt;				// image format
    QIODevice  *iodev;				// IO device
    QString	fname;				// file name
    char       *params;				// image parameters //### change to QImageIOData *d in 3.0
    QString     descr;				// image description
    QImageIOData *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QImageIO( const QImageIO & );
    QImageIO &operator=( const QImageIO & );
#endif
};

#endif //QT_NO_IMAGEIO

Q_EXPORT void bitBlt( QImage* dst, int dx, int dy, const QImage* src,
              int sx=0, int sy=0, int sw=-1, int sh=-1,
              int conversion_flags=0 );

/*****************************************************************************
  QImage member functions
 *****************************************************************************/

inline bool QImage::hasAlphaBuffer() const
{
    return data->alpha;
}

inline uchar *QImage::bits() const
{
    return data->bits ? data->bits[0] : 0;
}

inline uchar **QImage::jumpTable() const
{
    return data->bits;
}

inline QRgb *QImage::colorTable() const
{
    return data->ctbl;
}

inline int QImage::numBytes() const
{
    return data->nbytes;
}

inline int QImage::bytesPerLine() const
{
    return data->h ? data->nbytes/data->h : 0;
}

inline QImage QImage::copy(const QRect& r) const
{
    return copy(r.x(), r.y(), r.width(), r.height());
}

inline QRgb QImage::color( int i ) const
{
#if defined(QT_CHECK_RANGE)
    if ( i >= data->ncols )
    warningIndexRange( "color", i );
#endif
    return data->ctbl ? data->ctbl[i] : (QRgb)-1;
}

inline void QImage::setColor( int i, QRgb c )
{
#if defined(QT_CHECK_RANGE)
    if ( i >= data->ncols )
    warningIndexRange( "setColor", i );
#endif
    if ( data->ctbl )
    data->ctbl[i] = c;
}

inline uchar *QImage::scanLine( int i ) const
{
#if defined(QT_CHECK_RANGE)
    if ( i >= data->h )
    warningIndexRange( "scanLine", i );
#endif
    return data->bits ? data->bits[i] : 0;
}

inline int QImage::dotsPerMeterX() const
{
    return data->dpmx;
}

inline int QImage::dotsPerMeterY() const
{
    return data->dpmy;
}

inline QPoint QImage::offset() const
{
    return data->offset;
}

#endif // QIMAGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QImage Member List

Complete Member List for QImage

This is the complete list of member functions for QImage, including inherited members.

  • QImage()
  • ~QImage()
  • allGray()
  • bitOrder()
  • bits()
  • bytesPerLine()
  • color()
  • colorTable()
  • convertBitOrder()
  • convertDepth()
  • convertDepthWithPalette()
  • copy()
  • create()
  • createAlphaMask()
  • createHeuristicMask()
  • depth()
  • detach()
  • dotsPerMeterX()
  • dotsPerMeterY()
  • fill()
  • hasAlphaBuffer()
  • height()
  • imageFormat()
  • inputFormatList()
  • inputFormats()
  • invertPixels()
  • isGrayscale()
  • isNull()
  • jumpTable()
  • load()
  • loadFromData()
  • mirror()
  • numBytes()
  • numColors()
  • offset()
  • operator!=()
  • operator=()
  • operator==()
  • outputFormatList()
  • outputFormats()
  • pixel()
  • pixelIndex()
  • rect()
  • reset()
  • save()
  • scale()
  • scaleHeight()
  • scaleWidth()
  • scanLine()
  • setAlphaBuffer()
  • setColor()
  • setDotsPerMeterX()
  • setDotsPerMeterY()
  • setNumColors()
  • setOffset()
  • setPixel()
  • setText()
  • size()
  • smoothScale()
  • swapRGB()
  • systemBitOrder()
  • systemByteOrder()
  • text()
  • textKeys()
  • textLanguages()
  • textList()
  • valid()
  • width()
  • xForm()


QImageConsumer Class

QImageConsumer Class Reference

The QImageConsumer class is an abstraction used by QImageDecoder. More...

#include <qasyncimageio.h>

List of all member functions.

Public Members

  • virtual void end () = 0
  • virtual void changed ( const QRect & ) = 0
  • virtual void frameDone () = 0
  • virtual void frameDone ( const QPoint & offset, const QRect & rect ) = 0
  • virtual void setLooping ( int n ) = 0
  • virtual void setFramePeriod ( int milliseconds ) = 0
  • virtual void setSize ( int, int ) = 0

Detailed Description

The QImageConsumer class is an abstraction used by QImageDecoder.

The QMovie class, or QLabel::setMovie(), are easy to use and for most situations do what you want with regards animated images.

A QImageConsumer consumes information about changes to the QImage maintained by a QImageDecoder. Think of the QImage as the model or source of the image data, with the QImageConsumer as a view of that data and the QImageDecoder being the controller that orchestrates the relationship between the model and the view.

You'd use the QImageConsumer class, for example, if you were implementing a web browser with your own image loaders.

See also QImageDecoder, Graphics Classes, Image Processing Classes and Multimedia Classes.

Member Function Documentation

void QImageConsumer::changed ( const QRect & ) [pure virtual]

Called when the given area of the image has changed.

void QImageConsumer::end () [pure virtual]

Called when all the data from all the frames has been decoded and revealed as changed().

void QImageConsumer::frameDone () [pure virtual]

One of the two frameDone() functions will be called when a frame of an animated image has ended and been revealed as changed().

When this function is called, the current image should be displayed.

The decoder will not make any further changes to the image until the next call to QImageFormat::decode().

void QImageConsumer::frameDone ( const QPoint & offset, const QRect & rect ) [pure virtual]

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

One of the two frameDone() functions will be called when a frame of an animated image has ended and been revealed as changed().

When this function is called, the area rect in the current image should be moved by offset and displayed.

The decoder will not make any further changes to the image until the next call to QImageFormat::decode().

void QImageConsumer::setFramePeriod ( int milliseconds ) [pure virtual]

Notes that the frame about to be decoded should not be displayed until the given number of milliseconds after the time that this function is called. Of course, the image may not have been decoded by then, in which case the frame should not be displayed until it is complete. A value of -1 (the assumed default) indicates that the image should be displayed even while it is only partially loaded.

void QImageConsumer::setLooping ( int n ) [pure virtual]

Called to indicate that the sequence of frames in the image should be repeated n times, including the sequence during decoding.

  • 0 = Forever
  • 1 = Only display frames the first time through
  • 2 = Repeat once after first pass through images
  • etc.

To make the QImageDecoder do this, just delete it and pass the information to it again for decoding (setLooping() will be called again, of course, but that can be ignored), or keep copies of the changed areas at the ends of frames.

void QImageConsumer::setSize ( int, int ) [pure virtual]

This function is called as soon as the size of the image has been determined.

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


QImageConsumer Member List

Complete Member List for QImageConsumer

This is the complete list of member functions for QImageConsumer, including inherited members.

  • changed()
  • end()
  • frameDone()
  • setFramePeriod()
  • setLooping()
  • setSize()


QImageDecoder Class

QImageDecoder Class Reference

The QImageDecoder class is an incremental image decoder for all supported image formats. More...

#include <qasyncimageio.h>

List of all member functions.

Public Members

  • QImageDecoder ( QImageConsumer * c )
  • ~QImageDecoder ()
  • const QImage & image ()
  • int decode ( const uchar * buffer, int length )

Static Public Members

  • const char * formatName ( const uchar * buffer, int length )
  • QImageFormatType * format ( const char * name )
  • QStrList inputFormats ()
  • void registerDecoderFactory ( QImageFormatType * f )
  • void unregisterDecoderFactory ( QImageFormatType * f )

Detailed Description

The QImageDecoder class is an incremental image decoder for all supported image formats.

New formats are installed by creating objects of class QImageFormatType; the QMovie class can be used for all installed incremental image formats. QImageDecoder is only useful for creating new ways of feeding data to an QImageConsumer.

A QImageDecoder is a machine that decodes images. It takes encoded image data via its decode() method and expresses its decoding by supplying information to a QImageConsumer. It implements its decoding by using a QImageFormat created by one of the currently-existing QImageFormatType factory objects.

QImageFormatType and QImageFormat are the classes that you might need to implement support for additional image formats.

Qt supports GIF reading if it is configured that way during installation (see qgif.h). If it is, we are required to state that "The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated."

Warning: If you are in a country that recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license that technology. Such countries include Canada, Japan, the USA, France, Germany, Italy and the UK.

GIF support may be removed completely in a future version of Qt. We recommend using the MNG or PNG format.

See also Graphics Classes, Image Processing Classes and Multimedia Classes.

Member Function Documentation

QImageDecoder::QImageDecoder ( QImageConsumer * c )

Constructs a QImageDecoder that will send change information to the QImageConsumer c.

QImageDecoder::~QImageDecoder ()

Destroys a QImageDecoder. The image it built is destroyed. The decoder built by the factory for the file format is destroyed. The consumer for which it decoded the image is not destroyed.

int QImageDecoder::decode ( const uchar * buffer, int length )

Call this function to decode some data into image changes. The data in buffer will be decoded, sending change information to the QImageConsumer of this QImageDecoder until one of the change functions of the consumer returns FALSE. The length of the data is given in length.

Returns the number of bytes consumed: 0 if consumption is complete, and -1 if decoding fails due to invalid data.

QImageFormatType * QImageDecoder::format ( const char * name ) [static]

Returns a QImageFormatType by name. This might be used when the user needs to force data to be interpreted as being in a certain format. name is one of the formats listed by QImageDecoder::inputFormats(). Note that you will still need to supply decodable data to result->decoderFor() before you can begin decoding the data.

const char * QImageDecoder::formatName ( const uchar * buffer, int length ) [static]

Call this function to find the name of the format of the given header. The returned string is statically allocated. The function will look at the first length characters in the buffer.

Returns 0 if the format is not recognized.

const QImage & QImageDecoder::image ()

Returns the image currently being decoded.

QStrList QImageDecoder::inputFormats () [static]

Returns a sorted list of formats for which asynchronous loading is supported.

void QImageDecoder::registerDecoderFactory ( QImageFormatType * f ) [static]

Registers the new QImageFormatType f. This is not needed in application code because factories call this themselves.

void QImageDecoder::unregisterDecoderFactory ( QImageFormatType * f ) [static]

Unregisters the QImageFormatType f. This is not needed in application code because factories call this themselves.

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


QImageDecoder Member List

Complete Member List for QImageDecoder

This is the complete list of member functions for QImageDecoder, including inherited members.

  • QImageDecoder()
  • ~QImageDecoder()
  • decode()
  • format()
  • formatName()
  • image()
  • inputFormats()
  • registerDecoderFactory()
  • unregisterDecoderFactory()


QImageDrag Class

QImageDrag Class Reference

The QImageDrag class provides a drag and drop object for transferring images. More...

#include <qdragobject.h>

Inherits QDragObject.

List of all member functions.

Public Members

  • QImageDrag ( QImage image, QWidget * dragSource = 0, const char * name = 0 )
  • QImageDrag ( QWidget * dragSource = 0, const char * name = 0 )
  • ~QImageDrag ()
  • virtual void setImage ( QImage image )

Static Public Members

  • bool canDecode ( const QMimeSource * e )
  • bool decode ( const QMimeSource * e, QImage & img )
  • bool decode ( const QMimeSource * e, QPixmap & pm )

Detailed Description

The QImageDrag class provides a drag and drop object for transferring images.

Images are offered to the receiving application in multiple formats, determined by Qt's output formats.

For more information about drag and drop, see the QDragObject class and the drag and drop documentation.

See also Drag And Drop Classes.

Member Function Documentation

QImageDrag::QImageDrag ( QImage image, QWidget * dragSource = 0, const char * name = 0 )

Constructs an image drag object and sets its data to image. dragSource must be the drag source; name is the object name.

QImageDrag::QImageDrag ( QWidget * dragSource = 0, const char * name = 0 )

Constructs a default image drag object. dragSource must be the drag source; name is the object name.

QImageDrag::~QImageDrag ()

Destroys the image drag object and frees up all allocated resources.

bool QImageDrag::canDecode ( const QMimeSource * e ) [static]

Returns TRUE if the information in mime source e can be decoded into an image; otherwise returns FALSE.

See also decode().

Example: desktop/desktop.cpp.

bool QImageDrag::decode ( const QMimeSource * e, QImage & img ) [static]

Attempts to decode the dropped information in mime source e into img. Returns TRUE if successful; otherwise returns FALSE.

See also canDecode().

Example: desktop/desktop.cpp.

bool QImageDrag::decode ( const QMimeSource * e, QPixmap & pm ) [static]

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

Attempts to decode the dropped information in mime source e into pixmap pm. Returns TRUE if successful; otherwise returns FALSE.

This is a convenience function that converts to a QPixmap via a QImage.

See also canDecode().

void QImageDrag::setImage ( QImage image ) [virtual]

Sets the image to be dragged to image. You will need to call this if you did not pass the image during construction.

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


QImageDrag Member List

Complete Member List for QImageDrag

This is the complete list of member functions for QImageDrag, including inherited members.

  • QImageDrag()
  • ~QImageDrag()
  • blockSignals()
  • canDecode()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • decode()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setImage()
  • setName()
  • setPixmap()
  • setProperty()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


QImageFormat Class

QImageFormat Class Reference

The QImageFormat class is an incremental image decoder for a specific image format. More...

#include <qasyncimageio.h>

List of all member functions.

Public Members

  • virtual int decode ( QImage & img, QImageConsumer * consumer, const uchar * buffer, int length ) = 0

Detailed Description

The QImageFormat class is an incremental image decoder for a specific image format.

By making a derived class of QImageFormatType, which in turn creates objects that are a subclass of QImageFormat, you can add support for more incremental image formats, allowing such formats to be sources for a QMovie or for the first frame of the image stream to be loaded as a QImage or QPixmap.

Your new subclass must reimplement the decode() function in order to process your new format.

New QImageFormat objects are generated by new QImageFormatType factories.

See also Graphics Classes, Image Processing Classes and Multimedia Classes.

Member Function Documentation

int QImageFormat::decode ( QImage & img, QImageConsumer * consumer, const uchar * buffer, int length ) [pure virtual]

New subclasses must reimplement this method.

It should decode some or all of the bytes from buffer into img, calling the methods of consumer as the decoding proceeds to inform that consumer of changes to the image. The length of the data is given in length. The consumer may be 0, in which case the function should just process the data into img without telling any consumer about the changes. Note that the decoder must store enough state to be able to continue in subsequent calls to this method - this is the essence of the incremental image loading.

The function should return without processing all the data if it reaches the end of a frame in the input.

The function must return the number of bytes it has processed.

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


QImageFormat Member List

Complete Member List for QImageFormat

This is the complete list of member functions for QImageFormat, including inherited members.

  • decode()


QImageFormatPlugin Class

QImageFormatPlugin Class Reference

The QImageFormatPlugin class provides an abstract base for custom image format plugins. More...

#include <qimageformatplugin.h>

List of all member functions.

Public Members

  • QImageFormatPlugin ()
  • ~QImageFormatPlugin ()
  • virtual QStringList keys () const = 0
  • virtual bool installIOHandler ( const QString & format ) = 0

Detailed Description

The QImageFormatPlugin class provides an abstract base for custom image format plugins.

The image format plugin is a simple plugin interface that makes it easy to create custom image formats that can be used transparently by applications.

Writing an image format plugin is achieved by subclassing this base class, reimplementing the pure virtual functions keys() and installIOHandler(), and exporting the class with the Q_EXPORT_PLUGIN macro. See the Plugins documentation for details.

See also Plugins.

Member Function Documentation

QImageFormatPlugin::QImageFormatPlugin ()

Constructs an image format plugin. This is invoked automatically by the Q_EXPORT_PLUGIN macro.

QImageFormatPlugin::~QImageFormatPlugin ()

Destroys the image format plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

bool QImageFormatPlugin::installIOHandler ( const QString & format ) [pure virtual]

Installs a QImageIO image I/O handler for the image format format.

See also keys().

QStringList QImageFormatPlugin::keys () const [pure virtual]

Returns the list of image formats this plugin supports.

See also installIOHandler().

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


qimageformatplugin.h Include File

qimageformatplugin.h

This is the verbatim text of the qimageformatplugin.h include file. It is provided only for illustration; the copyright remains with Trolltech.

#ifndef QIMAGEFORMATPLUGIN_H
#define QIMAGEFORMATPLUGIN_H

#ifndef QT_H
#include "qgplugin.h"
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_IMAGEFORMATPLUGIN
class QImageFormat;
class QImageFormatPluginPrivate;

class Q_EXPORT QImageFormatPlugin : public QGPlugin
{
    Q_OBJECT
public:
    QImageFormatPlugin();
    ~QImageFormatPlugin();

    virtual QStringList keys() const = 0;
    virtual bool loadImage( const QString &format, const QString &filename, QImage *image );
    virtual bool saveImage( const QString &format, const QString &filename, const QImage &image );
    virtual bool installIOHandler( const QString &format ) = 0;

private:
    QImageFormatPluginPrivate *d;
};
#endif // QT_NO_IMAGEFORMATPLUGIN
#endif // QIMAGEFORMATPLUGIN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QImageFormatPlugin Member List

Complete Member List for QImageFormatPlugin

This is the complete list of member functions for QImageFormatPlugin, including inherited members.

  • QImageFormatPlugin()
  • ~QImageFormatPlugin()
  • installIOHandler()
  • keys()


QImageFormatType Class

QImageFormatType Class Reference

The QImageFormatType class is a factory that makes QImageFormat objects. More...

#include <qasyncimageio.h>

List of all member functions.

Public Members

  • virtual ~QImageFormatType ()
  • virtual QImageFormat * decoderFor ( const uchar * buffer, int length ) = 0
  • virtual const char * formatName () const = 0

Protected Members

  • QImageFormatType ()

Detailed Description

The QImageFormatType class is a factory that makes QImageFormat objects.

Whereas the QImageIO class allows for complete loading of images, QImageFormatType allows for incremental loading of images.

New image file formats are installed by creating objects of derived classes of QImageFormatType. They must implement decoderFor() and formatName().

QImageFormatType is a very simple class. Its only task is to recognize image data in some format and make a new object, subclassed from QImageFormat, which can decode that format.

The factories for formats built into Qt are automatically defined before any other factory is initialized. If two factories would recognize an image format, the factory created last will override the earlier one; you can thus override current and future built-in formats.

See also Graphics Classes, Image Processing Classes and Multimedia Classes.

Member Function Documentation

QImageFormatType::QImageFormatType () [protected]

Constructs a factory. It automatically registers itself with QImageDecoder.

QImageFormatType::~QImageFormatType () [virtual]

Destroys a factory. It automatically unregisters itself from QImageDecoder.

QImageFormat * QImageFormatType::decoderFor ( const uchar * buffer, int length ) [pure virtual]

Returns a decoder for decoding an image that starts with the bytes in buffer. The length of the data is given in length. This function should only return a decoder if it is certain that the decoder applies to data with the given header. Returns 0 if there is insufficient data in the header to make a positive identification or if the data is not recognized.

const char * QImageFormatType::formatName () const [pure virtual]

Returns the name of the format supported by decoders from this factory. The string is statically allocated.

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


QImageFormatType Member List

Complete Member List for QImageFormatType

This is the complete list of member functions for QImageFormatType, including inherited members.

  • QImageFormatType()
  • ~QImageFormatType()
  • decoderFor()
  • formatName()


QImageIO Class

QImageIO Class Reference

The QImageIO class contains parameters for loading and saving images. More...

#include <qimage.h>

List of all member functions.

Public Members

  • QImageIO ()
  • QImageIO ( QIODevice * ioDevice, const char * format )
  • QImageIO ( const QString & fileName, const char * format )
  • ~QImageIO ()
  • const QImage & image () const
  • int status () const
  • const char * format () const
  • QIODevice * ioDevice () const
  • QString fileName () const
  • int quality () const
  • QString description () const
  • const char * parameters () const
  • float gamma () const
  • void setImage ( const QImage & image )
  • void setStatus ( int status )
  • void setFormat ( const char * format )
  • void setIODevice ( QIODevice * ioDevice )
  • void setFileName ( const QString & fileName )
  • void setQuality ( int q )
  • void setDescription ( const QString & description )
  • void setParameters ( const char * parameters )
  • void setGamma ( float gamma )
  • bool read ()
  • bool write ()

Static Public Members

  • const char * imageFormat ( const QString & fileName )
  • const char * imageFormat ( QIODevice * d )
  • QStrList inputFormats ()
  • QStrList outputFormats ()
  • void defineIOHandler ( const char * format, const char * header, const char * flags, image_io_handler readImage, image_io_handler writeImage )

Detailed Description

The QImageIO class contains parameters for loading and saving images.

QImageIO contains a QIODevice object that is used for image data I/O. The programmer can install new image file formats in addition to those that Qt provides.

Qt currently supports the following image file formats: PNG, BMP, XBM, XPM and PNM. It may also support JPEG, MNG and GIF, if specially configured during compilation. The different PNM formats are: PBM (P1 or P4), PGM (P2 or P5), and PPM (P3 or P6).

You don't normally need to use this class; QPixmap::load(), QPixmap::save(), and QImage contain sufficient functionality.

For image files that contain sequences of images, only the first is read. See QMovie for loading multiple images.

PBM, PGM, and PPM format output is always in the more condensed raw format. PPM and PGM files with more than 256 levels of intensity are scaled down when reading.

Warning: If you are in a country which recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license the technology. Such countries include Canada, Japan, the USA, France, Germany, Italy and the UK.

GIF support may be removed completely in a future version of Qt. We recommend using the PNG format.

See also QImage, QPixmap, QFile, QMovie, Graphics Classes, Image Processing Classes and Input/Output and Networking.

Member Function Documentation

QImageIO::QImageIO ()

Constructs a QImageIO object with all parameters set to zero.

QImageIO::QImageIO ( QIODevice * ioDevice, const char * format )

Constructs a QImageIO object with the I/O device ioDevice and a format tag.

QImageIO::QImageIO ( const QString & fileName, const char * format )

Constructs a QImageIO object with the file name fileName and a format tag.

QImageIO::~QImageIO ()

Destroys the object and all related data.

void QImageIO::defineIOHandler ( const char * format, const char * header, const char * flags, image_io_handler readImage, image_io_handler writeImage ) [static]

Defines an image I/O handler for the image format called format, which is recognized using the regular expression header, read using readImage and written using writeImage.

flags is a string of single-character flags for this format. The only flag defined currently is T (upper case), so the only legal value for flags are "T" and the empty string. The "T" flag means that the image file is a text file, and Qt should treat all newline conventions as equivalent. (XPM files and some PPM files are text files for example.)

format is used to select a handler to write a QImage; header is used to select a handler to read an image file.

If readImage is a null pointer, the QImageIO will not be able to read images in format. If writeImage is a null pointer, the QImageIO will not be able to write images in format. If both are null, the QImageIO object is valid but useless.

Example:

        void readGIF( QImageIO *image )
        {
        // read the image using the image->ioDevice()
        }

        void writeGIF( QImageIO *image )
        {
        // write the image using the image->ioDevice()
        }

        // add the GIF image handler

        QImageIO::defineIOHandler( "GIF",
                                   "^GIF[0-9][0-9][a-z]",
                                   0,
                                   readGIF,
                                   writeGIF );

Before the regex test, all the 0 bytes in the file header are converted to 1 bytes. This is done because when Qt was ASCII-based, QRegExp could not handle 0 bytes in strings.

(Note that if one handlerIO supports writing a format and another supports reading it, Qt supports both reading and writing. If two handlers support the same operation, Qt chooses one arbitrarily.)

QString QImageIO::description () const

Returns the image description string.

See also setDescription().

QString QImageIO::fileName () const

Returns the file name currently set.

See also setFileName().

const char * QImageIO::format () const

Returns the image format string or 0 if no format has been explicitly set.

float QImageIO::gamma () const

Returns the gamma value at which the image will be viewed.

See also setGamma().

const QImage & QImageIO::image () const

Returns the image currently set.

See also setImage().

const char * QImageIO::imageFormat ( const QString & fileName ) [static]

Returns a string that specifies the image format of the file fileName, or null if the file cannot be read or if the format is not recognized.

const char * QImageIO::imageFormat ( QIODevice * d ) [static]

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

Returns a string that specifies the image format of the image read from IO device d, or 0 if the device cannot be read or if the format is not recognized.

Make sure that d is at the right position in the device (for example, at the beginning of the file).

See also QIODevice::at().

QStrList QImageIO::inputFormats () [static]

Returns a sorted list of image formats that are supported for image input.

QIODevice * QImageIO::ioDevice () const

Returns the IO device currently set.

See also setIODevice().

QStrList QImageIO::outputFormats () [static]

Returns a sorted list of image formats that are supported for image output.

Example: scribble/scribble.cpp.

const char * QImageIO::parameters () const

Returns the image's parameters string.

See also setParameters().

int QImageIO::quality () const

Returns the quality of the written image, related to the compression ratio.

See also setQuality() and QImage::save().

bool QImageIO::read ()

Reads an image into memory and returns TRUE if the image was successfully read; otherwise returns FALSE.

Before reading an image you must set an IO device or a file name. If both an IO device and a file name have been set, the IO device will be used.

Setting the image file format string is optional.

Note that this function does not set the format used to read the image. If you need that information, use the imageFormat() static functions.

Example:

        QImageIO iio;
        QPixmap  pixmap;
        iio.setFileName( "vegeburger.bmp" );
        if ( image.read() )        // ok
            pixmap = iio.image();  // convert to pixmap

See also setIODevice(), setFileName(), setFormat(), write() and QPixmap::load().

void QImageIO::setDescription ( const QString & description )

Sets the image description string for image handlers that support image descriptions to description.

Currently, no image format supported by Qt uses the description string.

void QImageIO::setFileName ( const QString & fileName )

Sets the name of the file to read or write an image from to fileName.

See also setIODevice().

void QImageIO::setFormat ( const char * format )

Sets the image format to format for the image to be read or written.

It is necessary to specify a format before writing an image, but it is not necessary to specify a format before reading an image.

If no format has been set, Qt guesses the image format before reading it. If a format is set the image will only be read if it has that format.

See also read(), write() and format().

void QImageIO::setGamma ( float gamma )

Sets the gamma value at which the image will be viewed to gamma. If the image format stores a gamma value for which the image is intended to be used, then this setting will be used to modify the image. Setting to 0.0 will disable gamma correction (i.e. any specification in the file will be ignored).

The default value is 0.0.

See also gamma().

void QImageIO::setIODevice ( QIODevice * ioDevice )

Sets the IO device to be used for reading or writing an image.

Setting the IO device allows images to be read/written to any block-oriented QIODevice.

If ioDevice is not null, this IO device will override file name settings.

See also setFileName().

void QImageIO::setImage ( const QImage & image )

Sets the image to image.

See also image().

void QImageIO::setParameters ( const char * parameters )

Sets the image's parameter string to parameters. This is for image handlers that require special parameters.

Although the current image formats supported by Qt ignore the parameters string, it may be used in future extensions or by contributions (for example, JPEG).

See also parameters().

void QImageIO::setQuality ( int q )

Sets the quality of the written image to q, related to the compression ratio.

q must be in the range -1..100. Specify 0 to obtain small compressed files, 100 for large uncompressed files. (-1 signifies the default compression.)

See also quality() and QImage::save().

void QImageIO::setStatus ( int status )

Sets the image IO status to status. A non-zero value indicates an error, whereas 0 means that the IO operation was successful.

See also status().

int QImageIO::status () const

Returns the image's IO status. A non-zero value indicates an error, whereas 0 means that the IO operation was successful.

See also setStatus().

bool QImageIO::write ()

Writes an image to an IO device and returns TRUE if the image was successfully written; otherwise returns FALSE.

Before writing an image you must set an IO device or a file name. If both an IO device and a file name have been set, the IO device will be used.

The image will be written using the specified image format.

Example:

        QImageIO iio;
        QImage   im;
        im = pixmap; // convert to image
        iio.setImage( im );
        iio.setFileName( "vegeburger.bmp" );
        iio.setFormat( "BMP" );
        if ( iio.write() )
            // returned TRUE if written successfully

See also setIODevice(), setFileName(), setFormat(), read() and QPixmap::save().

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


QImageIO Member List

Complete Member List for QImageIO

This is the complete list of member functions for QImageIO, including inherited members.

  • QImageIO()
  • ~QImageIO()
  • defineIOHandler()
  • description()
  • fileName()
  • format()
  • gamma()
  • image()
  • imageFormat()
  • inputFormats()
  • ioDevice()
  • outputFormats()
  • parameters()
  • quality()
  • read()
  • setDescription()
  • setFileName()
  • setFormat()
  • setGamma()
  • setIODevice()
  • setImage()
  • setParameters()
  • setQuality()
  • setStatus()
  • status()
  • write()


QIMEvent Class

QIMEvent Class Reference

The QIMEvent class provides parameters for input method events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QIMEvent ( Type type, const QString & text, int cursorPosition )
  • const QString & text () const
  • int cursorPos () const
  • bool isAccepted () const
  • void accept ()
  • void ignore ()

Detailed Description

The QIMEvent class provides parameters for input method events.

Input method events are sent to widgets when an input method is used to enter text into a widget. Input methods are widely used to enter text in Asian and other complex languages.

The events are of interest to widgets that accept keyboard input and want to be able to correctly handle complex languages. Text input in such languages is usually a three step process.

  1. Starting to Compose
    When the user presses the first key on a keyboard an input context is created. This input context will contain a string with the typed characters.

  2. Composing
    With every new key pressed, the input method will try to create a matching string for the text typed so far. While the input context is active, the user can only move the cursor inside the string belonging to this input context.

  3. Completing
    At some point, e.g. when the user presses the Spacebar, they get to this stage, where they can choose from a number of strings that match the text they have typed so far. The user can press Enter to confirm their choice or Escape to cancel the input; in either case the input context will be closed.

Note that the particular key presses used for a given input context may differ from those we've mentioned here, i.e. they may not be Spacebar, Enter and Escape.

These three stages are represented by three different types of events. The IMStartEvent, IMComposeEvent and IMEndEvent. When a new input context is created, an IMStartEvent will be sent to the widget and delivered to the QWidget::imStartEvent() function. The widget can then update internal data structures to reflect this.

After this, an IMComposeEvent will be sent to the widget for every key the user presses. It will contain the current composition string the widget has to show and the current cursor position within the composition string. This string is temporary and can change with every key the user types, so the widget will need to store the state before the composition started (the state it had when it received the IMStartEvent). IMComposeEvents will be delivered to the QWidget::imComposeEvent() function.

Usually, widgets try to mark the part of the text that is part of the current composition in a way that is visible to the user. A commonly used visual cue is to use a dotted underline.

After the user has selected the final string, an IMEndEvent will be sent to the widget. The event contains the final string the user selected, and could be empty if they cancelled the composition. This string should be accepted as the final text the user entered, and the intermediate composition string should be cleared. These events are delivered to QWidget::imEndEvent().

If the user clicks another widget, taking the focus out of the widget where the composition is taking place the IMEndEvent will be sent and the string it holds will be the result of the composition up to that point (which may be an empty string).

See also Event Classes.

Member Function Documentation

QIMEvent::QIMEvent ( Type type, const QString & text, int cursorPosition )

Constructs a new QIMEvent with the accept flag set to FALSE. type can be one of QEvent::IMStartEvent, QEvent::IMComposeEvent or QEvent::IMEndEvent. text contains the current compostion string and cursorPosition the current position of the cursor inside text.

void QIMEvent::accept ()

Sets the accept flag of the input method event object.

Setting the accept parameter indicates that the receiver of the event processed the input method event.

The accept flag is not set by default.

See also ignore().

int QIMEvent::cursorPos () const

Returns the current cursor position inside the composition string. Will return 0 for IMStartEvent and IMEndEvent.

void QIMEvent::ignore ()

Clears the accept flag parameter of the input method event object.

Clearing the accept parameter indicates that the event receiver does not want the input method event.

The accept flag is cleared by default.

See also accept().

bool QIMEvent::isAccepted () const

Returns TRUE if the receiver of the event processed the event; otherwise returns FALSE.

const QString & QIMEvent::text () const

Returns the composition text. This is a null string for an IMStartEvent, and contains the final accepted string (which may be empty) in the IMEndEvent.

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


QIMEvent Member List

Complete Member List for QIMEvent

This is the complete list of member functions for QIMEvent, including inherited members.

  • QIMEvent()
  • accept()
  • cursorPos()
  • ignore()
  • isAccepted()
  • spontaneous()
  • text()
  • type()


QInputDialog类

QInputDialog类参考

QInputDialog类提供了从用户那里得到一个单一值的简单方便的对话框。 详情请见……

#include <qinputdialog.h>

继承了QDialog。

所有成员函数的列表。

静态公有成员

  • QString getText ( const QString & caption, const QString & label, QLineEdit::EchoMode mode = QLineEdit::Normal, const QString & text = QString::null, bool * ok = 0, QWidget * parent = 0, const char * name = 0 )
  • int getInteger ( const QString & caption, const QString & label, int num = 0, int from = -2147483647, int to = 2147483647, int step = 1, bool * ok = 0, QWidget * parent = 0, const char * name = 0 )
  • double getDouble ( const QString & caption, const QString & label, double num = 0, double from = -2147483647, double to = 2147483647, int decimals = 1, bool * ok = 0, QWidget * parent = 0, const char * name = 0 )
  • QString getItem ( const QString & caption, const QString & label, const QStringList & list, int current = 0, bool editable = TRUE, bool * ok = 0, QWidget * parent = 0, const char * name = 0 )

详细描述

QInputDialog类提供了从用户那里得到一个单一值的简单方便的对话框。

输入值可以是字符串、数字或者列表中的一项。必须设置标签来告诉用户应该输入什么。

这里有四个方便的函数被提供：getText()、getInteger()、getDouble()和getItem()。所有这些函数都可以按相似的方式使用，例如：

  bool ok = FALSE;
  QString text = QInputDialog::getText(
                    tr( "Application name" ),
                    tr( "Please enter your name" ),
                    QLineEdit::Normal, QString::null, &ok, this );
  if ( ok && !text.isEmpty() )
      ;// 用户输入一些东西并且按下OK
  else
      ;// 用户不输入任何东西或者按下Cancel

也可以参考对话框类。

成员函数文档

double QInputDialog::getDouble ( const QString & caption, const QString & label, double num = 0, double from = -2147483647, double to = 2147483647, int decimals = 1, bool * ok = 0, QWidget * parent = 0, const char * name = 0 ) [静态]

从用户那里得到浮点数的静态方便函数。caption是这个对话框在标题栏显示的文本。label是显示给用户的文本（它应该告诉用户应该输入什么）。num是这个行编辑中所要设置的默认的浮点数值。from和to是最小值和最大值，用户应该在这个范围内进行选择并且decimals小数点后面小数的最大位数。

对话框的父对象为parent、名称为name。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。对话框将是模式的。

这个函数返回用户输入的浮点数。

像这样使用这个静态函数：

  bool ok = FALSE;
  double res = QInputDialog::getDouble(
                tr( "Application name" ),
                tr( "Please enter a decimal number" ),
                33.7, 0, 1000, 2, &ok, this );
  if ( ok )
      ;// 用户输入一些东西并且按下OK
  else
      ;// 用户按下Cancel

int QInputDialog::getInteger ( const QString & caption, const QString & label, int num = 0, int from = -2147483647, int to = 2147483647, int step = 1, bool * ok = 0, QWidget * parent = 0, const char * name = 0 ) [静态]

从用户那里得到整数的静态方便函数。caption是这个对话框在标题栏显示的文本。label是显示给用户的文本（它应该告诉用户应该输入什么）。num是微调框中所要设置的默认整数。from和to是最小值和最大值，用户应该在这个范围内进行选择并且step是用户通过点击上下箭头增加或者减少的数值。

对话框的父对象为parent、名称为name。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。对话框将是模式的。

这个函数返回用户输入的整数。

像这样使用这个静态函数：

  bool ok = FALSE;
  int res = QInputDialog::getInteger(
                tr( "Application name" ),
                tr( "Please enter a number" ), 22, 0, 1000, 2, &ok, this );
  if ( ok )
      ;// 用户输入一些东西并且按下OK
  else
      ;// 用户按下Cancel

QString QInputDialog::getItem ( const QString & caption, const QString & label, const QStringList & list, int current = 0, bool editable = TRUE, bool * ok = 0, QWidget * parent = 0, const char * name = 0 ) [静态]

让用户从一个字符串列表中选择一项的静态方便函数。caption是这个对话框在标题栏显示的文本。label是显示给用户的文本（它应该告诉用户应该输入什么）。list是插入到组合框中的字符串列表，并且current是指哪一项为当前项。如果editable为真，则用户可以输入自己的文本，如果editable为假，则用户只能选择已有的项中的一项。

对话框的父对象为parent、名称为name。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。对话框将是模式的。

这个函数返回当前项的文本，或者如果editable为真，就是组合框的当前文本。

像这样使用这个静态函数：

  QStringList lst;
  lst << "First" << "Second" << "Third" << "Fourth" << "Fifth";
  bool ok = FALSE;
  QString res = QInputDialog::getItem(
                    tr( "Application name" ),
                    tr( "Please select an item" ), lst, 1, TRUE, &ok, this );
  if ( ok )
      ;// 用户选择一项并且按下OK
  else
      ;// 用户按下Cancel

QString QInputDialog::getText ( const QString & caption, const QString & label, QLineEdit::EchoMode mode = QLineEdit::Normal, const QString & text = QString::null, bool * ok = 0, QWidget * parent = 0, const char * name = 0 ) [静态]

从用户那里得到一个字符串的静态方便函数。caption是这个对话框在标题栏显示的文本。label是显示给用户的文本（它应该告诉用户应该输入什么）。text是放置在行编辑中的默认文本。mode是行编辑的回显模式。

对话框的父对象为parent、名称为name。如果ok参数为非零，则如果用户点击OK，*ok被设置为真，并且如果用户点击Cancel，就被设置为假。对话框将是模式的。

这个函数返回用户在行编辑中输入的文本。如果没有输入，就返回空字符串。

像这样使用这个静态函数：

  bool ok = FALSE;
  QString text = QInputDialog::getText(
                    tr( "Application name" ),
                    tr( "Please enter your name" ),
                    QLineEdit::Normal, QString::null, &ok, this );
  if ( ok && !text.isEmpty() )
      ;// 用户输入一些东西并且按下OK
  else
      ;// 用户不输入任何东西或者按下Cancel

实例：network/ftpclient/ftpmainwindow.cpp。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qinputdialog.h包含文件

qinputdialog.h

这里是qinputdialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qinputdialog.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QInputDialog class
**
** Created : 991212
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QINPUTDIALOG_H
#define QINPUTDIALOG_H

#ifndef QT_H
#include <qdialog.h>
#include <qstring.h>
#include <qlineedit.h>
#endif // QT_H

#ifndef QT_NO_INPUTDIALOG

class QSpinBox;
class QComboBox;
class QInputDialogPrivate;

class Q_EXPORT QInputDialog : public QDialog
{
#if defined(Q_CC_MSVC)
    friend class QInputDialog;
#endif
    Q_OBJECT

private:
    enum Type { LineEdit, SpinBox, ComboBox, EditableComboBox };

    QInputDialog( const QString &label, QWidget* parent=0, const char* name=0,
         bool modal = TRUE, Type type = LineEdit );
    ~QInputDialog();

    QLineEdit *lineEdit() const;
    QSpinBox *spinBox() const;
    QComboBox *comboBox() const;
    QComboBox *editableComboBox() const;

    void setType( Type t );
    Type type() const;

public:
    static QString getText( const QString &caption, const QString &label, QLineEdit::EchoMode echo = QLineEdit::Normal,
                const QString &text = QString::null, bool *ok = 0, QWidget *parent = 0, const char *name = 0 );
    static int getInteger( const QString &caption, const QString &label, int num = 0, int from = -2147483647,
               int to = 2147483647,
               int step = 1, bool *ok = 0, QWidget *parent = 0, const char *name = 0 );
    static double getDouble( const QString &caption, const QString &label, double num = 0,
                 double from = -2147483647, double to = 2147483647,
                 int decimals = 1, bool *ok = 0, QWidget *parent = 0, const char *name = 0 );
    static QString getItem( const QString &caption, const QString &label, const QStringList &list,
                int current = 0, bool editable = TRUE,
                bool *ok = 0, QWidget *parent = 0, const char *name = 0 );

private slots:
    void textChanged( const QString &s );
    void tryAccept();

private:
    QInputDialogPrivate *d;
    friend class QInputDialogPrivate; /* to avoid 'has no friends' warnings... */

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QInputDialog( const QInputDialog & );
    QInputDialog &operator=( const QInputDialog & );
#endif
};

#endif // QT_NO_INPUTDIALOG

#endif // QINPUTDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QInputDialog成员列表

完整的QInputDialog成员列表

这里是QInputDialog成员函数的完整列表，包括继承的成员。

  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getDouble()
  • getInteger()
  • getItem()
  • getText()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QIntCache Class

QIntCache Class Reference

The QIntCache class is a template class that provides a cache based on long keys. More...

#include <qintcache.h>

List of all member functions.

Public Members

  • QIntCache ( int maxCost = 100, int size = 17 )
  • ~QIntCache ()
  • int maxCost () const
  • int totalCost () const
  • void setMaxCost ( int m )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • bool insert ( long k, const type * d, int c = 1, int p = 0 )
  • bool remove ( long k )
  • type * take ( long k )
  • virtual void clear ()
  • type * find ( long k, bool ref = TRUE ) const
  • type * operator[] ( long k ) const
  • void statistics () const

Detailed Description

The QIntCache class is a template class that provides a cache based on long keys.

QIntCache is implemented as a template class. Define a template instance QIntCache<X> to create a cache that operates on pointers to X, or X*.

A cache is a least recently used (LRU) list of cache items, accessed via long keys. Each cache item has a cost. The sum of item costs, totalCost(), will not exceed the maximum cache cost, maxCost(). If inserting a new item would cause the total cost to exceed the maximum cost, the least recently used items in the cache are removed.

Apart from insert(), by far the most important function is find() (which also exists as operator[]). This function looks up an item, returns it, and by default marks it as being the most recently used item.

There are also methods to remove() or take() an object from the cache. Calling setAutoDelete(TRUE) for a cache tells it to delete items that are removed. The default is to not delete items when they are removed (i.e. remove() and take() are equivalent).

When inserting an item into the cache, only the pointer is copied, not the item itself. This is called a shallow copy. It is possible to make the dictionary copy all of the item's data (known as a deep copy) when an item is inserted. insert() calls the virtual function QPtrCollection::newItem() for the item to be inserted. Inherit a dictionary and reimplement it if you want deep copies.

When removing a cache item if auto-deletion is enabled the item will be automatically deleted.

There is a QIntCacheIterator which may be used to traverse the items in the cache in arbitrary order.

See also QIntCacheIterator, QCache, QAsciiCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QIntCache::QIntCache ( int maxCost = 100, int size = 17 )

Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items.

size is actually the size of an internal hash array; it's usually best to make it prime and at least 50% bigger than the largest expected number of items in the cache.

Each inserted item is associated with a cost. When inserting a new item, if the total cost of all items in the cache will exceed maxCost, the cache will start throwing out the older (least recently used) items until there is enough room for the new item to be inserted.

QIntCache::~QIntCache ()

Removes all items from the cache and then destroys the int cache. If auto-deletion is enabled the cache's items are deleted. All iterators that access this cache will be reset.

void QIntCache::clear () [virtual]

Removes all items from the cache, and deletes them if auto-deletion has been enabled.

All cache iterators that operate this on cache are reset.

See also remove() and take().

uint QIntCache::count () const [virtual]

Returns the number of items in the cache.

See also totalCost().

type * QIntCache::find ( long k, bool ref = TRUE ) const

Returns the item associated with k, or null if the key does not exist in the cache. If ref is TRUE (the default), the item is moved to the front of the LRU list.

If there are two or more items with equal keys, the one that was inserted last is returned.

bool QIntCache::insert ( long k, const type * d, int c = 1, int p = 0 )

Inserts the item d into the cache with key k and cost c (default 1). Returns TRUE if it succeeds and FALSE if it fails.

The cache's size is limited, and if the total cost is too high, QIntCache will remove old, least-used items until there is room for this new item.

The parameter p is internal and should be left at the default value (0).

Warning: If this function returns FALSE, you must delete d yourself. Additionally, be very careful about using d after calling this function. Any other insertions into the cache, from anywhere in the application or within Qt itself, could cause the object to be discarded from the cache and the pointer to become invalid.

bool QIntCache::isEmpty () const

Returns TRUE if the cache is empty; otherwise returns FALSE.

int QIntCache::maxCost () const

Returns the maximum allowed total cost of the cache.

See also setMaxCost() and totalCost().

type * QIntCache::operator[] ( long k ) const

Returns the item associated with k, or null if k does not exist in the cache, and moves the item to the front of the LRU list.

If there are two or more items with equal keys, the one that was inserted last is returned.

This is the same as find( k, TRUE ).

See also find().

bool QIntCache::remove ( long k )

Removes the item associated with k, and returns TRUE if the item was present in the cache or FALSE if it was not.

The item is deleted if auto-deletion has been enabled, i.e. if you have called setAutoDelete(TRUE).

If there are two or more items with equal keys, the one that was inserted last is removed.

All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.

See also take() and clear().

void QIntCache::setMaxCost ( int m )

Sets the maximum allowed total cost of the cache to m. If the current total cost is above m, some items are removed immediately.

See also maxCost() and totalCost().

uint QIntCache::size () const

Returns the size of the hash array used to implement the cache. This should be a bit larger than count() is likely to be.

void QIntCache::statistics () const

A debug-only utility function. Prints out cache usage, hit/miss, and distribution information using qDebug(). This function does nothing in the release library.

type * QIntCache::take ( long k )

Takes the item associated with k out of the cache without deleting it, and returns a pointer to the item taken out or null if the key does not exist in the cache.

If there are two or more items with equal keys, the one that was inserted last is taken.

All iterators that refer to the taken item are set to point to the next item in the cache's traversal order.

See also remove() and clear().

int QIntCache::totalCost () const

Returns the total cost of the items in the cache. This is an integer in the range 0 to maxCost().

See also setMaxCost().

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


qintcache.h Include File

qintcache.h

This is the verbatim text of the qintcache.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QIntCache template class
**
** Created : 950209
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QINTCACHE_H
#define QINTCACHE_H

#ifndef QT_H
#include "qgcache.h"
#endif // QT_H

template<class type>
class QIntCache
: public QGCache
{
public:
    QIntCache( const QIntCache<type> &c ) : QGCache(c) {}
    QIntCache( int maxCost=100, int size=17 )
    : QGCache( maxCost, size, IntKey, FALSE, FALSE ) {}
   ~QIntCache()		{ clear(); }
    QIntCache<type> &operator=( const QIntCache<type> &c )
            { return (QIntCache<type>&)QGCache::operator=(c); }
    int	  maxCost()   const	{ return QGCache::maxCost(); }
    int	  totalCost() const	{ return QGCache::totalCost(); }
    void  setMaxCost( int m)	{ QGCache::setMaxCost(m); }
    uint  count()     const	{ return QGCache::count(); }
    uint  size()      const	{ return QGCache::size(); }
    bool  isEmpty()   const	{ return QGCache::count() == 0; }
    bool  insert( long k, const type *d, int c=1, int p=0 )
        { return QGCache::insert_other((const char*)k,(Item)d,c,p); }
    bool  remove( long k )
        { return QGCache::remove_other((const char*)k); }
    type *take( long k )
        { return (type *)QGCache::take_other((const char*)k);}
    void  clear()		{ QGCache::clear(); }
    type *find( long k, bool ref=TRUE ) const
        { return (type *)QGCache::find_other( (const char*)k,ref);}
    type *operator[]( long k ) const
        { return (type *)QGCache::find_other( (const char*)k); }
    void  statistics() const { QGCache::statistics(); }
private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QIntCache<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QIntCache<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QIntCacheIterator
: public QGCacheIterator
{
public:
    QIntCacheIterator( const QIntCache<type> &c )
    : QGCacheIterator( (QGCache &)c ) {}
    QIntCacheIterator( const QIntCacheIterator<type> &ci )
                  : QGCacheIterator((QGCacheIterator &)ci) {}
    QIntCacheIterator<type> &operator=( const QIntCacheIterator<type>&ci )
    { return ( QIntCacheIterator<type>&)QGCacheIterator::operator=( ci );}
    uint  count()   const     { return QGCacheIterator::count(); }
    bool  isEmpty() const     { return QGCacheIterator::count() == 0; }
    bool  atFirst() const     { return QGCacheIterator::atFirst(); }
    bool  atLast()  const     { return QGCacheIterator::atLast(); }
    type *toFirst()	      { return (type *)QGCacheIterator::toFirst(); }
    type *toLast()	      { return (type *)QGCacheIterator::toLast(); }
    operator type *()  const  { return (type *)QGCacheIterator::get(); }
    type *current()    const  { return (type *)QGCacheIterator::get(); }
    long  currentKey() const  { return (long)QGCacheIterator::getKeyInt();}
    type *operator()()	      { return (type *)QGCacheIterator::operator()();}
    type *operator++()	      { return (type *)QGCacheIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGCacheIterator::operator+=(j);}
    type *operator--()	      { return (type *)QGCacheIterator::operator--(); }
    type *operator-=(uint j)  { return (type *)QGCacheIterator::operator-=(j);}
};

#endif // QINTCACHE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QIntCache Member List

Complete Member List for QIntCache

This is the complete list of member functions for QIntCache, including inherited members.

  • ~QIntCache()
  • clear()
  • count()
  • find()
  • insert()
  • isEmpty()
  • maxCost()
  • operator[]()
  • remove()
  • setMaxCost()
  • size()
  • statistics()
  • take()
  • totalCost()


QIntCacheIterator Class

QIntCacheIterator Class Reference

The QIntCacheIterator class provides an iterator for QIntCache collections. More...

#include <qintcache.h>

List of all member functions.

Public Members

  • QIntCacheIterator ( const QIntCache<type> & cache )
  • QIntCacheIterator ( const QIntCacheIterator<type> & ci )
  • QIntCacheIterator<type> & operator= ( const QIntCacheIterator<type> & ci )
  • uint count () const
  • bool isEmpty () const
  • bool atFirst () const
  • bool atLast () const
  • type * toFirst ()
  • type * toLast ()
  • operator type * () const
  • type * current () const
  • long currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )
  • type * operator-- ()
  • type * operator-= ( uint jump )

Detailed Description

The QIntCacheIterator class provides an iterator for QIntCache collections.

Note that the traversal order is arbitrary; you are not guaranteed any particular order. If new objects are inserted into the cache while the iterator is active, the iterator may or may not see them.

Multiple iterators are completely independent, even when they operate on the same QIntCache. QIntCache updates all iterators that refer an item when that item is removed.

QIntCacheIterator provides an operator++(), and an operator+=() to traverse the cache; current() and currentKey() to access the current cache item and its key; atFirst() atLast(), which return TRUE if the iterator points to the first/last item in the cache; isEmpty(), which returns TRUE if the cache is empty; and count(), which returns the number of items in the cache.

Note that atFirst() and atLast() refer to the iterator's arbitrary ordering, not to the cache's internal LRU list.

See also QIntCache, Collection Classes and Non-GUI Classes.

Member Function Documentation

QIntCacheIterator::QIntCacheIterator ( const QIntCache<type> & cache )

Constructs an iterator for cache. The current iterator item is set to point to the first item in the cache (or rather, the first item is defined to be the item at which this constructor sets the iterator to point).

QIntCacheIterator::QIntCacheIterator ( const QIntCacheIterator<type> & ci )

Constructs an iterator for the same cache as ci. The new iterator starts at the same item as ci.current(), but moves independently from there on.

bool QIntCacheIterator::atFirst () const

Returns TRUE if the iterator points to the first item in the cache; otherwise returns FALSE. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal LRU list.

See also toFirst() and atLast().

bool QIntCacheIterator::atLast () const

Returns TRUE if the iterator points to the last item in the cache; otherwise returns FALSE. Note that this refers to the iterator's arbitrary ordering, not to the cache's internal LRU list.

See also toLast() and atFirst().

uint QIntCacheIterator::count () const

Returns the number of items in the cache on which this iterator operates.

See also isEmpty().

type * QIntCacheIterator::current () const

Returns a pointer to the current iterator item.

long QIntCacheIterator::currentKey () const

Returns the key for the current iterator item.

bool QIntCacheIterator::isEmpty () const

Returns TRUE if the cache is empty; otherwise returns FALSE.

See also count().

QIntCacheIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QIntCacheIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the cache or if it was null, null is returned.

type * QIntCacheIterator::operator++ ()

Prefix ++ makes the iterator point to the item just after current(), and makes it the new current item for the iterator. If current() was the last item, operator--() returns 0.

type * QIntCacheIterator::operator+= ( uint jump )

Returns the item jump positions after the current item, or null if it is beyond the last item. Makes this the current item.

type * QIntCacheIterator::operator-- ()

Prefix -- makes the iterator point to the item just before current(), and makes it the new current item for the iterator. If current() was the first item, operator--() returns 0.

type * QIntCacheIterator::operator-= ( uint jump )

Returns the item jump positions before the current item, or null if it is beyond the first item. Makes this the current item.

QIntCacheIterator<type> & QIntCacheIterator::operator= ( const QIntCacheIterator<type> & ci )

Makes this an iterator for the same cache as ci. The new iterator starts at the same item as ci.current(), but moves independently thereafter.

type * QIntCacheIterator::toFirst ()

Sets the iterator to point to the first item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if if the cache is empty.

See also toLast() and isEmpty().

type * QIntCacheIterator::toLast ()

Sets the iterator to point to the last item in the cache and returns a pointer to the item.

Sets the iterator to null and returns null if if the cache is empty.

See also toFirst() and isEmpty().

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


QIntCacheIterator Member List

Complete Member List for QIntCacheIterator

This is the complete list of member functions for QIntCacheIterator, including inherited members.

  • QIntCacheIterator()
  • atFirst()
  • atLast()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()


QIntDict Class

QIntDict Class Reference

The QIntDict class is a template class that provides a dictionary based on long keys. More...

#include <qintdict.h>

Inherits QPtrCollection.

List of all member functions.

Public Members

  • QIntDict ( int size = 17 )
  • QIntDict ( const QIntDict<type> & dict )
  • ~QIntDict ()
  • QIntDict<type> & operator= ( const QIntDict<type> & dict )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • void insert ( long key, const type * item )
  • void replace ( long key, const type * item )
  • bool remove ( long key )
  • type * take ( long key )
  • type * find ( long key ) const
  • type * operator[] ( long key ) const
  • virtual void clear ()
  • void resize ( uint newsize )
  • void statistics () const

Important Inherited Members

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

Protected Members

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item ) const

Detailed Description

The QIntDict class is a template class that provides a dictionary based on long keys.

QMap is an STL-compatible alternative to this class.

QIntDict is implemented as a template class. Define a template instance QIntDict<X> to create a dictionary that operates on pointers to X (X*).

A dictionary is a collection of key-value pairs. The key is an long used for insertion, removal and lookup. The value is a pointer. Dictionaries provide very fast insertion and lookup.

Example:

    QIntDict<QLineEdit> fields;
    for ( int i = 0; i < 3; i++ )
        fields.insert( i, new QLineEdit( this ) );

    fields[0]->setText( "Homer" );
    fields[1]->setText( "Simpson" );
    fields[2]->setText( "45" );

    QIntDictIterator<char> it( fields ); // See QIntDictIterator
    for ( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;

    for ( int i = 0; i < 3; i++ )
        cout << fields[i]->text() << " "; // Prints "Homer Simpson 45"
    cout << endl;

    fields.remove( 1 ); // Does not delete the line edit
    for ( int i = 0; i < 3; i++ )
        if ( fields[i] )
            cout << fields[i]->text() << " "; // Prints "Homer 45"

See QDict for full details, including the choice of dictionary size, and how deletions are handled.

See also QIntDictIterator, QDict, QAsciiDict, QPtrDict, Collection Classes, Collection Classes and Non-GUI Classes.

Member Function Documentation

QIntDict::QIntDict ( int size = 17 )

Constructs a dictionary using an internal hash array of size size.

Setting size to a suitably large prime number (equal to or greater than the expected number of entries) makes the hash distribution better and hence the lookup faster.

QIntDict::QIntDict ( const QIntDict<type> & dict )

Constructs a copy of dict.

Each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy).

QIntDict::~QIntDict ()

Removes all items from the dictionary and destroys it.

All iterators that access this dictionary will be reset.

See also setAutoDelete().

bool QPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is FALSE.

See also setAutoDelete().

void QIntDict::clear () [virtual]

Removes all items from the dictionary.

The removed items are deleted if auto-deletion is enabled.

All dictionary iterators that access this dictionary will be reset.

See also remove(), take() and setAutoDelete().

Reimplemented from QPtrCollection.

uint QIntDict::count () const [virtual]

Returns the number of items in the dictionary.

See also isEmpty().

Reimplemented from QPtrCollection.

type * QIntDict::find ( long key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the last inserted of these will be found.

Equivalent to the [] operator.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also operator[]().

Example: table/bigtable/main.cpp.

void QIntDict::insert ( long key, const type * item )

Insert item item into the dictionary using key key.

The key does not have to be unique. If multiple items are inserted with the same key, only the last item will be visible.

Null items are not allowed.

See also replace().

Example: scribble/scribble.cpp.

bool QIntDict::isEmpty () const

Returns TRUE if the dictionary is empty; otherwise returns FALSE.

See also count().

QIntDict<type> & QIntDict::operator= ( const QIntDict<type> & dict )

Assigns dict to this dictionary and returns a reference to this dictionary.

This dictionary is first cleared and then each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy), unless newItem() has been reimplemented.

type * QIntDict::operator[] ( long key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the last inserted of these will be found.

Equivalent to the find() function.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also find().

QDataStream & QIntDict::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

Reads a dictionary item from the stream s and returns a reference to the stream.

The default implementation sets item to 0.

See also write().

bool QIntDict::remove ( long key )

Removes the item associated with key from the dictionary. Returns TRUE if successful; otherwise returns FALSE, e.g. if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last inserted of these will be removed.

The removed item is deleted if auto-deletion is enabled.

All dictionary iterators that refer to the removed item will be set to point to the next item in the dictionary's traversing order.

See also take(), clear() and setAutoDelete().

Example: table/bigtable/main.cpp.

void QIntDict::replace ( long key, const type * item )

If the dictionary has key key, this key's item is replaced with item. If the dictionary doesn't contain key key, item is inserted into the dictionary using key key.

Null items are not allowed.

Equivalent to:

    QIntDict<char> dict;
    //  ...
    if ( dict.find(key) )
        dict.remove( key );
    dict.insert( key, item );

If there are two or more items with equal keys, then the last inserted of these will be replaced.

See also insert().

Example: table/bigtable/main.cpp.

void QIntDict::resize ( uint newsize )

Changes the size of the hashtable to newsize. The contents of the dictionary are preserved, but all iterators on the dictionary become invalid.

void QPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is TRUE and to never delete them if enable is FALSE.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is FALSE, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp and table/bigtable/main.cpp.

uint QIntDict::size () const

Returns the size of the internal hash array (as specified in the constructor).

See also count().

void QIntDict::statistics () const

Debugging-only function that prints out the dictionary distribution using qDebug().

type * QIntDict::take ( long key )

Takes the item associated with key out of the dictionary without deleting it (even if auto-deletion is enabled).

If there are two or more items with equal keys, then the last inserted of these will be taken.

Returns a pointer to the item taken out, or null if the key does not exist in the dictionary.

All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary's traversing order.

See also remove(), clear() and setAutoDelete().

QDataStream & QIntDict::write ( QDataStream & s, QPtrCollection::Item ) const [virtual protected]

Writes a dictionary item to the stream s and returns a reference to the stream.

See also read().

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


qintdict.h Include File

qintdict.h

This is the verbatim text of the qintdict.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QIntDict template class
**
** Created : 940624
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QINTDICT_H
#define QINTDICT_H

#ifndef QT_H
#include "qgdict.h"
#endif // QT_H

template<class type>
class QIntDict
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGDict
#endif
{
public:
    QIntDict(int size=17) : QGDict(size,IntKey,0,0) {}
    QIntDict( const QIntDict<type> &d ) : QGDict(d) {}
   ~QIntDict()				{ clear(); }
    QIntDict<type> &operator=(const QIntDict<type> &d)
            { return (QIntDict<type>&)QGDict::operator=(d); }
    uint  count()   const		{ return QGDict::count(); }
    uint  size()    const		{ return QGDict::size(); }
    bool  isEmpty() const		{ return QGDict::count() == 0; }
    void  insert( long k, const type *d )
                    { QGDict::look_int(k,(Item)d,1); }
    void  replace( long k, const type *d )
                    { QGDict::look_int(k,(Item)d,2); }
    bool  remove( long k )		{ return QGDict::remove_int(k); }
    type *take( long k )		{ return (type*)QGDict::take_int(k); }
    type *find( long k ) const
        { return (type *)((QGDict*)this)->QGDict::look_int(k,0,0); }
    type *operator[]( long k ) const
        { return (type *)((QGDict*)this)->QGDict::look_int(k,0,0); }
    void  clear()			{ QGDict::clear(); }
    void  resize( uint n )		{ QGDict::resize(n); }
    void  statistics() const		{ QGDict::statistics(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream &, QPtrCollection::Item & );
    virtual QDataStream& write( QDataStream &, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QIntDict<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QIntDict<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type*)d;
}

template<class type>
class QIntDictIterator
: public QGDictIterator
{
public:
    QIntDictIterator(const QIntDict<type> &d) :QGDictIterator((QGDict &)d) {}
   ~QIntDictIterator()	      {}
    uint  count()   const     { return dict->count(); }
    bool  isEmpty() const     { return dict->count() == 0; }
    type *toFirst()	      { return (type *)QGDictIterator::toFirst(); }
    operator type *()  const  { return (type *)QGDictIterator::get(); }
    type *current()    const  { return (type *)QGDictIterator::get(); }
    long  currentKey() const  { return QGDictIterator::getKeyInt(); }
    type *operator()()	      { return (type *)QGDictIterator::operator()(); }
    type *operator++()	      { return (type *)QGDictIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGDictIterator::operator+=(j);}
};

#endif // QINTDICT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QIntDict Member List

Complete Member List for QIntDict

This is the complete list of member functions for QIntDict, including inherited members.

  • QIntDict()
  • ~QIntDict()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • find()
  • insert()
  • isEmpty()
  • newItem()
  • operator=()
  • operator[]()
  • read()
  • remove()
  • replace()
  • resize()
  • setAutoDelete()
  • size()
  • statistics()
  • take()
  • write()


QIntDictIterator Class

QIntDictIterator Class Reference

The QIntDictIterator class provides an iterator for QIntDict collections. More...

#include <qintdict.h>

List of all member functions.

Public Members

  • QIntDictIterator ( const QIntDict<type> & dict )
  • ~QIntDictIterator ()
  • uint count () const
  • bool isEmpty () const
  • type * toFirst ()
  • operator type * () const
  • type * current () const
  • long currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )

Detailed Description

The QIntDictIterator class provides an iterator for QIntDict collections.

QIntDictIterator is implemented as a template class. Define a template instance QIntDictIterator<X> to create a dictionary iterator that operates on QIntDict<X> (dictionary of X*).

Example:

    QIntDict<QLineEdit> fields;
    for ( int i = 0; i < 3; i++ )
        fields.insert( i, new QLineEdit( this ) );

    fields[0]->setText( "Homer" );
    fields[1]->setText( "Simpson" );
    fields[2]->setText( "45" );

    QIntDictIterator<char> it( fields );
    for ( ; it.current(); ++it )
        cout << it.currentKey() << ": " << it.current()->text() << endl;

    // Output (random order):
    //  0: Homer
    //  1: Simpson
    //  2: 45

Note that the traversal order is arbitrary; you are not guaranteed the order above.

Multiple iterators may independently traverse the same dictionary. A QIntDict knows about all the iterators that are operating on the dictionary. When an item is removed from the dictionary, QIntDict updates all iterators that refer the removed item to point to the next item in the traversing order.

See also QIntDict, Collection Classes and Non-GUI Classes.

Member Function Documentation

QIntDictIterator::QIntDictIterator ( const QIntDict<type> & dict )

Constructs an iterator for dict. The current iterator item is set to point to the 'first' item in the dict. The first item refers to the first item in the dictionary's arbitrary internal ordering.

QIntDictIterator::~QIntDictIterator ()

Destroys the iterator.

uint QIntDictIterator::count () const

Returns the number of items in the dictionary this iterator operates over.

See also isEmpty().

type * QIntDictIterator::current () const

Returns a pointer to the current iterator item.

long QIntDictIterator::currentKey () const

Returns the key for the current iterator item.

bool QIntDictIterator::isEmpty () const

Returns TRUE if the dictionary is empty; otherwise eturns FALSE.

See also count().

QIntDictIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QIntDictIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QIntDictIterator::operator++ ()

Prefix ++ makes the succeeding item current and returns the new current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QIntDictIterator::operator+= ( uint jump )

Sets the current item to the item jump positions after the current item, and returns a pointer to that item.

If that item is beyond the last item or if the dictionary is empty, it sets the current item to null and returns null.

type * QIntDictIterator::toFirst ()

Sets the current iterator item to point to the first item in the dictionary and returns a pointer to the item. The first item refers to the first item in the dictionary's arbitrary internal ordering. If the dictionary is empty it sets the current item to null and returns null.

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


QIntDictIterator Member List

Complete Member List for QIntDictIterator

This is the complete list of member functions for QIntDictIterator, including inherited members.

  • QIntDictIterator()
  • ~QIntDictIterator()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • toFirst()


QIntValidator类

QIntValidator类参考

QIntValidator类提供了一个确保一个字符串包含一个在一定有效范围内的整数的验证器。 详情请见……

#include <qvalidator.h>

继承了QValidator。

所有成员函数的列表。

公有成员

  • QIntValidator ( QObject * parent, const char * name = 0 )
  • QIntValidator ( int minimum, int maximum, QObject * parent, const char * name = 0 )
  • ~QIntValidator ()
  • virtual QValidator::State validate ( QString & input, int & ) const
  • void setBottom ( int )
  • void setTop ( int )
  • virtual void setRange ( int minimum, int maximum )
  • int bottom () const
  • int top () const

属性

  • int bottom - 验证器可接受的最小值
  • int top - 验证器可接受的最大值

详细描述

QIntValidator类提供了一个确保一个字符串包含一个在一定有效范围内的整数的验证器。

validate()函数返回Acceptable、Intermediate或Invalid。Acceptable是指字符串是一个在指定范围内的有效整数。Intermediate是指字符串是一个有效整数，但不在指定范围内。Invalid是指字符串不是一个有效整数。

使用实例：

    QIntValidator v( 0, 100, this );
    QLineEdit* edit = new QLineEdit( this );

    // 这个行编辑只接受从0到100的整数
    edit->setValidator( &v );

下面我们提供一些验证器的实例。实际上，它们将会像上面的例子一样和窗口部件协同使用。

    QString s;
    QIntValidator v( 0, 100, this );

    s = "10";
    v.validate( s, 0 ); // 返回Acceptable
    s = "35";
    v.validate( s, 0 ); // 返回Acceptable

    s = "105";
    v.validate( s, 0 ); // 返回Intermediate

    s = "-763";
    v.validate( s, 0 ); // 返回Invalid
    s = "abc";
    v.validate( s, 0 ); // 返回Invalid
    s = "12v";
    v.validate( s, 0 ); // 返回Invalid

最大值和最小值可以通过调用setRange()同时设置或者通过分别调用setBottom()和setTop()来设置。

也可以参考QDoubleValidator、QRegExpValidator和杂项类。

成员函数文档

QIntValidator::QIntValidator ( QObject * parent, const char * name = 0 )

构造一个接受所有整数并且父对象为parent，名称为name的验证器。

QIntValidator::QIntValidator ( int minimum, int maximum, QObject * parent, const char * name = 0 )

构造一个接受从minimum到maximum（包含边界）的整数并且父对象为parent，名称为name的验证器。

QIntValidator::~QIntValidator ()

销毁这个验证器，释放所有已经分配的资源。

int QIntValidator::bottom () const

返回验证器可接受的最小值。详细情况请参考“bottom”属性。

void QIntValidator::setBottom ( int )

设置验证器可接受的最小值。详细情况请参考“bottom”属性。

void QIntValidator::setRange ( int minimum, int maximum ) [虚]

设置验证器所接受的数值的范围是从minimum到maximum（包含边界）。

void QIntValidator::setTop ( int )

设置验证器可接受的最大值。详细情况请参考“top”属性。

int QIntValidator::top () const

返回验证器可接受的最大值。详细情况请参考“top”属性。

QValidator::State QIntValidator::validate ( QString & input, int & ) const [虚]

如果input是在有效范围内的整数，返回Acceptable，如果input是在有效范围之外的整数，返回Intermediate并且如果input不是整数，返回Invalid。

    s = "35";
    v.validate( s, 0 ); // 返回Acceptable

    s = "105";
    v.validate( s, 0 ); // 返回Intermediate

    s = "abc";
    v.validate( s, 0 ); // 返回Invalid

从QValidator中重新实现。

属性文档

int bottom

这个属性保存的是验证器可接受的最小值。

通过setBottom()可以设置属性值并且通过bottom()返回属性值。

也可以参考setRange()。

int top

这个属性保存的是验证器可接受的最大值。

通过setTop()可以设置属性值并且通过top()返回属性值。

也可以参考setRange()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QIntValidator成员列表

完整的QIntValidator成员列表

这里是QIntValidator成员函数的完整列表，包括继承的成员。

  • QIntValidator()
  • ~QIntValidator()
  • blockSignals()
  • bottom()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fixup()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setBottom()
  • setName()
  • setProperty()
  • setRange()
  • setTop()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • top()
  • tr()
  • trUtf8()
  • validate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QIODevice类

QIODevice类参考

QIODevice类是输入/输出设备的基类。 详情请见……

#include <qiodevice.h>

被QBuffer、QFile、QSocket和QSocketDevice继承。

所有成员函数的列表。

公有成员

  • typedef off_t Offset
  • QIODevice ()
  • virtual ~QIODevice ()
  • int flags () const
  • int mode () const
  • int state () const
  • bool isDirectAccess () const
  • bool isSequentialAccess () const
  • bool isCombinedAccess () const
  • bool isBuffered () const
  • bool isRaw () const
  • bool isSynchronous () const
  • bool isAsynchronous () const
  • bool isTranslated () const
  • bool isReadable () const
  • bool isWritable () const
  • bool isReadWrite () const
  • bool isInactive () const
  • bool isOpen () const
  • int status () const
  • void resetStatus ()
  • virtual bool open ( int mode ) = 0
  • virtual void close () = 0
  • virtual void flush () = 0
  • virtual Offset size () const = 0
  • virtual Offset at () const
  • virtual bool at ( Offset pos )
  • virtual bool atEnd () const
  • bool reset ()
  • virtual Q_LONG readBlock ( char * data, Q_ULONG maxlen ) = 0
  • virtual Q_LONG writeBlock ( const char * data, Q_ULONG len ) = 0
  • virtual Q_LONG readLine ( char * data, Q_ULONG maxlen )
  • Q_LONG writeBlock ( const QByteArray & data )
  • virtual QByteArray readAll ()
  • virtual int getch () = 0
  • virtual int putch ( int ch ) = 0
  • virtual int ungetch ( int ch ) = 0

详细描述

QIODevice类是输入/输出设备的基类。

一个输入/输出设备代表了一个可从中读取字节和/和向它写字节的一种媒介。QIODevice类是一个所有这样的设备的抽象超类，像QFile、QBuffer和QSocket这些类继承了QIODevice类并且适当地实现了像write()这样地虚函数。

尽管应用程序有时直接使用QIODevice，但通常最好是通过提供了对任何一个QIODevice子类的流操作的QTextStream和QDataStream。QTextStream提供了基于文本的流的功能（比如对于人们是可读的ASCII文件），而QDataStream则可以以完全不依赖平台的方式处理二进制数据。

QIODevice中的公有成员可以粗略地分为两类：操作函数和状态访问函数。最主要的操作函数有：

  • open() 打开一个用来读和/或写的设备，依赖于open()所使用的参数。

  • close() 关闭设备并且整理好。

  • readBlock() 从一个设备中读取一块数据。

  • writeBlock() 向一个设备中写入一块数据。

  • readLine() reads a line (of text, usually) from the device.

  • flush() 确保所有的缓存数据都已经写入到真正的设备中。

这里是其它的一些不太常用的操作函数：

  • getch() 读一个单字符。

  • ungetch() 如果可能的话，忘记上一次对getch()的调用。

  • putch() 写一个单字符。

  • size() 如果有这个设备的话，返回它的大小。

  • at() 如果这个设备存在一个当前读/写指针，就返回这个指针的位置，否则就移动这个指针。

  • atEnd() 如果对于这个设备是有意义的问题的话，就会表示出是否还可以继续读。

  • reset() 如果对于这个设备是可能的话，就移动读/写指针到这个设备的开始位置。

状态访问就是所有的“读取”函数。QIODevice子类调用setState()来更新状态，并且简单的访问函数告诉用户这个设备的状态。这里就是设置和与它们相配合的访问函数：

  • 访问类型。 一些设备是被随机存取的（它可以在任何地方直接读/写），而其它的设备是顺序存取的。QIODevice提供了访问函数（isDirectAccess()、isSequentialAccess()和isCombinedAccess()）来告诉用户一个给定的输入/输出设备所支持的。

  • 缓存。 一些设备是以直接的模式被访问，而其它设备则使用缓存模式。缓存可以提供更高的效率，尤其是一些小的读/写操作。isBuffered()告诉用户给定的设备是否被缓存。（这通常可以通过应用程序调用open()来设置。）

  • 同步性。 同步设备立即工作（比如文件）。当你从一个文件中读时，文件立刻传递它的数据。其它类型的设备，比如一个连接到HTTP服务器的套接字，也许在你命令它读取的几秒后才传递数据。isSynchronous()和isAsynchronous()会告诉用户如何操作这个设备的。

  • 回车/换行翻译。 简单地说，应用程序通常喜欢看到只有一种单一的回车/换行风格，并且QIODevice子类可以提供这个。如果这个对象把回车/换行翻译成仅仅是换行，isTranslated()返回真。（这通常可以通过应用程序调用open()来设置。）

  • 权限。 一些文件不能被写。比如，isReadable()、isWritable()和isReadWrite()告诉应用程序一个给定设备是否可读和可写。（这通常可以通过应用程序调用open()来设置。）

  • 最后，如果设备是打开的话，比如在调用open()之后，isOpen()返回真。

QIODevice提供了大量的纯虚函数，你在继承它的时候需要实现这些函数。这里是一个子类的框架，其中包含了你所需要的全部成员和一些你也许需要的成员：

    class MyDevice : public QIODevice
    {
    public:
        MyDevice();
        ~MyDevice();

        bool open( int mode );
        void close();
        void flush();

        uint size() const;
        int  at() const;        // 非纯虚
        bool at( int );         // 非纯虚
        bool atEnd() const;     // 非纯虚

        int readBlock( char *data, uint maxlen );
        int writeBlock( const char *data, uint len );
        int readLine( char *data, uint maxlen );

        int getch();
        int putch( int );
        int ungetch( int );
    };

这里有三个非纯虚函数，它们对于顺序设备是可以不用实现的。

也可以参考QDataStream、QTextStream和输入/输出和网络。

成员类型文档

QIODevice::Offset

设备中的位移。

成员函数文档

QIODevice::QIODevice ()

构造一个输入/输出设备。

QIODevice::~QIODevice () [虚]

析构一个输入/输出设备。

Offset QIODevice::at () const [虚]

虚函数返回当前输入/输出设备位置。

这是输入/输出设备读/写数据的头的位置。

也可以参考size()。

在QFile和QSocket中被重新实现。

bool QIODevice::at ( Offset pos ) [虚]

这是一个重载成员函数，提供了更多方便。它的行为和上面的函数基本一致。

虚函数设置输入/输出位置到pos。如果位置设置成功，返回真，比如pos是在范围之内，否则返回假。

也可以参考size()。

在QFile和QSocket中被重新实现。

bool QIODevice::atEnd () const [虚]

如果输入/输出设备位置在输入的末尾位置时，虚函数返回真，否则返回假。

在QFile和QSocket中被重新实现。

void QIODevice::close () [纯虚]

关闭输入/输出设备。

这个虚函数在所有的子类中必须被重新实现。

也可以参考open()。

实例：grapher/grapher.cpp。

在QFile和QSocket中被重新实现。

int QIODevice::flags () const

返回当前输入/输出设备标记设置。

标记由模式标记和状态标记组成。

也可以参考mode()和state()。

void QIODevice::flush () [纯虚]

刷新一个打开的输入/输出设备。

这个虚函数在所有的子类中必须被重新实现。

在QFile和QSocket中被重新实现。

int QIODevice::getch () [纯虚]

从输入/输出设备中读取一个单一的字节/字符。

返回所读取的字节/字符，或者是如果到了输入/输出设备的终点，返回-1。

这个虚函数在所有的子类中必须被重新实现。

也可以参考putch()和ungetch()。

在QFile和QSocket中被重新实现。

bool QIODevice::isAsynchronous () const

如果这个输入/输出设备是一个异步设备，返回真，否则返回假，比如，如果这个设备是一个同步设备。

这个模式当前不在使用中。

也可以参考isSynchronous()。

bool QIODevice::isBuffered () const

如果这个输入/输出设备是一个被缓存的设备，返回真，否则返回假，比如，如果这个设备是一个直接的设备。

也可以参考isRaw()。

bool QIODevice::isCombinedAccess () const

如果这个输入/输出设备是一个组合存取（既可以随机存取也可以顺序存取）的设备，返回真，否则返回假。

这个访问方法当前不在使用中。

bool QIODevice::isDirectAccess () const

如果这个输入/输出设备是一个随机存取的设备，返回真，否则返回假，比如，如果这个设备是一个顺序存取的设备。

也可以参考isSequentialAccess()。

bool QIODevice::isInactive () const

如果这个输入/输出设备状态是0，返回真，比如，这个设备没有打开，否则返回假。

也可以参考isOpen()。

bool QIODevice::isOpen () const

如果这个输入/输出设备已经被打开，返回真，否则返回假。

也可以参考isInactive()。

实例：network/networkprotocol/nntp.cpp。

bool QIODevice::isRaw () const

如果这个输入/输出设备是一个直接设备，返回真，否则返回假，比如，如果这个设备是一个被缓存的设备。

也可以参考isBuffered()。

bool QIODevice::isReadWrite () const

如果这个输入/输出设备被使用IO_ReadWrite模式打开，返回真，否则返回假。

也可以参考isReadable()和isWritable()。

bool QIODevice::isReadable () const

如果这个输入/输出设备被使用IO_ReadOnly或IO_ReadWrite 模式打开，返回真，否则返回假。

也可以参考isWritable()和isReadWrite()。

bool QIODevice::isSequentialAccess () const

如果这个输入/输出设备是一个顺序存取的设备，返回真，否则返回假，比如，如果这个设备是一个随机存取的设备。

包括size()和at(int)的操作在顺序存取的设备上都是无效的。

也可以参考isDirectAccess()。

bool QIODevice::isSynchronous () const

如果这个输入/输出设备是一个同步设备，返回真，否则返回假，比如，如果这个设备是一个异步设备。

也可以参考isAsynchronous()。

bool QIODevice::isTranslated () const

如果这个输入/输出设备翻译回车/换行，返回真，否则返回假。

如果QFile是以IO_Translate模式标记打开的，它就是被翻译的。

bool QIODevice::isWritable () const

如果这个输入/输出设备被使用IO_WriteOnly或IO_ReadWrite模式打开，返回真，否则返回假。

也可以参考isReadable()和isReadWrite()。

int QIODevice::mode () const

返回指定的当前操作模式的位或运算的结果。

这里是提供给open()函数的标记。

这些标记是IO_ReadOnly、IO_WriteOnly、IO_ReadWrite、IO_Append、IO_Truncate和IO_Translate。

bool QIODevice::open ( int mode ) [纯虚]

使用指定的mode打开输入/输出设备。如果这个设备被成功打开，返回真，否则返回假。

模式参数mode必须是下列标记的或的组合。

  • IO_Raw 指定直接的（非缓存的）文件访问。
  • IO_ReadOnly 以只读模式打开文件。
  • IO_WriteOnly 以只写模式打开文件。
  • IO_ReadWrite 以读/写模式打开文件。
  • IO_Append 设置文件索引到文件的末尾。
  • IO_Truncate 截短文件。
  • IO_Translate 在MS-DOS、Windows和Macintosh下对文本文件翻译回车和换行。在Unix系统上这个标记无效。使用时请注意，它会把文件中的每一个换行符转换为一组回车换行。如果你写二进制数据的时候，可能会破坏你要写的文件。请不要和IO_Raw组合使用。

这个虚函数在所有的子类中必须被重新实现。

也可以参考close()。

实例：grapher/grapher.cpp。

在QFile和QSocket中被重新实现。

int QIODevice::putch ( int ch ) [纯虚]

向输入/输出设备写入字符ch。

返回ch，或者如果发生错误，返回-1。

这个虚函数在所有的子类中必须被重新实现。

也可以参考getch()和ungetch()。

实例：grapher/grapher.cpp。

在QFile和QSocket中被重新实现。

QByteArray QIODevice::readAll () [虚]

这个方便的函数返回这个设备中的所有剩余数据。

Q_LONG QIODevice::readBlock ( char * data, Q_ULONG maxlen ) [纯虚]

从这个输入/输出设备中读取最多maxlen字节到data并且返回实际读取的字节数量。

如果发生致命错误，这个函数应该返回-1。

这个虚函数在所有的子类中必须被重新实现。

也可以参考writeBlock()。

在QFile、QSocket和QSocketDevice中被重新实现。

Q_LONG QIODevice::readLine ( char * data, Q_ULONG maxlen ) [虚]

读取文本的一行，（或者如果还没有遇到新的一行的情况下，读取maxlen字节）加上一个结束符\0到data。如果这一行后面还有新的一行，就不再做上述的操作了。

返回包括终结符\0的所读字节数，或者如果发生错误返回-1。

这个虚函数在绝大多数子类中被重新实现的话能够提供更高的效率。

也可以参考readBlock()和QTextStream::readLine()。

在QFile中被重新实现。

bool QIODevice::reset ()

设置这个设备索引位置为0。

也可以参考at()。

void QIODevice::resetStatus ()

设置这个输入/输出设备状态为IO_Ok。

也可以参考status()。

Offset QIODevice::size () const [纯虚]

虚函数返回输入/输出设备的大小。

也可以参考at()。

在QFile和QSocket中被重新实现。

int QIODevice::state () const

返回指定当前状态的位或运算结果。

这个标记是：IO_Open。

子类也可以定义另外的标记。

int QIODevice::status () const

返回这个输入/输出设备的状态。

这个输入/输出设备状态返回一个错误码。如果open()返回失败或者readBlock()或writeBlock()返回-1，这个函数就可以被调用来发现操作为什么不成功的原因。

状态码是：

  • IO_Ok - 操作成功。
  • IO_ReadError - 不能从设备中读取。
  • IO_WriteError - 不能向设备写入。
  • IO_FatalError - 发生了致命的不可恢复的错误。
  • IO_OpenError - 不能打开设备。
  • IO_ConnectError - 不能连接设备。
  • IO_AbortError - 操作出乎意料地失败了。
  • IO_TimeOutError - 操作超时。
  • IO_UnspecifiedError - 关闭时发生了未指定的错误。

也可以参考resetStatus()。

int QIODevice::ungetch ( int ch ) [纯虚]

把字符ch放回到这个输入/输车设备中并且如果索引位置不是零的话，减一。

这个函数正常地被调用就是“撤销”getch()操作。

返回ch，或者如果发生错误，返回-1。

这个虚函数在所有的子类中必须被重新实现。

也可以参考getch()和putch()。

在QFile和QSocket中被重新实现。

Q_LONG QIODevice::writeBlock ( const char * data, Q_ULONG len ) [纯虚]

从data中写len字节到这个输入/输出设备并且返回实际写的字节数。

如果发生致命错误，这个函数应该返回-1。

这个虚函数在所有的子类中必须被重新实现。

也可以参考readBlock()。

在QBuffer、QSocket和QSocketDevice中被重新实现。

Q_LONG QIODevice::writeBlock ( const QByteArray & data )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

这个方便的函数与调用writeBlock( data.data(), data.size() )是一样的。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qiodevice.h包含文件

qiodevice.h

这里是qiodevice.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qiodevice.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QIODevice class
**
** Created : 940913
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QIODEVICE_H
#define QIODEVICE_H

#ifndef QT_H
#ifdef QT_LARGE_FILE_SUPPORT
// ### Should be included first. This is a problem in the current
// ### "qplatformdefs.h" strategy which is OK for source files but
// ### not for header files. Do we need defines back in qmake.conf?
#define _FILE_OFFSET_BITS 64
#include "qplatformdefs.h"
#endif
#include "qglobal.h"
#include "qcstring.h"
#endif // QT_H

// IO device access types

#define IO_Direct		0x0100		// direct access device
#define IO_Sequential		0x0200		// sequential access device
#define IO_Combined		0x0300		// combined direct/sequential
#define IO_TypeMask		0x0f00

// IO handling modes

#define IO_Raw			0x0040		// raw access (not buffered)
#define IO_Async		0x0080		// asynchronous mode

// IO device open modes

#define IO_ReadOnly		0x0001		// readable device
#define IO_WriteOnly		0x0002		// writable device
#define IO_ReadWrite		0x0003		// read+write device
#define IO_Append		0x0004		// append
#define IO_Truncate		0x0008		// truncate device
#define IO_Translate		0x0010		// translate CR+LF
#define IO_ModeMask		0x00ff

// IO device state

#define IO_Open			0x1000		// device is open
#define IO_StateMask		0xf000

// IO device status

#define IO_Ok			0
#define IO_ReadError		1		// read error
#define IO_WriteError		2		// write error
#define IO_FatalError		3		// fatal unrecoverable error
#define IO_ResourceError	4		// resource limitation
#define IO_OpenError		5		// cannot open device
#define IO_ConnectError		5		// cannot connect to device
#define IO_AbortError		6		// abort error
#define IO_TimeOutError		7		// time out
#define IO_UnspecifiedError	8		// unspecified error

class Q_EXPORT QIODevice			// IO device class
{
public:
#ifdef QT_LARGE_FILE_SUPPORT
    typedef off_t Offset;
#else
    typedef Q_ULONG Offset;
#endif

    QIODevice();
    virtual ~QIODevice();

    int		 flags()  const { return ioMode; }
    int		 mode()	  const { return ioMode & IO_ModeMask; }
    int		 state()  const { return ioMode & IO_StateMask; }

    bool	 isDirectAccess()     const { return ((ioMode & IO_Direct)     == IO_Direct); }
    bool	 isSequentialAccess() const { return ((ioMode & IO_Sequential) == IO_Sequential); }
    bool	 isCombinedAccess()   const { return ((ioMode & IO_Combined)   == IO_Combined); }
    bool	 isBuffered()	      const { return ((ioMode & IO_Raw)        != IO_Raw); }
    bool	 isRaw()	      const { return ((ioMode & IO_Raw)        == IO_Raw); }
    bool	 isSynchronous()      const { return ((ioMode & IO_Async)      != IO_Async); }
    bool	 isAsynchronous()     const { return ((ioMode & IO_Async)      == IO_Async); }
    bool	 isTranslated()	      const { return ((ioMode & IO_Translate)  == IO_Translate); }
    bool	 isReadable()	      const { return ((ioMode & IO_ReadOnly)   == IO_ReadOnly); }
    bool	 isWritable()	      const { return ((ioMode & IO_WriteOnly)  == IO_WriteOnly); }
    bool	 isReadWrite()	      const { return ((ioMode & IO_ReadWrite)  == IO_ReadWrite); }
    bool	 isInactive()	      const { return state() == 0; }
    bool	 isOpen()	      const { return state() == IO_Open; }

    int		 status() const { return ioSt; }
    void	 resetStatus()	{ ioSt = IO_Ok; }

    virtual bool open( int mode ) = 0;
    virtual void close() = 0;
    virtual void flush() = 0;

    virtual Offset size()  const = 0;
    virtual Offset at()  const;
    virtual bool at( Offset );
    virtual bool atEnd()  const;
    bool	 reset() { return at(0); }

    virtual Q_LONG readBlock( char *data, Q_ULONG maxlen ) = 0;
    virtual Q_LONG writeBlock( const char *data, Q_ULONG len ) = 0;
    virtual Q_LONG readLine( char *data, Q_ULONG maxlen );
    Q_LONG writeBlock( const QByteArray& data );
    virtual QByteArray readAll();

    virtual int	 getch() = 0;
    virtual int	 putch( int ) = 0;
    virtual int	 ungetch( int ) = 0;

protected:
    void	 setFlags( int f ) { ioMode = f; }
    void	 setType( int );
    void	 setMode( int );
    void	 setState( int );
    void	 setStatus( int );
    Offset	 ioIndex;

private:
    int		 ioMode;
    int		 ioSt;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QIODevice( const QIODevice & );
    QIODevice &operator=( const QIODevice & );
#endif
};

#endif // QIODEVICE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QIODevice成员列表

完整的QIODevice成员列表

这里是QIODevice成员函数的完整列表，包括继承的成员。

  • QIODevice()
  • ~QIODevice()
  • at()
  • atEnd()
  • close()
  • flags()
  • flush()
  • getch()
  • isAsynchronous()
  • isBuffered()
  • isCombinedAccess()
  • isDirectAccess()
  • isInactive()
  • isOpen()
  • isRaw()
  • isReadWrite()
  • isReadable()
  • isSequentialAccess()
  • isSynchronous()
  • isTranslated()
  • isWritable()
  • mode()
  • open()
  • putch()
  • readAll()
  • readBlock()
  • readLine()
  • reset()
  • resetStatus()
  • size()
  • state()
  • status()
  • ungetch()
  • writeBlock()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QIODeviceSource Class

QIODeviceSource Class Reference
[obsolete]

The QIODeviceSource class is a QDataSource that draws data from a QIODevice. More...

#include <qasyncio.h>

Inherits QDataSource.

List of all member functions.

Public Members

  • QIODeviceSource ( QIODevice * device, int buffer_size = 4096 )
  • ~QIODeviceSource ()
  • virtual int readyToSend ()
  • virtual void sendTo ( QDataSink * sink, int n )
  • virtual bool rewindable () const
  • virtual void enableRewind ( bool on )
  • virtual void rewind ()

Detailed Description

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

The QIODeviceSource class is a QDataSource that draws data from a QIODevice.

This class encapsulates retrieving data from a QIODevice (such as a QFile).

Member Function Documentation

QIODeviceSource::QIODeviceSource ( QIODevice * device, int buffer_size = 4096 )

Constructs a QIODeviceSource from the QIODevice device. The QIODevice must be dynamically allocated, becomes owned by the QIODeviceSource, and will be deleted when the QIODeviceSource is destroyed. buffer_size determines the size of buffering to use between asynchronous operations. The higher the buffer_size, the more efficient, but the less interleaved the operation will be with other processing.

QIODeviceSource::~QIODeviceSource ()

Destroys the QIODeviceSource, deleting the QIODevice from which it was constructed.

void QIODeviceSource::enableRewind ( bool on ) [virtual]

If on is set to TRUE then rewinding is enabled. No special action is taken. If on is set to FALSE then rewinding is disabled.

Reimplemented from QDataSource.

int QIODeviceSource::readyToSend () [virtual]

Ready until end-of-file.

Reimplemented from QDataSource.

void QIODeviceSource::rewind () [virtual]

Calls reset() on the QIODevice.

Reimplemented from QDataSource.

bool QIODeviceSource::rewindable () const [virtual]

All QIODeviceSource's are rewindable.

Reimplemented from QDataSource.

void QIODeviceSource::sendTo ( QDataSink * sink, int n ) [virtual]

Reads a block of data and sends up to n bytes to the sink.

Reimplemented from QDataSource.

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


QIODeviceSource Member List

Complete Member List for QIODeviceSource

This is the complete list of member functions for QIODeviceSource, including inherited members.

  • QIODeviceSource()
  • ~QIODeviceSource()
  • connect()
  • enableRewind()
  • maybeReady()
  • ready()
  • readyToSend()
  • rewind()
  • rewindable()
  • sendTo()


QJisCodec Class

QJisCodec Class Reference

The QJisCodec class provides conversion to and from JIS character sets. More...

#include <qjiscodec.h>

Inherits QTextCodec.

List of all member functions.

Public Members

  • virtual const char * mimeName () const

Detailed Description

The QJisCodec class provides conversion to and from JIS character sets.

More precisely, the QJisCodec class subclasses QTextCodec to provide support for JIS X 0201 Latin, JIS X 0201 Kana, JIS X 0208 and JIS X 0212.

The environment variable UNICODEMAP_JP can be used to fine-tune QJisCodec, QSjisCodec and QEucJpCodec. The mapping names are as for the Japanese XML working group's XML Japanese Profile, because it names and explains all the widely used mappings. Here are brief descriptions, written by Serika Kurusugawa:

  • "unicode-0.9" or "unicode-0201" for Unicode style. This assumes JISX0201 for 0x00-0x7f. (0.9 is a table version of jisx02xx mapping used for Uniocde spec version 1.1.)

  • "unicode-ascii" This assumes US-ASCII for 0x00-0x7f; some chars (JISX0208 0x2140 and JISX0212 0x2237) are different from Unicode 1.1 to avoid conflict.

  • "open-19970715-0201" ("open-0201" for convenience) or "jisx0221-1995" for JISX0221-JISX0201 style. JIS X 0221 is JIS version of Unicode, but a few chars (0x5c, 0x7e, 0x2140, 0x216f, 0x2131) are different from Unicode 1.1. This is used when 0x5c is treated as YEN SIGN.

  • "open-19970715-ascii" ("open-ascii" for convenience) for JISX0221-ASCII style. This is used when 0x5c is treated as REVERSE SOLIDUS.

  • "open-19970715-ms" ("open-ms" for convenience) or "cp932" for Microsoft Windows style. Windows Code Page 932. Some chars (0x2140, 0x2141, 0x2142, 0x215d, 0x2171, 0x2172) are different from Unicode 1.1.

  • "jdk1.1.7" for Sun's JDK style. Same as Unicode 1.1, except that JIS 0x2140 is mapped to UFF3C. Either ASCII or JISX0201 can be used for 0x00-0x7f.

In addition, the extensions "nec-vdc", "ibm-vdc" and "udc" are supported.

For example, if you want to use Unicode style conversion but with NEC's extension, set UNICODEMAP_JP to unicode-0.9, nec-vdc. (You will probably need to quote that in a shell command.)

Most of the code here was written by Serika Kurusugawa, a.k.a. Junji Takagi, and is included in Qt with the author's permission and the grateful thanks of the Trolltech team. Here is the copyright statement for that code:

Copyright (c) 1999 Serika Kurusugawa. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS". ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

Member Function Documentation

const char * QJisCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


qjiscodec.h Include File

qjiscodec.h

This is the verbatim text of the qjiscodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qjiscodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QJisCodec class
**
** Created : 990225
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

// Most of the code here was originally written by Serika Kurusugawa
// a.k.a. Junji Takagi, and is include in Qt with the author's permission,
// and the grateful thanks of the Trolltech team.

/*
 * Copyright (c) 1999 Serika Kurusugawa, All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef QJISCODEC_H
#define QJISCODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#include "qjpunicode.h"
#endif // QT_H

#ifndef QT_NO_BIG_CODECS

#if defined(QT_PLUGIN)
#define Q_EXPORT_CODECS_JP
#else
#define Q_EXPORT_CODECS_JP Q_EXPORT
#endif

class Q_EXPORT_CODECS_JP QJisCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;

    QJisCodec();
    ~QJisCodec();

protected:
    const QJpUnicodeConv *conv;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QJisCodec Member List

Complete Member List for QJisCodec

This is the complete list of member functions for QJisCodec, including inherited members.

  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


qkeyboard_qws.h Include File

qkeyboard_qws.h

This is the verbatim text of the qkeyboard_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of Qt/Embedded keyboards
**
** Created : 991025
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QKEYBOARD_QWS_H
#define QKEYBOARD_QWS_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_QWS_KEYBOARD
class QWSKeyboardHandler : public QObject {
    Q_OBJECT
public:
    QWSKeyboardHandler();
    virtual ~QWSKeyboardHandler();

protected:
    virtual void processKeyEvent(int unicode, int keycode, int modifiers,
                bool isPress, bool autoRepeat);
};
#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QKeyEvent Class

QKeyEvent Class Reference

The QKeyEvent class contains describes a key event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QKeyEvent ( Type type, int key, int ascii, int state, const QString & text = QString::null, bool autorep = FALSE, ushort count = 1 )
  • int key () const
  • int ascii () const
  • ButtonState state () const
  • ButtonState stateAfter () const
  • bool isAccepted () const
  • QString text () const
  • bool isAutoRepeat () const
  • int count () const
  • void accept ()
  • void ignore ()

Detailed Description

The QKeyEvent class contains describes a key event.

Key events occur when a key is pressed or released when a widget has keyboard input focus.

A key event contains a special accept flag that indicates whether the receiver wants the key event. You should call QKeyEvent::ignore() if the key press or release event is not handled by your widget. A key event is propagated up the parent widget chain until a widget accepts it with QKeyEvent::accept() or an event filter consumes it.

The QWidget::setEnable() function can be used to enable or disable mouse and keyboard events for a widget.

The event handlers QWidget::keyPressEvent() and QWidget::keyReleaseEvent() receive key events.

See also QFocusEvent, QWidget::grabKeyboard() and Event Classes.

Member Function Documentation

QKeyEvent::QKeyEvent ( Type type, int key, int ascii, int state, const QString & text = QString::null, bool autorep = FALSE, ushort count = 1 )

Constructs a key event object.

The type parameter must be QEvent::KeyPress or QEvent::KeyRelease. If key is 0 the event is not a result of a known key (e.g. it may be the result of a compose sequence or keyboard macro). ascii is the ASCII code of the key that was pressed or released. state holds the keyboard modifiers. text is the Unicode text that the key generated. If autorep is TRUE, isAutoRepeat() will be TRUE. count is the number of single keys.

The accept flag is set to TRUE.

void QKeyEvent::accept ()

Sets the accept flag of the key event object.

Setting the accept parameter indicates that the receiver of the event wants the key event. Unwanted key events are sent to the parent widget.

The accept flag is set by default.

See also ignore().

int QKeyEvent::ascii () const

Returns the ASCII code of the key that was pressed or released. We recommend using text() instead.

See also text().

Example: picture/picture.cpp.

int QKeyEvent::count () const

Returns the number of single keys for this event. If text() is not empty, this is simply the length of the string.

However, Qt also compresses invisible keycodes such as BackSpace. For those, count() returns the number of key presses/repeats this event represents.

See also QWidget::setKeyCompression().

void QKeyEvent::ignore ()

Clears the accept flag parameter of the key event object.

Clearing the accept parameter indicates that the event receiver does not want the key event. Unwanted key events are sent to the parent widget.

The accept flag is set by default.

See also accept().

bool QKeyEvent::isAccepted () const

Returns TRUE if the receiver of the event wants to keep the key; otherwise returns FALSE

bool QKeyEvent::isAutoRepeat () const

Returns TRUE if this event comes from an auto-repeating key and FALSE if it comes from an initial key press.

Note that if the event is a multiple-key compressed event that is partly due to auto-repeat, this function could return either TRUE or FALSE indeterminately.

int QKeyEvent::key () const

Returns the code of the key that was pressed or released.

See Qt::Key for the list of keyboard codes. These codes are independent of the underlying window system.

Key code 0 means that the event is not a result of a known key (e.g. it may be the result of a compose sequence or keyboard macro).

When key event compression is turned on, this function's return value is undefined. See QWidget::setKeyCompression() for details on key event compression.

Example: fileiconview/qfileiconview.cpp.

ButtonState QKeyEvent::state () const

Returns the keyboard modifier flags that existed immediately before the event occurred.

The returned value is ShiftButton, ControlButton and AltButton OR'ed together.

See also stateAfter().

Example: fileiconview/qfileiconview.cpp.

ButtonState QKeyEvent::stateAfter () const

Returns the keyboard modifier flags that existed immediately after the event occurred.

Warning: This function cannot be trusted.

See also state().

QString QKeyEvent::text () const

Returns the Unicode text that this key generated.

See also QWidget::setKeyCompression().

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


QKeyEvent Member List

Complete Member List for QKeyEvent

This is the complete list of member functions for QKeyEvent, including inherited members.

  • QKeyEvent()
  • accept()
  • ascii()
  • count()
  • ignore()
  • isAccepted()
  • isAutoRepeat()
  • key()
  • spontaneous()
  • state()
  • stateAfter()
  • text()
  • type()


QKeySequence Class

QKeySequence Class Reference

The QKeySequence class encapsulates a key sequence as used by accelerators. More...

#include <qkeysequence.h>

Inherits Qt.

List of all member functions.

Public Members

  • QKeySequence ()
  • QKeySequence ( const QString & key )
  • QKeySequence ( int key )
  • operator QString () const
  • operator int () const
  • QKeySequence ( const QKeySequence & keysequence )
  • QKeySequence & operator= ( const QKeySequence & keysequence )
  • ~QKeySequence ()
  • bool operator== ( const QKeySequence & keysequence ) const
  • bool operator!= ( const QKeySequence & keysequence ) const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QKeySequence & keysequence )
  • QDataStream & operator>> ( QDataStream & s, QKeySequence & keysequence )

Detailed Description

The QKeySequence class encapsulates a key sequence as used by accelerators.

A key sequence consists of a keyboard code, optionally combined with modifiers, e.g. SHIFT, CTRL, ALT or UNICODE_ACCEL. For example, CTRL + Key_P might be a sequence used as a shortcut for printing a document. The key codes are listed in qnamespace.h. As an alternative, use UNICODE_ACCEL with the unicode code point of the character. For example, UNICODE_ACCEL + 'A' gives the same key sequence as Key_A.

Key sequences can be constructed either from an integer key code, or from a human readable translatable string. A key sequence can be cast to a QString to obtain a human readable translated version of the sequence. Translations are done in the "QAccel" context.

See also QAccel and Miscellaneous Classes.

Member Function Documentation

QKeySequence::QKeySequence ()

Constructs an empty key sequence.

QKeySequence::QKeySequence ( const QString & key )

Creates a key sequence from the string key. For example "Ctrl+O" gives CTRL+UNICODE_ACCEL+'O'. The strings "Ctrl", "Shift" and "Alt" are recognized, as well as their translated equivalents in the "QAccel" context (using QObject::tr()).

This contructor is typically used with tr(), so that accelerator keys can be replaced in translations:

        QPopupMenu *file = new QPopupMenu( this );
        file->insertItem( tr("&Open..."), this, SLOT(open()),
                          QKeySequence( tr("Ctrl+O", "File|Open") ) );

Note the "File|Open" translator comment. It is by no means necessary, but it provides some context for the human translator.

QKeySequence::QKeySequence ( int key )

Constructs a key sequence from the keycode key.

The key codes are listed in qnamespace.h and can be combined with modifiers, e.g. with SHIFT, CTRL, ALT or UNICODE_ACCEL.

QKeySequence::QKeySequence ( const QKeySequence & keysequence )

Copy constructor. Makes a copy of keysequence.

QKeySequence::~QKeySequence ()

Destroys the key sequence.

QKeySequence::operator QString () const

Creates an accelerator string for the key sequence. For example, CTRL+Key_O gives "Ctrl+O". The strings, "Ctrl", "Shift", etc. are translated (using QObject::tr()) in the "QAccel" context.

QKeySequence::operator int () const

For backward compatibility: returns the keycode as an integer.

If QKeySequence ever supports more than one keycode, this function will return the first one.

bool QKeySequence::operator!= ( const QKeySequence & keysequence ) const

Returns TRUE if keysequence is not equal to this key sequence; otherwise returns FALSE.

QKeySequence & QKeySequence::operator= ( const QKeySequence & keysequence )

Assignment operator. Assigns keysequence to this object.

bool QKeySequence::operator== ( const QKeySequence & keysequence ) const

Returns TRUE if keysequence is equal to this key sequence; otherwise returns FALSE.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QKeySequence & keysequence )

Writes the key sequence keysequence to the stream s.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QKeySequence & keysequence )

Reads a key sequence from the stream s into the key sequence keysequence.

See also Format of the QDataStream operators.

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


qkeysequence.h Include File

qkeysequence.h

This is the verbatim text of the qkeysequence.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qkeysequence.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QKeySequence class
**
** Created : 0108007
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QKEYSEQUENCE_H
#define QKEYSEQUENCE_H

#ifndef QT_H
#ifndef QT_H
#include "qnamespace.h"
#include "qstring.h"
#endif // QT_H
#endif

#ifndef QT_NO_ACCEL

class QKeySequencePrivate;

class Q_EXPORT QKeySequence : public Qt
{
public:
    QKeySequence();
    QKeySequence( const QString& key );
    QKeySequence( int key );

    operator QString() const;
    operator int () const;

    QKeySequence( const QKeySequence& );
    QKeySequence &operator=( const QKeySequence & );
    ~QKeySequence();
    bool operator==( const QKeySequence& ) const;
    bool operator!= ( const QKeySequence& ) const;

private:
    QKeySequencePrivate* d;

};

/*****************************************************************************
  QKeySequence stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QKeySequence & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QKeySequence & );
#endif

#else
class Q_EXPORT QKeySequence : public Qt
{
public:
    QKeySequence() {}
    QKeySequence( int ) {}
};

#endif //QT_NO_ACCEL

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QKeySequence Member List

Complete Member List for QKeySequence

This is the complete list of member functions for QKeySequence, including inherited members.

  • QKeySequence()
  • ~QKeySequence()
  • operator QString()
  • operator int()
  • operator!=()
  • operator=()
  • operator==()


QLabel Class

QLabel Class Reference

The QLabel widget provides a text or image display. More...

#include <qlabel.h>

Inherits QFrame.

List of all member functions.

Public Members

  • QLabel ( QWidget * parent, const char * name = 0, WFlags f = 0 )
  • QLabel ( const QString & text, QWidget * parent, const char * name = 0, WFlags f = 0 )
  • QLabel ( QWidget * buddy, const QString & text, QWidget * parent, const char * name = 0, WFlags f = 0 )
  • ~QLabel ()
  • QString text () const
  • QPixmap * pixmap () const
  • QPicture * picture () const
  • QMovie * movie () const
  • TextFormat textFormat () const
  • void setTextFormat ( TextFormat )
  • int alignment () const
  • virtual void setAlignment ( int )
  • int indent () const
  • void setIndent ( int )
  • bool autoResize () const (obsolete)
  • virtual void setAutoResize ( bool enable ) (obsolete)
  • bool hasScaledContents () const
  • void setScaledContents ( bool )
  • virtual void setBuddy ( QWidget * buddy )
  • QWidget * buddy () const
  • virtual void setFont ( const QFont & f )

Public Slots

  • virtual void setText ( const QString & )
  • virtual void setPixmap ( const QPixmap & )
  • virtual void setPicture ( const QPicture & picture )
  • virtual void setMovie ( const QMovie & movie )
  • virtual void setNum ( int num )
  • virtual void setNum ( double num )
  • void clear ()

Properties

  • Alignment alignment - the alignment of the label's contents
  • int indent - the label's text indent in pixels
  • QPixmap pixmap - the label's pixmap
  • bool scaledContents - whether the label will scale its contents to fill all available space
  • QString text - the label text
  • TextFormat textFormat - the label's text format

Protected Members

  • virtual void drawContents ( QPainter * p )

Detailed Description

The QLabel widget provides a text or image display.

QLabel is used for displaying information in the form of text or an image. No user interaction functionality is provided. The visual appearance of the label can be configured in various ways, and it can be used for specifying a focus accelerator key for another widget.

A QLabel can contain any of the following content types:

  • Plain text: set by passing a QString to setText().
  • Rich text: set by passing a QString that contains rich text to setText().
  • A pixmap: set by passing a QPixmap to setPixmap().
  • A movie: set by passing a QMovie to setMovie().
  • A number: set by passing an int or a double to setNum(), which converts the number to plain text.
  • Nothing: the same as an empty plain text. This is the default. Set by clear().

When the content is changed using any of these functions, any previous content is cleared.

The look of a QLabel can be tuned in several ways. All the settings of QFrame are available for specifying a widget frame. The positioning of the content within the QLabel widget area can be tuned with setAlignment() and setIndent(). For example, this code sets up a sunken panel with a two-line text in the bottom right corner (both lines being flush with the right side of the label):

    QLabel *label = new QLabel;
    label->setFrameStyle( QFrame::Panel | QFrame::Sunken );
    label->setText( "first line\nsecond line" );
    label->setAlignment( AlignBottom | AlignRight );

A QLabel is often used as a label for an interactive widget. For this use QLabel provides a useful mechanism for adding an accelerator key (see QAccel) that will set the keyboard focus to the other widget (called the QLabel's "buddy"). Example:

     QLineEdit* phoneEdit = new QLineEdit( this, "phoneEdit" );
     QLabel* phoneLabel = new QLabel( phoneEdit, "&Phone:", this, "phoneLabel" );

In this example, keyboard focus is transferred to the label's buddy (the QLineEdit) when the user presses Alt-P. You can also use the setBuddy() function to accomplish the same thing.

See also QLineEdit, QTextView, QPixmap, QMovie, GUI Design Handbook: Label, Basic Widgets and Text Related Classes.

Member Function Documentation

QLabel::QLabel ( QWidget * parent, const char * name = 0, WFlags f = 0 )

Constructs an empty label.

The parent, name and widget flag f, arguments are passed to the QFrame constructor.

See also alignment, setFrameStyle() and indent.

QLabel::QLabel ( const QString & text, QWidget * parent, const char * name = 0, WFlags f = 0 )

Constructs a label that displays the text, text.

The parent, name and widget flag f, arguments are passed to the QFrame constructor.

See also text, alignment, setFrameStyle() and indent.

QLabel::QLabel ( QWidget * buddy, const QString & text, QWidget * parent, const char * name = 0, WFlags f = 0 )

Constructs a label that displays the text text. The label has a buddy widget, buddy.

If the text contains an underlined letter (a letter preceded by an ampersand, &), and the text is in plain text format, when the user presses Alt+ the underlined letter, focus is passed to the buddy widget.

The parent, name and widget flag, f, arguments are passed to the QFrame constructor.

See also text, setBuddy(), alignment, setFrameStyle() and indent.

QLabel::~QLabel ()

Destroys the label.

int QLabel::alignment () const

Returns the alignment of the label's contents. See the "alignment" property for details.

bool QLabel::autoResize () const

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

Returns TRUE if auto-resizing is enabled, or FALSE if auto-resizing is disabled.

Auto-resizing is disabled by default.

See also setAutoResize().

QWidget * QLabel::buddy () const

Returns the buddy of this label, or 0 if no buddy is currently set.

See also setBuddy().

void QLabel::clear () [slot]

Clears any label contents. Equivalent to setText( "" ).

void QLabel::drawContents ( QPainter * p ) [virtual protected]

Draws the label contents using the painter p.

Reimplemented from QFrame.

bool QLabel::hasScaledContents () const

Returns TRUE if the label will scale its contents to fill all available space; otherwise returns FALSE. See the "scaledContents" property for details.

int QLabel::indent () const

Returns the label's text indent in pixels. See the "indent" property for details.

QMovie * QLabel::movie () const

If the label contains a movie, returns a pointer to it. Otherwise, returns 0.

See also setMovie().

QPicture * QLabel::picture () const

Returns the label's picture or 0 if the label doesn't have a picture.

QPixmap * QLabel::pixmap () const

Returns the label's pixmap. See the "pixmap" property for details.

void QLabel::setAlignment ( int ) [virtual]

Sets the alignment of the label's contents. See the "alignment" property for details.

void QLabel::setAutoResize ( bool enable ) [virtual]

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

Enables auto-resizing if enable is TRUE, or disables it if enable is FALSE.

When auto-resizing is enabled the label will resize itself to fit the contents whenever the contents change. The top-left corner is not moved. This is useful for QLabel widgets that are not managed by a QLayout (e.g., top-level widgets).

Auto-resizing is disabled by default.

See also autoResize(), adjustSize() and sizeHint.

void QLabel::setBuddy ( QWidget * buddy ) [virtual]

Sets the buddy of this label to buddy.

When the user presses the accelerator key indicated by this label, the keyboard focus is transferred to the label's buddy widget.

The buddy mechanism is available only for QLabels that contain plain text in which one letter is prefixed with an ampersand, &. This letter is set as the accelerator key. The letter is displayed underlined, and the '&' is not displayed (i.e. the ShowPrefix alignment flag is turned on; see setAlignment()).

In a dialog, you might create two data entry widgets and a label for each, and set up the geometry layout so each label is just to the left of its data entry widget (its "buddy"), perhaps like this:

    QLineEdit *nameEd  = new QLineEdit( this );
    QLabel    *nameLb  = new QLabel( "&Name:", this );
    nameLb->setBuddy( nameEd );
    QLineEdit *phoneEd = new QLineEdit( this );
    QLabel    *phoneLb = new QLabel( "&Phone:", this );
    phoneLb->setBuddy( phoneEd );
    // ( layout setup not shown )

With the code above, the focus jumps to the Name field when the user presses Alt-N, and to the Phone field when the user presses Alt-P.

To unset a previously set buddy, call this function with buddy set to 0.

See also buddy(), text, QAccel and alignment.

Examples: addressbook/centralwidget.cpp and chart/optionsform.cpp.

void QLabel::setFont ( const QFont & f ) [virtual]

Sets the font used on the QLabel to font f.

Reimplemented from QWidget.

void QLabel::setIndent ( int )

Sets the label's text indent in pixels. See the "indent" property for details.

void QLabel::setMovie ( const QMovie & movie ) [virtual slot]

Sets the label contents to movie. Any previous content is cleared.

The buddy accelerator, if any, is disabled.

The label resizes itself if auto-resizing is enabled.

See also movie() and setBuddy().

void QLabel::setNum ( int num ) [virtual slot]

Sets the label contents to plain text containing the printed representation of integer num. Any previous content is cleared. Does nothing if the integer's string representation is the same as the current contents of the label.

The buddy accelerator, if any, is disabled.

The label resizes itself if auto-resizing is enabled.

See also text, QString::setNum() and setBuddy().

void QLabel::setNum ( double num ) [virtual slot]

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

Sets the label contents to plain text containing the printed representation of double num. Any previous content is cleared. Does nothing if the double's string representation is the same as the current contents of the label.

The buddy accelerator, if any, is disabled.

The label resizes itself if auto-resizing is enabled.

See also text, QString::setNum() and setBuddy().

void QLabel::setPicture ( const QPicture & picture ) [virtual slot]

Sets the label contents to picture. Any previous content is cleared.

The buddy accelerator, if any, is disabled.

See also picture() and setBuddy().

void QLabel::setPixmap ( const QPixmap & ) [virtual slot]

Sets the label's pixmap. See the "pixmap" property for details.

void QLabel::setScaledContents ( bool )

Sets whether the label will scale its contents to fill all available space. See the "scaledContents" property for details.

void QLabel::setText ( const QString & ) [virtual slot]

Sets the label text. See the "text" property for details.

void QLabel::setTextFormat ( TextFormat )

Sets the label's text format. See the "textFormat" property for details.

QString QLabel::text () const

Returns the label text. See the "text" property for details.

TextFormat QLabel::textFormat () const

Returns the label's text format. See the "textFormat" property for details.

Property Documentation

Alignment alignment

This property holds the alignment of the label's contents.

The alignment is a bitwise OR of Qt::AlignmentFlags and Qt::TextFlags values. The ExpandTabs, SingleLine and ShowPrefix flags apply only if the label contains plain text; otherwise they are ignored. The DontClip flag is always ignored. WordBreak applies to both rich text and plain text labels.

If the label has a buddy, the ShowPrefix flag is forced to TRUE.

The default alignment is AlignAuto | AlignVCenter | ExpandTabs if the label doesn't have a buddy and AlignAuto | AlignVCenter | ExpandTabs | ShowPrefix if the label has a buddy. If the label contains rich text, additionally WordBreak is turned on.

See also Qt::AlignmentFlags, setBuddy() and text.

Set this property's value with setAlignment() and get this property's value with alignment().

int indent

This property holds the label's text indent in pixels.

If a label displays text, the indent applies to the left edge if alignment() is AlignLeft, to the right edge if alignment() is AlignRight, to the top edge if alignment() is AlignTop, and to to the bottom edge if alignment() is AlignBottom.

If indent is negative, or if no indent has been set, the label computes the effective indent as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater than 0, the effective indent becomes half the width of the "x" character of the widget's current font().

See also alignment, frameWidth and font.

Set this property's value with setIndent() and get this property's value with indent().

QPixmap pixmap

This property holds the label's pixmap.

If no pixmap has been set this will return an invalid pixmap.

Setting the pixmap clears any previous content, and resizes the label if QLabel::autoResize() is TRUE. The buddy accelerator, if any, is disabled.

Set this property's value with setPixmap() and get this property's value with pixmap().

bool scaledContents

This property holds whether the label will scale its contents to fill all available space.

When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space.

This property's default is FALSE.

See also scaledContents.

Set this property's value with setScaledContents() and get this property's value with hasScaledContents().

QString text

This property holds the label text.

If no text has been set this will return an empty string. Setting the text clears any previous content, unless they are the same.

The text will be interpreted either as a plain text or as a rich text, depending on the text format setting; see setTextFormat(). The default setting is AutoText, i.e. QLabel will try to auto-detect the format of the text set.

If the text is interpreted as a plain text and a buddy has been set, the buddy accelerator key is updated from the new text.

The label resizes itself if auto-resizing is enabled.

Note that Qlabel is well-suited to display small rich text documents only. Those small documents get their document specific settings (font, text color, link color) from the label's palette and font properties. For large documents, use QTextView instead. QTextView will flicker less on resize and can also provide a scrollbar, when necessary.

See also textFormat, setBuddy() and alignment.

Set this property's value with setText() and get this property's value with text().

TextFormat textFormat

This property holds the label's text format.

See the Qt::TextFormat enum for an explanation of the possible options.

The default format is AutoText.

See also text.

Set this property's value with setTextFormat() and get this property's value with textFormat().

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


qlabel.h Include File

qlabel.h

This is the verbatim text of the qlabel.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qlabel.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QLabel widget class
**
** Created : 941215
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLABEL_H
#define QLABEL_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_LABEL

class QSimpleRichText;
class QLabelPrivate;

class Q_EXPORT QLabel : public QFrame
{
    Q_OBJECT
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( TextFormat textFormat READ textFormat WRITE setTextFormat )
    Q_PROPERTY( QPixmap pixmap READ pixmap WRITE setPixmap )
    Q_PROPERTY( bool scaledContents READ hasScaledContents WRITE setScaledContents )
    Q_PROPERTY( Alignment alignment READ alignment WRITE setAlignment )
    Q_PROPERTY( int indent READ indent WRITE setIndent )

public:
    QLabel( QWidget *parent, const char* name=0, WFlags f=0 );
    QLabel( const QString &text, QWidget *parent, const char* name=0,
        WFlags f=0 );
    QLabel( QWidget *buddy, const QString &,
        QWidget *parent, const char* name=0, WFlags f=0 );
    ~QLabel();

    QString	 text()		const	{ return ltext; }
    QPixmap     *pixmap()	const	{ return lpixmap; }
#ifndef QT_NO_PICTURE
    QPicture    *picture()	const	{ return lpicture; }
#endif
#ifndef QT_NO_MOVIE
    QMovie      *movie()		const;
#endif

    TextFormat textFormat() const;
    void 	 setTextFormat( TextFormat );

    int		 alignment() const	{ return align; }
    virtual void setAlignment( int );
    int		 indent() const		{ return extraMargin; }
    void 	 setIndent( int );

    bool 	 autoResize() const	{ return autoresize; }
    virtual void setAutoResize( bool );
#ifndef QT_NO_IMAGE_SMOOTHSCALE
    bool 	hasScaledContents() const;
    void 	setScaledContents( bool );
#endif
    QSize	 sizeHint() const;
    QSize	 minimumSizeHint() const;
#ifndef QT_NO_ACCEL
    virtual void setBuddy( QWidget * );
    QWidget     *buddy() const;
#endif
    int		 heightForWidth(int) const;

    void setFont( const QFont &f );

public slots:
    virtual void setText( const QString &);
    virtual void setPixmap( const QPixmap & );
#ifndef QT_NO_PICTURE
    virtual void setPicture( const QPicture & );
#endif
#ifndef QT_NO_MOVIE
    virtual void setMovie( const QMovie & );
#endif
    virtual void setNum( int );
    virtual void setNum( double );
    void	 clear();

protected:
    void	 drawContents( QPainter * );
    void	 fontChange( const QFont & );
    void	 resizeEvent( QResizeEvent* );

private slots:
#ifndef QT_NO_ACCEL
    void	 acceleratorSlot();
    void	 buddyDied();
#endif
#ifndef QT_NO_MOVIE
    void	 movieUpdated(const QRect&);
    void	 movieResized(const QSize&);
#endif

private:
    void	init();
    void	clearContents();
    void	updateLabel( QSize oldSizeHint );
    QSize	sizeForWidth( int w ) const;
    QString	ltext;
    QPixmap    *lpixmap;
#ifndef QT_NO_PICTURE
    QPicture   *lpicture;
#endif
#ifndef QT_NO_MOVIE
    QMovie *	lmovie;
#endif
#ifndef QT_NO_ACCEL
    QWidget *	lbuddy;
#endif
    ushort	align;
    short	extraMargin;
    uint	autoresize:1;
    uint	scaledcontents :1;
    TextFormat textformat;
#ifndef QT_NO_RICHTEXT
    QSimpleRichText* doc;
#endif
#ifndef QT_NO_ACCEL
    QAccel *	accel;
#endif
    QLabelPrivate* d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QLabel( const QLabel & );
    QLabel &operator=( const QLabel & );
#endif
};

#endif // QT_NO_LABEL

#endif // QLABEL_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLabel Member List

Complete Member List for QLabel

This is the complete list of member functions for QLabel, including inherited members.

  • QLabel()
  • ~QLabel()
  • acceptDrops()
  • adjustSize()
  • alignment()
  • autoMask()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • buddy()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasScaledContents()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • movie()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • picture()
  • pixmap()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBuddy()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setIndent()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMovie()
  • setName()
  • setNum()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPicture()
  • setPixmap()
  • setProperty()
  • setScaledContents()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setText()
  • setTextFormat()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • textFormat()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QLayout Class

QLayout Class Reference

The QLayout class is the base class of geometry managers. More...

#include <qlayout.h>

Inherits QObject and QLayoutItem.

Inherited by QGridLayout and QBoxLayout.

List of all member functions.

Public Members

  • QLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )
  • QLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )
  • QLayout ( int spacing = -1, const char * name = 0 )
  • int margin () const
  • int spacing () const
  • virtual void setMargin ( int )
  • virtual void setSpacing ( int )
  • enum ResizeMode { FreeResize, Minimum, Fixed }
  • void setResizeMode ( ResizeMode )
  • ResizeMode resizeMode () const
  • virtual void setMenuBar ( QMenuBar * w )
  • QMenuBar * menuBar () const
  • QWidget * mainWidget ()
  • bool isTopLevel () const
  • virtual void setAutoAdd ( bool b )
  • bool autoAdd () const
  • virtual void invalidate ()
  • bool activate ()
  • void add ( QWidget * w )
  • virtual void addItem ( QLayoutItem * item ) = 0
  • virtual QSizePolicy::ExpandData expanding () const
  • virtual QSize minimumSize () const
  • virtual QSize maximumSize () const
  • virtual void setGeometry ( const QRect & r ) = 0
  • virtual QLayoutIterator iterator () = 0
  • virtual bool isEmpty () const
  • bool supportsMargin () const
  • void setEnabled ( bool enable )
  • bool isEnabled () const

Properties

  • int margin - the width of the outside border of the layout
  • ResizeMode resizeMode - the resize mode of the layout
  • int spacing - the spacing between widgets inside the layout

Protected Members

  • void addChildLayout ( QLayout * l )
  • void deleteAllItems ()
  • void setSupportsMargin ( bool b )
  • QRect alignmentRect ( const QRect & r ) const

Detailed Description

The QLayout class is the base class of geometry managers.

This is an abstract base class inherited by the concrete classes, QBoxLayout and QGridLayout.

For users of QLayout subclasses or of QMainWindow there is seldom any need to use the basic functions provided by QLayout, such as resizeMode or setMenuBar(). See the layout overview page for more information.

To make your own layout manager, subclass QGLayoutIterator and implement the functions addItem(), sizeHint(), setGeometry(), and iterator(). You should also implement minimumSize() to ensure your layout isn't resized to zero size if there is too little space. To support children whose heights depend on their widths, implement hasHeightForWidth() and heightForWidth(). See the custom layout page for an in-depth description.

Geometry management stops when the layout manager is deleted.

See also Widget Appearance and Style and Layout Management.

Member Type Documentation

QLayout::ResizeMode

The possible values are:

  • QLayout::Fixed - The main widget's size is set to sizeHint(); it cannot be resized at all.
  • QLayout::Minimum - The main widget's minimum size is set to minimumSize(); it cannot be smaller.
  • QLayout::FreeResize - The widget is not constrained.

Member Function Documentation

QLayout::QLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )

Constructs a new top-level QLayout called name, with main widget parent. parent may not be 0.

The margin is the number of pixels between the edge of the widget and the managed children. The spacing sets the value of spacing(), which gives the spacing between the managed widgets. If spacing is -1 (the default), spacing is set to the value of margin.

There can be only one top-level layout for a widget. It is returned by QWidget::layout()

QLayout::QLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )

Constructs a new child QLayout called name, and places it inside parentLayout by using the default placement defined by addItem().

If spacing is -1, this QLayout inherits parentLayout's spacing(), otherwise the value of spacing is used.

QLayout::QLayout ( int spacing = -1, const char * name = 0 )

Constructs a new child QLayout called name. If spacing is -1, this QLayout inherits its parent's spacing(); otherwise the value of spacing is used.

This layout has to be inserted into another layout before geometry management will work.

bool QLayout::activate ()

Redoes the layout for mainWidget(). You should generally not need to call this because it is automatically called at the most appropriate times.

However, if you set up a QLayout for a visible widget without resizing that widget, you will need to call this function in order to lay it out.

See also QWidget::updateGeometry().

Examples: layout/layout.cpp, popup/popup.cpp, scrollview/scrollview.cpp and sql/overview/form1/main.cpp.

void QLayout::add ( QWidget * w )

Adds widget w to this layout in a manner specific to the layout. This function uses addItem().

Examples: customlayout/border.cpp and customlayout/main.cpp.

void QLayout::addChildLayout ( QLayout * l ) [protected]

This function is called from addLayout() functions in subclasses to add layout l as a sub-layout.

void QLayout::addItem ( QLayoutItem * item ) [pure virtual]

Implemented in subclasses to add an item. How it is added is specific to each subclass.

The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented in QGridLayout and QBoxLayout.

QRect QLayout::alignmentRect ( const QRect & r ) const [protected]

Returns the rectangle that should be covered when the geometry of this layout is set to r, provided that this layout supports setAlignment().

The result is derived from sizeHint() and expanding(). It is never larger than r.

bool QLayout::autoAdd () const

Returns TRUE if this layout automatically grabs all new mainWidget()'s new children and adds them as defined by addItem(); otherwise returns FALSE. This has effect only for top-level layouts, i.e. layouts that are direct children of their mainWidget().

autoAdd() is disabled by default.

Note that a top-level layout is not necessarily associated with the top-level widget.

See also setAutoAdd().

void QLayout::deleteAllItems () [protected]

Removes and deletes all items in this layout.

QSizePolicy::ExpandData QLayout::expanding () const [virtual]

Returns whether this layout can make use of more space than sizeHint(). A value of Vertical or Horizontal means that it wants to grow in only one dimension, whereas BothDirections means that it wants to grow in both dimensions.

The default implementation returns BothDirections.

Examples: customlayout/border.cpp and customlayout/flow.cpp.

Reimplemented from QLayoutItem.

Reimplemented in QGridLayout and QBoxLayout.

void QLayout::invalidate () [virtual]

Invalidates cached information. Reimplementations must call this.

Reimplemented from QLayoutItem.

Reimplemented in QGridLayout and QBoxLayout.

bool QLayout::isEmpty () const [virtual]

Returns TRUE if this layout is empty. The default implementation returns FALSE.

Reimplemented from QLayoutItem.

bool QLayout::isEnabled () const

Returns TRUE if the layout is enabled; otherwise returns FALSE.

See also setEnabled().

bool QLayout::isTopLevel () const

Returns TRUE if this layout is a top-level layout, i.e. not a child of another layout; otherwise returns FALSE.

QLayoutIterator QLayout::iterator () [pure virtual]

Implemented in subclasses to return an iterator that iterates over this layout's children.

A typical implementation will be:

        QLayoutIterator MyLayout::iterator()
        {
            QGLayoutIterator *i = new MyLayoutIterator( internal_data );
            return QLayoutIterator( i );
        }
where MyLayoutIterator is a subclass of QGLayoutIterator.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented from QLayoutItem.

QWidget * QLayout::mainWidget ()

Returns the main widget (parent widget) of this layout, or 0 if this layout is a sub-layout that is not yet inserted.

int QLayout::margin () const

Returns the width of the outside border of the layout. See the "margin" property for details.

QSize QLayout::maximumSize () const [virtual]

Returns the maximum size of this layout. This is the largest size that the layout can have while still respecting the specifications. Does not include what's needed by margin() or menuBar().

The default implementation allows unlimited resizing.

Reimplemented from QLayoutItem.

Reimplemented in QGridLayout and QBoxLayout.

QMenuBar * QLayout::menuBar () const

Returns the menu bar set for this layout, or 0 if no menu bar is set.

QSize QLayout::minimumSize () const [virtual]

Returns the minimum size of this layout. This is the smallest size that the layout can have while still respecting the specifications. Does not include what's needed by margin() or menuBar().

The default implementation allows unlimited resizing.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented from QLayoutItem.

Reimplemented in QGridLayout and QBoxLayout.

ResizeMode QLayout::resizeMode () const

Returns the resize mode of the layout. See the "resizeMode" property for details.

void QLayout::setAutoAdd ( bool b ) [virtual]

If b is TRUE, auto-add is enabled; otherwise auto-add is disabled.

See also autoAdd().

Example: i18n/main.cpp.

void QLayout::setEnabled ( bool enable )

Enables this layout if enable is TRUE, otherwise disables it.

An enabled layout adjusts dynamically to changes; a disabled layout acts as if it did not exist.

By default all layouts are enabled.

See also isEnabled().

void QLayout::setGeometry ( const QRect & r ) [pure virtual]

This function is reimplemented in subclasses to perform layout.

The default implementation maintains the geometry() information given by rect r. Reimplementors must call this function.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented from QLayoutItem.

Reimplemented in QGridLayout and QBoxLayout.

void QLayout::setMargin ( int ) [virtual]

Sets the width of the outside border of the layout. See the "margin" property for details.

void QLayout::setMenuBar ( QMenuBar * w ) [virtual]

Makes the geometry manager take account of the menu bar w. All child widgets are placed below the bottom edge of the menu bar.

A menu bar does its own geometry management: never do addWidget() on a QMenuBar.

Examples: layout/layout.cpp and scrollview/scrollview.cpp.

void QLayout::setResizeMode ( ResizeMode )

Sets the resize mode of the layout. See the "resizeMode" property for details.

void QLayout::setSpacing ( int ) [virtual]

Sets the spacing between widgets inside the layout. See the "spacing" property for details.

void QLayout::setSupportsMargin ( bool b ) [protected]

Sets the value returned by supportsMargin(). If b is TRUE, margin() handling is implemented by the subclass. If b is FALSE (the default), QLayout will add margin() around top-level layouts.

If b is TRUE, margin handling needs to be implemented in setGeometry(), maximumSize(), minimumSize(), sizeHint() and heightForWidth().

See also supportsMargin().

int QLayout::spacing () const

Returns the spacing between widgets inside the layout. See the "spacing" property for details.

bool QLayout::supportsMargin () const

Returns TRUE if this layout supports QLayout::margin on non-top-level layouts; otherwise returns FALSE.

See also margin.

Property Documentation

int margin

This property holds the width of the outside border of the layout.

For some layout classes this property has an effect only on top-level layouts; QBoxLayout and QGridLayout support margins for child layouts. The default value is 0.

See also spacing.

Set this property's value with setMargin() and get this property's value with margin().

ResizeMode resizeMode

This property holds the resize mode of the layout.

The default mode is Minimum for top-level widgets and FreeResize for all others.

See also QLayout::ResizeMode.

Set this property's value with setResizeMode() and get this property's value with resizeMode().

int spacing

This property holds the spacing between widgets inside the layout.

The default value is -1, which signifies that the layout's spacing should not override the widget's spacing.

See also margin.

Set this property's value with setSpacing() and get this property's value with spacing().

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


qlayout.h Include File

qlayout.h

This is the verbatim text of the qlayout.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of layout classes
**
** Created : 960416
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLAYOUT_H
#define QLAYOUT_H

#ifndef QT_H
#include "qobject.h"
#include "qsizepolicy.h"
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_LAYOUT

#if 0
Q_OBJECT
#endif
//static const int QLAYOUTSIZE_MAX=INT_MAX/256/16; //wait for 3.1

/*
  First comes the definition of QLayout and of related abstract
  classes that used to be defined in qabstractlayout.h.
*/

class QMenuBar;
class QWidget;
struct QLayoutData;
class QLayoutItem;
class QLayout;
class QSpacerItem;

class Q_EXPORT QGLayoutIterator : public QShared
{
public:
    virtual ~QGLayoutIterator();
    virtual QLayoutItem *next() = 0;
    virtual QLayoutItem *current() = 0;
    virtual QLayoutItem *takeCurrent() = 0;
};

class Q_EXPORT QLayoutIterator
{
public:
    QLayoutIterator( QGLayoutIterator *i ) :it( i ) { }
    QLayoutIterator( const QLayoutIterator &i ) :it( i.it )
    { if ( it ) it->ref(); }
    ~QLayoutIterator() { if ( it && it->deref() ) delete it; }
    QLayoutIterator &operator=( const QLayoutIterator &i )
    {
    if ( i.it ) i.it->ref();
    if ( it && it->deref() ) delete it;
    it = i.it;
    return *this;
    }
    QLayoutItem *operator++() { return it ? it->next() : 0; }
    QLayoutItem *current() { return it ? it->current() : 0; }
    QLayoutItem *takeCurrent() { return it ? it->takeCurrent() : 0; }
    void deleteCurrent();

private:
    QGLayoutIterator *it;
};

class Q_EXPORT QLayoutItem
{
public:
    QLayoutItem( int alignment = 0 ) : align( alignment ) { }
    virtual ~QLayoutItem();
    virtual QSize sizeHint() const = 0;
    virtual QSize minimumSize() const = 0;
    virtual QSize maximumSize() const = 0;
    virtual QSizePolicy::ExpandData expanding() const = 0;
    virtual void setGeometry( const QRect& ) = 0;
    virtual QRect geometry() const = 0;
    virtual bool isEmpty() const = 0;
    virtual bool hasHeightForWidth() const;
    virtual int heightForWidth( int ) const;
    virtual void invalidate();

    virtual QWidget *widget();
    virtual QLayoutIterator iterator();
    virtual QLayout *layout();
    virtual QSpacerItem *spacerItem();

    int alignment() const { return align; }
    virtual void setAlignment( int a );

protected:
    int align;
};

class Q_EXPORT QSpacerItem : public QLayoutItem
{
 public:
    QSpacerItem( int w, int h,
         QSizePolicy::SizeType hData=QSizePolicy::Minimum,
         QSizePolicy::SizeType vData= QSizePolicy::Minimum )
    : width( w ), height( h ), sizeP( hData, vData ) { }
    void changeSize( int w, int h,
             QSizePolicy::SizeType hData=QSizePolicy::Minimum,
             QSizePolicy::SizeType vData=QSizePolicy::Minimum );
    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize maximumSize() const;
    QSizePolicy::ExpandData expanding() const;
    bool isEmpty() const;
    void setGeometry( const QRect& );
    QRect geometry() const;
    QSpacerItem *spacerItem();

private:
    int width;
    int height;
    QSizePolicy sizeP;
    QRect rect;
};

class Q_EXPORT QWidgetItem : public QLayoutItem
{
public:
    QWidgetItem( QWidget *w ) : wid( w ) { }
    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize maximumSize() const;
    QSizePolicy::ExpandData expanding() const;
    bool isEmpty() const;
    void setGeometry( const QRect& );
    QRect geometry() const;
    virtual QWidget *widget();

    bool hasHeightForWidth() const;
    int heightForWidth( int ) const;

private:
    QWidget *wid;
};

class Q_EXPORT QLayout : public QObject, public QLayoutItem
{
    Q_OBJECT
    Q_ENUMS( ResizeMode )
    Q_PROPERTY( int margin READ margin WRITE setMargin )
    Q_PROPERTY( int spacing READ spacing WRITE setSpacing )
    Q_PROPERTY( ResizeMode resizeMode READ resizeMode WRITE setResizeMode )

public:
    QLayout( QWidget *parent, int margin = 0, int spacing = -1,
         const char *name = 0 );
    QLayout( QLayout *parentLayout, int spacing = -1, const char *name = 0 );
    QLayout( int spacing = -1, const char *name = 0 );

    ~QLayout();

    int margin() const { return outsideBorder; }
    int spacing() const { return insideSpacing; }

    virtual void setMargin( int );
    virtual void setSpacing( int );

    //enum { unlimited = QLAYOUTSIZE_MAX }; //in 3.1
    enum { unlimited = QWIDGETSIZE_MAX };
    int defaultBorder() const { return insideSpacing; }
    void freeze( int w, int h );
    void freeze() { setResizeMode( Fixed ); }

    enum ResizeMode { FreeResize, Minimum, Fixed };
    void setResizeMode( ResizeMode );
    ResizeMode resizeMode() const;

#ifndef QT_NO_MENUBAR
    virtual void  setMenuBar( QMenuBar *w );
    QMenuBar *menuBar() const { return menubar; }
#endif

    QWidget *mainWidget();
    bool isTopLevel() const { return topLevel; }

    virtual void setAutoAdd( bool );
    bool autoAdd() const { return autoNewChild; }

    void invalidate();
    QRect geometry() const;
    bool activate();

    void add( QWidget *w ) { addItem( new QWidgetItem(w) ); }
    virtual void addItem ( QLayoutItem * ) = 0;

    QSizePolicy::ExpandData expanding() const;
    QSize minimumSize() const;
    QSize maximumSize() const;
    void setGeometry( const QRect& )=0;
    QLayoutIterator iterator()=0;
    bool isEmpty() const;

    int totalHeightForWidth( int w ) const;
    QSize totalMinimumSize() const;
    QSize totalMaximumSize() const;
    QSize totalSizeHint() const;
    QLayout *layout();

    bool supportsMargin() const { return marginImpl; }

    void setEnabled( bool );
    bool isEnabled() const;

protected:
    bool eventFilter( QObject *, QEvent * );
    void childEvent( QChildEvent *e );
    void addChildLayout( QLayout *l );
    void deleteAllItems();

    void setSupportsMargin( bool );
    QRect alignmentRect( const QRect& ) const;

private:
    void setWidgetLayout( QWidget *, QLayout * );
    void init();
    int insideSpacing;
    int outsideBorder;
    uint topLevel : 1;
    uint autoMinimum : 1;
    uint autoNewChild : 1;
    uint frozen : 1;
    uint activated : 1;
    uint marginImpl : 1;
    uint enabled : 1;
    QRect rect;
    QLayoutData *extraData;
#ifndef QT_NO_MENUBAR
    QMenuBar *menubar;
#endif
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QLayout( const QLayout & );
    QLayout &operator=( const QLayout & );
#endif

};

inline void QLayoutIterator::deleteCurrent()
{
    delete takeCurrent();
}

/*
  Follow the Q*Layout classes, that always belonged to qlayout.h.
*/

class QGridLayoutData;
class QGridLayoutBox;

class Q_EXPORT QGridLayout : public QLayout
{
    Q_OBJECT
public:
    QGridLayout( QWidget *parent, int nRows = 1, int nCols = 1, int border = 0,
         int spacing = -1, const char *name = 0 );
    QGridLayout( int nRows = 1, int nCols = 1, int spacing = -1,
         const char *name = 0 );
    QGridLayout( QLayout *parentLayout, int nRows = 1, int nCols = 1,
         int spacing = -1, const char *name = 0 );
    ~QGridLayout();

    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize maximumSize() const;

    virtual void setRowStretch( int row, int stretch );
    virtual void setColStretch( int col, int stretch );
    int rowStretch( int row ) const;
    int colStretch( int col ) const;

    int numRows() const;
    int numCols() const;
    QRect cellGeometry( int row, int col ) const;

    bool hasHeightForWidth() const;
    int heightForWidth( int ) const;

    QSizePolicy::ExpandData expanding() const;
    void invalidate();

    void addItem( QLayoutItem * );
    void addItem( QLayoutItem *item, int row, int col );
    void addMultiCell( QLayoutItem *, int fromRow, int toRow,
                   int fromCol, int toCol, int align = 0 );
    // void setAlignment( QWidget* );

    void addWidget( QWidget *, int row, int col, int align = 0 );
    void addMultiCellWidget( QWidget *, int fromRow, int toRow,
                 int fromCol, int toCol, int align = 0 );
    void addLayout( QLayout *layout, int row, int col);
    void addMultiCellLayout( QLayout *layout, int fromRow, int toRow,
                 int fromCol, int toCol, int align = 0 );
    void addRowSpacing( int row, int minsize );
    void addColSpacing( int col, int minsize );
    void expand( int rows, int cols );

    enum Corner { TopLeft, TopRight, BottomLeft, BottomRight };
    void setOrigin( Corner );
    Corner origin() const;
    QLayoutIterator iterator();
    void setGeometry( const QRect& );

protected:
    bool findWidget( QWidget* w, int *r, int *c );
    void add( QLayoutItem*, int row, int col );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QGridLayout( const QGridLayout & );
    QGridLayout &operator=( const QGridLayout & );
#endif

    void init( int rows, int cols );
    QGridLayoutData *data;
};

class QBoxLayoutData;
class QDockWindow;

class Q_EXPORT QBoxLayout : public QLayout
{
    Q_OBJECT
public:
    enum Direction { LeftToRight, RightToLeft, TopToBottom, BottomToTop,
             Down = TopToBottom, Up = BottomToTop };

    QBoxLayout( QWidget *parent, Direction, int border=0,
        int spacing = -1, const char *name=0 );
    QBoxLayout( QLayout *parentLayout, Direction, int spacing = -1,
        const char *name=0 );
    QBoxLayout(	Direction, int spacing = -1,
        const char *name=0 );
    ~QBoxLayout();

    void addItem( QLayoutItem * );

    Direction direction() const { return dir; }
    void setDirection( Direction );

    void addSpacing( int size );
    void addStretch( int stretch = 0 );
    void addWidget( QWidget *, int stretch = 0, int alignment = 0 );
    void addLayout( QLayout *layout, int stretch = 0 );
    void addStrut( int );

    void insertSpacing( int index, int size );
    void insertStretch( int index, int stretch = 0 );
    void insertWidget( int index, QWidget *widget, int stretch = 0,
               int alignment = 0 );
    void insertLayout( int index, QLayout *layout, int stretch = 0 );

    bool setStretchFactor( QWidget*, int stretch );
    bool setStretchFactor( QLayout *l, int stretch );

    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize maximumSize() const;

    bool hasHeightForWidth() const;
    int heightForWidth( int ) const;

    QSizePolicy::ExpandData expanding() const;
    void invalidate();
    QLayoutIterator iterator();
    void setGeometry( const QRect& );

    int findWidget( QWidget* w );

protected:
    void insertItem( int index, QLayoutItem * );

private:	// Disabled copy constructor and operator=
    friend class QDockWindow;
#if defined(Q_DISABLE_COPY)
    QBoxLayout( const QBoxLayout & );
    QBoxLayout &operator=( const QBoxLayout & );
#endif

    void setupGeom();
    int calcHfw( int );
    QBoxLayoutData *data;
    Direction dir;
    QBoxLayout *createTmpCopy();
};

class Q_EXPORT QHBoxLayout : public QBoxLayout
{
    Q_OBJECT
public:
    QHBoxLayout( QWidget *parent, int border = 0,
         int spacing = -1, const char *name = 0 );
    QHBoxLayout( QLayout *parentLayout,
         int spacing = -1, const char *name = 0 );
    QHBoxLayout( int spacing = -1, const char *name = 0 );

    ~QHBoxLayout();
};

class Q_EXPORT QVBoxLayout : public QBoxLayout
{
    Q_OBJECT
public:
    QVBoxLayout( QWidget *parent, int border = 0,
         int spacing = -1, const char *name = 0 );
    QVBoxLayout( QLayout *parentLayout,
         int spacing = -1, const char *name = 0 );
    QVBoxLayout( int spacing = -1, const char *name = 0 );

    ~QVBoxLayout();
};

#endif // QT_NO_LAYOUT
#endif // QLAYOUT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLayout Member List

Complete Member List for QLayout

This is the complete list of member functions for QLayout, including inherited members.

  • QLayout()
  • activate()
  • add()
  • addChildLayout()
  • addItem()
  • alignment()
  • alignmentRect()
  • autoAdd()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteAllItems()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • expanding()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • invalidate()
  • isA()
  • isEmpty()
  • isEnabled()
  • isTopLevel()
  • isWidgetType()
  • iterator()
  • killTimer()
  • killTimers()
  • layout()
  • mainWidget()
  • margin()
  • maximumSize()
  • menuBar()
  • metaObject()
  • minimumSize()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • resizeMode()
  • sender()
  • setAlignment()
  • setAutoAdd()
  • setEnabled()
  • setGeometry()
  • setMargin()
  • setMenuBar()
  • setName()
  • setProperty()
  • setResizeMode()
  • setSpacing()
  • setSupportsMargin()
  • signalsBlocked()
  • sizeHint()
  • spacerItem()
  • spacing()
  • startTimer()
  • supportsMargin()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()


QLayoutItem Class

QLayoutItem Class Reference

The QLayoutItem class provides an abstract item that a QLayout manipulates. More...

#include <qlayout.h>

Inherited by QLayout, QSpacerItem and QWidgetItem.

List of all member functions.

Public Members

  • QLayoutItem ( int alignment = 0 )
  • virtual ~QLayoutItem ()
  • virtual QSize sizeHint () const = 0
  • virtual QSize minimumSize () const = 0
  • virtual QSize maximumSize () const = 0
  • virtual QSizePolicy::ExpandData expanding () const = 0
  • virtual void setGeometry ( const QRect & r ) = 0
  • virtual QRect geometry () const = 0
  • virtual bool isEmpty () const = 0
  • virtual bool hasHeightForWidth () const
  • virtual int heightForWidth ( int w ) const
  • virtual void invalidate ()
  • virtual QWidget * widget ()
  • virtual QLayoutIterator iterator ()
  • virtual QLayout * layout ()
  • virtual QSpacerItem * spacerItem ()
  • int alignment () const
  • virtual void setAlignment ( int a )

Detailed Description

The QLayoutItem class provides an abstract item that a QLayout manipulates.

This is used by custom layouts.

Pure virtual functions are provided to return information about the layout, including, sizeHint(), minimumSize(), maximumSize() and expanding().

The layout's geometry can be set and retrieved with setGeometry() and geometry(), and its alignment with setAlignment() and alignment().

isEmpty() returns whether the layout is empty. iterator() returns an iterator for the layout's children. If the concrete item is a QWidget, it can be retrieved using widget(). Similarly for layout() and spacerItem().

See also QLayout, Widget Appearance and Style and Layout Management.

Member Function Documentation

QLayoutItem::QLayoutItem ( int alignment = 0 )

Constructs a layout item with an alignment that is a bitwise OR of the Qt::AlignmentFlags. Not all subclasses support alignment.

QLayoutItem::~QLayoutItem () [virtual]

Destroys the QLayoutItem.

int QLayoutItem::alignment () const

Returns the alignment of this item.

QSizePolicy::ExpandData QLayoutItem::expanding () const [pure virtual]

Implemented in subclasses to return whether this item "wants" to expand.

Reimplemented in QLayout, QSpacerItem and QWidgetItem.

QRect QLayoutItem::geometry () const [pure virtual]

Returns the rectangle covered by this layout item.

Example: customlayout/border.cpp.

bool QLayoutItem::hasHeightForWidth () const [virtual]

Returns TRUE if this layout's preferred height depends on its width; otherwise returns FALSE. The default implementation returns FALSE.

Reimplement this function in layout managers that support height for width.

See also heightForWidth() and QWidget::heightForWidth().

Examples: customlayout/border.cpp and customlayout/flow.cpp.

Reimplemented in QGridLayout and QBoxLayout.

int QLayoutItem::heightForWidth ( int w ) const [virtual]

Returns the preferred height for this layout item, given the width w.

The default implementation returns -1, indicating that the preferred height is independent of the width of the item. Using the function hasHeightForWidth() will typically be much faster than calling this function and testing for -1.

Reimplement this function in layout managers that support height for width. A typical implementation will look like this:

        int MyLayout::heightForWidth( int w ) const
        {
            if ( cache_dirty || cached_width != w ) {
                // not all C++ compilers support "mutable"
                MyLayout *that = (MyLayout*)this;
                int h = calculateHeightForWidth( w );
                that->cached_hfw = h;
                return h;
            }
            return cached_hfw;
        }

Caching is strongly recommended; without it layout will take exponential time.

See also hasHeightForWidth().

Example: customlayout/flow.cpp.

Reimplemented in QGridLayout and QBoxLayout.

void QLayoutItem::invalidate () [virtual]

Invalidates any cached information in this layout item.

Reimplemented in QLayout.

bool QLayoutItem::isEmpty () const [pure virtual]

Implemented in subclasses to return whether this item is empty, i.e. whether it contains any widgets.

Reimplemented in QLayout, QSpacerItem and QWidgetItem.

QLayoutIterator QLayoutItem::iterator () [virtual]

Returns an iterator over this item's QLayoutItem children. The default implementation returns an empty iterator.

Reimplement this function in subclasses that can have children.

Reimplemented in QLayout.

QLayout * QLayoutItem::layout () [virtual]

If this item is a QLayout, it is returned as a QLayout; otherwise 0 is returned. This function provides type-safe casting.

QSize QLayoutItem::maximumSize () const [pure virtual]

Implemented in subclasses to return the maximum size of this item.

Reimplemented in QLayout, QSpacerItem and QWidgetItem.

QSize QLayoutItem::minimumSize () const [pure virtual]

Implemented in subclasses to return the minimum size of this item.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented in QLayout, QSpacerItem and QWidgetItem.

void QLayoutItem::setAlignment ( int a ) [virtual]

Sets the alignment of this item to a, which is a bitwise OR of the Qt::AlignmentFlags. Not all subclasses support alignment.

Example: chart/optionsform.cpp.

void QLayoutItem::setGeometry ( const QRect & r ) [pure virtual]

Implemented in subclasses to set this item's geometry to r.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented in QLayout, QSpacerItem and QWidgetItem.

QSize QLayoutItem::sizeHint () const [pure virtual]

Implemented in subclasses to return the preferred size of this item.

Examples: customlayout/border.cpp, customlayout/card.cpp and customlayout/flow.cpp.

Reimplemented in QSpacerItem, QWidgetItem, QGridLayout and QBoxLayout.

QSpacerItem * QLayoutItem::spacerItem () [virtual]

If this item is a QSpacerItem, it is returned as a QSpacerItem; otherwise 0 is returned. This function provides type-safe casting.

QWidget * QLayoutItem::widget () [virtual]

If this item is a QWidget, it is returned as a QWidget; otherwise 0 is returned. This function provides type-safe casting.

Reimplemented in QWidgetItem.

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


QLayoutItem Member List

Complete Member List for QLayoutItem

This is the complete list of member functions for QLayoutItem, including inherited members.

  • QLayoutItem()
  • ~QLayoutItem()
  • alignment()
  • expanding()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • invalidate()
  • isEmpty()
  • iterator()
  • layout()
  • maximumSize()
  • minimumSize()
  • setAlignment()
  • setGeometry()
  • sizeHint()
  • spacerItem()
  • widget()


QLayoutIterator Class

QLayoutIterator Class Reference

The QLayoutIterator class provides iterators over QLayoutItem. More...

#include <qlayout.h>

List of all member functions.

Public Members

  • QLayoutIterator ( QGLayoutIterator * gi )
  • QLayoutIterator ( const QLayoutIterator & i )
  • ~QLayoutIterator ()
  • QLayoutIterator & operator= ( const QLayoutIterator & i )
  • QLayoutItem * operator++ ()
  • QLayoutItem * current ()
  • QLayoutItem * takeCurrent ()
  • void deleteCurrent ()

Detailed Description

The QLayoutIterator class provides iterators over QLayoutItem.

Use QLayoutItem::iterator() to create an iterator over a layout.

QLayoutIterator uses explicit sharing with a reference count. If an iterator is copied and one of the copies is modified, both iterators will be modified.

A QLayoutIterator is not protected against changes in its layout. If the layout is modified or deleted the iterator will become invalid. It is not possible to test for validity. It is safe to delete an invalid layout; any other access may lead to an illegal memory reference and the abnormal termination of the program.

Calling takeCurrent() or deleteCurrent() leaves the iterator in a valid state, but may invalidate any other iterators that access the same layout.

The following code will draw a rectangle for each layout item in the layout structure of the widget.

    static void paintLayout( QPainter *p, QLayoutItem *lay )
    {
        QLayoutIterator it = lay->iterator();
        QLayoutItem *child;
        while ( (child = it.current()) != 0 ) {
            paintLayout( p, child );
            it.next();
        }
        p->drawRect( lay->geometry() );
    }
    void ExampleWidget::paintEvent( QPaintEvent * )
    {
        QPainter p( this );
        if ( layout() )
            paintLayout( &p, layout() );
    }

All the functionality of QLayoutIterator is implemented by subclasses of QGLayoutIterator. QLayoutIterator itself is not designed to be subclassed.

See also Widget Appearance and Style and Layout Management.

Member Function Documentation

QLayoutIterator::QLayoutIterator ( QGLayoutIterator * gi )

Constructs an iterator based on gi. The constructed iterator takes ownership of gi and will delete it.

This constructor is provided for layout implementors. Application programmers should use QLayoutItem::iterator() to create an iterator over a layout.

QLayoutIterator::QLayoutIterator ( const QLayoutIterator & i )

Creates a shallow copy of i, i.e. if the copy is modified, then the original will also be modified.

QLayoutIterator::~QLayoutIterator ()

Destroys the iterator.

QLayoutItem * QLayoutIterator::current ()

Returns the current item, or 0 if there is no current item.

void QLayoutIterator::deleteCurrent ()

Removes and deletes the current child item from the layout and moves the iterator to the next item. This iterator will still be valid, but any other iterator over the same layout may become invalid.

QLayoutItem * QLayoutIterator::operator++ ()

Moves the iterator to the next child item and returns that item, or 0 if there is no such item.

QLayoutIterator & QLayoutIterator::operator= ( const QLayoutIterator & i )

Assigns i to this iterator and returns a reference to this iterator.

QLayoutItem * QLayoutIterator::takeCurrent ()

Removes the current child item from the layout without deleting it, and moves the iterator to the next item. Returns the removed item, or 0 if there was no item to be removed. This iterator will still be valid, but any other iterator over the same layout may become invalid.

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


QLayoutIterator Member List

Complete Member List for QLayoutIterator

This is the complete list of member functions for QLayoutIterator, including inherited members.

  • QLayoutIterator()
  • ~QLayoutIterator()
  • current()
  • deleteCurrent()
  • operator++()
  • operator=()
  • takeCurrent()


QLCDNumber Class

QLCDNumber Class Reference

The QLCDNumber widget displays a number with LCD-like digits. More...

#include <qlcdnumber.h>

Inherits QFrame.

List of all member functions.

Public Members

  • QLCDNumber ( QWidget * parent = 0, const char * name = 0 )
  • QLCDNumber ( uint numDigits, QWidget * parent = 0, const char * name = 0 )
  • ~QLCDNumber ()
  • enum Mode { Hex, Dec, Oct, Bin, HEX = Hex, DEC = Dec, OCT = Oct, BIN = Bin }
  • enum SegmentStyle { Outline, Filled, Flat }
  • bool smallDecimalPoint () const
  • int numDigits () const
  • virtual void setNumDigits ( int nDigits )
  • bool checkOverflow ( double num ) const
  • bool checkOverflow ( int num ) const
  • Mode mode () const
  • virtual void setMode ( Mode )
  • SegmentStyle segmentStyle () const
  • virtual void setSegmentStyle ( SegmentStyle )
  • double value () const
  • int intValue () const

Public Slots

  • void display ( const QString & s )
  • void display ( int num )
  • void display ( double num )
  • virtual void setHexMode ()
  • virtual void setDecMode ()
  • virtual void setOctMode ()
  • virtual void setBinMode ()
  • virtual void setSmallDecimalPoint ( bool )

Signals

  • void overflow ()

Properties

  • int intValue - the displayed value rounded to the nearest integer
  • Mode mode - the current display mode (number base)
  • int numDigits - the current number of digits displayed
  • SegmentStyle segmentStyle - the style of the LCDNumber
  • bool smallDecimalPoint - the style of the decimal point
  • double value - the displayed value

Protected Members

  • virtual void drawContents ( QPainter * p )

Detailed Description

The QLCDNumber widget displays a number with LCD-like digits.

It can display a number in just about any size. It can display decimal, hexadecimal, octal or binary numbers. It is easy to connect to data sources using the display() slot, which is overloaded to take any of five argument types.

There are also slots to change the base with setMode() and the decimal point with setSmallDecimalPoint().

QLCDNumber emits the overflow() signal when it is asked to display something beyond its range. The range is set by setNumDigits(), but setSmallDecimalPoint() also influences it. If the display is set to hexadecimal, octal or binary, the integer equivalent of the value is displayed.

These digits and other symbols can be shown: 0/O, 1, 2, 3, 4, 5/S, 6, 7, 8, 9/g, minus, decimal point, A, B, C, D, E, F, h, H, L, o, P, r, u, U, Y, colon, degree sign (which is specified as single quote in the string) and space. QLCDNumber substitutes spaces for illegal characters.

It is not possible to retrieve the contents of a QLCDNumber object, although you can retrieve the numeric value with value(). If you really need the text, we recommend that you connect the signals that feed the display() slot to another slot as well and store the value there.

Incidentally, QLCDNumber is the very oldest part of Qt, tracing back to a BASIC program on the Sinclair Spectrum.

See also QLabel, QFrame and Basic Widgets.

Member Type Documentation

QLCDNumber::Mode

This type determines how numbers are shown. The possible values are:

  • QLCDNumber::Hex - Hexadecimal
  • QLCDNumber::Dec - Decimal
  • QLCDNumber::Oct - Octal
  • QLCDNumber::Bin - Binary

If the display is set to hexadecimal, octal or binary, the integer equivalent of the value is displayed.

QLCDNumber::SegmentStyle

This type determines the visual appearance of the QLCDNumber widget. The possible values are:

  • QLCDNumber::Outline - gives raised segments filled with the background brush.
  • QLCDNumber::Filled - gives raised segments filled with the foreground brush.
  • QLCDNumber::Flat - gives flat segments filled with the foreground brush.

Member Function Documentation

QLCDNumber::QLCDNumber ( QWidget * parent = 0, const char * name = 0 )

Constructs an LCD number, sets the number of digits to 5, the base to decimal, the decimal point mode to 'small' and the frame style to a raised box. The segmentStyle() is set to Outline.

The parent and name arguments are passed to the QFrame constructor.

See also numDigits and smallDecimalPoint.

QLCDNumber::QLCDNumber ( uint numDigits, QWidget * parent = 0, const char * name = 0 )

Constructs an LCD number, sets the number of digits to numDigits, the base to decimal, the decimal point mode to 'small' and the frame style to a raised box. The segmentStyle() is set to Outline.

The parent and name arguments are passed to the QFrame constructor.

See also numDigits and smallDecimalPoint.

QLCDNumber::~QLCDNumber ()

Destroys the LCD number.

bool QLCDNumber::checkOverflow ( double num ) const

Returns TRUE if num is too big to be displayed in its entirety; otherwise returns FALSE.

See also intValue, numDigits and smallDecimalPoint.

bool QLCDNumber::checkOverflow ( int num ) const

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

Returns TRUE if num is too big to be displayed in its entirety; otherwise returns FALSE.

See also intValue, numDigits and smallDecimalPoint.

void QLCDNumber::display ( int num ) [slot]

Sets the displayed value rounded to the nearest integer to num. See the "intValue" property for details.

void QLCDNumber::display ( const QString & s ) [slot]

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

Displays the number represented by the string s.

This version of the function disregards mode() and smallDecimalPoint().

These digits and other symbols can be shown: 0/O, 1, 2, 3, 4, 5/S, 6, 7, 8, 9/g, minus, decimal point, A, B, C, D, E, F, h, H, L, o, P, r, u, U, Y, colon, degree sign (which is specified as single quote in the string) and space. QLCDNumber substitutes spaces for illegal characters.

void QLCDNumber::display ( double num ) [slot]

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

Displays the number num.

void QLCDNumber::drawContents ( QPainter * p ) [virtual protected]

Draws the LCD number using painter p. This function is called from QFrame::paintEvent().

Reimplemented from QFrame.

int QLCDNumber::intValue () const

Returns the displayed value rounded to the nearest integer. See the "intValue" property for details.

Mode QLCDNumber::mode () const

Returns the current display mode (number base). See the "mode" property for details.

int QLCDNumber::numDigits () const

Returns the current number of digits displayed. See the "numDigits" property for details.

void QLCDNumber::overflow () [signal]

This signal is emitted whenever the QLCDNumber is asked to display a too-large number or a too-long string.

It is never emitted by setNumDigits().

SegmentStyle QLCDNumber::segmentStyle () const

Returns the style of the LCDNumber. See the "segmentStyle" property for details.

void QLCDNumber::setBinMode () [virtual slot]

Calls setMode( BIN ). Provided for convenience (e.g. for connecting buttons to it).

See also mode, setHexMode(), setDecMode(), setOctMode() and mode.

void QLCDNumber::setDecMode () [virtual slot]

Calls setMode( DEC ). Provided for convenience (e.g. for connecting buttons to it).

See also mode, setHexMode(), setOctMode(), setBinMode() and mode.

void QLCDNumber::setHexMode () [virtual slot]

Calls setMode( HEX ). Provided for convenience (e.g. for connecting buttons to it).

See also mode, setDecMode(), setOctMode(), setBinMode() and mode.

void QLCDNumber::setMode ( Mode ) [virtual]

Sets the current display mode (number base). See the "mode" property for details.

void QLCDNumber::setNumDigits ( int nDigits ) [virtual]

Sets the current number of digits displayed to nDigits. See the "numDigits" property for details.

void QLCDNumber::setOctMode () [virtual slot]

Calls setMode( OCT ). Provided for convenience (e.g. for connecting buttons to it).

See also mode, setHexMode(), setDecMode(), setBinMode() and mode.

void QLCDNumber::setSegmentStyle ( SegmentStyle ) [virtual]

Sets the style of the LCDNumber. See the "segmentStyle" property for details.

void QLCDNumber::setSmallDecimalPoint ( bool ) [virtual slot]

Sets the style of the decimal point. See the "smallDecimalPoint" property for details.

bool QLCDNumber::smallDecimalPoint () const

Returns the style of the decimal point. See the "smallDecimalPoint" property for details.

double QLCDNumber::value () const

Returns the displayed value. See the "value" property for details.

Property Documentation

int intValue

This property holds the displayed value rounded to the nearest integer.

This property corresponds to the nearest integer to the current value displayed by the LCDNumber. This is the value used for hexadecimal, octal and binary modes.

If the displayed value is not a number, the property has a value of 0.

Set this property's value with display() and get this property's value with intValue().

Mode mode

This property holds the current display mode (number base).

Corresponds to the current display mode, which is one of BIN, OCT, DEC (the default) and HEX. DEC mode can display floating point values, the other modes display the integer equivalent.

See also smallDecimalPoint, setHexMode(), setDecMode(), setOctMode() and setBinMode().

Set this property's value with setMode() and get this property's value with mode().

int numDigits

This property holds the current number of digits displayed.

Corresponds to the current number of digits. If QLCDNumber::smallDecimalPoint is FALSE, the decimal point occupies one digit position.

If the display is set to hexadecimal, octal or binary, the integer equivalent of the value is displayed.

See also smallDecimalPoint.

Set this property's value with setNumDigits() and get this property's value with numDigits().

SegmentStyle segmentStyle

This property holds the style of the LCDNumber.

The style of the QLCDNumber is one of:

  • Outline gives raised segments filled with the background color (this is the default).
  • Filled gives raised segments filled with the foreground color.
  • Flat gives flat segments filled with the foreground color.

Outline and Filled will additionally use QColorGroup::light() and QColorGroup::dark() for shadow effects.

Set this property's value with setSegmentStyle() and get this property's value with segmentStyle().

bool smallDecimalPoint

This property holds the style of the decimal point.

If TRUE the decimal point is drawn between two digit positions. Otherwise it occupies a digit position of its own, i.e. is drawn in a digit position. The default is FALSE.

The inter-digit space is made slightly wider when the decimal point is drawn between the digits.

See also mode.

Set this property's value with setSmallDecimalPoint() and get this property's value with smallDecimalPoint().

double value

This property holds the displayed value.

This property corresponds to the current value displayed by the LCDNumber.

If the displayed value is not a number, the property has a value of 0.

Set this property's value with display() and get this property's value with value().

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


qlcdnumber.h Include File

qlcdnumber.h

This is the verbatim text of the qlcdnumber.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qlcdnumber.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QLCDNumber class
**
** Created : 940518
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLCDNUMBER_H
#define QLCDNUMBER_H

#ifndef QT_H
#include "qframe.h"
#include "qbitarray.h"
#endif // QT_H

#ifndef QT_NO_LCDNUMBER

class QLCDNumberPrivate;

class Q_EXPORT QLCDNumber : public QFrame		// LCD number widget
{
    Q_OBJECT
    Q_ENUMS( Mode SegmentStyle )
    Q_PROPERTY( bool smallDecimalPoint READ smallDecimalPoint WRITE setSmallDecimalPoint )
    Q_PROPERTY( int numDigits READ numDigits WRITE setNumDigits )
    Q_PROPERTY( Mode mode READ mode WRITE setMode )
    Q_PROPERTY( SegmentStyle segmentStyle READ segmentStyle WRITE setSegmentStyle )
    Q_PROPERTY( double value READ value WRITE display )
    Q_PROPERTY( int intValue READ intValue WRITE display )

public:
    QLCDNumber( QWidget* parent=0, const char* name=0 );
    QLCDNumber( uint numDigits, QWidget* parent=0, const char* name=0 );
    ~QLCDNumber();

    enum Mode { Hex, Dec, Oct, Bin, HEX = Hex, DEC = Dec, OCT = Oct,
        BIN = Bin };
    enum SegmentStyle { Outline, Filled, Flat };

    bool    smallDecimalPoint() const;

    int	    numDigits() const;
    virtual void setNumDigits( int nDigits );

    bool    checkOverflow( double num ) const;
    bool    checkOverflow( int	  num ) const;

    Mode mode() const;
    virtual void setMode( Mode );

    SegmentStyle segmentStyle() const;
    virtual void setSegmentStyle( SegmentStyle );

    double  value() const;
    int	    intValue() const;

    QSize sizeHint() const;

public slots:
    void    display( const QString &str );
    void    display( int num );
    void    display( double num );
    virtual void setHexMode();
    virtual void setDecMode();
    virtual void setOctMode();
    virtual void setBinMode();
    virtual void setSmallDecimalPoint( bool );

signals:
    void    overflow();

protected:
    void    drawContents( QPainter * );

private:
    void    init();
    void    internalDisplay( const QString &);
    void    internalSetString( const QString& s );
    void    drawString( const QString& s, QPainter &, QBitArray * = 0,
            bool = TRUE );
    //void    drawString( const QString &, QPainter &, QBitArray * = 0 ) const;
    void    drawDigit( const QPoint &, QPainter &, int, char,
               char = ' ' );
    void    drawSegment( const QPoint &, char, QPainter &, int, bool = FALSE );

    int	    ndigits;
    double  val;
    uint    base	: 2;
    uint    smallPoint	: 1;
    uint    fill	: 1;
    uint    shadow	: 1;
    QString digitStr;
    QBitArray points;
    QLCDNumberPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QLCDNumber( const QLCDNumber & );
    QLCDNumber &operator=( const QLCDNumber & );
#endif
};

inline bool QLCDNumber::smallDecimalPoint() const
{ return (bool)smallPoint; }

inline int QLCDNumber::numDigits() const
{ return ndigits; }

#endif // QT_NO_LCDNUMBER

#endif // QLCDNUMBER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLCDNumber Member List

Complete Member List for QLCDNumber

This is the complete list of member functions for QLCDNumber, including inherited members.

  • QLCDNumber()
  • ~QLCDNumber()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • checkOverflow()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • display()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • intValue()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mode()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numDigits()
  • objectTrees()
  • overflow()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • segmentStyle()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBinMode()
  • setCaption()
  • setCursor()
  • setDecMode()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHexMode()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMode()
  • setMouseTracking()
  • setName()
  • setNumDigits()
  • setOctMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSegmentStyle()
  • setSizeIncrement()
  • setSizePolicy()
  • setSmallDecimalPoint()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • smallDecimalPoint()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • value()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QLibrary Class

QLibrary Class Reference

The QLibrary class provides a wrapper for handling shared libraries. More...

#include <qlibrary.h>

List of all member functions.

Public Members

  • QLibrary ( const QString & filename )
  • virtual ~QLibrary ()
  • void * resolve ( const char * symb )
  • bool load ()
  • virtual bool unload ()
  • bool isLoaded () const
  • bool autoUnload () const
  • void setAutoUnload ( bool enabled )
  • QString library () const

Static Public Members

  • void * resolve ( const QString & filename, const char * symb )

Detailed Description

The QLibrary class provides a wrapper for handling shared libraries.

An instance of a QLibrary object can handle a single shared library and provide access to the functionality in the library in a platform independent way. If the library is a component server, QLibrary provides access to the exported component and can directly query this component for interfaces.

QLibrary ensures that the shared library is loaded and stays in memory whilst it is in use. QLibrary can also unload the library on destruction and release unused resources.

A typical use of QLibrary is to resolve an exported symbol in a shared object, and to e.g. call the function that this symbol represents. This is called "explicit linking" in contrast to "implicit linking", which is done by the link step in the build process when linking an executable against a library.

The following code snippet loads a library, resolves the symbol "mysymbol", and calls the function if everything succeeded. If something went wrong, e.g. the library file does not exist or the symbol is not defined, the function pointer will become a null pointer. Upon destruction of the QLibrary object the library will be unloaded, making all references to memory allocated in the library invalid.

  typedef void (*MyPrototype)();
  MyPrototype myFunction;

  QLibrary myLib( "mylib" );
  myFunction = (MyProtoype) myLib.resolve( "mysymbol" );
  if ( myFunction ) {
      myFunction();
  }

Member Function Documentation

QLibrary::QLibrary ( const QString & filename )

Creates a QLibrary object for the shared library filename. The library will be unloaded in the destructor.

Note that filename does not need to include the (platform specific) file extension, so calling

  QLibrary lib( "mylib" );
is equivalent to calling
  QLibrary lib( "mylib.dll" );
on Windows. Specifying the extension is not recommended, since doing so introduces a platform dependency.

If filename does not include a path, the library loader will look for the file in the platform specific search paths.

See also load(), unload() and setAutoUnload().

QLibrary::~QLibrary () [virtual]

Deletes the QLibrary object.

The library will be unloaded if autoUnload() is TRUE (the default), otherwise it stays in memory until the application is exited.

See also unload() and setAutoUnload().

bool QLibrary::autoUnload () const

Returns TRUE if the library will be automatically unloaded when this wrapper object is destructed; otherwise returns FALSE. The default is TRUE.

See also setAutoUnload().

bool QLibrary::isLoaded () const

Returns TRUE if the library is loaded; otherwise returns FALSE.

See also unload().

QString QLibrary::library () const

Returns the filename of the shared library this QLibrary object handles, including the platform specific file extension.

For example:

  QLibrary lib( "mylib" );
  QString str = lib.library();

will set str to "mylib.dll" on Windows, and "libmylib.so" on Linux.

bool QLibrary::load ()

Loads the library. Since resolve() always calls this function before resolving any symbols it is not necessary to call this function explicitly. In some situations you might want the library loaded in advance, in which case you would call this function.

void * QLibrary::resolve ( const char * symb )

Returns the address of the exported symbol symb. The library is loaded if necessary. The function returns a null pointer if the symbol could not be resolved or the library could not be loaded.

  typedef int (*avgProc)( int, int );

  avgProc avg = (avgProc) library->resolve( "avg" );
  if ( avg )
      return avg( 5, 8 );
  else
      return -1;

void * QLibrary::resolve ( const QString & filename, const char * symb ) [static]

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

Loads the library filename and returns the address of the exported symbol symb. Note that like the constructor, filename does not need to include the (platform specific) file extension. The library remains loaded until the process exits.

The function returns a null pointer if the symbol could not be resolved or the library could not be loaded.

This function is useful only if you want to resolve a single symbol, e.g. a function pointer from a specific library once:

  typedef void (*FunctionType)();
  static FunctionType *ptrFunction = 0;
  static bool triedResolve = FALSE;
  if ( !ptrFunction && !triedResolve )
      ptrFunction = QLibrary::resolve( "foo", "function" );

  if ( ptrFunction )
      ptrFunction();
  else
      ...

If you want to resolve multiple symbols, use a QLibrary object and call the non-static version of resolve().

See also

void QLibrary::setAutoUnload ( bool enabled )

If enabled is TRUE (the default), the wrapper object is set to automatically unload the library upon destruction. If enabled is FALSE, the wrapper object is not unloaded unless you explicitly call unload().

See also autoUnload().

bool QLibrary::unload () [virtual]

Unloads the library and returns TRUE if the library could be unloaded; otherwise returns FALSE.

This function is called by the destructor if autoUnload() is enabled.

See also resolve().

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


qlibrary.h Include File

qlibrary.h

This is the verbatim text of the qlibrary.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QLibrary class
**
** Created : 2000-01-01
**
** Copyright (C) 2000-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLIBRARY_H
#define QLIBRARY_H

#ifndef QT_H
#include <qstring.h>
#endif // QT_H

class QLibraryPrivate;

class Q_EXPORT QLibrary
{
public:
    QLibrary( const QString& filename );
    virtual ~QLibrary();

    void *resolve( const char* );
    static void *resolve( const QString &filename, const char * );

    bool load();
    virtual bool unload();
    bool isLoaded() const;

    bool autoUnload() const;
    void setAutoUnload( bool enable );

    QString library() const;

private:
    QLibraryPrivate *d;

    QString libfile;
    uint aunload : 1;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QLibrary( const QLibrary & );
    QLibrary &operator=( const QLibrary & );
#endif
};

#endif //QLIBRARY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLibrary Member List

Complete Member List for QLibrary

This is the complete list of member functions for QLibrary, including inherited members.

  • QLibrary()
  • ~QLibrary()
  • autoUnload()
  • isLoaded()
  • library()
  • load()
  • resolve()
  • setAutoUnload()
  • unload()


QLineEdit Class

QLineEdit Class Reference

The QLineEdit widget is a one-line text editor. More...

#include <qlineedit.h>

Inherits QFrame.

List of all member functions.

Public Members

  • QLineEdit ( QWidget * parent, const char * name = 0 )
  • QLineEdit ( const QString & contents, QWidget * parent, const char * name = 0 )
  • ~QLineEdit ()
  • QString text () const
  • QString displayText () const
  • int maxLength () const
  • bool frame () const
  • enum EchoMode { Normal, NoEcho, Password }
  • EchoMode echoMode () const
  • bool isReadOnly () const
  • const QValidator * validator () const
  • virtual QSize sizeHint () const
  • virtual QSize minimumSizeHint () const
  • int cursorPosition () const
  • bool validateAndSet ( const QString & newText, int newPos, int newMarkAnchor, int newMarkDrag )
  • int alignment () const
  • void cursorLeft ( bool mark, int steps = 1 ) (obsolete)
  • void cursorRight ( bool mark, int steps = 1 ) (obsolete)
  • void cursorForward ( bool mark, int steps = 1 )
  • void cursorBackward ( bool mark, int steps = 1 )
  • void cursorWordForward ( bool mark )
  • void cursorWordBackward ( bool mark )
  • void backspace ()
  • void del ()
  • void home ( bool mark )
  • void end ( bool mark )
  • void setEdited ( bool )
  • bool edited () const
  • bool hasSelectedText () const
  • QString selectedText () const
  • bool getSelection ( int * start, int * end )
  • bool isUndoAvailable () const
  • bool isRedoAvailable () const
  • bool hasMarkedText () const (obsolete)
  • QString markedText () const (obsolete)
  • void setPasswordChar ( QChar c )
  • QChar passwordChar () const
  • bool dragEnabled () const
  • int characterAt ( int xpos, QChar * chr ) const

Public Slots

  • virtual void setText ( const QString & )
  • virtual void selectAll ()
  • virtual void deselect ()
  • virtual void clearValidator ()
  • virtual void insert ( const QString & newText )
  • virtual void clear ()
  • virtual void undo ()
  • virtual void redo ()
  • virtual void setMaxLength ( int )
  • virtual void setFrame ( bool )
  • virtual void setEchoMode ( EchoMode )
  • virtual void setReadOnly ( bool )
  • virtual void setValidator ( const QValidator * v )
  • virtual void setSelection ( int start, int length )
  • virtual void setCursorPosition ( int )
  • virtual void setAlignment ( int flag )
  • virtual void cut ()
  • virtual void copy () const
  • virtual void paste ()
  • virtual void setDragEnabled ( bool b )

Signals

  • void textChanged ( const QString & )
  • void returnPressed ()
  • void selectionChanged ()

Properties

  • Alignment alignment - the alignment of the line edit
  • int cursorPosition - the current cursor position for this line edit
  • QString displayText - the text that is displayed (read only)
  • bool dragEnabled - whether the lineedit starts a drag if the user presses and moves the mouse on some selected text
  • EchoMode echoMode - the echo mode of the line edit
  • bool edited - the edited flag of the line edit
  • bool frame - whether the line edit draws itself with a frame
  • bool hasMarkedText - whether part of the text has been selected by the user (e.g. by clicking and dragging) (read only) (obsolete)
  • bool hasSelectedText - whether there is any text selected (read only)
  • QString markedText - the text selected by the user (e.g. by clicking and dragging), or QString::null if no text is selected (read only) (obsolete)
  • int maxLength - the maximum permitted length of the text in the editor
  • bool readOnly - whether the line edit is read only
  • bool redoAvailable - whether redo is available (read only)
  • QString selectedText - any text selected by the user or QString::null (read only)
  • QString text - the text in the line
  • bool undoAvailable - whether undo is available (read only)

Protected Members

  • virtual void keyPressEvent ( QKeyEvent * e )
  • void repaintArea ( int from, int to ) (obsolete)
  • virtual QPopupMenu * createPopupMenu ()

Detailed Description

The QLineEdit widget is a one-line text editor.

A line edit allows the user to enter and edit a single line of plain text with a useful collection of editing functions, including undo and redo, cut and paste, and drag and drop.

By changing the echoMode() of a line edit, it can also be used as a "write-only" field, for inputs such as passwords.

The length of the field can be constrained to maxLength(), or the value can be arbitrarily constrained by setting a validator().

A closely related class is QTextEdit which allows multi-line, rich-text editing.

You can change the text with setText() or insert(). The text is retrieved with text(); the displayed text (which may be different, see EchoMode) is retrieved with displayText(). Text can be selected with setSelection() or selectAll(), and the selection can be cut(), copy()ied and paste()d. The text can be aligned with setAlignment().

When the text changes the textChanged() signal is emitted; when the Return or Enter key is pressed the returnPressed() signal is emitted.

By default, QLineEdits have a frame as specified by the Windows and Motif style guides; you can turn it off by calling setFrame(FALSE).

The default key bindings are described below. A right mouse button menu presents some of the editing commands to the user.

  • Left Arrow - moves the cursor one character to the left.
  • Right Arrow - moves the cursor one character to the right.
  • Backspace - deletes the character to the left of the cursor.
  • Home - moves the cursor to the beginning of the line.
  • End - moves the cursor to the end of the line.
  • Delete - deletes the character to the right of the cursor.
  • Shift+Left Arrow - moves and selects text one character to the left.
  • Shift+Right Arrow - moves and selects text one character to the right.
  • Ctrl+A - moves the cursor to the beginning of the line.
  • Ctrl+B - moves the cursor one character to the left.
  • Ctrl+C - copies the selected text to the clipboard. (Windows also supports Ctrl+Insert for this operation.)
  • Ctrl+D - deletes the character to the right of the cursor.
  • Ctrl+E - moves the cursor to the end of the line.
  • Ctrl+F - moves the cursor one character to the right.
  • Ctrl+H - deletes the character to the left of the cursor.
  • Ctrl+K - deletes to the end of the line.
  • Ctrl+V - pastes the clipboard text into line edit. (Windows also supports Shift+Insert for this operation.)
  • Ctrl+X - deletes the selected text and copies it to the clipboard. (Windows also supports Shift+Delete for this operation.)
  • Ctrl+Z - undoes the last operation.
  • Ctrl+Y - redoes the last undone operation.

Any other key sequence, that represents a valid character, will cause the character to be inserted into the line.

See also QTextEdit, QLabel, QComboBox, GUI Design Handbook: Field, Entry and Basic Widgets.

Member Type Documentation

QLineEdit::EchoMode

This enum type describes how a line edit should display its contents. The defined values are:

  • QLineEdit::Normal - display characters as they are entered. This is the default.
  • QLineEdit::NoEcho - do not display anything. This may be appropriate for passwords where even the length of the password should be kept secret.
  • QLineEdit::Password - display asterisks instead of the characters actually entered.

See also echoMode and echoMode.

Member Function Documentation

QLineEdit::QLineEdit ( QWidget * parent, const char * name = 0 )

Constructs a line edit with no text.

The maximum text length is set to 32767 characters.

The parent and name arguments are sent to the QWidget constructor.

See also text and maxLength.

QLineEdit::QLineEdit ( const QString & contents, QWidget * parent, const char * name = 0 )

Constructs a line edit containing the text contents.

The cursor position is set to the end of the line and the maximum text length to 32767 characters.

The parent and name arguments are sent to the QWidget constructor.

See also text and maxLength.

QLineEdit::~QLineEdit ()

Destroys the line edit.

int QLineEdit::alignment () const

Returns the alignment of the line edit. See the "alignment" property for details.

void QLineEdit::backspace ()

Deletes the character to the left of the text cursor and moves the cursor one position to the left. If any text has been selected by the user (e.g. by clicking and dragging), the cursor will be put at the beginning of the selected text and the selected text will be removed.

See also del().

int QLineEdit::characterAt ( int xpos, QChar * chr ) const

Returns the index position of the character which is at xpos (in logical coordinates from the left). If chr is not 0, *<em>chr</em> is populated with the character at this position.

void QLineEdit::clear () [virtual slot]

Clears the contents of the editor. This is equivalent to setText("").

void QLineEdit::clearValidator () [virtual slot]

This slot is equivalent to setValidator( 0 ).

void QLineEdit::copy () const [virtual slot]

Copies the selected text to the clipboard, if there is any, and if echoMode() is Normal.

See also cut() and paste().

QPopupMenu * QLineEdit::createPopupMenu () [virtual protected]

This function is called to create the popup menu which is shown when the user clicks on the lineedit with the right mouse button. If you want to create a custom popup menu, reimplement this function and return the popup menu you create. The popup menu's ownership is transferred to the caller.

void QLineEdit::cursorBackward ( bool mark, int steps = 1 )

Moves the cursor back steps characters. If mark is TRUE each character moved over is added to the selection; if mark is FALSE the selection is cleared.

See also cursorForward().

void QLineEdit::cursorForward ( bool mark, int steps = 1 )

Moves the cursor forward steps characters. If mark is TRUE each character moved over is added to the selection; if mark is FALSE the selection is cleared.

See also cursorBackward().

void QLineEdit::cursorLeft ( bool mark, int steps = 1 )

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

For compatibilty with older applications only. Use cursorBackward() instead.

See also cursorBackward().

int QLineEdit::cursorPosition () const

Returns the current cursor position for this line edit. See the "cursorPosition" property for details.

void QLineEdit::cursorRight ( bool mark, int steps = 1 )

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

Use cursorForward() instead.

See also cursorForward().

void QLineEdit::cursorWordBackward ( bool mark )

Moves the cursor one word backward. If mark is TRUE, the word is also selected.

See also cursorWordForward().

void QLineEdit::cursorWordForward ( bool mark )

Moves the cursor one word forward. If mark is TRUE, the word is also selected.

See also cursorWordBackward().

void QLineEdit::cut () [virtual slot]

Copies the selected text to the clipboard and deletes it, if there is any, and if echoMode() is Normal.

If the current validator disallows deleting the selected text, cut() will copy it but not delete it.

See also copy() and paste().

void QLineEdit::del ()

Deletes the character on the right side of the text cursor. If any text has been selected by the user (e.g. by clicking and dragging), the cursor will be put at the beginning of the selected text and the selected text will be removed.

See also backspace().

void QLineEdit::deselect () [virtual slot]

De-selects all text (i.e. removes highlighting) and leaves the cursor at the current position.

See also setSelection() and selectAll().

QString QLineEdit::displayText () const

Returns the text that is displayed. See the "displayText" property for details.

bool QLineEdit::dragEnabled () const

Returns TRUE if the lineedit starts a drag if the user presses and moves the mouse on some selected text; otherwise returns FALSE. See the "dragEnabled" property for details.

EchoMode QLineEdit::echoMode () const

Returns the echo mode of the line edit. See the "echoMode" property for details.

bool QLineEdit::edited () const

Returns the edited flag of the line edit. See the "edited" property for details.

void QLineEdit::end ( bool mark )

Moves the text cursor to the end of the line. If mark is TRUE, text is selected towards the last position; otherwise, any selected text is unselected if the cursor is moved.

See also home().

bool QLineEdit::frame () const

Returns TRUE if the line edit draws itself with a frame; otherwise returns FALSE. See the "frame" property for details.

bool QLineEdit::getSelection ( int * start, int * end )

This function sets *<em>start</em> to the position in the text where the selection starts and *<em>end</em> to the position where the selection ends. Returns TRUE if start and end are not null and if there is some selected text; otherwise returns FALSE.

See also setSelection().

bool QLineEdit::hasMarkedText () const

Returns TRUE if part of the text has been selected by the user (e.g. by clicking and dragging); otherwise returns FALSE. See the "hasMarkedText" property for details.

bool QLineEdit::hasSelectedText () const

Returns TRUE if there is any text selected; otherwise returns FALSE. See the "hasSelectedText" property for details.

void QLineEdit::home ( bool mark )

Moves the text cursor to the beginning of the line. If mark is TRUE, text is selected towards the first position; otherwise, any selected text is unselected if the cursor is moved.

See also end().

void QLineEdit::insert ( const QString & newText ) [virtual slot]

Removes any selected text, inserts newText, and validates the result. If it is valid, it sets it as the new contents of the line edit.

bool QLineEdit::isReadOnly () const

Returns TRUE if the line edit is read only; otherwise returns FALSE. See the "readOnly" property for details.

bool QLineEdit::isRedoAvailable () const

Returns TRUE if redo is available; otherwise returns FALSE. See the "redoAvailable" property for details.

bool QLineEdit::isUndoAvailable () const

Returns TRUE if undo is available; otherwise returns FALSE. See the "undoAvailable" property for details.

void QLineEdit::keyPressEvent ( QKeyEvent * e ) [virtual protected]

Converts key press event e into a line edit action.

If Return or Enter is pressed and the current text is valid (or can be made valid by the validator), the signal returnPressed is emitted.

The default key bindings are listed in the detailed description.

Reimplemented from QWidget.

QString QLineEdit::markedText () const

Returns the text selected by the user (e.g. by clicking and dragging), or QString::null if no text is selected. See the "markedText" property for details.

int QLineEdit::maxLength () const

Returns the maximum permitted length of the text in the editor. See the "maxLength" property for details.

QSize QLineEdit::minimumSizeHint () const [virtual]

Returns a minimum size for the line edit.

The width returned is enough for at least one character.

Reimplemented from QWidget.

QChar QLineEdit::passwordChar () const

Returns the password character.

See also setPasswordChar().

void QLineEdit::paste () [virtual slot]

Inserts the clipboard's text at the cursor position, deleting any selected text.

If the end result is not acceptable for the current validator, nothing happens.

See also copy() and cut().

void QLineEdit::redo () [virtual slot]

Redoes the last operation

void QLineEdit::repaintArea ( int from, int to ) [protected]

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

Repaints all characters from from to to. If cursorPos is between from and to, ensures that cursorPos is visible.

void QLineEdit::returnPressed () [signal]

This signal is emitted when the Return or Enter key is pressed.

Example: popup/popup.cpp.

void QLineEdit::selectAll () [virtual slot]

Selects all the text (i.e. highlights it) and moves the cursor to the end. This is useful when a default value has been inserted because if the user types before clicking on the widget, the selected text will be erased.

See also setSelection() and deselect().

QString QLineEdit::selectedText () const

Returns any text selected by the user or QString::null. See the "selectedText" property for details.

void QLineEdit::selectionChanged () [signal]

This signal is emitted whenever the selection changes.

See also hasSelectedText and selectedText.

void QLineEdit::setAlignment ( int flag ) [virtual slot]

Sets the alignment of the line edit to flag. See the "alignment" property for details.

void QLineEdit::setCursorPosition ( int ) [virtual slot]

Sets the current cursor position for this line edit. See the "cursorPosition" property for details.

void QLineEdit::setDragEnabled ( bool b ) [virtual slot]

Sets whether the lineedit starts a drag if the user presses and moves the mouse on some selected text to b. See the "dragEnabled" property for details.

void QLineEdit::setEchoMode ( EchoMode ) [virtual slot]

Sets the echo mode of the line edit. See the "echoMode" property for details.

void QLineEdit::setEdited ( bool )

Sets the edited flag of the line edit. See the "edited" property for details.

void QLineEdit::setFrame ( bool ) [virtual slot]

Sets whether the line edit draws itself with a frame. See the "frame" property for details.

void QLineEdit::setMaxLength ( int ) [virtual slot]

Sets the maximum permitted length of the text in the editor. See the "maxLength" property for details.

void QLineEdit::setPasswordChar ( QChar c )

Sets the password character to c.

See also passwordChar().

void QLineEdit::setReadOnly ( bool ) [virtual slot]

Sets whether the line edit is read only. See the "readOnly" property for details.

void QLineEdit::setSelection ( int start, int length ) [virtual slot]

Sets the selected area of this line edit to start at position start and be length characters long.

See also deselect(), selectAll() and getSelection().

void QLineEdit::setText ( const QString & ) [virtual slot]

Sets the text in the line. See the "text" property for details.

void QLineEdit::setValidator ( const QValidator * v ) [virtual slot]

Sets this line edit to accept input only as accepted by the validator, v, allowing arbitrary constraints on the text which may be entered.

If v == 0, setValidator() removes the current input validator. The initial setting is to have no input validator (i.e. any input is accepted up to maxLength()).

See also validator() and QValidator.

Examples: lineedits/lineedits.cpp and wizard/wizard.cpp.

QSize QLineEdit::sizeHint () const [virtual]

Returns a recommended size for the widget.

The width returned, in pixels, is usually enough for about 15 to 20 characters.

Example: addressbook/centralwidget.cpp.

QString QLineEdit::text () const

Returns the text in the line. See the "text" property for details.

void QLineEdit::textChanged ( const QString & ) [signal]

This signal is emitted whenever the text changes. The argument is the new text.

Examples: wizard/wizard.cpp and xform/xform.cpp.

void QLineEdit::undo () [virtual slot]

Undoes the last operation

bool QLineEdit::validateAndSet ( const QString & newText, int newPos, int newMarkAnchor, int newMarkDrag )

Validates and perhaps sets this line edit to contain newText with the cursor at position newPos, with selected text from newMarkAnchor to newMarkDrag. Returns TRUE if it changes the line edit; otherwise returns FALSE.

Linebreaks in newText are converted to spaces, and the text is truncated to maxLength() before its validity is tested.

Repaints and emits textChanged() if appropriate.

const QValidator * QLineEdit::validator () const

Returns a pointer to the current input validator, or 0 if no validator has been set.

See also setValidator().

Example: wizard/wizard.cpp.

Property Documentation

Alignment alignment

This property holds the alignment of the line edit.

Possible Values are Qt::AlignAuto, Qt::AlignLeft, Qt::AlignRight and Qt::AlignHCenter.

Attempting to set the alignment to an illegal flag combination does nothing.

See also Qt::AlignmentFlags.

Set this property's value with setAlignment() and get this property's value with alignment().

int cursorPosition

This property holds the current cursor position for this line edit.

Setting the cursor position causes a repaint when appropriate.

Set this property's value with setCursorPosition() and get this property's value with cursorPosition().

QString displayText

This property holds the text that is displayed.

If EchoMode is Normal this returns the same as text(); if EchoMode is Password it returns a string of asterisks the text().length() characters long, e.g. "******"; if EchoMode is NoEcho returns an empty string, "".

See also echoMode, text and EchoMode.

Get this property's value with displayText().

bool dragEnabled

This property holds whether the lineedit starts a drag if the user presses and moves the mouse on some selected text.

Set this property's value with setDragEnabled() and get this property's value with dragEnabled().

EchoMode echoMode

This property holds the echo mode of the line edit.

The initial setting is Normal, but QLineEdit also supports NoEcho and Password modes.

The widget's display and the ability to copy or drag the text is affected by this setting.

See also EchoMode and displayText.

Set this property's value with setEchoMode() and get this property's value with echoMode().

bool edited

This property holds the edited flag of the line edit.

The edited flag is never read by QLineEdit; it has a default value of FALSE and is changed to TRUE whenever the user changes the line edit's contents.

This is useful for things that need to provide a default value but cannot find the default at once. Just start the line edit without the best default; when the default is known, check the edited() return value and set the line edit's contents if the user has not started editing the line edit.

Calling setText() resets the edited flag to FALSE.

Set this property's value with setEdited() and get this property's value with edited().

bool frame

This property holds whether the line edit draws itself with a frame.

If enabled (the default) the line edit draws itself inside a two-pixel frame, otherwise the line edit draws itself without any frame.

Set this property's value with setFrame() and get this property's value with frame().

bool hasMarkedText

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

This property holds whether part of the text has been selected by the user (e.g. by clicking and dragging).

Get this property's value with hasMarkedText().

See also selectedText.

bool hasSelectedText

This property holds whether there is any text selected.

hasSelectedText() returns TRUE if some or all of the text has been selected by the user (e.g. by clicking and dragging); otherwise returns FALSE.

See also selectedText.

Get this property's value with hasSelectedText().

QString markedText

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

This property holds the text selected by the user (e.g. by clicking and dragging), or QString::null if no text is selected.

Get this property's value with markedText().

See also hasSelectedText.

int maxLength

This property holds the maximum permitted length of the text in the editor.

If the text is too long, it is truncated at the limit.

If truncation occurs any selected text will be unselected, the cursor position is set to 0 and the first part of the string is shown.

Set this property's value with setMaxLength() and get this property's value with maxLength().

bool readOnly

This property holds whether the line edit is read only.

In read-only mode, the user can still copy the text to the clipboard or drag-and-drop the text, but cannot edit it.

QLineEdit does not show a cursor in read-only mode.

See also enabled.

Set this property's value with setReadOnly() and get this property's value with isReadOnly().

bool redoAvailable

This property holds whether redo is available.

Get this property's value with isRedoAvailable().

QString selectedText

This property holds any text selected by the user or QString::null.

Get this property's value with selectedText().

See also hasSelectedText.

QString text

This property holds the text in the line.

Setting this property clears the selection, moves the cursor to the end of the line and resets the edited property to FALSE.

The text is truncated to maxLength() length.

Set this property's value with setText() and get this property's value with text().

bool undoAvailable

This property holds whether undo is available.

Get this property's value with isUndoAvailable().

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


qlineedit.h Include File

qlineedit.h

This is the verbatim text of the qlineedit.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qlineedit.h   3.0.5   edited May 28 10:45 $
**
** Definition of QLineEdit widget class
**
** Created : 941011
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLINEEDIT_H
#define QLINEEDIT_H

struct QLineEditPrivate;

class QValidator;
class QPopupMenu;

#ifndef QT_H
#include "qframe.h"
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_LINEEDIT

class Q_EXPORT QLineEdit : public QFrame
{
    Q_OBJECT
    Q_ENUMS( EchoMode )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( int maxLength READ maxLength WRITE setMaxLength )
    Q_PROPERTY( bool frame READ frame WRITE setFrame )
    Q_PROPERTY( EchoMode echoMode READ echoMode WRITE setEchoMode )
    Q_PROPERTY( QString displayText READ displayText )
    Q_PROPERTY( int cursorPosition READ cursorPosition WRITE setCursorPosition )
    Q_PROPERTY( Alignment alignment READ alignment WRITE setAlignment )
    Q_PROPERTY( bool edited READ edited WRITE setEdited )
    Q_PROPERTY( bool hasMarkedText READ hasMarkedText DESIGNABLE false )
    Q_PROPERTY( bool hasSelectedText READ hasSelectedText )
    Q_PROPERTY( QString markedText READ markedText DESIGNABLE false )
    Q_PROPERTY( QString selectedText READ selectedText )
    Q_PROPERTY( bool dragEnabled READ dragEnabled WRITE setDragEnabled )
    Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly )
    Q_PROPERTY( bool undoAvailable READ isUndoAvailable )
    Q_PROPERTY( bool redoAvailable READ isRedoAvailable )

public:
    QLineEdit( QWidget* parent, const char* name=0 );
    QLineEdit( const QString &, QWidget* parent, const char* name=0 );
    ~QLineEdit();

    QString text() const;

    QString displayText() const;

    int maxLength() const;

    bool frame() const;

    enum EchoMode { Normal, NoEcho, Password };
    EchoMode echoMode() const;

    bool isReadOnly() const;

    const QValidator * validator() const;

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    int cursorPosition() const;
    bool validateAndSet( const QString &, int, int, int );

    int alignment() const;

#ifndef QT_NO_COMPAT
    void cursorLeft( bool mark, int steps = 1 ) { cursorForward( mark, -steps ); }
    void cursorRight( bool mark, int steps = 1 ) { cursorForward( mark, steps ); }
#endif
    void cursorForward( bool mark, int steps = 1 );
    void cursorBackward( bool mark, int steps = 1 );
    void cursorWordForward( bool mark );
    void cursorWordBackward( bool mark );
    void backspace();
    void del();
    void home( bool mark );
    void end( bool mark );

    void setEdited( bool );
    bool edited() const;

    bool hasSelectedText() const;
    QString selectedText() const;
    bool getSelection( int *start, int *end );
    bool isUndoAvailable() const;
    bool isRedoAvailable() const;

#ifndef QT_NO_COMPAT
    bool hasMarkedText() const { return hasSelectedText(); }
    QString markedText() const { return selectedText(); }
#endif

#if defined(Q_INCOMPATIBLE_3_0_ADDONS)
    void 	setPasswordChar( QChar c );
    QChar 	passwordChar() const;
#endif

    bool dragEnabled() const;
    int characterAt( int xpos, QChar *chr ) const;

public slots:
    virtual void setText( const QString &);
    virtual void selectAll();
    virtual void deselect();
    virtual void clearValidator();
    virtual void insert( const QString &);
    virtual void clear();
    virtual void undo();
    virtual void redo();
    virtual void setMaxLength( int );
    virtual void setFrame( bool );
    virtual void setEchoMode( EchoMode );
    virtual void setReadOnly( bool );
    virtual void setValidator( const QValidator * );
    virtual void setFont( const QFont & );
    virtual void setPalette( const QPalette & );
    virtual void setSelection( int, int );
    virtual void setCursorPosition( int );
    virtual void setAlignment( int flag );
#ifndef QT_NO_CLIPBOARD
    virtual void cut();
    virtual void copy() const;
    virtual void paste();
#endif
    virtual void setDragEnabled( bool b );

signals:
    void textChanged( const QString &);
    void returnPressed();
    void selectionChanged();

protected:
    bool event( QEvent * );
    void mousePressEvent( QMouseEvent * );
    void mouseMoveEvent( QMouseEvent * );
    void mouseReleaseEvent( QMouseEvent * );
    void mouseDoubleClickEvent( QMouseEvent * );
    void keyPressEvent( QKeyEvent * );
    void imStartEvent( QIMEvent * );
    void imComposeEvent( QIMEvent * );
    void imEndEvent( QIMEvent * );
    void focusInEvent( QFocusEvent * );
    void focusOutEvent( QFocusEvent * );
    void drawContents( QPainter *painter );
    void resizeEvent( QResizeEvent * );
#ifndef QT_NO_DRAGANDDROP
    void dragEnterEvent( QDragEnterEvent * );
    void dragMoveEvent( QDragMoveEvent *e );
    void dragLeaveEvent( QDragLeaveEvent *e );
    void dropEvent( QDropEvent * );
#endif
    void contextMenuEvent( QContextMenuEvent * );

#ifndef QT_NO_COMPAT
    void repaintArea( int, int ) { update(); }
#endif

    virtual QPopupMenu *createPopupMenu();
    void windowActivationChange( bool );

private slots:
    void clipboardChanged();
    void blinkSlot();
#ifndef QT_NO_DRAGANDDROP
    void doDrag();
#endif
    void dragSlot();
    void popupActivated( int r );

private:
    void init();
    void blinkOn();
    void updateOffset();
    void updateSelection();
    void removeSelectedText();
    void delOrBackspace( bool backspace );

    QLineEditPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QLineEdit( const QLineEdit & );
    QLineEdit &operator=( const QLineEdit & );
#endif
};

#endif // QT_NO_LINEEDIT

#endif // QLINEEDIT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLineEdit Member List

Complete Member List for QLineEdit

This is the complete list of member functions for QLineEdit, including inherited members.

  • QLineEdit()
  • ~QLineEdit()
  • acceptDrops()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • backspace()
  • baseSize()
  • blockSignals()
  • caption()
  • characterAt()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearValidator()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • copy()
  • create()
  • createPopupMenu()
  • cursor()
  • cursorBackward()
  • cursorForward()
  • cursorLeft()
  • cursorPosition()
  • cursorRight()
  • cursorWordBackward()
  • cursorWordForward()
  • customEvent()
  • customWhatsThis()
  • cut()
  • del()
  • deleteLater()
  • deselect()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • displayText()
  • dragEnabled()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • echoMode()
  • edited()
  • enabledChange()
  • end()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frame()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getSelection()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMarkedText()
  • hasMouse()
  • hasMouseTracking()
  • hasSelectedText()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • home()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isReadOnly()
  • isRedoAvailable()
  • isTopLevel()
  • isUndoAvailable()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • markedText()
  • maxLength()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • passwordChar()
  • paste()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintArea()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • returnPressed()
  • scroll()
  • selectAll()
  • selectedText()
  • selectionChanged()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setCursorPosition()
  • setDisabled()
  • setDragEnabled()
  • setEchoMode()
  • setEdited()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrame()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaxLength()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPasswordChar()
  • setProperty()
  • setReadOnly()
  • setSelection()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setText()
  • setUpdatesEnabled()
  • setValidator()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • undo()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • validateAndSet()
  • validator()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QListBox Class

QListBox Class Reference

The QListBox widget provides a list of selectable, read-only items. More...

#include <qlistbox.h>

Inherits QScrollView.

List of all member functions.

Public Members

  • QListBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QListBox ()
  • uint count () const
  • void insertStringList ( const QStringList & list, int index = -1 )
  • void insertStrList ( const QStrList * list, int index = -1 )
  • void insertStrList ( const QStrList & list, int index = -1 )
  • void insertStrList ( const char ** strings, int numStrings = -1, int index = -1 )
  • void insertItem ( const QListBoxItem * lbi, int index = -1 )
  • void insertItem ( const QListBoxItem * lbi, const QListBoxItem * after )
  • void insertItem ( const QString & text, int index = -1 )
  • void insertItem ( const QPixmap & pixmap, int index = -1 )
  • void insertItem ( const QPixmap & pixmap, const QString & text, int index = -1 )
  • void removeItem ( int index )
  • QString text ( int index ) const
  • const QPixmap * pixmap ( int index ) const
  • void changeItem ( const QListBoxItem * lbi, int index )
  • void changeItem ( const QString & text, int index )
  • void changeItem ( const QPixmap & pixmap, int index )
  • void changeItem ( const QPixmap & pixmap, const QString & text, int index )
  • void takeItem ( const QListBoxItem * item )
  • int numItemsVisible () const
  • int currentItem () const
  • QString currentText () const
  • virtual void setCurrentItem ( int index )
  • virtual void setCurrentItem ( QListBoxItem * i )
  • void centerCurrentItem ()
  • int topItem () const
  • virtual void setTopItem ( int index )
  • virtual void setBottomItem ( int index )
  • long maxItemWidth () const
  • enum SelectionMode { Single, Multi, Extended, NoSelection }
  • virtual void setSelectionMode ( SelectionMode )
  • SelectionMode selectionMode () const
  • void setMultiSelection ( bool multi ) (obsolete)
  • bool isMultiSelection () const (obsolete)
  • virtual void setSelected ( QListBoxItem * item, bool select )
  • void setSelected ( int index, bool select )
  • bool isSelected ( int i ) const
  • bool isSelected ( const QListBoxItem * i ) const
  • QListBoxItem * item ( int index ) const
  • int index ( const QListBoxItem * lbi ) const
  • QListBoxItem * findItem ( const QString & text, ComparisonFlags compare = BeginsWith ) const
  • void triggerUpdate ( bool doLayout )
  • bool itemVisible ( int index )
  • bool itemVisible ( const QListBoxItem * item )
  • enum LayoutMode { FixedNumber, FitToWidth, FitToHeight = FitToWidth, Variable }
  • virtual void setColumnMode ( LayoutMode )
  • virtual void setColumnMode ( int columns )
  • virtual void setRowMode ( LayoutMode )
  • virtual void setRowMode ( int rows )
  • LayoutMode columnMode () const
  • LayoutMode rowMode () const
  • int numColumns () const
  • int numRows () const
  • bool variableWidth () const
  • virtual void setVariableWidth ( bool )
  • bool variableHeight () const
  • virtual void setVariableHeight ( bool )
  • bool autoScrollBar () const
  • void setAutoScrollBar ( bool enable )
  • bool scrollBar () const
  • void setScrollBar ( bool enable )
  • bool autoBottomScrollBar () const
  • void setAutoBottomScrollBar ( bool enable )
  • bool bottomScrollBar () const
  • void setBottomScrollBar ( bool enable )
  • int inSort ( const QListBoxItem * lbi ) (obsolete)
  • int inSort ( const QString & text ) (obsolete)
  • int cellHeight ( int i ) const (obsolete)
  • int cellHeight () const (obsolete)
  • int cellWidth () const (obsolete)
  • int numCols () const (obsolete)
  • int itemHeight ( int index = 0 ) const
  • QListBoxItem * itemAt ( const QPoint & p ) const
  • QRect itemRect ( QListBoxItem * item ) const
  • QListBoxItem * firstItem () const
  • void sort ( bool ascending = TRUE )

Public Slots

  • void clear ()
  • virtual void ensureCurrentVisible ()
  • virtual void clearSelection ()
  • virtual void selectAll ( bool select )
  • virtual void invertSelection ()

Signals

  • void highlighted ( int index )
  • void selected ( int index )
  • void highlighted ( const QString & )
  • void selected ( const QString & )
  • void highlighted ( QListBoxItem * )
  • void selected ( QListBoxItem * )
  • void selectionChanged ()
  • void selectionChanged ( QListBoxItem * item )
  • void currentChanged ( QListBoxItem * item )
  • void clicked ( QListBoxItem * item )
  • void clicked ( QListBoxItem * item, const QPoint & pnt )
  • void pressed ( QListBoxItem * item )
  • void pressed ( QListBoxItem * item, const QPoint & pnt )
  • void doubleClicked ( QListBoxItem * item )
  • void returnPressed ( QListBoxItem * )
  • void rightButtonClicked ( QListBoxItem *, const QPoint & )
  • void rightButtonPressed ( QListBoxItem *, const QPoint & )
  • void mouseButtonPressed ( int button, QListBoxItem * item, const QPoint & pos )
  • void mouseButtonClicked ( int button, QListBoxItem * item, const QPoint & pos )
  • void contextMenuRequested ( QListBoxItem * item, const QPoint & pos )
  • void onItem ( QListBoxItem * i )
  • void onViewport ()

Properties

  • LayoutMode columnMode - the column layout mode for this list box
  • uint count - the number of items in the list box (read only)
  • int currentItem - the current highlighted item
  • QString currentText - the text of the current item (read only)
  • bool multiSelection - whether or not the list box is in Multi selection mode (obsolete)
  • int numColumns - the number of columns in the list box (read only)
  • int numItemsVisible - the number of visible items (read only)
  • int numRows - the number of rows in the list box (read only)
  • LayoutMode rowMode - the row layout mode for this list box
  • SelectionMode selectionMode - the selection mode of the list box
  • int topItem - the index of an item at the top of the screen
  • bool variableHeight - whether this list box has variable-height rows
  • bool variableWidth - whether this list box has variable-width columns

Protected Members

  • void updateItem ( int index )
  • void updateItem ( QListBoxItem * i )
  • int totalWidth () const (obsolete)
  • int totalHeight () const (obsolete)
  • virtual void paintCell ( QPainter * p, int row, int col )
  • void toggleCurrentItem ()
  • bool isRubberSelecting () const
  • void doLayout () const
  • bool itemYPos ( int index, int * yPos ) const (obsolete)
  • int findItem ( int yPos ) const (obsolete)

Detailed Description

The QListBox widget provides a list of selectable, read-only items.

This is typically a single-column list in which zero or one item is selected, but it can also be used in many other ways.

QListBox will add scroll bars as necessary, but it isn't intended for really big lists. If you want more than a few thousand items, it's probably better to use a different widget mainly because the scroll bars won't provide very good navigation, but also because QListBox may become slow with huge lists.

There are a variety of selection modes described in the QListBox::SelectionMode documentation. The default is Single selection mode, but you can change it using setSelectionMode(). (setMultiSelection() is still provided for compatibility with Qt 1.x. We recomment using setSelectionMode() in all code.)

Because QListBox offers multiple selection it must display keyboard focus and selection state separately. Therefore there are functions both to set the selection state of an item, i.e. setSelected(), and to select which item displays keyboard focus, i.e. setCurrentItem().

The list box normally arranges its items in a single column and adds a vertical scroll bar if required. It is possible to have a different fixed number of columns (setColumnMode()), or as many columns as will fit in the list box's assigned screen space (setColumnMode( FitToWidth )), or to have a fixed number of rows (setRowMode()) or as many rows as will fit in the list box's assigned screen space (setRowMode( FitToHeight )). In all these cases QListBox will add scroll bars, as appropriate, in at least one direction.

If multiple rows are used, each row can be as high as necessary (the normal setting), or you can request that all items will have the same height by calling setVariableHeight( FALSE ). The same applies to a column's width, see setVariableWidth().

The items discussed are QListBoxItem objects. QListBox provides methods to insert new items as strings, as pixmaps, and as QListBoxItem * (insertItem() with various arguments), and to replace an existing item with a new string, pixmap or QListBoxItem (changeItem() with various arguments). You can also remove items singly with removeItem() or clear() the entire list box. Note that if you create a QListBoxItem yourself and insert it, it becomes the property of QListBox and you must not delete it. (QListBox will delete it when appropriate.)

You can also create a QListBoxItem, such as QListBoxText or QListBoxPixmap, with the list box as first parameter. The item will then append itself. When you delete an item it is automatically removed from the list box.

The list of items can be arbitrarily large; QListBox will add scroll bars if necessary. QListBox can display a single-column (the common case) or multiple-columns, and offers both single and multiple selection. (QListBox does not support multiple-column items, or tree hierarchies; use QListView if you require such functionality.)

The list box items can be accessed both as QListBoxItem objects (recommended) and using integer indexes (the original QListBox implementation used an array of strings internally, and the API still supports this mode of operation). Everything can be done using the new objects; most things can be done using the indexes, too, but unfortunately not everything.

Each item in a QListBox contains a QListBoxItem. One of the items can be the current item. The highlighted() signal is emitted when a new item gets highlighted, e.g. because the user clicks on it or QListBox::setCurrentItem() is called. The selected() signal is emitted when the user double-clicks on an item or presses Enter when an item is highlighted.

If the user does not select anything, no signals are emitted and currentItem() returns -1.

A list box has WheelFocus as a default focusPolicy(), i.e. it can get keyboard focus by tabbing, clicking and through the use of the mouse wheel.

New items can be inserted using insertItem(), insertStrList() or insertStringList(). inSort() is obsolete because this method is quite inefficient. It's preferable to insert the items normally and call sort() afterwards, or to insert a sorted QStringList().

By default, vertical and horizontal scroll bars are added and removed as necessary. setHScrollBarMode() and setVScrollBarMode() can be used to change this policy.

If you need to insert types other than strings and pixmaps, you must define new classes which inherit QListBoxItem.

Warning: The list box assumes ownership of all list box items and will delete them when it does not need them any more.

See also QListView, QComboBox, QButtonGroup, GUI Design Handbook: List Box (two sections) and Advanced Widgets.

Member Type Documentation

QListBox::LayoutMode

This enum type is used to specify how QListBox lays out its rows and columns.

The possible values for each row or column mode are:

  • QListBox::FixedNumber - There is a fixed number of rows (or columns).
  • QListBox::FitToWidth - There are as many columns as will fit on-screen.
  • QListBox::FitToHeight - There are as many rows as will fit on-screen.
  • QListBox::Variable - There are as many rows as are required by the column mode. (Or as many columns as required by the row mode.)

Example: When you call setRowMode( FitToHeight ), columnMode() automatically becomes Variable to accommodate the row mode you've set.

QListBox::SelectionMode

This enumerated type is used by QListBox to indicate how it reacts to selection by the user. It has four values:

  • QListBox::Single - When the user selects an item, any already-selected item becomes unselected and the user cannot unselect the selected item. This means that the user can never clear the selection, even though the selection may be cleared by the application programmer using QListBox::clearSelection().
  • QListBox::Multi - When the user selects an item the selection status of that item is toggled and the other items are left alone.
  • QListBox::Extended - When the user selects an item the selection is cleared and the new item selected. However, if the user presses the Ctrl key when clicking on an item, the clicked item gets toggled and all other items are left untouched. And if the user presses the Shift key while clicking on an item, all items between the current item and the clicked item get selected or unselected, depending on the state of the clicked item. Also, multiple items can be selected by dragging the mouse while the left mouse button is kept pressed.
  • QListBox::NoSelection - Items cannot be selected.

In other words, Single is a real single-selection list box, Multi is a real multi-selection list box, Extended is a list box in which users can select multiple items but usually want to select either just one or a range of contiguous items, and NoSelection is for a list box where the user can look but not touch.

Member Function Documentation

QListBox::QListBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a new empty list box, with parent as a parent and name as object name.

Performance is boosted by modifying the widget flags f so that only part of the QListBoxItem children is redrawn. This may be unsuitable for custom QListBoxItem classes, in which case WStaticContents and WRepaintNoErase should be cleared immediately after construction.

See also QWidget::clearWFlags() and Qt::WidgetFlags.

QListBox::~QListBox ()

Destroys the list box. Deletes all list box items.

bool QListBox::autoBottomScrollBar () const

Returns TRUE if hScrollBarMode() is Auto; otherwise returns FALSE.

bool QListBox::autoScrollBar () const

Returns TRUE if vScrollBarMode() is Auto; otherwise returns FALSE.

bool QListBox::bottomScrollBar () const

Returns FALSE if vScrollBarMode() is AlwaysOff; otherwise returns TRUE.

int QListBox::cellHeight ( int i ) const

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

Returns the item height of item i.

See also itemHeight().

int QListBox::cellHeight () const

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

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

Returns the item height of the first item, item 0.

See also itemHeight().

int QListBox::cellWidth () const

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

Returns the maximum item width.

See also maxItemWidth().

void QListBox::centerCurrentItem ()

If there is a current item, the list box is scrolled so that this item is displayed centered.

See also QListBox::ensureCurrentVisible().

void QListBox::changeItem ( const QListBoxItem * lbi, int index )

Replaces the item at position index with lbi. If index is negative or too large, changeItem() does nothing.

The item that has been changed will become selected.

See also insertItem() and removeItem().

void QListBox::changeItem ( const QString & text, int index )

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

Replaces the item at position index with a new list box text item with text text.

The operation is ignored if index is out of range.

See also insertItem() and removeItem().

void QListBox::changeItem ( const QPixmap & pixmap, int index )

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

Replaces the item at position index with a new list box pixmap item with pixmap pixmap.

The operation is ignored if index is out of range.

See also insertItem() and removeItem().

void QListBox::changeItem ( const QPixmap & pixmap, const QString & text, int index )

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

Replaces the item at position index with a new list box pixmap item with pixmap pixmap and text text.

The operation is ignored if index is out of range.

See also insertItem() and removeItem().

void QListBox::clear () [slot]

Deletes all the items in the list.

See also removeItem().

void QListBox::clearSelection () [virtual slot]

Deselects all items, if possible.

Note that a Single selection list box will automatically select an item if it has keyboard focus.

Example: listbox/listbox.cpp.

void QListBox::clicked ( QListBoxItem * item ) [signal]

This signal is emitted when the user clicks any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

void QListBox::clicked ( QListBoxItem * item, const QPoint & pnt ) [signal]

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

This signal is emitted when the user clicks any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pnt is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pnt is the position at release time.)

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

LayoutMode QListBox::columnMode () const

Returns the column layout mode for this list box. See the "columnMode" property for details.

void QListBox::contextMenuRequested ( QListBoxItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user invokes a context menu with the right mouse button or with special system keys, with item being the item under the mouse cursor or the current item, respectively.

pos is the position for the context menu in the global coordinate system.

uint QListBox::count () const

Returns the number of items in the list box. See the "count" property for details.

void QListBox::currentChanged ( QListBoxItem * item ) [signal]

This signal is emitted when the user highlights a new current item. item is the new current list box item.

See also currentItem and currentItem.

int QListBox::currentItem () const

Returns the current highlighted item. See the "currentItem" property for details.

QString QListBox::currentText () const

Returns the text of the current item. See the "currentText" property for details.

void QListBox::doLayout () const [protected]

This function does the hard layout work. You should never need to call it.

void QListBox::doubleClicked ( QListBoxItem * item ) [signal]

This signal is emitted whenever an item is double-clicked. It's emitted on the second button press, not the second button release. item is the item item on which the user did the double-click. item may be 0.

void QListBox::ensureCurrentVisible () [virtual slot]

Ensures that the current item is visible.

QListBoxItem * QListBox::findItem ( const QString & text, ComparisonFlags compare = BeginsWith ) const

Finds the first list box item that has the text text and returns it, or returns 0 of no such item could be found. If ComparisonFlags are specified in compare then these flags are used, otherwise the default is a case-insensitive, begins with search.

See also Qt::StringComparisonMode.

int QListBox::findItem ( int yPos ) const [protected]

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

Returns the index of the item a point (0, yPos).

See also index() and itemAt().

QListBoxItem * QListBox::firstItem () const

Returns the first item in this list box. If the list box is empty this will be 0.

void QListBox::highlighted ( int index ) [signal]

This signal is emitted when the user highlights a new current item. index is the index of the highlighted item.

See also selected(), currentItem and selectionChanged().

void QListBox::highlighted ( const QString & ) [signal]

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

This signal is emitted when the user highlights a new current item and the new item is a string. The argument is the text of the new current item.

See also selected(), currentItem and selectionChanged().

void QListBox::highlighted ( QListBoxItem * ) [signal]

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

This signal is emitted when the user highlights a new current item. The argument is a pointer to the new current item.

See also selected(), currentItem and selectionChanged().

int QListBox::inSort ( const QListBoxItem * lbi )

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

Using this method is quite inefficient. We suggest to use insertItem() for inserting and sort() afterwards.

Inserts lbi at its sorted position in the list box and returns the position.

All items must be inserted with inSort() to maintain the sorting order. inSort() treats any pixmap (or user-defined type) as lexicographically less than any string.

See also insertItem() and sort().

int QListBox::inSort ( const QString & text )

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

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

Using this method is quite inefficient. We suggest to use insertItem() for inserting and sort() afterwards.

Inserts a new item of text at its sorted position in the list box and returns the position.

All items must be inserted with inSort() to maintain the sorting order. inSort() treats any pixmap (or user-defined type) as lexicographically less than any string.

See also insertItem() and sort().

int QListBox::index ( const QListBoxItem * lbi ) const

Returns the index of lbi, or -1 if the item is not in this list box or lbi is a null pointer.

See also item().

void QListBox::insertItem ( const QListBoxItem * lbi, int index = -1 )

Inserts the item lbi into the list at position index.

If index is negative or larger than the number of items in the list box, lbi is inserted at the end of the list.

See also insertStrList().

Examples: i18n/mywidget.cpp, listbox/listbox.cpp, listboxcombo/listboxcombo.cpp and tabdialog/tabdialog.cpp.

void QListBox::insertItem ( const QListBoxItem * lbi, const QListBoxItem * after )

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

Inserts the item lbi into the list after the item after.

If after is 0, lbi is inserted at the beginning.

See also insertStrList().

void QListBox::insertItem ( const QString & text, int index = -1 )

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

Inserts a new list box text item with the text text into the list at position index.

If index is negative, text is inserted at the end of the list.

See also insertStrList().

void QListBox::insertItem ( const QPixmap & pixmap, int index = -1 )

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

Inserts a new list box pixmap item with the pixmap pixmap into the list at position index.

If index is negative, pixmap is inserted at the end of the list.

See also insertStrList().

void QListBox::insertItem ( const QPixmap & pixmap, const QString & text, int index = -1 )

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

Inserts a new list box pixmap item with the pixmap pixmap and the text text into the list at position index.

If index is negative, pixmap is inserted at the end of the list.

See also insertStrList().

void QListBox::insertStrList ( const QStrList * list, int index = -1 )

Inserts the string list list into the list at position index.

If index is negative, list is inserted at the end of the list. If index is too large, the operation is ignored.

Warning: This function uses const char * rather than QString, so we recommend against using it. It is provided so that legacy code will continue to work, and so that programs that certainly will not need to handle code outside a single 8-bit locale can use it. See insertStringList() which uses real QStrings.

Warning: This function is never significantly faster than a loop around insertItem().

See also insertItem() and insertStringList().

void QListBox::insertStrList ( const QStrList & list, int index = -1 )

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

Inserts the string list list into the list at position index.

If index is negative, list is inserted at the end of the list. If index is too large, the operation is ignored.

Warning: This function uses const char * rather than QString, so we recommend against using it. It is provided so that legacy code will continue to work, and so that programs that certainly will not need to handle code outside a single 8-bit locale can use it. See insertStringList() which uses real QStrings.

Warning: This function is never significantly faster than a loop around insertItem().

See also insertItem() and insertStringList().

void QListBox::insertStrList ( const char ** strings, int numStrings = -1, int index = -1 )

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

Inserts the numStrings strings of the array strings into the list at position index.

If index is negative, insertStrList() inserts strings at the end of the list. If index is too large, the operation is ignored.

Warning: This function uses const char * rather than QString, so we recommend against using it. It is provided so that legacy code will continue to work, and so that programs that certainly will not need to handle code outside a single 8-bit locale can use it. See insertStringList() which uses real QStrings.

Warning: This function is never significantly faster than a loop around insertItem().

See also insertItem() and insertStringList().

void QListBox::insertStringList ( const QStringList & list, int index = -1 )

Inserts the string list list into the list at position index.

If index is negative, list is inserted at the end of the list. If index is too large, the operation is ignored.

Warning: This function is never significantly faster than a loop around insertItem().

See also insertItem() and insertStrList().

void QListBox::invertSelection () [virtual slot]

Inverts the selection. Only works in Multi and Extended selection mode.

bool QListBox::isMultiSelection () const

Returns TRUE if or not the list box is in Multi selection mode; otherwise returns FALSE. See the "multiSelection" property for details.

bool QListBox::isRubberSelecting () const [protected]

Returns whether the user is selecting items using a rubber band rectangle.

bool QListBox::isSelected ( int i ) const

Returns TRUE if item i is selected; otherwise returns FALSE.

bool QListBox::isSelected ( const QListBoxItem * i ) const

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

Returns TRUE if item i is selected; otherwise returns FALSE.

QListBoxItem * QListBox::item ( int index ) const

Returns a pointer to the item at position index, or 0 if index is out of bounds.

See also index().

Example: listboxcombo/listboxcombo.cpp.

QListBoxItem * QListBox::itemAt ( const QPoint & p ) const

Returns a pointer to the item at point p, which is in on-screen coordinates, or a null pointer if there is no item at p.

int QListBox::itemHeight ( int index = 0 ) const

Returns the height in pixels of the item with index index. index defaults to 0.

If index is too large, this function returns 0.

QRect QListBox::itemRect ( QListBoxItem * item ) const

Returns the rectangle on the sizecreen that item occupies in viewport()'s coordinates, or an invalid rectangle if item is a null pointer or is not currently visible.

bool QListBox::itemVisible ( int index )

Returns TRUE if the item at position index is at least partly visible; otherwise returns FALSE.

bool QListBox::itemVisible ( const QListBoxItem * item )

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

Returns TRUE if item is at least partly visible; otherwise returns FALSE.

bool QListBox::itemYPos ( int index, int * yPos ) const [protected]

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

Returns the vertical pixel-coordinate in *yPos, of the list box item at position index in the list. Returns FALSE if the item is outside the visible area.

long QListBox::maxItemWidth () const

Returns the width of the widest item in the list box.

void QListBox::mouseButtonClicked ( int button, QListBoxItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user clicks mouse button button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pos is the position at release time.)

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

void QListBox::mouseButtonPressed ( int button, QListBoxItem * item, const QPoint & pos ) [signal]

This signal is emitted when the user presses mouse button button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pos is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()).

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

int QListBox::numCols () const

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

Returns the number of columns.

See also numColumns.

int QListBox::numColumns () const

Returns the number of columns in the list box. See the "numColumns" property for details.

int QListBox::numItemsVisible () const

Returns the number of visible items. See the "numItemsVisible" property for details.

int QListBox::numRows () const

Returns the number of rows in the list box. See the "numRows" property for details.

void QListBox::onItem ( QListBoxItem * i ) [signal]

This signal is emitted when the user moves the mouse cursor onto an item, similar to the QWidget::enterEvent() function. i is the QListBoxItem that the mouse has moved on.

void QListBox::onViewport () [signal]

This signal is emitted when the user moves the mouse cursor from an item to an empty part of the list box.

void QListBox::paintCell ( QPainter * p, int row, int col ) [virtual protected]

Provided for compatibility with the old QListBox. We recommend using QListBoxItem::paint()

Repaints the cell at row, col using painter p.

const QPixmap * QListBox::pixmap ( int index ) const

Returns a pointer to the pixmap at position index, or 0 if there is no pixmap there.

See also text().

void QListBox::pressed ( QListBoxItem * item ) [signal]

This signal is emitted when the user presses any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

void QListBox::pressed ( QListBoxItem * item, const QPoint & pnt ) [signal]

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

This signal is emitted when the user presses any mouse button. If item is non-null, the cursor is on item. If item is null, the mouse cursor isn't on any item.

pnt is the position of the mouse cursor in the global coordinate system (QMouseEvent::globalPos()). (If the click's press and release differ by a pixel or two, pnt is the position at release time.)

Note that you must not delete any QListBoxItem objects in slots connected to this signal.

See also mouseButtonPressed(), rightButtonPressed() and clicked().

void QListBox::removeItem ( int index )

Removes and deletes the item at position index. If index is equal to currentItem(), a new item gets highlighted and the highlighted() signal is emitted.

See also insertItem() and clear().

void QListBox::returnPressed ( QListBoxItem * ) [signal]

This signal is emitted when Enter or Return is pressed. The argument is currentItem().

void QListBox::rightButtonClicked ( QListBoxItem *, const QPoint & ) [signal]

This signal is emitted when the right button is clicked (i.e. when it's released at the same point where it was pressed). The arguments are the relevant QListBoxItem (may be 0) and the point in global coordinates.

void QListBox::rightButtonPressed ( QListBoxItem *, const QPoint & ) [signal]

This signal is emitted when the right button is pressed. The arguments are the relevant QListBoxItem (may be 0) and the point in global coordinates.

LayoutMode QListBox::rowMode () const

Returns the row layout mode for this list box. See the "rowMode" property for details.

bool QListBox::scrollBar () const

Returns FALSE if vScrollBarMode() is AlwaysOff; otherwise returns TRUE.

void QListBox::selectAll ( bool select ) [virtual slot]

In Multi and Extended modes, this function sets all items to be selected if select is TRUE, and to be unselected if select is FALSE.

In Single and NoSelection modes, this function only changes the selection status of currentItem().

void QListBox::selected ( int index ) [signal]

This signal is emitted when the user double-clicks on an item or presses Enter when an item is highlighted. index is the index of the selected item.

See also highlighted() and selectionChanged().

void QListBox::selected ( const QString & ) [signal]

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

This signal is emitted when the user double-clicks on an item or presses Enter while an item is highlighted, and the selected item is (or has) a string. The argument is the text of the selected item.

See also highlighted() and selectionChanged().

void QListBox::selected ( QListBoxItem * ) [signal]

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

This signal is emitted when the user double-clicks on an item or presses Enter when an item is highlighted. The argument is a pointer to the new selected item.

See also highlighted() and selectionChanged().

void QListBox::selectionChanged () [signal]

This signal is emitted when the selection set of a list box changes. This signal is emitted in each selection mode. If the user selects five items by drag-selecting, QListBox tries to emit just one selectionChanged() signal so the signal can be connected to computationally expensive slots.

See also selected() and currentItem.

void QListBox::selectionChanged ( QListBoxItem * item ) [signal]

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

This signal is emitted when the selection in a Single selection list box changes. item is the new selected list box item.

See also selected() and currentItem.

SelectionMode QListBox::selectionMode () const

Returns the selection mode of the list box. See the "selectionMode" property for details.

void QListBox::setAutoBottomScrollBar ( bool enable )

If enable is TRUE sets setHScrollBarMode() to AlwaysOn; otherwise sets setHScrollBarMode() to AlwaysOff.

void QListBox::setAutoScrollBar ( bool enable )

If enable is TRUE sets setVScrollBarMode() to AlwaysOn; otherwise sets setVScrollBarMode() to AlwaysOff.

void QListBox::setBottomItem ( int index ) [virtual]

Scrolls the list box so the item at position index in the list is displayed in the bottom row of the list box.

See also topItem.

void QListBox::setBottomScrollBar ( bool enable )

If enable is TRUE sets setHScrollBarMode() to AlwaysOn; otherwise sets setHScrollBarMode() to AlwaysOff.

void QListBox::setColumnMode ( LayoutMode ) [virtual]

Sets the column layout mode for this list box. See the "columnMode" property for details.

void QListBox::setColumnMode ( int columns ) [virtual]

Sets the column layout mode for this list box to columns. See the "columnMode" property for details.

void QListBox::setCurrentItem ( int index ) [virtual]

Sets the current highlighted item to index. See the "currentItem" property for details.

void QListBox::setCurrentItem ( QListBoxItem * i ) [virtual]

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

Sets the current item to the QListBoxItem i.

void QListBox::setMultiSelection ( bool multi )

Sets whether or not the list box is in Multi selection mode to multi. See the "multiSelection" property for details.

void QListBox::setRowMode ( LayoutMode ) [virtual]

Sets the row layout mode for this list box. See the "rowMode" property for details.

void QListBox::setRowMode ( int rows ) [virtual]

Sets the row layout mode for this list box to rows. See the "rowMode" property for details.

void QListBox::setScrollBar ( bool enable )

If enable is TRUE sets setVScrollBarMode() to AlwaysOn; otherwise sets setVScrollBarMode() to AlwaysOff.

void QListBox::setSelected ( QListBoxItem * item, bool select ) [virtual]

Selects item if select is TRUE or unselects it if select is FALSE, and repaints the item appropriately.

If the list box is a Single selection list box and select is TRUE, setSelected() calls setCurrentItem().

If the list box is a Single selection list box, select is FALSE, setSelected() calls clearSelection().

See also multiSelection, currentItem, clearSelection() and currentItem.

void QListBox::setSelected ( int index, bool select )

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

If select is TRUE the item at position index is selected; otherwise the item is deselected.

void QListBox::setSelectionMode ( SelectionMode ) [virtual]

Sets the selection mode of the list box. See the "selectionMode" property for details.

void QListBox::setTopItem ( int index ) [virtual]

Sets the index of an item at the top of the screen to index. See the "topItem" property for details.

void QListBox::setVariableHeight ( bool ) [virtual]

Sets whether this list box has variable-height rows. See the "variableHeight" property for details.

void QListBox::setVariableWidth ( bool ) [virtual]

Sets whether this list box has variable-width columns. See the "variableWidth" property for details.

void QListBox::sort ( bool ascending = TRUE )

If ascending is TRUE sorts the items in ascending order; otherwise sorts in descending order.

To compare the items, the text (QListBoxItem::text()) of the items is used.

Example: listbox/listbox.cpp.

void QListBox::takeItem ( const QListBoxItem * item )

Removes item from the list box and causes an update of the screen display. The item is not deleted. You should normally not need to call this function because QListBoxItem::~QListBoxItem() calls it. The normal way to delete an item is with delete.

See also QListBox::insertItem().

QString QListBox::text ( int index ) const

Returns the text at position index, or a null string if there is no text at that position.

See also pixmap().

void QListBox::toggleCurrentItem () [protected]

Toggles the selection status of currentItem() and repaints if the list box is a Multi selection list box.

See also multiSelection.

int QListBox::topItem () const

Returns the index of an item at the top of the screen. See the "topItem" property for details.

int QListBox::totalHeight () const [protected]

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

Returns contentsHeight().

int QListBox::totalWidth () const [protected]

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

Returns contentsWidth().

void QListBox::triggerUpdate ( bool doLayout )

Ensures that a single paint event will occur at the end of the current event loop iteration. If doLayout is TRUE, the layout is also redone.

void QListBox::updateItem ( int index ) [protected]

Repaints the item at position index in the list.

void QListBox::updateItem ( QListBoxItem * i ) [protected]

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

Repaints the QListBoxItem i.

bool QListBox::variableHeight () const

Returns TRUE if this list box has variable-height rows; otherwise returns FALSE. See the "variableHeight" property for details.

bool QListBox::variableWidth () const

Returns TRUE if this list box has variable-width columns; otherwise returns FALSE. See the "variableWidth" property for details.

Property Documentation

LayoutMode columnMode

This property holds the column layout mode for this list box.

Set this property's value with setColumnMode() and get this property's value with columnMode().

See also rowMode.

setColumnMode() sets the layout mode and adjusts the number of displayed columns. The row layout mode automatically becomes Variable, unless the column mode is Variable.

See also rowMode.

uint count

This property holds the number of items in the list box.

Get this property's value with count().

int currentItem

This property holds the current highlighted item.

When setting this property, the highlighting is moved and the list box scrolled as necessary.

If no item has been highlighted, currentItem() returns -1.

Set this property's value with setCurrentItem() and get this property's value with currentItem().

QString currentText

This property holds the text of the current item.

This is equivalent to text(currentItem()).

Get this property's value with currentText().

bool multiSelection

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

This property holds whether or not the list box is in Multi selection mode.

Consider using the QListBox::selectionMode property instead of this property.

When setting this property, Multi selection mode is used if set to TRUE and to Single selection mode if set to FALSE.

When getting this property, TRUE is returned if the list box is in Multi selection mode or Extended selection mode, and FALSE if it is in Single selection mode or NoSelection mode.

See also selectionMode.

Set this property's value with setMultiSelection() and get this property's value with isMultiSelection().

int numColumns

This property holds the number of columns in the list box.

This is normally 1, but can be different if QListBox::columnMode or QListBox::rowMode has been set.

See also columnMode, rowMode and numRows.

Get this property's value with numColumns().

int numItemsVisible

This property holds the number of visible items.

Both partially and entirely visible items are counted.

Get this property's value with numItemsVisible().

int numRows

This property holds the number of rows in the list box.

This is equal to the number of items in the default single-column layout, but can be different.

See also columnMode, rowMode and numColumns.

Get this property's value with numRows().

LayoutMode rowMode

This property holds the row layout mode for this list box.

This property is normally Variable.

setRowMode() sets the layout mode and adjusts the number of displayed rows. The column layout mode automatically becomes Variable, unless the row mode is Variable.

See also columnMode.

Set this property's value with setRowMode() and get this property's value with rowMode().

SelectionMode selectionMode

This property holds the selection mode of the list box.

Sets the list box's selection mode, which may be one of Single (the default), Extended, Multi or NoSelection.

See also SelectionMode.

Set this property's value with setSelectionMode() and get this property's value with selectionMode().

int topItem

This property holds the index of an item at the top of the screen.

When getting this property and the listbox has multiple columns, an arbitrary item is selected and returned.

When setting this property, the list box is scrolled so the item at position index in the list is displayed in the top row of the list box.

Set this property's value with setTopItem() and get this property's value with topItem().

bool variableHeight

This property holds whether this list box has variable-height rows.

When the list box has variable-height rows (the default), each row is as high as the highest item in that row. When it has same-sized rows, all rows are as high as the highest item in the list box.

See also variableWidth.

Set this property's value with setVariableHeight() and get this property's value with variableHeight().

bool variableWidth

This property holds whether this list box has variable-width columns.

When the list box has variable-width columns, each column is as wide as the widest item in that column. When it has same-sized columns (the default), all columns are as wide as the widest item in the list box.

See also variableHeight.

Set this property's value with setVariableWidth() and get this property's value with variableWidth().

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


qlistbox.h Include File

qlistbox.h

This is the verbatim text of the qlistbox.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qlistbox.h   3.0.5   edited Mar 1 17:39 $
**
** Definition of QListBox widget class
**
** Created : 941121
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLISTBOX_H
#define QLISTBOX_H

#ifndef QT_H
#include "qscrollview.h"
#include "qpixmap.h"
#endif // QT_H

#ifndef QT_NO_LISTBOX

class QListBoxPrivate;
class QListBoxItem;
class QString;
class QStrList;
class QStringList;

class Q_EXPORT QListBox : public QScrollView
{
    friend class QListBoxItem;
    friend class QListBoxPrivate;

    Q_OBJECT
    Q_ENUMS( SelectionMode LayoutMode )
    Q_PROPERTY( uint count READ count )
    Q_PROPERTY( int numItemsVisible READ numItemsVisible )
    Q_PROPERTY( int currentItem READ currentItem WRITE setCurrentItem )
    Q_PROPERTY( QString currentText READ currentText )
    Q_PROPERTY( int topItem READ topItem WRITE setTopItem DESIGNABLE false )
    Q_PROPERTY( SelectionMode selectionMode READ selectionMode WRITE setSelectionMode )
    Q_PROPERTY( bool multiSelection READ isMultiSelection WRITE setMultiSelection DESIGNABLE false )
    Q_PROPERTY( LayoutMode columnMode READ columnMode WRITE setColumnMode )
    Q_PROPERTY( LayoutMode rowMode READ rowMode WRITE setRowMode )
    Q_PROPERTY( int numColumns READ numColumns )
    Q_PROPERTY( int numRows READ numRows )
    Q_PROPERTY( bool variableWidth READ variableWidth WRITE setVariableWidth )
    Q_PROPERTY( bool variableHeight READ variableHeight WRITE setVariableHeight )

public:
    QListBox( QWidget* parent=0, const char* name=0, WFlags f=0  );
    ~QListBox();

    virtual void setFont( const QFont & );

    uint count() const;

    void insertStringList( const QStringList&, int index=-1 );
    void insertStrList( const QStrList *, int index=-1 );
    void insertStrList( const QStrList &, int index=-1 );
    void insertStrList( const char **,
            int numStrings=-1, int index=-1 );

    void insertItem( const QListBoxItem *, int index=-1 );
    void insertItem( const QListBoxItem *, const QListBoxItem *after );
    void insertItem( const QString &text, int index=-1 );
    void insertItem( const QPixmap &pixmap, int index=-1 );
    void insertItem( const QPixmap &pixmap, const QString &text, int index=-1 );

    void removeItem( int index );

    QString text( int index )	const;
    const QPixmap *pixmap( int index )	const;

    void changeItem( const QListBoxItem *, int index );
    void changeItem( const QString &text, int index );
    void changeItem( const QPixmap &pixmap, int index );
    void changeItem( const QPixmap &pixmap, const QString &text, int index );

    void takeItem( const QListBoxItem * );

    int numItemsVisible() const;

    int currentItem() const;
    QString currentText() const { return text(currentItem()); }
    virtual void setCurrentItem( int index );
    virtual void setCurrentItem( QListBoxItem * );
    void centerCurrentItem() { ensureCurrentVisible(); }
    int topItem() const;
    virtual void setTopItem( int index );
    virtual void setBottomItem( int index );

    long maxItemWidth() const;

    enum SelectionMode { Single, Multi, Extended, NoSelection };
    virtual void setSelectionMode( SelectionMode );
    SelectionMode selectionMode() const;

    void setMultiSelection( bool multi );
    bool isMultiSelection() const;

    virtual void setSelected( QListBoxItem *, bool );
    void setSelected( int, bool );
    bool isSelected( int ) const;
    bool isSelected( const QListBoxItem * ) const;

    QSize sizeHint() const;
    QSize	minimumSizeHint() const;

    QListBoxItem *item( int index ) const;
    int index( const QListBoxItem * ) const;
    QListBoxItem *findItem( const QString &text, ComparisonFlags compare = BeginsWith ) const;

    void triggerUpdate( bool doLayout );

    bool itemVisible( int index );
    bool itemVisible( const QListBoxItem * );

    enum LayoutMode { FixedNumber,
              FitToWidth, FitToHeight = FitToWidth,
              Variable };
    virtual void setColumnMode( LayoutMode );
    virtual void setColumnMode( int );
    virtual void setRowMode( LayoutMode );
    virtual void setRowMode( int );

    LayoutMode columnMode() const;
    LayoutMode rowMode() const;

    int numColumns() const;
    int numRows() const;

    bool variableWidth() const;
    virtual void setVariableWidth( bool );

    bool variableHeight() const;
    virtual void setVariableHeight( bool );

    void viewportPaintEvent( QPaintEvent * );

#ifndef QT_NO_COMPAT
    bool dragSelect() const { return TRUE; }
    void setDragSelect( bool ) {}
    bool autoScroll() const { return TRUE; }
    void setAutoScroll( bool ) {}
    bool autoScrollBar() const { return vScrollBarMode() == Auto; }
    void setAutoScrollBar( bool enable ) { setVScrollBarMode( enable ? Auto : AlwaysOff ); }
    bool scrollBar() const { return vScrollBarMode() != AlwaysOff; }
    void setScrollBar( bool enable ) { setVScrollBarMode( enable ? AlwaysOn : AlwaysOff ); }
    bool autoBottomScrollBar() const { return hScrollBarMode() == Auto; }
    void setAutoBottomScrollBar( bool enable ) { setHScrollBarMode( enable ? Auto : AlwaysOff ); }
    bool bottomScrollBar() const { return hScrollBarMode() != AlwaysOff; }
    void setBottomScrollBar( bool enable ) { setHScrollBarMode( enable ? AlwaysOn : AlwaysOff ); }
    bool smoothScrolling() const { return FALSE; }
    void setSmoothScrolling( bool ) {}
    bool autoUpdate() const { return TRUE; }
    void setAutoUpdate( bool ) {}
    void setFixedVisibleLines( int lines ) { setRowMode( lines ); }
    int inSort( const QListBoxItem * );
    int inSort( const QString& text );
    int cellHeight( int i ) const { return itemHeight(i); }
    int cellHeight() const { return itemHeight(); }
    int cellWidth() const { return maxItemWidth(); }
    int cellWidth(int i) const { Q_ASSERT(i==0); Q_UNUSED(i) return maxItemWidth(); }
    int	numCols() const { return numColumns(); }
#endif

    int itemHeight( int index = 0 ) const;
    QListBoxItem * itemAt( const QPoint & ) const;

    QRect itemRect( QListBoxItem *item ) const;

    QListBoxItem *firstItem() const;

    void sort( bool ascending = TRUE );

public slots:
    void clear();
    virtual void ensureCurrentVisible();
    virtual void clearSelection();
    virtual void selectAll( bool select );
    virtual void invertSelection();

signals:
    void highlighted( int index );
    void selected( int index );
    void highlighted( const QString &);
    void selected( const QString &);
    void highlighted( QListBoxItem * );
    void selected( QListBoxItem * );

    void selectionChanged();
    void selectionChanged( QListBoxItem * );
    void currentChanged( QListBoxItem * );
    void clicked( QListBoxItem * );
    void clicked( QListBoxItem *, const QPoint & );
    void pressed( QListBoxItem * );
    void pressed( QListBoxItem *, const QPoint & );

    void doubleClicked( QListBoxItem * );
    void returnPressed( QListBoxItem * );
    void rightButtonClicked( QListBoxItem *, const QPoint & );
    void rightButtonPressed( QListBoxItem *, const QPoint & );
    void mouseButtonPressed( int, QListBoxItem*, const QPoint& );
    void mouseButtonClicked( int, QListBoxItem*, const QPoint& );

    void contextMenuRequested( QListBoxItem *, const QPoint & );

    void onItem( QListBoxItem *item );
    void onViewport();

protected:
    void mousePressEvent( QMouseEvent * );
    void mouseReleaseEvent( QMouseEvent * );
    void mouseDoubleClickEvent( QMouseEvent * );
    void mouseMoveEvent( QMouseEvent * );
    void contentsContextMenuEvent( QContextMenuEvent * );

    void keyPressEvent( QKeyEvent *e );
    void focusInEvent( QFocusEvent *e );
    void focusOutEvent( QFocusEvent *e );
    void resizeEvent( QResizeEvent * );
    void showEvent( QShowEvent * );

    bool eventFilter( QObject *o, QEvent *e );

    void updateItem( int index );
    void updateItem( QListBoxItem * );

#ifndef QT_NO_COMPAT
    void updateCellWidth() { }
    int totalWidth() const { return contentsWidth(); }
    int totalHeight() const { return contentsHeight(); }
#endif

    virtual void paintCell( QPainter *, int row, int col );

    void toggleCurrentItem();
    bool isRubberSelecting() const;

    void doLayout() const;

    void windowActivationChange( bool );

#ifndef QT_NO_COMPAT
    bool itemYPos( int index, int *yPos ) const;
    int findItem( int yPos ) const { return index(itemAt(QPoint(0,yPos)) ); }
#endif

protected slots:
    void clearInputString();

private slots:
    void refreshSlot();
    void doAutoScroll();
    void adjustItems();

private:
    void mousePressEventEx( QMouseEvent * );
    void tryGeometry( int, int ) const;
    int currentRow() const;
    int currentColumn() const;
    void updateSelection();
    void drawRubber();
    void doRubberSelection( const QRect &old, const QRect &rubber );
    void handleItemChange( QListBoxItem *old, bool shift, bool control );
    void selectRange( QListBoxItem *from, QListBoxItem *to, bool invert, bool includeFirst, bool clearSel = FALSE );

    void emitChangedSignal( bool );

    int columnAt( int ) const;
    int rowAt( int ) const;

    QListBoxPrivate * d;

    static QListBox * changedListBox;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QListBox( const QListBox & );
    QListBox &operator=( const QListBox & );
#endif
};

class Q_EXPORT QListBoxItem
{
public:
    QListBoxItem( QListBox* listbox = 0 );
    QListBoxItem( QListBox* listbox, QListBoxItem *after );
    virtual ~QListBoxItem();

    virtual QString text() const;
    virtual const QPixmap *pixmap() const;

    virtual int	 height( const QListBox * ) const;
    virtual int	 width( const QListBox * )  const;

    bool isSelected() const { return s; }
    bool isCurrent() const;

#ifndef QT_NO_COMPAT
    bool selected() const { return isSelected(); }
    bool current() const { return isCurrent(); }
#endif

    QListBox *listBox() const;

    void setSelectable( bool b );
    bool isSelectable() const;

    QListBoxItem *next() const;
    QListBoxItem *prev() const;

    virtual int rtti() const;
    static int RTTI;

protected:
    virtual void paint( QPainter * ) = 0;
    virtual void setText( const QString &text ) { txt = text; }
    void setCustomHighlighting( bool );

private:
    QString txt;
    uint s:1;
    uint dirty:1;
    uint custom_highlight : 1;
    int x, y;
    QListBoxItem * p, * n;
    QListBox* lbox;
    friend class QListBox;
    friend class QListBoxPrivate;
    friend class QComboBox;
    friend class QComboBoxPopupItem;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QListBoxItem( const QListBoxItem & );
    QListBoxItem &operator=( const QListBoxItem & );
#endif
};

class Q_EXPORT QListBoxText : public QListBoxItem
{
public:
    QListBoxText( QListBox* listbox, const QString & text=QString::null );
    QListBoxText( const QString & text=QString::null );
    QListBoxText( QListBox* listbox, const QString & text, QListBoxItem *after );
   ~QListBoxText();

    int	 height( const QListBox * ) const;
    int	 width( const QListBox * )  const;

    int rtti() const;
    static int RTTI;

protected:
    void  paint( QPainter * );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QListBoxText( const QListBoxText & );
    QListBoxText &operator=( const QListBoxText & );
#endif
};

class Q_EXPORT QListBoxPixmap : public QListBoxItem
{
public:
    QListBoxPixmap( QListBox* listbox, const QPixmap & );
    QListBoxPixmap( const QPixmap & );
    QListBoxPixmap( QListBox* listbox, const QPixmap & pix, QListBoxItem *after );
    QListBoxPixmap( QListBox* listbox, const QPixmap &, const QString& );
    QListBoxPixmap( const QPixmap &, const QString& );
    QListBoxPixmap( QListBox* listbox, const QPixmap & pix, const QString&, QListBoxItem *after );
   ~QListBoxPixmap();

    const QPixmap *pixmap() const { return &pm; }

    int	 height( const QListBox * ) const;
    int	 width( const QListBox * )  const;

    int rtti() const;
    static int RTTI;

protected:
    void paint( QPainter * );

private:
    QPixmap pm;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QListBoxPixmap( const QListBoxPixmap & );
    QListBoxPixmap &operator=( const QListBoxPixmap & );
#endif
};

#endif // QT_NO_LISTBOX

#endif // QLISTBOX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QListBox Member List

Complete Member List for QListBox

This is the complete list of member functions for QListBox, including inherited members.

  • QListBox()
  • ~QListBox()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • autoBottomScrollBar()
  • autoMask()
  • autoScrollBar()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • bottomScrollBar()
  • caption()
  • cellHeight()
  • cellWidth()
  • center()
  • centerCurrentItem()
  • changeItem()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearSelection()
  • clearWFlags()
  • clicked()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columnMode()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • contextMenuRequested()
  • cornerWidget()
  • count()
  • create()
  • currentChanged()
  • currentItem()
  • currentText()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doLayout()
  • doubleClicked()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureCurrentVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • findItem()
  • firstItem()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • highlighted()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inSort()
  • index()
  • inherits()
  • insertChild()
  • insertItem()
  • insertStrList()
  • insertStringList()
  • installEventFilter()
  • invertSelection()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isMultiSelection()
  • isPopup()
  • isRubberSelecting()
  • isSelected()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • item()
  • itemAt()
  • itemHeight()
  • itemRect()
  • itemVisible()
  • itemYPos()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maxItemWidth()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseButtonClicked()
  • mouseButtonPressed()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numCols()
  • numColumns()
  • numItemsVisible()
  • numRows()
  • objectTrees()
  • onItem()
  • onViewport()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintCell()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeItem()
  • repaint()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • returnPressed()
  • rightButtonClicked()
  • rightButtonPressed()
  • rightMargin()
  • rowMode()
  • scroll()
  • scrollBar()
  • scrollBy()
  • selectAll()
  • selected()
  • selectionChanged()
  • selectionMode()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoBottomScrollBar()
  • setAutoMask()
  • setAutoScrollBar()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBottomItem()
  • setBottomScrollBar()
  • setCaption()
  • setColumnMode()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentItem()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMultiSelection()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizePolicy()
  • setRowMode()
  • setScrollBar()
  • setSelected()
  • setSelectionMode()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setTopItem()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setVariableHeight()
  • setVariableWidth()
  • setWFlags()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sort()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • takeItem()
  • testWFlags()
  • text()
  • timerEvent()
  • toggleCurrentItem()
  • topItem()
  • topLevelWidget()
  • topMargin()
  • totalHeight()
  • totalWidth()
  • tr()
  • trUtf8()
  • triggerUpdate()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateItem()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • variableHeight()
  • variableWidth()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QListBoxItem Class

QListBoxItem Class Reference

The QListBoxItem class is the base class of all list box items. More...

#include <qlistbox.h>

Inherited by QListBoxText and QListBoxPixmap.

List of all member functions.

Public Members

  • QListBoxItem ( QListBox * listbox = 0 )
  • QListBoxItem ( QListBox * listbox, QListBoxItem * after )
  • virtual ~QListBoxItem ()
  • virtual QString text () const
  • virtual const QPixmap * pixmap () const
  • virtual int height ( const QListBox * lb ) const
  • virtual int width ( const QListBox * lb ) const
  • bool isSelected () const
  • bool isCurrent () const
  • bool selected () const (obsolete)
  • bool current () const (obsolete)
  • QListBox * listBox () const
  • void setSelectable ( bool b )
  • bool isSelectable () const
  • QListBoxItem * next () const
  • QListBoxItem * prev () const
  • virtual int rtti () const

Protected Members

  • virtual void paint ( QPainter * p ) = 0
  • virtual void setText ( const QString & text )
  • void setCustomHighlighting ( bool b )

Detailed Description

The QListBoxItem class is the base class of all list box items.

This class is an abstract base class used for all list box items. If you need to insert customized items into a QListBox you must inherit this class and reimplement paint(), height() and width().

See also QListBox and Advanced Widgets.

Member Function Documentation

QListBoxItem::QListBoxItem ( QListBox * listbox = 0 )

Constructs an empty list box item in the list box listbox.

QListBoxItem::QListBoxItem ( QListBox * listbox, QListBoxItem * after )

Constructs an empty list box item in the list box listbox and inserts it after the item after. If after is 0, the item is inserted at the beginning.

QListBoxItem::~QListBoxItem () [virtual]

Destroys the list box item.

bool QListBoxItem::current () const

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

int QListBoxItem::height ( const QListBox * lb ) const [virtual]

Implement this function to return the height of your item. The lb parameter is the same as listBox() and is provided for convenience and compatibility.

See also paint() and width().

Reimplemented in QListBoxText and QListBoxPixmap.

bool QListBoxItem::isCurrent () const

Returns TRUE if the item is the current item; otherwise returns FALSE.

See also QListBox::currentItem, QListBox::item() and isSelected().

bool QListBoxItem::isSelectable () const

Returns TRUE if this item is selectable; otherwise returns FALSE.

See also setSelectable().

bool QListBoxItem::isSelected () const

Returns TRUE if the item is selected; otherwise returns FALSE.

See also QListBox::isSelected() and isCurrent().

Example: listboxcombo/listboxcombo.cpp.

QListBox * QListBoxItem::listBox () const

Returns a pointer to the list box containing this item.

QListBoxItem * QListBoxItem::next () const

Returns the item that comes after this in the list box. If this is the last item, a null pointer is returned.

See also prev().

void QListBoxItem::paint ( QPainter * p ) [pure virtual protected]

Implement this function to draw your item. You will need to pass the QPainter that will draw the item in p.

See also height() and width().

Example: listboxcombo/listboxcombo.cpp.

Reimplemented in QListBoxText and QListBoxPixmap.

const QPixmap * QListBoxItem::pixmap () const [virtual]

Returns the pixmap associated with the item, if any.

The default implementation returns a null pointer.

Example: listboxcombo/listboxcombo.cpp.

Reimplemented in QListBoxPixmap.

QListBoxItem * QListBoxItem::prev () const

Returns the item which comes before this in the list box. If this is the first item, a null pointer is returned.

See also next().

int QListBoxItem::rtti () const [virtual]

Returns 0.

Although often frowned upon by purists, Run Time Type Identification is very useful in this case, as it allows a QListBox to be an efficient indexed storage mechanism.

Make your derived classes return their own values for rtti(), and you can distinguish between listbox items. You should use values greater than 1000 preferably a large random number, to allow for extensions to this class.

bool QListBoxItem::selected () const

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

void QListBoxItem::setCustomHighlighting ( bool b ) [protected]

Defines whether the list box item is responsible for drawing itself in a highlighted state when being selected.

If b is FALSE (the default), the list box will draw some default highlight indicator before calling paint().

See also selected() and paint().

void QListBoxItem::setSelectable ( bool b )

If b is TRUE then this item can be selected by the user; otherwise this item cannot be selected by the user.

See also isSelectable().

void QListBoxItem::setText ( const QString & text ) [virtual protected]

Sets the text of the QListBoxItem to text. This text is also used for sorting. The text is not shown unless explicitly drawn in paint().

See also text().

QString QListBoxItem::text () const [virtual]

Returns the text of the item. This text is also used for sorting.

See also setText().

Example: listboxcombo/listboxcombo.cpp.

int QListBoxItem::width ( const QListBox * lb ) const [virtual]

Implement this function to return the width of your item. The lb parameter is the same as listBox() and is provided for convenience and compatibility.

See also paint() and height().

Reimplemented in QListBoxText and QListBoxPixmap.

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


QListBoxItem Member List

Complete Member List for QListBoxItem

This is the complete list of member functions for QListBoxItem, including inherited members.

  • QListBoxItem()
  • ~QListBoxItem()
  • current()
  • height()
  • isCurrent()
  • isSelectable()
  • isSelected()
  • listBox()
  • next()
  • paint()
  • pixmap()
  • prev()
  • rtti()
  • selected()
  • setCustomHighlighting()
  • setSelectable()
  • setText()
  • text()
  • width()


QListBoxPixmap Class

QListBoxPixmap Class Reference

The QListBoxPixmap class provides list box items with a pixmap and optional text. More...

#include <qlistbox.h>

Inherits QListBoxItem.

List of all member functions.

Public Members

  • QListBoxPixmap ( QListBox * listbox, const QPixmap & pixmap )
  • QListBoxPixmap ( const QPixmap & pixmap )
  • QListBoxPixmap ( QListBox * listbox, const QPixmap & pixmap, QListBoxItem * after )
  • QListBoxPixmap ( QListBox * listbox, const QPixmap & pix, const QString & text )
  • QListBoxPixmap ( const QPixmap & pix, const QString & text )
  • QListBoxPixmap ( QListBox * listbox, const QPixmap & pix, const QString & text, QListBoxItem * after )
  • ~QListBoxPixmap ()
  • virtual const QPixmap * pixmap () const
  • virtual int height ( const QListBox * lb ) const
  • virtual int width ( const QListBox * lb ) const

Protected Members

  • virtual void paint ( QPainter * painter )

Detailed Description

The QListBoxPixmap class provides list box items with a pixmap and optional text.

Items of this class are drawn with the pixmap on the left with the optional text to the right of the pixmap.

See also QListBox, QListBoxItem and Advanced Widgets.

Member Function Documentation

QListBoxPixmap::QListBoxPixmap ( QListBox * listbox, const QPixmap & pixmap )

Constructs a new list box item in list box listbox showing the pixmap pixmap.

QListBoxPixmap::QListBoxPixmap ( const QPixmap & pixmap )

Constructs a new list box item showing the pixmap pixmap.

QListBoxPixmap::QListBoxPixmap ( QListBox * listbox, const QPixmap & pixmap, QListBoxItem * after )

Constructs a new list box item in list box listbox showing the pixmap pixmap. The item gets inserted after the item after.

QListBoxPixmap::QListBoxPixmap ( QListBox * listbox, const QPixmap & pix, const QString & text )

Constructs a new list box item in list box listbox showing the pixmap pix and the text text.

QListBoxPixmap::QListBoxPixmap ( const QPixmap & pix, const QString & text )

Constructs a new list box item showing the pixmap pix and the text to text.

QListBoxPixmap::QListBoxPixmap ( QListBox * listbox, const QPixmap & pix, const QString & text, QListBoxItem * after )

Constructs a new list box item in list box listbox showing the pixmap pix and the string text. The item gets inserted after the item after.

QListBoxPixmap::~QListBoxPixmap ()

Destroys the item.

int QListBoxPixmap::height ( const QListBox * lb ) const [virtual]

Returns the height of the pixmap in list box lb.

See also paint() and width().

Reimplemented from QListBoxItem.

void QListBoxPixmap::paint ( QPainter * painter ) [virtual protected]

Draws the pixmap using painter.

Reimplemented from QListBoxItem.

const QPixmap * QListBoxPixmap::pixmap () const [virtual]

Returns the pixmap associated with the item.

Reimplemented from QListBoxItem.

int QListBoxPixmap::width ( const QListBox * lb ) const [virtual]

Returns the width of the pixmap plus some margin in list box lb.

See also paint() and height().

Reimplemented from QListBoxItem.

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


QListBoxPixmap Member List

Complete Member List for QListBoxPixmap

This is the complete list of member functions for QListBoxPixmap, including inherited members.

  • QListBoxPixmap()
  • ~QListBoxPixmap()
  • current()
  • height()
  • isCurrent()
  • isSelectable()
  • isSelected()
  • listBox()
  • next()
  • paint()
  • pixmap()
  • prev()
  • rtti()
  • selected()
  • setCustomHighlighting()
  • setSelectable()
  • setText()
  • text()
  • width()


QListBoxText Class

QListBoxText Class Reference

The QListBoxText class provides list box items that display text. More...

#include <qlistbox.h>

Inherits QListBoxItem.

List of all member functions.

Public Members

  • QListBoxText ( QListBox * listbox, const QString & text = QString::null )
  • QListBoxText ( const QString & text = QString::null )
  • QListBoxText ( QListBox * listbox, const QString & text, QListBoxItem * after )
  • ~QListBoxText ()
  • virtual int height ( const QListBox * lb ) const
  • virtual int width ( const QListBox * lb ) const

Protected Members

  • virtual void paint ( QPainter * painter )

Detailed Description

The QListBoxText class provides list box items that display text.

The text is drawn in the widget's current font. If you need several different fonts, you must implement your own subclass of QListBoxItem.

See also QListBox, QListBoxItem and Advanced Widgets.

Member Function Documentation

QListBoxText::QListBoxText ( QListBox * listbox, const QString & text = QString::null )

Constructs a list box item in list box listbox showing the text text.

QListBoxText::QListBoxText ( const QString & text = QString::null )

Constructs a list box item showing the text text.

QListBoxText::QListBoxText ( QListBox * listbox, const QString & text, QListBoxItem * after )

Constructs a list box item in list box listbox showing the text text. The item gets inserted after the item after.

QListBoxText::~QListBoxText ()

Destroys the item.

int QListBoxText::height ( const QListBox * lb ) const [virtual]

Returns the height of a line of text in list box lb.

See also paint() and width().

Reimplemented from QListBoxItem.

void QListBoxText::paint ( QPainter * painter ) [virtual protected]

Draws the text using painter.

Reimplemented from QListBoxItem.

int QListBoxText::width ( const QListBox * lb ) const [virtual]

Returns the width of this line in list box lb.

See also paint() and height().

Reimplemented from QListBoxItem.

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


QListBoxText Member List

Complete Member List for QListBoxText

This is the complete list of member functions for QListBoxText, including inherited members.

  • QListBoxText()
  • ~QListBoxText()
  • current()
  • height()
  • isCurrent()
  • isSelectable()
  • isSelected()
  • listBox()
  • next()
  • paint()
  • pixmap()
  • prev()
  • rtti()
  • selected()
  • setCustomHighlighting()
  • setSelectable()
  • setText()
  • text()
  • width()


QListView Class

QListView Class Reference

The QListView class implements a list/tree view. More...

#include <qlistview.h>

Inherits QScrollView.

List of all member functions.

Public Members

  • QListView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QListView ()
  • int treeStepSize () const
  • virtual void setTreeStepSize ( int )
  • virtual void insertItem ( QListViewItem * i )
  • virtual void takeItem ( QListViewItem * i )
  • virtual void removeItem ( QListViewItem * item ) (obsolete)
  • QHeader * header () const
  • virtual int addColumn ( const QString & label, int width = -1 )
  • virtual int addColumn ( const QIconSet & iconset, const QString & label, int width = -1 )
  • virtual void removeColumn ( int index )
  • virtual void setColumnText ( int column, const QString & label )
  • virtual void setColumnText ( int column, const QIconSet & iconset, const QString & label )
  • QString columnText ( int c ) const
  • virtual void setColumnWidth ( int column, int w )
  • int columnWidth ( int c ) const
  • enum WidthMode { Manual, Maximum }
  • virtual void setColumnWidthMode ( int c, WidthMode mode )
  • WidthMode columnWidthMode ( int c ) const
  • int columns () const
  • virtual void setColumnAlignment ( int column, int align )
  • int columnAlignment ( int column ) const
  • QListViewItem * itemAt ( const QPoint & viewPos ) const
  • QRect itemRect ( const QListViewItem * i ) const
  • int itemPos ( const QListViewItem * item )
  • void ensureItemVisible ( const QListViewItem * i )
  • void repaintItem ( const QListViewItem * item ) const
  • virtual void setMultiSelection ( bool enable )
  • bool isMultiSelection () const
  • enum SelectionMode { Single, Multi, Extended, NoSelection }
  • void setSelectionMode ( SelectionMode mode )
  • SelectionMode selectionMode () const
  • virtual void clearSelection ()
  • virtual void setSelected ( QListViewItem * item, bool selected )
  • bool isSelected ( const QListViewItem * i ) const
  • QListViewItem * selectedItem () const
  • virtual void setOpen ( QListViewItem * item, bool open )
  • bool isOpen ( const QListViewItem * item ) const
  • virtual void setCurrentItem ( QListViewItem * i )
  • QListViewItem * currentItem () const
  • QListViewItem * firstChild () const
  • QListViewItem * lastItem () const
  • int childCount () const
  • virtual void setAllColumnsShowFocus ( bool )
  • bool allColumnsShowFocus () const
  • virtual void setItemMargin ( int )
  • int itemMargin () const
  • virtual void setRootIsDecorated ( bool )
  • bool rootIsDecorated () const
  • virtual void setSorting ( int column, bool ascending = TRUE )
  • virtual void sort ()
  • virtual bool eventFilter ( QObject * o, QEvent * e )
  • virtual void setShowSortIndicator ( bool show )
  • bool showSortIndicator () const
  • virtual void setShowToolTips ( bool b )
  • bool showToolTips () const
  • enum ResizeMode { NoColumn, AllColumns, LastColumn }
  • virtual void setResizeMode ( ResizeMode m )
  • ResizeMode resizeMode () const
  • QListViewItem * findItem ( const QString & text, int column, ComparisonFlags compare = ExactMatch | CaseSensitive ) const
  • enum RenameAction { Accept, Reject }
  • virtual void setDefaultRenameAction ( RenameAction a )
  • RenameAction defaultRenameAction () const
  • bool isRenaming () const

Public Slots

  • virtual void clear ()
  • virtual void invertSelection ()
  • virtual void selectAll ( bool select )
  • void triggerUpdate ()

Signals

  • void selectionChanged ()
  • void selectionChanged ( QListViewItem * )
  • void currentChanged ( QListViewItem * )
  • void clicked ( QListViewItem * item )
  • void clicked ( QListViewItem * item, const QPoint & pnt, int c )
  • void pressed ( QListViewItem * item )
  • void pressed ( QListViewItem * item, const QPoint & pnt, int c )
  • void doubleClicked ( QListViewItem * item )
  • void returnPressed ( QListViewItem * )
  • void spacePressed ( QListViewItem * )
  • void rightButtonClicked ( QListViewItem *, const QPoint &, int )
  • void rightButtonPressed ( QListViewItem *, const QPoint &, int )
  • void mouseButtonPressed ( int button, QListViewItem * item, const QPoint & pos, int c )
  • void mouseButtonClicked ( int button, QListViewItem * item, const QPoint & pos, int c )
  • void contextMenuRequested ( QListViewItem * item, const QPoint & pos, int col )
  • void onItem ( QListViewItem * i )
  • void onViewport ()
  • void expanded ( QListViewItem * item )
  • void collapsed ( QListViewItem * item )
  • void dropped ( QDropEvent * e )
  • void itemRenamed ( QListViewItem * item, int col, const QString & text )
  • void itemRenamed ( QListViewItem * item, int col )

Properties

  • bool allColumnsShowFocus - whether items should show keyboard focus using all columns
  • int childCount - the number of parentless (top level) QListViewItem objects in this QListView (read only)
  • int columns - the number of columns in this list view (read only)
  • RenameAction defaultRenameAction - whether the list view accepts the rename operation by default
  • int itemMargin - the advisory item margin that list items may use
  • bool multiSelection - whether the list view is in multi-selection or single selection mode
  • ResizeMode resizeMode - whether all, none or the last column should be resized
  • bool rootIsDecorated - whether the list view show open/close signs on root items
  • SelectionMode selectionMode - the list view's multi-selection mode
  • bool showSortIndicator - whether the list view header should display a sort indicator
  • bool showToolTips - whether this list view should show tooltips for truncated column texts
  • int treeStepSize - the number of pixels a child is offset from its parent

Protected Members

  • virtual void contentsMousePressEvent ( QMouseEvent * e )
  • virtual void contentsMouseReleaseEvent ( QMouseEvent * e )
  • virtual void contentsMouseMoveEvent ( QMouseEvent * e )
  • virtual void contentsMouseDoubleClickEvent ( QMouseEvent * e )
  • virtual QDragObject * dragObject ()
  • virtual void startDrag ()
  • virtual void resizeEvent ( QResizeEvent * e )
  • virtual void drawContentsOffset ( QPainter * p, int ox, int oy, int cx, int cy, int cw, int ch )
  • virtual void paintEmptyArea ( QPainter * p, const QRect & rect )

Protected Slots

  • void updateContents ()
  • void doAutoScroll ()

Detailed Description

The QListView class implements a list/tree view.

It can display and control a hierarchy of multi-column items, and provides the ability to add new items at any time. Among others the user may select one or many items and sort the list in increasing or decreasing order by any column.

The simplest mode of use is to create a QListView, add some column headers using addColumn() and create one or more QListViewItem or QCheckListItem objects with the QListView as parent:

        QListView * table;

        table->addColumn( "Qualified name" );
        table->addColumn( "Namespace" );

            element = new QListViewItem( table, qName, namespaceURI );

Further nodes can be added to the listview object (the root of the tree) or as child nodes to QListViewItems:

            for ( int i = 0 ; i < attributes.length(); i++ ) {
                new QListViewItem( element, attributes.qName(i), attributes.uri(i) );
            }

(From xml/tagreader-with-features/structureparser.cpp )

The main setup functions are

  • addColumn() - adds a column with text and perhaps width.

  • setColumnWidthMode() - sets the column to be resized automatically or not.

  • setAllColumnsShowFocus() - sets whether items should show keyboard focus using all columns or just column 0. The default is to show focus using just column 0.

  • setRootIsDecorated() - sets whether root items can be opened and closed by the user and have open/close decoration to their left. The default is FALSE.

  • setTreeStepSize() - sets how many pixels an item's children are indented relative to their parent. The default is 20. This is mostly a matter of taste.

  • setSorting() - sets whether the items should be sorted, whether it should be in ascending or descending order, and by what column it should be sorted. By default the list view is sorted by the first column; to switch this off call setSorting( -1 ).

To handle events such as mouse presses on the list view, derived classes can reimplement the QScrollView functions contentsMousePressEvent, contentsMouseReleaseEvent, contentsMouseDoubleClickEvent, contentsMouseMoveEvent, contentsDragEnterEvent, contentsDragMoveEvent, contentsDragLeaveEvent, contentsDropEvent, and contentsWheelEvent.

There are also several functions for mapping between items and coordinates. itemAt() returns the item at a position on-screen, itemRect() returns the rectangle an item occupies on the screen, and itemPos() returns the position of any item (not on-screen in the list view). firstChild() returns the item at the top of the view (not necessarily on-screen) so you can iterate over the items using either QListViewItem::itemBelow() or a combination of QListViewItem::firstChild() and QListViewItem::nextSibling().

If you need to move a list view item you can use takeItem() and insertItem(). Item's are deleted with delete; to delete all items use clear(). See the QListViewItem documentation for examples of traversal.

There are a variety of selection modes described in the QListView::SelectionMode documentation. The default is Single selection, which you can change using setSelectionMode().

Because QListView offers multiple selection it has to display keyboard focus and selection state separately. Therefore there are functions both to set the selection state of an item (setSelected()) and to select which item displays keyboard focus (setCurrentItem()).

QListView emits two groups of signals; one group signals changes in selection/focus state and one signals selection. The first group consists of selectionChanged() (applicable to all list views), selectionChanged( QListViewItem * ) (applicable only to Single selection list view), and currentChanged( QListViewItem * ). The second group consists of doubleClicked( QListViewItem * ), returnPressed( QListViewItem * ) and rightButtonClicked( QListViewItem *, const QPoint&, int ), etc.

In Motif style, QListView deviates fairly strongly from the look and feel of the Motif hierarchical tree view. This is done mostly to provide a usable keyboard interface and to make the list view look better with a white background.

If selectionMode() is Single (the default) the user can select one item at a time, e.g. by clicking an item with the mouse, see QListView::SelectionMode for details.

The listview can be navigated either using the mouse or the keyboard. Clicking an - icon closes an item (hides its children) and clicking an + icon opens an item (shows its children). The keyboard controls are these:

  • Home - Make the first item current and visible.
  • End - Make the last item current and visible.
  • Page Up - Make the item above the top visible item current and visible.
  • Page Down - Make the item below the bottom visible item current and visible.
  • Up Arrow - Make the item above the current item current and visible.
  • Down Arrow - Make the item below the current item current and visible.
  • Left Arrow - If the current item is closed (+ icon) or has no children make its parent item current and visible. If the current item is open (- icon) close it, i.e. hide its children. Exception: if the current item is the first item and is closed and the horizontal scrollbar is offset to the right the listview will be scrolled left.
  • Right Arrow - If the current item is closed (+ icon) and has children the item is opened. If the current item is opened (- icon) and has children the item's first child is made current and visible. If the current item has no children the listview is scrolled right.
If the user starts typing letters with the focus in the listview an incremental search will occur. For example if the user types 'd' the current item will change to the first item that begins with the letter 'd'; if they then type 'a', the current item will change to the first item that begins with 'da', and so on. If no item begins with the letters they type the current item doesn't change.

Warning: The list view assumes ownership of all list view items and will delete them when it does not need them any more.

See also QListViewItem, QCheckListItem and Advanced Widgets.

Member Type Documentation

QListView::RenameAction

This enum describes whether a rename operation is accepted if the rename editor loses focus without the user pressing Enter.

  • QListView::Accept - Rename if Enter is pressed or focus is lost.
  • QListView::Reject - Discard the rename operation if focus is lost (and Enter has not been pressed).

QListView::ResizeMode

This enum describes how the header adjusts to resize events which affect the width of the listview.

  • QListView::NoColumn - The columns do not get resized in resize events.
  • QListView::AllColumns - All columns are resized equally to fit the width of the listview.
  • QListView::LastColumn - The last columns is resized to fit the with of the listview.

QListView::SelectionMode

This enumerated type is used by QListView to indicate how it reacts to selection by the user. It has four values:

  • QListView::Single - When the user selects an item, any already-selected item becomes unselected, and the user cannot unselect the selected item. This means that the user can never clear the selection, even though the selection may be cleared by the application programmer using QListView::clearSelection().
  • QListView::Multi - When the user selects an item in the most ordinary way, the selection status of that item is toggled and the other items are left alone.
  • QListView::Extended - When the user selects an item in the most ordinary way, the selection is cleared and the new item selected. However, if the user presses the CTRL key when clicking on an item, the clicked item gets toggled and all other items are left untouched. And if the user presses the SHIFT key while clicking on an item, all items between the current item and the clicked item get selected or unselected, depending on the state of the clicked item. Also, multiple items can be selected by dragging the mouse while the left mouse button stays pressed.
  • QListView::NoSelection - Items cannot be selected.

In other words, Single is a real single-selection list view, Multi a real multi-selection list view, Extended is a list view where users can select multiple items but usually want to select either just one or a range of contiguous items, and NoSelection is a list view where the user can look but not touch.

QListView::WidthMode

This enum type describes how the width of a column in the view changes. The currently defined modes are:

  • QListView::Manual - the column width does not change automatically.
  • QListView::Maximum - the column is automatically sized according to the widths of all items in the column. (Note: The column never shrinks in this case.) This means the column is always resized to the width of the item with the largest width in the column.

See also setColumnWidth(), setColumnWidthMode() and columnWidth().

Member Function Documentation

QListView::QListView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a new empty list view, with parent as a parent and name as object name.

Performance is boosted by modifying the widget flags f so that only part of the QListViewItem children is redrawn. This may be unsuitable for custom QListViewItem classes, in which case WStaticContents and WRepaintNoErase should be cleared.

See also QWidget::clearWFlags() and Qt::WidgetFlags.

QListView::~QListView ()

Destroys the list view, deleting all its items, and frees up all allocated resources.

int QListView::addColumn ( const QString & label, int width = -1 ) [virtual]

Adds a width pixels wide column with the column header label to this QListView, and returns the index of the new column.

All columns apart from the first one are inserted to the right of the existing ones.

If width is negative, the new column's WidthMode is set to Maximum instead of Manual.

See also setColumnText(), setColumnWidth() and setColumnWidthMode().

Examples: addressbook/centralwidget.cpp, checklists/checklists.cpp, dirview/main.cpp, fileiconview/mainwindow.cpp, listviews/listviews.cpp and qdir/qdir.cpp.

int QListView::addColumn ( const QIconSet & iconset, const QString & label, int width = -1 ) [virtual]

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

Adds a width pixels wide new column with the header label and iconset to this QListView, and returns the index of the column.

If width is negative, the new column's WidthMode is set to Maximum, and to Manual otherwise.

See also setColumnText(), setColumnWidth() and setColumnWidthMode().

bool QListView::allColumnsShowFocus () const

Returns TRUE if items should show keyboard focus using all columns; otherwise returns FALSE. See the "allColumnsShowFocus" property for details.

int QListView::childCount () const

Returns the number of parentless (top level) QListViewItem objects in this QListView. See the "childCount" property for details.

void QListView::clear () [virtual slot]

Removes and deletes all the items in this list view and triggers an update.

See also triggerUpdate().

Examples: addressbook/centralwidget.cpp, checklists/checklists.cpp, listviews/listviews.cpp and network/ftpclient/ftpmainwindow.cpp.

void QListView::clearSelection () [virtual]

Sets all items to be not selected, updates the list view as necessary and emits the selectionChanged() signals. Note that for Multi selection list views this function needs to iterate over all items.

See also setSelected() and multiSelection.

Example: addressbook/centralwidget.cpp.

void QListView::clicked ( QListViewItem * item ) [signal]

This signal is emitted whenever the user clicks (mouse pressed and mouse released) in the list view. item is the pointer to the clicked list view item, or 0 if the user didn't click on an item.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

Example: addressbook/centralwidget.cpp.

void QListView::clicked ( QListViewItem * item, const QPoint & pnt, int c ) [signal]

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

This signal is emitted whenever the user clicks (mouse pressed and mouse released) in the list view. item is the pointer to the clicked list view item, or 0 if the user didn't click on an item. pnt is the position where the user has clicked. If item is not 0, c is the list view column into which the user pressed; if item is 0 c's value is undefined.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

void QListView::collapsed ( QListViewItem * item ) [signal]

This signal is emitted when the item has been collapsed, i.e. when the children of item are hidden.

See also setOpen() and expanded().

int QListView::columnAlignment ( int column ) const

Returns the alignment of column column. The default is AlignAuto.

See also Qt::AlignmentFlags.

QString QListView::columnText ( int c ) const

Returns the text of column c.

See also setColumnText().

int QListView::columnWidth ( int c ) const

Returns the width of column c.

See also setColumnWidth().

WidthMode QListView::columnWidthMode ( int c ) const

Returns the WidthMode for column c.

See also setColumnWidthMode().

int QListView::columns () const

Returns the number of columns in this list view. See the "columns" property for details.

void QListView::contentsMouseDoubleClickEvent ( QMouseEvent * e ) [virtual protected]

Processes the mouse double-click event e on behalf of the viewed widget.

Reimplemented from QScrollView.

void QListView::contentsMouseMoveEvent ( QMouseEvent * e ) [virtual protected]

Processes the mouse move event e on behalf of the viewed widget.

Example: dirview/dirview.cpp.

Reimplemented from QScrollView.

void QListView::contentsMousePressEvent ( QMouseEvent * e ) [virtual protected]

Processes the mouse move event e on behalf of the viewed widget.

Example: dirview/dirview.cpp.

Reimplemented from QScrollView.

void QListView::contentsMouseReleaseEvent ( QMouseEvent * e ) [virtual protected]

Processes the mouse move event e on behalf of the viewed widget.

Example: dirview/dirview.cpp.

Reimplemented from QScrollView.

void QListView::contextMenuRequested ( QListViewItem * item, const QPoint & pos, int col ) [signal]

This signal is emitted when the user invokes a context menu with the right mouse button or with special system keys, with item being the item under the mouse cursor or the current item, respectively.

pos is the position for the context menu in the global coordinate system.

col is the column on which the user pressed, or -1 if the signal was triggered by a key event.

Example: listviews/listviews.cpp.

void QListView::currentChanged ( QListViewItem * ) [signal]

This signal is emitted whenever the current item has changed (normally after the screen update). The current item is the item responsible for indicating keyboard focus.

The argument is the newly current item, or 0 if the change was to make no item current. This can happen, for example, if all items in the list view are deleted.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

See also setCurrentItem() and currentItem().

Example: listviews/listviews.cpp.

QListViewItem * QListView::currentItem () const

Returns a pointer to the currently highlighted item, or 0 if there isn't one.

See also setCurrentItem().

Examples: addressbook/centralwidget.cpp and listviews/listviews.cpp.

RenameAction QListView::defaultRenameAction () const

Returns TRUE if the list view accepts the rename operation by default; otherwise returns FALSE. See the "defaultRenameAction" property for details.

void QListView::doAutoScroll () [protected slot]

This slot handles auto-scrolling when the mouse button is pressed and the mouse is outside the widget.

void QListView::doubleClicked ( QListViewItem * item ) [signal]

This signal is emitted whenever an item is double-clicked. It's emitted on the second button press, not the second button release. item is the list view item on which the user did the double-click.

QDragObject * QListView::dragObject () [virtual protected]

If the user presses the mouse on an item and starts moving the mouse, and the items allow dragging (see QListViewItem::setDragEnabled()), this function is called to get a drag object and a drag is started unless dragObject() returns 0.

By default this function returns 0. You should reimplement it and create a QDragObject depending on the selected items.

void QListView::drawContentsOffset ( QPainter * p, int ox, int oy, int cx, int cy, int cw, int ch ) [virtual protected]

Calls QListViewItem::paintCell() and/or QListViewItem::paintBranches() for all list view items that require repainting in the cw pixels wide and ch pixels high bounding rectangle starting at position cx, cy with offset ox, oy. Uses the painter p.

Reimplemented from QScrollView.

void QListView::dropped ( QDropEvent * e ) [signal]

This signal is emitted, when a drop event occurred onto the viewport (not onto an item).

e gives you all information about the drop.

void QListView::ensureItemVisible ( const QListViewItem * i )

Ensures that item i is made visible, scrolling the list view vertically as required and also opening (expanding) any parent items if this is necessary to show the item.

See also itemRect() and QScrollView::ensureVisible().

bool QListView::eventFilter ( QObject * o, QEvent * e ) [virtual]

Redirects the event e relating to object o, for the viewport to mousePressEvent(), keyPressEvent() and friends.

Reimplemented from QScrollView.

void QListView::expanded ( QListViewItem * item ) [signal]

This signal is emitted when item has been expanded, i.e. when the children of item are shown.

See also setOpen() and collapsed().

QListViewItem * QListView::findItem ( const QString & text, int column, ComparisonFlags compare = ExactMatch | CaseSensitive ) const

Finds the first list view item in column column, that matches text and returns the item, or returns 0 of no such item could be found. Pass OR-ed together Qt::StringComparisonMode values in the compare flag, to control how the matching is performed. The default comparison mode is case-sensitive, exact match.

QListViewItem * QListView::firstChild () const

Returns the first item in this QListView. You can use its firstChild() and nextSibling() functions to traverse the entire tree of items.

Returns 0 if there is no first item.

See also itemAt(), QListViewItem::itemBelow() and QListViewItem::itemAbove().

Examples: addressbook/centralwidget.cpp and listviews/listviews.cpp.

QHeader * QListView::header () const

Returns a pointer to the QHeader object that manages this list view's columns. Please don't modify the header behind the list view's back.

You may safely call QHeader::setClickEnabled(), QHeader::setResizeEnabled(), QHeader::setMovingEnabled() and all the const QHeader functions.

Examples: listviews/listviews.cpp and qdir/qdir.cpp.

void QListView::insertItem ( QListViewItem * i ) [virtual]

Inserts item i into the list view as a top-level item. You do not need to call this unless you've called takeItem(i) or QListViewItem::takeItem(i) and need to reinsert i elsewhere.

See also QListViewItem::takeItem() and takeItem().

void QListView::invertSelection () [virtual slot]

Inverts the selection. Works only in Multi and Extended selection mode.

bool QListView::isMultiSelection () const

Returns TRUE if the list view is in multi-selection or single selection mode; otherwise returns FALSE. See the "multiSelection" property for details.

bool QListView::isOpen ( const QListViewItem * item ) const

Identical to item->isOpen(). Provided for completeness.

See also setOpen().

bool QListView::isRenaming () const

Returns whether currently an item of the listview is being renamed

bool QListView::isSelected ( const QListViewItem * i ) const

Returns TRUE if the list view item i is selected; otherwise returns FALSE.

See also QListViewItem::isSelected().

QListViewItem * QListView::itemAt ( const QPoint & viewPos ) const

Returns a pointer to the QListViewItem at viewPos. Note that viewPos is in the coordinate system of viewport(), not in the list view's own, much larger, coordinate system.

itemAt() returns 0 if there is no such item.

Note that you also get the pointer to the item if viewPos points to the root decoration (see setRootIsDecorated()) of the item. To check whether or not viewPos is on the root decoration of the item, you can do something like this:

  QListViewItem *i = itemAt( p );
  if ( i ) {
      if ( p.x() > header()->cellPos( header()->mapToActual( 0 ) ) +
             treeStepSize() * ( i->depth() + ( rootIsDecorated() ? 1 : 0) ) + itemMargin() ||
             p.x() < header()->cellPos( header()->mapToActual( 0 ) ) ) {
          ; // p is not on root decoration
      else
          ; // p is on the root decoration
  }

This might be interesting if you use this function to find out where the user clicked and if you want to start a drag (which you do not want to do if the user clicked onto the root decoration of an item).

See also itemPos() and itemRect().

int QListView::itemMargin () const

Returns the advisory item margin that list items may use. See the "itemMargin" property for details.

int QListView::itemPos ( const QListViewItem * item )

Returns the y-coordinate of item in the list view's coordinate system. This function is normally much slower than itemAt() but it works for all items, whereas itemAt() normally works only for items on the screen.

This is a thin wrapper around QListViewItem::itemPos().

See also itemAt() and itemRect().

QRect QListView::itemRect ( const QListViewItem * i ) const

Returns the rectangle on the screen that item i occupies in viewport()'s coordinates, or an invalid rectangle if i is a null pointer or is not currently visible.

The rectangle returned does not include any children of the rectangle (i.e. it uses QListViewItem::height(), rather than QListViewItem::totalHeight()). If you want the rectangle to include children you can use something like this:

    QRect r( listView->itemRect( item ) );
    r.setHeight( (QCOORD)(QMIN( item->totalHeight(),
                                listView->viewport->height() - r.y() ) ) )

Note the way it avoids too-high rectangles. totalHeight() can be much larger than the window system's coordinate system allows.

itemRect() is comparatively slow. It's best to call it only for items that are probably on-screen.

void QListView::itemRenamed ( QListViewItem * item, int col, const QString & text ) [signal]

This signal is emitted when item has been renamed to text, e.g. by in in-place renaming, in column col.

void QListView::itemRenamed ( QListViewItem * item, int col ) [signal]

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

This signal is emitted when item has been renamed, e.g. by in-place renaming, in column col.

QListViewItem * QListView::lastItem () const

Returns the last item in the list view tree.

Returns 0 if there are no items in the QListView.

This function is slow.

void QListView::mouseButtonClicked ( int button, QListViewItem * item, const QPoint & pos, int c ) [signal]

This signal is emitted whenever the user clicks (mouse pressed and mouse released) in the list view at position pos. button is the mouse button that the user pressed, item is the pointer to the clicked list view item or 0 if the user didn't click on an item. If item is not 0, c is the list view column into which the user pressed; if item is 0 c's value is undefined.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

void QListView::mouseButtonPressed ( int button, QListViewItem * item, const QPoint & pos, int c ) [signal]

This signal is emitted whenever the user pressed the mouse button in the list view at position pos. button is the mouse button which the user pressed, item is the pointer to the pressed list view item or 0 if the user didn't press on an item. If item is not 0, c is the list view column into which the user pressed; if item is 0 c's value is undefined.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

void QListView::onItem ( QListViewItem * i ) [signal]

This signal is emitted when the user moves the mouse cursor onto the item i, similar to the QWidget::enterEvent() function.

void QListView::onViewport () [signal]

This signal is emitted when the user moves the mouse cursor from an item to an empty part of the list view.

void QListView::paintEmptyArea ( QPainter * p, const QRect & rect ) [virtual protected]

Paints rect so that it looks like empty background using painter p. rect is is widget coordinates, ready to be fed to p.

The default function fills rect with the viewport()->backgroundBrush()

void QListView::pressed ( QListViewItem * item ) [signal]

This signal is emitted whenever the user presses the mouse button in a list view. item is the pointer to the list view item on which the user pressed the mouse button, or 0 if the user didn't press the mouse on an item.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

void QListView::pressed ( QListViewItem * item, const QPoint & pnt, int c ) [signal]

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

This signal is emitted whenever the user presses the mouse button in a list view. item is the pointer to the list view item on which the user pressed the mouse button, or 0 if the user didn't press the mouse on an item. pnt is the position of the mouse cursor, and c is the column where the mouse cursor was when the user pressed the mouse button.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

void QListView::removeColumn ( int index ) [virtual]

Removes the column at position index.

void QListView::removeItem ( QListViewItem * item ) [virtual]

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

This function has been renamed takeItem().

void QListView::repaintItem ( const QListViewItem * item ) const

Repaints item on the screen if item is currently visible. Takes care to avoid multiple repaints.

void QListView::resizeEvent ( QResizeEvent * e ) [virtual protected]

Ensures that the header is correctly sized and positioned when the resize event e occurs.

ResizeMode QListView::resizeMode () const

Returns TRUE if all, none or the last column should be resized; otherwise returns FALSE. See the "resizeMode" property for details.

void QListView::returnPressed ( QListViewItem * ) [signal]

This signal is emitted when Enter or Return is pressed. The argument is the currentItem().

void QListView::rightButtonClicked ( QListViewItem *, const QPoint &, int ) [signal]

This signal is emitted when the right button is clicked (i.e. when it's released). The arguments are the relevant QListViewItem (may be 0), the point in global coordinates and the relevant column (or -1 if the click was outside the list).

void QListView::rightButtonPressed ( QListViewItem *, const QPoint &, int ) [signal]

This signal is emitted when the right button is pressed. Arguments are then the relevant QListViewItem (may be 0), the point in global coordinates and the relevant column (or -1 if the click was outside the list).

bool QListView::rootIsDecorated () const

Returns TRUE if the list view show open/close signs on root items; otherwise returns FALSE. See the "rootIsDecorated" property for details.

void QListView::selectAll ( bool select ) [virtual slot]

If select is TRUE, all items get selected; otherwise all items get unselected. This works only in the selection modes Multi and Extended. In Single and NoSelection mode the selection of the current item is just set to select.

QListViewItem * QListView::selectedItem () const

Returns a pointer to the selected item if the list view is in single-selection mode and an item is selected.

If no items are selected or the list view is in multi-selection mode this function returns 0.

See also setSelected() and multiSelection.

void QListView::selectionChanged () [signal]

This signal is emitted whenever the set of selected items has changed (normally before the screen update). It is available both in Single selection and Multi selection mode but is most useful in Multi selection mode.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

See also setSelected() and QListViewItem::setSelected().

Example: listviews/listviews.cpp.

void QListView::selectionChanged ( QListViewItem * ) [signal]

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

This signal is emitted whenever the selected item has changed in Single selection mode (normally after the screen update). The argument is the newly selected item.

The no argument overload of this signal is more useful in Multi selection mode.

Note that you may not delete any QListViewItem objects in slots connected to this signal.

See also setSelected(), QListViewItem::setSelected() and currentChanged().

SelectionMode QListView::selectionMode () const

Returns the list view's multi-selection mode. See the "selectionMode" property for details.

void QListView::setAllColumnsShowFocus ( bool ) [virtual]

Sets whether items should show keyboard focus using all columns. See the "allColumnsShowFocus" property for details.

void QListView::setColumnAlignment ( int column, int align ) [virtual]

Sets column column's alignment to align. The alignment is ultimately passed to QListViewItem::paintCell() for each item in the view.

See also Qt::AlignmentFlags.

Example: listviews/listviews.cpp.

void QListView::setColumnText ( int column, const QString & label ) [virtual]

Sets the heading of column column to label. The leftmost column is 0.

See also columnText().

void QListView::setColumnText ( int column, const QIconSet & iconset, const QString & label ) [virtual]

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

Sets the heading of column column to iconset and label. The leftmost column is 0.

See also columnText().

void QListView::setColumnWidth ( int column, int w ) [virtual]

Sets the width of column column to w pixels. Note that if the column has a WidthMode other than Manual, this width setting may be subsequently overridden. The leftmost column is 0.

See also columnWidth().

void QListView::setColumnWidthMode ( int c, WidthMode mode ) [virtual]

Sets column c's width mode to mode. The default depends on whether the width argument to addColumn was positive or negative.

See also QListViewItem::width().

void QListView::setCurrentItem ( QListViewItem * i ) [virtual]

Sets item i to be the current highlighted item and repaints appropriately. This highlighted item is used for keyboard navigation and focus indication; it doesn't mean anything else, e.g. it is different from selection.

See also currentItem() and setSelected().

Example: listviews/listviews.cpp.

void QListView::setDefaultRenameAction ( RenameAction a ) [virtual]

Sets whether the list view accepts the rename operation by default to a. See the "defaultRenameAction" property for details.

void QListView::setItemMargin ( int ) [virtual]

Sets the advisory item margin that list items may use. See the "itemMargin" property for details.

void QListView::setMultiSelection ( bool enable ) [virtual]

Sets whether the list view is in multi-selection or single selection mode to enable. See the "multiSelection" property for details.

void QListView::setOpen ( QListViewItem * item, bool open ) [virtual]

Sets item to be open if open is TRUE and item is expandable, and to be closed if open is FALSE. Repaints accordingly.

See also QListViewItem::setOpen() and QListViewItem::setExpandable().

void QListView::setResizeMode ( ResizeMode m ) [virtual]

Sets whether all, none or the last column should be resized to m. See the "resizeMode" property for details.

void QListView::setRootIsDecorated ( bool ) [virtual]

Sets whether the list view show open/close signs on root items. See the "rootIsDecorated" property for details.

void QListView::setSelected ( QListViewItem * item, bool selected ) [virtual]

If selected is TRUE the item is selected; otherwise it is unselected.

If the list view is in Single selection mode and selected is TRUE, the currently selected item is unselected and item is made current. Unlike QListViewItem::setSelected(), this function updates the list view as necessary and emits the selectionChanged() signals.

See also isSelected(), multiSelection, multiSelection and setCurrentItem().

Example: listviews/listviews.cpp.

void QListView::setSelectionMode ( SelectionMode mode )

Sets the list view's multi-selection mode to mode. See the "selectionMode" property for details.

void QListView::setShowSortIndicator ( bool show ) [virtual]

Sets whether the list view header should display a sort indicator to show. See the "showSortIndicator" property for details.

void QListView::setShowToolTips ( bool b ) [virtual]

Sets whether this list view should show tooltips for truncated column texts to b. See the "showToolTips" property for details.

void QListView::setSorting ( int column, bool ascending = TRUE ) [virtual]

Sets the list view to be sorted by column and in ascending order if ascending is TRUE or descending order if it is FALSE.

If column is -1, sorting is disabled and the user cannot sort columns by clicking on the column headers. If column is larger than the number of columns the user has to click on a column header to sort the list view.

void QListView::setTreeStepSize ( int ) [virtual]

Sets the number of pixels a child is offset from its parent. See the "treeStepSize" property for details.

bool QListView::showSortIndicator () const

Returns TRUE if the list view header should display a sort indicator; otherwise returns FALSE. See the "showSortIndicator" property for details.

bool QListView::showToolTips () const

Returns TRUE if this list view should show tooltips for truncated column texts; otherwise returns FALSE. See the "showToolTips" property for details.

void QListView::sort () [virtual]

(Re)sorts the list view using the last sorting configuration (sort column and ascending/descending).

void QListView::spacePressed ( QListViewItem * ) [signal]

This signal is emitted when Space is pressed. The argument is currentItem().

void QListView::startDrag () [virtual protected]

Starts a drag.

void QListView::takeItem ( QListViewItem * i ) [virtual]

Removes item i from the list view; i must be a top-level item. The warnings regarding QListViewItem::takeItem() apply to this function, too.

See also insertItem().

int QListView::treeStepSize () const

Returns the number of pixels a child is offset from its parent. See the "treeStepSize" property for details.

void QListView::triggerUpdate () [slot]

Triggers a size, geometry and content update during the next iteration of the event loop. Ensures that there'll be just one update to avoid flicker.

void QListView::updateContents () [protected slot]

Updates the sizes of the viewport, header, scroll bars and so on. Don't call this directly; call triggerUpdate() instead.

Property Documentation

bool allColumnsShowFocus

This property holds whether items should show keyboard focus using all columns.

If this property is TRUE all columns will show focus and selection states, otherwise only column 0 will show focus.

The default is FALSE.

Setting this to TRUE if it's not necessary may cause noticeable flicker.

Set this property's value with setAllColumnsShowFocus() and get this property's value with allColumnsShowFocus().

int childCount

This property holds the number of parentless (top level) QListViewItem objects in this QListView.

Represents the current number of parentless (top level) QListViewItem objects in this QListView, like QListViewItem::childCount() returns the number of child items for a QListViewItem.

See also QListViewItem::childCount().

Get this property's value with childCount().

int columns

This property holds the number of columns in this list view.

Get this property's value with columns().

See also addColumn() and removeColumn().

RenameAction defaultRenameAction

This property holds whether the list view accepts the rename operation by default.

If this property is Accept, and the user renames an item and the editor looses focus (without the user pressing Enter), the item will still be renamed. If the property's value is Reject, the item will not be renamed unless the user presses Enter. The default is Reject.

Set this property's value with setDefaultRenameAction() and get this property's value with defaultRenameAction().

int itemMargin

This property holds the advisory item margin that list items may use.

The item margin defaults to one pixel and is the margin between the item's edges and the area where it draws its contents. QListViewItem::paintFocus() draws in the margin.

See also QListViewItem::paintCell().

Set this property's value with setItemMargin() and get this property's value with itemMargin().

bool multiSelection

This property holds whether the list view is in multi-selection or single selection mode.

If you enable multi-selection mode, it is possible to specify whether or not this mode should be extended. Extended means that the user can select multiple items only when pressing the Shift or Ctrl key at the same time.

The default selection mode is Single.

See also selectionMode.

Set this property's value with setMultiSelection() and get this property's value with isMultiSelection().

ResizeMode resizeMode

This property holds whether all, none or the last column should be resized.

Specifies whether all, none or the last column should be resized to fit the full width of the listview. The values for this property can be one of the following: NoColumn (the default), AllColumns or LastColumn.

See also QHeader and header().

Set this property's value with setResizeMode() and get this property's value with resizeMode().

bool rootIsDecorated

This property holds whether the list view show open/close signs on root items.

Open/close signs are small + or - symbols in windows style, or arrows in Motif style. The default is FALSE.

Set this property's value with setRootIsDecorated() and get this property's value with rootIsDecorated().

SelectionMode selectionMode

This property holds the list view's multi-selection mode.

The mode can be Single (the default), Extended, Multi or NoSelection.

See also multiSelection.

Set this property's value with setSelectionMode() and get this property's value with selectionMode().

bool showSortIndicator

This property holds whether the list view header should display a sort indicator.

If this property is TRUE, an arrow is drawn in the header of the list view to indicate the sort order of the list view contents. The arrow will be drawn in the correct column and will point up or down, depending on the current sort direction. The default is FALSE (don't show an indicator).

See also QHeader::setSortIndicator().

Set this property's value with setShowSortIndicator() and get this property's value with showSortIndicator().

bool showToolTips

This property holds whether this list view should show tooltips for truncated column texts.

The default is TRUE.

Set this property's value with setShowToolTips() and get this property's value with showToolTips().

int treeStepSize

This property holds the number of pixels a child is offset from its parent.

The default is 20 pixels.

Of course, this property is only meaningful for hierarchical list views.

Set this property's value with setTreeStepSize() and get this property's value with treeStepSize().

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


qlistview.h Include File

qlistview.h

This is the verbatim text of the qlistview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qlistview.h   3.0.5   edited Mar 21 18:07 $
**
** Definition of QListView widget class
**
** Created : 970809
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLISTVIEW_H
#define QLISTVIEW_H

#ifndef QT_H
#include "qscrollview.h"
#endif // QT_H

#ifndef QT_NO_LISTVIEW

class QPixmap;
class QFont;
class QHeader;
class QIconSet;

class QListView;
struct QListViewPrivate;
struct QCheckListItemPrivate;
class QListViewItemIterator;
class QDragObject;
class QMimeSource;
class QLineEdit;
class QListViewToolTip;

class Q_EXPORT QListViewItem : public Qt
{
    friend class QListViewItemIterator;
    friend class QListViewToolTip;
#if defined(Q_CC_MSVC)
    friend class QListViewItem;
#endif

public:
    QListViewItem( QListView * parent );
    QListViewItem( QListViewItem * parent );
    QListViewItem( QListView * parent, QListViewItem * after );
    QListViewItem( QListViewItem * parent, QListViewItem * after );

    QListViewItem( QListView * parent,
           QString,     QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null );
    QListViewItem( QListViewItem * parent,
           QString,     QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null );

    QListViewItem( QListView * parent, QListViewItem * after,
           QString,     QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null );
    QListViewItem( QListViewItem * parent, QListViewItem * after,
           QString,     QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null,
           QString = QString::null, QString = QString::null );
    virtual ~QListViewItem();

    virtual void insertItem( QListViewItem * );
    virtual void takeItem( QListViewItem * );
    virtual void removeItem( QListViewItem *item ) { takeItem( item ); } //obsolete, use takeItem instead

    int height() const;
    virtual void invalidateHeight();
    int totalHeight() const;
    virtual int width( const QFontMetrics&,
               const QListView*, int column) const;
    void widthChanged(int column=-1) const;
    int depth() const;

    virtual void setText( int, const QString &);
    virtual QString text( int ) const;

    virtual void setPixmap( int, const QPixmap & );
    virtual const QPixmap * pixmap( int ) const;

    virtual QString key( int, bool ) const;
    virtual int compare( QListViewItem *i, int col, bool ) const;
    virtual void sortChildItems( int, bool );

    int childCount() const { return nChildren; }

    bool isOpen() const { return open; }
    virtual void setOpen( bool );
    virtual void setup();

    virtual void setSelected( bool );
    bool isSelected() const { return selected; }

    virtual void paintCell( QPainter *, const QColorGroup & cg,
                int column, int width, int alignment );
    virtual void paintBranches( QPainter * p, const QColorGroup & cg,
                int w, int y, int h );
    virtual void paintFocus( QPainter *, const QColorGroup & cg,
                 const QRect & r );

    QListViewItem * firstChild() const;
    QListViewItem * nextSibling() const { return siblingItem; }
    QListViewItem * parent() const;

    QListViewItem * itemAbove();
    QListViewItem * itemBelow();

    int itemPos() const;

    QListView *listView() const;

    virtual void setSelectable( bool enable );
    bool isSelectable() const { return selectable && enabled; }

    virtual void setExpandable( bool );
    bool isExpandable() const { return expandable; }

    void repaint() const;

    virtual void sort();
    void moveItem( QListViewItem *after );

    virtual void setDragEnabled( bool allow );
    virtual void setDropEnabled( bool allow );
    bool dragEnabled() const;
    bool dropEnabled() const;
    virtual bool acceptDrop( const QMimeSource *mime ) const;

    void setVisible( bool b );
    bool isVisible() const;

    virtual void setRenameEnabled( int col, bool b );
    bool renameEnabled( int col ) const;
    virtual void startRename( int col );

    virtual void setEnabled( bool b );
    bool isEnabled() const;

    virtual int rtti() const;
    static int RTTI;

    virtual void setMultiLinesEnabled( bool b );
    bool multiLinesEnabled() const;

protected:
    virtual void enforceSortOrder() const;
    virtual void setHeight( int );
    virtual void activate();

    bool activatedPos( QPoint & );
#ifndef QT_NO_DRAGANDDROP
    virtual void dropped( QDropEvent *e );
#endif
    virtual void dragEntered();
    virtual void dragLeft();
    virtual void okRename( int col );
    virtual void cancelRename( int col );

    void ignoreDoubleClick();

private:
    void init();
    void moveToJustAfter( QListViewItem * );
    void enforceSortOrderBackToRoot();

    int ownHeight;
    int maybeTotalHeight;
    int nChildren;

    uint lsc: 14;
    uint lso: 1;
    uint open : 1;
    uint selected : 1;
    uint selectable: 1;
    uint configured: 1;
    uint expandable: 1;
    uint is_root: 1;
    uint allow_drag : 1;
    uint allow_drop : 1;
    uint visible : 1;
    uint enabled : 1;
    uint mlenabled : 1;

    QListViewItem * parentItem;
    QListViewItem * siblingItem;
    QListViewItem * childItem;
    QLineEdit *renameBox;
    int renameCol;

    void * columns;

    friend class QListView;
};

class QCheckListItem;

class Q_EXPORT QListView: public QScrollView
{
    friend class QListViewItemIterator;
    friend class QListViewItem;
    friend class QCheckListItem;
    friend class QListViewToolTip;

    Q_OBJECT
    Q_ENUMS( SelectionMode ResizeMode RenameAction )
    Q_PROPERTY( int columns READ columns )
    Q_PROPERTY( bool multiSelection READ isMultiSelection WRITE setMultiSelection DESIGNABLE false )
    Q_PROPERTY( SelectionMode selectionMode READ selectionMode WRITE setSelectionMode )
    Q_PROPERTY( int childCount READ childCount )
    Q_PROPERTY( bool allColumnsShowFocus READ allColumnsShowFocus WRITE setAllColumnsShowFocus )
    Q_PROPERTY( bool showSortIndicator READ showSortIndicator WRITE setShowSortIndicator )
    Q_PROPERTY( int itemMargin READ itemMargin WRITE setItemMargin )
    Q_PROPERTY( bool rootIsDecorated READ rootIsDecorated WRITE setRootIsDecorated )
    Q_PROPERTY( bool showToolTips READ showToolTips WRITE setShowToolTips )
    Q_PROPERTY( ResizeMode resizeMode READ resizeMode WRITE setResizeMode )
    Q_PROPERTY( int treeStepSize READ treeStepSize WRITE setTreeStepSize )
    Q_PROPERTY( RenameAction defaultRenameAction READ defaultRenameAction WRITE setDefaultRenameAction )

public:
    QListView( QWidget* parent=0, const char* name=0, WFlags f = 0 );
    ~QListView();

    int treeStepSize() const;
    virtual void setTreeStepSize( int );

    virtual void insertItem( QListViewItem * );
    virtual void takeItem( QListViewItem * );
    virtual void removeItem( QListViewItem *item ) { takeItem( item ); } // obsolete, use takeItem instead

    QHeader * header() const;

    virtual int addColumn( const QString &label, int size = -1);
    virtual int addColumn( const QIconSet& iconset, const QString &label, int size = -1);
    virtual void removeColumn( int index );
    virtual void setColumnText( int column, const QString &label );
    virtual void setColumnText( int column, const QIconSet& iconset, const QString &label );
    QString columnText( int column ) const;
    virtual void setColumnWidth( int column, int width );
    int columnWidth( int column ) const;
    enum WidthMode { Manual, Maximum };
    virtual void setColumnWidthMode( int column, WidthMode );
    WidthMode columnWidthMode( int column ) const;
    int columns() const;

    virtual void setColumnAlignment( int, int );
    int columnAlignment( int ) const;

    void show();

    QListViewItem * itemAt( const QPoint & screenPos ) const;
    QRect itemRect( const QListViewItem * ) const;
    int itemPos( const QListViewItem * );

    void ensureItemVisible( const QListViewItem * );

    void repaintItem( const QListViewItem * ) const;

    virtual void setMultiSelection( bool enable );
    bool isMultiSelection() const;

    enum SelectionMode { Single, Multi, Extended, NoSelection  };
    void setSelectionMode( SelectionMode mode );
    SelectionMode selectionMode() const;

    virtual void clearSelection();
    virtual void setSelected( QListViewItem *, bool );
    bool isSelected( const QListViewItem * ) const;
    QListViewItem * selectedItem() const;
    virtual void setOpen( QListViewItem *, bool );
    bool isOpen( const QListViewItem * ) const;

    virtual void setCurrentItem( QListViewItem * );
    QListViewItem * currentItem() const;

    QListViewItem * firstChild() const;
    QListViewItem * lastItem() const;

    int childCount() const;

    virtual void setAllColumnsShowFocus( bool );
    bool allColumnsShowFocus() const;

    virtual void setItemMargin( int );
    int itemMargin() const;

    virtual void setRootIsDecorated( bool );
    bool rootIsDecorated() const;

    virtual void setSorting( int column, bool ascending = TRUE );
    virtual void sort();

    virtual void setFont( const QFont & );
    virtual void setPalette( const QPalette & );

    bool eventFilter( QObject * o, QEvent * );

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    virtual void setShowSortIndicator( bool show );
    bool showSortIndicator() const;
    virtual void setShowToolTips( bool b );
    bool showToolTips() const;

    enum ResizeMode { NoColumn, AllColumns, LastColumn };
    virtual void setResizeMode( ResizeMode m );
    ResizeMode resizeMode() const;

    QListViewItem * findItem( const QString& text, int column, ComparisonFlags compare = ExactMatch | CaseSensitive ) const;

    enum RenameAction { Accept, Reject };
    virtual void setDefaultRenameAction( RenameAction a );
    RenameAction defaultRenameAction() const;
    bool isRenaming() const;

public slots:
    virtual void clear();
    virtual void invertSelection();
    virtual void selectAll( bool select );
    void triggerUpdate();
    void setContentsPos( int x, int y );

signals:
    void selectionChanged();
    void selectionChanged( QListViewItem * );
    void currentChanged( QListViewItem * );
    void clicked( QListViewItem * );
    void clicked( QListViewItem *, const QPoint &, int );
    void pressed( QListViewItem * );
    void pressed( QListViewItem *, const QPoint &, int );

    void doubleClicked( QListViewItem * );
    void returnPressed( QListViewItem * );
    void spacePressed( QListViewItem * );
    void rightButtonClicked( QListViewItem *, const QPoint&, int );
    void rightButtonPressed( QListViewItem *, const QPoint&, int );
    void mouseButtonPressed( int, QListViewItem *, const QPoint& , int );
    void mouseButtonClicked( int, QListViewItem *,  const QPoint&, int );

    void contextMenuRequested( QListViewItem *, const QPoint &, int );

    void onItem( QListViewItem *item );
    void onViewport();

    void expanded( QListViewItem *item );
    void collapsed( QListViewItem *item );
#ifndef QT_NO_DRAGANDDROP
    void dropped( QDropEvent *e );
#endif
    void itemRenamed( QListViewItem *item, int col, const QString & );
    void itemRenamed( QListViewItem *item, int col  );

protected:
    void contentsMousePressEvent( QMouseEvent * e );
    void contentsMouseReleaseEvent( QMouseEvent * e );
    void contentsMouseMoveEvent( QMouseEvent * e );
    void contentsMouseDoubleClickEvent( QMouseEvent * e );
    void contentsContextMenuEvent( QContextMenuEvent * e );
#ifndef QT_NO_DRAGANDDROP
    void contentsDragEnterEvent( QDragEnterEvent *e );
    void contentsDragMoveEvent( QDragMoveEvent *e );
    void contentsDragLeaveEvent( QDragLeaveEvent *e );
    void contentsDropEvent( QDropEvent *e );
    virtual QDragObject *dragObject();
    virtual void startDrag();
#endif

    void focusInEvent( QFocusEvent * e );
    void focusOutEvent( QFocusEvent * e );

    void keyPressEvent( QKeyEvent *e );

    void resizeEvent( QResizeEvent *e );
    void viewportResizeEvent( QResizeEvent *e );

    void showEvent( QShowEvent * );

    void drawContentsOffset( QPainter *, int ox, int oy,
                 int cx, int cy, int cw, int ch );

    virtual void paintEmptyArea( QPainter *, const QRect & );
    void styleChange( QStyle& );
    void windowActivationChange( bool );

protected slots:
    void updateContents();
    void doAutoScroll();

private slots:
    void changeSortColumn( int );
    void updateDirtyItems();
    void makeVisible();
    void handleSizeChange( int, int, int );
    void startRename();

private:
    void contentsMousePressEventEx( QMouseEvent * e );
    void init();
    void updateGeometries();
    void buildDrawableList() const;
    void reconfigureItems();
    void widthChanged(const QListViewItem*, int c);
    void handleItemChange( QListViewItem *old, bool shift, bool control );
    void selectRange( QListViewItem *from, QListViewItem *to, bool invert, bool includeFirst, bool clearSel = FALSE );

    QListViewPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QListView( const QWidget & );
    QListView &operator=( const QWidget & );
#endif
};

class Q_EXPORT QCheckListItem : public QListViewItem
{
public:
    enum Type { RadioButton, CheckBox, Controller };

    QCheckListItem( QCheckListItem *parent, const QString &text,
            Type = Controller );
    QCheckListItem( QListViewItem *parent, const QString &text,
            Type = Controller );
    QCheckListItem( QListView *parent, const QString &text,
            Type = Controller );
    QCheckListItem( QListViewItem *parent, const QString &text,
            const QPixmap & );
    QCheckListItem( QListView *parent, const QString &text,
            const QPixmap & );
    ~QCheckListItem();

    void paintCell( QPainter *,  const QColorGroup & cg,
            int column, int width, int alignment );
    virtual void paintFocus( QPainter *, const QColorGroup & cg,
                 const QRect & r );
    int width( const QFontMetrics&, const QListView*, int column) const;
    void setup();

    virtual void setOn( bool );
    bool isOn() const { return on; }
    Type type() const { return myType; }
    QString text() const { return QListViewItem::text( 0 ); }
    QString text( int n ) const { return QListViewItem::text( n ); }

    int rtti() const;
    static int RTTI;

protected:
    void activate();
    void turnOffChild();
    virtual void stateChange( bool );

private:
    void init();
    Type myType;
    bool on;
    QCheckListItem *exclusive;
};

class Q_EXPORT QListViewItemIterator
{
    friend struct QListViewPrivate;
    friend class QListView;
    friend class QListViewItem;

public:
    QListViewItemIterator();
    QListViewItemIterator( QListViewItem *item );
    QListViewItemIterator( const QListViewItemIterator &it );
    QListViewItemIterator( QListView *lv );

    QListViewItemIterator &operator=( const QListViewItemIterator &it );

    ~QListViewItemIterator();

    QListViewItemIterator &operator++();
    const QListViewItemIterator operator++( int );
    QListViewItemIterator &operator+=( int j );

    QListViewItemIterator &operator--();
    const QListViewItemIterator operator--( int );
    QListViewItemIterator &operator-=( int j );

    QListViewItem *current() const;

protected:
    QListViewItem *curr;
    QListView *listView;

private:
    void addToListView();
    void currentRemoved();

};

#endif // QT_NO_LISTVIEW

#endif // QLISTVIEW_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QListView Member List

Complete Member List for QListView

This is the complete list of member functions for QListView, including inherited members.

  • QListView()
  • ~QListView()
  • acceptDrops()
  • addChild()
  • addColumn()
  • adjustSize()
  • allColumnsShowFocus()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • caption()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childCount()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearSelection()
  • clearWFlags()
  • clicked()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • collapsed()
  • colorGroup()
  • columnAlignment()
  • columnText()
  • columnWidth()
  • columnWidthMode()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • contextMenuRequested()
  • cornerWidget()
  • create()
  • currentChanged()
  • currentItem()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • defaultRenameAction()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doAutoScroll()
  • doubleClicked()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • dragObject()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dropped()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureItemVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • expanded()
  • find()
  • findItem()
  • firstChild()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • header()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insertItem()
  • installEventFilter()
  • invertSelection()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isMultiSelection()
  • isOpen()
  • isPopup()
  • isRenaming()
  • isSelected()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • itemAt()
  • itemMargin()
  • itemPos()
  • itemRect()
  • itemRenamed()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • lastItem()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseButtonClicked()
  • mouseButtonPressed()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • onItem()
  • onViewport()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEmptyArea()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeColumn()
  • removeEventFilter()
  • removeItem()
  • repaint()
  • repaintContents()
  • repaintItem()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizeMode()
  • resizePolicy()
  • returnPressed()
  • rightButtonClicked()
  • rightButtonPressed()
  • rightMargin()
  • rootIsDecorated()
  • scroll()
  • scrollBy()
  • selectAll()
  • selectedItem()
  • selectionChanged()
  • selectionMode()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAllColumnsShowFocus()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setColumnAlignment()
  • setColumnText()
  • setColumnWidth()
  • setColumnWidthMode()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentItem()
  • setCursor()
  • setDefaultRenameAction()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItemMargin()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMultiSelection()
  • setName()
  • setOpen()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeMode()
  • setResizePolicy()
  • setRootIsDecorated()
  • setSelected()
  • setSelectionMode()
  • setShowSortIndicator()
  • setShowToolTips()
  • setSizeIncrement()
  • setSizePolicy()
  • setSorting()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setTreeStepSize()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showSortIndicator()
  • showToolTips()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sort()
  • spacePressed()
  • stackUnder()
  • startDrag()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • takeItem()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • treeStepSize()
  • triggerUpdate()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QListViewItem Class

QListViewItem Class Reference

The QListViewItem class implements a list view item. More...

#include <qlistview.h>

Inherits Qt.

Inherited by QCheckListItem.

List of all member functions.

Public Members

  • QListViewItem ( QListView * parent )
  • QListViewItem ( QListViewItem * parent )
  • QListViewItem ( QListView * parent, QListViewItem * after )
  • QListViewItem ( QListViewItem * parent, QListViewItem * after )
  • QListViewItem ( QListView * parent, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )
  • QListViewItem ( QListViewItem * parent, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )
  • QListViewItem ( QListView * parent, QListViewItem * after, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )
  • QListViewItem ( QListViewItem * parent, QListViewItem * after, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )
  • virtual ~QListViewItem ()
  • virtual void insertItem ( QListViewItem * newChild )
  • virtual void takeItem ( QListViewItem * item )
  • virtual void removeItem ( QListViewItem * item ) (obsolete)
  • int height () const
  • virtual void invalidateHeight ()
  • int totalHeight () const
  • virtual int width ( const QFontMetrics & fm, const QListView * lv, int c ) const
  • void widthChanged ( int c = -1 ) const
  • int depth () const
  • virtual void setText ( int column, const QString & text )
  • virtual QString text ( int column ) const
  • virtual void setPixmap ( int column, const QPixmap & pm )
  • virtual const QPixmap * pixmap ( int column ) const
  • virtual QString key ( int column, bool ascending ) const
  • virtual int compare ( QListViewItem * i, int col, bool ascending ) const
  • virtual void sortChildItems ( int column, bool ascending )
  • int childCount () const
  • bool isOpen () const
  • virtual void setOpen ( bool o )
  • virtual void setup ()
  • virtual void setSelected ( bool s )
  • bool isSelected () const
  • virtual void paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align )
  • virtual void paintBranches ( QPainter * p, const QColorGroup & cg, int w, int y, int h )
  • virtual void paintFocus ( QPainter * p, const QColorGroup & cg, const QRect & r )
  • QListViewItem * firstChild () const
  • QListViewItem * nextSibling () const
  • QListViewItem * parent () const
  • QListViewItem * itemAbove ()
  • QListViewItem * itemBelow ()
  • int itemPos () const
  • QListView * listView () const
  • virtual void setSelectable ( bool enable )
  • bool isSelectable () const
  • virtual void setExpandable ( bool enable )
  • bool isExpandable () const
  • void repaint () const
  • virtual void sort ()
  • void moveItem ( QListViewItem * after )
  • virtual void setDragEnabled ( bool allow )
  • virtual void setDropEnabled ( bool allow )
  • bool dragEnabled () const
  • bool dropEnabled () const
  • virtual bool acceptDrop ( const QMimeSource * mime ) const
  • void setVisible ( bool b )
  • bool isVisible () const
  • virtual void setRenameEnabled ( int col, bool b )
  • bool renameEnabled ( int col ) const
  • virtual void startRename ( int col )
  • virtual void setEnabled ( bool b )
  • bool isEnabled () const
  • virtual int rtti () const
  • virtual void setMultiLinesEnabled ( bool b )
  • bool multiLinesEnabled () const

Protected Members

  • virtual void enforceSortOrder () const
  • virtual void setHeight ( int height )
  • virtual void activate ()
  • bool activatedPos ( QPoint & pos )
  • virtual void dropped ( QDropEvent * e )
  • virtual void dragEntered ()
  • virtual void dragLeft ()
  • virtual void okRename ( int col )
  • virtual void cancelRename ( int col )

Detailed Description

The QListViewItem class implements a list view item.

A list view item is a multi-column object capable of displaying itself in a QListView. Its design has the following main goals:

  • Work quickly and well for large sets of data.
  • Be easy to use in the simple case.

The easiest way to use QListViewItem is to construct one with a few constant strings. This creates an item that is a child of parent with two fixed-content strings, and discards the pointer to it:

    (void) new QListViewItem( parent, "first column", "second column" );

This object will be deleted when parent is deleted, as for QObjects.

The parent is either another QListViewItem or a QListView. If the parent is a QListView, this item is a top-level item within that QListView. If the parent is another QListViewItem, this item becomes a child of that list view item.

If you keep the pointer, you can set or change the texts using setText(), add pixmaps using setPixmap(), change its mode using setSelectable(), setSelected(), setOpen() and setExpandable(). You'll also be able to change its height using setHeight(), and traverse the tree. There's no need to retain the pointer however, since you can get a pointer to any QListViewItem in a QListView using QListView::selectedItem(), QListView::currentItem(), QListView::firstChild(), QListView::lastItem(), QListView::findItem().

QCheckListItems are list view items that have a checkbox or radio button and can be used in place of QListViewItems.

You can traverse the tree as if it were a doubly-linked list using itemAbove() and itemBelow(); they return pointers to the items directly above and below this item on the screen (even if none of the three are actually visible at the moment).

You can also traverse it as a tree by using parent(), firstChild(), and nextSibling().

Example:

    QListViewItem * myChild = myItem->firstChild();
    while( myChild ) {
        doSomething( myChild );
        myChild = myChild->nextSibling();
    }

There is also an interator class to traverse a tree of list view items. To iterate over all items of a list view, do the following:

    QListViewItemIterator it( listview );
    for ( ; it.current(); ++it )
      doSomething( it.current() ); // it.current() is a QListViewItem*

Note that the order of the children will change when the sorting order changes and is undefined if the items are not visible. You can, however, call enforceSortOrder() at any time; QListView will always call it before it needs to show an item.

Many programs will need to reimplement QListViewItem. The most commonly reimplemented functions are:

  • text() returns the text in a column. Many subclasses will compute that on the fly.
  • key() is used for sorting. The default key() simply calls text(), but judicious use of key can be used to sort by date, for example (as QFileDialog does).
  • setup() is called before showing the item and whenever the font changes, for example.
  • activate() is called whenever the user clicks on the item or presses space when the item is the currently highlighted item.

Some subclasses call setExpandable(TRUE) even when they have no children, and populate themselves when setup() or setOpen(TRUE) is called. The dirview/dirview.cpp example program uses this technique to start up quickly: The files and subdirectories in a directory aren't inserted into the tree until they're actually needed.

List View Items

See also QCheckListItem, QListView and Advanced Widgets.

Member Function Documentation

QListViewItem::QListViewItem ( QListView * parent )

Constructs a new top-level list view item in the QListView parent.

QListViewItem::QListViewItem ( QListViewItem * parent )

Constructs a new list view item that is a child of parent and first in the parent's list of children.

QListViewItem::QListViewItem ( QListView * parent, QListViewItem * after )

Constructs an empty list view item that is a child of parent and is after after in the parent's list of children. Since parent is a QListView the item will be a top-level item.

QListViewItem::QListViewItem ( QListViewItem * parent, QListViewItem * after )

Constructs an empty list view item that is a child of parent and is after after in the parent's list of children.

QListViewItem::QListViewItem ( QListView * parent, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )

Constructs a new list view item in the QListView parent, parent, with up to eight constant strings label1, label2, label3, label4, label5, label6, label7 and label8 defining its column contents.

See also setText().

QListViewItem::QListViewItem ( QListViewItem * parent, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )

Constructs a new list view item as a child of the QListViewItem parent with optional constant strings label1, label2, label3, label4, label5, label6, label7 and label8 as column contents.

See also setText().

QListViewItem::QListViewItem ( QListView * parent, QListViewItem * after, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )

Constructs a new list view item in the QListView parent that is included after item after and can contain up to eight column texts label1, label2, label3, label4, label5, label6, label7 andlabel8.

Note that the order is changed according to QListViewItem::key() unless the list view's sorting is disabled using QListView::setSorting( -1 ).

See also setText().

QListViewItem::QListViewItem ( QListViewItem * parent, QListViewItem * after, QString label1, QString label2 = QString::null, QString label3 = QString::null, QString label4 = QString::null, QString label5 = QString::null, QString label6 = QString::null, QString label7 = QString::null, QString label8 = QString::null )

Constructs a new list view item as a child of the QListViewItem parent. It is inserted after item after and may contain up to eight strings label1, label2, label3, label4, label5, label6, label7 and label8 as column entries.

Note that the order is changed according to QListViewItem::key() unless the list view's sorting is disabled using QListView::setSorting( -1 ).

See also setText().

QListViewItem::~QListViewItem () [virtual]

Destroys the item, deleting all its children and freeing up all allocated resources.

bool QListViewItem::acceptDrop ( const QMimeSource * mime ) const [virtual]

Returns TRUE if the item can accept drops of type QMimeSource mime; otherwise returns FALSE.

The default implementation does nothing and returns FALSE. A subclass must reimplement this to accept drops.

void QListViewItem::activate () [virtual protected]

This virtual function is called whenever the user clicks on this item or presses Space on it.

See also activatedPos().

Reimplemented in QCheckListItem.

bool QListViewItem::activatedPos ( QPoint & pos ) [protected]

When called from a reimplementation of activate(), this function gives information on how the item was activated. Otherwise the behavior is undefined.

If activate() was caused by a mouse press, the function sets pos to where the user clicked and returns TRUE; otherwise it returns FALSE and does not change pos.

pos is relative to the top-left corner of this item.

We recommend not using this function; it is scheduled to become obsolete.

See also activate().

void QListViewItem::cancelRename ( int col ) [virtual protected]

This function is called if the user cancels in-place renaming of this item in column col.

See also okRename().

int QListViewItem::childCount () const

Returns how many children this item has.

int QListViewItem::compare ( QListViewItem * i, int col, bool ascending ) const [virtual]

Compares this listview item to i using the column col in ascending order. Returns -1 if this item is less than i, 0 if they are equal and 1 if this item is greater than i.

This function is used for sorting.

The default implementation compares the item keys (key()) using QString::localeAwareCompare(). A reimplementation may use different values and a different comparison function. Here is a reimplementation that uses plain Unicode comparison:

    int MyListViewItem::compare( QListViewItem *i, int col,
                                 bool ascending ) const
    {
        return key( col, ascending ).compare( i->key(col, ascending) );
    }
We don't recommend using ascending so your code can safely ignore it.

See also key(), QString::localeAwareCompare() and QString::compare().

Example: network/ftpclient/ftpview.cpp.

int QListViewItem::depth () const

Returns the depth of this item.

Example: dirview/dirview.cpp.

bool QListViewItem::dragEnabled () const

Returns TRUE if this item can be dragged; otherwise returns FALSE.

See also setDragEnabled().

void QListViewItem::dragEntered () [virtual protected]

This method is called when a drag entered the item's bounding rectangle.

The default implementation does nothing, subclasses may need to reimplement this method.

void QListViewItem::dragLeft () [virtual protected]

This method is called when a drag left the item's bounding rectangle.

The default implementation does nothing, subclasses may need to reimplement this method.

bool QListViewItem::dropEnabled () const

Returns TRUE if this item accepts drops; otherwise returns FALSE.

See also setDropEnabled() and acceptDrop().

void QListViewItem::dropped ( QDropEvent * e ) [virtual protected]

This method is called when something was dropped on the item. e contains all the information about the drop.

The default implementation does nothing, subclasses may need to reimplement this method.

void QListViewItem::enforceSortOrder () const [virtual protected]

Makes sure that this object's children are sorted appropriately.

This works only if every item from the root item down to this item is already sorted.

See also sortChildItems().

QListViewItem * QListViewItem::firstChild () const

Returns a pointer to the first (top) child of this item, or a null pointer if this item has no children.

Note that the children are not guaranteed to be sorted properly. QListView and QListViewItem try to postpone or avoid sorting to the greatest degree possible, in order to keep the user interface snappy.

See also nextSibling().

Example: checklists/checklists.cpp.

int QListViewItem::height () const

Returns the height of this item in pixels. This does not include the height of any children; totalHeight() returns that.

void QListViewItem::insertItem ( QListViewItem * newChild ) [virtual]

Inserts newChild into this list view item's list of children. You should not need to call this function; it is called automatically by the constructor of newChild.

void QListViewItem::invalidateHeight () [virtual]

Invalidates the cached total height of this item, including all open children.

See also setHeight(), height() and totalHeight().

bool QListViewItem::isEnabled () const

Returns TRUE if this item is enabled; otherwise returns FALSE.

See also setEnabled().

bool QListViewItem::isExpandable () const

Returns TRUE if this item is expandable even when it has no children; otherwise returns FALSE.

bool QListViewItem::isOpen () const

Returns TRUE if this list view item has children and they are potentially visible. Returns FALSE if the item has no children or they are hidden.

See also setOpen().

bool QListViewItem::isSelectable () const

Returns TRUE if the item is selectable (as it is by default); otherwise returns FALSE

See also setSelectable().

bool QListViewItem::isSelected () const

Returns TRUE if this item is selected; otherwise returns FALSE.

See also setSelected(), QListView::setSelected() and QListView::selectionChanged().

Example: listviews/listviews.cpp.

bool QListViewItem::isVisible () const

Returns TRUE if the item is visible; otherwise returns FALSE.

See also setVisible().

QListViewItem * QListViewItem::itemAbove ()

Returns a pointer to the item immediately above this item on the screen. This is usually the item's closest older sibling, but it may also be its parent or its next older sibling's youngest child, or something else if anyoftheabove->height() returns 0. Returns a null pointer if there is no item immediately above this item.

This function assumes that all parents of this item are open (i.e. that this item is visible, or can be made visible by scrolling).

See also itemBelow() and QListView::itemRect().

QListViewItem * QListViewItem::itemBelow ()

Returns a pointer to the item immediately below this item on the screen. This is usually the item's eldest child, but it may also be its next younger sibling, its parent's next younger sibling, grandparent's, etc., or something else if anyoftheabove->height() returns 0. Returns a null pointer if there is no item immediately below this item.

This function assumes that all parents of this item are open (i.e. that this item is visible or can be made visible by scrolling).

See also itemAbove() and QListView::itemRect().

Example: dirview/dirview.cpp.

int QListViewItem::itemPos () const

Returns the y coordinate of this item in the list view's coordinate system. This function is normally much slower than QListView::itemAt(), but it works for all items whereas QListView::itemAt() normally only works for items on the screen.

See also QListView::itemAt(), QListView::itemRect() and QListView::itemPos().

QString QListViewItem::key ( int column, bool ascending ) const [virtual]

Returns a key that can be used for sorting by column column. The default implementation returns text(). Derived classes may also incorporate the order indicated by ascending into this key, although this is not recommended.

If you want to sort on non-alphabetical data, e.g. dates, numbers, etc., reimplement compare().

See also compare() and sortChildItems().

QListView * QListViewItem::listView () const

Returns a pointer to the list view containing this item.

void QListViewItem::moveItem ( QListViewItem * after )

Moves this item after the item after. This means it will get the sibling exactly after the item after. To move an item in the hierarchy, use takeItem() and insertItem().

bool QListViewItem::multiLinesEnabled () const

Returns TRUE if the item can display multiple lines of text; otherwise returns FALSE.

QListViewItem * QListViewItem::nextSibling () const

Returns a pointer to the sibling item below this item, or a null pointer if there is no sibling item after this item.

Note that the siblings are not guaranteed to be sorted properly. QListView and QListViewItem try to postpone or avoid sorting to the greatest degree possible, in order to keep the user interface snappy.

See also firstChild().

Example: xml/tagreader-with-features/structureparser.cpp.

void QListViewItem::okRename ( int col ) [virtual protected]

This function is called if the user presses Enter during in-place renaming of the item in column col.

See also cancelRename().

void QListViewItem::paintBranches ( QPainter * p, const QColorGroup & cg, int w, int y, int h ) [virtual]

Paints a set of branches from this item to (some of) its children.

Painter p is set up with clipping and translation so that you can draw only in the rectangle you need to; cg is the color group to use; the update rectangle is at (0, 0) and has size width w by height h. The top of the rectangle you own is at y (which is never greater than 0 but can be outside the window system's allowed coordinate range).

The update rectangle is in an undefined state when this function is called; this function must draw on all of the pixels.

See also paintCell() and QListView::drawContentsOffset().

void QListViewItem::paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align ) [virtual]

This virtual function paints the contents of one column of an item and aligns it as described by align.

p is a QPainter open on the relevant paint device. p is translated so (0, 0) is the top-left pixel in the cell and width-1, height()-1 is the bottom-right pixel in the cell. The other properties of p (pen, brush, etc) are undefined. cg is the color group to use. column is the logical column number within the item that is to be painted; 0 is the column which may contain a tree.

This function may use QListView::itemMargin() for readability spacing on the left and right sides of data such as text, and should honor isSelected() and QListView::allColumnsShowFocus().

If you reimplement this function, you should also reimplement width().

The rectangle to be painted is in an undefined state when this function is called, so you must draw on all the pixels. The painter p has the right font on entry.

See also paintBranches() and QListView::drawContentsOffset().

Example: listviews/listviews.cpp.

Reimplemented in QCheckListItem.

void QListViewItem::paintFocus ( QPainter * p, const QColorGroup & cg, const QRect & r ) [virtual]

Paints a focus indication on the rectangle r using painter p and colors cg.

p is already clipped.

See also paintCell(), paintBranches() and QListView::allColumnsShowFocus.

Reimplemented in QCheckListItem.

QListViewItem * QListViewItem::parent () const

Returns a pointer to the parent of this item, or a null pointer if this item has no parent.

See also firstChild() and nextSibling().

Example: dirview/dirview.cpp.

const QPixmap * QListViewItem::pixmap ( int column ) const [virtual]

Returns a pointer to the pixmap for column, or a null pointer if there is no pixmap for column.

See also setText() and setPixmap().

Examples: dirview/dirview.cpp and network/ftpclient/ftpview.cpp.

void QListViewItem::removeItem ( QListViewItem * item ) [virtual]

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

This function has been renamed takeItem().

bool QListViewItem::renameEnabled ( int col ) const

Returns TRUE if this item can be in-place renamed in column col; otherwise returns FALSE.

void QListViewItem::repaint () const

Repaints this item on the screen if it is currently visible.

Example: addressbook/centralwidget.cpp.

int QListViewItem::rtti () const [virtual]

Returns 0.

Make your derived classes return their own values for rtti(), and you can distinguish between listview items. You should use values greater than 1000 preferably a large random number, to allow for extensions to this class.

Reimplemented in QCheckListItem.

void QListViewItem::setDragEnabled ( bool allow ) [virtual]

If allow is TRUE, the listview starts a drag (see QListView::dragObject()) when the user presses and moves the mouse on this item.

void QListViewItem::setDropEnabled ( bool allow ) [virtual]

If allow is TRUE, the listview accepts drops onto the item; otherwise drops are not allowed..

void QListViewItem::setEnabled ( bool b ) [virtual]

If b is TRUE the item is enabled; otherwise it is disabled. Disabled items are drawn grayed-out and are not accessable by the user.

void QListViewItem::setExpandable ( bool enable ) [virtual]

Sets this item to be expandable even if it has no children if enable is TRUE, and to be expandable only if it has children if enable is FALSE (the default).

The dirview example uses this in the canonical fashion. It checks whether the directory is empty in setup() and calls setExpandable(TRUE) if not; in setOpen() it reads the contents of the directory and inserts items accordingly. This strategy means that dirview can display the entire file system without reading very much at startup.

Note that root items are not expandable by the user unless QListView::setRootIsDecorated() is set to TRUE.

See also setSelectable().

void QListViewItem::setHeight ( int height ) [virtual protected]

Sets this item's height to height pixels. This implicitly changes totalHeight(), too.

Note that a font change causes this height to be overwritten unless you reimplement setup().

For best results in Windows style we suggest using an even number of pixels.

See also height(), totalHeight() and isOpen().

void QListViewItem::setMultiLinesEnabled ( bool b ) [virtual]

If b is TRUE items may contain multiple lines of text; otherwise they may only contain a single line.

void QListViewItem::setOpen ( bool o ) [virtual]

Opens or closes an item, i.e. shows or hides an item's children.

If o is TRUE all child items are shown initially. The user can hide them by clicking the - icon to the left of the item. If o is FALSE, the children of this item are initially hidden. The user can show them by clicking the + icon to the left of the item.

See also height(), totalHeight() and isOpen().

Examples: checklists/checklists.cpp, dirview/dirview.cpp, dirview/main.cpp, fileiconview/mainwindow.cpp and xml/tagreader-with-features/structureparser.cpp.

void QListViewItem::setPixmap ( int column, const QPixmap & pm ) [virtual]

Sets the pixmap in column column to pm, if pm is non-null and different from the current pixmap, and if column is non-negative.

See also pixmap() and setText().

Example: dirview/dirview.cpp.

void QListViewItem::setRenameEnabled ( int col, bool b ) [virtual]

If b is TRUE, this item can be in-place renamed in the column col by the user, otherwise it is not possible.

void QListViewItem::setSelectable ( bool enable ) [virtual]

Sets this items to be selectable if enable is TRUE (the default) or not to be selectable if enable is FALSE.

The user is not able to select a non-selectable item using either the keyboard or mouse. The application programmer still can, e.g. using setSelected().

See also isSelectable().

Example: network/ftpclient/ftpview.cpp.

void QListViewItem::setSelected ( bool s ) [virtual]

If s is TRUE this item is selected; otherwise it is deselected.

This function does not maintain any invariants or repaint anything -- QListView::setSelected() does that.

See also height() and totalHeight().

Example: addressbook/centralwidget.cpp.

void QListViewItem::setText ( int column, const QString & text ) [virtual]

Sets the text in column column to text, if column is a valid column number and text is different from the existing text.

If text() has been reimplemented, this function may be a no-op.

See also text() and key().

Examples: addressbook/centralwidget.cpp and xml/outliner/outlinetree.cpp.

void QListViewItem::setVisible ( bool b )

If b is TRUE, the item is made visible; otherwise it is hidden.

If the item is not visible, itemAbove() and itemBelow() will never hit this item, although you still can reach it by using e.g. the QListViewItemIterator.

void QListViewItem::setup () [virtual]

This virtual function is called before the first time QListView needs to know the height or any other graphical attribute of this object, and whenever the font, GUI style, or colors of the list view change.

The default calls widthChanged() and sets the item's height to the height of a single line of text in the list view's font. (If you use icons, multi-line text, etc., you will probably need to call setHeight() yourself or reimplement it.)

Example: dirview/dirview.cpp.

void QListViewItem::sort () [virtual]

(Re)sorts all child items of this item using the last sorting configuration (sort column and direction).

See also enforceSortOrder().

void QListViewItem::sortChildItems ( int column, bool ascending ) [virtual]

Sorts the children of this item using column column. This is done in ascending order if ascending is TRUE and in descending order if ascending is FALSE.

Asks some of the children to sort their children. (QListView and QListViewItem ensure that all on-screen objects are properly sorted but may avoid or defer sorting other objects in order to be more responsive.)

See also key() and compare().

void QListViewItem::startRename ( int col ) [virtual]

If in-place renaming of this item is enabled (see renameEnabled()), this function starts renaming the item in cloumn col, by creating and initializing an edit box.

void QListViewItem::takeItem ( QListViewItem * item ) [virtual]

Removes item from this object's list of children and causes an update of the screen display. The item is not deleted. You should normally not need to call this function because QListViewItem::~QListViewItem() calls it.

The normal way to delete an item is delete.

If you need to move an item from one place in the hierarchy to another you can use takeItem() to remove the item from the list view and then insertItem() to put the item back in its new position.

Warning: This function leaves item and its children in a state where most member functions are unsafe. Only a few functions work correctly on an item in this state, most notably insertItem(). The functions that work on detached items are explicitly documented as such.

See also QListViewItem::insertItem().

QString QListViewItem::text ( int column ) const [virtual]

Returns the text in column column, or a null string if there is no text in that column.

See also key() and paintCell().

Examples: addressbook/centralwidget.cpp, dirview/dirview.cpp and network/ftpclient/ftpview.cpp.

int QListViewItem::totalHeight () const

Returns the total height of this object, including any visible children. This height is recomputed lazily and cached for as long as possible.

Functions which can affect the total height are, setHeight() which is used to set an item's height, setOpen() to show or hide an item's children, and invalidateHeight() to invalidate the cached height.

See also height().

int QListViewItem::width ( const QFontMetrics & fm, const QListView * lv, int c ) const [virtual]

Returns the number of pixels of width required to draw column c of list view lv, using the metrics fm without cropping. The list view containing this item may use this information depending on the QListView::WidthMode settings for the column.

The default implementation returns the width of the bounding rectangle of the text of column c.

See also listView(), widthChanged(), QListView::setColumnWidthMode() and QListView::itemMargin.

void QListViewItem::widthChanged ( int c = -1 ) const

Call this function when the value of width() may have changed for column c. Normally, you should call this if text(c) changes. Passing -1 for c indicates that all columns may have changed. For efficiency, you should do this if more than one call to widthChanged() is required.

See also width().

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


QListViewItem Member List

Complete Member List for QListViewItem

This is the complete list of member functions for QListViewItem, including inherited members.

  • QListViewItem()
  • ~QListViewItem()
  • acceptDrop()
  • activate()
  • activatedPos()
  • cancelRename()
  • childCount()
  • compare()
  • depth()
  • dragEnabled()
  • dragEntered()
  • dragLeft()
  • dropEnabled()
  • dropped()
  • enforceSortOrder()
  • firstChild()
  • height()
  • insertItem()
  • invalidateHeight()
  • isEnabled()
  • isExpandable()
  • isOpen()
  • isSelectable()
  • isSelected()
  • isVisible()
  • itemAbove()
  • itemBelow()
  • itemPos()
  • key()
  • listView()
  • moveItem()
  • multiLinesEnabled()
  • nextSibling()
  • okRename()
  • paintBranches()
  • paintCell()
  • paintFocus()
  • parent()
  • pixmap()
  • removeItem()
  • renameEnabled()
  • repaint()
  • rtti()
  • setDragEnabled()
  • setDropEnabled()
  • setEnabled()
  • setExpandable()
  • setHeight()
  • setMultiLinesEnabled()
  • setOpen()
  • setPixmap()
  • setRenameEnabled()
  • setSelectable()
  • setSelected()
  • setText()
  • setVisible()
  • setup()
  • sort()
  • sortChildItems()
  • startRename()
  • takeItem()
  • text()
  • totalHeight()
  • width()
  • widthChanged()


QListViewItemIterator Class

QListViewItemIterator Class Reference

The QListViewItemIterator class provides an iterator for collections of QListViewItems. More...

#include <qlistview.h>

List of all member functions.

Public Members

  • QListViewItemIterator ()
  • QListViewItemIterator ( QListViewItem * item )
  • QListViewItemIterator ( const QListViewItemIterator & it )
  • QListViewItemIterator ( QListView * lv )
  • QListViewItemIterator & operator= ( const QListViewItemIterator & it )
  • ~QListViewItemIterator ()
  • QListViewItemIterator & operator++ ()
  • const QListViewItemIterator operator++ ( int )
  • QListViewItemIterator & operator+= ( int j )
  • QListViewItemIterator & operator-- ()
  • const QListViewItemIterator operator-- ( int )
  • QListViewItemIterator & operator-= ( int j )
  • QListViewItem * current () const

Detailed Description

The QListViewItemIterator class provides an iterator for collections of QListViewItems.

Construct an instance of a QListViewItemIterator, with either a QListView* or a QListViewItem* as argument, to operate on the tree of QListViewItems.

A QListViewItemIterator iterates over all items of a list view. This means that it always makes the first child of the current item the new current item. If there is no child, the next sibling becomes the new current item; and if there is no next sibling, the next sibling of the parent becomes current.

The following example function gets a list of all the items that have been selected by the user, storing pointers to the items in a QPtrList:

    QPtrList<QListViewItem> lst;
    QListViewItemIterator it( lv );
    while ( it.current() != 0 ) {
        if ( it.current()->isSelected() )
            lst.append( it.current() );
        ++it;
    }

A QListViewItemIterator provides a convenient and easy way to traverse a hierarchical QListView.

Multiple QListViewItemIterators can operate on the tree of QListViewItems. A QListView knows about all iterators operating on its QListViewItems. So when a QListViewItem gets removed all iterators that point to this item are updated and point to the following item if possible, otherwise to a valid item before the current one or to 0.

See also QListView, QListViewItem and Advanced Widgets.

Member Function Documentation

QListViewItemIterator::QListViewItemIterator ()

Constructs an empty iterator.

QListViewItemIterator::QListViewItemIterator ( QListViewItem * item )

Constructs an iterator for the QListView of the item. The current iterator item is set to point to the item.

QListViewItemIterator::QListViewItemIterator ( const QListViewItemIterator & it )

Constructs an iterator for the same QListView as it. The current iterator item is set to point on the current item of it.

QListViewItemIterator::QListViewItemIterator ( QListView * lv )

Constructs an iterator for the QListView lv. The current iterator item is set to point on the first child (QListViewItem) of lv.

QListViewItemIterator::~QListViewItemIterator ()

Destroys the iterator.

QListViewItem * QListViewItemIterator::current () const

Returns a pointer to the current item of the iterator.

Examples: addressbook/centralwidget.cpp, checklists/checklists.cpp, dirview/dirview.cpp and network/ftpclient/ftpview.cpp.

QListViewItemIterator & QListViewItemIterator::operator++ ()

Prefix ++ makes the next item in the QListViewItem tree of the QListView of the iterator the current item and returns it. If the current item was the last item in the QListView or null, null is returned.

const QListViewItemIterator QListViewItemIterator::operator++ ( int )

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

Postfix ++ makes the next item in the QListViewItem tree of the QListView of the iterator the current item and returns the item which was previously current.

QListViewItemIterator & QListViewItemIterator::operator+= ( int j )

Sets the current item to the item j positions after the current item in the QListViewItem hierarchy. If this item is beyond the last item, the current item is set to null.

The new current item (or null, if the new current item is null) is returned.

QListViewItemIterator & QListViewItemIterator::operator-- ()

Prefix -- makes the previous item in the QListViewItem tree of the QListView of the iterator the current item and returns it. If the current item was the last first in the QListView or null, null is returned.

const QListViewItemIterator QListViewItemIterator::operator-- ( int )

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

Postfix -- makes the previous item in the QListViewItem tree of the QListView of the iterator the current item and returns the item.

QListViewItemIterator & QListViewItemIterator::operator-= ( int j )

Sets the current item to the item j positions before the current item in the QListViewItem hierarchy. If this item is before the first item, the current item is set to null. The new current item (or null, if the new current item is null) is returned.

QListViewItemIterator & QListViewItemIterator::operator= ( const QListViewItemIterator & it )

Assignment. Makes a copy of it and returns a reference to its iterator.

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


QListViewItemIterator Member List

Complete Member List for QListViewItemIterator

This is the complete list of member functions for QListViewItemIterator, including inherited members.

  • QListViewItemIterator()
  • ~QListViewItemIterator()
  • current()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()


QLocalFs Class

QLocalFs Class Reference
[network module]

The QLocalFs class is an implementation of a QNetworkProtocol that works on the local file system. More...

#include <qlocalfs.h>

Inherits QNetworkProtocol.

List of all member functions.

Public Members

  • QLocalFs ()

Detailed Description

The QLocalFs class is an implementation of a QNetworkProtocol that works on the local file system.

This class is derived from QNetworkProtocol. QLocalFs is not normally used directly, but rather through a QUrlOperator, for example:

    QUrlOperator op( "file:///tmp" );
    op.listChildren(); // Asks the server to provide a directory listing

This code will only work if the QLocalFs class is registered; to register the class, you must call qInitNetworkProtocols() before using a QUrlOperator with QLocalFs.

If you really need to use QLocalFs directly, don't forget to set its QUrlOperator with setUrl().

See also Qt Network Documentation, QNetworkProtocol, QUrlOperator and Input/Output and Networking.

Member Function Documentation

QLocalFs::QLocalFs ()

Constructor.

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


qlocalfs.h Include File

qlocalfs.h

This is the verbatim text of the qlocalfs.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qlocalfs.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QLocalFs class
**
** Created : 950429
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLOCALFS_H
#define QLOCALFS_H

#ifndef QT_H
#include "qnetworkprotocol.h"
#include "qdir.h"
#endif // QT_H

#ifndef QT_NO_NETWORKPROTOCOL

class Q_EXPORT QLocalFs : public QNetworkProtocol
{
    Q_OBJECT

public:
    QLocalFs();
    virtual int supportedOperations() const;

protected:
    virtual void operationListChildren( QNetworkOperation *op );
    virtual void operationMkDir( QNetworkOperation *op );
    virtual void operationRemove( QNetworkOperation *op );
    virtual void operationRename( QNetworkOperation *op );
    virtual void operationGet( QNetworkOperation *op );
    virtual void operationPut( QNetworkOperation *op );

private:
    int calcBlockSize( int totalSize ) const;
    QDir dir;

};

#endif // QT_NO_NETWORKPROTOCOL

#endif // QLOCALFS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QLocalFs Member List

Complete Member List for QLocalFs

This is the complete list of member functions for QLocalFs, including inherited members.

  • QLocalFs()
  • addOperation()
  • autoDelete()
  • blockSignals()
  • checkConnectArgs()
  • checkConnection()
  • child()
  • childEvent()
  • children()
  • className()
  • clearOperationQueue()
  • connect()
  • connectNotify()
  • connectionStateChanged()
  • createdDirectory()
  • customEvent()
  • data()
  • dataTransferProgress()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • finished()
  • getNetworkProtocol()
  • hasOnlyLocalFileSystem()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemChanged()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • newChild()
  • newChildren()
  • normalizeSignalSlot()
  • objectTrees()
  • operationGet()
  • operationInProgress()
  • operationListChildren()
  • operationMkDir()
  • operationPut()
  • operationRemove()
  • operationRename()
  • parent()
  • property()
  • queryList()
  • registerNetworkProtocol()
  • removeChild()
  • removeEventFilter()
  • removed()
  • sender()
  • setAutoDelete()
  • setName()
  • setProperty()
  • setUrl()
  • signalsBlocked()
  • start()
  • startTimer()
  • stop()
  • supportedOperations()
  • timerEvent()
  • tr()
  • trUtf8()
  • url()


QLock Class

QLock Class Reference

The QLock class is a wrapper for a System V shared semaphore. More...

#include <qlock_qws.h>

List of all member functions.

Public Members

  • QLock ( const QString & filename, char id, bool create = FALSE )
  • ~QLock ()
  • enum Type { Read, Write }
  • bool isValid () const
  • void lock ( Type t )
  • void unlock ()
  • bool locked () const

Detailed Description

The QLock class is a wrapper for a System V shared semaphore.

It is used by Qt/Embedded for synchronizing access to the graphics card and shared memory region between processes.

See also Input/Output and Networking and Qt/Embedded.

Member Type Documentation

QLock::Type

  • QLock::Read
  • QLock::Write

Member Function Documentation

QLock::QLock ( const QString & filename, char id, bool create = FALSE )

Creates a lock. filename is the file path of the Unix-domain socket the Qt/Embedded client is using. id is the name of the particular lock to be created on that socket. If create is TRUE the lock is to be created (as the Qt/Embedded server does); if create is FALSE the lock should exist already (as the Qt/Embedded client expects).

QLock::~QLock ()

Destroys a lock

bool QLock::isValid () const

Returns TRUE if the lock constructor was succesful; returns FALSE if the lock could not be created or was not available to connect to.

void QLock::lock ( Type t )

Locks the semaphore with a lock of type t. Locks can either be Read or Write. If a lock is Read, attempts by other processes to obtain Read locks will succeed, and Write attempts will block until the lock is unlocked. If locked as Write, all attempts to lock by other processes will block until the lock is unlocked. Locks are stacked: i.e. a given QLock can be locked multiple times by the same process without blocking, and will only be unlocked after a corresponding number of unlock() calls.

bool QLock::locked () const

Returns TRUE if the lock is currently held by the current process; otherwise returns FALSE.

void QLock::unlock ()

Unlocks the semaphore. If other processes were blocking waiting to lock() the semaphore, one of them will wake up and succeed in lock()ing.

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


QLock Member List

Complete Member List for QLock

This is the complete list of member functions for QLock, including inherited members.

  • QLock()
  • ~QLock()
  • isValid()
  • lock()
  • locked()
  • unlock()


qlock_qws.h Include File

qlock_qws.h

This is the verbatim text of the qlock_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qlock_qws.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QLock class. This manages interprocess locking
**
** Created : 20000406
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QLOCK_QWS_H
#define QLOCK_QWS_H

#ifndef QT_H
#include <qstring.h>
#endif // QT_H

class QLockData;

class QLock
{
public:
    QLock( const QString &filename, char id, bool create = FALSE );
    ~QLock();

    enum Type { Read, Write };

    bool isValid() const;
    void lock( Type type );
    void unlock();
    bool locked() const;

private:
    Type type;
    QLockData *data;
};

// Nice class for ensuring the lock is released.
// Just create one on the stack and the lock is automatically released
// when QLockHolder is destructed.
class QLockHolder
{
public:
    QLockHolder( QLock *l, QLock::Type type ) : qlock(l) {
    qlock->lock( type );
    }
    ~QLockHolder() { if ( locked() ) qlock->unlock(); }

    void lock( QLock::Type type ) { qlock->lock( type ); }
    void unlock() { qlock->unlock(); }
    bool locked() const { return qlock->locked(); }

private:
    QLock *qlock;
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMag

This is a simple magnifier-type program. It shows how one can do some quite low-level operations in a portable way using Qt.

Run it, click in the magnifier window, then click where you want to magnify or drag out a rectangle. Two combo boxes let you select amplification and refresh frequency, a text label tells you the color of the pixel the cursor is on, and a button lets you save the magnified area as a .bmp file.

Implementation:

/****************************************************************************
** $Id:  qt/qmag.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qcombobox.h>
#include <qpushbutton.h>
#include <qpixmap.h>
#include <qimage.h>
#include <qlabel.h>
#include <qfiledialog.h>
#include <qregexp.h>

#include <qapplication.h>
#include <qpainter.h>
#include <qwmatrix.h>

class MagWidget : public QWidget
{
    Q_OBJECT
public:
    MagWidget( QWidget *parent=0, const char *name=0 );

public slots:
    void        setZoom( int );
    void        setRefresh( int );
    void        save();
    void        multiSave();

protected:
    void        paintEvent( QPaintEvent * );
    void        mousePressEvent( QMouseEvent * );
    void        mouseReleaseEvent( QMouseEvent * );
    void        mouseMoveEvent( QMouseEvent * );
    void        focusOutEvent( QFocusEvent * );
    void        timerEvent( QTimerEvent * );
    void        resizeEvent( QResizeEvent * );

private:
    void        grabAround(QPoint pos);
    void        grab();

    QComboBox   *zoom;
    QComboBox   *refresh;
    QPushButton *saveButton;
    QPushButton *multiSaveButton;
    QPushButton *quitButton;
    QPixmap     pm;             // pixmap, magnified
    QPixmap     p;              // pixmap
    QImage      image;          // image of pixmap (for RGB)
    QLabel      *rgb;
    int         yoffset;        // pixels in addition to the actual picture
    int         z;              // magnification factor
    int         r;              // autorefresh rate (index into refreshrates)
    bool        grabbing;       // TRUE if qmag is currently grabbing
    int         grabx, graby;
    QString     multifn;        // filename for multisave
};

#ifdef COMPLEX_GUI
static const char *zoomfactors[] = {
    "100%", "200%", "300%", "400%", "500%",
    "600%", "700%", "800%", "1600%", 0 };

static const char *refreshrates[] = {
    "No autorefresh", "50 per second", "4 per second", "3 per second", "2 per second",
    "Every second", "Every two seconds", "Every three seconds",
    "Every five seconds", "Every ten seconds", 0 };
#endif

static const int timer[] = {
    0, 20, 250, 333, 500, 1000, 2000, 3000, 5000, 10000 };

MagWidget::MagWidget( QWidget *parent, const char *name )
    : QWidget( parent, name)
{
    z = 1;                      // default zoom (100%)
    r = 0;                      // default refresh (none)

#ifdef COMPLEX_GUI
    int w=0, x=0, n;

    zoom = new QComboBox( FALSE, this );
    Q_CHECK_PTR(zoom);
    zoom->insertStrList( zoomfactors, 9 );
    connect( zoom, SIGNAL(activated(int)), SLOT(setZoom(int)) );

    refresh = new QComboBox( FALSE, this );
    Q_CHECK_PTR(refresh);
    refresh->insertStrList( refreshrates, 9 );
    connect( refresh, SIGNAL(activated(int)), SLOT(setRefresh(int)) );

    for( n=0; n<9; n++) {
        int w2 = zoom->fontMetrics().width( zoomfactors[n] );
        w = QMAX(w2, w);
    }
    zoom->setGeometry( 2, 2, w+30, 20 );

    x = w+34;
    w = 0;
    for( n=0; n<9; n++) {
        int w2 = refresh->fontMetrics().width( refreshrates[n] );
        w = QMAX(w2, w);
    }
    refresh->setGeometry( x, 2, w+30, 20 );

    saveButton = new QPushButton( this );
    Q_CHECK_PTR(saveButton);
    connect( saveButton, SIGNAL(clicked()), this, SLOT(save()) );
    saveButton->setText( "Save" );
    saveButton->setGeometry( x+w+30+2, 2,
                             10+saveButton->fontMetrics().width("Save"), 20 );

    multiSaveButton = new QPushButton( this );
    multiSaveButton->setToggleButton(TRUE);
    Q_CHECK_PTR(multiSaveButton);
    connect( multiSaveButton, SIGNAL(clicked()), this, SLOT(multiSave()) );
    multiSaveButton->setText( "MultiSave" );
    multiSaveButton->setGeometry( saveButton->geometry().right() + 2, 2,
                             10+multiSaveButton->fontMetrics().width("MultiSave"), 20 );

    quitButton = new QPushButton( this );
    Q_CHECK_PTR(quitButton);
    connect( quitButton, SIGNAL(clicked()), qApp, SLOT(quit()) );
    quitButton->setText( "Quit" );
    quitButton->setGeometry( multiSaveButton->geometry().right() + 2, 2,
                             10+quitButton->fontMetrics().width("Quit"), 20 );
#else
    zoom = 0;
    multiSaveButton = 0;
#endif

    setRefresh(1);
    setZoom(5);

    rgb = new QLabel( this );
    Q_CHECK_PTR( rgb );
    rgb->setText( "" );
    rgb->setAlignment( AlignVCenter );
    rgb->resize( width(), rgb->fontMetrics().height() + 4 );

#ifdef COMPLEX_GUI
    yoffset = zoom->height()    // top buttons
        + 4                     // space around top buttons
        + rgb->height();        // color-value text height
    setMinimumSize( quitButton->pos().x(), yoffset+20 );
    resize( quitButton->geometry().topRight().x() + 2, yoffset+60 );
#else
    yoffset = 0;
    resize(350,350);
#endif

    grabx = graby = -1;
    grabbing = FALSE;

    setMouseTracking( TRUE );   // and do let me know what pixel I'm at, eh?

    grabAround( QPoint(grabx=qApp->desktop()->width()/2, graby=qApp->desktop()->height()/2) );
}

void MagWidget::setZoom( int index )
{
    if (index == 8)
        z = 16;
    else
        z = index+1;
    grab();
}

void MagWidget::setRefresh( int index )
{
    r = index;
    killTimers();
    if (index && !grabbing)
        startTimer( timer[r] );
}

void MagWidget::save()
{
    if ( !p.isNull() ) {
        killTimers();
        QString fn = QFileDialog::getSaveFileName();
        if ( !fn.isEmpty() )
            p.save( fn, "BMP" );
        if ( r )
            startTimer( timer[r] );
    }
}

void MagWidget::multiSave()
{
    if ( !p.isNull() ) {
        multifn = ""; // stops saving
        multifn = QFileDialog::getSaveFileName();
        if ( multifn.isEmpty() )
            multiSaveButton->setOn(FALSE);
        if ( !r )
            p.save( multifn, "BMP" );
    } else {
        multiSaveButton->setOn(FALSE);
    }
}

void MagWidget::grab()
{
    if ( !isVisible() )
        return;                 // don't eat resources when iconified

    if ( grabx < 0 || graby < 0 )
        return;                 // don't grab until the user has said to

    int x,y, w,h;

    w = (width()+z-1)/z;
    h = (height()+z-1-yoffset)/z;
    if ( w<1 || h<1 )
        return;                 // don't ask too much from the window system :)

    x = grabx-w/2;              // find a suitable position to grab from
    y = graby-h/2;
    if ( x + w > QApplication::desktop()->width() )
        x = QApplication::desktop()->width()-w;
    else if ( x < 0 )
        x = 0;
    if ( y + h > QApplication::desktop()->height() )
        y = QApplication::desktop()->height()-h;
    else if ( y < 0 )
        y = 0;

    p = QPixmap::grabWindow( QApplication::desktop()->winId(),  x, y, w, h );
    image = p.convertToImage();
    QWMatrix m;                 // after getting it, scale it
    m.scale( (double)z, (double)z );
    pm = p.xForm( m );

    if ( !multiSaveButton || !multiSaveButton->isOn() )
        repaint( FALSE );               // and finally repaint, flicker-free
}

void MagWidget::paintEvent( QPaintEvent * )
{
    if ( !pm.isNull() ) {
        QPainter paint( this );
        paint.drawPixmap( 0, zoom ? zoom->height()+4 : 0, pm,
                              0,0, width(), height()-yoffset );
    }
}

void MagWidget::mousePressEvent( QMouseEvent *e )
{
    if ( !grabbing ) {          // prepare to grab...
        grabbing = TRUE;
        killTimers();
        grabMouse( crossCursor );
        grabx = -1;
        graby = -1;
    } else {                    // REALLY prepare to grab
        grabx = mapToGlobal(e->pos()).x();
        graby = mapToGlobal(e->pos()).y();
    }
}

void MagWidget::mouseReleaseEvent( QMouseEvent * e )
{
    if ( grabbing && grabx >= 0 && graby >= 0 ) {
        grabbing = FALSE;
        grabAround(e->pos());
        releaseMouse();
    }
}

void MagWidget::grabAround(QPoint pos)
{
    int rx, ry;
    rx = mapToGlobal(pos).x();
    ry = mapToGlobal(pos).y();
    int w = QABS(rx-grabx);
    int h = QABS(ry-graby);
    if ( w > 10 && h > 10 ) {
        int pz;
        pz = 1;
        while ( w*pz*h*pz < width()*(height()-yoffset) &&
                w*pz < QApplication::desktop()->width() &&
                h*pz < QApplication::desktop()->height() )
            pz++;
        if ( (w*pz*h*pz - width()*(height()-yoffset)) >
             (width()*(height()-yoffset) - w*(pz-1)*h*(pz-1)) )
            pz--;
        if ( pz < 1 )
            pz = 1;
        if ( pz > 8 )
            pz = 8;
        if ( zoom )
            zoom->setCurrentItem( pz-1 );

        z = pz;
        grabx = QMIN(rx, grabx) + w/2;
        graby = QMIN(ry, graby) + h/2;
        resize( w*z, h*z+yoffset );
    }
    grab();
    if ( r )
        startTimer( timer[r] );
}

void MagWidget::mouseMoveEvent( QMouseEvent *e )
{
    if ( grabbing || pm.isNull() ||
         e->pos().y() > height() - (zoom ? zoom->fontMetrics().height() - 4 : 0) ||
         e->pos().y() < (zoom ? zoom->height()+4 : 4) ) {
        rgb->setText( "" );
    } else {
        int x,y;
        x = e->pos().x() / z;
        y = (e->pos().y() - ( zoom ? zoom->height() : 0 ) - 4) / z;
        QString pixelinfo;
        if ( image.valid(x,y) )
        {
            QRgb px = image.pixel(x,y);
            pixelinfo.sprintf(" %3d,%3d,%3d  #%02x%02x%02x",
                qRed(px), qGreen(px), qBlue(px),
                qRed(px), qGreen(px), qBlue(px));
        }
        QString label;
        label.sprintf( "x=%d, y=%d %s",
            x+grabx, y+graby, (const char*)pixelinfo );
        rgb->setText( label );
    }
}

void MagWidget::focusOutEvent( QFocusEvent * )
{
    rgb->setText( "" );
}

void MagWidget::timerEvent( QTimerEvent * )
{
    grab();
/*
    if ( multiSaveButton->isOn() && !multifn.isEmpty() ) {
        QRegExp num("[0-9][0-9]*");
        int start;
        int len;
        if ((start=num.match(multifn,0,&len))>=0)
            multifn.replace(num,
                QString().setNum(multifn.mid(start,len).toInt()+1)
            );
        p.save( multifn, "BMP" );
    }
*/
}

void MagWidget::resizeEvent( QResizeEvent * )
{
    rgb->setGeometry( 0, height() - rgb->height(), width(), rgb->height() );
    grab();
}

#include "qmag.moc"

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    MagWidget m;
    a.setMainWidget( &m );
    m.show();
    return a.exec();
}

See also Examples.


QMainWindow类

QMainWindow类参考

QMainWindow类提供一个有菜单条、锚接窗口（例如工具条）和一个状态条的主应用程序窗口。 详情请见……

#include <qmainwindow.h>

继承了QWidget。

所有成员函数的列表。

公有成员

  • QMainWindow ( QWidget * parent = 0, const char * name = 0, WFlags f = WType_TopLevel )
  • ~QMainWindow ()
  • QMenuBar * menuBar () const
  • QStatusBar * statusBar () const
  • QToolTipGroup * toolTipGroup () const
  • virtual void setCentralWidget ( QWidget * w )
  • QWidget * centralWidget () const
  • virtual void setDockEnabled ( Dock dock, bool enable )
  • bool isDockEnabled ( Dock dock ) const
  • bool isDockEnabled ( QDockArea * area ) const
  • virtual void setDockEnabled ( QDockWindow * dw, Dock dock, bool enable )
  • bool isDockEnabled ( QDockWindow * tb, Dock dock ) const
  • bool isDockEnabled ( QDockWindow * dw, QDockArea * area ) const
  • virtual void addDockWindow ( QDockWindow * dockWindow, Dock edge = DockTop, bool newLine = FALSE )
  • virtual void addDockWindow ( QDockWindow * dockWindow, const QString & label, Dock edge = DockTop, bool newLine = FALSE )
  • virtual void moveDockWindow ( QDockWindow * dockWindow, Dock edge = DockTop )
  • virtual void moveDockWindow ( QDockWindow * dockWindow, Dock edge, bool nl, int index, int extraOffset = -1 )
  • virtual void removeDockWindow ( QDockWindow * dockWindow )
  • bool rightJustification () const
  • bool usesBigPixmaps () const
  • bool usesTextLabel () const
  • bool dockWindowsMovable () const
  • bool opaqueMoving () const
  • bool getLocation ( QDockWindow * dw, Dock & dock, int & index, bool & nl, int & extraOffset ) const
  • QPtrList<QDockWindow> dockWindows ( Dock dock ) const
  • QPtrList<QDockWindow> dockWindows () const
  • void lineUpDockWindows ( bool keepNewLines = FALSE )
  • bool isDockMenuEnabled () const
  • bool hasDockWindow ( QDockWindow * dw )
  • void addToolBar ( QDockWindow *, Dock = DockTop, bool newLine = FALSE ) （废弃）
  • void addToolBar ( QDockWindow *, const QString & label, Dock = DockTop, bool newLine = FALSE ) （废弃）
  • void moveToolBar ( QDockWindow *, Dock = DockTop ) （废弃）
  • void moveToolBar ( QDockWindow *, Dock, bool nl, int index, int extraOffset = -1 ) （废弃）
  • void removeToolBar ( QDockWindow * ) （废弃）
  • bool toolBarsMovable () const （废弃）
  • QPtrList<QToolBar> toolBars ( Dock dock ) const
  • void lineUpToolBars ( bool keepNewLines = FALSE ) （废弃）
  • QDockArea * leftDock () const
  • QDockArea * rightDock () const
  • QDockArea * topDock () const
  • QDockArea * bottomDock () const
  • virtual bool isCustomizable () const
  • bool appropriate ( QDockWindow * dw ) const
  • enum DockWindows { OnlyToolBars, NoToolBars, AllDockWindows }
  • QPopupMenu * createDockWindowMenu ( DockWindows dockWindows = AllDockWindows ) const

公有槽

  • virtual void setRightJustification ( bool )
  • virtual void setUsesBigPixmaps ( bool )
  • virtual void setUsesTextLabel ( bool )
  • virtual void setDockWindowsMovable ( bool )
  • virtual void setOpaqueMoving ( bool )
  • virtual void setDockMenuEnabled ( bool b )
  • virtual void whatsThis ()
  • virtual void setAppropriate ( QDockWindow * dw, bool a )
  • virtual void customize ()
  • void setToolBarsMovable ( bool ) （废弃）

信号

  • void pixmapSizeChanged ( bool )
  • void usesTextLabelChanged ( bool )
  • void dockWindowPositionChanged ( QDockWindow * dockWindow )
  • void toolBarPositionChanged ( QToolBar * ) （废弃）

属性

  • bool dockWindowsMovable - 锚接窗口是否可以移动
  • bool opaqueMoving - 锚接窗口是否是被不透明地移动
  • bool rightJustification - 主窗口是否右对齐它的锚接窗口
  • bool usesBigPixmaps - 大像素映射是否生效
  • bool usesTextLabel - 工具条按钮的文本标签是否生效

保护成员

  • virtual void childEvent ( QChildEvent * e )

保护槽

  • virtual void setUpLayout ()
  • virtual bool showDockMenu ( const QPoint & globalPos )
  • void menuAboutToShow ()

相关函数

  • QTextStream & operator<< ( QTextStream & ts, const QMainWindow & mainWindow )
  • QTextStream & operator>> ( QTextStream & ts, QMainWindow & mainWindow )

详细描述

QMainWindow类提供一个有菜单条、锚接窗口（例如工具条）和一个状态条的主应用程序窗口。

主窗口通常用在提供一个大的中央窗口部件（例如文本编辑或者绘制画布）以及周围菜单、工具条和一个状态条。QMainWindow常常被继承，因为这使得封装中央部件、菜单和工具条以及窗口状态变得更容易。继承使创建当用户点击菜单项或者工具条按钮时被调用的槽成为可能。你也可以使用Qt设计器来创建主窗口。我们将简要地回顾一下有关添加菜单项和工具条按钮，然后描述QMainWindow自己的便捷。

    QMainWindow *mw = new QMainWindow;
    QTextEdit *edit = new QTextEdit( mw, "editor" );
    edit->setFocus();
    mw->setCaption( "Main Window" );
    mw->setCentralWidget( edit );
    mw->show();

QMainWindow可以像上面那样显示地来被创建。中央窗口部件是通过setCentralWidget()设置地。弹出菜单可以被添加到默认工具条，窗口部件可以被添加到状态条，工具条和锚接窗口可以被添加到任何一个锚接区域。

        ApplicationWindow * mw = new ApplicationWindow();
        mw->setCaption( "Qt Example - Application" );
        mw->show();

上面代码中的ApplicationWindow是我们自己写的QMainWindow的子类，这是一个使用QMainWindow的常用方法。（源代码取自application/main.cpp、application/application.cpp、action/main.cpp和action/application.cpp。）

在继承的时候，我们在子类的构造函数中添加菜单项和工具条。如果我们已经直接创建了一个QMainWindow实例，我们可以很容易地通过传递QMainWindow实例代替作为父对象的this指针来添加菜单项和工具条。

        QPopupMenu * help = new QPopupMenu( this );
        menuBar()->insertItem( "&Help", help );

        help->insertItem( "&About", this, SLOT(about()), Key_F1 );

这里我们添加了有一个菜单项的新菜单。这个菜单已经被插入QMainWindow默认提供的并且可以通过menuBar()函数访问的菜单条。当这个菜单项被点击时，这个槽被调用。

        QToolBar * fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );

        QToolButton * fileOpen
            = new QToolButton( openIcon, "Open File", QString::null,
                               this, SLOT(choose()), fileTools, "open file" );

这部分提取显示的是有一个工具条按钮的工具条的创建。QMainWindow为工具条提供了四个锚接区域。当一个工具条被作为QMainWindow（或者继承类）实例 的子对象被创建时，它将会被放置到一个锚接区域中（默认是Top锚接区域）。当这个工具条按钮被点击时，这个槽被调用。任何锚接窗口可以使用addDockWindow()，或者通过把QMainWindow作为父对象来创建的方法来被添加到一个锚接区域中。

        e = new QTextEdit( this, "editor" );
        e->setFocus();
        setCentralWidget( e );
        statusBar()->message( "Ready", 2000 );

创建完菜单和工具条，我们创建一个大的中央窗口部件的实例，给它焦点并且把它设置为主窗口的中央窗口部件。在这个实例中，我们也已经通过statusBar()函数设置好了状态条，显示初始信息两秒。注意你可以添加其它的窗口部件到状态条重，例如标签，来显示更多的状态信息。详细情况请参考QStatusBar文档，特别是addWidget()函数。

通常我们想让一个工具条按钮和一个菜单项同步。例如，如果用户点击“加粗”工具条按钮，我们希望“加粗”菜单项被选中。这种同步可以通过创建操作并且把它们添加到工具条和菜单上来自动实现。

        QAction * fileOpenAction;

        fileOpenAction = new QAction( "Open File", QPixmap( fileopen ), "&Open",
                                      CTRL+Key_O, this, "open" );
        connect( fileOpenAction, SIGNAL( activated() ) , this, SLOT( choose() ) );

这里我们创建了一个有图标的操作，这个图标要用在这个操作所被添加到的菜单和工具条中。我们也给定这个操作一个菜单名称“&Open”和一个键盘快捷键。我们已经建立的这个连接在用户点击这个菜单项或者这个工具条按钮时将会被使用。

        QPopupMenu * file = new QPopupMenu( this );
        menuBar()->insertItem( "&File", file );

        fileOpenAction->addTo( file );

上面这部分提取显示一个弹出菜单的创建。我们把这个菜单添加到QMainWindow的菜单条中并且添加我们的操作。

        QToolBar * fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );
        fileOpenAction->addTo( fileTools );

这里我们创建一个作为QMainWindow的子对象的工具条并且把我们的操作添加到这个工具条中。

现在我们来探险QMainWindow提供的功能。

主窗口将会注意锚接区域和中央窗口部件的几何形状，但是中央窗口部件的其它所有方面都留给你了。如果你指定QMainWindow作为父对象来创建菜单条或者状态条，QMainWindow会自动检测它们，或者你可以使用提供的menuBar()和statusBar()函数。如果一个窗口部件也没有，menuBar()和statusBar()函数创建一个合适的窗口部件，并且更新窗口的布局来得到空间。

QMainWindow提供了一个连接到状态条的QToolTipGroup。toolTipGroup()函数提供了对默认QToolTipGroup的访问。它不能设置一个不同的工具提示组。

新的锚接窗口和工具条可以通过使用addDockWindow()来被添加到QMainWindow中。锚接窗口可以使用moveDockWindow()来移动并且使用removeDockWindow()来移除。QMainWindow允许默认锚接窗口（工具条）锚接在所有它的锚接区域中（上、下、左、右）。你可以使用setDockEnabled()为锚接窗口而使锚接区域生效/失效。当添加或者移动锚接窗口时，你可以指定它们的“边缘”（锚接区域）。当前可用的边缘有：Top、Left、Right、Bottom、Minimized （有效地一个“隐藏”锚接区域）和TornOff（浮动）。关于这些区域的解释请参考Qt::Dock。注意*ToolBar函数被考虑向后兼容，所有的新代码都应该使用*DockWindow函数。QToolBar是QDockWindow的子类，所以所有对于锚接窗口能工作地函数对于工具条也一样可以工作。如果用户通过点击锚接窗口地窗口句柄来最小化一个锚接窗口，那么锚接窗口将会被移到Minimized锚接区域。如果用户点击关闭按钮，那么锚接窗口被隐藏并且只能再次通过使用锚接窗口菜单来再次被显示。

一些函数会全局地改变QMainWindow的外观：

  • QDockWindow::setHorizontalStretchable()和QDockWindow::setVerticalStretchable()被用于指定锚接窗口和工具条是可延伸的。
  • setUsesBigPixmaps()被用于设置工具按钮是应该用小像素映射还是大像素映射（更多信息请参考QIconSet）。
  • setUsesTextLabel()被用于设置工具按钮是否应该在显示像素映射之外还显示文本标签（更多信息请参考QToolButton）。

用户可以把锚接窗口拖入任何生效的锚接区域中。锚接窗口也可以在一个锚接区域中被拖动，例如重新排列一些工具条的顺序。锚接窗口也可以被拖动出任何锚接区域（取消锚接或者“浮动”）。你可以使用setDockWindowsMovable()把锚接窗口设置为生效的（默认）和失效的。如果用户点击浮动锚接窗口的关闭按钮，然后锚接窗口将会消失。为了重新得到锚接窗口，用户必须右键点击一个锚接区域，弹出一个锚接窗口菜单，然后点击我们要恢复的锚接窗口的名字。可视的锚接窗口在菜单中它们的名字之前有一个勾。锚接窗口菜单会根据createDockWindowMenu()的需要自动被创建。因为它可能不总是适合把一个锚接窗口显示到这个菜单中，setAppropriate()函数被用来告知主窗口这个锚接窗口菜单是否应该包含一个特定的锚接窗口。双击锚接窗口句柄（通常在锚接窗口的左侧）会使这个锚接窗口取消锚接（浮动）。双击浮动锚接窗口的标题栏将会锚接这个浮动的锚接窗口。

Minimized边缘是一个隐藏的锚接区域。如果这个锚接区域是生效的，用户可以隐藏（最小化）锚接窗口或者通过点击锚接窗口句柄显示（恢复）一个最小化的锚接窗口。如果用户在一个句柄上方悬浮鼠标光标，锚接窗口的标题会被作为工具提示显示（请参考QDockWindow::caption()或QToolBar::label()），所以如果你使Minimized锚接区域生效，最好为每一个锚接窗口指定一个有意义的标题或者标签。为了能够程序化地最小化一个锚接窗口，请使用一个带有Minimized边缘的moveDockWindow()。

锚接窗口默认是被透明地移动，也就是在拖动期间，一个边框矩形会在屏幕上被绘制出来呈现锚接窗口在移动时的位置。如果你想让锚接窗口在移动时被正常显示，请使用setOpaqueMoving()。

锚接窗口的定位，也就是它的锚接区域和在锚接区域中的位置，可以通过调用getLocation()来被决定。可移动的锚接窗口可以通过lineUpDockWindows()被排列成一行来使浪费的空间最小化。锚接区域的指针可以由topDock()、leftDock()、rightDock()和bottomDock()提供。如果isCustomizable()返回真（它默认返回假），一个自定义的菜单项会被添加入弹出的锚接窗口菜单。如果你想提供这个额外的菜单项，重新实现isCustomizable()和customize()，例如，允许用户改变和主窗口以及它的工具条和锚接窗口相关的设置。

主窗口的菜单条默认是固定的（在上面）。如果你想有一个可移动的菜单条，创建一个QMenuBar作为一个在它自己可移动的锚接窗口中可伸展的窗口部件并且限制这个锚接窗口只在Top或Bottom锚接区域存在：

    QToolBar *tb = new QToolBar( this );
    addDockWindow( tb, tr( "Menubar" ), Top, FALSE );
    QMenuBar *mb = new QMenuBar( tb );
    mb->setFrameStyle( QFrame::NoFrame );
    tb->setStretchableWidget( mb );
    setDockEnabled( tb, Left, FALSE );
    setDockEnabled( tb, Right, FALSE );

有多个锚接窗口的应用程序可以选择为了以后（例如，在下个对话中）恢复当前的锚接窗口布局来把它们保存起来。你可以通过使用QMainWindow的流操作符来做到这点。

为了保存所有锚接窗口的布局和位置，请这样做：

  QFile f( filename );
  if ( f.open( IO_WriteOnly ) ) {
      QTextStream ts( &f );
      ts << *mainWindow;
      f.close();
  }

为了恢复锚接窗口的位置和大小（通常是当这个应用程序再次开始），请这样做：

  QFile f( filename );
  if ( f.open( IO_ReadOnly ) ) {
      QTextStream ts( &f );
      ts >> *mainWindow;
      f.close();
  }

QSettings类可以和这些流操作符联合使用来存放这个应用程序的设置。

QMainWindow对锚接窗口和工具条的管理很明显地是由QDockArea在后面完成的。

对于多文档界面（MDI），使用QWorkspace作为中央窗口部件。

把锚接窗口（例如工具条）添加到QMainWindow的锚接区域是很简单的。如果被提供的锚接区域对于你的应用程序是不够的，我们建议你创建一个QWidget的子类并且把你自己的锚接区域（请参考QDockArea）添加到这个子类中，因为QMainWindow只提供了由它提供的标准锚接区域的特定功能。

也可以参考QToolBar、QDockWindow、QStatusBar、QAction、QMenuBar、QPopupMenu、QToolTipGroup、QDialog和主窗口和相关类。

成员类型文档

QMainWindow::DockWindows

右键点击锚接区域会弹出锚接窗口菜单（createDockWindowMenu()被自动调用）。当被调用时，在代码中你可以通过这个枚举变量指定哪些项应该出现在菜单中。

  • QMainWindow::OnlyToolBars - 菜单将会列出所有的工具条，但没有任何其它锚接窗口。
  • QMainWindow::NoToolBars - 菜单将会列出除工具条之外的所有的锚接窗口。
  • QMainWindow::AllDockWindows - 菜单将会列出所有的工具条和其它锚接窗口。（这是默认值。）

成员函数文档

QMainWindow::QMainWindow ( QWidget * parent = 0, const char * name = 0, WFlags f = WType_TopLevel )

构造一个空的主窗口。parent、name和窗口部件标记f被传递给QWidget构造函数。

默认情况下，窗口部件标记被设置为WType_TopLevel而不是只把它作为QWidget的0。如果你不想让你的QMainWindow为一个顶级窗口部件，你将需要把f设置为0。

QMainWindow::~QMainWindow ()

销毁这个对象并且释放所有已经分配的资源。

void QMainWindow::addDockWindow ( QDockWindow * dockWindow, Dock edge = DockTop, bool newLine = FALSE ) [虚]

把dockWindow添加到edge锚接区域。

如果newLine为假（默认），那么dockWindow被添加到edge的末尾。对于垂直边缘，末尾在下面，对于水平边缘（包含Minimized），末尾在右面。如果newLine为真，会为锚接窗口开始新的一行，并且dockWindow作为第一个（最左面或者最上面）锚接窗口。

如果dockWindow被另一个主窗口管理，它首先从那一个窗口中被移除。

void QMainWindow::addDockWindow ( QDockWindow * dockWindow, const QString & label, Dock edge = DockTop, bool newLine = FALSE ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把标签为label的dockWindow添加到edge锚接区域。

如果newLine为假（默认），那么dockWindow被添加到edge的末尾。对于垂直边缘，末尾在下面，对于水平边缘（包含Minimized），末尾在右面。如果newLine为真，会为锚接窗口开始新的一行，并且dockWindow作为第一个（最左面或者最上面）锚接窗口。

如果dockWindow被另一个主窗口管理，它首先从那一个窗口中被移除。

void QMainWindow::addToolBar ( QDockWindow *, Dock = DockTop, bool newLine = FALSE )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QMainWindow::addToolBar ( QDockWindow *, const QString & label, Dock = DockTop, bool newLine = FALSE )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

bool QMainWindow::appropriate ( QDockWindow * dw ) const

如果适合在锚接窗口菜单中包含一个可以列出dw锚接窗口的菜单项，返回真，否则返回假。

用户可以通过点击菜单项来改变有菜单项的锚接窗口的状态（显示或者隐藏）。

调用setAppropriate()来指出一个特定锚接窗口是否应该显示在弹出菜单中。

也可以参考setAppropriate()。

QDockArea * QMainWindow::bottomDock () const

返回Bottom锚接区域的指针。

也可以参考topDock()、leftDock()和rightDock()。

QWidget * QMainWindow::centralWidget () const

返回主窗口的中央窗口部件的指针。

中央窗口部件就是被上、下、左、右锚接区域环绕的。菜单条在上锚接区域的上面。

也可以参考setCentralWidget()。

实例：qfd/qfd.cpp。

void QMainWindow::childEvent ( QChildEvent * e ) [虚 保护]

监视事件，从e中接收，来保证布局被更新。

从QObject中重新实现。

QPopupMenu * QMainWindow::createDockWindowMenu ( DockWindows dockWindows = AllDockWindows ) const

创建一个包含所有工具条（如果dockWindows为OnlyToolBars）、所有锚接窗口（如果dockWindows为NoToolBars）或者所有工具条和锚接窗口（如果dockWindows为AllDockWindows——默认）的锚接窗口菜单。

当需要的时候，例如当用户右键点击一个锚接区域（假如isDockMenuEnabled()返回真）时，这个函数被内部调用。如果你想自定义这个行为，你可以重新实现这个函数。

呈现工具条和锚接窗口的菜单项是可选择的。可视的锚接窗口被选择的并且隐藏的锚接窗口是被取消选择的。用户点击一个菜单项来改变它的状态（显示或者隐藏这个锚接窗口）。

这个列表和状态总是保持最新。

在当前上下文（请参考setAppropriate()）中是不适合的工具条和锚接窗口不会在这个菜单中被列出来。

这个菜单也有一个把锚接窗口排成一行的菜单选项。

如果isCustomizable()返回真，一个Customize的菜单项被添加到菜单中，如果它被点击，就会调用customize()。我们提供的isCustomizable()函数返回假并且customize()什么也不做，所以它们必须在子类中被重新实现才能有用。

void QMainWindow::customize () [虚 槽]

当用户点击在锚接窗口菜单中的Customize菜单项时，这个函数被调用。

只有在isCustomizable()返回真（默认为假）时，Customize菜单项才会出现。

这个函数是有意图的，例如，提供给用户来告诉应用程序他们要自定义主窗口、锚接窗口或者锚接区域的一个手段。

默认实现是什么也不做，但是这可能在以后的Qt版本中发生改变。现在默认情况下，Customize菜单项不会显示在右键菜单中。如果你想让这项出现，那么请重新实现isCustomizable()来返回真。

也可以参考isCustomizable()。

void QMainWindow::dockWindowPositionChanged ( QDockWindow * dockWindow ) [信号]

当dockWindow已经改变位置时，这个信号被发射。当锚接窗口被移入它的锚接区域或者移到另一个锚接区域（包括Minimized和TearOff锚接区域）时，位置的变化发生。

也可以参考getLocation()。

QPtrList<QDockWindow> QMainWindow::dockWindows ( Dock dock ) const

返回在dock锚接区域的所有锚接窗口的列表，而不管它们的状态。

例如，TornOff锚接区域可能包含关闭的锚接窗口，但它们会和可视锚接窗口一起被返回。

QPtrList<QDockWindow> QMainWindow::dockWindows () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回属于主窗口的所有锚接窗口的列表，而不管它们的状态（也就是不考虑它们是否可视）。

bool QMainWindow::dockWindowsMovable () const

如果锚接窗口是可移动的，返回真，否则返回假。详细情况请参考“dockWindowsMovable”属性。

bool QMainWindow::getLocation ( QDockWindow * dw, Dock & dock, int & index, bool & nl, int & extraOffset ) const

找到锚接窗口dw的定位。

如果锚接窗口dw在主窗口中被找到，函数返回真并且dock变量为dw所在的锚接区域并且index为dw在锚接区域中的位置索引。如果dw开始一个新行，它也设置nl为真（否则为假），并且extraOffset为dw的位移。

如果dw在主窗口中没有被找到，那么这个函数返回真并且dock、index、nl和extraOffset的状态都是不确定的。

如果你想保存并且恢复锚接窗口的位置，那么请使用operator>>()和operator<<()。

也可以参考operator>>()和operator<<()。

bool QMainWindow::hasDockWindow ( QDockWindow * dw )

如果dw是被主窗口知道的锚接窗口，返回真，否则返回假。

bool QMainWindow::isCustomizable () const [虚]

如果锚接区域的锚接窗口菜单包含Customize菜单项（当它被点击时，会调用customize()），返回真。默认返回假，也就是弹出菜单不包含Customize菜单选项。如果你希望用户能在锚接窗口菜单中看到它时，你将需要重新实现这个函数并且把它设置为返回真。

也可以参考customize()。

bool QMainWindow::isDockEnabled ( Dock dock ) const

如果dock锚接区域是生效的，返回真，也就是它可以接收用户拖动的锚接窗口，否则返回假。

也可以参考setDockEnabled()。

bool QMainWindow::isDockEnabled ( QDockArea * area ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果area是生效的，返回真，也就是它可以接收用户拖动的锚接窗口，否则返回假。

也可以参考setDockEnabled()。

bool QMainWindow::isDockEnabled ( QDockWindow * tb, Dock dock ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果dock对于锚接窗口tb是生效的，返回真，否则返回假。

也可以参考setDockEnabled()。

bool QMainWindow::isDockEnabled ( QDockWindow * dw, QDockArea * area ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果area对于锚接窗口tb是生效的，返回真，否则返回假。

也可以参考setDockEnabled()。

bool QMainWindow::isDockMenuEnabled () const

如果锚接窗口菜单是生效的，返回真，否则返回假。

这个菜单会列出（appropriate()）锚接窗口（它们会被显示或者隐藏）并且有一个“Line Up Dock Windows”菜单项。如果isCustomizable()返回真，它也将会有一个“Customize”菜单项。

也可以参考setDockEnabled()、lineUpDockWindows()、appropriate()和setAppropriate()。

QDockArea * QMainWindow::leftDock () const

返回Left锚接区域。

也可以参考rightDock()、topDock()和bottomDock()。

void QMainWindow::lineUpDockWindows ( bool keepNewLines = FALSE )

这个函数将会尽量紧凑地排列在可视的锚接区域（Top、Left、Right和Bottom）中的锚接窗口。

如果keepNewLines为真，所有锚接窗口保持在它们的原有行中。如果keepNewLines为假，那么新行将别移除来达到最可能紧凑的布局。

这个方法只有在dockWindowsMovable()返回真的情况下才能够工作。

void QMainWindow::lineUpToolBars ( bool keepNewLines = FALSE )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QMainWindow::menuAboutToShow () [保护 槽]

这个槽会从主窗口的默认铆接菜单中地aboutToShow()信号调用。默认实现是在这个槽中用所有锚接窗口和菜单条来初始化这个菜单。

如果你想对这个菜单做小的调节，你可以在这个槽中做到这一点。另外要重新实现createDockWindowMenu()。

QMenuBar * QMainWindow::menuBar () const

返回这个窗口的菜单条。

如果这里一个也没有，那么menuBar()会创建一个空的菜单条。

也可以参考statusBar()。

void QMainWindow::moveDockWindow ( QDockWindow * dockWindow, Dock edge = DockTop ) [虚]

把dockWindow移动到edge的末尾。

对于垂直边缘，末尾是下面，对于水平边缘（包括Minimized），末尾是右面。

如果dockWindow被另一个主窗口管理，它首先被从那个窗口移除。

void QMainWindow::moveDockWindow ( QDockWindow * dockWindow, Dock edge, bool nl, int index, int extraOffset = -1 ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把dockWindow移动到edge的index位置。

任何在index或者更高位置的锚接窗口的位置数都被增加并且同一行的空间都被向右移（垂直区域的向下移）。

如果nl为真，一个新的锚接窗口行会在被移动的锚接窗口所在行下面创建新行，任何和被移动的锚接窗口在一行的并且位置更高的都被移到新行中。

extraOffset是放在这个锚接窗口和锚接区域的最左面（对于垂直锚接区域是最上面）的距离。（它通常用于恢复锚接窗口的位置为用于曾经拖到的位置。）

如果dockWindow被另一个主窗口管理，它首先被从那个窗口移除。

void QMainWindow::moveToolBar ( QDockWindow *, Dock = DockTop )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QMainWindow::moveToolBar ( QDockWindow *, Dock, bool nl, int index, int extraOffset = -1 )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

bool QMainWindow::opaqueMoving () const

如果锚接窗口被不透明地移动，返回真，否则返回假。详细情况请参考“opaqueMoving”属性。

void QMainWindow::pixmapSizeChanged ( bool ) [信号]

只要setUsesBigPixmaps()被使用和当前设置不同地值调用时，这个信号就被调用。所有窗口部件都应该对这个变化做出回应，例如工具条按钮必须连接到这个信号。

void QMainWindow::removeDockWindow ( QDockWindow * dockWindow ) [虚]

假如dockWindow为非零并且被这个主窗口管理，那么从主窗口的锚接区域移除dockWindow。

void QMainWindow::removeToolBar ( QDockWindow * )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

QDockArea * QMainWindow::rightDock () const

返回Right锚接区域。

也可以参考leftDock()、topDock()和bottomDock()。

bool QMainWindow::rightJustification () const

如果主窗口正确对齐它的锚接窗口，返回真，否则返回假。详细情况请参考“rightJustification”属性。

void QMainWindow::setAppropriate ( QDockWindow * dw, bool a ) [虚 槽]

使用这个函数来控制dw锚接窗口的标题是否应该作为一个菜单项显示在列出锚接窗口的锚接窗口菜单中。

如果a为真，那么dw将会作为一个菜单项显示在锚接窗口菜单中。用户能够通过点击这个菜单项来改变锚接窗口的状态（显示或者隐藏），根据你的应用程序的状态，这可能是也可能不是适合的。如果a为假，dw将会被显示在弹出菜单中。

也可以参考showDockMenu()、isCustomizable()和customize()。

void QMainWindow::setCentralWidget ( QWidget * w ) [虚]

设置这个窗口的中央窗口部件为w。

这个中央窗口部件被上、下、左、右锚接区域环绕。菜单条在上锚接区域的上面。

也可以参考centralWidget()。

void QMainWindow::setDockEnabled ( Dock dock, bool enable ) [虚]

如果enable为真，那么用户可以在dock区域中锚接窗口。如果enable为假，那么用户不可以在dock区域中锚接窗口。

用户可以把锚接窗口锚接（拖动）进入任何生效锚接区域。

void QMainWindow::setDockEnabled ( QDockWindow * dw, Dock dock, bool enable ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果enable为真，那么用户可以在dock区域中锚接窗口。如果enable为假，那么用户不可以在dock区域中锚接窗口。

通常用户可以把锚接窗口锚接（拖动）进入任何生效锚接区域。使用这个函数特定的锚接区域能够对特定地锚接窗口生效（或者失效）。

void QMainWindow::setDockMenuEnabled ( bool b ) [虚 槽]

如果b为真，那么在一个锚接窗口或者锚接区域上右键单击将会弹出锚接窗口菜单。如果b为假，那么在一个锚接窗口或者锚接区域上右键单击将不会弹出锚接窗口菜单。

这个菜单会列出（appropriate()）锚接窗口（它们会被显示或者隐藏）并且有一个“Line Up Dock Windows”菜单项。如果isCustomizable()返回真，它也将会有一个“Customize”菜单项。

也可以参考lineUpDockWindows()和isDockMenuEnabled()。

void QMainWindow::setDockWindowsMovable ( bool ) [虚 槽]

设置锚接窗口是否可以移动。详细情况请参考“dockWindowsMovable”属性。

void QMainWindow::setOpaqueMoving ( bool ) [虚 槽]

设置锚接窗口是否是被不透明地移动。详细情况请参考“opaqueMoving”属性。

void QMainWindow::setRightJustification ( bool ) [虚 槽]

设置主窗口是否右对齐它的锚接窗口。详细情况请参考“rightJustification”属性。

void QMainWindow::setToolBarsMovable ( bool ) [slot]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QMainWindow::setUpLayout () [虚 保护 槽]

设置窗口的几何形状管理。当需要的时候，它会被自动调用，所以你不需要调用它。

void QMainWindow::setUsesBigPixmaps ( bool ) [虚 槽]

设置大像素映射是否生效。详细情况请参考“usesBigPixmaps”属性。

void QMainWindow::setUsesTextLabel ( bool ) [虚 槽]

设置工具条按钮的文本标签是否生效。详细情况请参考“usesTextLabel”属性。

bool QMainWindow::showDockMenu ( const QPoint & globalPos ) [虚 保护 槽]

在globalPos位置显示锚接窗口菜单。这个菜单来出锚接窗口，所以它们可以被显示（或者隐藏）、排列并且可能会被定制。如果这个菜单被显示，返回真，否则返回假。

默认实现是使用得到由createDockWindowMenu()创建的锚接窗口。如果你想使用你自己特定的弹出菜单，你可以重新实现createDockWindowMenu()。

QStatusBar * QMainWindow::statusBar () const

返回这个窗口的状态条。如果没有的话，statusBar()会创建一个空的状态条，并且如果需要也创建一个工具提示组。

也可以参考menuBar()和toolTipGroup()。

实例：qfd/qfd.cpp。

void QMainWindow::toolBarPositionChanged ( QToolBar * ) [信号]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

QPtrList<QToolBar> QMainWindow::toolBars ( Dock dock ) const

返回在dock锚接区域的所有工具条的列表，而不管它们的状态。

例如，TornOff锚接区域可能包含关闭的工具条，但是它们会和可视的工具条一起被返回。

也可以参考dockWindows()。

bool QMainWindow::toolBarsMovable () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

QToolTipGroup * QMainWindow::toolTipGroup () const

返回这个窗口的工具提示组。如果没有的话，toolTipGroup()会自动创建一个空的工具提示组。

也可以参考menuBar()和statusBar()。

QDockArea * QMainWindow::topDock () const

返回Top锚接区域。

也可以参考bottomDock()、leftDock()和rightDock()。

bool QMainWindow::usesBigPixmaps () const

如果大像素映射生效，返回真，否则返回假。详细情况请参考“usesBigPixmaps”属性。

bool QMainWindow::usesTextLabel () const

如果工具条按钮的文本标签生效，返回真，否则返回假。详细情况请参考“usesTextLabel”属性。

void QMainWindow::usesTextLabelChanged ( bool ) [信号]

只要setUsesTextLabel()使用与当前设置不同的值被调用，这个信号被调用。所有窗口部件应该对这个变化做出回应，例如工具条按钮必须连接到这个信号。

void QMainWindow::whatsThis () [虚 槽]

进入“这是什么？”问题模式并且立即返回。

这和QWhatsThis::enterWhatsThisMode()是相同的，但是作为主窗口对象的槽而被重新实现。这个方式可以很容易地用于弹出菜单，例如：

    QPopupMenu * help = new QPopupMenu( this );
    help->insertItem( "What's &This", this , SLOT(whatsThis()), SHIFT+Key_F1);

也可以参考QWhatsThis::enterWhatsThisMode()。

属性文档

bool dockWindowsMovable

This property holds whether the dock windows are movable. 这个属性保存的是锚接窗口是否可以移动。

如果为真（默认），用户可以把可移动的锚接窗口从一个QMainWindow锚接区域移动到另一个，包括浮动（TearOff）区域（也就是，锚接窗口就其自身而言作为一个窗口自由地移动）和Minimized区域（就是锚接窗口的句柄被显示在菜单条下面的地方）。可移动锚接窗口也可以在QMainWindow的锚接区域内被移动，也就是说在一个锚接区域中重新整理它们。

如果为假，用户就不能移动任何锚接窗口。

默认情况下，锚接窗口是被透明地移动（也就是在拖动的时候，只显示一个边框矩形），但是这个设置可以通过setOpaqueMoving()改变。

也可以参考setDockEnabled()和opaqueMoving。

通过setDockWindowsMovable()设置属性值并且通过dockWindowsMovable()来获得属性值。

bool opaqueMoving

这个属性保存的是锚接窗口是否是被不透明地移动。

如果为真，当主窗口的锚接窗口被移动时，它显示为不透明地。如果为假（默认），它们被透明地显示（也就是一个边框矩形）。

工具条和锚接窗口的不透明移动已经被知道有一些问题。我们建议不要在这时使用这一点。我们将在稍后的发布中修改这个行为问题。

通过setOpaqueMoving()设置属性值并且通过opaqueMoving()来获得属性值。

bool rightJustification

这个属性保存的是主窗口是否右对齐它的锚接窗口。

如果失效（默认），可延伸的锚接窗口被延伸，并且不能延伸的锚接窗口被按它们需要的最小空间进行分配。因为绝大多数锚接窗口是不可延伸的，这通常会导致不对齐的右边缘结果（或者对于垂直的锚接区域是不对齐的下边缘）。如果生效，主窗口将会右对齐它的锚接窗口。

也可以参考QDockWindow::setVerticalStretchable()和QDockWindow::setHorizontalStretchable()。

通过setRightJustification()设置属性值并且通过rightJustification()来获得属性值。

bool usesBigPixmaps

这个属性保存的是大像素映射是否生效。

如果为假（默认），工具按钮将会使用小像素映射，否则大像素映射将被使用。

希望对这个设置做出反应的工具按钮和其它窗口部件要对在开始的时候读取正确的状态并且连接到主窗口部件的pixmapSizeChanged()信号连接起来负责。

通过setUsesBigPixmaps()设置属性值并且通过usesBigPixmaps()来获得属性值。

bool usesTextLabel

这个属性保存的是工具条按钮的文本标签是否生效。

如果失效（默认），工具按钮将不使用文本标签。如果生效，文本标签将被使用。

希望对这个设置做出反应的工具按钮和其它窗口部件要对在开始的时候读取正确的状态并且连接到主窗口部件的usesTextLabelChanged()信号连接起来负责。

也可以参考QToolButton::usesTextLabel。

通过setUsesTextLabel()设置属性值并且通过usesTextLabel()来获得属性值。

相关函数

QTextStream & operator<< ( QTextStream & ts, const QMainWindow & mainWindow )

把QMainWindow mainWindow的锚接区域中的锚接窗口，以及Minimized和TornOff锚接窗口的布局（大小和位置）都写到文本流ts中。

例如，这可以被用于和QSettings联合使用来保存用户的布局。

也可以参考operator>>()。

QTextStream & operator>> ( QTextStream & ts, QMainWindow & mainWindow )

从文本流ts中读入QMainWindow mainWindow的锚接区域中的锚接窗口，以及Minimized和TornOff锚接窗口的布局（大小和位置）。恢复锚接窗口和锚接区域的大小和位置。布局信息必须是由operator<<()生成的。

例如，这可以被用于和QSettings联合使用来恢复用户的布局。

也可以参考operator<<()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmainwindow.h包含文件

qmainwindow.h

这里是qmainwindow.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qmainwindow.h   3.0.5   edited Nov 30 2001 $
**
** Definition of QMainWindow class
**
** Created : 980316
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMAINWINDOW_H
#define QMAINWINDOW_H

#ifndef QT_H
#include "qwidget.h"
#include "qtoolbar.h"
#include "qptrlist.h"
#include "qtextstream.h"
#endif // QT_H

#ifndef QT_NO_MAINWINDOW

class QMenuBar;
class QStatusBar;
class QToolTipGroup;
class QMainWindowPrivate;
class QMainWindowLayout;
class QPopupMenu;

class Q_EXPORT QMainWindow: public QWidget
{
    Q_OBJECT
    Q_PROPERTY( bool rightJustification READ rightJustification WRITE setRightJustification )
    Q_PROPERTY( bool usesBigPixmaps READ usesBigPixmaps WRITE setUsesBigPixmaps )
    Q_PROPERTY( bool usesTextLabel READ usesTextLabel WRITE setUsesTextLabel )
    Q_PROPERTY( bool dockWindowsMovable READ dockWindowsMovable WRITE setDockWindowsMovable )
    Q_PROPERTY( bool opaqueMoving READ opaqueMoving WRITE setOpaqueMoving )

public:
    QMainWindow( QWidget* parent=0, const char* name=0, WFlags f = WType_TopLevel );
    ~QMainWindow();

#ifndef QT_NO_MENUBAR
    QMenuBar * menuBar() const;
#endif
    QStatusBar * statusBar() const;
#ifndef QT_NO_TOOLTIP
    QToolTipGroup * toolTipGroup() const;
#endif

    virtual void setCentralWidget( QWidget * );
    QWidget * centralWidget() const;

    virtual void setDockEnabled( Dock dock, bool enable );
    bool isDockEnabled( Dock dock ) const;
    bool isDockEnabled( QDockArea *area ) const;
    virtual void setDockEnabled( QDockWindow *tb, Dock dock, bool enable );
    bool isDockEnabled( QDockWindow *tb, Dock dock ) const;
    bool isDockEnabled( QDockWindow *tb, QDockArea *area ) const;

    virtual void addDockWindow( QDockWindow *, Dock = DockTop, bool newLine = FALSE );
    virtual void addDockWindow( QDockWindow *, const QString &label,
                Dock = DockTop, bool newLine = FALSE );
    virtual void moveDockWindow( QDockWindow *, Dock = DockTop );
    virtual void moveDockWindow( QDockWindow *, Dock, bool nl, int index, int extraOffset = -1 );
    virtual void removeDockWindow( QDockWindow * );

    void show();
    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    bool rightJustification() const;
    bool usesBigPixmaps() const;
    bool usesTextLabel() const;
    bool dockWindowsMovable() const;
    bool opaqueMoving() const;

    bool eventFilter( QObject*, QEvent* );

    bool getLocation( QDockWindow *tb, Dock &dock, int &index, bool &nl, int &extraOffset ) const;

    QPtrList<QDockWindow> dockWindows( Dock dock ) const;
    QPtrList<QDockWindow> dockWindows() const;
    void lineUpDockWindows( bool keepNewLines = FALSE );

    bool isDockMenuEnabled() const;

    // compatibility stuff
    bool hasDockWindow( QDockWindow *dw );
#ifndef QT_NO_TOOLBAR
    void addToolBar( QDockWindow *, Dock = DockTop, bool newLine = FALSE );
    void addToolBar( QDockWindow *, const QString &label,
             Dock = DockTop, bool newLine = FALSE );
    void moveToolBar( QDockWindow *, Dock = DockTop );
    void moveToolBar( QDockWindow *, Dock, bool nl, int index, int extraOffset = -1 );
    void removeToolBar( QDockWindow * );

    bool toolBarsMovable() const;
    QPtrList<QToolBar> toolBars( Dock dock ) const;
    void lineUpToolBars( bool keepNewLines = FALSE );
#endif

    virtual QDockArea *dockingArea( const QPoint &p );
    QDockArea *leftDock() const;
    QDockArea *rightDock() const;
    QDockArea *topDock() const;
    QDockArea *bottomDock() const;

    virtual bool isCustomizable() const;

    bool appropriate( QDockWindow *dw ) const;

    enum DockWindows { OnlyToolBars, NoToolBars, AllDockWindows };
    QPopupMenu *createDockWindowMenu( DockWindows dockWindows = AllDockWindows ) const;

public slots:
    virtual void setRightJustification( bool );
    virtual void setUsesBigPixmaps( bool );
    virtual void setUsesTextLabel( bool );
    virtual void setDockWindowsMovable( bool );
    virtual void setOpaqueMoving( bool );
    virtual void setDockMenuEnabled( bool );
    virtual void whatsThis();
    virtual void setAppropriate( QDockWindow *dw, bool a );
    virtual void customize();

    // compatibility stuff
    void setToolBarsMovable( bool );

signals:
    void pixmapSizeChanged( bool );
    void usesTextLabelChanged( bool );
    void dockWindowPositionChanged( QDockWindow * );

#ifndef QT_NO_TOOLBAR
    // compatibility stuff
    void toolBarPositionChanged( QToolBar * );
#endif

protected slots:
    virtual void setUpLayout();
    virtual bool showDockMenu( const QPoint &globalPos );
    void menuAboutToShow();

protected:
    void paintEvent( QPaintEvent * );
    void childEvent( QChildEvent * );
    bool event( QEvent * );
    void styleChange( QStyle& );

private slots:
    void slotPlaceChanged();
    void doLineUp() { lineUpDockWindows( TRUE ); }

private:
    QMainWindowPrivate * d;
    void triggerLayout( bool deleteLayout = TRUE);
    bool dockMainWindow( QObject *dock );

#ifndef QT_NO_MENUBAR
    virtual void setMenuBar( QMenuBar * );
#endif
    virtual void setStatusBar( QStatusBar * );
#ifndef QT_NO_TOOLTIP
    virtual void setToolTipGroup( QToolTipGroup * );
#endif

    friend class QDockWindow;
    friend class QMenuBar;
    friend class QHideDock;
    friend class QToolBar;
    friend class QMainWindowLayout;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMainWindow( const QMainWindow & );
    QMainWindow& operator=( const QMainWindow & );
#endif
};

#ifndef QT_NO_TOOLBAR
inline void QMainWindow::addToolBar( QDockWindow *w, ToolBarDock dock, bool newLine )
{
    addDockWindow( w, dock, newLine );
}

inline void QMainWindow::addToolBar( QDockWindow *w, const QString &label,
                  ToolBarDock dock, bool newLine )
{
    addDockWindow( w, label, dock, newLine );
}

inline void QMainWindow::moveToolBar( QDockWindow *w, ToolBarDock dock )
{
    moveDockWindow( w, dock );
}

inline void QMainWindow::moveToolBar( QDockWindow *w, ToolBarDock dock, bool nl, int index, int extraOffset )
{
    moveDockWindow( w, dock, nl, index, extraOffset );
}

inline void QMainWindow::removeToolBar( QDockWindow *w )
{
    removeDockWindow( w );
}

inline bool QMainWindow::toolBarsMovable() const
{
    return dockWindowsMovable();
}

inline void QMainWindow::lineUpToolBars( bool keepNewLines )
{
    lineUpDockWindows( keepNewLines );
}

inline void QMainWindow::setToolBarsMovable( bool b )
{
    setDockWindowsMovable( b );
}
#endif

#ifndef QT_NO_TEXTSTREAM
Q_EXPORT QTextStream &operator<<( QTextStream &, const QMainWindow & );
Q_EXPORT QTextStream &operator>>( QTextStream &, QMainWindow & );
#endif

#endif // QT_NO_MAINWINDOW

#endif // QMAINWINDOW_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMainWindow成员列表

完整的QMainWindow成员列表

这里是QMainWindow成员函数的完整列表，包括继承的成员。

  • QMainWindow()
  • ~QMainWindow()
  • acceptDrops()
  • addDockWindow()
  • addToolBar()
  • adjustSize()
  • appropriate()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomDock()
  • caption()
  • centralWidget()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • createDockWindowMenu()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • customize()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dockWindowPositionChanged()
  • dockWindows()
  • dockWindowsMovable()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getLocation()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasDockWindow()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isCustomizable()
  • isDesktop()
  • isDialog()
  • isDockEnabled()
  • isDockMenuEnabled()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftDock()
  • lineUpDockWindows()
  • lineUpToolBars()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • menuAboutToShow()
  • menuBar()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveDockWindow()
  • moveEvent()
  • moveToolBar()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • opaqueMoving()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmapSizeChanged()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeDockWindow()
  • removeEventFilter()
  • removeToolBar()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • rightDock()
  • rightJustification()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAppropriate()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCentralWidget()
  • setCursor()
  • setDisabled()
  • setDockEnabled()
  • setDockMenuEnabled()
  • setDockWindowsMovable()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOpaqueMoving()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRightJustification()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setToolBarsMovable()
  • setUpLayout()
  • setUpdatesEnabled()
  • setUsesBigPixmaps()
  • setUsesTextLabel()
  • setWFlags()
  • show()
  • showDockMenu()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • statusBar()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • toolBarPositionChanged()
  • toolBars()
  • toolBarsMovable()
  • toolTipGroup()
  • topDock()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • usesBigPixmaps()
  • usesTextLabel()
  • usesTextLabelChanged()
  • visibleRect()
  • whatsThis()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMap Class

QMap Class Reference

The QMap class is a value-based template class that provides a dictionary. More...

#include <qmap.h>

List of all member functions.

Public Members

  • typedef Key key_type
  • typedef T mapped_type
  • typedef QPair<const key_type, mapped_type> value_type
  • typedef value_type * pointer
  • typedef const value_type * const_pointer
  • typedef value_type & reference
  • typedef const value_type & const_reference
  • typedef size_t size_type
  • typedef QMapIterator<Key, T> iterator
  • typedef QMapConstIterator<Key, T> const_iterator
  • typedef QPair<iterator, bool> insert_pair
  • QMap ()
  • QMap ( const QMap<Key, T> & m )
  • QMap ( const std::map<Key, T> & m )
  • ~QMap ()
  • QMap<Key, T> & operator= ( const QMap<Key, T> & m )
  • QMap<Key, T> & operator= ( const std::map<Key, T> & m )
  • iterator begin ()
  • iterator end ()
  • const_iterator begin () const
  • const_iterator end () const
  • iterator replace ( const Key & k, const T & v )
  • size_type size () const
  • bool empty () const
  • QPair<iterator, bool> insert ( const value_type & x )
  • void erase ( iterator it )
  • void erase ( const key_type & k )
  • size_type count ( const key_type & k ) const
  • T & operator[] ( const Key & k )
  • void clear ()
  • typedef QMapIterator<Key, T> Iterator
  • typedef QMapConstIterator<Key, T> ConstIterator
  • typedef T ValueType
  • iterator find ( const Key & k )
  • const_iterator find ( const Key & k ) const
  • const T & operator[] ( const Key & k ) const
  • bool contains ( const Key & k ) const
  • size_type count () const
  • QValueList<Key> keys () const
  • QValueList<T> values () const
  • bool isEmpty () const
  • iterator insert ( const Key & key, const T & value, bool overwrite = TRUE )
  • void remove ( iterator it )
  • void remove ( const Key & k )

Protected Members

  • void detach ()

Related Functions

  • QDataStream & operator>> ( QDataStream & s, QMap<Key, T> & m )
  • QDataStream & operator<< ( QDataStream & s, const QMap<Key, T> & m )

Detailed Description

The QMap class is a value-based template class that provides a dictionary.

QMap is a Qt implementation of an STL-like map container. It can be used in your application if the standard map is not available. QMap is part of the Qt Template Library.

QMap<Key, Data> defines a template instance to create a dictionary with keys of type Key and values of type Data. QMap does not store pointers to the members of the map; instead, it holds a copy of every member. For that reason, QMap is value-based, whereas QPtrList and QDict are pointer-based.

QMap contains and manages a collection of objects of type Data with associated key values of type Key and provides iterators that allow the contained objects to be addressed. QMap owns the contained items.

Some classes cannot be used within a QMap. For example everything derived from QObject and thus all classes that implement widgets. Only values can be used in a QMap. To qualify as a value, the class must provide

  • A copy constructor
  • An assignment operator
  • A default constructor, i.e. a constructor that does not take any arguments.

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases, this is sufficient.

The class used for the key requires that the operator< is implemented to define ordering of the keys.

QMap's function naming is consistent with the other Qt classes (e.g., count(), isEmpty()). QMap also provides extra functions for compatibility with STL algorithms, such as size() and empty(). Programmers already familiar with the STL map can use these functions instead.

Example:

    #include <qstring.h>
    #include <qmap.h>
    #include <qstring.h>

    class Employee
    {
    public:
        Employee(): sn(0) {}
        Employee( const QString& forename, const QString& surname, int salary )
            : fn(forename), sn(surname), sal(salary)
        { }

        QString forename() const { return fn; }
        QString surname() const { return sn; }
        int salary() const { return sal; }
        void setSalary( int salary ) { sal = salary; }

    private:
        QString fn;
        QString sn;
        int sal;
    };

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

        typedef QMap<QString, Employee> EmployeeMap;
        EmployeeMap map;

        map["JD001"] = Employee("John", "Doe", 50000);
        map["JD002"] = Employee("Jane", "Williams", 80000);
        map["TJ001"] = Employee("Tom", "Jones", 60000);

        Employee sasha( "Sasha", "Hind", 50000 );
        map["SH001"] = sasha;
        sasha.setSalary( 40000 );

        EmployeeMap::Iterator it;
        for ( it = map.begin(); it != map.end(); ++it ) {
            printf( "%s: %s, %s earns %d\n",
                    it.key().latin1(),
                    it.data().surname().latin1(),
                    it.data().forename().latin1(),
                    it.data().salary() );
        }
        return 0;
    }

Program output:

    JD001: Doe, John earns 50000
    JW002: Williams, Jane earns 80000
    SH001: Hind, Sasha earns 50000
    TJ001: Jones, Tom earns 60000

The latest changes to Sasha's salary did not affect the value in the list because the map created a copy of Sasha's entry. In addition, notice that the items are sorted alphabetically (by key) when iterating over the map.

There are several ways to find items in a map. The begin() and end() functions return iterators to the beginning and end of the map. The advantage of using an iterator is that you can move forward or backward by incrementing/decrementing the iterator. The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value. If the map is empty, the iterator returned by begin() will equal the iterator returned by end().

Another way to find an element in the map is by using the find() function. This returns an iterator pointing to the desired item or to the end() iterator if no such element exists.

Another approach uses the operator[]. But be warned: if the map does not contain an entry for the element you are looking for, operator[] inserts a default value. If you do not know that the element you are searching for is really in the list, you should not use operator[]. The following example illustrates this:

        QMap<QString,QString> map;
        map["Clinton"] = "Bill";
        str << map["Clinton"] << map["Bush"] << endl;

The code fragment will print out "Clinton", "". Since the value associated with the "Bush" key did not exist, the map inserted a default value (in this case, an empty string). If you are not sure whether a certain element is in the map, you should use find() and iterators instead.

If you just want to know whether a certain key is contained in the map, use the contains() function. In addition, count() tells you how many keys there are currently in the map.

It is safe to have multiple iterators at the same time. If some member of the map is removed, only iterators pointing to the removed member become invalid; inserting in the map does not invalidate any iterators.

Since QMap is value-based, there is no need to be concerned about deleting items in the map. The map holds its own copies and will free them if the corresponding member or the map itself is deleted.

QMap is implicitly shared. This means you can just make copies of the map in time O(1). If multiple QMap instances share the same data and one is modifying the map's data, this modifying instance makes a copy and modifies its private copy; it thus does not affect other instances. From a developer's point of view you can think that a QMap and a copy of this map have nothing to do with each other. If a QMap is being used in a multi-threaded program, you must protect all access to the map. See QMutex.

There are several ways of inserting new items into the map. One uses the insert() method; the other one uses operator[] like this:

    QMap<QString, QString> map;
    map["Clinton"] = "Bill";
    map.insert( qMakePair("Bush", "George") );

Items can also be removed from the map in several ways. The first is to pass an iterator to remove(). The other is to pass a key value to remove(), which will delete the entry with the requested key. In addition you can clear the entire map using the clear() method.

See also QMapIterator, Qt Template Library Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

Member Type Documentation

QMap::ConstIterator

The map's const iterator type, Qt style.

QMap::Iterator

The map's iterator type, Qt style.

QMap::ValueType

Corresponds to QPair<key_type, mapped_type>, Qt style.

QMap::const_iterator

The map's const iterator type.

QMap::const_pointer

Const pointer to value_type.

QMap::const_reference

Const reference to value_type.

QMap::iterator

The map's iterator type.

QMap::key_type

The map's key type.

QMap::mapped_type

The map's data type.

QMap::pointer

Pointer to value_type.

QMap::reference

Reference to value_type.

QMap::size_type

An unsigned integral type, used to represent various sizes.

QMap::value_type

Corresponds to QPair<key_type, mapped_type>.

Member Function Documentation

QMap::QMap ()

Constructs an empty map.

QMap::QMap ( const QMap<Key, T> & m )

Constructs a copy of m.

This operation costs O(1) time because QMap is implicitly shared. The first instance of applying modifications to a shared map will create a copy that takes in turn O(n) time. However, returning a QMap from a function is very fast.

QMap::QMap ( const std::map<Key, T> & m )

Constructs a copy of m.

QMap::~QMap ()

Destroys the map. References to the values in the map and all iterators of this map become invalidated. Since QMap is highly tuned for performance you won't see warnings if you use invalid iterators, because it is not possible for an iterator to check whether it is valid or not.

iterator QMap::begin ()

Returns an iterator pointing to the first element in the map. This iterator equals end() if the map is empty.

The items in the map are traversed in the order defined by operator<(Key, Key).

See also end() and QMapIterator.

const_iterator QMap::begin () const

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

See also end() and QMapConstIterator.

void QMap::clear ()

Removes all items from the map.

See also remove().

bool QMap::contains ( const Key & k ) const

Returns TRUE if the map contains an item with key k; otherwise returns FALSE.

size_type QMap::count ( const key_type & k ) const

Returns the number of items whose key is k. Since QMap does not allow duplicate keys, the return value is always 0 or 1.

This function is provided for STL compatibility.

size_type QMap::count () const

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

Returns the number of items in the map.

See also isEmpty().

void QMap::detach () [protected]

If the map does not share its data with another QMap instance, nothing happens; otherwise the function creates a new copy of this map and detaches from the shared one. This function is called whenever the map is modified. The implicit sharing mechanism is implemented this way.

bool QMap::empty () const

Returns TRUE if the map contains zero items; otherwise returns FALSE.

This function is provided for STL compatibility. It is equivalent to isEmpty().

See also size().

iterator QMap::end ()

The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value.

This iterator equals begin() if the map is empty.

See also begin() and QMapIterator.

const_iterator QMap::end () const

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

The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the map it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value.

This iterator equals begin() if the map is empty.

See also begin() and QMapConstIterator.

void QMap::erase ( iterator it )

Removes the item associated with the iterator it from the map.

This function is provided for STL compatibility. It is equivalent to remove().

See also clear().

void QMap::erase ( const key_type & k )

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

Removes the item with the key k from the map.

iterator QMap::find ( const Key & k )

Returns an iterator pointing to the element with key k in the map.

Returns end() if no key matched.

See also QMapIterator.

const_iterator QMap::find ( const Key & k ) const

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

Returns an iterator pointing to the element with key k in the map.

Returns end() if no key matched.

See also QMapConstIterator.

iterator QMap::insert ( const Key & key, const T & value, bool overwrite = TRUE )

Inserts the value with key. If there is already a value associated with key, it is replaced, unless overwrite is FALSE (it is TRUE by default).

QPair<iterator, bool> QMap::insert ( const value_type & x )

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

Inserts the (key, value) pair x into the map. x is a QPair whose first element is a key to be inserted and whose second element is the associated value to be inserted. Returns a pair whose first element is an iterator pointing to the inserted item and whose second element is a bool indicating TRUE if x was inserted and FALSE if it was not inserted because it was already present.

bool QMap::isEmpty () const

Returns TRUE if the map contains zero items; otherwise returns FALSE.

See also count().

QValueList<Key> QMap::keys () const

Returns a list of all the keys in the map.

QMap<Key, T> & QMap::operator= ( const QMap<Key, T> & m )

Assigns m to this map and returns a reference to this map.

All iterators of the current map become invalidated by this operation. The cost of such an assignment is O(1), because QMap is implicitly shared.

QMap<Key, T> & QMap::operator= ( const std::map<Key, T> & m )

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

Assigns m to this map and returns a reference to this map.

All iterators of the current map become invalidated by this operation.

T & QMap::operator[] ( const Key & k )

Returns the value associated with the key k. If no such key is present, an empty item is inserted with this key and a reference to the item is returned.

You can use this operator both for reading and writing:

    QMap<QString, QString> map;
    map["Clinton"] = "Bill";
    stream << map["Clinton"];

const T & QMap::operator[] ( const Key & k ) const

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

Warning: This function differs from the non-const version of the same function. It will not insert an empty value if the key k does not exist. This may lead to logic errors in your program. You should check if the element exists before calling this function.

Returns the value associated with the key k. If no such key is present, a reference to an empty item is returned.

void QMap::remove ( iterator it )

Removes the item associated with the iterator it from the map.

See also clear().

void QMap::remove ( const Key & k )

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

Removes the item with the key k from the map.

iterator QMap::replace ( const Key & k, const T & v )

Replaces the value with key k from the map if possible, and inserts the new value v with key k in the map.

See also insert() and remove().

size_type QMap::size () const

Returns the number of items in the map.

This function is provided for STL compatibility. It is equivalent to count().

See also empty().

QValueList<T> QMap::values () const

Returns a list of all the values in the map.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QMap<Key, T> & m )

Writes the map m to the stream s. The types Key and T must implement the streaming operator as well.

QDataStream & operator>> ( QDataStream & s, QMap<Key, T> & m )

Reads the map m from the stream s. The types Key and T must implement the streaming operator as well.

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


qmap.h Include File

qmap.h

This is the verbatim text of the qmap.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmap.h   3.0.5   edited Jun 7 04:20 $
**
** Definition of QMap class
**
** Created : 990406
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMAP_H
#define QMAP_H

#ifndef QT_H
#include "qglobal.h"
#include "qshared.h"
#include "qdatastream.h"
#include "qpair.h"
#include "qtl.h"
#include "qvaluelist.h"
#endif // QT_H

#ifndef QT_NO_STL
#include <iterator>
#include <map>
#endif

//#define QT_CHECK_MAP_RANGE

struct Q_EXPORT QMapNodeBase
{
    enum Color { Red, Black };

    QMapNodeBase* left;
    QMapNodeBase* right;
    QMapNodeBase* parent;

    Color color;

    QMapNodeBase* minimum() {
    QMapNodeBase* x = this;
    while ( x->left )
        x = x->left;
    return x;
    }

    QMapNodeBase* maximum() {
    QMapNodeBase* x = this;
    while ( x->right )
        x = x->right;
    return x;
    }
};

template <class K, class T>
struct QMapNode : public QMapNodeBase
{
    QMapNode( const K& _key, const T& _data ) { data = _data; key = _key; }
    QMapNode( const K& _key )	   { key = _key; }
    QMapNode( const QMapNode<K,T>& _n ) { key = _n.key; data = _n.data; }
    QMapNode() { }
    T data;
    K key;
};

template<class K, class T>
class QMapIterator
{
 public:
    /**
     * Typedefs
     */
    typedef QMapNode< K, T >* NodePtr;
#ifndef QT_NO_STL
    typedef std::bidirectional_iterator_tag  iterator_category;
#endif
    typedef T          value_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif
    typedef T*         pointer;
    typedef T&         reference;

    /**
     * Variables
     */
    QMapNode<K,T>* node;

    /**
     * Functions
     */
    QMapIterator() : node( 0 ) {}
    QMapIterator( QMapNode<K,T>* p ) : node( p ) {}
    QMapIterator( const QMapIterator<K,T>& it ) : node( it.node ) {}

    bool operator==( const QMapIterator<K,T>& it ) const { return node == it.node; }
    bool operator!=( const QMapIterator<K,T>& it ) const { return node != it.node; }
    T& operator*() { return node->data; }
    const T& operator*() const { return node->data; }
    // UDT for T = x*
    // T* operator->() const { return &node->data; }

    const K& key() const { return node->key; }
    T& data() { return node->data; }
    const T& data() const { return node->data; }

private:
    int inc();
    int dec();

public:
    QMapIterator<K,T>& operator++() {
    inc();
    return *this;
    }

    QMapIterator<K,T> operator++(int) {
    QMapIterator<K,T> tmp = *this;
    inc();
    return tmp;
    }

    QMapIterator<K,T>& operator--() {
    dec();
    return *this;
    }

    QMapIterator<K,T> operator--(int) {
    QMapIterator<K,T> tmp = *this;
    dec();
    return tmp;
    }
};

template <class K, class T>
Q_INLINE_TEMPLATES int QMapIterator<K,T>::inc()
{
    QMapNodeBase* tmp = node;
    if ( tmp->right ) {
    tmp = tmp->right;
    while ( tmp->left )
        tmp = tmp->left;
    } else {
    QMapNodeBase* y = tmp->parent;
    while (tmp == y->right) {
        tmp = y;
        y = y->parent;
    }
    if (tmp->right != y)
        tmp = y;
    }
    node = (NodePtr)tmp;
    return 0;
}

template <class K, class T>
Q_INLINE_TEMPLATES int QMapIterator<K,T>::dec()
{
    QMapNodeBase* tmp = node;
    if (tmp->color == QMapNodeBase::Red &&
    tmp->parent->parent == tmp ) {
    tmp = tmp->right;
    } else if (tmp->left != 0) {
    QMapNodeBase* y = tmp->left;
    while ( y->right )
        y = y->right;
    tmp = y;
    } else {
    QMapNodeBase* y = tmp->parent;
    while (tmp == y->left) {
        tmp = y;
        y = y->parent;
    }
    tmp = y;
    }
    node = (NodePtr)tmp;
    return 0;
}

template<class K, class T>
class QMapConstIterator
{
 public:
    /**
     * Typedefs
     */
    typedef QMapNode< K, T >* NodePtr;
#ifndef QT_NO_STL
    typedef std::bidirectional_iterator_tag  iterator_category;
#endif
    typedef T          value_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif
    typedef const T*   pointer;
    typedef const T&   reference;

    /**
     * Variables
     */
    QMapNode<K,T>* node;

    /**
     * Functions
     */
    QMapConstIterator() : node( 0 ) {}
    QMapConstIterator( QMapNode<K,T>* p ) : node( p ) {}
    QMapConstIterator( const QMapConstIterator<K,T>& it ) : node( it.node ) {}
    QMapConstIterator( const QMapIterator<K,T>& it ) : node( it.node ) {}

    bool operator==( const QMapConstIterator<K,T>& it ) const { return node == it.node; }
    bool operator!=( const QMapConstIterator<K,T>& it ) const { return node != it.node; }
    const T& operator*()  const { return node->data; }
    // UDT for T = x*
    // const T* operator->() const { return &node->data; }

    const K& key() const { return node->key; }
    const T& data() const { return node->data; }

private:
    int inc();
    int dec();

public:
    QMapConstIterator<K,T>& operator++() {
    inc();
    return *this;
    }

    QMapConstIterator<K,T> operator++(int) {
    QMapConstIterator<K,T> tmp = *this;
    inc();
    return tmp;
    }

    QMapConstIterator<K,T>& operator--() {
    dec();
    return *this;
    }

    QMapConstIterator<K,T> operator--(int) {
    QMapConstIterator<K,T> tmp = *this;
    dec();
    return tmp;
    }
};

template <class K, class T>
Q_INLINE_TEMPLATES int QMapConstIterator<K,T>::inc()
{
    QMapNodeBase* tmp = node;
    if ( tmp->right ) {
    tmp = tmp->right;
    while ( tmp->left )
        tmp = tmp->left;
    } else {
    QMapNodeBase* y = tmp->parent;
    while (tmp == y->right) {
        tmp = y;
        y = y->parent;
    }
    if (tmp->right != y)
        tmp = y;
    }
    node = (NodePtr)tmp;
    return 0;
}

template <class K, class T>
Q_INLINE_TEMPLATES int QMapConstIterator<K,T>::dec()
{
    QMapNodeBase* tmp = node;
    if (tmp->color == QMapNodeBase::Red &&
    tmp->parent->parent == tmp ) {
    tmp = tmp->right;
    } else if (tmp->left != 0) {
    QMapNodeBase* y = tmp->left;
    while ( y->right )
        y = y->right;
    tmp = y;
    } else {
    QMapNodeBase* y = tmp->parent;
    while (tmp == y->left) {
        tmp = y;
        y = y->parent;
    }
    tmp = y;
    }
    node = (NodePtr)tmp;
    return 0;
}

class Q_EXPORT QMapPrivateBase : public QShared
{
public:
    QMapPrivateBase() {
    node_count = 0;
    }
    QMapPrivateBase( const QMapPrivateBase* _map) {
    node_count = _map->node_count;
    }

    /**
     * Implementations of basic tree algorithms
     */
    void rotateLeft( QMapNodeBase* x, QMapNodeBase*& root);
    void rotateRight( QMapNodeBase* x, QMapNodeBase*& root );
    void rebalance( QMapNodeBase* x, QMapNodeBase*& root );
    QMapNodeBase* removeAndRebalance( QMapNodeBase* z, QMapNodeBase*& root,
                      QMapNodeBase*& leftmost,
                      QMapNodeBase*& rightmost );

    /**
     * Variables
     */
    int node_count;
};

template <class Key, class T>
class QMapPrivate : public QMapPrivateBase
{
public:
    /**
     * Typedefs
     */
    typedef QMapIterator< Key, T > Iterator;
    typedef QMapConstIterator< Key, T > ConstIterator;
    typedef QMapNode< Key, T > Node;
    typedef QMapNode< Key, T >* NodePtr;

    /**
     * Functions
     */
    QMapPrivate();
    QMapPrivate( const QMapPrivate< Key, T >* _map );
    ~QMapPrivate() { clear(); delete header; }

    NodePtr copy( NodePtr p );
    void clear();
    void clear( NodePtr p );

    Iterator begin()	{ return Iterator( (NodePtr)(header->left ) ); }
    Iterator end()	{ return Iterator( header ); }
    ConstIterator begin() const { return ConstIterator( (NodePtr)(header->left ) ); }
    ConstIterator end() const { return ConstIterator( header ); }

    ConstIterator find(const Key& k) const;

    void remove( Iterator it ) {
    NodePtr del = (NodePtr) removeAndRebalance( it.node, header->parent, header->left, header->right );
    delete del;
    --node_count;
    }

#ifdef QT_QMAP_DEBUG
    void inorder( QMapNodeBase* x = 0, int level = 0 ){
    if ( !x )
        x = header->parent;
    if ( x->left )
        inorder( x->left, level + 1 );
    //cout << level << " Key=" << key(x) << " Value=" << ((NodePtr)x)->data << endl;
    if ( x->right )
        inorder( x->right, level + 1 );
    }
#endif

#if 0
    Iterator insertMulti(const Key& v){
    QMapNodeBase* y = header;
    QMapNodeBase* x = header->parent;
    while (x != 0){
        y = x;
        x = ( v < key(x) ) ? x->left : x->right;
    }
    return insert(x, y, v);
    }
#endif

    Iterator insertSingle( const Key& k );
    Iterator insert( QMapNodeBase* x, QMapNodeBase* y, const Key& k );

protected:
    /**
     * Helpers
     */
    const Key& key( QMapNodeBase* b ) const { return ((NodePtr)b)->key; }

    /**
     * Variables
     */
    NodePtr header;
};

template <class Key, class T>
Q_INLINE_TEMPLATES QMapPrivate<Key,T>::QMapPrivate() {
    header = new Node;
    header->color = QMapNodeBase::Red; // Mark the header
    header->parent = 0;
    header->left = header->right = header;
}
template <class Key, class T>
Q_INLINE_TEMPLATES QMapPrivate<Key,T>::QMapPrivate( const QMapPrivate< Key, T >* _map ) : QMapPrivateBase( _map ) {
    header = new Node;
    header->color = QMapNodeBase::Red; // Mark the header
    if ( _map->header->parent == 0 ) {
    header->parent = 0;
    header->left = header->right = header;
    } else {
    header->parent = copy( (NodePtr)(_map->header->parent) );
    header->parent->parent = header;
    header->left = header->parent->minimum();
    header->right = header->parent->maximum();
    }
}

template <class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMapPrivate<Key,T>::NodePtr QMapPrivate<Key,T>::copy( Q_TYPENAME QMapPrivate<Key,T>::NodePtr p )
{
    if ( !p )
    return 0;
    NodePtr n = new Node( *p );
    n->color = p->color;
    if ( p->left ) {
    n->left = copy( (NodePtr)(p->left) );
    n->left->parent = n;
    } else {
    n->left = 0;
    }
    if ( p->right ) {
    n->right = copy( (NodePtr)(p->right) );
    n->right->parent = n;
    } else {
    n->right = 0;
    }
    return n;
}

template <class Key, class T>
Q_INLINE_TEMPLATES void QMapPrivate<Key,T>::clear()
{
    clear( (NodePtr)(header->parent) );
    header->color = QMapNodeBase::Red;
    header->parent = 0;
    header->left = header->right = header;
    node_count = 0;
}

template <class Key, class T>
Q_INLINE_TEMPLATES void QMapPrivate<Key,T>::clear( Q_TYPENAME QMapPrivate<Key,T>::NodePtr p )
{
    while ( p != 0 ) {
    clear( (NodePtr)p->right );
    NodePtr y = (NodePtr)p->left;
    delete p;
    p = y;
    }
}

template <class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMapPrivate<Key,T>::ConstIterator QMapPrivate<Key,T>::find(const Key& k) const
{
    QMapNodeBase* y = header;        // Last node
    QMapNodeBase* x = header->parent; // Root node.

    while ( x != 0 ) {
    // If as k <= key(x) go left
    if ( !( key(x) < k ) ) {
        y = x;
        x = x->left;
    } else {
        x = x->right;
    }
    }

    // Was k bigger/smaller then the biggest/smallest
    // element of the tree ? Return end()
    if ( y == header || k < key(y) )
    return ConstIterator( header );
    return ConstIterator( (NodePtr)y );
}

template <class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMapPrivate<Key,T>::Iterator QMapPrivate<Key,T>::insertSingle( const Key& k )
{
    // Search correct position in the tree
    QMapNodeBase* y = header;
    QMapNodeBase* x = header->parent;
    bool result = TRUE;
    while ( x != 0 ) {
    result = ( k < key(x) );
    y = x;
    x = result ? x->left : x->right;
    }
    // Get iterator on the last not empty one
    Iterator j( (NodePtr)y );
    if ( result ) {
    // Smaller then the leftmost one ?
    if ( j == begin() ) {
        return insert(x, y, k );
    } else {
        // Perhaps daddy is the right one ?
        --j;
    }
    }
    // Really bigger ?
    if ( (j.node->key) < k )
    return insert(x, y, k );
    // We are going to replace a node
    return j;
}

template <class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMapPrivate<Key,T>::Iterator QMapPrivate<Key,T>::insert( QMapNodeBase* x, QMapNodeBase* y, const Key& k )
{
    NodePtr z = new Node( k );
    if (y == header || x != 0 || k < key(y) ) {
    y->left = z;                // also makes leftmost = z when y == header
    if ( y == header ) {
        header->parent = z;
        header->right = z;
    } else if ( y == header->left )
        header->left = z;           // maintain leftmost pointing to min node
    } else {
    y->right = z;
    if ( y == header->right )
        header->right = z;          // maintain rightmost pointing to max node
    }
    z->parent = y;
    z->left = 0;
    z->right = 0;
    rebalance( z, header->parent );
    ++node_count;
    return Iterator(z);
}

#ifdef QT_CHECK_RANGE
# if !defined( QT_NO_DEBUG ) && defined( QT_CHECK_MAP_RANGE )
#  define QT_CHECK_INVALID_MAP_ELEMENT if ( empty() ) qWarning( "QMap: Warning invalid element" )
#  define QT_CHECK_INVALID_MAP_ELEMENT_FATAL Q_ASSERT( !empty() );
# else
#  define QT_CHECK_INVALID_MAP_ELEMENT
#  define QT_CHECK_INVALID_MAP_ELEMENT_FATAL
# endif
#else
# define QT_CHECK_INVALID_MAP_ELEMENT
# define QT_CHECK_INVALID_MAP_ELEMENT_FATAL
#endif

template<class Key, class T>
class QMap
{
public:
    /**
     * Typedefs
     */
    typedef Key key_type;
    typedef T mapped_type;
    typedef QPair<const key_type, mapped_type> value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type& reference;
    typedef const value_type& const_reference;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif
    typedef size_t      size_type;
    typedef QMapIterator<Key,T> iterator;
    typedef QMapConstIterator<Key,T> const_iterator;
    typedef QPair<iterator,bool> insert_pair;

    /**
     * API
     */
    QMap()
    {
    sh = new QMapPrivate< Key, T >;
    }
    QMap( const QMap<Key,T>& m )
    {
    sh = m.sh; sh->ref();
    }

#ifndef QT_NO_STL
    QMap( const Q_TYPENAME std::map<Key,T>& m )
    {
    sh = new QMapPrivate<Key,T>;
#if defined(Q_OS_WIN32)
    std::map<Key,T>::const_iterator it = m.begin();
#else
    QMapConstIterator<Key,T> it = m.begin();
#endif
    for ( ; it != m.end(); ++it ) {
        value_type p( (*it).first, (*it).second );
        insert( p );
    }
    }
#endif
    ~QMap()
    {
    if ( sh->deref() )
        delete sh;
    }
    QMap<Key,T>& operator= ( const QMap<Key,T>& m );
#ifndef QT_NO_STL
    QMap<Key,T>& operator= ( const Q_TYPENAME std::map<Key,T>& m )
    {
    clear();
#if defined(Q_OS_WIN32)
    std::map<Key,T>::const_iterator it = m.begin();
#else
    QMapConstIterator<Key,T> it = m.begin();
#endif
    for ( ; it != m.end(); ++it ) {
        value_type p( (*it).first, (*it).second );
        insert( p );
    }
    return *this;
    }
#endif

    iterator begin() { detach(); return sh->begin(); }
    iterator end() { detach(); return sh->end(); }
    const_iterator begin() const { return ((const Priv*)sh)->begin(); }
    const_iterator end() const { return ((const Priv*)sh)->end(); }
    iterator replace( const Key& k, const T& v )
    {
    remove( k );
    return insert( k, v );
    }

    size_type size() const
    {
    return sh->node_count;
    }
    bool empty() const
    {
    return sh->node_count == 0;
    }
    QPair<iterator,bool> insert( const value_type& x );

    void erase( iterator it )
    {
    detach();
    sh->remove( it );
    }
    void erase( const key_type& k );
    size_type count( const key_type& k ) const;
    T& operator[] ( const Key& k );
    void clear();

    typedef QMapIterator< Key, T > Iterator;
    typedef QMapConstIterator< Key, T > ConstIterator;
    typedef T ValueType;
    typedef QMapPrivate< Key, T > Priv;

    iterator find ( const Key& k )
    {
    detach();
    return iterator( sh->find( k ).node );
    }
    const_iterator find ( const Key& k ) const {	return sh->find( k ); }

    const T& operator[] ( const Key& k ) const
    { QT_CHECK_INVALID_MAP_ELEMENT; return sh->find( k ).data(); }
    bool contains ( const Key& k ) const
    { return find( k ) != end(); }
    //{ return sh->find( k ) != ((const Priv*)sh)->end(); }

    size_type count() const { return sh->node_count; }

    QValueList<Key> keys() const {
    QValueList<Key> r;
    for (const_iterator i=begin(); i!=end(); ++i)
        r.append(i.key());
    return r;
    }

    QValueList<T> values() const {
    QValueList<T> r;
    for (const_iterator i=begin(); i!=end(); ++i)
        r.append(*i);
    return r;
    }

    bool isEmpty() const { return sh->node_count == 0; }

    iterator insert( const Key& key, const T& value, bool overwrite = TRUE );
    void remove( iterator it ) { detach(); sh->remove( it ); }
    void remove( const Key& k );

#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const QMap<Key,T>& ) const { return FALSE; }
#ifndef QT_NO_STL
    bool operator==( const Q_TYPENAME std::map<Key,T>& ) const { return FALSE; }
#endif
#endif

protected:
    /**
     * Helpers
     */
    void detach() {  if ( sh->count > 1 ) detachInternal(); }

    Priv* sh;
private:
    void detachInternal();
};

template<class Key, class T>
Q_INLINE_TEMPLATES QMap<Key,T>& QMap<Key,T>::operator= ( const QMap<Key,T>& m )
{
    m.sh->ref();
    if ( sh->deref() )
    delete sh;
    sh = m.sh;
    return *this;
}

template<class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMap<Key,T>::insert_pair QMap<Key,T>::insert( const Q_TYPENAME QMap<Key,T>::value_type& x )
{
    detach();
    size_type n = size();
    iterator it = sh->insertSingle( x.first );
    bool inserted = FALSE;
    if ( n < size() ) {
    inserted = TRUE;
    it.data() = x.second;
    }
    return QPair<iterator,bool>( it, inserted );
}

template<class Key, class T>
Q_INLINE_TEMPLATES void QMap<Key,T>::erase( const Key& k )
{
    detach();
    iterator it( sh->find( k ).node );
    if ( it != end() )
    sh->remove( it );
}

template<class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMap<Key,T>::size_type QMap<Key,T>::count( const Key& k ) const
{
    const_iterator it( sh->find( k ).node );
    if ( it != end() ) {
    size_type c = 0;
    while ( it != end() ) {
        ++it;
        ++c;
    }
    return c;
    }
    return 0;
}

template<class Key, class T>
Q_INLINE_TEMPLATES T& QMap<Key,T>::operator[] ( const Key& k )
{
    detach();
    QMapNode<Key,T>* p = sh->find( k ).node;
    if ( p != sh->end().node )
    return p->data;
    return insert( k, T() ).data();
}

template<class Key, class T>
Q_INLINE_TEMPLATES void QMap<Key,T>::clear()
{
    if ( sh->count == 1 )
    sh->clear();
    else {
    sh->deref();
    sh = new QMapPrivate<Key,T>;
    }
}

template<class Key, class T>
Q_INLINE_TEMPLATES Q_TYPENAME QMap<Key,T>::iterator QMap<Key,T>::insert( const Key& key, const T& value, bool overwrite )
{
    detach();
    size_type n = size();
    iterator it = sh->insertSingle( key );
    if ( overwrite || n < size() )
    it.data() = value;
    return it;
}

template<class Key, class T>
Q_INLINE_TEMPLATES void QMap<Key,T>::remove( const Key& k )
{
    detach();
    iterator it( sh->find( k ).node );
    if ( it != end() )
    sh->remove( it );
}

template<class Key, class T>
Q_INLINE_TEMPLATES void QMap<Key,T>::detachInternal()
{
    sh->deref(); sh = new QMapPrivate<Key,T>( sh );
}

#ifndef QT_NO_DATASTREAM
template<class Key, class T>
Q_INLINE_TEMPLATES QDataStream& operator>>( QDataStream& s, QMap<Key,T>& m ) {
    m.clear();
    Q_UINT32 c;
    s >> c;
    for( Q_UINT32 i = 0; i < c; ++i ) {
    Key k; T t;
    s >> k >> t;
    m.insert( k, t );
    if ( s.atEnd() )
        break;
    }
    return s;
}

template<class Key, class T>
Q_INLINE_TEMPLATES QDataStream& operator<<( QDataStream& s, const QMap<Key,T>& m ) {
    s << (Q_UINT32)m.size();
    QMapConstIterator<Key,T> it = m.begin();
    for( ; it != m.end(); ++it )
    s << it.key() << it.data();
    return s;
}
#endif

#endif // QMAP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMap Member List

Complete Member List for QMap

This is the complete list of member functions for QMap, including inherited members.

  • QMap()
  • ~QMap()
  • begin()
  • clear()
  • contains()
  • count()
  • detach()
  • empty()
  • end()
  • erase()
  • find()
  • insert()
  • isEmpty()
  • keys()
  • operator=()
  • operator[]()
  • remove()
  • replace()
  • size()
  • values()


QMapConstIterator Class

QMapConstIterator Class Reference

The QMapConstIterator class provides an iterator for QMap. More...

#include <qmap.h>

List of all member functions.

Public Members

  • typedef std::bidirectional_iterator_tag iterator_category
  • typedef T value_type
  • typedef const T * pointer
  • typedef const T & reference
  • QMapConstIterator ()
  • QMapConstIterator ( QMapNode<K, T> * p )
  • QMapConstIterator ( const QMapConstIterator<K, T> & it )
  • QMapConstIterator ( const QMapIterator<K, T> & it )
  • bool operator== ( const QMapConstIterator<K, T> & it ) const
  • bool operator!= ( const QMapConstIterator<K, T> & it ) const
  • const T & operator* () const
  • const K & key () const
  • const T & data () const
  • QMapConstIterator<K, T> & operator++ ()
  • QMapConstIterator<K, T> operator++ ( int )
  • QMapConstIterator<K, T> & operator-- ()
  • QMapConstIterator<K, T> operator-- ( int )

Detailed Description

The QMapConstIterator class provides an iterator for QMap.

In contrast to QMapIterator, this class is used to iterate over a const map. It does not allow you to modify the values of the map because this would break the const semantics.

For more information on QMap iterators, see QMapIterator. and the QMap example.

See also QMap, QMapIterator, Qt Template Library Classes and Non-GUI Classes.

Member Type Documentation

QMapConstIterator::iterator_category

The type of iterator category, std::bidirectional_iterator_tag.

QMapConstIterator::pointer

Const pointer to value_type.

QMapConstIterator::reference

Const reference to value_type.

QMapConstIterator::value_type

The type of const value.

Member Function Documentation

QMapConstIterator::QMapConstIterator ()

Constructs an uninitialized iterator.

QMapConstIterator::QMapConstIterator ( QMapNode<K, T> * p )

Constructs an iterator starting at node p.

QMapConstIterator::QMapConstIterator ( const QMapConstIterator<K, T> & it )

Constructs a copy of the iterator, it.

QMapConstIterator::QMapConstIterator ( const QMapIterator<K, T> & it )

Constructs a copy of the iterator, it.

const T & QMapConstIterator::data () const

Returns a const reference to the data of the current item.

const K & QMapConstIterator::key () const

Returns a const reference to the current key.

bool QMapConstIterator::operator!= ( const QMapConstIterator<K, T> & it ) const

Compares the iterator to the it iterator and returns FALSE if they point to the same item; otherwise returns TRUE.

const T & QMapConstIterator::operator* () const

Dereference operator. Returns a const reference to the current item. The same as data().

QMapConstIterator<K, T> & QMapConstIterator::operator++ ()

Prefix ++ makes the succeeding item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the end of the map. Incrementing the iterator returned by end() causes undefined results.

QMapConstIterator<K, T> QMapConstIterator::operator++ ( int )

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

Postfix ++ makes the succeeding item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the end of the map. Incrementing the iterator returned by end() causes undefined results.

QMapConstIterator<K, T> & QMapConstIterator::operator-- ()

Prefix -- makes the previous item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the beginning of the map. Decrementing the iterator returned by begin() causes undefined results.

QMapConstIterator<K, T> QMapConstIterator::operator-- ( int )

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

Postfix -- makes the previous item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the beginning of the map. Decrementing the iterator returned by begin() causes undefined results.

bool QMapConstIterator::operator== ( const QMapConstIterator<K, T> & it ) const

Compares the iterator to the it iterator and returns TRUE if they point to the same item; otherwise returns FALSE.

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


QMapConstIterator Member List

Complete Member List for QMapConstIterator

This is the complete list of member functions for QMapConstIterator, including inherited members.

  • QMapConstIterator()
  • data()
  • key()
  • operator!=()
  • operator*()
  • operator++()
  • operator--()
  • operator==()


QMapIterator Class

QMapIterator Class Reference

The QMapIterator class provides an iterator for QMap. More...

#include <qmap.h>

List of all member functions.

Public Members

  • typedef std::bidirectional_iterator_tag iterator_category
  • typedef T value_type
  • typedef T * pointer
  • typedef T & reference
  • QMapIterator ()
  • QMapIterator ( QMapNode<K, T> * p )
  • QMapIterator ( const QMapIterator<K, T> & it )
  • bool operator== ( const QMapIterator<K, T> & it ) const
  • bool operator!= ( const QMapIterator<K, T> & it ) const
  • T & operator* ()
  • const T & operator* () const
  • const K & key () const
  • T & data ()
  • const T & data () const
  • QMapIterator<K, T> & operator++ ()
  • QMapIterator<K, T> operator++ ( int )
  • QMapIterator<K, T> & operator-- ()
  • QMapIterator<K, T> operator-- ( int )

Detailed Description

The QMapIterator class provides an iterator for QMap.

You cannot create an iterator by yourself. Instead, you have to ask a map to give you one. An iterator is as big as a pointer; on 32-bit machines that means 4 bytes, on 64-bit ones 8 bytes. That makes copying them very fast. They resemble the semantics of pointers as much as possible, and they are almost as fast as usual pointers. See the QMap example.

The only way to traverse a map is to use iterators. QMap is highly optimized for performance and memory usage. On the other hand this means that you have to be a bit more careful with what you are doing. QMap does not know about all its iterators, and the iterators don't even know to which map they belong. That makes things fast but a bit dangerous because it is up to you to make sure that the iterators you are using are still valid. QDictIterator will be able to give warnings, whereas QMapIterator may end up in an undefined state.

For every Iterator there is also a ConstIterator. You have to use the ConstIterator to access a QMap in a const environment or if the reference or pointer to the map is itself const. Its semantics are the same, but it returns only const references to the item it points to.

See also QMap, QMapConstIterator, Qt Template Library Classes and Non-GUI Classes.

Member Type Documentation

QMapIterator::iterator_category

The type of iterator category, std::bidirectional_iterator_tag.

QMapIterator::pointer

Pointer to value_type.

QMapIterator::reference

Reference to value_type.

QMapIterator::value_type

The type of value.

Member Function Documentation

QMapIterator::QMapIterator ()

Creates an uninitialized iterator.

QMapIterator::QMapIterator ( QMapNode<K, T> * p )

Constructs an iterator starting at node p.

QMapIterator::QMapIterator ( const QMapIterator<K, T> & it )

Constructs a copy of the iterator, it.

T & QMapIterator::data ()

Returns a reference to the current item.

const T & QMapIterator::data () const

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

Returns a const reference to the data of the current item.

const K & QMapIterator::key () const

Returns a const reference to the data of the current key.

bool QMapIterator::operator!= ( const QMapIterator<K, T> & it ) const

Compares the iterator to the it iterator and returns FALSE if they point to the same item; otherwise returns TRUE.

T & QMapIterator::operator* ()

Dereference operator. Returns a reference to the current item. The same as data().

const T & QMapIterator::operator* () const

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

Dereference operator. Returns a const reference to the current item. The same as data().

QMapIterator<K, T> & QMapIterator::operator++ ()

Prefix ++ makes the succeeding item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the end of the map. Incrementing the iterator returned by end() causes undefined results.

QMapIterator<K, T> QMapIterator::operator++ ( int )

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

Postfix ++ makes the succeeding item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the end of the map. Incrementing the iterator returned by end() causes undefined results.

QMapIterator<K, T> & QMapIterator::operator-- ()

Prefix -- makes the previous item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the beginning of the map. Decrementing the iterator returned by begin() causes undefined results.

QMapIterator<K, T> QMapIterator::operator-- ( int )

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

Postfix -- makes the previous item current and returns an iterator pointing to the new current item. The iterator cannot check whether it reached the beginning of the map. Decrementing the iterator returned by begin() causes undefined results.

bool QMapIterator::operator== ( const QMapIterator<K, T> & it ) const

Compares the iterator to the it iterator and returns TRUE if they point to the same item; otherwise returns FALSE.

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


QMapIterator Member List

Complete Member List for QMapIterator

This is the complete list of member functions for QMapIterator, including inherited members.

  • QMapIterator()
  • data()
  • key()
  • operator!=()
  • operator*()
  • operator++()
  • operator--()
  • operator==()


QMemArray类

QMemArray类参考

QMemArray类是一个提供简单类型的数组的模板类。 详情请见……

#include <qmemarray.h>

被QByteArray和QPointArray继承。

所有成员函数的列表。

公有成员

  • typedef type * Iterator
  • typedef const type * ConstIterator
  • QMemArray ()
  • QMemArray ( int size )
  • QMemArray ( const QMemArray<type> & a )
  • ~QMemArray ()
  • QMemArray<type> & operator= ( const QMemArray<type> & a )
  • type * data () const
  • uint nrefs () const
  • uint size () const
  • uint count () const
  • bool isEmpty () const
  • bool isNull () const
  • bool resize ( uint size )
  • bool truncate ( uint pos )
  • bool fill ( const type & v, int size = -1 )
  • virtual void detach ()
  • QMemArray<type> copy () const
  • QMemArray<type> & assign ( const QMemArray<type> & a )
  • QMemArray<type> & assign ( const type * data, uint size )
  • QMemArray<type> & duplicate ( const QMemArray<type> & a )
  • QMemArray<type> & duplicate ( const type * data, uint size )
  • QMemArray<type> & setRawData ( const type * data, uint size )
  • void resetRawData ( const type * data, uint size )
  • int find ( const type & v, uint index = 0 ) const
  • int contains ( const type & v ) const
  • void sort ()
  • int bsearch ( const type & v ) const
  • type & operator[] ( int index ) const
  • type & at ( uint index ) const
  • operator const type * () const
  • bool operator== ( const QMemArray<type> & a ) const
  • bool operator!= ( const QMemArray<type> & a ) const
  • Iterator begin ()
  • Iterator end ()
  • ConstIterator begin () const
  • ConstIterator end () const

保护成员

  • QMemArray ( int, int )

相关函数

  • Q_UINT16 qChecksum ( const char * data, uint len )
  • QDataStream & operator<< ( QDataStream & s, const QByteArray & a )
  • QDataStream & operator>> ( QDataStream & s, QByteArray & a )

详细描述

QMemArray是一个提供简单类型的数组的模板类。

QMemArray是作为模板类实现的。定义一个模板实例QMemArray<X>可以创建一个包含X数据项的数组。

QMemArray直接在数组中存储数组元素。它只能处理简单类型（比如，C++类型、结构体和没有构造函数、析构函数和虚函数的类）。QMemArray使用逐位的操作来复制和比较数组元素。

QPtrVector集合类也是一种数组。就像所有的集合类一样，它存储的是指向所包含的数据项的指针。

QMemArray通过一个引用计数器使用明显共享。如果超过一个的数组共享公有的数据并且，一个数组被修改的时候，所有的数组都将被修改。

共享的好处就是程序可以在不被需要复制的时候就不必再复制了，这样的结果就是可以减少的内存使用和数据复制了。

实例：

    #include <qmemarray.h>
    #include <stdio.h>

    QMemArray<int> fib( int num ) // 返回斐波纳契数列
    {
        Q_ASSERT( num > 2 );
        QMemArray<int> f( num ); // 整形数组

        f[0] = f[1] = 1;
        for ( int i = 2; i < num; i++ )
            f[i] = f[i-1] + f[i-2];

        return f;
    }

    int main()
    {
        QMemArray<int> a = fib( 6 ); // get 6 first fibonaccis
        for ( int i = 0; i < a.size(); i++ )
            qDebug( "%d: %d", i, a[i] );

        qDebug( "1 is found %d times", a.contains(1) );
        qDebug( "5 is found at index %d", a.find(5) );

        return 0;
    }

程序输出：

    0: 1
    1: 1
    2: 2
    3: 3
    4: 5
    5: 8
    1 is found 2 times
    5 is found at index 4

使用QMemArray来操作结构体或者类的时候需要注意：编译器经常会在结构体后面加一些不定长的东西从而达到最近的字边界。这就将是QMemArray用来做逐位元素比较的大小了。因为剩余的字节将不被初始化，这将导致find()等等在查找元素时失败。实例：

    // MyStruct也许会被加上4或8字节
    struct MyStruct
    {
        short i; // 2 bytes
        char c;  // 1 byte
    };

    QMemArray<MyStruct> a(1);
    a[0].i = 5;
    a[0].c = 't';

    MyStruct x;
    x.i = '5';
    x.c = 't';
    int i = a.find( x ); // 如果所加上的字节不同，也许会返回-1

为了能在这种情况下工作，确认你使用的结构体使用sizeof()返回到大小和各个成员的大小之和相同，否则通过改变结构体成员的类型或者加入一些虚构的成员来解决这个问题。

QMemArray数据可以通过迭代器来遍历（请看begin()和end()）。数据项的数量可以由count()返回。可以用resize()重新定义数组的大小并且用fill()填充。

你可以使用a href="#assign">assign()（或者operator=()）来做浅复制，可以使用duplicate()来做深复制。

在数组中搜索值可以用find()和contains()。在排过序的数组（请看sort()）中搜索可以使用bsearch()。

你可以直接使用setRawData()和resetRawData()来直接设置数据，但是这需要注意。

也可以参考共享类和非GUI的类。

成员类型文档

QMemArray::ConstIterator

一个常量的QMemArray迭代器。

也可以参考begin()和end()。

QMemArray::Iterator

一个QMemArray迭代器。

也可以参考begin()和end()。

成员函数文档

QMemArray::QMemArray ( int, int ) [保护]

构造一个数组但不分配数组空间。参数必须为(0, 0)。使用的时候你要自己承担风险。

QMemArray::QMemArray ()

构造一个空数组。

也可以参考isNull()。

QMemArray::QMemArray ( int size )

构造一个为size个元素提供空间的数组。如果size==0，就是一个空数组。

元素没有被初始化。

也可以参考resize()和isNull()。

QMemArray::QMemArray ( const QMemArray<type> & a )

构造一个a的浅复制。

也可以参考assign()。

QMemArray::~QMemArray ()

数组数据的引用计数减一并且如果这是最后一个引用就删除它。

QMemArray<type> & QMemArray::assign ( const QMemArray<type> & a )

浅复制。数组数据的引用计数减一并且相反地引用a中包含的数据。返回这个数组的引用。

也可以参考operator=()。

QMemArray<type> & QMemArray::assign ( const type * data, uint size )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

浅复制。数组数据的引用计数减一并且相反地引用包含了size个元素的数组数据data。返回这个数组的引用。

在这之后不要删除data，QMemArray会维护它的。

type & QMemArray::at ( uint index ) const

返回数组中在index位置的元素的引用。

这个可以用来读写一个元素。

也可以参考operator[]()。

Iterator QMemArray::begin ()

返回指向数组开始的一个迭代器。这个迭代器与如QValueList和QMap中的迭代器使用方法相同。实际上，它不仅行为和指针相似，它就是一个指针。

ConstIterator QMemArray::begin () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向数组开始的一个常量迭代器。这个迭代器与如QValueList和QMap中的迭代器使用方法相同。实际上，它不仅行为和指针相似，它就是一个指针。

int QMemArray::bsearch ( const type & v ) const

在排过序的数组中，通过使用二进制搜索找到第一个出现的v。对于排过序的数组，它通常比做线性搜索的find()快很多。

返回v的位置，或者如果v没有被找到，返回-1。

也可以参考sort()和find()。

int QMemArray::contains ( const type & v ) const

返回数组中v出现的次数。

也可以参考find()。

QMemArray<type> QMemArray::copy () const

返回一个数组的深复制。

也可以参考detach()和duplicate()。

uint QMemArray::count () const

返回和size()一样的值。

也可以参考size()。

实例：scribble/scribble.cpp。

type * QMemArray::data () const

返回实际数组数据的指针。

如果data()==0（空指针），这个数组为空数组。

也可以参考isNull()。

实例：fileiconview/qfileiconview.cpp和network/networkprotocol/nntp.cpp。

void QMemArray::detach () [虚]

把这个数组从共享内存数据中分离出来，比如它做了一次秘密的数据的深复制。

复制操作只有在引用计数比一大的时候执行。

也可以参考copy()。

在QBitArray中被重新实现。

QMemArray<type> & QMemArray::duplicate ( const QMemArray<type> & a )

深复制。当前数组数据的引用计数减一并且相反地获得a中包含的数据的复制。返回这个数组的引用。

也可以参考copy()。

QMemArray<type> & QMemArray::duplicate ( const type * data, uint size )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

深复制。当前数组数据的引用计数减一并且相反地获得数组数据data中复制。返回这个数组的引用。数组的大小由size给定。

也可以参考copy()。

Iterator QMemArray::end ()

返回指向数组最后一个元素之后的一个迭代器。这个迭代器与如QValueList和QMap中的迭代器使用方法相同。实际上，它不仅行为和指针相似，它就是一个指针。

ConstIterator QMemArray::end () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向数组最后一个元素之后的一个迭代器。这个迭代器与如QValueList和QMap中的迭代器使用方法相同。实际上，它不仅行为和指针相似，它就是一个指针。

bool QMemArray::fill ( const type & v, int size = -1 )

用值v来填充数组。如果size被指定为与-1不同的值，数组将在填充之前被重新定义大小。

如果成功，返回真，或者如果不能分配内存时（只有当size!=-1时），返回假。

也可以参考resize()。

int QMemArray::find ( const type & v, uint index = 0 ) const

查找从index位置开始，v第一次出现的位置。

返回v的位置，或者如果v没有找到，返回-1。

也可以参考contains()。

bool QMemArray::isEmpty () const

如果数组是空的，返回真，否则返回假。

对于QMemArray，isEmpty()与isNull()相同。（这一点与QString不同）

bool QMemArray::isNull () const

如果数组为空，返回真，否则返回假。

一个空数组的size()==0并且data()==0。

uint QMemArray::nrefs () const

返回共享数组数据的引用计数。这个引用计数总是比零大。

QMemArray::operator const type * () const

强制性操作符。返回数组的指针。

也可以参考data()。

bool QMemArray::operator!= ( const QMemArray<type> & a ) const

如果这个数组与a不同，返回真，否则返回假。

两个数组进行逐位比较。

也可以参考operator==()。

QMemArray<type> & QMemArray::operator= ( const QMemArray<type> & a )

分配a的一个浅复制到这个数组并且返回这个数组的引用。

与 assign( a )相同。

bool QMemArray::operator== ( const QMemArray<type> & a ) const

Returns TRUE if this array is equal to a; otherwise returns FALSE. 如果这个数组与a相同，返回真，否则返回假。

两个数组进行逐位比较。

也可以参考operator!=()。

type & QMemArray::operator[] ( int index ) const

返回数组中index位置的元素的引用。

这个可以用来读写一个元素。与at()相同。

也可以参考at()。

void QMemArray::resetRawData ( const type * data, uint size )

使用setRawData()重新设置原始数据。

参数必须为data和长度size，它们将被传递给setRawData()。这里是为了一致性检验。

也可以参考setRawData()。

bool QMemArray::resize ( uint size )

重新定义数组的大小为size个元素（扩大或者缩小）。如果size==0，数组将变为空数组。

如果成功，返回真，或者如果不能分配内存时，返回假。

新元素没有被初始化。

也可以参考size()。

例子：fileiconview/qfileiconview.cpp。

QMemArray<type> & QMemArray::setRawData ( const type * data, uint size )

设置原始数据并且返回数组的引用。

当前数组数据的引用计数减一并且设置新的数组数据为data并且新数组大小为size。当原始数据已经被设定之后，不要试图重新定义数组的大小。 Call resetRawData(data, size) to reset the array.

设置原始数据是有用的因为它设置QMemArray数据而没有分配内存或者复制数据。

实例一（故意使用）：

    static char bindata[] = { 231, 1, 44, ... };
    QByteArray  a;
    a.setRawData( bindata, sizeof(bindata) );   // a指向bindata
    QDataStream s( a, IO_ReadOnly );            // 打开a的数据
    s >> <something>;                           // 读取原始的bindata
    a.resetRawData( bindata, sizeof(bindata) ); // 完成

实例二（如果你不想这么做）：

    static char bindata[] = { 231, 1, 44, ... };
    QByteArray  a, b;
    a.setRawData( bindata, sizeof(bindata) );   // a指向bindata
    a.resize( 8 );                              // 将会崩溃
    b = a;                                      // 将会崩溃
    a[2] = 123;                                 // 也许会崩溃
    // 忘了resetRawData：将会崩溃

警告：如果你没有调用resetRawData()，QMemArray将会试图解除分配或者重新分配原始数据，这也许太不好了。请注意。

也可以参考resetRawData()。

uint QMemArray::size () const

返回数组大小（元素的最大数量）。

如果size()==0，这个数组是一个空数组。

也可以参考isNull()和resize()。

void QMemArray::sort ()

把数据元素按升序排列，使用逐位比较（memcmp()）。

也可以参考bsearch()。

bool QMemArray::truncate ( uint pos )

从pos位置截短数组。

如果成功，返回真，或者如果不能分配内存时，返回假。

与resize(pos)相同。

也可以参考resize()。

相关函数

QDataStream & operator<< ( QDataStream & s, const QByteArray & a )

从字节数组a写到s流中并且返回流的引用。

也可以参考QDataStream操作符的格。

QDataStream & operator>> ( QDataStream & s, QByteArray & a )

从s流中到读取字节数组a中并且返回流的引用。

也可以参考QDataStream操作符的格式。

Q_UINT16 qChecksum ( const char * data, uint len )

返回data开始的len字节的CRC-16的校验和。

校验和与字节顺序无关。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmemarray.h包含文件

qmemarray.h

这里是qmemarray.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QMemArray template/macro class
**
** Created : 930906
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMEMARRAY_H
#define QMEMARRAY_H

#ifndef QT_H
#include "qgarray.h"
#endif // QT_H

template<class type>
class QMemArray
: public QGArray
{
public:
    typedef type* Iterator;
    typedef const type* ConstIterator;
    typedef type ValueType;

protected:
    QMemArray( int, int ) : QGArray( 0, 0 ) {}

public:
    QMemArray() {}
    QMemArray( int size ) : QGArray(size*sizeof(type)) {}
    QMemArray( const QMemArray<type> &a ) : QGArray(a) {}
   ~QMemArray() {}
    QMemArray<type> &operator=(const QMemArray<type> &a)
                { return (QMemArray<type>&)QGArray::assign(a); }
    type *data()    const	{ return (type *)QGArray::data(); }
    uint  nrefs()   const	{ return QGArray::nrefs(); }
    uint  size()    const	{ return QGArray::size()/sizeof(type); }
    uint  count()   const	{ return size(); }
    bool  isEmpty() const	{ return QGArray::size() == 0; }
    bool  isNull()  const	{ return QGArray::data() == 0; }
    bool  resize( uint size )	{ return QGArray::resize(size*sizeof(type)); }
    bool  truncate( uint pos )	{ return QGArray::resize(pos*sizeof(type)); }
    bool  fill( const type &d, int size = -1 )
    { return QGArray::fill((char*)&d,size,sizeof(type) ); }
    void  detach()		{ QGArray::detach(); }
    QMemArray<type>   copy() const
    { QMemArray<type> tmp; return tmp.duplicate(*this); }
    QMemArray<type>& assign( const QMemArray<type>& a )
    { return (QMemArray<type>&)QGArray::assign(a); }
    QMemArray<type>& assign( const type *a, uint n )
    { return (QMemArray<type>&)QGArray::assign((char*)a,n*sizeof(type)); }
    QMemArray<type>& duplicate( const QMemArray<type>& a )
    { return (QMemArray<type>&)QGArray::duplicate(a); }
    QMemArray<type>& duplicate( const type *a, uint n )
    { return (QMemArray<type>&)QGArray::duplicate((char*)a,n*sizeof(type)); }
    QMemArray<type>& setRawData( const type *a, uint n )
    { return (QMemArray<type>&)QGArray::setRawData((char*)a,
                             n*sizeof(type)); }
    void resetRawData( const type *a, uint n )
    { QGArray::resetRawData((char*)a,n*sizeof(type)); }
    int	 find( const type &d, uint i=0 ) const
    { return QGArray::find((char*)&d,i,sizeof(type)); }
    int	 contains( const type &d ) const
    { return QGArray::contains((char*)&d,sizeof(type)); }
    void sort() { QGArray::sort(sizeof(type)); }
    int  bsearch( const type &d ) const
    { return QGArray::bsearch((const char*)&d,sizeof(type)); }
    type& operator[]( int i ) const
    { return (type &)(*(type *)QGArray::at(i*sizeof(type))); }
    type& at( uint i ) const
    { return (type &)(*(type *)QGArray::at(i*sizeof(type))); }
     operator const type*() const { return (const type *)QGArray::data(); }
    bool operator==( const QMemArray<type> &a ) const { return isEqual(a); }
    bool operator!=( const QMemArray<type> &a ) const { return !isEqual(a); }
    Iterator begin() { return data(); }
    Iterator end() { return data() + size(); }
    ConstIterator begin() const { return data(); }
    ConstIterator end() const { return data() + size(); }
};

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QMemArray<int>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QMemArray<bool>;
// MOC_SKIP_END
#endif

#ifndef QT_NO_COMPAT
#define QArray QMemArray
#endif

#endif // QARRAY_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMemArray成员列表

完整的QMemArray成员列表

这里是QMemArray成员函数的完整列表，包括继承的成员。

  • QMemArray()
  • ~QMemArray()
  • assign()
  • at()
  • begin()
  • bsearch()
  • contains()
  • copy()
  • count()
  • data()
  • detach()
  • duplicate()
  • end()
  • fill()
  • find()
  • isEmpty()
  • isNull()
  • nrefs()
  • operator const type *()
  • operator!=()
  • operator=()
  • operator==()
  • operator[]()
  • resetRawData()
  • resize()
  • setRawData()
  • size()
  • sort()
  • truncate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMenuBar Class

QMenuBar Class Reference

The QMenuBar class provides a horizontal menu bar. More...

#include <qmenubar.h>

Inherits QFrame and QMenuData.

List of all member functions.

Public Members

  • QMenuBar ( QWidget * parent = 0, const char * name = 0 )
  • ~QMenuBar ()
  • virtual void show ()
  • virtual void hide ()
  • virtual int heightForWidth ( int max_width ) const
  • enum Separator { Never = 0, InWindowsStyle = 1 }
  • Separator separator () const (obsolete)
  • virtual void setSeparator ( Separator when ) (obsolete)
  • void setDefaultUp ( bool )
  • bool isDefaultUp () const

Signals

  • void activated ( int id )
  • void highlighted ( int id )

Important Inherited Members

  • int insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( QWidget * widget, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertSeparator ( int index = -1 )
  • void removeItem ( int id )
  • void clear ()
  • bool isItemEnabled ( int id ) const
  • void setItemEnabled ( int id, bool enable )

Properties

  • bool defaultUp - the popup orientation
  • Separator separator - in which cases a menubar sparator is drawn (obsolete)

Protected Members

  • virtual void drawContents ( QPainter * p )
  • virtual void menuContentsChanged ()
  • virtual void menuStateChanged ()

Detailed Description

The QMenuBar class provides a horizontal menu bar.

A menu bar consists of a list of pull-down menu items. You add menu items with insertItem(). For example, asuming that menubar is a pointer to a QMenuBar and filemenu is a pointer to a QPopupMenu, the following statement inserts the menu into the menu bar:

  menubar->insertItem( "&File", filemenu );
The ampersand in the menu item's text sets Alt+F as a shortcut for this menu. (You can use "&&" to get a real ampersand in the menu bar.)

Items are either enabled or disabled. You toggle their state with setItemEnabled().

There is no need to lay out a menu bar. It automatically sets its own geometry to the top of the parent widget and changes it appropriately whenever the parent is resized.

Example of creating a menu bar with menu items (from menu/menu.cpp):

        QPopupMenu *file = new QPopupMenu( this );

        file->insertItem( p1, "&Open",  this, SLOT(open()), CTRL+Key_O );
        file->insertItem( p2, "&New", this, SLOT(news()), CTRL+Key_N );

        menu = new QMenuBar( this );

        menu->insertItem( "&File", file );

In most main window style applications you would use the menuBar() provided in QMainWindow, adding QPopupMenus to the menu bar and adding QActions to the popup menus.

Example (from action/application.cpp):

        QPopupMenu * file = new QPopupMenu( this );
        menuBar()->insertItem( "&File", file );
        fileNewAction->addTo( file );

Menu items can have text and pixmaps (or iconsets), see the various insertItem() overloads, as well as separators, see insertSeparator(). You can also add custom menu items that are derived from QCustomMenuItem.

Menu items may be removed with removeItem() and enabled or disabled with setItemEnabled().

QMenuBar on Qt/Mac is a wrapper for using the system-wide menubar. However, if you have multiple menubars in one dialog the outermost menubar (normally inside a widget with WType_TopLevel) will be used for the global menubar.

Qt/Mac also provides a menubar merging feature, with this your QMenubar will be brought closer to conforming to accepted Mac OS X menubar layout. The merging functionality is based on string matching the title of a QPopupMenu entry, these strings are translated (using QObject::tr()) in the "QMenuBar" context. If an entry is moved the regularly connected slots will still fire as if it was in the original place. The table below outlines the strings looked for and where the entry is placed if matched:

String matches | Placement | Notes
about.* | Application Menu | About | If this entry is not found no About item will appear in the Application Menu
config, options, setup, settings, preferences | Application Menu | Settings | If this entry is not found the Settings item will be disabled
quit, exit | Application Menu | Quit | If this entry is not found a default Quit item will be created to call QApplication::quit()

See also QPopupMenu, QAccel, QAction, Aqua Style Guidelines, GUI Design Handbook: Menu Bar and Main Window and Related Classes.

Member Type Documentation

QMenuBar::Separator

This enum type is used to decide whether QMenuBar should draw a separator line at its bottom. The possible values are:

  • QMenuBar::Never - In many applications there is already a separator, and having two looks wrong.
  • QMenuBar::InWindowsStyle - In some other applications a separator looks good in Windows style, but nowhere else.

Member Function Documentation

QMenuBar::QMenuBar ( QWidget * parent = 0, const char * name = 0 )

Constructs a menu bar with a parent and a name.

QMenuBar::~QMenuBar ()

Destroys the menu bar.

void QMenuBar::activated ( int id ) [signal]

This signal is emitted when a menu item is selected; id is the id of the selected item.

Normally you will connect each menu item to a single slot using QMenuData::insertItem(), but sometimes you will want to connect several items to a single slot (most often if the user selects from an array). This signal is useful in such cases.

See also highlighted() and QMenuData::insertItem().

Example: progress/progress.cpp.

void QMenuData::clear ()

Removes all menu items.

See also removeItem() and removeItemAt().

Examples: mdi/application.cpp and qwerty/qwerty.cpp.

void QMenuBar::drawContents ( QPainter * p ) [virtual protected]

Called from QFrame::paintEvent(). Draws the menu bar contents using painter p.

Reimplemented from QFrame.

int QMenuBar::heightForWidth ( int max_width ) const [virtual]

Returns the height that the menu would resize itself to if its parent (and hence itself) resized to the given max_width. This can be useful for simple layout tasks in which the height of the menu bar is needed after items have been inserted. See showimg/showimg.cpp for an example of the usage.

Example: showimg/showimg.cpp.

Reimplemented from QWidget.

void QMenuBar::hide () [virtual]

Reimplements QWidget::hide() in order to deselect any selected item, and calls setUpLayout() for the main window.

Example: grapher/grapher.cpp.

Reimplemented from QWidget.

void QMenuBar::highlighted ( int id ) [signal]

This signal is emitted when a menu item is highlighted; id is the id of the highlighted item.

Normally, you will connect each menu item to a single slot using QMenuData::insertItem(), but sometimes you will want to connect several items to a single slot (most often if the user selects from an array). This signal is useful in such cases.

See also activated() and QMenuData::insertItem().

int QMenuData::insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

The family of insertItem() functions inserts menu items into a popup menu or a menu bar.

A menu item is usually either a text string or a pixmap, both with an optional icon or keyboard accelerator. For special cases it is also possible to insert custom items (see QCustomMenuItem) or even widgets into popup menus.

Some insertItem() members take a popup menu as an additional argument. Use this to insert submenus to existing menus or pulldown menus to a menu bar.

The number of insert functions may look confusing, but they are actually quite simple to use.

This default version inserts a menu item with the text text, the accelerator key accel, an id and an optional index and connects it to the slot member in the object receiver.

Example:

    QMenuBar   *mainMenu = new QMenuBar;
    QPopupMenu *fileMenu = new QPopupMenu;
    fileMenu->insertItem( "New",  myView, SLOT(newFile()), CTRL+Key_N );
    fileMenu->insertItem( "Open", myView, SLOT(open()),    CTRL+Key_O );
    mainMenu->insertItem( "File", fileMenu );

Not all insert functions take an object/slot parameter or an accelerator key. Use connectItem() and setAccel() on these items.

If you need to translate accelerators, use tr() with a string description that use pass to the QKeySequence constructor:

    fileMenu->insertItem( tr("Open"), myView, SLOT(open()),
                         tr("Ctrl+O") );

In the example above, pressing Ctrl+N or selecting "Open" from the menu activates the myView->open() function.

Some insert functions take a QIconSet parameter to specify the little menu item icon. Note that you can always pass a QPixmap object instead.

The index specifies the position in the menu. The menu item is appended at the end of the list if index is negative.

Note that keyboard accelerators in Qt are not application-global, instead they are bound to a certain top-level window. For example, accelerators in QPopupMenu items only work for menus that are associated with a certain window. This is true for popup menus that live in a menu bar since their accelerators will then be installed in the menu bar itself. This also applies to stand-alone popup menus that have a top-level widget in their parentWidget() chain. The menu will then install its accelerator object on that top-level widget. For all other cases use an independent QAccel object.

Warning: Be careful when passing a literal 0 to insertItem() because some C++ compilers choose the wrong overloaded function. Cast the 0 to what you mean, e.g. (QObject*)0.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

Examples: addressbook/mainwindow.cpp, canvas/canvas.cpp, mdi/application.cpp, menu/menu.cpp, qwerty/qwerty.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, accelerator accel, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item. The item is connected to the member slot in the receiver object.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with text text, optional id id, and optional index.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with text text, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, submenu popup, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, optional id id, and optional index.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap submenu popup, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( QWidget * widget, int id = -1, int index = -1 )

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

Inserts a menu item that consists of the widget widget with optional id id, and optional index.

Ownership of widget is transferred to the popup menu or to the menu bar.

Theoretically, any widget can be inserted into a popup menu. In practice, this only makes sense with certain widgets.

If a widget is not focus-enabled (see QWidget::isFocusEnabled()), the menu treats it as a separator; this means that the item is not selectable and will never get focus. In this way you can, for example, simply insert a QLabel if you need a popup menu with a title.

If the widget is focus-enabled it will get focus when the user traverses the popup menu with the arrow keys. If the widget does not accept ArrowUp and ArrowDown in its key event handler, the focus will move back to the menu when the respective arrow key is hit one more time. This works with a QLineEdit, for example. If the widget accepts the arrow key itself, it must also provide the possibility to put the focus back on the menu again by calling QWidget::focusNextPrevChild(). Futhermore, if the embedded widget closes the menu when the user made a selection, this can be done safely by calling

    if ( isVisible() &&
         parentWidget() &&
         parentWidget()->inherits("QPopupMenu") )
        parentWidget()->close();

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem().

int QMenuData::insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with an icon and with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertSeparator ( int index = -1 )

Inserts a separator at position index. The separator becomes the last menu item if index is negative.

In a popup menu a separator is rendered as a horizontal line. In a Motif menu bar a separator is spacing, so the rest of the items (normally just "Help") are drawn right-justified. In a Windows menu bar separators are ignored (to comply with the Windows style guidelines).

Examples: addressbook/mainwindow.cpp, mdi/application.cpp, menu/menu.cpp, progress/progress.cpp, scrollview/scrollview.cpp, showimg/showimg.cpp and sound/sound.cpp.

bool QMenuBar::isDefaultUp () const

Returns the popup orientation. See the "defaultUp" property for details.

bool QMenuData::isItemEnabled ( int id ) const

Returns TRUE if the item with identifier id is enabled; otherwise returns FALSE

See also setItemEnabled().

void QMenuBar::menuContentsChanged () [virtual protected]

Recomputes the menu bar's display data according to the new contents.

You should never need to call this; it is called automatically by QMenuData whenever it needs to be called.

Reimplemented from QMenuData.

void QMenuBar::menuStateChanged () [virtual protected]

Recomputes the menu bar's display data according to the new state.

You should never need to call this; it is called automatically by QMenuData whenever it needs to be called.

Reimplemented from QMenuData.

void QMenuData::removeItem ( int id )

Removes the menu item that has the identifier id.

See also removeItemAt() and clear().

Example: chart/chartform.cpp.

Separator QMenuBar::separator () const

Returns in which cases a menubar sparator is drawn. See the "separator" property for details.

void QMenuBar::setDefaultUp ( bool )

Sets the popup orientation. See the "defaultUp" property for details.

void QMenuData::setItemEnabled ( int id, bool enable )

If enable is TRUE, enables the menu item with identifier id; otherwise disables the menu item with identifier id.

See also isItemEnabled().

Examples: mdi/application.cpp, menu/menu.cpp, progress/progress.cpp and showimg/showimg.cpp.

void QMenuBar::setSeparator ( Separator when ) [virtual]

Sets in which cases a menubar sparator is drawn to when. See the "separator" property for details.

void QMenuBar::show () [virtual]

Reimplements QWidget::show() in order to set up the correct keyboard accelerators and to raise itself to the top of the widget stack.

Example: grapher/grapher.cpp.

Reimplemented from QWidget.

Property Documentation

bool defaultUp

This property holds the popup orientation.

The default popup orientation. By default, menus pop "down" the screen. By setting the property to TRUE, the menu will pop "up". You might call this for menus that are below the document to which they refer.

If the menu would not fit on the screen, the other direction is used rather than the default.

Set this property's value with setDefaultUp() and get this property's value with isDefaultUp().

Separator separator

This property holds in which cases a menubar sparator is drawn.

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

Set this property's value with setSeparator() and get this property's value with separator().

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


qmenubar.h Include File

qmenubar.h

This is the verbatim text of the qmenubar.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmenubar.h   3.0.5   edited Apr 30 08:40 $
**
** Definition of QMenuBar class
**
** Created : 941209
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMENUBAR_H
#define QMENUBAR_H

#ifndef QT_H
#include "qpopupmenu.h" // ### remove or keep for users' convenience?
#include "qframe.h"
#include "qmenudata.h"
#endif // QT_H

#ifndef QT_NO_MENUBAR

class QPopupMenu;

class Q_EXPORT QMenuBar : public QFrame, public QMenuData
{
    Q_OBJECT
    Q_ENUMS( Separator )
    Q_PROPERTY( Separator separator READ separator WRITE setSeparator DESIGNABLE false )
    Q_PROPERTY( bool defaultUp READ isDefaultUp WRITE setDefaultUp )

public:
    QMenuBar( QWidget* parent=0, const char* name=0 );
    ~QMenuBar();

    void	updateItem( int id );

    void	show();				// reimplemented show
    void	hide();				// reimplemented hide

    bool	eventFilter( QObject *, QEvent * );

    int		heightForWidth(int) const;

    enum	Separator { Never=0, InWindowsStyle=1 };
    Separator 	separator() const;
    virtual void	setSeparator( Separator when );

    void	setDefaultUp( bool );
    bool	isDefaultUp() const;

    bool customWhatsThis() const;

    QSize sizeHint() const;
    QSize minimumSize() const;
    QSize minimumSizeHint() const;

    void activateItemAt( int index ); // ### virtual in QMenuData 3.0

#if defined(Q_WS_MAC) && !defined(QMAC_QMENUBAR_NO_NATIVE)
    static void initialize();
    static void cleanup();
#endif

signals:
    void	activated( int itemId );
    void	highlighted( int itemId );

protected:
    void	drawContents( QPainter * );
    void	fontChange( const QFont & );
    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	keyPressEvent( QKeyEvent * );
    void	focusInEvent( QFocusEvent * );
    void	focusOutEvent( QFocusEvent * );
    void	resizeEvent( QResizeEvent * );
    void	leaveEvent( QEvent * );
    void	menuContentsChanged();
    void	menuStateChanged();
    void 	styleChange( QStyle& );
    int	itemAtPos( const QPoint & );
    void	hidePopups();
    QRect	itemRect( int item );

private slots:
    void	subActivated( int itemId );
    void	subHighlighted( int itemId );
#ifndef QT_NO_ACCEL
    void	accelActivated( int itemId );
    void	accelDestroyed();
#endif
    void	popupDestroyed( QObject* );
    void 	performDelayedChanges();

private:
    void 	performDelayedContentsChanged();
    void 	performDelayedStateChanged();
    void	menuInsPopup( QPopupMenu * );
    void	menuDelPopup( QPopupMenu * );
    void	frameChanged();

    bool	tryMouseEvent( QPopupMenu *, QMouseEvent * );
    void	tryKeyEvent( QPopupMenu *, QKeyEvent * );
    void	goodbye( bool cancelled = FALSE );
    void	openActPopup();

    void setActiveItem( int index, bool show = TRUE, bool activate_first_item = TRUE );
    void setAltMode( bool );

    int		calculateRects( int max_width = -1 );

#ifndef QT_NO_ACCEL
    void	setupAccelerators();
    QAccel     *autoaccel;
#endif
    QRect      *irects;
    int		rightSide;

    uint	mseparator : 1;
    uint	waitforalt : 1;
    uint	popupvisible  : 1;
    uint	hasmouse : 1;
    uint 	defaultup : 1;
    uint 	toggleclose : 1;
    uint        pendingDelayedContentsChanges : 1;
    uint        pendingDelayedStateChanges : 1;

    friend class QPopupMenu;

#if defined(Q_WS_MAC) && !defined(QMAC_QMENUBAR_NO_NATIVE)
    friend class QWidget;
    friend class QApplication;

    void macCreateNativeMenubar();
    void macRemoveNativeMenubar();
    void macDirtyNativeMenubar();

#if !defined(QMAC_QMENUBAR_NO_EVENT)
    static void qt_mac_install_menubar_event(MenuRef);
    static OSStatus qt_mac_menubar_event(EventHandlerCallRef, EventRef, void *);
#endif
    bool syncPopups(MenuRef ret, QPopupMenu *d);
    MenuRef createMacPopup(QPopupMenu *d, bool, bool =FALSE);
    bool updateMenuBar();
#if !defined(QMAC_QMENUBAR_NO_MERGE)
    uint isCommand(QMenuItem *);
#endif

    uint mac_eaten_menubar : 1;
    class MacPrivate;
    MacPrivate *mac_d;
    static bool activate(MenuRef, short, bool highlight=FALSE, bool by_accel=FALSE);
    static bool activateCommand(uint cmd);
    static void macUpdateMenuBar();
    static void macUpdatePopup(MenuRef);
#endif

private:	// Disabled copy constructor and operator=

#if defined(Q_DISABLE_COPY)
    QMenuBar( const QMenuBar & );
    QMenuBar &operator=( const QMenuBar & );
#endif
};

#endif // QT_NO_MENUBAR

#endif // QMENUBAR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMenuBar Member List

Complete Member List for QMenuBar

This is the complete list of member functions for QMenuBar, including inherited members.

  • QMenuBar()
  • ~QMenuBar()
  • accel()
  • acceptDrops()
  • activateItemAt()
  • activated()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • changeItem()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectItem()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectItem()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • findItem()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • highlighted()
  • icon()
  • iconSet()
  • iconText()
  • iconify()
  • idAt()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertItem()
  • insertSeparator()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDefaultUp()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isItemActive()
  • isItemChecked()
  • isItemEnabled()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • itemParameter()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • menuContentsChanged()
  • menuDelPopup()
  • menuInsPopup()
  • menuStateChanged()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeItem()
  • removeItemAt()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • separator()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDefaultUp()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setId()
  • setItemChecked()
  • setItemEnabled()
  • setItemParameter()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSeparator()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • setWhatsThis()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateItem()
  • updateMask()
  • visibleRect()
  • whatsThis()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QMenuData Class

QMenuData Class Reference

The QMenuData class is a base class for QMenuBar and QPopupMenu. More...

#include <qmenudata.h>

Inherited by QMenuBar and QPopupMenu.

List of all member functions.

Public Members

  • QMenuData ()
  • virtual ~QMenuData ()
  • uint count () const
  • int insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( QWidget * widget, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertSeparator ( int index = -1 )
  • void removeItem ( int id )
  • void removeItemAt ( int index )
  • void clear ()
  • QKeySequence accel ( int id ) const
  • void setAccel ( const QKeySequence & key, int id )
  • QIconSet * iconSet ( int id ) const
  • QString text ( int id ) const
  • QPixmap * pixmap ( int id ) const
  • void setWhatsThis ( int id, const QString & text )
  • QString whatsThis ( int id ) const
  • void changeItem ( int id, const QString & text )
  • void changeItem ( int id, const QPixmap & pixmap )
  • void changeItem ( int id, const QIconSet & icon, const QString & text )
  • void changeItem ( int id, const QIconSet & icon, const QPixmap & pixmap )
  • void changeItem ( const QString & text, int id ) (obsolete)
  • void changeItem ( const QPixmap & pixmap, int id ) (obsolete)
  • void changeItem ( const QIconSet & icon, const QString & text, int id ) (obsolete)
  • bool isItemActive ( int id ) const
  • bool isItemEnabled ( int id ) const
  • void setItemEnabled ( int id, bool enable )
  • bool isItemChecked ( int id ) const
  • void setItemChecked ( int id, bool check )
  • virtual void updateItem ( int id )
  • int indexOf ( int id ) const
  • int idAt ( int index ) const
  • virtual void setId ( int index, int id )
  • bool connectItem ( int id, const QObject * receiver, const char * member )
  • bool disconnectItem ( int id, const QObject * receiver, const char * member )
  • bool setItemParameter ( int id, int param )
  • int itemParameter ( int id ) const
  • QMenuItem * findItem ( int id ) const
  • QMenuItem * findItem ( int id, QMenuData ** parent ) const
  • virtual void activateItemAt ( int index )

Protected Members

  • virtual void menuContentsChanged ()
  • virtual void menuStateChanged ()
  • virtual void menuInsPopup ( QPopupMenu * )
  • virtual void menuDelPopup ( QPopupMenu * )

Detailed Description

The QMenuData class is a base class for QMenuBar and QPopupMenu.

QMenuData has an internal list of menu items. A menu item is a text, pixmap or separator, and may also have a popup menu (separators have no popup menus).

The menu item sends out an activated() signal when it is selected and a highlighted() signal when it receives the user input focus.

Menu items are assigned the menu identifier id that is passed in insertItem() or an automatically generated identifier if id is < 0 (the default). The generated identifiers (negative integers) are guaranteed to be unique within the entire application. The identifier is used to access the menu item in other functions.

Menu items can be removed with removeItem() or changed with changeItem(). Accelerators can be changed or set with setAccel(). Checkable items can be checked or unchecked with setItemChecked(). Items can be enabled or disabled using setItemEnabled() and connected and disconnected with connectItem() and disconnectItem() respectively.

Menu items are stored in a list. Use findItem() to find an item by its list position or by its menu identifier.

See also QAccel, QPopupMenu, QAction and Miscellaneous Classes.

Member Function Documentation

QMenuData::QMenuData ()

Constructs an empty menu data list.

QMenuData::~QMenuData () [virtual]

Removes all menu items and disconnects any signals that have been connected.

QKeySequence QMenuData::accel ( int id ) const

Returns the accelerator key that has been defined for the menu item id, or 0 if it has no accelerator key.

See also setAccel(), QAccel and qnamespace.h.

void QMenuData::activateItemAt ( int index ) [virtual]

Activates the menu item at position index.

If the index is invalid (for example, -1), the object itself is deactivated.

void QMenuData::changeItem ( int id, const QString & text )

Changes the text of the menu item id to text. If the item has an icon, the icon remains unchanged.

See also text().

void QMenuData::changeItem ( int id, const QPixmap & pixmap )

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

Changes the pixmap of the menu item id to the pixmap pixmap. If the item has an icon, the icon is unchanged.

See also pixmap().

void QMenuData::changeItem ( int id, const QIconSet & icon, const QString & text )

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

Changes the iconset and text of the menu item id to the icon and text respectively.

See also pixmap().

void QMenuData::changeItem ( int id, const QIconSet & icon, const QPixmap & pixmap )

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

Changes the iconset and pixmap of the menu item id to icon and pixmap respectively.

See also pixmap().

void QMenuData::changeItem ( const QString & text, int id )

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

Changes the text of the menu item id. If the item has an icon, the icon remains unchanged.

See also text().

void QMenuData::changeItem ( const QPixmap & pixmap, int id )

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

Changes the pixmap of the menu item id. If the item has an icon, the icon remains unchanged.

See also pixmap().

void QMenuData::changeItem ( const QIconSet & icon, const QString & text, int id )

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

Changes the icon and text of the menu item id.

See also pixmap().

void QMenuData::clear ()

Removes all menu items.

See also removeItem() and removeItemAt().

Examples: mdi/application.cpp and qwerty/qwerty.cpp.

bool QMenuData::connectItem ( int id, const QObject * receiver, const char * member )

Connects the menu item with identifier id to receiver's member slot or signal.

The receiver's slot/signal is activated when the menu item is activated.

See also disconnectItem() and setItemParameter().

Example: menu/menu.cpp.

uint QMenuData::count () const

Returns the number of items in the menu.

bool QMenuData::disconnectItem ( int id, const QObject * receiver, const char * member )

Disconnects the receiver's member from the menu item with identifier id.

All connections are removed when the menu data object is destroyed.

See also connectItem() and setItemParameter().

QMenuItem * QMenuData::findItem ( int id ) const

Returns a pointer to the menu item with identifier id, or 0 if there is no item with this identifier.

See also indexOf().

Example: chart/chartform.cpp.

QMenuItem * QMenuData::findItem ( int id, QMenuData ** parent ) const

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

Returns a pointer to the menu item with identifier id, or 0 if there is no item with this identifier. Changes *parent to point to the parent of the return value.

See also indexOf().

QIconSet * QMenuData::iconSet ( int id ) const

Returns the icon set that has been set for menu item id, or 0 if no icon set has been set.

See also changeItem(), text() and pixmap().

int QMenuData::idAt ( int index ) const

Returns the identifier of the menu item at position index in the internal list, or -1 if index is out of range.

See also setId() and indexOf().

int QMenuData::indexOf ( int id ) const

Returns the index of the menu item with identifier id, or -1 if there is no item with this identifier.

See also idAt() and findItem().

Example: scrollview/scrollview.cpp.

int QMenuData::insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

The family of insertItem() functions inserts menu items into a popup menu or a menu bar.

A menu item is usually either a text string or a pixmap, both with an optional icon or keyboard accelerator. For special cases it is also possible to insert custom items (see QCustomMenuItem) or even widgets into popup menus.

Some insertItem() members take a popup menu as an additional argument. Use this to insert submenus to existing menus or pulldown menus to a menu bar.

The number of insert functions may look confusing, but they are actually quite simple to use.

This default version inserts a menu item with the text text, the accelerator key accel, an id and an optional index and connects it to the slot member in the object receiver.

Example:

    QMenuBar   *mainMenu = new QMenuBar;
    QPopupMenu *fileMenu = new QPopupMenu;
    fileMenu->insertItem( "New",  myView, SLOT(newFile()), CTRL+Key_N );
    fileMenu->insertItem( "Open", myView, SLOT(open()),    CTRL+Key_O );
    mainMenu->insertItem( "File", fileMenu );

Not all insert functions take an object/slot parameter or an accelerator key. Use connectItem() and setAccel() on these items.

If you need to translate accelerators, use tr() with a string description that use pass to the QKeySequence constructor:

    fileMenu->insertItem( tr("Open"), myView, SLOT(open()),
                         tr("Ctrl+O") );

In the example above, pressing Ctrl+N or selecting "Open" from the menu activates the myView->open() function.

Some insert functions take a QIconSet parameter to specify the little menu item icon. Note that you can always pass a QPixmap object instead.

The index specifies the position in the menu. The menu item is appended at the end of the list if index is negative.

Note that keyboard accelerators in Qt are not application-global, instead they are bound to a certain top-level window. For example, accelerators in QPopupMenu items only work for menus that are associated with a certain window. This is true for popup menus that live in a menu bar since their accelerators will then be installed in the menu bar itself. This also applies to stand-alone popup menus that have a top-level widget in their parentWidget() chain. The menu will then install its accelerator object on that top-level widget. For all other cases use an independent QAccel object.

Warning: Be careful when passing a literal 0 to insertItem() because some C++ compilers choose the wrong overloaded function. Cast the 0 to what you mean, e.g. (QObject*)0.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

Examples: addressbook/mainwindow.cpp, canvas/canvas.cpp, mdi/application.cpp, menu/menu.cpp, qwerty/qwerty.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, accelerator accel, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item. The item is connected to the member slot in the receiver object.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with text text, optional id id, and optional index.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with text text, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, submenu popup, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, optional id id, and optional index.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap submenu popup, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( QWidget * widget, int id = -1, int index = -1 )

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

Inserts a menu item that consists of the widget widget with optional id id, and optional index.

Ownership of widget is transferred to the popup menu or to the menu bar.

Theoretically, any widget can be inserted into a popup menu. In practice, this only makes sense with certain widgets.

If a widget is not focus-enabled (see QWidget::isFocusEnabled()), the menu treats it as a separator; this means that the item is not selectable and will never get focus. In this way you can, for example, simply insert a QLabel if you need a popup menu with a title.

If the widget is focus-enabled it will get focus when the user traverses the popup menu with the arrow keys. If the widget does not accept ArrowUp and ArrowDown in its key event handler, the focus will move back to the menu when the respective arrow key is hit one more time. This works with a QLineEdit, for example. If the widget accepts the arrow key itself, it must also provide the possibility to put the focus back on the menu again by calling QWidget::focusNextPrevChild(). Futhermore, if the embedded widget closes the menu when the user made a selection, this can be done safely by calling

    if ( isVisible() &&
         parentWidget() &&
         parentWidget()->inherits("QPopupMenu") )
        parentWidget()->close();

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem().

int QMenuData::insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with an icon and with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertSeparator ( int index = -1 )

Inserts a separator at position index. The separator becomes the last menu item if index is negative.

In a popup menu a separator is rendered as a horizontal line. In a Motif menu bar a separator is spacing, so the rest of the items (normally just "Help") are drawn right-justified. In a Windows menu bar separators are ignored (to comply with the Windows style guidelines).

Examples: addressbook/mainwindow.cpp, mdi/application.cpp, menu/menu.cpp, progress/progress.cpp, scrollview/scrollview.cpp, showimg/showimg.cpp and sound/sound.cpp.

bool QMenuData::isItemActive ( int id ) const

Returns TRUE if the menu item with the id id is currently active; otherwise returns FALSE.

bool QMenuData::isItemChecked ( int id ) const

Returns TRUE if the menu item with the id id has been checked; otherwise returns FALSE.

See also setItemChecked().

Examples: canvas/canvas.cpp, progress/progress.cpp and showimg/showimg.cpp.

bool QMenuData::isItemEnabled ( int id ) const

Returns TRUE if the item with identifier id is enabled; otherwise returns FALSE

See also setItemEnabled().

int QMenuData::itemParameter ( int id ) const

Returns the parameter of the activation signal of item id.

If no parameter has been specified for this item with setItemParameter(), the value defaults to id.

See also connectItem(), disconnectItem() and setItemParameter().

void QMenuData::menuContentsChanged () [virtual protected]

Virtual function; notifies subclasses that one or more items have been inserted or removed.

Reimplemented in QMenuBar.

void QMenuData::menuDelPopup ( QPopupMenu * ) [virtual protected]

Virtual function; notifies subclasses that a popup menu item has been removed.

void QMenuData::menuInsPopup ( QPopupMenu * ) [virtual protected]

Virtual function; notifies subclasses that a popup menu item has been inserted.

void QMenuData::menuStateChanged () [virtual protected]

Virtual function; notifies subclasses that one or more items have changed state (enabled/disabled or checked/unchecked).

Reimplemented in QMenuBar.

QPixmap * QMenuData::pixmap ( int id ) const

Returns the pixmap that has been set for menu item id, or 0 if no pixmap has been set.

See also changeItem(), text() and iconSet().

void QMenuData::removeItem ( int id )

Removes the menu item that has the identifier id.

See also removeItemAt() and clear().

Example: chart/chartform.cpp.

void QMenuData::removeItemAt ( int index )

Removes the menu item at position index.

See also removeItem() and clear().

void QMenuData::setAccel ( const QKeySequence & key, int id )

Sets the accelerator key for the menu item id to key.

An accelerator key consists of a key code and a combination of the modifiers SHIFT, CTRL, ALT or UNICODE_ACCEL (OR'ed or added). The header file qnamespace.h contains a list of key codes.

Defining an accelerator key produces a text that is added to the menu item; for instance, CTRL + Key_O produces "Ctrl+O". The text is formatted differently for different platforms.

Note that keyboard accelerators in Qt are not application-global, instead they are bound to a certain top-level window. For example, accelerators in QPopupMenu items only work for menus that are associated with a certain window. This is true for popup menus that live in a menu bar since their accelerators will then be installed in the menu bar itself. This also applies to stand-alone popup menus that have a top-level widget in their parentWidget() chain. The menu will then install its accelerator object on that top-level widget. For all other cases use an independent QAccel object.

Example:

    QMenuBar *mainMenu = new QMenuBar;
    QPopupMenu *fileMenu = new QPopupMenu;       // file sub menu
    fileMenu->insertItem( "Open Document", 67 ); // add "Open" item
    fileMenu->setAccel( CTRL + Key_O, 67 );      // Control and O to open
    fileMenu->insertItem( "Quit", 69 );          // add "Quit" item
    fileMenu->setAccel( CTRL + ALT + Key_Delete, 69 );
    mainMenu->insertItem( "File", fileMenu );    // add the file menu

If you need to translate accelerators, use tr() with a string:

    fileMenu->setAccel( tr("Ctrl+O"), 67 );

You can also specify the accelerator in the insertItem() function. You may prefer to use QAction to associate accelerators with menu items.

See also accel(), insertItem(), QAccel and QAction.

Example: menu/menu.cpp.

void QMenuData::setId ( int index, int id ) [virtual]

Sets the menu identifier of the item at index to id.

If index is out of range, the operation is ignored.

See also idAt().

void QMenuData::setItemChecked ( int id, bool check )

If check is TRUE, checks the menu item with id id; otherwise unchecks the menu item with id id. Calls QPopupMenu::setCheckable( TRUE ) if necessary.

See also isItemChecked().

Examples: canvas/canvas.cpp, grapher/grapher.cpp, mdi/application.cpp, menu/menu.cpp, progress/progress.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

void QMenuData::setItemEnabled ( int id, bool enable )

If enable is TRUE, enables the menu item with identifier id; otherwise disables the menu item with identifier id.

See also isItemEnabled().

Examples: mdi/application.cpp, menu/menu.cpp, progress/progress.cpp and showimg/showimg.cpp.

bool QMenuData::setItemParameter ( int id, int param )

Sets the parameter of the activation signal of item id to param.

If any receiver takes an integer parameter, this value is passed.

See also connectItem(), disconnectItem() and itemParameter().

Example: mdi/application.cpp.

void QMenuData::setWhatsThis ( int id, const QString & text )

Sets text as What's This help for the menu item with identifier id.

See also whatsThis().

Examples: application/application.cpp and mdi/application.cpp.

QString QMenuData::text ( int id ) const

Returns the text that has been set for menu item id, or a null string if no text has been set.

See also changeItem(), pixmap() and iconSet().

Examples: qdir/qdir.cpp and showimg/showimg.cpp.

void QMenuData::updateItem ( int id ) [virtual]

Virtual function; notifies subclasses about an item with id that has been changed.

Reimplemented in QPopupMenu.

QString QMenuData::whatsThis ( int id ) const

Returns the What's This help text for the item with identifier id or QString::null if no text has yet been defined.

See also setWhatsThis().

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


qmenudata.h Include File

qmenudata.h

This is the verbatim text of the qmenudata.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmenudata.h   3.0.5   edited Apr 4 18:25 $
**
** Definition of QMenuData class
**
** Created : 941128
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMENUDATA_H
#define QMENUDATA_H

#ifndef QT_H
#include "qglobal.h"
#include "qiconset.h" // conversion QPixmap->QIconset
#include "qkeysequence.h"
#include "qstring.h"
#include "qsignal.h"
#include "qfont.h"
#endif // QT_H

#ifndef QT_NO_MENUDATA

class QPopupMenu;
class QMenuDataData;
class QObject;

class QCustomMenuItem;
class QMenuItemData;

class Q_EXPORT QMenuItem			// internal menu item class
{
friend class QMenuData;
public:
    QMenuItem();
   ~QMenuItem();

    int		id()		const	{ return ident; }
    QIconSet   *iconSet()	const	{ return iconset_data; }
    QString	text()		const	{ return text_data; }
    QString	whatsThis()	const	{ return whatsthis_data; }
    QPixmap    *pixmap()	const	{ return pixmap_data; }
    QPopupMenu *popup()		const	{ return popup_menu; }
    QWidget *widget()		const	{ return widget_item; }
    QCustomMenuItem *custom()	const;
#ifndef QT_NO_ACCEL
    QKeySequence key()		const	{ return accel_key; }
#endif
    QSignal    *signal()	const	{ return signal_data; }
    bool	isSeparator()	const	{ return is_separator; }
    bool	isEnabled()	const	{ return is_enabled; }
    bool	isChecked()	const	{ return is_checked; }
    bool	isDirty()	const	{ return is_dirty; }

    void	setText( const QString &text ) { text_data = text; }
    void	setDirty( bool dirty )	       { is_dirty = dirty; }
    void	setWhatsThis( const QString &text ) { whatsthis_data = text; }

private:
    int		ident;				// item identifier
    QIconSet   *iconset_data;			// icons
    QString	text_data;			// item text
    QString	whatsthis_data;			// item Whats This help text
    QPixmap    *pixmap_data;			// item pixmap
    QPopupMenu *popup_menu;			// item popup menu
    QWidget    *widget_item;			// widget menu item
#ifndef QT_NO_ACCEL
    QKeySequence	accel_key;		// accelerator key (state|ascii)
#endif
    QSignal    *signal_data;			// connection
    uint	is_separator : 1;		// separator flag
    uint	is_enabled   : 1;		// disabled flag
    uint	is_checked   : 1;		// checked flag
    uint	is_dirty     : 1;		// dirty (update) flag
    QMenuItemData* d;

    QMenuItemData* extra();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMenuItem( const QMenuItem & );
    QMenuItem &operator=( const QMenuItem & );
#endif
};

#include "qptrlist.h"
typedef QPtrList<QMenuItem>	 QMenuItemList;
typedef QPtrListIterator<QMenuItem> QMenuItemListIt;

class Q_EXPORT QCustomMenuItem : public Qt
{
public:
    QCustomMenuItem();
    virtual ~QCustomMenuItem();
    virtual bool fullSpan() const;
    virtual bool isSeparator() const;
    virtual void setFont( const QFont& font );
    virtual void paint( QPainter* p, const QColorGroup& cg, bool act,
            bool enabled, int x, int y, int w, int h ) = 0;
    virtual QSize sizeHint() = 0;
};

class Q_EXPORT QMenuData			// menu data class
{
friend class QMenuBar;
friend class QPopupMenu;
public:
    QMenuData();
    virtual ~QMenuData();

    uint	count() const;

    int		insertItem( const QString &text,
                const QObject *receiver, const char* member,
                const QKeySequence& accel = 0, int id = -1, int index = -1 );
    int		insertItem( const QIconSet& icon,
                const QString &text,
                const QObject *receiver, const char* member,
                const QKeySequence& accel = 0, int id = -1, int index = -1 );
    int		insertItem( const QPixmap &pixmap,
                const QObject *receiver, const char* member,
                const QKeySequence& accel = 0, int id = -1, int index = -1 );
    int		insertItem( const QIconSet& icon,
                const QPixmap &pixmap,
                const QObject *receiver, const char* member,
                const QKeySequence& accel = 0, int id = -1, int index = -1 );

    int		insertItem( const QString &text, int id=-1, int index=-1 );
    int		insertItem( const QIconSet& icon,
                const QString &text, int id=-1, int index=-1 );

    int		insertItem( const QString &text, QPopupMenu *popup,
                int id=-1, int index=-1 );
    int		insertItem( const QIconSet& icon,
                const QString &text, QPopupMenu *popup,
                int id=-1, int index=-1 );

    int		insertItem( const QPixmap &pixmap, int id=-1, int index=-1 );
    int		insertItem( const QIconSet& icon,
                const QPixmap &pixmap, int id=-1, int index=-1 );
    int		insertItem( const QPixmap &pixmap, QPopupMenu *popup,
                int id=-1, int index=-1 );
    int		insertItem( const QIconSet& icon,
                const QPixmap &pixmap, QPopupMenu *popup,
                int id=-1, int index=-1 );

    int		insertItem( QWidget* widget, int id=-1, int index=-1 );

    int		insertItem( const QIconSet& icon, QCustomMenuItem* custom, int id=-1, int index=-1 );
    int		insertItem( QCustomMenuItem* custom, int id=-1, int index=-1 );

    int		insertSeparator( int index=-1 );

    void	removeItem( int id )		{ removeItemAt(indexOf(id)); }
    void	removeItemAt( int index );
    void	clear();

#ifndef QT_NO_ACCEL
    QKeySequence accel( int id )	const;
    void	setAccel( const QKeySequence& key, int id );
#endif

    QIconSet    *iconSet( int id )	const;
    QString text( int id )		const;
    QPixmap    *pixmap( int id )	const;

    void setWhatsThis( int id, const QString& );
    QString whatsThis( int id ) const;

    void	changeItem( int id, const QString &text );
    void	changeItem( int id, const QPixmap &pixmap );
    void	changeItem( int id, const QIconSet &icon, const QString &text );
    void	changeItem( int id, const QIconSet &icon, const QPixmap &pixmap );

    void	changeItem( const QString &text, int id ) { changeItem( id, text); } // obsolete
    void	changeItem( const QPixmap &pixmap, int id ) { changeItem( id, pixmap ); } // obsolete
    void	changeItem( const QIconSet &icon, const QString &text, int id ) {	// obsolete
    changeItem( id, icon, text );
    }

    bool	isItemActive( int id ) const;

    bool	isItemEnabled( int id ) const;
    void	setItemEnabled( int id, bool enable );

    bool	isItemChecked( int id ) const;
    void	setItemChecked( int id, bool check );

    virtual void updateItem( int id );

    int		indexOf( int id )	const;
    int		idAt( int index )	const;
    virtual void	setId( int index, int id );

    bool	connectItem( int id,
                 const QObject *receiver, const char* member );
    bool	disconnectItem( int id,
                const QObject *receiver, const char* member );

    bool	setItemParameter( int id, int param );
    int	itemParameter( int id ) const;

    QMenuItem  *findItem( int id )	const;
    QMenuItem  *findItem( int id, QMenuData ** parent )	const;
    QMenuItem * findPopup( QPopupMenu *, int *index = 0 );

    virtual void activateItemAt( int index );

protected:
    int		   actItem;
    QMenuItemList *mitems;
    QMenuData	  *parentMenu;
    uint	   isPopupMenu	: 1;
    uint	   isMenuBar	: 1;
    uint	   badSize	: 1;
    uint	   mouseBtDn	: 1;
    uint	avoid_circularity : 1;
    uint	actItemDown : 1;
    virtual void   menuContentsChanged();
    virtual void   menuStateChanged();
    virtual void   menuInsPopup( QPopupMenu * );
    virtual void   menuDelPopup( QPopupMenu * );

private:
    int		insertAny( const QString *, const QPixmap *, QPopupMenu *,
               const QIconSet*, int, int, QWidget* = 0, QCustomMenuItem* = 0);
    void	removePopup( QPopupMenu * );
    void	changeItemIconSet( int id, const QIconSet &icon );

    QMenuDataData *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMenuData( const QMenuData & );
    QMenuData &operator=( const QMenuData & );
#endif
};

#endif // QT_NO_MENUDATA

#endif // QMENUDATA_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMenuData Member List

Complete Member List for QMenuData

This is the complete list of member functions for QMenuData, including inherited members.

  • QMenuData()
  • ~QMenuData()
  • accel()
  • activateItemAt()
  • changeItem()
  • clear()
  • connectItem()
  • count()
  • disconnectItem()
  • findItem()
  • iconSet()
  • idAt()
  • indexOf()
  • insertItem()
  • insertSeparator()
  • isItemActive()
  • isItemChecked()
  • isItemEnabled()
  • itemParameter()
  • menuContentsChanged()
  • menuDelPopup()
  • menuInsPopup()
  • menuStateChanged()
  • pixmap()
  • removeItem()
  • removeItemAt()
  • setAccel()
  • setId()
  • setItemChecked()
  • setItemEnabled()
  • setItemParameter()
  • setWhatsThis()
  • text()
  • updateItem()
  • whatsThis()


QMessageBox类

QMessageBox类参考

QMessageBox类提供了一个有一条简短消息、一个图标和一些按钮的模式对话框。 详情请见……

#include <qmessagebox.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • enum Icon { NoIcon = 0, Information = 1, Warning = 2, Critical = 3 }
  • QMessageBox ( QWidget * parent = 0, const char * name = 0 )
  • QMessageBox ( const QString & caption, const QString & text, Icon icon, int button0, int button1, int button2, QWidget * parent = 0, const char * name = 0, bool modal = TRUE, WFlags f = WStyle_DialogBorder )
  • ~QMessageBox ()
  • QString text () const
  • void setText ( const QString & )
  • Icon icon () const
  • void setIcon ( Icon )
  • const QPixmap * iconPixmap () const
  • void setIconPixmap ( const QPixmap & )
  • QString buttonText ( int button ) const
  • void setButtonText ( int button, const QString & text )
  • virtual void adjustSize ()
  • TextFormat textFormat () const
  • void setTextFormat ( TextFormat )

静态公有成员

  • int information ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1 = 0, int button2 = 0 )
  • int information ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 )
  • int warning ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1, int button2 = 0 )
  • int warning ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 )
  • int critical ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1, int button2 = 0 )
  • int critical ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 )
  • void about ( QWidget * parent, const QString & caption, const QString & text )
  • void aboutQt ( QWidget * parent, const QString & caption = QString::null )
  • int message ( const QString & caption, const QString & text, const QString & buttonText = QString::null, QWidget * parent = 0, const char * = 0 ) (obsolete)
  • bool query ( const QString & caption, const QString & text, const QString & yesButtonText = QString::null, const QString & noButtonText = QString::null, QWidget * parent = 0, const char * = 0 ) (obsolete)
  • QPixmap standardIcon ( Icon icon, GUIStyle style ) (obsolete)
  • QPixmap standardIcon ( Icon icon )

属性

  • Icon icon - 消息框的图标
  • QPixmap iconPixmap - 当前图标
  • QString text - 被显示的消息框文本
  • TextFormat textFormat - 消息框中被显示的文本的格式

详细描述

QMessageBox类提供了一个有一条简短消息、一个图标和一些按钮的模式对话框。

消息框用于提供情报信息并且问一些简单的问题。

QMessageBox提供了一个不同信息的范围，大致按两个轴进行排列：严重程度和复杂程度。

按严重程度分：

信息 | 用于普通操作的一部分的消息框
警告 | 用于告诉用户一些不常出现的错误的消息框
严重 | 用于告诉用户严重的错误的消息框

对于每一个严重程度，消息框都有不同的图标。

按复杂程度分为一个按钮（确定）的简单消息、或者用于提问的两个或者甚至三个按钮。

还有一些用于常用情况的静态函数。

实例：

如果程序不能找到一个支持文件，但是能在没有它的情况在做得很好：

QMessageBox::information( this, "Application name",
    "Unable to find the user preferences file.\n"
    "The factory default will be used instead." );

warning()可以用于告诉用户一些不常出现的错误，或者不容易被修复的错误：

switch( QMessageBox::warning( this, "Application name",
        "Could not connect to the <mumble> server.\n"
        "This program can't function correctly "
        "without the server.\n\n",
        "Retry",
        "Quit", 0, 0, 1 ) )
    case 0: // 用户点击“再试”或者按下回车键
        // 再次尝试
        break;
    case 1: // 用户点击“退出”或者按下Esc键
        // 退出
        break;
}

所有消息框的消息的文本部分都可以是多信息文本或者一般文本。如果拟制定一个多信息文本格式字符串，它将会被使用默认样式单来呈现。详细情况请参考QStyleSheet::defaultSheet()。对于包含XML元字符的特定字符串，自动多信息文本检测可能会失败，会把一般文本不正确地解释为多信息文本。在这种情况下，可以使用QStyleSheet::convertFromPlainText()来把你的一般文本字符串转化为在视觉上一致的多信息文本或者明确地通过setTextFormat()设置文本格式。

注意微软视窗用户界面指南强烈建议在把应用程序名称作为这个窗口的标题。

下面是更多的关于如何使用静态成员函数地实例。在这些实例之后，你将会找到非静态成员函数的概述。

退出程序是正常操作的一部分。如果存在没有保存地数据，用户可能应该被被询问他们是否想保存数据。例如：

switch( QMessageBox::information( this, "Application name here",
        "The document contains unsaved changes\n"
        "Do you want to save the changes before exiting?",
        "&Save", "&Discard", "Cancel",
        0,      // Enter == button 0
        2 ) ) { // Escape == button 2
    case 0: // Save被点击或者Alt+S被按下或者Enter被按下。
        // 保存
        break;
    case 1: // Discard被点击或者Alt+D被按下。
        // 不保存但退出
        break;
    case 2: // Cancel被点击或者Alt+C被按下或者Escape被按下。
        // 不退出
        break;
}

为了和微软的建议一致，应用程序的名称被作为窗口标题。Escape按钮撤销整个退出操作，并且按下Enter导致在退出发生之前这些变化被保存。

磁盘已满错误是不常见的（在完美的世界中，它们是存在的）并且它们通常很难变为正确。这个实例使用了预定义的按钮来替换了写在代码中的按钮文本：

switch( QMessageBox::warning( this, "Application name here",
        "Could not save the user preferences,\n"
        "because the disk is full.  You can delete\n"
        "some files and press Retry, or you can\n"
        "abort the Save Preferences operation.",
        QMessageBox::Retry | QMessageBox::Default,
        QMessageBox::Abort | QMessageBox::Escape )) {
    case QMessageBox::Retry: // Retry被点击或者Enter被按下。
        // 再次尝试
        break;
    case QMessageBox::Abort: // Abort被点击或者Escape被按下。
        // 放弃
        break;
}

critical()函数应用被用于保留严重错误。在这个实例中，errorDetails是QString或者const char*，并且QString被用于连接几个字符串：

QMessageBox::critical( 0, "Application name here",
        QString("An internal error occurred. Please ") +
        "call technical support at 123456789 and report\n"+
        "these numbers:\n\n" + errorDetails +
        "\n\n<Application> will now exit." );

在这个实例中，一个“OK”按钮被显示。

QMessageBox提供了一个非常简单的关于框，可以显示你提供的适当的图标和文本。

QMessageBox::about( this, "About <Application>",
        "<Application> is a <one-paragraph blurb>\n\n"
        "Copyright 1951-2002 Such-and-such.  "
        "<License words here.>\n\n"
        "For technical support, call 123456789 or see\n"
        "http://www.such-and-such.com/Application/\n" );

更多信息请参考about()。

如果你想让用户知道这个应用程序是使用Qt构建的（这样他们就会知道你使用的是高质量的工具）：你也许喜欢在帮助菜单下的“关于Qt”菜单选项来调用aboutQt()。

如果没有任何标准消息框是合适地，你可以自己手工创建一个QMessageBox并且自己定义按钮文本：

QMessageBox mb( "Application name here",
        "Saving the file will overwrite the original file on the disk.\n"
        "Do you really want to save?",
        QMessageBox::Information,
        QMessageBox::Yes | QMessageBox::Default,
        QMessageBox::No,
        QMessageBox::Cancel | QMessageBox::Escape );
mb.setButtonText( QMessageBox::Yes, "Save" );
mb.setButtonText( QMessageBox::No, "Discard" );
switch( mb.exec() ) {
    case QMessageBox::Yes:
        // 保存并且退出
        break;
    case QMessageBox::No:
        // 不保存退出
        break;
    case QMessageBox::Cancel:
        // 不保存并且不退出
        break;
}

QMessageBox定义了两个枚举变量：Icon和没有名称的按钮类型。Icon为每一个图形用户界面风格定义了Information、Warning和Critical图标。它被构造函数和information()、warning()和critical()静态函数使用。叫做standardIcon()的函数让你能够访问不同的图标。

按钮类型有：

  • Ok - 单按钮消息框地默认值
  • Cancel - 注意这个不是自动和Escape关联的
  • Yes
  • No
  • Abort
  • Retry
  • Ignore

按钮类型可以由上述类型和下面两个修饰成分使用或“|”来进行组合。

  • Default - 让按Enter键等于点击这个按钮。通常用于OK、Yes或者其它相似的。
  • Escape - 让按Escape键等于点击这个按钮。通常用于Abort、Cancel或者其它相似的。

text()、icon()和iconPixmap()函数提供了对消息框的当前文本和像素映射的访问。

setButtonText()和buttonText()提供了对按钮的访问。setText()、setIcon()和setIconPixmap()让你能够修改它。setIcon()和setIconPixmap()的不同是前者接受QMessageBox::Icon并且用于设置标准图标，而后者接受QPixmap并且用于设置自定义图标。

QMessageBox没有信号和槽。

也可以参考QDialog、Isys on error messages、图形用户界面设计手册：消息框和对话框类。

成员类型文档

QMessageBox::Icon

这个枚举变量包含被提供的如下值：

  • QMessageBox::NoIcon - 消息框没有任何图标。
  • QMessageBox::Information - 一个指出这个消息没有超出普通范围的图标。
  • QMessageBox::Warning - 一个指出这个消息是警告，但是还能被处理的图标。
  • QMessageBox::Critical - 一个指出这个消息意味着严重问题的图标。

成员函数文档

QMessageBox::QMessageBox ( QWidget * parent = 0, const char * name = 0 )

构造一个没有文本和一个标签为“OK”的按钮的消息框。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

parent和name参数被传递给QDialog构造函数。

QMessageBox::QMessageBox ( const QString & caption, const QString & text, Icon icon, int button0, int button1, int button2, QWidget * parent = 0, const char * name = 0, bool modal = TRUE, WFlags f = WStyle_DialogBorder )

构造一个标题为caption、文本为text、图标为icon并且最多为三个按钮的消息框。

icon必须为如下之一：

  • QMessageBox::NoIcon
  • QMessageBox::Information
  • QMessageBox::Warning
  • QMessageBox::Critical

每一个按钮，button0、button1和button2为如下之一：

  • QMessageBox::NoButton
  • QMessageBox::Ok
  • QMessageBox::Cancel
  • QMessageBox::Yes
  • QMessageBox::No
  • QMessageBox::Abort
  • QMessageBox::Retry
  • QMessageBox::Ignore

如果你的消息框少于三个按钮，QMessageBox::NoButton用于靠后的参数。

一个按钮可以和QMessageBox::Default标记进行或运算，这使得它成为默认按钮（当Enter被按下时，它被点击）。

一个按钮可以和QMessageBox::Escape标记进行或运算，这使得它成为撤销或者关闭按钮（当Escape被按下时，它被点击）。

实例：

QMessageBox mb( "Application Name",
        "Hardware failure.\n\nDisk error detected\nDo you want to stop?",
        QMessageBox::NoIcon,
        QMessageBox::Yes | QMessageBox::Default,
        QMessageBox::No  | QMessageBox::Escape,
        QMessageBox::NoButton );
if ( mb.exec() == QMessageBox::No )
    // 再次尝试

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

如果modal为真，这个消息框变为模式的，否则它变为非模式的。

parent、name、modal和f参数被传递给QDialog构造函数。

也可以参考caption、text和icon。

QMessageBox::~QMessageBox ()

销毁这个消息框。

void QMessageBox::about ( QWidget * parent, const QString & caption, const QString & text ) [静态]

显示一个标题为caption并且文本为text的简单关于框。关于框的父对象为parent。

about()在四个位置查找合适的图标：

  1. 如果parent->icon()存在，它会首先使用它。
  2. 如果没有，它会尝试一下包含parent的顶级窗口部件。
  3. 如果这个也失败了，它会尝试主窗口部件。
  4. 作为最后的手段，它使用信息图标。

关于框有一个标签为OK的单一按钮。

也可以参考QWidget::icon和QApplication::mainWidget()。

实例：action/application.cpp、application/application.cpp、chart/chartform.cpp、helpviewer/helpwindow.cpp、mdi/application.cpp、menu/menu.cpp和themes/themes.cpp。

void QMessageBox::aboutQt ( QWidget * parent, const QString & caption = QString::null ) [静态]

显示标题为caption并且放在parent（如果parent不为0）的中间关于Qt的简单消息框。这个消息包含这个应用程序正在使用的Qt的版本号。

这个会被包含在帮助菜单中。关于实例请参考examples/menu/menu.cpp。

实例：action/application.cpp、application/application.cpp、chart/chartform.cpp、helpviewer/helpwindow.cpp、menu/menu.cpp、themes/themes.cpp和trivial/trivial.cpp。

void QMessageBox::adjustSize () [虚]

仅在QDialog::exec()或QDialog::show()被调用之前调节消息框的大小来适合内容。

如果消息框在显示之前已经被明显地重新定义大小，这个函数就不会被调用。

从QWidget中重新实现。

QString QMessageBox::buttonText ( int button ) const

返回消息框按钮button的文本，或者如果消息框没有包含这个按钮返回零。

也可以参考setButtonText()。

int QMessageBox::critical ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1, int button2 = 0 ) [静态]

打开一个标题为caption并且文本为text的严重消息框。这个对话框最多有三个按钮。每个按钮参数button0、button1和button2被设置为下列各值之一：

  • QMessageBox::NoButton
  • QMessageBox::Ok
  • QMessageBox::Cancel
  • QMessageBox::Yes
  • QMessageBox::No
  • QMessageBox::Abort
  • QMessageBox::Retry
  • QMessageBox::Ignore

如果你不想要三个按钮，设置最后一个按钮或者最后两个按钮为QMessageBox::NoButton。

返回被点击的按钮地标识（QMessageBox::Ok或QMessageBox::No等等）。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考information()和warning()。

实例：network/ftpclient/ftpmainwindow.cpp、process/process.cpp和xml/outliner/outlinetree.cpp。

int QMessageBox::critical ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

显示一个标题为caption、文本为text并且按钮分别为1、2、3的严重消息对话框。返回被点击的按钮的数字（0、1或2）。

button0Text为第一个按钮的文本并且它是可选的。如果button0Text没有被提供，“OK”（被翻译的）将被使用。button1Text为第二个按钮的文本并且它是可选的并且button2Text为第三个按钮的文本并且它是可选的。defaultButtonNumber（0、1或2）是默认按钮的索引，按下Return或者Enter和点击这个默认按钮是相同的。它默认为0（第一个按钮）。escapeButtonNumber是Escape按钮的索引，按下Escape和点击这个按钮是相同的。它默认为-1（就是按下Escape什么也不做），提供0、1或2使按下Escape等同于按下对应的按钮。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考information()和warning()。

Icon QMessageBox::icon () const

返回消息框的图标。详细情况请参考“icon”属性。

const QPixmap * QMessageBox::iconPixmap () const

返回当前图标。详细情况请参考“iconPixmap”属性。

int QMessageBox::information ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1 = 0, int button2 = 0 ) [静态]

打开一个标题为caption并且文本为text的信息消息框。这个对话框最多有三个按钮。每个按钮参数button0、button1和button2被设置为下列各值之一：

  • QMessageBox::NoButton
  • QMessageBox::Ok
  • QMessageBox::Cancel
  • QMessageBox::Yes
  • QMessageBox::No
  • QMessageBox::Abort
  • QMessageBox::Retry
  • QMessageBox::Ignore

如果你不想要三个按钮，设置最后一个按钮或者最后两个按钮为QMessageBox::NoButton。

返回被点击的按钮地标识（QMessageBox::Ok或QMessageBox::No等等）。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考warning()和critical()。

实例：action/application.cpp、application/application.cpp、chart/chartform.cpp、dirview/dirview.cpp、fileiconview/qfileiconview.cpp、picture/picture.cpp和qwerty/qwerty.cpp。

int QMessageBox::information ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

显示一个标题为caption、文本为text并且按钮分别为1、2、3的信息消息对话框。返回被点击的按钮的数字（0、1或2）。

button0Text为第一个按钮的文本并且它是可选的。如果button0Text没有被提供，“OK”（被翻译的）将被使用。button1Text为第二个按钮的文本并且它是可选的并且button2Text为第三个按钮的文本并且它是可选的。defaultButtonNumber（0、1或2）是默认按钮的索引，按下Return或者Enter和点击这个默认按钮是相同的。它默认为0（第一个按钮）。escapeButtonNumber是Escape按钮的索引，按下Escape和点击这个按钮是相同的。它默认为-1（就是按下Escape什么也不做），提供0、1或2使按下Escape等同于按下对应的按钮。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考warning()和critical()。

int QMessageBox::message ( const QString & caption, const QString & text, const QString & buttonText = QString::null, QWidget * parent = 0, const char * = 0 ) [静态]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用特定参数直接打开模式消息框。

请使用information()、warning()或critical()来替代。

实例：grapher/grapher.cpp。

bool QMessageBox::query ( const QString & caption, const QString & text, const QString & yesButtonText = QString::null, const QString & noButtonText = QString::null, QWidget * parent = 0, const char * = 0 ) [静态]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用有两个按钮的模式消息框询问用户。注意caption不总是被显示，它依赖于窗口管理器。

请使用information()、warning()或critical()来替代。

void QMessageBox::setButtonText ( int button, const QString & text )

设置消息框按钮button的文本为text。设置一个没有在消息框中出现的按钮的文本会被默默地忽略。

也可以参考buttonText()。

void QMessageBox::setIcon ( Icon )

设置消息框的图标。详细情况请参考“icon”属性。

void QMessageBox::setIconPixmap ( const QPixmap & )

设置当前图标。详细情况请参考“iconPixmap”属性。

void QMessageBox::setText ( const QString & )

设置被显示的消息框文本。详细情况请参考“text”属性。

void QMessageBox::setTextFormat ( TextFormat )

设置消息框中被显示的文本的格式。详细情况请参考“textFormat”属性。

QPixmap QMessageBox::standardIcon ( Icon icon ) [静态]

返回标准图标使用的像素映射。这允许这些像素映射用于更复杂的消息框。icon指定了所需图标，例如QMessageBox::Information、QMessageBox::Warning或QMessageBox::Critical。

QPixmap QMessageBox::standardIcon ( Icon icon, GUIStyle style ) [静态]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

返回标准图标使用的像素映射。这允许这些像素映射用于更复杂的消息框。icon指定了所需图标，例如QMessageBox::Information、QMessageBox::Warning或QMessageBox::Critical。

style不被使用。

QString QMessageBox::text () const

返回被显示的消息框文本。详细情况请参考“text”属性。

TextFormat QMessageBox::textFormat () const

返回消息框中被显示的文本的格式。详细情况请参考“textFormat”属性。

int QMessageBox::warning ( QWidget * parent, const QString & caption, const QString & text, int button0, int button1, int button2 = 0 ) [静态]

打开一个标题为caption并且文本为text的警告消息框。这个对话框最多有三个按钮。每个按钮参数button0、button1和button2被设置为下列各值之一：

  • QMessageBox::NoButton
  • QMessageBox::Ok
  • QMessageBox::Cancel
  • QMessageBox::Yes
  • QMessageBox::No
  • QMessageBox::Abort
  • QMessageBox::Retry
  • QMessageBox::Ignore

如果你不想要三个按钮，设置最后一个按钮或者最后两个按钮为QMessageBox::NoButton。

返回被点击的按钮地标识（QMessageBox::Ok或QMessageBox::No等等）。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考information()和critical()。

实例：chart/chartform.cpp、i18n/main.cpp、network/mail/smtp.cpp、qwerty/qwerty.cpp、showimg/showimg.cpp和sound/sound.cpp。

int QMessageBox::warning ( QWidget * parent, const QString & caption, const QString & text, const QString & button0Text = QString::null, const QString & button1Text = QString::null, const QString & button2Text = QString::null, int defaultButtonNumber = 0, int escapeButtonNumber = -1 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

显示一个标题为caption、文本为text并且按钮分别为1、2、3的警告消息对话框。返回被点击的按钮的数字（0、1或2）。

button0Text为第一个按钮的文本并且它是可选的。如果button0Text没有被提供，“OK”（被翻译的）将被使用。button1Text为第二个按钮的文本并且它是可选的并且button2Text为第三个按钮的文本并且它是可选的。defaultButtonNumber（0、1或2）是默认按钮的索引，按下Return或者Enter和点击这个默认按钮是相同的。它默认为0（第一个按钮）。escapeButtonNumber是Escape按钮的索引，按下Escape和点击这个按钮是相同的。它默认为-1（就是按下Escape什么也不做），提供0、1或2使按下Escape等同于按下对应的按钮。

如果parent为0，消息框变为应用程序全局的模式对话框。如果parent为一个窗口部件，消息框变为相对于parent的模式对话框。

也可以参考information()和critical()。

属性文档

Icon icon

这个属性保存的是消息框的图标。

消息框的图标可以是如下预定义图标的一种：

  • QMessageBox::NoIcon
  • QMessageBox::Information
  • QMessageBox::Warning
  • QMessageBox::Critical

用于显示图标的实际像素映射依赖于当前图形用户界面风格。你也可以使用QMessageBox::iconPixmap属性来设置自定义像素映射。默认图标为QMessageBox::NoIcon。

也可以参考iconPixmap。

通过setIcon()设置属性值并且通过icon()来获得属性值。

QPixmap iconPixmap

这个属性保存的是当前图标。

这个图标正在被这个消息框使用。注意很难绘制一个在Motif和Windows风格中看起来比较一致的像素映射，你也许需要绘制两个像素映射。

也可以参考icon。

通过setIconPixmap()设置属性值并且通过iconPixmap()来获得属性值。

QString text

This property holds the message box text to be displayed. 这个属性保存的是被显示的消息框文本。

这个文本将被解释为一般文本或者多信息文本，根据文本格式设置（QMessageBox::textFormat）。默认设置为AutoText，也就是说消息框将会试图自动检测文本格式。

这个属性的默认设置是QString::null。

也可以参考textFormat。

通过setText()设置属性值并且通过text()来获得属性值。

TextFormat textFormat

This property holds the format of the text displayed by the message box. 这个属性保存的是消息框中被显示的文本的格式。

这是当前被消息框使用的文本格式。对于可能选项的解释请参考Qt::TextFormat枚举变量。

默认设置是AutoText。

也可以参考text。

通过setTextFormat()设置属性值并且通过textFormat()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmessagebox.h包含文件

qmessagebox.h

这里是qmessagebox.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qmessagebox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QMessageBox class
**
** Created : 950503
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMESSAGEBOX_H
#define QMESSAGEBOX_H

#ifndef QT_H
#include "qdialog.h"
#endif // QT_H

#ifndef QT_NO_MESSAGEBOX

class  QLabel;
class  QPushButton;
struct QMessageBoxData;

class Q_EXPORT QMessageBox : public QDialog
{
    Q_OBJECT
    Q_ENUMS( Icon )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( Icon icon READ icon WRITE setIcon )
    Q_PROPERTY( QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap )
    Q_PROPERTY( TextFormat textFormat READ textFormat WRITE setTextFormat )

public:
    enum Icon { NoIcon = 0, Information = 1, Warning = 2, Critical = 3 };

    QMessageBox( QWidget* parent=0, const char* name=0 );
    QMessageBox( const QString& caption, const QString &text, Icon icon,
         int button0, int button1, int button2,
         QWidget* parent=0, const char* name=0, bool modal=TRUE,
         WFlags f=WStyle_DialogBorder  );
    ~QMessageBox();

    enum { NoButton = 0, Ok = 1, Cancel = 2, Yes = 3, No = 4, Abort = 5,
       Retry = 6, Ignore = 7, ButtonMask = 0x07,
       Default = 0x100, Escape = 0x200, FlagMask = 0x300 };

    static int information( QWidget *parent, const QString &caption,
                const QString& text,
                int button0, int button1=0, int button2=0 );
    static int information( QWidget *parent, const QString &caption,
                const QString& text,
                const QString& button0Text = QString::null,
                const QString& button1Text = QString::null,
                const QString& button2Text = QString::null,
                int defaultButtonNumber = 0,
                int escapeButtonNumber = -1 );

    static int warning( QWidget *parent, const QString &caption,
            const QString& text,
            int button0, int button1, int button2=0 );
    static int warning( QWidget *parent, const QString &caption,
            const QString& text,
            const QString& button0Text = QString::null,
            const QString& button1Text = QString::null,
            const QString& button2Text = QString::null,
            int defaultButtonNumber = 0,
            int escapeButtonNumber = -1 );

    static int critical( QWidget *parent, const QString &caption,
             const QString& text,
             int button0, int button1, int button2=0 );
    static int critical( QWidget *parent, const QString &caption,
             const QString& text,
             const QString& button0Text = QString::null,
             const QString& button1Text = QString::null,
             const QString& button2Text = QString::null,
             int defaultButtonNumber = 0,
             int escapeButtonNumber = -1 );

    static void about( QWidget *parent, const QString &caption,
               const QString& text );

    static void aboutQt( QWidget *parent,
             const QString& caption=QString::null );

/* OBSOLETE */
    static int message( const QString &caption,
            const QString& text,
            const QString& buttonText=QString::null,
            QWidget *parent=0, const char * =0 ) {
    return QMessageBox::information( parent, caption, text,
                     buttonText.isEmpty()
                     ? tr("OK") : buttonText ) == 0;
    }

/* OBSOLETE */
    static bool query( const QString &caption,
               const QString& text,
               const QString& yesButtonText=QString::null,
               const QString& noButtonText=QString::null,
               QWidget *parent=0, const char * = 0 ) {
    return QMessageBox::information( parent, caption, text,
                     yesButtonText.isEmpty()
                     ? tr("OK") : yesButtonText,
                     noButtonText ) == 0;
    }

    QString	text() const;
    void	setText( const QString &);

    Icon	icon() const;

    // ### the next four functions will probably be renamed in 3.0.
    void	setIcon( Icon );
    void	setIcon( const QPixmap & );

    const QPixmap *iconPixmap() const;
    void	setIconPixmap( const QPixmap & );

    QString	buttonText( int button ) const;
    void	setButtonText( int button, const QString &);

    void	adjustSize();

/* OBSOLETE */
    static QPixmap standardIcon( Icon icon, GUIStyle );

    static QPixmap standardIcon( Icon icon );

    TextFormat textFormat() const;
    void	 setTextFormat( TextFormat );

protected:
    void	resizeEvent( QResizeEvent * );
    void	showEvent( QShowEvent * );
    void	keyPressEvent( QKeyEvent * );
    void	styleChanged( QStyle& );

private slots:
    void	buttonClicked();

private:
    void	init( int, int, int );
    int		indexOf( int ) const;
    void	resizeButtons();
    QLabel     *label;
    QMessageBoxData *mbd;
    void       *reserved1;
    void       *reserved2;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMessageBox( const QMessageBox & );
    QMessageBox &operator=( const QMessageBox & );
#endif
};

#endif // QT_NO_MESSAGEBOX

#endif // QMESSAGEBOX_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMessageBox成员列表

完整的QMessageBox成员列表

这里是QMessageBox成员函数的完整列表，包括继承的成员。

  • QMessageBox()
  • ~QMessageBox()
  • about()
  • aboutQt()
  • accept()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • buttonText()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • critical()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconPixmap()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • information()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • message()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • query()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setButtonText()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconPixmap()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setText()
  • setTextFormat()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • standardIcon()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • textFormat()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • warning()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMetaObject Class

QMetaObject Class Reference

The QMetaObject class contains meta information about Qt objects. More...

#include <qmetaobject.h>

List of all member functions.

Public Members

  • const char * className () const
  • const char * superClassName () const
  • QMetaObject * superClass () const
  • bool inherits ( const char * clname ) const
  • int numSlots ( bool super = FALSE ) const
  • int numSignals ( bool super = FALSE ) const
  • QStrList slotNames ( bool super = FALSE ) const
  • QStrList signalNames ( bool super = FALSE ) const
  • int numClassInfo ( bool super = FALSE ) const
  • const QClassInfo * classInfo ( int index, bool super = FALSE ) const
  • const char * classInfo ( const char * name, bool super = FALSE ) const
  • const QMetaProperty * property ( int index, bool super = FALSE ) const
  • int findProperty ( const char * name, bool super = FALSE ) const
  • QStrList propertyNames ( bool super = FALSE ) const
  • int numProperties ( bool super = FALSE ) const

Detailed Description

The QMetaObject class contains meta information about Qt objects.

The Meta Object System in Qt is responsible for the signals and slots inter-object communication mechanism, runtime type information and the property system. All meta information in Qt is kept in a single instance of QMetaObject per class.

This class is not normally required for application programming. But if you write meta applications, such as scripting engines or GUI builders, you might find these functions useful:

  • className() to get the name of a class.
  • superClassName() to get the name of the superclass.
  • inherits(), the function called by QObject::inherits().
  • superClass() to access the superclass's meta object.
  • numSlots(), numSignals(), slotNames(), and signalNames() to get information about a class's signals and slots.
  • property() and propertyNames() to obtain information about a class's properties.

Classes may have a list of name-value pairs of class information. The number of pairs is returned by numClassInfo(), and values are returned by classInfo().

See also moc (Meta Object Compiler) and Object Model.

Member Function Documentation

const QClassInfo * QMetaObject::classInfo ( int index, bool super = FALSE ) const

Returns the class information with index index or 0 if no such information exists.

If super is TRUE, inherited class information is included.

const char * QMetaObject::classInfo ( const char * name, bool super = FALSE ) const

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

Returns the class information with name name or 0 if no such information exists.

If super is TRUE, inherited class information is included.

const char * QMetaObject::className () const

Returns the class name.

See also QObject::className() and superClassName().

int QMetaObject::findProperty ( const char * name, bool super = FALSE ) const

Returns the index for the property with name name or -1 if no such property exists.

If super is TRUE, inherited properties are included.

See also property() and propertyNames().

bool QMetaObject::inherits ( const char * clname ) const

Returns TRUE if this class inherits clname within the meta object inheritance chain; otherwise returns FALSE.

(A class is considered to inherit itself.)

int QMetaObject::numClassInfo ( bool super = FALSE ) const

Returns the number of items of class information available for this class.

If super is TRUE, inherited class information is included.

int QMetaObject::numProperties ( bool super = FALSE ) const

Returns the number of properties for this class.

If super is TRUE, inherited properties are included.

See also propertyNames().

int QMetaObject::numSignals ( bool super = FALSE ) const

Returns the number of signals for this class.

If super is TRUE, inherited signals are included.

See also signalNames().

int QMetaObject::numSlots ( bool super = FALSE ) const

Returns the number of slots for this class.

If super is TRUE, inherited slots are included.

See also slotNames().

const QMetaProperty * QMetaObject::property ( int index, bool super = FALSE ) const

Returns the property meta data for the property at index index or 0 if no such property exists.

If super is TRUE, inherited properties are included.

See also propertyNames().

QStrList QMetaObject::propertyNames ( bool super = FALSE ) const

Returns a list with the names of all this class's properties.

If super is TRUE, inherited properties are included.

See also property().

QStrList QMetaObject::signalNames ( bool super = FALSE ) const

Returns a list with the names of all this class's signals.

If super is TRUE, inherited signals are included.

QStrList QMetaObject::slotNames ( bool super = FALSE ) const

Returns a list with the names of all this class's slots.

If super is TRUE, inherited slots are included.

See also numSlots().

QMetaObject * QMetaObject::superClass () const

Returns the meta object of the super class or 0 if there is no such object.

const char * QMetaObject::superClassName () const

Returns the class name of the superclass or 0 if there is no superclass in the QObject hierachy.

See also className().

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


qmetaobject.h Include File

qmetaobject.h

This is the verbatim text of the qmetaobject.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmetaobject.h   3.0.5   edited Dec 4 2001 $
**
** Definition of QMetaObject class
**
** Created : 930419
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMETAOBJECT_H
#define QMETAOBJECT_H

#ifndef QT_H
#include "qconnection.h"
#include "qstrlist.h"
#endif // QT_H

#ifndef Q_MOC_OUTPUT_REVISION
#define Q_MOC_OUTPUT_REVISION 19
#endif

class QObject;
struct QUMethod;
class QMetaObjectPrivate;

struct QMetaData				// - member function meta data
{						//   for signal and slots
    const char *name;				// - member name
    const QUMethod* method;			// - detailed method description
    enum Access { Private, Protected, Public };
    Access access;				// - access permission
};

#ifndef QT_NO_PROPERTIES
struct QMetaEnum				// enumerator meta data
{						//  for properties
    const char *name;				// - enumerator name
    uint count;					// - number of values
    struct Item					// - a name/value pair
    {
    const char *key;
    int value;
    };
    const Item *items;				// - the name/value pairs
    bool set;					// whether enum has to be treated as a set
};
#endif

#ifndef QT_NO_PROPERTIES

class Q_EXPORT QMetaProperty			// property meta data
{
public:
    const char*	type() const { return t; }	// type of the property
    const char*	name() const { return n; }	// name of the property

    bool writable() const;
    bool isValid() const;

    bool isSetType() const;
    bool isEnumType() const;
    QStrList enumKeys() const;			// enumeration names

    int keyToValue( const char* key ) const;	// enum and set conversion functions
    const char* valueToKey( int value ) const;
    int keysToValue( const QStrList& keys ) const;
    QStrList valueToKeys( int value ) const;

    bool designable( QObject* ) const;
    bool scriptable( QObject* ) const;
    bool stored( QObject* ) const;

    bool reset( QObject* ) const;

    const char* t;			// internal
    const char* n;			// internal

    enum Flags  {
    Invalid		= 0x00000000,
    Readable	= 0x00000001,
    Writable	= 0x00000002,
    EnumOrSet	= 0x00000004,
    StdSet		= 0x00000100,
    Override	= 0x00000200
    };

    uint flags; // internal
    bool testFlags( uint f ) const;	// internal
    bool stdSet() const; 		// internal
    int id() const; 			// internal

    QMetaObject** meta; 		// internal
    const QMetaEnum* enumData;		// internal
    int _id; 				// internal
    void clear(); 			// internal
};

inline bool QMetaProperty::testFlags( uint f ) const
{ return (flags & (uint)f) != (uint)0; }

#endif // QT_NO_PROPERTIES

struct QClassInfo				// class info meta data
{
    const char* name;				// - name of the info
    const char* value;				// - value of the info
};

class Q_EXPORT QMetaObject			// meta object class
{
public:
    QMetaObject( const char * const class_name, QMetaObject *superclass,
         const QMetaData * const slot_data, int n_slots,
         const QMetaData * const signal_data, int n_signals,
#ifndef QT_NO_PROPERTIES
         const QMetaProperty *const prop_data, int n_props,
         const QMetaEnum *const enum_data, int n_enums,
#endif
         const QClassInfo *const class_info, int n_info );

    virtual ~QMetaObject();

    const char	*className()		const { return classname; }
    const char	*superClassName()	const { return superclassname; }

    QMetaObject *superClass()		const { return superclass; }

    bool	inherits( const char* clname ) const;

    int	numSlots( bool super = FALSE ) const;
    int		numSignals( bool super = FALSE ) const;

    int		findSlot( const char *, bool super = FALSE ) const;
    int		findSignal( const char *, bool super = FALSE ) const;

    const QMetaData 	*slot( int index, bool super = FALSE ) const;
    const QMetaData 	*signal( int index, bool super = FALSE ) const;

    QStrList	slotNames( bool super = FALSE ) const;
    QStrList	signalNames( bool super = FALSE ) const;

    int		slotOffset() const;
    int		signalOffset() const;
    int		propertyOffset() const;

    int		numClassInfo( bool super = FALSE ) const;
    const QClassInfo	*classInfo( int index, bool super = FALSE ) const;
    const char	*classInfo( const char* name, bool super = FALSE ) const;

#ifndef QT_NO_PROPERTIES
    const QMetaProperty	*property( int index, bool super = FALSE ) const;
    int findProperty( const char *name, bool super = FALSE ) const;
    int indexOfProperty( const QMetaProperty*, bool super = FALSE ) const;
    const QMetaProperty* resolveProperty( const QMetaProperty* ) const;
    int resolveProperty( int ) const;
    QStrList		propertyNames( bool super = FALSE ) const;
    int		numProperties( bool super = FALSE ) const;
#endif

    // static wrappers around constructors, necessary to work around a
    // Windows-DLL limitation: objects can only be deleted within a
    // DLL if they were actually created within that DLL.
    static QMetaObject	*new_metaobject( const char *, QMetaObject *,
                    const QMetaData *const, int,
                    const QMetaData *const, int,
#ifndef QT_NO_PROPERTIES
                    const QMetaProperty *const prop_data, int n_props,
                    const QMetaEnum *const enum_data, int n_enums,
#endif
                    const QClassInfo *const  class_info, int n_info );
#ifndef QT_NO_PROPERTIES
    const QMetaEnum		*enumerator( const char* name, bool super = FALSE ) const;
#endif

    static QMetaObject *metaObject( const char *class_name );

private:
    QMemberDict		*init( const QMetaData *, int );

    const char		*classname;		// class name
    const char		*superclassname;	// super class name
    QMetaObject	*superclass;			// super class meta object
    QMetaObjectPrivate	*d;			// private data for...
    void	*reserved;			// ...binary compatibility
    const QMetaData		*slotData;	// slot meta data
    QMemberDict	*slotDict;			// slot dictionary
    const QMetaData		*signalData;	// signal meta data
    QMemberDict	*signalDict;			// signal dictionary
    int signaloffset;
    int slotoffset;
#ifndef QT_NO_PROPERTIES
    int propertyoffset;
#endif

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMetaObject( const QMetaObject & );
    QMetaObject &operator=( const QMetaObject & );
#endif
};

inline int QMetaObject::slotOffset() const
{ return slotoffset; }

inline int QMetaObject::signalOffset() const
{ return signaloffset; }

#ifndef QT_NO_PROPERTIES
inline int QMetaObject::propertyOffset() const
{ return propertyoffset; }
#endif

class Q_EXPORT QMetaObjectCleanUp
{
public:
    QMetaObjectCleanUp();
    ~QMetaObjectCleanUp();

    void setMetaObject( QMetaObject *&mo );

private:
    QMetaObject **metaObject;
};

#endif // QMETAOBJECT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMetaObject Member List

Complete Member List for QMetaObject

This is the complete list of member functions for QMetaObject, including inherited members.

  • classInfo()
  • className()
  • findProperty()
  • inherits()
  • numClassInfo()
  • numProperties()
  • numSignals()
  • numSlots()
  • property()
  • propertyNames()
  • signalNames()
  • slotNames()
  • superClass()
  • superClassName()


QMetaProperty Class

QMetaProperty Class Reference

The QMetaProperty class stores meta data about a property. More...

#include <qmetaobject.h>

List of all member functions.

Public Members

  • const char * type () const
  • const char * name () const
  • bool writable () const
  • bool isSetType () const
  • bool isEnumType () const
  • QStrList enumKeys () const
  • int keyToValue ( const char * key ) const
  • const char * valueToKey ( int value ) const
  • int keysToValue ( const QStrList & keys ) const
  • QStrList valueToKeys ( int value ) const
  • bool designable ( QObject * o ) const
  • bool scriptable ( QObject * o ) const
  • bool stored ( QObject * o ) const
  • bool reset ( QObject * o ) const

Detailed Description

The QMetaProperty class stores meta data about a property.

Property meta data includes type(), name(), and whether a property is writable(), designable() and stored().

The functions isSetType(), isEnumType() and enumKeys() provide further information about a property's type. The conversion functions keyToValue(), valueToKey(), keysToValue() and valueToKeys() allow conversion between the integer representation of an enumeration or set value and its literal representation.

Actual property values are set and received through QObject's set and get functions. See QObject::setProperty() and QObject::property() for details.

You receive meta property data through an object's meta object. See QMetaObject::property() and QMetaObject::propertyNames() for details.

See also Object Model.

Member Function Documentation

bool QMetaProperty::designable ( QObject * o ) const

Returns TRUE if the property is designable for object o; otherwise returns FALSE.

QStrList QMetaProperty::enumKeys () const

Returns the possible enumeration keys if this property is an enumeration type (or a set type).

See also isEnumType().

bool QMetaProperty::isEnumType () const

Returns TRUE if the property's type is an enumeration value; otherwise returns FALSE.

See also isSetType() and enumKeys().

bool QMetaProperty::isSetType () const

Returns TRUE if the property's type is an enumeration value that is used as set, i.e. if the enumeration values can be OR-ed together; otherwise returns FALSE. A set type is implicitly also an enum type.

See also isEnumType() and enumKeys().

int QMetaProperty::keyToValue ( const char * key ) const

Converts the enumeration key key to its integer value.

For set types, use keysToValue().

See also valueToKey(), isSetType() and keysToValue().

int QMetaProperty::keysToValue ( const QStrList & keys ) const

Converts the list of keys keys to their combined (OR-ed) integer value.

See also isSetType() and valueToKey().

const char * QMetaProperty::name () const

Returns the name of the property.

bool QMetaProperty::reset ( QObject * o ) const

Tries to reset the property for object o with a reset method. On success, returns TRUE; otherwise returns FALSE.

Reset methods are optional, usually only a few properties support them.

bool QMetaProperty::scriptable ( QObject * o ) const

Returns TRUE if the property is scriptable for object o; otherwise returns FALSE.

bool QMetaProperty::stored ( QObject * o ) const

Returns TRUE if the property shall be stored for object o; otherwise returns FALSE.

const char * QMetaProperty::type () const

Returns the type of the property.

const char * QMetaProperty::valueToKey ( int value ) const

Converts the enumeration value value to its literal key.

For set types, use valueToKeys().

See also isSetType() and valueToKeys().

QStrList QMetaProperty::valueToKeys ( int value ) const

Converts the set value value to a list of keys.

See also isSetType() and valueToKey().

bool QMetaProperty::writable () const

Returns TRUE if the property is writable; otherwise returns FALSE.

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


QMetaProperty Member List

Complete Member List for QMetaProperty

This is the complete list of member functions for QMetaProperty, including inherited members.

  • designable()
  • enumKeys()
  • isEnumType()
  • isSetType()
  • keyToValue()
  • keysToValue()
  • name()
  • reset()
  • scriptable()
  • stored()
  • type()
  • valueToKey()
  • valueToKeys()
  • writable()


qmime.h Include File

qmime.h

This is the verbatim text of the qmime.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmime.h   3.0.5   edited Oct 12 2001 $
**
** Definition of mime classes
**
** Created : 981204
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMIME_H
#define QMIME_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qmap.h"
#endif // QT_H

#ifndef QT_NO_MIME

class QImageDrag;
class QTextDrag;

class Q_EXPORT QMimeSource
{
    friend class QClipboardData;

public:
    QMimeSource();
    virtual ~QMimeSource();
    virtual const char* format( int n = 0 ) const = 0;
    virtual bool provides( const char* ) const;
    virtual QByteArray encodedData( const char* ) const = 0;
    int serialNumber() const;

private:
    int ser_no;
    enum { NoCache, Text, Graphics } cacheType;
    union
    {
    struct
    {
        QString *str;
        QCString *subtype;
    } txt;
    struct
    {
        QImage *img;
        QPixmap *pix;
    } gfx;
    } cache;
    void clearCache();

    // friends for caching
    friend class QImageDrag;
    friend class QTextDrag;

};

inline int QMimeSource::serialNumber() const
{ return ser_no; }

class QStringList;
class QMimeSourceFactoryData;

class Q_EXPORT QMimeSourceFactory {
public:
    QMimeSourceFactory();
    virtual ~QMimeSourceFactory();

    static QMimeSourceFactory* defaultFactory();
    static void setDefaultFactory( QMimeSourceFactory* );
    static QMimeSourceFactory* takeDefaultFactory();
    static void addFactory( QMimeSourceFactory *f );
    static void removeFactory( QMimeSourceFactory *f );

    virtual const QMimeSource* data(const QString& abs_name) const;
    virtual QString makeAbsolute(const QString& abs_or_rel_name, const QString& context) const;
    const QMimeSource* data(const QString& abs_or_rel_name, const QString& context) const;

    virtual void setText( const QString& abs_name, const QString& text );
    virtual void setImage( const QString& abs_name, const QImage& im );
    virtual void setPixmap( const QString& abs_name, const QPixmap& pm );
    virtual void setData( const QString& abs_name, QMimeSource* data );
    virtual void setFilePath( const QStringList& );
    virtual QStringList filePath() const;
    void addFilePath( const QString& );
    virtual void setExtensionType( const QString& ext, const char* mimetype );

private:
    QMimeSource *dataInternal(const QString& abs_name, const QMap<QString, QString> &extensions ) const;
    QMimeSourceFactoryData* d;
};

#ifdef Q_WS_WIN

#ifndef QT_H
#include "qptrlist.h" // down here for GCC 2.7.* compatibility
#endif // QT_H

/*
  Encapsulation of conversion between MIME and Windows CLIPFORMAT.
  Not need on X11, as the underlying protocol uses the MIME standard
  directly.
*/

class Q_EXPORT QWindowsMime {
public:
    QWindowsMime();
    virtual ~QWindowsMime();

    static void initialize();

    static QPtrList<QWindowsMime> all();
    static QWindowsMime* convertor( const char* mime, int cf );
    static const char* cfToMime(int cf);

    static int registerMimeType(const char *mime);

    virtual const char* convertorName()=0;
    virtual int countCf()=0;
    virtual int cf(int index)=0;
    virtual bool canConvert( const char* mime, int cf )=0;
    virtual const char* mimeFor(int cf)=0;
    virtual int cfFor(const char* )=0;
    virtual QByteArray convertToMime( QByteArray data, const char* mime, int cf )=0;
    virtual QByteArray convertFromMime( QByteArray data, const char* mime, int cf )=0;
};

#endif // Q_WS_WIN

#endif // QT_NO_MIME

#endif // QMIME_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMimeSource Class

QMimeSource Class Reference

The QMimeSource class is an abstraction of objects which provide formatted data of a certain MIME type. More...

#include <qmime.h>

Inherited by QDragObject and QDropEvent.

List of all member functions.

Public Members

  • QMimeSource ()
  • virtual ~QMimeSource ()
  • virtual const char * format ( int i = 0 ) const = 0
  • virtual bool provides ( const char * mimeType ) const
  • virtual QByteArray encodedData ( const char * ) const = 0
  • int serialNumber () const

Detailed Description

The QMimeSource class is an abstraction of objects which provide formatted data of a certain MIME type.

Drag-and-drop and clipboard use this abstraction.

See also IANA list of MIME media types, Drag And Drop Classes, Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QMimeSource::QMimeSource ()

Constructs a mime source and assigns a globally unique serial number to it.

See also serialNumber().

QMimeSource::~QMimeSource () [virtual]

Provided to ensure that subclasses destroy themselves correctly.

QByteArray QMimeSource::encodedData ( const char * ) const [pure virtual]

Returns the encoded data of this object in the specified MIME format.

Subclasses must reimplement this function.

Reimplemented in QStoredDrag, QDropEvent and QIconDrag.

const char * QMimeSource::format ( int i = 0 ) const [pure virtual]

Returns the i-th supported MIME format, or 0.

Reimplemented in QDropEvent.

bool QMimeSource::provides ( const char * mimeType ) const [virtual]

Returns TRUE if the object can provide the data in format mimeType; otherwise returns FALSE.

If you inherit from QMimeSource, for consistency reasons it is better to implement the more abstract canDecode() functions such as QTextDrag::canDecode() and QImageDrag::canDecode().

Example: iconview/simple_dd/main.cpp.

Reimplemented in QDropEvent.

int QMimeSource::serialNumber () const

Returns the mime source's globally unique serial number.

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


QMimeSource Member List

Complete Member List for QMimeSource

This is the complete list of member functions for QMimeSource, including inherited members.

  • QMimeSource()
  • ~QMimeSource()
  • encodedData()
  • format()
  • provides()
  • serialNumber()


QMimeSourceFactory Class

QMimeSourceFactory Class Reference

The QMimeSourceFactory class is an extensible provider of mime-typed data. More...

#include <qmime.h>

List of all member functions.

Public Members

  • QMimeSourceFactory ()
  • virtual ~QMimeSourceFactory ()
  • virtual const QMimeSource * data ( const QString & abs_name ) const
  • virtual QString makeAbsolute ( const QString & abs_or_rel_name, const QString & context ) const
  • const QMimeSource * data ( const QString & abs_or_rel_name, const QString & context ) const
  • virtual void setText ( const QString & abs_name, const QString & text )
  • virtual void setImage ( const QString & abs_name, const QImage & image )
  • virtual void setPixmap ( const QString & abs_name, const QPixmap & pixmap )
  • virtual void setData ( const QString & abs_name, QMimeSource * data )
  • virtual void setFilePath ( const QStringList & path )
  • virtual QStringList filePath () const
  • void addFilePath ( const QString & p )
  • virtual void setExtensionType ( const QString & ext, const char * mimetype )

Static Public Members

  • QMimeSourceFactory * defaultFactory ()
  • void setDefaultFactory ( QMimeSourceFactory * factory )
  • QMimeSourceFactory * takeDefaultFactory ()
  • void addFactory ( QMimeSourceFactory * f )
  • void removeFactory ( QMimeSourceFactory * f )

Detailed Description

The QMimeSourceFactory class is an extensible provider of mime-typed data.

A QMimeSourceFactory provides an abstract interface to a collection of information. Each piece of information is represented by a QMimeSource object which can be examined and converted to concrete data types by functions such as QImageDrag::canDecode() and QImageDrag::decode().

The base QMimeSourceFactory can be used in two ways: as an abstraction of a collection of files or as specifically stored data. For it to access files, call setFilePath() before accessing data. For stored data, call setData() for each item (there are also convenience functions, e.g. setText(), setImage() and setPixmap(), that simply call setData() with appropriate parameters).

The rich text widgets, QTextEdit and QTextBrowser, use QMimeSourceFactory to resolve references such as images or links within rich text documents. They either access the default factory (see defaultFactory()) or their own (see QTextEdit::setMimeSourceFactory()). Other classes that are capable of displaying rich text (such as QLabel, QWhatsThis or QMessageBox) always use the default factory.

A factory can also be used as a container to store data associated with a name. This technique is useful whenever rich text contains images that are stored in the program itself, not loaded from the hard disk. Your program may, for example, define some image data as:

    static const char* myimage_data[]={
    "...",
    ...
    "..."};

To be able to use this image within some rich text, for example inside a QLabel, you must create a QImage from the raw data and insert it into the factory with a unique name:

    QMimeSourceFactory::defaultFactory()->setImage( "myimage", QImage(myimage_data) );

Now you can create a rich text QLabel with:

    QLabel* label = new QLabel(
        "Rich text with embedded image:<img source=\"myimage\">"
        "Isn't that <em>cute</em>?" );

See also Environment Classes and Input/Output and Networking.

Member Function Documentation

QMimeSourceFactory::QMimeSourceFactory ()

Constructs a QMimeSourceFactory that has no file path and no stored content.

QMimeSourceFactory::~QMimeSourceFactory () [virtual]

Destroys the QMimeSourceFactory, deleting all stored content.

void QMimeSourceFactory::addFactory ( QMimeSourceFactory * f ) [static]

Adds the QMimeSourceFactory f to the list of available mimesource factories. If the defaultFactory() can't resolve a data() it iterates over the list of installed mimesource factories until the data can be resolved.

See also removeFactory().

void QMimeSourceFactory::addFilePath ( const QString & p )

Adds another search path, p to the existing search paths.

See also setFilePath().

const QMimeSource * QMimeSourceFactory::data ( const QString & abs_name ) const [virtual]

Returns a reference to the data associated with abs_name. The return value remains valid only until the next data() or setData() call, so you should immediately decode the result.

If there is no data associated with abs_name in the factory's store, the factory tries to access the local filesystem. If abs_name isn't an absolute file name, the factory will search for it in all defined paths (see setFilePath()).

The factory understands all the image formats supported by QImageIO. Any other mime types are determined by the file name extension. The default settings are

    setExtensionType("html", "text/html;charset=iso8859-1");
    setExtensionType("htm", "text/html;charset=iso8859-1");
    setExtensionType("txt", "text/plain");
    setExtensionType("xml", "text/xml;charset=UTF-8");
The effect of these is that file names ending in "html" or "htm" will be treated as text encoded in the iso8859-1 encoding, those ending in "txt" will be treated as text encoded in the local encoding; those ending in "xml" will be treated as text encoded in Unicode UTF-8 encoding. The text subtype ("html", "plain", or "xml") does not affect the factory, but users of the factory may behave differently. We recommend creating "xml" files where practical. These files can be viewed regardless of the runtime encoding and can encode any Unicode characters without resorting to encoding definitions inside the file.

Any file data that is not recognized will be retrieved as a QMimeSource providing the "application/octet-stream" mime type, meaning uninterpreted binary data.

You can add further extensions or change existing ones with subsequent calls to setExtensionType(). If the extension mechanism is not sufficient for your problem domain, you can inherit QMimeSourceFactory and reimplement this function to perform some more specialized mime-type detection. The same applies if you want to use the mime source factory to access URL referenced data over a network.

const QMimeSource * QMimeSourceFactory::data ( const QString & abs_or_rel_name, const QString & context ) const

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

A convenience function. See data(const QString& abs_name). The file name is given in abs_or_rel_name and the path is in context.

QMimeSourceFactory * QMimeSourceFactory::defaultFactory () [static]

Returns the application-wide default mime source factory. This factory is used by rich text rendering classes such as QSimpleRichText, QWhatsThis and QMessageBox to resolve named references within rich text documents. It serves also as the initial factory for the more complex render widgets, QTextEdit and QTextBrowser.

See also setDefaultFactory().

Examples: action/application.cpp and application/application.cpp.

QStringList QMimeSourceFactory::filePath () const [virtual]

Returns the currently set search paths.

QString QMimeSourceFactory::makeAbsolute ( const QString & abs_or_rel_name, const QString & context ) const [virtual]

Converts the absolute or relative data item name abs_or_rel_name to an absolute name, interpreted within the context (path) of the data item named context (this must be an absolute name).

void QMimeSourceFactory::removeFactory ( QMimeSourceFactory * f ) [static]

Removes the mimesource factory f from the list of available mimesource factories.

See also addFactory().

void QMimeSourceFactory::setData ( const QString & abs_name, QMimeSource * data ) [virtual]

Sets data to be the data item associated with the absolute name abs_name.

The ownership of data is transferred to the factory: do not delete or access the pointer after passing it to this function.

void QMimeSourceFactory::setDefaultFactory ( QMimeSourceFactory * factory ) [static]

Sets the default factory, destroying any previously set mime source provider. The ownership of the factory is transferred to Qt.

See also defaultFactory().

void QMimeSourceFactory::setExtensionType ( const QString & ext, const char * mimetype ) [virtual]

Sets the mime-type to be associated with the file name extension, ext to mimetype. This determines the mime-type for files found via the paths set by setFilePath().

void QMimeSourceFactory::setFilePath ( const QStringList & path ) [virtual]

Sets the list of directories that will be searched when named data is requested to the those given in the string list path.

See also filePath().

void QMimeSourceFactory::setImage ( const QString & abs_name, const QImage & image ) [virtual]

Sets image to be the data item associated with the absolute name abs_name.

Equivalent to setData(abs_name, new QImageDrag(image)).

void QMimeSourceFactory::setPixmap ( const QString & abs_name, const QPixmap & pixmap ) [virtual]

Sets pixmap to be the data item associated with the absolute name abs_name.

void QMimeSourceFactory::setText ( const QString & abs_name, const QString & text ) [virtual]

Sets text to be the data item associated with the absolute name abs_name.

Equivalent to setData(abs_name, new QTextDrag(text)).

QMimeSourceFactory * QMimeSourceFactory::takeDefaultFactory () [static]

Sets the defaultFactory() to 0 and returns the previous one.

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


QMimeSourceFactory Member List

Complete Member List for QMimeSourceFactory

This is the complete list of member functions for QMimeSourceFactory, including inherited members.

  • QMimeSourceFactory()
  • ~QMimeSourceFactory()
  • addFactory()
  • addFilePath()
  • data()
  • defaultFactory()
  • filePath()
  • makeAbsolute()
  • removeFactory()
  • setData()
  • setDefaultFactory()
  • setExtensionType()
  • setFilePath()
  • setImage()
  • setPixmap()
  • setText()
  • takeDefaultFactory()


QMotifPlusStyle Class

QMotifPlusStyle Class Reference

The QMotifPlusStyle class provides a more sophisticated Motif-ish look and feel. More...

#include <qmotifplusstyle.h>

Inherits QMotifStyle.

List of all member functions.

Public Members

  • QMotifPlusStyle ( bool hoveringHighlight = TRUE )

Detailed Description

The QMotifPlusStyle class provides a more sophisticated Motif-ish look and feel.

This class implements a Motif-ish look and feel with more sophisticated bevelling as used by the GIMP Toolkit (GTK+) for Unix/X11.

See also Widget Appearance and Style.

Member Function Documentation

QMotifPlusStyle::QMotifPlusStyle ( bool hoveringHighlight = TRUE )

Constructs a QMotifPlusStyle

If hoveringHighlight is TRUE (the default), then the style will not highlight push buttons, checkboxes, radiobuttons, comboboxes, scrollbars or sliders.

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


qmotifplusstyle.h Include File

qmotifplusstyle.h

This is the verbatim text of the qmotifplusstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmotifplusstyle.h   3.0.5   edited May 27 22:19 $
**
** Definition of QMotifPlusStyle class
**
** Created : 2000.07.27
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMOTIFPLUSSTYLE_H
#define QMOTIFPLUSSTYLE_H

#ifndef QT_H
#include "qmotifstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE_MOTIFPLUS

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_MOTIFPLUS
#else
#define Q_EXPORT_STYLE_MOTIFPLUS Q_EXPORT
#endif

class Q_EXPORT_STYLE_MOTIFPLUS QMotifPlusStyle : public QMotifStyle
{
    Q_OBJECT

public:
    QMotifPlusStyle(bool hoveringHighlight = TRUE);
    virtual ~QMotifPlusStyle();

    void polish(QPalette &pal);
    void polish(QWidget *widget);
    void unPolish(QWidget*widget);

    void polish(QApplication *app);
    void unPolish(QApplication *app);

    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    QRect subRect(SubRect r, const QWidget *widget) const;

    void drawComplexControl(ComplexControl control,
                QPainter *p,
                const QWidget *widget,
                const QRect &r,
                const QColorGroup &cg,
                SFlags how = Style_Default,
                SCFlags controls = SC_All,
                SCFlags active = SC_None,
                const QStyleOption& = QStyleOption::Default ) const;

    QRect querySubControlMetrics(ComplexControl control,
                 const QWidget *widget,
                 SubControl subcontrol,
                 const QStyleOption& = QStyleOption::Default) const;

    int pixelMetric(PixelMetric metric, const QWidget *widget = 0) const;

    int styleHint(StyleHint sh, const QWidget *, const QStyleOption & = QStyleOption::Default,
          QStyleHintReturn* = 0) const;

protected:
    bool eventFilter(QObject *, QEvent *);

private:
    bool useHoveringHighlight;
};

#endif // QT_NO_STYLE_MOTIFPLUS

#endif // QMOTIFPLUSSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMotifPlusStyle Member List

Complete Member List for QMotifPlusStyle

This is the complete list of member functions for QMotifPlusStyle, including inherited members.

  • QMotifPlusStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • setUseHighlightColors()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • useHighlightColors()
  • visualRect()


QMotifStyle Class

QMotifStyle Class Reference

The QMotifStyle class provides Motif look and feel. More...

#include <qmotifstyle.h>

Inherits QCommonStyle.

Inherited by QCDEStyle, QMotifPlusStyle and QSGIStyle.

List of all member functions.

Public Members

  • QMotifStyle ( bool useHighlightCols = FALSE )
  • void setUseHighlightColors ( bool arg )
  • bool useHighlightColors () const

Detailed Description

The QMotifStyle class provides Motif look and feel.

This class implements the Motif look and feel. It closely resembles the original Motif look as defined by the Open Group, with the addition of some minor improvements. The Motif style is Qt's default GUI style on UNIX platforms.

See also Widget Appearance and Style.

Member Function Documentation

QMotifStyle::QMotifStyle ( bool useHighlightCols = FALSE )

Constructs a QMotifStyle.

If useHighlightCols is FALSE (the default), the style will polish the application's color palette to emulate the Motif way of highlighting, which is a simple inversion between the base and the text color.

void QMotifStyle::setUseHighlightColors ( bool arg )

If arg is FALSE, the style will polish the application's color palette to emulate the Motif way of highlighting, which is a simple inversion between the base and the text color.

The effect will show up the next time an application palette is set via QApplication::setPalette(). The current color palette of the application remains unchanged.

See also QStyle::polish().

bool QMotifStyle::useHighlightColors () const

Returns TRUE if the style treats the highlight colors of the palette in a Motif-like manner, which is a simple inversion between the base and the text color; otherwise returns FALSE. The default is FALSE.

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


qmotifstyle.h Include File

qmotifstyle.h

This is the verbatim text of the qmotifstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmotifstyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Motif-like style class
**
** Created : 981231
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMOTIFSTYLE_H
#define QMOTIFSTYLE_H

#ifndef QT_H
#include "qcommonstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE_MOTIF

class QPalette;

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_MOTIF
#else
#define Q_EXPORT_STYLE_MOTIF Q_EXPORT
#endif

class Q_EXPORT_STYLE_MOTIF QMotifStyle : public QCommonStyle
{
    Q_OBJECT
public:
    QMotifStyle( bool useHighlightCols=FALSE );
    virtual ~QMotifStyle();

    void setUseHighlightColors( bool );
    bool useHighlightColors() const;

    void polish( QPalette& );
    void polish( QWidget* );
    void polish( QApplication* );

    void polishPopupMenu( QPopupMenu* );

    // new style API
    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl control,
                 QPainter *p,
                 const QWidget* widget,
                 const QRect& r,
                 const QColorGroup& cg,
                 SFlags how = Style_Default,
                 SCFlags sub = SC_All,
                 SCFlags subActive = SC_None,
                 const QStyleOption& = QStyleOption::Default ) const;

    QRect querySubControlMetrics( ComplexControl control,
                  const QWidget *widget,
                  SubControl sc,
                  const QStyleOption& = QStyleOption::Default ) const;

    int pixelMetric( PixelMetric metric, const QWidget *widget = 0 ) const;

    QSize sizeFromContents( ContentsType contents,
                const QWidget *widget,
                const QSize &contentsSize,
                const QStyleOption& = QStyleOption::Default ) const;

    QRect subRect( SubRect r, const QWidget *widget ) const;

    QPixmap stylePixmap(StylePixmap, const QWidget * = 0, const QStyleOption& = QStyleOption::Default) const;

    int styleHint(StyleHint sh, const QWidget *, const QStyleOption & = QStyleOption::Default,
          QStyleHintReturn* = 0) const;

private:
    bool highlightCols;

    // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMotifStyle( const QMotifStyle & );
    QMotifStyle& operator=( const QMotifStyle & );
#endif
};

#endif // QT_NO_STYLE_MOTIF

#endif // QMOTIFSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMotifStyle Member List

Complete Member List for QMotifStyle

This is the complete list of member functions for QMotifStyle, including inherited members.

  • QMotifStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • setUseHighlightColors()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • useHighlightColors()
  • visualRect()


QMouseEvent Class

QMouseEvent Class Reference

The QMouseEvent class contains parameters that describe a mouse event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QMouseEvent ( Type type, const QPoint & pos, int button, int state )
  • QMouseEvent ( Type type, const QPoint & pos, const QPoint & globalPos, int button, int state )
  • const QPoint & pos () const
  • const QPoint & globalPos () const
  • int x () const
  • int y () const
  • int globalX () const
  • int globalY () const
  • ButtonState button () const
  • ButtonState state () const
  • ButtonState stateAfter () const
  • bool isAccepted () const
  • void accept ()
  • void ignore ()

Detailed Description

The QMouseEvent class contains parameters that describe a mouse event.

Mouse events occur when a mouse button is pressed or released inside a widget or when the mouse cursor is moved.

Mouse move events will occur only when a mouse button is pressed down, unless mouse tracking has been enabled with QWidget::setMouseTracking().

Qt automatically grabs the mouse when a mouse button is pressed inside a widget; the widget will continue to receive mouse events until the last mouse button is released.

A mouse event contains a special accept flag that indicates whether the receiver wants the event. You should call QMouseEvent::ignore() if the mouse event is not handled by your widget. A mouse event is propagated up the parent widget chain until a widget accepts it with QMouseEvent::accept() or an event filter consumes it.

The functions pos(), x() and y() give the cursor position relative to the widget that receives the mouse event. If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.

The QWidget::setEnabled() function can be used to enable or disable mouse and keyboard events for a widget.

 The event handlers QWidget::mousePressEvent(),
QWidget::mouseReleaseEvent(), QWidget::mouseDoubleClickEvent() and
QWidget::mouseMoveEvent() receive mouse events.

See also QWidget::mouseTracking, QWidget::grabMouse(), QCursor::pos() and Event Classes.

Member Function Documentation

QMouseEvent::QMouseEvent ( Type type, const QPoint & pos, int button, int state )

Constructs a mouse event object.

The type parameter must be one of QEvent::MouseButtonPress, QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick or QEvent::MouseMove.

The pos parameter specifies the position relative to the receiving widget. button specifies the button that caused the event, which should be Qt::NoButton (0), if type is MouseMove. state is the ButtonState at the time of the event.

The globalPos() is initialized to QCursor::pos(), which may not be appropriate. Use the other constructor to specify the global position explicitly.

QMouseEvent::QMouseEvent ( Type type, const QPoint & pos, const QPoint & globalPos, int button, int state )

Constructs a mouse event object.

The type parameter must be QEvent::MouseButtonPress, QEvent::MouseButtonRelease, QEvent::MouseButtonDblClick or QEvent::MouseMove.

The pos parameter specifies the position relative to the receiving widget. globalPos is the position in absolute coordinates. button specifies the button that caused the event, which should be Qt::NoButton (0), if type is MouseMove. state is the ButtonState at the time of the event.

void QMouseEvent::accept ()

Sets the accept flag of the mouse event object.

Setting the accept parameter indicates that the receiver of the event wants the mouse event. Unwanted mouse events are sent to the parent widget.

The accept flag is set by default.

See also ignore().

ButtonState QMouseEvent::button () const

Returns the button that caused the event.

Possible return values are LeftButton, RightButton, MidButton and NoButton.

Note that the returned value is always NoButton for mouse move events.

See also state() and Qt::ButtonState.

Examples: dclock/dclock.cpp, life/life.cpp and t14/cannon.cpp.

const QPoint & QMouseEvent::globalPos () const

Returns the global position of the mouse pointer at the time of the event. This is important on asynchronous window systems like X11. Whenever you move your widgets around in response to mouse events, globalPos() may differ a lot from the current pointer position QCursor::pos(), and from QWidget::mapToGlobal( pos() ).

See also globalX() and globalY().

Example: aclock/aclock.cpp.

int QMouseEvent::globalX () const

Returns the global x-position of the mouse pointer at the time of the event.

See also globalY() and globalPos().

int QMouseEvent::globalY () const

Returns the global y-position of the mouse pointer at the time of the event.

See also globalX() and globalPos().

void QMouseEvent::ignore ()

Clears the accept flag parameter of the mouse event object.

Clearing the accept parameter indicates that the event receiver does not want the mouse event. Unwanted mouse events are sent to the parent widget.

The accept flag is set by default.

See also accept().

bool QMouseEvent::isAccepted () const

Returns TRUE if the receiver of the event wants to keep the key; otherwise returns FALSE.

const QPoint & QMouseEvent::pos () const

Returns the position of the mouse pointer relative to the widget that received the event.

If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.

See also x(), y() and globalPos().

Examples: chart/canvasview.cpp, drawlines/connect.cpp, life/life.cpp, popup/popup.cpp, qmag/qmag.cpp, t14/cannon.cpp and tooltip/tooltip.cpp.

ButtonState QMouseEvent::state () const

Returns the button state (a combination of mouse buttons and keyboard modifiers), i.e. what buttons and keys were being pressed immediately before the event was generated.

Note that this means that for QEvent::MouseButtonPress and QEvent::MouseButtonDblClick, the flag for the button() itself will not be set in the state, whereas for QEvent::MouseButtonRelease it will.

This value is mainly interesting for QEvent::MouseMove; for the other cases, button() is more useful.

The returned value is LeftButton, RightButton, MidButton, ShiftButton, ControlButton and AltButton OR'ed together.

See also button(), stateAfter() and Qt::ButtonState.

Examples: popup/popup.cpp and showimg/showimg.cpp.

ButtonState QMouseEvent::stateAfter () const

Returns the state of buttons after the event.

See also state() and Qt::ButtonState.

int QMouseEvent::x () const

Returns the x-position of the mouse pointer, relative to the widget that received the event.

See also y() and pos().

Example: showimg/showimg.cpp.

int QMouseEvent::y () const

Returns the y-position of the mouse pointer, relative to the widget that received the event.

See also x() and pos().

Example: showimg/showimg.cpp.

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


QMouseEvent Member List

Complete Member List for QMouseEvent

This is the complete list of member functions for QMouseEvent, including inherited members.

  • QMouseEvent()
  • accept()
  • button()
  • globalPos()
  • globalX()
  • globalY()
  • ignore()
  • isAccepted()
  • pos()
  • spontaneous()
  • state()
  • stateAfter()
  • type()
  • x()
  • y()


QMoveEvent Class

QMoveEvent Class Reference

The QMoveEvent class contains event parameters for move events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QMoveEvent ( const QPoint & pos, const QPoint & oldPos )
  • const QPoint & pos () const
  • const QPoint & oldPos () const

Detailed Description

The QMoveEvent class contains event parameters for move events.

Move events are sent to widgets that have been moved to a new position relative to their parent.

The event handler QWidget::moveEvent() receives move events.

See also QWidget::pos, QWidget::geometry and Event Classes.

Member Function Documentation

QMoveEvent::QMoveEvent ( const QPoint & pos, const QPoint & oldPos )

Constructs a move event with the new and old widget positions, pos and oldPos respectively.

const QPoint & QMoveEvent::oldPos () const

Returns the old position of the widget.

const QPoint & QMoveEvent::pos () const

Returns the new position of the widget. This excludes the window frame for top level widgets.

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


QMoveEvent Member List

Complete Member List for QMoveEvent

This is the complete list of member functions for QMoveEvent, including inherited members.

  • QMoveEvent()
  • oldPos()
  • pos()
  • spontaneous()
  • type()


QMovie Class

QMovie Class Reference

The QMovie class provides incremental loading of animations or images, signalling as it progresses. More...

#include <qmovie.h>

List of all member functions.

Public Members

  • QMovie ()
  • QMovie ( int bufsize )
  • QMovie ( QDataSource * src, int bufsize = 1024 )
  • QMovie ( const QString & fileName, int bufsize = 1024 )
  • QMovie ( QByteArray data, int bufsize = 1024 )
  • QMovie ( const QMovie & movie )
  • ~QMovie ()
  • QMovie & operator= ( const QMovie & movie )
  • int pushSpace () const
  • void pushData ( const uchar * data, int length )
  • const QColor & backgroundColor () const
  • void setBackgroundColor ( const QColor & c )
  • const QRect & getValidRect () const
  • const QPixmap & framePixmap () const
  • const QImage & frameImage () const
  • bool isNull () const
  • int frameNumber () const
  • int steps () const
  • bool paused () const
  • bool finished () const
  • bool running () const
  • void unpause ()
  • void pause ()
  • void step ()
  • void step ( int steps )
  • void restart ()
  • int speed () const
  • void setSpeed ( int percent )
  • void connectResize ( QObject * receiver, const char * member )
  • void disconnectResize ( QObject * receiver, const char * member = 0 )
  • void connectUpdate ( QObject * receiver, const char * member )
  • void disconnectUpdate ( QObject * receiver, const char * member = 0 )
  • enum Status { SourceEmpty = -2, UnrecognizedFormat = -1, Paused = 1, EndOfFrame = 2, EndOfLoop = 3, EndOfMovie = 4, SpeedChanged = 5 }
  • void connectStatus ( QObject * receiver, const char * member )
  • void disconnectStatus ( QObject * receiver, const char * member = 0 )

Detailed Description

The QMovie class provides incremental loading of animations or images, signalling as it progresses.

The simplest way to display a QMovie is to use a QLabel and QLabel::setMovie().

A QMovie provides a QPixmap as the framePixmap(); connections can be made via connectResize() and connectUpdate() to receive notification of size and pixmap changes. All decoding is driven by the normal event-processing mechanisms.

The movie begins playing as soon as the QMovie is created (actually, once control returns to the event loop). When the last frame in the movie has been played, it may loop back to the start if such looping is defined in the input source.

QMovie objects are explicitly shared. This means that a QMovie copied from another QMovie will be displaying the same frame at all times. If one shared movie pauses, all pause. To make independent movies, they must be constructed separately.

The set of data formats supported by QMovie is determined by the decoder factories that have been installed; the format of the input is determined as the input is decoded.

The supported formats are MNG (if Qt is configured with MNG support enabled) and GIF (if Qt is configured with GIF support enabled, see qgif.h).

If Qt is configured to support GIF reading, we are required to state that "The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated.

Warning: If you are in a country that recognizes software patents and in which Unisys holds a patent on LZW compression and/or decompression and you want to use GIF, Unisys may require you to license that technology. Such countries include Canada, Japan, the USA, France, Germany, Italy and the UK.

GIF support may be removed completely in a future version of Qt. We recommend using the MNG or PNG format.

See also QLabel::setMovie(), Graphics Classes, Image Processing Classes and Multimedia Classes.

Member Type Documentation

QMovie::Status

  • QMovie::SourceEmpty
  • QMovie::UnrecognizedFormat
  • QMovie::Paused
  • QMovie::EndOfFrame
  • QMovie::EndOfLoop
  • QMovie::EndOfMovie
  • QMovie::SpeedChanged

Member Function Documentation

QMovie::QMovie ()

Constructs a null QMovie. The only interesting thing to do with such a movie is to assign another movie to it.

See also isNull().

QMovie::QMovie ( int bufsize )

Constructs a QMovie with an external data source. You should later call pushData() to send incoming animation data to the movie.

The bufsize argument sets the maximum amount of data the movie will transfer from the data source per event loop. The lower this value, the better interleaved the movie playback will be with other event processing, but the slower the overall processing will be.

See also pushData().

QMovie::QMovie ( QDataSource * src, int bufsize = 1024 )

Constructs a QMovie that reads an image sequence from the given data source, src. The source must be allocated dynamically, because QMovie will take ownership of it and will destroy it when the movie is destroyed. The movie starts playing as soon as event processing continues.

The bufsize argument sets the maximum amount of data the movie will transfer from the data source per event loop. The lower this value, the better interleaved the movie playback will be with other event processing, but the slower the overall processing will be.

QMovie::QMovie ( const QString & fileName, int bufsize = 1024 )

Constructs a QMovie that reads an image sequence from the file, fileName.

The bufsize argument sets the maximum amount of data the movie will transfer from the data source per event loop. The lower this value, the better interleaved the movie playback will be with other event processing, but the slower the overall processing will be.

QMovie::QMovie ( QByteArray data, int bufsize = 1024 )

Constructs a QMovie that reads an image sequence from the byte array, data.

The bufsize argument sets the maximum amount of data the movie will transfer from the data source per event loop. The lower this value, the better interleaved the movie playback will be with other event processing, but the slower the overall processing will be.

QMovie::QMovie ( const QMovie & movie )

Constructs a movie that uses the same data as movie movie. QMovies use explicit sharing, so operations on the copy will affect both.

QMovie::~QMovie ()

Destroys the QMovie. If this is the last reference to the data of the movie, the data is deallocated.

const QColor & QMovie::backgroundColor () const

Returns the background color of the movie set by setBackgroundColor().

void QMovie::connectResize ( QObject * receiver, const char * member )

Connects the receiver's member of type void member(const QSize&) so that it is signalled when the movie changes size.

Note that due to the explicit sharing of QMovie objects, these connections persist until they are explicitly disconnected with disconnectResize() or until every shared copy of the movie is deleted.

Example: movies/main.cpp.

void QMovie::connectStatus ( QObject * receiver, const char * member )

Connects the receiver's member, of type void member(int) so that it is signalled when the movie changes status. The status codes are negative for errors and positive for information.

Status Code | Meaning
QMovie::SourceEmpty | signalled if the input cannot be read.
QMovie::UnrecognizedFormat | signalled if the input data is unrecognized.
QMovie::Paused | signalled when the movie is paused by a call to paused() or by after stepping pauses.
QMovie::EndOfFrame | signalled at end-of-frame after any update and Paused signals.
QMovie::EndOfLoop | signalled at end-of-loop, after any update signals, EndOfFrame - but before EndOfMovie.
QMovie::EndOfMovie | signalled when the movie completes and is not about to loop.

More status messages may be added in the future, so a general test for errors would test for negative.

Note that due to the explicit sharing of QMovie objects, these connections persist until they are explicitly disconnected with disconnectStatus() or until every shared copy of the movie is deleted.

Example: movies/main.cpp.

void QMovie::connectUpdate ( QObject * receiver, const char * member )

Connects the receiver's member of type void member(const QRect&) so that it is signalled when an area of the framePixmap() has changed since the previous frame.

Note that due to the explicit sharing of QMovie objects, these connections persist until they are explicitly disconnected with disconnectUpdate() or until every shared copy of the movie is deleted.

Example: movies/main.cpp.

void QMovie::disconnectResize ( QObject * receiver, const char * member = 0 )

Disconnects the receiver's member (or all members if member is zero) that were previously connected by connectResize().

void QMovie::disconnectStatus ( QObject * receiver, const char * member = 0 )

Disconnects the receiver's member (or all members if member is zero) that were previously connected by connectStatus().

void QMovie::disconnectUpdate ( QObject * receiver, const char * member = 0 )

Disconnects the receiver's member (or all members if \q member is zero) that were previously connected by connectUpdate().

bool QMovie::finished () const

Returns TRUE if the image is no longer playing: this happens when all loops of all frames are complete; otherwise returns FALSE.

Example: movies/main.cpp.

const QImage & QMovie::frameImage () const

Returns the current frame of the movie, as a QImage. It is not generally useful to keep a copy of this image. Also note that you must not call this function if the movie is finished(), since by then the image will not be available.

See also framePixmap().

int QMovie::frameNumber () const

Returns the number of times EndOfFrame has been emitted since the start of the current loop of the movie. Thus, before any EndOfFrame has been emitted the value will be 0; within slots processing the first signal, frameNumber() will be 1, and so on.

const QPixmap & QMovie::framePixmap () const

Returns the current frame of the movie, as a QPixmap. It is not generally useful to keep a copy of this pixmap. It is better to keep a copy of the QMovie and get the framePixmap() only when needed for drawing.

See also frameImage().

Example: movies/main.cpp.

const QRect & QMovie::getValidRect () const

Returns the area of the pixmap for which pixels have been generated.

bool QMovie::isNull () const

Returns TRUE if the movie is null; otherwise returns FALSE.

QMovie & QMovie::operator= ( const QMovie & movie )

Makes this movie use the same data as movie movie. QMovies use explicit sharing.

void QMovie::pause ()

Pauses the progress of the animation.

See also unpause().

Example: movies/main.cpp.

bool QMovie::paused () const

Returns TRUE if the image is paused; otherwise returns FALSE.

Example: movies/main.cpp.

void QMovie::pushData ( const uchar * data, int length )

Pushes length bytes from data into the movie. length must be no more than the amount returned by pushSpace() since the previous call to pushData().

int QMovie::pushSpace () const

Returns the maximum amount of data that can currently be pushed into the movie by a call to pushData(). This is affected by the initial buffer size, but varies as the movie plays and data is consumed.

void QMovie::restart ()

Rewinds the movie to the beginning. If the movie has not been paused, it begins playing again.

Example: movies/main.cpp.

bool QMovie::running () const

Returns TRUE if the image is not single-stepping, not paused, and not finished; otherwise returns FALSE.

void QMovie::setBackgroundColor ( const QColor & c )

Sets the background color of the pixmap to c. If the background color isValid(), the pixmap will never have a mask because the background color will be used in transparent regions of the image.

See also backgroundColor().

void QMovie::setSpeed ( int percent )

Sets the movie's play speed as a percentage, to percent. This is a percentage of the speed dictated by the input data format. The default is 100 percent.

int QMovie::speed () const

Returns the movie's play speed as a percentage. The default is 100 percent.

See also setSpeed().

void QMovie::step ()

Steps forward 1 frame and then pauses.

Example: movies/main.cpp.

void QMovie::step ( int steps )

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

Steps forward, showing steps frames, and then pauses.

int QMovie::steps () const

Returns the number of steps remaining after a call to step(). If the movie is paused, steps() returns 0. If it's running normally or is finished, steps() returns a negative number.

Example: movies/main.cpp.

void QMovie::unpause ()

Unpauses the progress of the animation.

See also pause().

Example: movies/main.cpp.

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


qmovie.h Include File

qmovie.h

This is the verbatim text of the qmovie.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qmovie.h   3.0.5   edited Oct 12 2001 $
**
** Definition of movie classes
**
** Created : 970617
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMOVIE_H
#define QMOVIE_H

#ifndef QT_H
#include "qpixmap.h" // ### remove or keep for users' convenience?
#endif // QT_H

#ifndef QT_NO_MOVIE

class QDataSource;
class QObject;
class QMoviePrivate;

class Q_EXPORT QMovie {
public:
    QMovie();
    QMovie(int bufsize);
    QMovie(QDataSource*, int bufsize=1024);
    QMovie(const QString &fileName, int bufsize=1024);
    QMovie(QByteArray data, int bufsize=1024);
    QMovie(const QMovie&);
    ~QMovie();

    QMovie& operator=(const QMovie&);

    int pushSpace() const;
    void pushData(const uchar* data, int length);

    const QColor& backgroundColor() const;
    void setBackgroundColor(const QColor&);

    const QRect& getValidRect() const;
    const QPixmap& framePixmap() const;
    const QImage& frameImage() const;

    bool isNull() const;

    int  frameNumber() const;
    int  steps() const;
    bool paused() const;
    bool finished() const;
    bool running() const;

    void unpause();
    void pause();
    void step();
    void step(int);
    void restart();

    int  speed() const;
    void setSpeed(int);

    void connectResize(QObject* receiver, const char *member);
    void disconnectResize(QObject* receiver, const char *member=0);

    void connectUpdate(QObject* receiver, const char *member);
    void disconnectUpdate(QObject* receiver, const char *member=0);

#ifdef Q_WS_QWS
    // Temporary hack
    void setDisplayWidget(QWidget * w);
#endif

    enum Status { SourceEmpty=-2,
          UnrecognizedFormat=-1,
          Paused=1,
          EndOfFrame=2,
          EndOfLoop=3,
          EndOfMovie=4,
          SpeedChanged=5 };
    void connectStatus(QObject* receiver, const char *member);
    void disconnectStatus(QObject* receiver, const char *member=0);

private:
    QMoviePrivate *d;
};

#endif	// QT_NO_MOVIE

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMovie Member List

Complete Member List for QMovie

This is the complete list of member functions for QMovie, including inherited members.

  • QMovie()
  • ~QMovie()
  • backgroundColor()
  • connectResize()
  • connectStatus()
  • connectUpdate()
  • disconnectResize()
  • disconnectStatus()
  • disconnectUpdate()
  • finished()
  • frameImage()
  • frameNumber()
  • framePixmap()
  • getValidRect()
  • isNull()
  • operator=()
  • pause()
  • paused()
  • pushData()
  • pushSpace()
  • restart()
  • running()
  • setBackgroundColor()
  • setSpeed()
  • speed()
  • step()
  • steps()
  • unpause()


QMultiLineEdit Class

QMultiLineEdit Class Reference
[obsolete]

The QMultiLineEdit widget is a simple editor for inputting text. More...

#include <qmultilineedit.h>

Inherits QTextEdit.

List of all member functions.

Public Members

  • QMultiLineEdit ( QWidget * parent = 0, const char * name = 0 )
  • QString textLine ( int line ) const
  • int numLines () const
  • virtual void insertLine ( const QString & txt, int line = -1 )
  • virtual void insertAt ( const QString & s, int line, int col, bool mark = FALSE )
  • virtual void removeLine ( int paragraph )
  • virtual void setCursorPosition ( int line, int col, bool mark = FALSE )
  • bool atBeginning () const
  • bool atEnd () const
  • virtual void setAlignment ( int flags )
  • int alignment () const
  • void setEdited ( bool )
  • bool edited () const
  • bool hasMarkedText () const
  • QString markedText () const
  • void cursorWordForward ( bool mark )
  • void cursorWordBackward ( bool mark )
  • bool autoUpdate () const (obsolete)
  • virtual void setAutoUpdate ( bool ) (obsolete)
  • int totalWidth () const (obsolete)
  • int totalHeight () const (obsolete)
  • int maxLines () const (obsolete)
  • void setMaxLines ( int ) (obsolete)

Public Slots

  • void deselect () (obsolete)

Properties

  • Alignment alignment - the editor's paragraph alignment
  • bool atBeginning - whether the cursor is placed at the beginning of the text (read only)
  • bool atEnd - whether the cursor is placed at the end of the text (read only)
  • bool edited - whether the document has been edited by the user
  • int numLines - the number of paragraphs in the editor (read only)

Protected Members

  • QPoint cursorPoint () const
  • virtual void insertAndMark ( const QString & str, bool mark )
  • virtual void newLine ()
  • virtual void killLine ()
  • virtual void pageUp ( bool mark = FALSE )
  • virtual void pageDown ( bool mark = FALSE )
  • virtual void cursorLeft ( bool mark = FALSE, bool wrap = TRUE )
  • virtual void cursorRight ( bool mark = FALSE, bool wrap = TRUE )
  • virtual void cursorUp ( bool mark = FALSE )
  • virtual void cursorDown ( bool mark = FALSE )
  • virtual void backspace ()
  • virtual void home ( bool mark = FALSE )
  • virtual void end ( bool mark = FALSE )
  • bool getMarkedRegion ( int * line1, int * col1, int * line2, int * col2 ) const
  • int lineLength ( int row ) const

Detailed Description

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

The QMultiLineEdit widget is a simple editor for inputting text.

The QMultiLineEdit was a simple editor widget in former Qt versions. Qt 3.0 includes a new richtext engine which obsoletes QMultiLineEdit. It is still included for compatibility reasons. It is now a subclass of QTextEdit, and provides enough of the old QMultiLineEdit API to keep old applications working.

If you implement something new with QMultiLineEdit, we suggest using QTextEdit instead and call QTextEdit::setTextFormat(Qt::PlainText).

Although most of the old QMultiLineEdit API is still available, there is a few difference. The old QMultiLineEdit operated on lines, not on paragraphs. As lines change all the time during wordwrap, the new richtext engine uses paragraphs as basic elements in the data structure. All functions (numLines(), textLine(), etc.) that operated on lines, now operate on paragraphs. Further, getString() has been removed completely. It revealed too much of the internal data structure.

Applications which made normal and reasonable use of QMultiLineEdit should still work without problems. Some odd usage will require some porting. In these cases, it may be better to use QTextEdit now.

See also QTextEdit and Advanced Widgets.

Member Function Documentation

QMultiLineEdit::QMultiLineEdit ( QWidget * parent = 0, const char * name = 0 )

Constructs a new, empty, QMultiLineEdit with parent parent called name.

int QMultiLineEdit::alignment () const

Returns the editor's paragraph alignment. See the "alignment" property for details.

bool QMultiLineEdit::atBeginning () const

Returns TRUE if the cursor is placed at the beginning of the text; otherwise returns FALSE. See the "atBeginning" property for details.

bool QMultiLineEdit::atEnd () const

Returns TRUE if the cursor is placed at the end of the text; otherwise returns FALSE. See the "atEnd" property for details.

bool QMultiLineEdit::autoUpdate () const

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

void QMultiLineEdit::backspace () [virtual protected]

Deletes the character on the left side of the text cursor and moves the cursor one position to the left. If a text has been selected by the user (e.g. by clicking and dragging) the cursor is put at the beginning of the selected text and the selected text is removed. del()

void QMultiLineEdit::cursorDown ( bool mark = FALSE ) [virtual protected]

Moves the cursor one line down. If mark is TRUE, the text is selected.

See also cursorUp(), cursorLeft() and cursorRight().

void QMultiLineEdit::cursorLeft ( bool mark = FALSE, bool wrap = TRUE ) [virtual protected]

Moves the cursor one character to the left. If mark is TRUE, the text is selected. The wrap parameter is currently ignored.

See also cursorRight(), cursorUp() and cursorDown().

QPoint QMultiLineEdit::cursorPoint () const [protected]

Returns the top center point where the cursor is drawn.

void QMultiLineEdit::cursorRight ( bool mark = FALSE, bool wrap = TRUE ) [virtual protected]

Moves the cursor one character to the right. If mark is TRUE, the text is selected. The wrap parameter is currently ignored.

See also cursorLeft(), cursorUp() and cursorDown().

void QMultiLineEdit::cursorUp ( bool mark = FALSE ) [virtual protected]

Moves the cursor up one line. If mark is TRUE, the text is selected.

See also cursorDown(), cursorLeft() and cursorRight().

void QMultiLineEdit::cursorWordBackward ( bool mark )

Moves the cursor one word to the left. If mark is TRUE, the text is selected.

See also cursorWordForward().

void QMultiLineEdit::cursorWordForward ( bool mark )

Moves the cursor one word to the right. If mark is TRUE, the text is selected.

See also cursorWordBackward().

void QMultiLineEdit::deselect () [slot]

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

bool QMultiLineEdit::edited () const

Returns TRUE if the document has been edited by the user; otherwise returns FALSE. See the "edited" property for details.

void QMultiLineEdit::end ( bool mark = FALSE ) [virtual protected]

Moves the text cursor to the right end of the line. If mark is TRUE, text is selected toward the last position. If it is FALSE and the cursor is moved, all selected text is unselected.

See also home().

bool QMultiLineEdit::getMarkedRegion ( int * line1, int * col1, int * line2, int * col2 ) const [protected]

If there is selected text, sets line1, col1, line2 and col2 to the start and end of the selected region and returns TRUE. Returns FALSE if there is no selected text.

bool QMultiLineEdit::hasMarkedText () const

Returns TRUE if there is selected text.

void QMultiLineEdit::home ( bool mark = FALSE ) [virtual protected]

Moves the text cursor to the left end of the line. If mark is TRUE, text is selected toward the first position. If it is FALSE and the cursor is moved, all selected text is unselected.

See also end().

void QMultiLineEdit::insertAndMark ( const QString & str, bool mark ) [virtual protected]

Inserts str at the current cursor position and selects the text if mark is TRUE.

void QMultiLineEdit::insertAt ( const QString & s, int line, int col, bool mark = FALSE ) [virtual]

Inserts string s at paragraph number line, after character number col in the paragraph. If s contains newline characters, new lines are inserted. If mark is TRUE the inserted string will be selected.

The cursor position is adjusted.

void QMultiLineEdit::insertLine ( const QString & txt, int line = -1 ) [virtual]

Inserts txt at paragraph number line. If line is less than zero, or larger than the number of paragraphs, the new text is put at the end. If txt contains newline characters, several paragraphs are inserted.

The cursor position is not changed.

void QMultiLineEdit::killLine () [virtual protected]

Deletes text from the current cursor position to the end of the line. (Note that this function still operates on lines, not paragraphs.)

int QMultiLineEdit::lineLength ( int row ) const [protected]

Returns the number of characters at paragraph number row. If row is out of range, -1 is returned.

QString QMultiLineEdit::markedText () const

Returns a copy of the selected text.

int QMultiLineEdit::maxLines () const

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

void QMultiLineEdit::newLine () [virtual protected]

Splits the paragraph at the current cursor position.

int QMultiLineEdit::numLines () const

Returns the number of paragraphs in the editor. See the "numLines" property for details.

void QMultiLineEdit::pageDown ( bool mark = FALSE ) [virtual protected]

Moves the cursor one page down. If mark is TRUE, the text is selected.

void QMultiLineEdit::pageUp ( bool mark = FALSE ) [virtual protected]

Moves the cursor one page up. If mark is TRUE, the text is selected.

void QMultiLineEdit::removeLine ( int paragraph ) [virtual]

Deletes the paragraph at paragraph number paragraph. If paragraph is less than zero or larger than the number of paragraphs, nothing is deleted.

void QMultiLineEdit::setAlignment ( int flags ) [virtual]

Sets the editor's paragraph alignment to flags. See the "alignment" property for details.

Reimplemented from QTextEdit.

void QMultiLineEdit::setAutoUpdate ( bool ) [virtual]

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

Example: qwerty/qwerty.cpp.

void QMultiLineEdit::setCursorPosition ( int line, int col, bool mark = FALSE ) [virtual]

Sets the cursor position to character number col in paragraph number line. The parameters are adjusted to lie within the legal range.

If mark is FALSE, the selection is cleared. otherwise it is extended.

void QMultiLineEdit::setEdited ( bool )

Sets whether the document has been edited by the user. See the "edited" property for details.

void QMultiLineEdit::setMaxLines ( int )

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

QString QMultiLineEdit::textLine ( int line ) const

Returns the text at line number line (possibly the empty string), or a null string if line is invalid.

Examples: mdi/application.cpp and qwerty/qwerty.cpp.

int QMultiLineEdit::totalHeight () const

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

int QMultiLineEdit::totalWidth () const

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

Property Documentation

Alignment alignment

This property holds the editor's paragraph alignment.

Sets the alignment to flag, which must be AlignLeft, AlignHCenter or AlignRight.

If flag is an illegal flag nothing happens.

See also Qt::AlignmentFlags.

Set this property's value with setAlignment() and get this property's value with alignment().

bool atBeginning

This property holds whether the cursor is placed at the beginning of the text.

Get this property's value with atBeginning().

See also atEnd.

bool atEnd

This property holds whether the cursor is placed at the end of the text.

Get this property's value with atEnd().

See also atBeginning.

bool edited

This property holds whether the document has been edited by the user.

This is the same as QTextEdit's "modifed" property.

See also QTextEdit::modified.

Set this property's value with setEdited() and get this property's value with edited().

int numLines

This property holds the number of paragraphs in the editor.

The count includes any empty paragraph at top and bottom, so for an empty editor this method returns 1.

Get this property's value with numLines().

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


qmultilineedit.h Include File

qmultilineedit.h

This is the verbatim text of the qmultilineedit.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qmultilineedit.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QMultiLineEdit widget class
**
** Created : 961005
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMULTILINEEDIT_H
#define QMULTILINEEDIT_H

#ifndef QT_H
#include "qtextedit.h"
#endif // QT_H

#ifndef QT_NO_MULTILINEEDIT

class QMultiLineEditCommand;
class QValidator;
class QMultiLineEditData;

class Q_EXPORT QMultiLineEdit : public QTextEdit
{
    Q_OBJECT
    Q_PROPERTY( int numLines READ numLines )
    Q_PROPERTY( bool atBeginning READ atBeginning )
    Q_PROPERTY( bool atEnd READ atEnd )
    Q_PROPERTY( Alignment alignment READ alignment WRITE setAlignment )
    Q_PROPERTY( bool edited READ edited WRITE setEdited DESIGNABLE false )

public:
    QMultiLineEdit( QWidget* parent=0, const char* name=0 );
    ~QMultiLineEdit();

    QString textLine( int line ) const;
    int numLines() const;

    virtual void insertLine( const QString &s, int line = -1 );
    virtual void insertAt( const QString &s, int line, int col, bool mark = FALSE );
    virtual void removeLine( int line );

    virtual void setCursorPosition( int line, int col, bool mark = FALSE );
    bool atBeginning() const;
    bool atEnd() const;

    void setAlignment( int flags );
    int alignment() const;

    void setEdited( bool );
    bool edited() const;

    bool hasMarkedText() const;
    QString markedText() const;

    void cursorWordForward( bool mark );
    void cursorWordBackward( bool mark );

    // noops
    bool autoUpdate() const { return TRUE; }
    virtual void setAutoUpdate( bool ) {}

    int totalWidth() const { return contentsWidth(); }
    int totalHeight() const { return contentsHeight(); }

    int maxLines() const { return QWIDGETSIZE_MAX; }
    void setMaxLines( int ) {}

public slots:
    void deselect() { selectAll( FALSE ); }

protected:
    QPoint	cursorPoint() const;

protected:
    virtual void insertAndMark( const QString&, bool mark );
    virtual void newLine();
    virtual void killLine();
    virtual void pageUp( bool mark=FALSE );
    virtual void pageDown( bool mark=FALSE );
    virtual void cursorLeft( bool mark=FALSE, bool wrap = TRUE );
    virtual void cursorRight( bool mark=FALSE, bool wrap = TRUE );
    virtual void cursorUp( bool mark=FALSE );
    virtual void cursorDown( bool mark=FALSE );
    virtual void backspace();
    virtual void home( bool mark=FALSE );
    virtual void end( bool mark=FALSE );

    bool getMarkedRegion( int *line1, int *col1,
              int *line2, int *col2 ) const;
    int lineLength( int row ) const;

private:
    QMultiLineEditData *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QMultiLineEdit( const QMultiLineEdit & );
    QMultiLineEdit &operator=( const QMultiLineEdit & );
#endif
};

#endif // QT_NO_MULTILINEEDIT

#endif // QMULTILINED_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QMultiLineEdit Member List

Complete Member List for QMultiLineEdit

This is the complete list of member functions for QMultiLineEdit, including inherited members.

  • QMultiLineEdit()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • alignment()
  • anchorAt()
  • append()
  • atBeginning()
  • atEnd()
  • autoMask()
  • autoUpdate()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • backspace()
  • baseSize()
  • blockSignals()
  • bold()
  • bottomMargin()
  • caption()
  • center()
  • charAt()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearParagraphBackground()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • color()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • context()
  • contextMenuEvent()
  • copy()
  • copyAvailable()
  • cornerWidget()
  • create()
  • createPopupMenu()
  • currentAlignmentChanged()
  • currentColorChanged()
  • currentFontChanged()
  • currentVerticalAlignmentChanged()
  • cursor()
  • cursorDown()
  • cursorLeft()
  • cursorPoint()
  • cursorPositionChanged()
  • cursorRight()
  • cursorUp()
  • cursorWordBackward()
  • cursorWordForward()
  • customEvent()
  • customWhatsThis()
  • cut()
  • del()
  • deleteLater()
  • deselect()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doKeyboardAction()
  • documentTitle()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • edited()
  • enableClipper()
  • enabledChange()
  • end()
  • ensureCursorVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • family()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getCursorPosition()
  • getMarkedRegion()
  • getSelection()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMarkedText()
  • hasMouse()
  • hasMouseTracking()
  • hasSelectedText()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • home()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indent()
  • inherits()
  • insert()
  • insertAndMark()
  • insertAt()
  • insertChild()
  • insertLine()
  • insertParagraph()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isModified()
  • isOverwriteMode()
  • isPopup()
  • isReadOnly()
  • isRedoAvailable()
  • isTopLevel()
  • isUndoAvailable()
  • isUndoRedoEnabled()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • italic()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killLine()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • length()
  • lineLength()
  • lineOfChar()
  • lineWidth()
  • lines()
  • linesOfParagraph()
  • linkUnderline()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • markedText()
  • maxLines()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • mimeSourceFactory()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • modificationChanged()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveCursor()
  • moveEvent()
  • name()
  • newLine()
  • normalizeSignalSlot()
  • numLines()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageDown()
  • pageUp()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • paper()
  • paragraphAt()
  • paragraphBackgroundColor()
  • paragraphLength()
  • paragraphRect()
  • paragraphs()
  • parent()
  • parentWidget()
  • paste()
  • pasteSubType()
  • placeCursor()
  • pointSize()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • redoAvailable()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeLine()
  • removeParagraph()
  • removeSelectedText()
  • removeSelection()
  • repaint()
  • repaintChanged()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • returnPressed()
  • rightMargin()
  • scroll()
  • scrollBy()
  • scrollToAnchor()
  • scrollToBottom()
  • selectAll()
  • selectedText()
  • selectionChanged()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setAutoUpdate()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBold()
  • setCaption()
  • setColor()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentFont()
  • setCursor()
  • setCursorPosition()
  • setDisabled()
  • setDragAutoScroll()
  • setEdited()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFamily()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItalic()
  • setKeyCompression()
  • setLineWidth()
  • setLinkUnderline()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaxLines()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMimeSourceFactory()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setModified()
  • setMouseTracking()
  • setName()
  • setOverwriteMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPaper()
  • setParagraphBackgroundColor()
  • setPointSize()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setSelection()
  • setSelectionAttributes()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setStyleSheet()
  • setTabOrder()
  • setTabStopWidth()
  • setText()
  • setTextFormat()
  • setUnderline()
  • setUndoDepth()
  • setUndoRedoEnabled()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setVerticalAlignment()
  • setWFlags()
  • setWordWrap()
  • setWrapColumnOrWidth()
  • setWrapPolicy()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • styleSheet()
  • tabStopWidth()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • textCursor()
  • textFormat()
  • textLine()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • totalHeight()
  • totalWidth()
  • tr()
  • trUtf8()
  • underline()
  • undo()
  • undoAvailable()
  • undoDepth()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrap()
  • wrapColumnOrWidth()
  • wrapPolicy()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()
  • zoomIn()
  • zoomOut()
  • zoomTo()


QMutex类

QMutex类参考

QMutex类提供的是线程之间的访问顺序化。 详情请见……

#include <qmutex.h>

所有成员函数的列表。

公有成员

  • QMutex ( bool recursive = FALSE )
  • virtual ~QMutex ()
  • void lock ()
  • void unlock ()
  • bool locked ()
  • bool tryLock ()

详细描述

QMutex类提供的是线程之间的访问顺序化。

QMutex的目的是保护一个对象、数据结构或者代码段，所以同一时间只有一个线程可以访问它。（在Java术语中，它和同步关键字“synchronized”很相似）。例如，这里有一个方法打印给用户两条消息：

  void someMethod()
  {
     qDebug("Hello");
     qDebug("World");
  }

如果同时在两个线程中调用这个方法，结果的顺序将是：

  Hello
  Hello
  World
  World

如果你使用了一个互斥量：

  QMutex mutex;

  void someMethod()
  {
     mutex.lock();
     qDebug("Hello");
     qDebug("World");
     mutex.unlock();
  }

用Java的术语，这段代码应该是：

  void someMethod()
  {
     synchronized {
       qDebug("Hello");
       qDebug("World");
     }
  }

然后同一时间只有一个线程可以运行someMethod并且消息的顺序也一直是正确的。当然，这只是一个很简单的例子，但是它适用于任何需要按特定频率发生的情况。

但你在一个线程中调用lock()，其它线程将会在同一地点试图调用lock()来阻塞，知道这个线程调用unlock()之后其它线程才会获得这个锁。lock()的一种非阻塞选择是tryLock()。

也可以参考环境类和线程类。

成员函数文档

QMutex::QMutex ( bool recursive = FALSE )

构造一个新的互斥量。这个互斥量是在没有锁定的状态下创建的。如果recursive为真，就构造一个递归互斥量，如果recursive为假（默认值），就构造一个普通互斥量。对于一个递归互斥量，一个线程可以锁定一个互斥量多次并且只有在相同数量的unlock()调用之后，它才会被解锁。

QMutex::~QMutex () [虚]

销毁这个互斥量。

void QMutex::lock ()

试图锁定互斥量。如果另一个线程已经锁定这个互斥量，那么这次调用将阻塞直到那个线程把它解锁。

也可以参考unlock()和locked()。

bool QMutex::locked ()

如果互斥量被另一个线程锁定了，返回真，否则返回假。

警告：由于不同平台上递归互斥量的实现不同，所以从以前锁定这个互斥量的同一个线程上调用这个函数可能会返回未定义的结果。

也可以参考lock()和unlock()。

bool QMutex::tryLock ()

试图锁定互斥量。如果锁被得到，这个函数返回真。如果另一个进程已经锁定了这个互斥量，这个函数返回假，而不是一直等到这个锁可用为止，比如，它不是阻塞的。

在另一个线程可以成功锁定它之前，这个锁必须被调用unlock()来解锁。

也可以参考lock()、unlock()和locked()。

void QMutex::unlock ()

解锁这个互斥量。试图对不同的线程中锁定的互斥量进行解锁将会返回一个错误。对一个没有锁定的互斥量进行解锁的结果是将导致未定义的行为（不同的操作系统的线程实现是有很大不同的）。

也可以参考lock()和locked()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qmutex.h包含文件

qmutex.h

这里是qmutex.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QMutex class
**
** Created : 931107
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QMUTEX_H
#define QMUTEX_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

#if defined(QT_THREAD_SUPPORT)

class QMutexPrivate;

const int Q_MUTEX_NORMAL = 0;
const int Q_MUTEX_RECURSIVE = 1;

class Q_EXPORT QMutex
{
    friend class QWaitCondition;
    friend class QWaitConditionPrivate;

public:
    QMutex(bool recursive = FALSE);
    virtual ~QMutex();

    void lock();
    void unlock();
    bool locked();
    bool tryLock();

private:
    QMutexPrivate * d;

#if defined(Q_DISABLE_COPY)
    QMutex( const QMutex & );
    QMutex &operator=( const QMutex & );
#endif
};

#endif

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QMutex成员列表

完整的QMutex成员列表

这里是QMutex成员函数的完整列表，包括继承的成员。

  • QMutex()
  • ~QMutex()
  • lock()
  • locked()
  • tryLock()
  • unlock()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qnamespace.h Include File

qnamespace.h

This is the verbatim text of the qnamespace.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of Qt namespace (as class for compiler compatibility)
**
** Created : 980927
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QNAMESPACE_H
#define QNAMESPACE_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

class QColor;
class QCursor;

class Q_EXPORT Qt {
public:
    QT_STATIC_CONST QColor & color0;
    QT_STATIC_CONST QColor & color1;
    QT_STATIC_CONST QColor & black;
    QT_STATIC_CONST QColor & white;
    QT_STATIC_CONST QColor & darkGray;
    QT_STATIC_CONST QColor & gray;
    QT_STATIC_CONST QColor & lightGray;
    QT_STATIC_CONST QColor & red;
    QT_STATIC_CONST QColor & green;
    QT_STATIC_CONST QColor & blue;
    QT_STATIC_CONST QColor & cyan;
    QT_STATIC_CONST QColor & magenta;
    QT_STATIC_CONST QColor & yellow;
    QT_STATIC_CONST QColor & darkRed;
    QT_STATIC_CONST QColor & darkGreen;
    QT_STATIC_CONST QColor & darkBlue;
    QT_STATIC_CONST QColor & darkCyan;
    QT_STATIC_CONST QColor & darkMagenta;
    QT_STATIC_CONST QColor & darkYellow;

    // documented in qevent.cpp
    enum ButtonState {				// mouse/keyboard state values
    NoButton	= 0x0000,
    LeftButton	= 0x0001,
    RightButton	= 0x0002,
    MidButton	= 0x0004,
    MouseButtonMask = 0x00ff,
    ShiftButton	= 0x0100,
    ControlButton   = 0x0200,
    AltButton	= 0x0400,
    MetaButton	= 0x0800,
    KeyButtonMask	= 0x0fff,
    Keypad		= 0x4000
    };

    // documented in qobject.cpp
    // ideally would start at 1, as in QSizePolicy, but that breaks other things
    enum Orientation {
        Horizontal = 0,
    Vertical
    };

    // Text formatting flags for QPainter::drawText and QLabel
    // the following four enums can be combined to one integer which
    // is passed as textflag to drawText and qt_format_text.

    // documented in qpainter.cpp
    enum AlignmentFlags {
    AlignAuto		= 0x0000, 	// text alignment
    AlignLeft		= 0x0001,
    AlignRight		= 0x0002,
    AlignHCenter		= 0x0004,
    AlignJustify		= 0x0008,
    AlignHorizontal_Mask	= AlignLeft | AlignRight | AlignHCenter | AlignJustify,
    AlignTop		= 0x0010,
    AlignBottom		= 0x0020,
    AlignVCenter		= 0x0040,
    AlignVertical_Mask 	= AlignTop | AlignBottom | AlignVCenter,
    AlignCenter		= AlignVCenter | AlignHCenter
    };

    // documented in qpainter.cpp
    enum TextFlags {
    SingleLine	= 0x0080,		// misc. flags
    DontClip	= 0x0100,
    ExpandTabs	= 0x0200,
    ShowPrefix	= 0x0400,
    WordBreak	= 0x0800,
    BreakAnywhere = 0x1000,
    DontPrint	= 0x2000,		// internal
    NoAccel = 0x4000
    };

    // Widget flags; documented in qwidget.cpp
    typedef uint WState;

    // QWidget state flags (internal, barely documented in qwidget.cpp)
    enum WidgetState {
    WState_Created		= 0x00000001,
    WState_Disabled		= 0x00000002,
    WState_Visible		= 0x00000004,
    WState_ForceHide	= 0x00000008,
    WState_OwnCursor	= 0x00000010,
    WState_MouseTracking	= 0x00000020,
    WState_CompressKeys	= 0x00000040,
    WState_BlockUpdates	= 0x00000080,
    WState_InPaintEvent	= 0x00000100,
    WState_Reparented	= 0x00000200,
    WState_ConfigPending	= 0x00000400,
    WState_Resized		= 0x00000800,
    WState_AutoMask		= 0x00001000,
    WState_Polished		= 0x00002000,
    WState_DND		= 0x00004000,
    WState_Reserved0	= 0x00008000,
    WState_Reserved1	= 0x00010000,
    WState_Reserved2	= 0x00020000,
    WState_Reserved3	= 0x00040000,
    WState_Maximized	= 0x00080000,
    WState_Minimized	= 0x00100000,
    WState_ForceDisabled	= 0x00200000,
    WState_Exposed		= 0x00400000,
    WState_HasMouse		= 0x00800000
    };

    // Widget flags2; documented in qwidget.cpp
    typedef uint WFlags;

    // documented in qwidget.cpp
    enum WidgetFlags {
    WType_TopLevel		= 0x00000001,	// widget type flags
    WType_Dialog		= 0x00000002,
    WType_Popup		= 0x00000004,
    WType_Desktop		= 0x00000008,
    WType_Mask		= 0x0000000f,

    WStyle_Customize	= 0x00000010,	// window style flags
    WStyle_NormalBorder	= 0x00000020,
    WStyle_DialogBorder	= 0x00000040, // MS-Windows only
    WStyle_NoBorder		= 0x00002000,
    WStyle_Title		= 0x00000080,
    WStyle_SysMenu		= 0x00000100,
    WStyle_Minimize		= 0x00000200,
    WStyle_Maximize		= 0x00000400,
    WStyle_MinMax		= WStyle_Minimize | WStyle_Maximize,
    WStyle_Tool		= 0x00000800,
    WStyle_StaysOnTop	= 0x00001000,
    WStyle_ContextHelp	= 0x00004000,
    WStyle_Reserved		= 0x00008000,
    WStyle_Mask		= 0x0000fff0,

    WDestructiveClose	= 0x00010000,	// misc flags
    WPaintDesktop		= 0x00020000,
    WPaintUnclipped		= 0x00040000,
    WPaintClever		= 0x00080000,
    WResizeNoErase		= 0x00100000,
    WMouseNoMask		= 0x00200000,
    WStaticContents		= 0x00400000,
    WRepaintNoErase		= 0x00800000,
#ifdef Q_WS_X11
    WX11BypassWM		= 0x01000000,
    WWinOwnDC		= 0x00000000,
#else
    WX11BypassWM		= 0x00000000,
    WWinOwnDC		= 0x01000000,
#endif
    WGroupLeader 		= 0x02000000,
    WShowModal 	       	= 0x04000000,
    WNoMousePropagation	= 0x08000000,
    WSubWindow              = 0x10000000
#ifndef QT_NO_COMPAT
    ,
    WNorthWestGravity	= WStaticContents,
    WType_Modal		= WType_Dialog | WShowModal,
    WStyle_Dialog 		= WType_Dialog,
    WStyle_NoBorderEx	= WStyle_NoBorder
#endif
    };

    // Image conversion flags.  The unusual ordering is caused by
    // compatibility and default requirements.
    // Documented in qimage.cpp

    enum ImageConversionFlags {
    ColorMode_Mask		= 0x00000003,
    AutoColor		= 0x00000000,
    ColorOnly		= 0x00000003,
    MonoOnly		= 0x00000002,
    //	  Reserved	= 0x00000001,

    AlphaDither_Mask	= 0x0000000c,
    ThresholdAlphaDither	= 0x00000000,
    OrderedAlphaDither	= 0x00000004,
    DiffuseAlphaDither	= 0x00000008,
    NoAlpha			= 0x0000000c, // Not supported

    Dither_Mask		= 0x00000030,
    DiffuseDither		= 0x00000000,
    OrderedDither		= 0x00000010,
    ThresholdDither		= 0x00000020,
    //	  ReservedDither= 0x00000030,

    DitherMode_Mask		= 0x000000c0,
    AutoDither		= 0x00000000,
    PreferDither		= 0x00000040,
    AvoidDither		= 0x00000080
    };

    // documented in qpainter.cpp
    enum BGMode	{				// background mode
    TransparentMode,
    OpaqueMode
    };

#ifndef QT_NO_COMPAT
    // documented in qpainter.cpp
    enum PaintUnit {				// paint unit
    PixelUnit,
    LoMetricUnit, // OBSOLETE
    HiMetricUnit, // OBSOLETE
    LoEnglishUnit, // OBSOLETE
    HiEnglishUnit, // OBSOLETE
    TwipsUnit // OBSOLETE
    };
#endif

    // documented in qstyle.cpp
#ifdef QT_NO_COMPAT
    enum GUIStyle {
    WindowsStyle = 1,     // ### Qt 4.0: either remove the obsolete enums or clean up compat vs.
    MotifStyle = 4        // ### QT_NO_COMPAT by reordering or combination into one enum.
    };
#else
    enum GUIStyle {
    MacStyle, // OBSOLETE
    WindowsStyle,
    Win3Style, // OBSOLETE
    PMStyle, // OBSOLETE
    MotifStyle
    };
#endif

    // documented in qevent.cpp
    enum Modifier {		// accelerator modifiers
    SHIFT         = 0x00200000,
    CTRL          = 0x00400000,
    ALT           = 0x00800000,
    MODIFIER_MASK = 0x00e00000,
    UNICODE_ACCEL = 0x10000000,

    ASCII_ACCEL = UNICODE_ACCEL // 1.x compat
    };

    // documented in qevent.cpp
    enum Key {
    Key_Escape = 0x1000,		// misc keys
    Key_Tab = 0x1001,
    Key_Backtab = 0x1002, Key_BackTab = Key_Backtab,
    Key_Backspace = 0x1003, Key_BackSpace = Key_Backspace,
    Key_Return = 0x1004,
    Key_Enter = 0x1005,
    Key_Insert = 0x1006,
    Key_Delete = 0x1007,
    Key_Pause = 0x1008,
    Key_Print = 0x1009,
    Key_SysReq = 0x100a,
    Key_Home = 0x1010,		// cursor movement
    Key_End = 0x1011,
    Key_Left = 0x1012,
    Key_Up = 0x1013,
    Key_Right = 0x1014,
    Key_Down = 0x1015,
    Key_Prior = 0x1016, Key_PageUp = Key_Prior,
    Key_Next = 0x1017, Key_PageDown = Key_Next,
    Key_Shift = 0x1020,		// modifiers
    Key_Control = 0x1021,
    Key_Meta = 0x1022,
    Key_Alt = 0x1023,
    Key_CapsLock = 0x1024,
    Key_NumLock = 0x1025,
    Key_ScrollLock = 0x1026,
    Key_F1 = 0x1030,		// function keys
    Key_F2 = 0x1031,
    Key_F3 = 0x1032,
    Key_F4 = 0x1033,
    Key_F5 = 0x1034,
    Key_F6 = 0x1035,
    Key_F7 = 0x1036,
    Key_F8 = 0x1037,
    Key_F9 = 0x1038,
    Key_F10 = 0x1039,
    Key_F11 = 0x103a,
    Key_F12 = 0x103b,
    Key_F13 = 0x103c,
    Key_F14 = 0x103d,
    Key_F15 = 0x103e,
    Key_F16 = 0x103f,
    Key_F17 = 0x1040,
    Key_F18 = 0x1041,
    Key_F19 = 0x1042,
    Key_F20 = 0x1043,
    Key_F21 = 0x1044,
    Key_F22 = 0x1045,
    Key_F23 = 0x1046,
    Key_F24 = 0x1047,
    Key_F25 = 0x1048,		// F25 .. F35 only on X11
    Key_F26 = 0x1049,
    Key_F27 = 0x104a,
    Key_F28 = 0x104b,
    Key_F29 = 0x104c,
    Key_F30 = 0x104d,
    Key_F31 = 0x104e,
    Key_F32 = 0x104f,
    Key_F33 = 0x1050,
    Key_F34 = 0x1051,
    Key_F35 = 0x1052,
    Key_Super_L = 0x1053, 		// extra keys
    Key_Super_R = 0x1054,
    Key_Menu = 0x1055,
    Key_Hyper_L = 0x1056,
    Key_Hyper_R = 0x1057,
    Key_Help = 0x1058,
    Key_Direction_L = 0x1059,
    Key_Direction_R = 0x1060,
    Key_Space = 0x20,		// 7 bit printable ASCII
    Key_Any = Key_Space,
    Key_Exclam = 0x21,
    Key_QuoteDbl = 0x22,
    Key_NumberSign = 0x23,
    Key_Dollar = 0x24,
    Key_Percent = 0x25,
    Key_Ampersand = 0x26,
    Key_Apostrophe = 0x27,
    Key_ParenLeft = 0x28,
    Key_ParenRight = 0x29,
    Key_Asterisk = 0x2a,
    Key_Plus = 0x2b,
    Key_Comma = 0x2c,
    Key_Minus = 0x2d,
    Key_Period = 0x2e,
    Key_Slash = 0x2f,
    Key_0 = 0x30,
    Key_1 = 0x31,
    Key_2 = 0x32,
    Key_3 = 0x33,
    Key_4 = 0x34,
    Key_5 = 0x35,
    Key_6 = 0x36,
    Key_7 = 0x37,
    Key_8 = 0x38,
    Key_9 = 0x39,
    Key_Colon = 0x3a,
    Key_Semicolon = 0x3b,
    Key_Less = 0x3c,
    Key_Equal = 0x3d,
    Key_Greater = 0x3e,
    Key_Question = 0x3f,
    Key_At = 0x40,
    Key_A = 0x41,
    Key_B = 0x42,
    Key_C = 0x43,
    Key_D = 0x44,
    Key_E = 0x45,
    Key_F = 0x46,
    Key_G = 0x47,
    Key_H = 0x48,
    Key_I = 0x49,
    Key_J = 0x4a,
    Key_K = 0x4b,
    Key_L = 0x4c,
    Key_M = 0x4d,
    Key_N = 0x4e,
    Key_O = 0x4f,
    Key_P = 0x50,
    Key_Q = 0x51,
    Key_R = 0x52,
    Key_S = 0x53,
    Key_T = 0x54,
    Key_U = 0x55,
    Key_V = 0x56,
    Key_W = 0x57,
    Key_X = 0x58,
    Key_Y = 0x59,
    Key_Z = 0x5a,
    Key_BracketLeft = 0x5b,
    Key_Backslash = 0x5c,
    Key_BracketRight = 0x5d,
    Key_AsciiCircum = 0x5e,
    Key_Underscore = 0x5f,
    Key_QuoteLeft = 0x60,
    Key_BraceLeft = 0x7b,
    Key_Bar = 0x7c,
    Key_BraceRight = 0x7d,
    Key_AsciiTilde = 0x7e,

    // Latin 1 codes adapted from X: keysymdef.h,v 1.21 94/08/28 16:17:06

    Key_nobreakspace = 0x0a0,
    Key_exclamdown = 0x0a1,
    Key_cent = 0x0a2,
    Key_sterling = 0x0a3,
    Key_currency = 0x0a4,
    Key_yen = 0x0a5,
    Key_brokenbar = 0x0a6,
    Key_section = 0x0a7,
    Key_diaeresis = 0x0a8,
    Key_copyright = 0x0a9,
    Key_ordfeminine = 0x0aa,
    Key_guillemotleft = 0x0ab,	// left angle quotation mark
    Key_notsign = 0x0ac,
    Key_hyphen = 0x0ad,
    Key_registered = 0x0ae,
    Key_macron = 0x0af,
    Key_degree = 0x0b0,
    Key_plusminus = 0x0b1,
    Key_twosuperior = 0x0b2,
    Key_threesuperior = 0x0b3,
    Key_acute = 0x0b4,
    Key_mu = 0x0b5,
    Key_paragraph = 0x0b6,
    Key_periodcentered = 0x0b7,
    Key_cedilla = 0x0b8,
    Key_onesuperior = 0x0b9,
    Key_masculine = 0x0ba,
    Key_guillemotright = 0x0bb,	// right angle quotation mark
    Key_onequarter = 0x0bc,
    Key_onehalf = 0x0bd,
    Key_threequarters = 0x0be,
    Key_questiondown = 0x0bf,
    Key_Agrave = 0x0c0,
    Key_Aacute = 0x0c1,
    Key_Acircumflex = 0x0c2,
    Key_Atilde = 0x0c3,
    Key_Adiaeresis = 0x0c4,
    Key_Aring = 0x0c5,
    Key_AE = 0x0c6,
    Key_Ccedilla = 0x0c7,
    Key_Egrave = 0x0c8,
    Key_Eacute = 0x0c9,
    Key_Ecircumflex = 0x0ca,
    Key_Ediaeresis = 0x0cb,
    Key_Igrave = 0x0cc,
    Key_Iacute = 0x0cd,
    Key_Icircumflex = 0x0ce,
    Key_Idiaeresis = 0x0cf,
    Key_ETH = 0x0d0,
    Key_Ntilde = 0x0d1,
    Key_Ograve = 0x0d2,
    Key_Oacute = 0x0d3,
    Key_Ocircumflex = 0x0d4,
    Key_Otilde = 0x0d5,
    Key_Odiaeresis = 0x0d6,
    Key_multiply = 0x0d7,
    Key_Ooblique = 0x0d8,
    Key_Ugrave = 0x0d9,
    Key_Uacute = 0x0da,
    Key_Ucircumflex = 0x0db,
    Key_Udiaeresis = 0x0dc,
    Key_Yacute = 0x0dd,
    Key_THORN = 0x0de,
    Key_ssharp = 0x0df,
    Key_agrave = 0x0e0,
    Key_aacute = 0x0e1,
    Key_acircumflex = 0x0e2,
    Key_atilde = 0x0e3,
    Key_adiaeresis = 0x0e4,
    Key_aring = 0x0e5,
    Key_ae = 0x0e6,
    Key_ccedilla = 0x0e7,
    Key_egrave = 0x0e8,
    Key_eacute = 0x0e9,
    Key_ecircumflex = 0x0ea,
    Key_ediaeresis = 0x0eb,
    Key_igrave = 0x0ec,
    Key_iacute = 0x0ed,
    Key_icircumflex = 0x0ee,
    Key_idiaeresis = 0x0ef,
    Key_eth = 0x0f0,
    Key_ntilde = 0x0f1,
    Key_ograve = 0x0f2,
    Key_oacute = 0x0f3,
    Key_ocircumflex = 0x0f4,
    Key_otilde = 0x0f5,
    Key_odiaeresis = 0x0f6,
    Key_division = 0x0f7,
    Key_oslash = 0x0f8,
    Key_ugrave = 0x0f9,
    Key_uacute = 0x0fa,
    Key_ucircumflex = 0x0fb,
    Key_udiaeresis = 0x0fc,
    Key_yacute = 0x0fd,
    Key_thorn = 0x0fe,
    Key_ydiaeresis = 0x0ff,

    Key_unknown = 0xffff
    };

    // documented in qcommonstyle.cpp
    enum ArrowType {
    UpArrow,
    DownArrow,
    LeftArrow,
    RightArrow
    };

    // documented in qpainter.cpp
    enum RasterOp { // raster op mode
    CopyROP,
    OrROP,
    XorROP,
    NotAndROP, EraseROP=NotAndROP,
    NotCopyROP,
    NotOrROP,
    NotXorROP,
    AndROP,	NotEraseROP=AndROP,
    NotROP,
    ClearROP,
    SetROP,
    NopROP,
    AndNotROP,
    OrNotROP,
    NandROP,
    NorROP,	LastROP=NorROP
    };

    // documented in qpainter.cpp
    enum PenStyle { // pen style
    NoPen,
    SolidLine,
    DashLine,
    DotLine,
    DashDotLine,
    DashDotDotLine,
    MPenStyle = 0x0f
    };

    // documented in qpainter.cpp
    enum PenCapStyle { // line endcap style
    FlatCap = 0x00,
    SquareCap = 0x10,
    RoundCap = 0x20,
    MPenCapStyle = 0x30
    };

    // documented in qpainter.cpp
    enum PenJoinStyle { // line join style
    MiterJoin = 0x00,
    BevelJoin = 0x40,
    RoundJoin = 0x80,
    MPenJoinStyle = 0xc0
    };

    // documented in qpainter.cpp
    enum BrushStyle { // brush style
    NoBrush,
    SolidPattern,
    Dense1Pattern,
    Dense2Pattern,
    Dense3Pattern,
    Dense4Pattern,
    Dense5Pattern,
    Dense6Pattern,
    Dense7Pattern,
    HorPattern,
    VerPattern,
    CrossPattern,
    BDiagPattern,
    FDiagPattern,
    DiagCrossPattern,
    CustomPattern=24
    };

    // documented in qapplication_win.cpp
    enum WindowsVersion {
    WV_32s 		= 0x0001,
    WV_95 		= 0x0002,
    WV_98		= 0x0003,
    WV_Me		= 0x0004,
    WV_DOS_based	= 0x000f,

    WV_NT 		= 0x0010,
    WV_2000 	= 0x0020,
    WV_XP		= 0x0030,
    WV_NT_based	= 0x00f0
    };

    // documented in qstyle.cpp
    enum UIEffect {
    UI_General,
    UI_AnimateMenu,
    UI_FadeMenu,
    UI_AnimateCombo,
    UI_AnimateTooltip,
    UI_FadeTooltip
    };

    // documented in qcursor.cpp
    enum CursorShape {
    ArrowCursor,
    UpArrowCursor,
    CrossCursor,
    WaitCursor,
    IbeamCursor,
    SizeVerCursor,
    SizeHorCursor,
    SizeBDiagCursor,
    SizeFDiagCursor,
    SizeAllCursor,
    BlankCursor,
    SplitVCursor,
    SplitHCursor,
    PointingHandCursor,
    ForbiddenCursor,
    WhatsThisCursor,
    LastCursor	= WhatsThisCursor,
    BitmapCursor	= 24
    };

    // Global cursors

    QT_STATIC_CONST QCursor & arrowCursor;	// standard arrow cursor
    QT_STATIC_CONST QCursor & upArrowCursor;	// upwards arrow
    QT_STATIC_CONST QCursor & crossCursor;	// crosshair
    QT_STATIC_CONST QCursor & waitCursor;	// hourglass/watch
    QT_STATIC_CONST QCursor & ibeamCursor;	// ibeam/text entry
    QT_STATIC_CONST QCursor & sizeVerCursor;	// vertical resize
    QT_STATIC_CONST QCursor & sizeHorCursor;	// horizontal resize
    QT_STATIC_CONST QCursor & sizeBDiagCursor;	// diagonal resize (/)
    QT_STATIC_CONST QCursor & sizeFDiagCursor;	// diagonal resize (\)
    QT_STATIC_CONST QCursor & sizeAllCursor;	// all directions resize
    QT_STATIC_CONST QCursor & blankCursor;	// blank/invisible cursor
    QT_STATIC_CONST QCursor & splitVCursor;	// vertical bar with left-right
                        // arrows
    QT_STATIC_CONST QCursor & splitHCursor;	// horizontal bar with up-down
                        // arrows
    QT_STATIC_CONST QCursor & pointingHandCursor;	// pointing hand
    QT_STATIC_CONST QCursor & forbiddenCursor;	// forbidden cursor (slashed circle)
    QT_STATIC_CONST QCursor & whatsThisCursor;  // arrow with a question mark

    enum TextFormat {
    PlainText,
    RichText,
    AutoText
    };

    // Documented in qmainwindow.cpp
    enum Dock {
    DockUnmanaged,
    DockTornOff,
    DockTop,
    DockBottom,
    DockRight,
    DockLeft,
    DockMinimized
#ifndef QT_NO_COMPAT
        ,
    Unmanaged = DockUnmanaged,
    TornOff = DockTornOff,
    Top = DockTop,
    Bottom = DockBottom,
    Right = DockRight,
    Left = DockLeft,
    Minimized = DockMinimized
#endif
    };
    // compatibility
    typedef Dock ToolBarDock;

    // documented in qdatetime.cpp
    enum DateFormat {
    TextDate,      // default Qt
    ISODate,       // ISO 8601
    LocalDate      // locale dependant
    };

    // documented in qwidget.cpp
    enum BackgroundMode {
    FixedColor,
    FixedPixmap,
    NoBackground,
    PaletteForeground,
    PaletteButton,
    PaletteLight,
    PaletteMidlight,
    PaletteDark,
    PaletteMid,
    PaletteText,
    PaletteBrightText,
    PaletteBase,
    PaletteBackground,
    PaletteShadow,
    PaletteHighlight,
    PaletteHighlightedText,
    PaletteButtonText,
    PaletteLink,
    PaletteLinkVisited,
    X11ParentRelative
    };

    typedef uint ComparisonFlags;

    // Documented in qstring.cpp
    enum StringComparisonMode {
        CaseSensitive   = 0x00001, // 0 0001
        BeginsWith      = 0x00002, // 0 0010
        EndsWith        = 0x00004, // 0 0100
        Contains        = 0x00008, // 0 1000
        ExactMatch      = 0x00010  // 1 0000
    };

    // "handle" type for system objects. Documented as \internal in
    // qapplication.cpp
#if defined(Q_WS_MAC)
    typedef void * HANDLE;
#elif defined(Q_WS_WIN)
    typedef void *HANDLE;
#elif defined(Q_WS_X11)
    typedef unsigned long HANDLE;
#elif defined(Q_WS_QWS)
    typedef void * HANDLE;
#endif
};

class Q_EXPORT QInternal {
public:
    enum PaintDeviceFlags {
    UndefinedDevice = 0x00,
    Widget = 0x01,
    Pixmap = 0x02,
    Printer = 0x03,
    Picture = 0x04,
    System = 0x05,
    DeviceTypeMask = 0x0f,
    ExternalDevice = 0x10,
    // used to emulate some of the behaviour different between Qt2 and Qt3 (mainly for printing)
    CompatibilityMode = 0x20
    };
};

#endif // QNAMESPACE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


qnetwork.h Example File

Copyright © 2002
TrolltechTrademarks

Qt version 3.0.5


QNetworkOperation Class

QNetworkOperation Class Reference

The QNetworkOperation class provides common operations for network protocols. More...

#include <qnetworkprotocol.h>

Inherits QObject.

List of all member functions.

Public Members

  • QNetworkOperation ( QNetworkProtocol::Operation operation, const QString & arg0, const QString & arg1, const QString & arg2 )
  • QNetworkOperation ( QNetworkProtocol::Operation operation, const QByteArray & arg0, const QByteArray & arg1, const QByteArray & arg2 )
  • ~QNetworkOperation ()
  • void setState ( QNetworkProtocol::State state )
  • void setProtocolDetail ( const QString & detail )
  • void setErrorCode ( int ec )
  • void setArg ( int num, const QString & arg )
  • void setRawArg ( int num, const QByteArray & arg )
  • QNetworkProtocol::Operation operation () const
  • QNetworkProtocol::State state () const
  • QString arg ( int num ) const
  • QByteArray rawArg ( int num ) const
  • QString protocolDetail () const
  • int errorCode () const
  • void free ()

Detailed Description

The QNetworkOperation class provides common operations for network protocols.

An object is created to describe the operation and the current state for each operation that a network protocol should process.

For a detailed description of the Qt Network Architecture and how to implement and use network protocols in Qt, see the Qt Network Documentation.

See also QNetworkProtocol and Input/Output and Networking.

Member Function Documentation

QNetworkOperation::QNetworkOperation ( QNetworkProtocol::Operation operation, const QString & arg0, const QString & arg1, const QString & arg2 )

Constructs a network operation object. operation is the type of the operation, and arg0, arg1 and arg2 are the first three arguments of the operation. The state is initialized to QNetworkProtocol::StWaiting.

See also QNetworkProtocol::Operation and QNetworkProtocol::State.

QNetworkOperation::QNetworkOperation ( QNetworkProtocol::Operation operation, const QByteArray & arg0, const QByteArray & arg1, const QByteArray & arg2 )

Constructs a network operation object. operation is the type of the operation, and arg0, arg1 and arg2 are the first three raw data arguments of the operation. The state is initialized to QNetworkProtocol::StWaiting.

See also QNetworkProtocol::Operation and QNetworkProtocol::State.

QNetworkOperation::~QNetworkOperation ()

Destructor.

QString QNetworkOperation::arg ( int num ) const

Returns the operation's num-th argument. If this argument was not already set, an empty string is returned.

Examples: network/ftpclient/ftpmainwindow.cpp and network/networkprotocol/nntp.cpp.

int QNetworkOperation::errorCode () const

Returns the error code for the last error that occurred.

Example: network/ftpclient/ftpmainwindow.cpp.

void QNetworkOperation::free ()

Sets this object to delete itself when it hasn't been used for one second.

Because QNetworkOperation pointers are passed around a lot the QNetworkProtocol generally does not have enough knowledge to delete these at the correct time. If a QNetworkProtocol doesn't need an operation any more it will call this function instead.

Note: you should never need to call the method yourself.

QNetworkProtocol::Operation QNetworkOperation::operation () const

Returns the type of the operation.

Example: network/ftpclient/ftpmainwindow.cpp.

QString QNetworkOperation::protocolDetail () const

Returns a detailed error message for the last error. This must have been set using setProtocolDetail().

Example: network/ftpclient/ftpmainwindow.cpp.

QByteArray QNetworkOperation::rawArg ( int num ) const

Returns the operation's num-th raw data argument. If this argument was not already set, an empty bytearray is returned.

void QNetworkOperation::setArg ( int num, const QString & arg )

Sets the network operation's num-th argument to arg.

void QNetworkOperation::setErrorCode ( int ec )

Sets the error code to ec.

If the operation failed, the protocol should set an error code to describe the error in more detail. If possible, one of the error codes defined in QNetworkProtocol should be used.

See also setProtocolDetail() and QNetworkProtocol::Error.

void QNetworkOperation::setProtocolDetail ( const QString & detail )

If the operation failed, the error message can be specified as detail.

void QNetworkOperation::setRawArg ( int num, const QByteArray & arg )

Sets the network operation's num-th raw data argument to arg.

void QNetworkOperation::setState ( QNetworkProtocol::State state )

Sets the state of the operation object. This should be done by the network protocol during processing; at the end it should be set to QNetworkProtocol::StDone or QNetworkProtocol::StFailed, depending on success or failure.

See also QNetworkProtocol::State.

QNetworkProtocol::State QNetworkOperation::state () const

Returns the state of the operation. You can determine whether an operation is still waiting to be processed, is being processed, has been processed successfully, or failed.

Example: network/ftpclient/ftpmainwindow.cpp.

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


QNetworkOperation Member List

Complete Member List for QNetworkOperation

This is the complete list of member functions for QNetworkOperation, including inherited members.

  • QNetworkOperation()
  • ~QNetworkOperation()
  • arg()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • errorCode()
  • event()
  • eventFilter()
  • free()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • operation()
  • parent()
  • property()
  • protocolDetail()
  • queryList()
  • rawArg()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setArg()
  • setErrorCode()
  • setName()
  • setProperty()
  • setProtocolDetail()
  • setRawArg()
  • setState()
  • signalsBlocked()
  • startTimer()
  • state()
  • timerEvent()
  • tr()
  • trUtf8()


QNetworkProtocol Class

QNetworkProtocol Class Reference

The QNetworkProtocol class provides a common API for network protocols. More...

#include <qnetworkprotocol.h>

Inherits QObject.

Inherited by QFtp, QHttp and QLocalFs.

List of all member functions.

Public Members

  • enum State { StWaiting = 0, StInProgress, StDone, StFailed, StStopped }
  • enum Operation { OpListChildren = 1, OpMkDir = 2, OpMkdir = OpMkDir, OpRemove = 4, OpRename = 8, OpGet = 32, OpPut = 64 }
  • enum ConnectionState { ConHostFound, ConConnected, ConClosed }
  • enum Error { NoError = 0, ErrValid, ErrUnknownProtocol, ErrUnsupported, ErrParse, ErrLoginIncorrect, ErrHostNotFound, ErrListChildren, ErrListChlidren = ErrListChildren, ErrMkDir, ErrMkdir = ErrMkDir, ErrRemove, ErrRename, ErrGet, ErrPut, ErrFileNotExisting, ErrPermissionDenied }
  • QNetworkProtocol ()
  • virtual ~QNetworkProtocol ()
  • virtual void setUrl ( QUrlOperator * u )
  • virtual void setAutoDelete ( bool b, int i = 10000 )
  • bool autoDelete () const
  • virtual int supportedOperations () const
  • virtual void addOperation ( QNetworkOperation * op )
  • QUrlOperator * url () const
  • QNetworkOperation * operationInProgress () const
  • virtual void clearOperationQueue ()
  • virtual void stop ()

Signals

  • void data ( const QByteArray & data, QNetworkOperation * op )
  • void connectionStateChanged ( int state, const QString & data )
  • void finished ( QNetworkOperation * op )
  • void start ( QNetworkOperation * op )
  • void newChildren ( const QValueList<QUrlInfo> & i, QNetworkOperation * op )
  • void newChild ( const QUrlInfo & i, QNetworkOperation * op )
  • void createdDirectory ( const QUrlInfo & i, QNetworkOperation * op )
  • void removed ( QNetworkOperation * op )
  • void itemChanged ( QNetworkOperation * op )
  • void dataTransferProgress ( int bytesDone, int bytesTotal, QNetworkOperation * op )

Static Public Members

  • void registerNetworkProtocol ( const QString & protocol, QNetworkProtocolFactoryBase * protocolFactory )
  • QNetworkProtocol * getNetworkProtocol ( const QString & protocol )
  • bool hasOnlyLocalFileSystem ()

Protected Members

  • virtual void operationListChildren ( QNetworkOperation * op )
  • virtual void operationMkDir ( QNetworkOperation * op )
  • virtual void operationRemove ( QNetworkOperation * op )
  • virtual void operationRename ( QNetworkOperation * op )
  • virtual void operationGet ( QNetworkOperation * op )
  • virtual void operationPut ( QNetworkOperation * op )
  • virtual bool checkConnection ( QNetworkOperation * op )

Detailed Description

The QNetworkProtocol class provides a common API for network protocols.

This is a base class which should be used for network protocols implementations that can then be used in Qt (e.g. in the file dialog) together with the QUrlOperator.

The easiest way to implement a new network protocol is to reimplement the operation*() methods, e.g. operationGet(), etc. Only the supported operations should be reimplemented. To specify which operations are supported, also reimplement supportedOperations() and return an int that is OR'd together using the supported operations from the QNetworkProtocol::Operation enum.

When you implement a network protocol this way, it is important to emit the correct signals. Also, always emit the finished() signal when an operation is done (on success and on failure). Qt relies on correctly emitted finished() signals.

For a detailed description of the Qt Network Architecture and how to implement and use network protocols in Qt, see the Qt Network Documentation.

See also Input/Output and Networking.

Member Type Documentation

QNetworkProtocol::ConnectionState

When the connection state of a network protocol changes it emits the signal connectionStateChanged(). The first argument is one of the following values:

  • QNetworkProtocol::ConHostFound - Host has been found.
  • QNetworkProtocol::ConConnected - Connection to the host has been established.
  • QNetworkProtocol::ConClosed - Connection has been closed.

QNetworkProtocol::Error

When an operation fails (finishes unsuccessfully), the QNetworkOperation of the operation returns an error code which has one of the following values:

  • QNetworkProtocol::NoError - No error occurred.
  • QNetworkProtocol::ErrValid - The URL you are operating on is not valid.
  • QNetworkProtocol::ErrUnknownProtocol - There is no protocol implementation available for the protocol of the URL you are operating on (e.g. if the protocol is http and no http implementation has been registered).
  • QNetworkProtocol::ErrUnsupported - The operation is not supported by the protocol.
  • QNetworkProtocol::ErrParse - The URL could not be parsed correctly.
  • QNetworkProtocol::ErrLoginIncorrect - You needed to login but the username or password is wrong.
  • QNetworkProtocol::ErrHostNotFound - The specified host (in the URL) couldn't be found.
  • QNetworkProtocol::ErrListChildren - An error occurred while listing the children (files).
  • QNetworkProtocol::ErrMkDir - An error occurred when creating a directory.
  • QNetworkProtocol::ErrRemove - An error occurred when removing a child (file).
  • QNetworkProtocol::ErrRename - An error occurred when renaming a child (file).
  • QNetworkProtocol::ErrGet - An error occurred while getting (retrieving) data.
  • QNetworkProtocol::ErrPut - An error occurred while putting (uploading) data.
  • QNetworkProtocol::ErrFileNotExisting - A file which is needed by the operation doesn't exist.
  • QNetworkProtocol::ErrPermissionDenied - Permission for doing the operation has been denied.

You should also use these error codes when implementing custom network protocols. If this is not possible, you can define your own error codes by using integer values that don't conflict with any of these values.

QNetworkProtocol::Operation

This enum lists the possible operations that a network protocol can support. supportedOperations() returns an int of these that is OR'd together. Also, the type() of a QNetworkOperation is always one of these values.

  • QNetworkProtocol::OpListChildren - List the children of a URL, e.g. of a directory.
  • QNetworkProtocol::OpMkDir - Create a directory.
  • QNetworkProtocol::OpRemove - Remove a child (e.g. a file).
  • QNetworkProtocol::OpRename - Rename a child (e.g. a file).
  • QNetworkProtocol::OpGet - Get data from a location.
  • QNetworkProtocol::OpPut - Put data to a location.

QNetworkProtocol::State

This enum contains the state that a QNetworkOperation can have.

  • QNetworkProtocol::StWaiting - The operation is in the QNetworkProtocol's queue waiting to be prcessed.
  • QNetworkProtocol::StInProgress - The operation is being processed.
  • QNetworkProtocol::StDone - The operation has been processed succesfully.
  • QNetworkProtocol::StFailed - The operation has been processed but an error occurred.
  • QNetworkProtocol::StStopped - The operation has been processed but has been stopped before it finished, and is waiting to be processed.

Member Function Documentation

QNetworkProtocol::QNetworkProtocol ()

Constructor of the network protocol base class. Does some initialization and connecting of signals and slots.

QNetworkProtocol::~QNetworkProtocol () [virtual]

Destructor.

void QNetworkProtocol::addOperation ( QNetworkOperation * op ) [virtual]

Adds the operation op to the operation queue. The operation will be processed as soon as possible. This method returns immediately.

bool QNetworkProtocol::autoDelete () const

Returns TRUE if auto-deleting is enabled; otherwise returns FALSE.

See also QNetworkProtocol::setAutoDelete().

bool QNetworkProtocol::checkConnection ( QNetworkOperation * op ) [virtual protected]

For processing operations the network protocol base class calls this method quite often. This should be reimplemented by new network protocols. It should return TRUE if the connection is OK (open); otherwise it should return FALSE. If the connection is not open the protocol should open it.

If the connection can't be opened (e.g. because you already tried but the host couldn't be found), set the state of op to QNetworkProtocol::StFailed and emit the finished() signal with this QNetworkOperation as argument.

op is the operation that needs an open connection.

Example: network/networkprotocol/nntp.cpp.

void QNetworkProtocol::clearOperationQueue () [virtual]

Clears the operation queue.

void QNetworkProtocol::connectionStateChanged ( int state, const QString & data ) [signal]

This signal is emitted whenever the state of the connection of the network protocol is changed. state describes the new state, which is one of, ConHostFound, ConConnected or ConClosed. data is a message text.

void QNetworkProtocol::createdDirectory ( const QUrlInfo & i, QNetworkOperation * op ) [signal]

This signal is emitted when mkdir() has been succesful and the directory has been created. i holds the information about the new directory. op is the pointer to the operation object which contains all the information about the operation, including the state, etc. Using op->arg( 0 ), you can get the file name of the new directory.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

void QNetworkProtocol::data ( const QByteArray & data, QNetworkOperation * op ) [signal]

This signal is emitted when new data has been received after calling get() or put(). op holds the name of the file from which data is retrieved or uploaded in its first argument, and the (raw) data in its second argument. You can get them with op->arg( 0 ) and op->rawArg( 1 ). op is the pointer to the operation object, which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator (which is used by the network protocol) emit its corresponding signal.

void QNetworkProtocol::dataTransferProgress ( int bytesDone, int bytesTotal, QNetworkOperation * op ) [signal]

This signal is emitted during the transfer of data (using put() or get()). bytesDone is how many bytes of bytesTotal have been transferred. bytesTotal may be -1, which means that the total number of bytes is not known. op is the pointer to the operation object which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

void QNetworkProtocol::finished ( QNetworkOperation * op ) [signal]

This signal is emitted when an operation finishes. This signal is always emitted, for both success and failure. op is the pointer to the operation object which contains all the information about the operation, including the state, etc. Check the state and error code of the operation object to determine whether or not the operation was successful.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

QNetworkProtocol * QNetworkProtocol::getNetworkProtocol ( const QString & protocol ) [static]

Static method to get a new instance of the network protocol protocol. For example, if you need to do some FTP operations, do the following:
    QFtp *ftp = QNetworkProtocol::getNetworkProtocol( "ftp" );
This returns a pointer to a new instance of an ftp implementation or null if no protocol for ftp was registered. The ownership of the pointer is transferred to you, so you must delete it if you don't need it anymore.

Normally you should not work directly with network protocols, so you will not need to call this method yourself. Instead, use QUrlOperator, which makes working with network protocols much more convenient.

See also QUrlOperator.

bool QNetworkProtocol::hasOnlyLocalFileSystem () [static]

Returns TRUE if the only protocol registered is for working on the local filesystem; returns FALSE if other network protocols are also registered.

void QNetworkProtocol::itemChanged ( QNetworkOperation * op ) [signal]

This signal is emitted whenever a file which is a child of this URL has been changed, e.g. by successfully calling rename(). op holds the original and the new file names in the first and second arguments, accessible with op->arg( 0 ) and op->arg( 1 ) respectively. op is the pointer to the operation object which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

void QNetworkProtocol::newChild ( const QUrlInfo & i, QNetworkOperation * op ) [signal]

This signal is emitted if a new child (file) has been read. QNetworkProtocol automatically connects it to a slot which creates a list of QUrlInfo objects (with just one QUrlInfo i) and emits the newChildren() signal with this list. op is the pointer to the operation object which contains all the information about the operation that has finished, including the state, etc.

This is just a convenience signal useful for implementing your own network protocol. In all other cases connect to the newChildren() signal with its list of QUrlInfo objects.

void QNetworkProtocol::newChildren ( const QValueList<QUrlInfo> & i, QNetworkOperation * op ) [signal]

This signal is emitted after listChildren() was called and new children (files) have been read from the list of files. i holds the information about the new children. op is the pointer to the operation object which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

When implementing your own network protocol and reading children, you usually don't read one child at once, but rather a list of them. That's why this signal takes a list of QUrlInfo objects. If you prefer to read just one child at a time you can use the convenience signal newChild(), which takes a single QUrlInfo object.

void QNetworkProtocol::operationGet ( QNetworkOperation * op ) [virtual protected]

When implementing a new network protocol, this method should be reimplemented if the protocol supports getting data; this method should then process the QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

Example: network/networkprotocol/nntp.cpp.

QNetworkOperation * QNetworkProtocol::operationInProgress () const

Returns the operation, which is being processed, or 0 of no operation is being processed at the moment.

void QNetworkProtocol::operationListChildren ( QNetworkOperation * op ) [virtual protected]

When implementing a new network protocol, this method should be reimplemented if the protocol supports listing children (files); this method should then process this QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

Example: network/networkprotocol/nntp.cpp.

void QNetworkProtocol::operationMkDir ( QNetworkOperation * op ) [virtual protected]

When implementing a new network protocol, this method should be reimplemented if the protocol supports making directories; this method should then process this QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

void QNetworkProtocol::operationPut ( QNetworkOperation * op ) [virtual protected]

When implementing a new network protocol, this method should be reimplemented if the protocol supports putting (uploading) data; this method should then process the QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

void QNetworkProtocol::operationRemove ( QNetworkOperation * op ) [virtual protected]

When implementing a new network protocol, this method should be reimplemented if the protocol supports removing children (files); this method should then process this QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which is describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

void QNetworkProtocol::operationRename ( QNetworkOperation * op ) [virtual protected]

When implementing a new newtork protocol, this method should be reimplemented if the protocol supports renaming children (files); this method should then process this QNetworkOperation.

When you reimplement this method it's very important that you emit the correct signals at the correct time (especially the finished() signal after processing an operation). Take a look at the Qt Network Documentation which describes in detail how to reimplement this method. You may also want to look at the example implementation in examples/network/networkprotocol/nntp.cpp.

op is the pointer to the operation object which contains all the information on the operation that has finished, including the state, etc.

void QNetworkProtocol::registerNetworkProtocol ( const QString & protocol, QNetworkProtocolFactoryBase * protocolFactory ) [static]

Static method to register a network protocol for Qt. For example, if you have an implementation of NNTP (called Nntp) which is derived from QNetworkProtocol, call:
    QNetworkProtocol::registerNetworkProtocol( "nntp", new QNetworkProtocolFactory<Nntp> );
after which your implementation is registered for future nntp operations.

The name of the protocol is given in protocol and a pointer to the protocol factory is given in protocolFactory.

void QNetworkProtocol::removed ( QNetworkOperation * op ) [signal]

This signal is emitted when remove() has been succesful and the file has been removed. op holds the file name of the removed file in the first argument, accessible with op->arg( 0 ). op is the pointer to the operation object which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

void QNetworkProtocol::setAutoDelete ( bool b, int i = 10000 ) [virtual]

Because it's sometimes hard to take care of removing network protocol instances, QNetworkProtocol provides an auto-delete mechanism. If you set b to TRUE, the network protocol instance is removed after it has been inactive for i milliseconds (i.e. i milliseconds after the last operation has been processed). If you set b to FALSE the auto-delete mechanism is switched off.

If you switch on auto-delete, the QNetworkProtocol also deletes its QUrlOperator.

void QNetworkProtocol::setUrl ( QUrlOperator * u ) [virtual]

Sets the QUrlOperator, on which the protocol works, to u.

See also QUrlOperator.

void QNetworkProtocol::start ( QNetworkOperation * op ) [signal]

Some operations (such as listChildren()) emit this signal when they start processing the operation. op is the pointer to the operation object which contains all the information about the operation, including the state, etc.

When a protocol emits this signal, QNetworkProtocol is smart enough to let the QUrlOperator, which is used by the network protocol, emit its corresponding signal.

void QNetworkProtocol::stop () [virtual]

Stops the current operation that is being processed and clears all waiting operations.

int QNetworkProtocol::supportedOperations () const [virtual]

Returns an int that is OR'd together using the enum values of QNetworkProtocol::Operation, which describes which operations are supported by the network protocol. Should be reimplemented by new network protocols.

Example: network/networkprotocol/nntp.cpp.

QUrlOperator * QNetworkProtocol::url () const

Returns the QUrlOperator on which the protocol works.

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


qnetworkprotocol.h Include File

qnetworkprotocol.h

This is the verbatim text of the qnetworkprotocol.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qnetworkprotocol.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QNetworkProtocol class
**
** Created : 950429
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QNETWORKPROTOCOL_H
#define QNETWORKPROTOCOL_H

#ifndef QT_H
#include "qurlinfo.h"
#include "qstring.h"
#include "qdict.h"
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_NETWORKPROTOCOL

class QNetworkProtocol;
class QNetworkOperation;
class QTimer;
class QUrlOperator;
class QNetworkProtocolPrivate;
template <class T> class QValueList;

class Q_EXPORT QNetworkProtocolFactoryBase
{
public:
   virtual QNetworkProtocol *createObject() = 0;

};

template< class Protocol >
class QNetworkProtocolFactory : public QNetworkProtocolFactoryBase
{
public:
    QNetworkProtocol *createObject() {
    return new Protocol;
    }

};

typedef QDict< QNetworkProtocolFactoryBase > QNetworkProtocolDict;

class Q_EXPORT QNetworkProtocol : public QObject
{
    Q_OBJECT

public:
    enum State {
    StWaiting = 0,
    StInProgress,
    StDone,
    StFailed,
    StStopped
    };

    enum Operation {
    OpListChildren = 1,
    OpMkDir = 2,
    OpMkdir = OpMkDir, // ### remove in 4.0
    OpRemove = 4,
    OpRename = 8,
    OpGet = 32,
    OpPut = 64
    };

    enum ConnectionState {
    ConHostFound,
    ConConnected,
    ConClosed
    };

    enum Error {
    // no error
    NoError = 0,
    // general errors
    ErrValid,
    ErrUnknownProtocol,
    ErrUnsupported,
    ErrParse,
    // errors on connect
    ErrLoginIncorrect,
    ErrHostNotFound,
    // protocol errors
    ErrListChildren,
    ErrListChlidren = ErrListChildren, // ### remove in 4.0
    ErrMkDir,
    ErrMkdir = ErrMkDir, // ### remove in 4.0
    ErrRemove,
    ErrRename,
    ErrGet,
    ErrPut,
    ErrFileNotExisting,
    ErrPermissionDenied
    };

    QNetworkProtocol();
    virtual ~QNetworkProtocol();

    virtual void setUrl( QUrlOperator *u );

    virtual void setAutoDelete( bool b, int i = 10000 );
    bool autoDelete() const;

    static void registerNetworkProtocol( const QString &protocol,
                     QNetworkProtocolFactoryBase *protocolFactory );
    static QNetworkProtocol *getNetworkProtocol( const QString &protocol );
    static bool hasOnlyLocalFileSystem();

    virtual int supportedOperations() const;
    virtual void addOperation( QNetworkOperation *op );

    QUrlOperator *url() const;
    QNetworkOperation *operationInProgress() const;
    virtual void clearOperationQueue();
    virtual void stop();

signals:
    void data( const QByteArray &, QNetworkOperation *res );
    void connectionStateChanged( int state, const QString &data );
    void finished( QNetworkOperation *res );
    void start( QNetworkOperation *res );
    void newChildren( const QValueList<QUrlInfo> &, QNetworkOperation *res );
    void newChild( const QUrlInfo &, QNetworkOperation *res );
    void createdDirectory( const QUrlInfo &, QNetworkOperation *res );
    void removed( QNetworkOperation *res );
    void itemChanged( QNetworkOperation *res );
    void dataTransferProgress( int bytesDone, int bytesTotal, QNetworkOperation *res );

protected:
    virtual void processOperation( QNetworkOperation *op );
    virtual void operationListChildren( QNetworkOperation *op );
    virtual void operationMkDir( QNetworkOperation *op );
    virtual void operationRemove( QNetworkOperation *op );
    virtual void operationRename( QNetworkOperation *op );
    virtual void operationGet( QNetworkOperation *op );
    virtual void operationPut( QNetworkOperation *op );
    virtual void operationPutChunk( QNetworkOperation *op );
    virtual bool checkConnection( QNetworkOperation *op );

private:
    QNetworkProtocolPrivate *d;

private slots:
    void processNextOperation( QNetworkOperation *old );
    void startOps();
    void emitNewChildren( const QUrlInfo &i, QNetworkOperation *op );

    void removeMe();

};

class QNetworkOperationPrivate;

class Q_EXPORT QNetworkOperation : public QObject
{
    Q_OBJECT
    friend class QUrlOperator;

public:
    QNetworkOperation( QNetworkProtocol::Operation operation,
            const QString &arg0, const QString &arg1,
            const QString &arg2 );
    QNetworkOperation( QNetworkProtocol::Operation operation,
            const QByteArray &arg0, const QByteArray &arg1,
            const QByteArray &arg2 );
    ~QNetworkOperation();

    void setState( QNetworkProtocol::State state );
    void setProtocolDetail( const QString &detail );
    void setErrorCode( int ec );
    void setArg( int num, const QString &arg );
    void setRawArg( int num, const QByteArray &arg );

    QNetworkProtocol::Operation operation() const;
    QNetworkProtocol::State state() const;
    QString arg( int num ) const;
    QByteArray rawArg( int num ) const;
    QString protocolDetail() const;
    int errorCode() const;

    void free();

private slots:
    void deleteMe();

private:
    QByteArray &raw( int num ) const;
    QNetworkOperationPrivate *d;

};

#endif // QT_NO_NETWORKPROTOCOL

#endif // QNETWORKPROTOCOL_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QNetworkProtocol Member List

Complete Member List for QNetworkProtocol

This is the complete list of member functions for QNetworkProtocol, including inherited members.

  • QNetworkProtocol()
  • ~QNetworkProtocol()
  • addOperation()
  • autoDelete()
  • blockSignals()
  • checkConnectArgs()
  • checkConnection()
  • child()
  • childEvent()
  • children()
  • className()
  • clearOperationQueue()
  • connect()
  • connectNotify()
  • connectionStateChanged()
  • createdDirectory()
  • customEvent()
  • data()
  • dataTransferProgress()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • finished()
  • getNetworkProtocol()
  • hasOnlyLocalFileSystem()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemChanged()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • newChild()
  • newChildren()
  • normalizeSignalSlot()
  • objectTrees()
  • operationGet()
  • operationInProgress()
  • operationListChildren()
  • operationMkDir()
  • operationPut()
  • operationRemove()
  • operationRename()
  • parent()
  • property()
  • queryList()
  • registerNetworkProtocol()
  • removeChild()
  • removeEventFilter()
  • removed()
  • sender()
  • setAutoDelete()
  • setName()
  • setProperty()
  • setUrl()
  • signalsBlocked()
  • start()
  • startTimer()
  • stop()
  • supportedOperations()
  • timerEvent()
  • tr()
  • trUtf8()
  • url()


qnp.h Include File

qnp.h

This is the verbatim text of the qnp.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qnp.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Qt extension classes for Netscape Plugin support.
**
** Created : 970601
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QNP_H
#define QNP_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

struct _NPInstance;
struct _NPStream;
class QNPInstance;

class QNPStream {
public:
    ~QNPStream();

    const char* url() const;
    uint end() const;
    uint lastModified() const;

    const char* type() const;
    bool seekable() const;
    bool okay() const;
    bool complete() const;

    void requestRead(int offset, uint length);
    int write( int len, void* buffer );

    QNPInstance* instance() { return inst; }
    QNPStream(QNPInstance*,const char*,_NPStream*,bool);
    void setOkay(bool);
    void setComplete(bool);

private:
    QNPInstance* inst;
    _NPStream* stream;
    QString mtype;
    int seek:1;
    int isokay:1;
    int iscomplete:1;
};

class QNPWidget : public QWidget {
    Q_OBJECT
public:
    QNPWidget();
    ~QNPWidget();

    void setWindow(bool);
    void unsetWindow();
    virtual void enterInstance();
    virtual void leaveInstance();

    QNPInstance* instance();

private:
    WId saveWId;
    _NPInstance* pi;
};

class QNPInstance : public QObject {
    Q_OBJECT
public:
    ~QNPInstance();

    // Arguments passed to EMBED
    int argc() const;
    const char* argn(int) const;
    const char* argv(int) const;
    enum Reason {
        ReasonDone = 0,
        ReasonBreak = 1,
        ReasonError = 2,
        ReasonUnknown = -1
    };
    const char* arg(const char* name) const;
    enum InstanceMode { Embed=1, Full=2, Background=3 };
    InstanceMode mode() const;

    // The browser's name
    const char* userAgent() const;

    // Your window.
    virtual QNPWidget* newWindow();
    QNPWidget* widget();

    // Incoming streams (SRC=... tag).
    // Defaults ignore data.
    enum StreamMode { Normal=1, Seek=2, AsFile=3, AsFileOnly=4 };
    virtual bool newStreamCreated(QNPStream*, StreamMode& smode);
    virtual int writeReady(QNPStream*);
    virtual int write(QNPStream*, int offset, int len, void* buffer);
    virtual void streamDestroyed(QNPStream*);

    void status(const char* msg);
    void getURLNotify(const char* url, const char* window=0, void*data=0);

    void getURL(const char* url, const char* window=0);
    void postURL(const char* url, const char* window,
         uint len, const char* buf, bool file);

    QNPStream* newStream(const char* mimetype, const char* window,
    bool as_file=FALSE);
    virtual void streamAsFile(QNPStream*, const char* fname);

    void* getJavaPeer() const;

    virtual void notifyURL(const char* url, Reason r, void* notifyData);
    virtual bool printFullPage();
    virtual void print(QPainter*);

protected:
    QNPInstance();

private:
    friend class QNPStream;
    _NPInstance* pi;
};

class QNPlugin {
public:
    // Write this to return your QNPlugin derived class.
    static QNPlugin* create();

    static QNPlugin* actual();

    virtual ~QNPlugin();

    void getVersionInfo(int& plugin_major, int& plugin_minor,
         int& browser_major, int& browser_minor);

    virtual QNPInstance* newInstance()=0;
    virtual const char* getMIMEDescription() const=0;
    virtual const char* getPluginNameString() const=0;
    virtual const char* getPluginDescriptionString() const=0;

    virtual void* getJavaClass();
    virtual void unuseJavaClass();
    void* getJavaEnv() const;

protected:
    QNPlugin();
};

#endif  // QNP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QNPInstance Class

QNPInstance Class Reference

The QNPInstance class provides a QObject that is a Web-browser plugin.

This class is part of the Qt NSPlugin Extension. More...

#include <qnp.h>

Inherits QObject.

List of all member functions.

Public Members

  • ~QNPInstance ()
  • int argc () const
  • const char * argn ( int i ) const
  • const char * argv ( int i ) const
  • enum Reason { ReasonDone = 0, ReasonBreak = 1, ReasonError = 2, ReasonUnknown = -1 }
  • const char * arg ( const char * name ) const
  • enum InstanceMode { Embed = 1, Full = 2, Background = 3 }
  • InstanceMode mode () const
  • const char * userAgent () const
  • virtual QNPWidget * newWindow ()
  • QNPWidget * widget ()
  • enum StreamMode { Normal = 1, Seek = 2, AsFile = 3, AsFileOnly = 4 }
  • virtual bool newStreamCreated ( QNPStream *, StreamMode & smode )
  • virtual int writeReady ( QNPStream * )
  • virtual int write ( QNPStream *, int offset, int len, void * buffer )
  • virtual void streamDestroyed ( QNPStream * )
  • void status ( const char * msg )
  • void getURLNotify ( const char * url, const char * window = 0, void * data = 0 )
  • void getURL ( const char * url, const char * window = 0 )
  • void postURL ( const char * url, const char * window, uint len, const char * buf, bool file )
  • QNPStream * newStream ( const char * mimetype, const char * window, bool as_file = FALSE )
  • virtual void streamAsFile ( QNPStream *, const char * fname )
  • void * getJavaPeer () const
  • virtual void notifyURL ( const char * url, Reason r, void * notifyData )
  • virtual bool printFullPage ()
  • virtual void print ( QPainter * )

Protected Members

  • QNPInstance ()

Detailed Description

This class is defined in the Qt NSPlugin Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QNPInstance class provides a QObject that is a Web-browser plugin.

Deriving from QNPInstance creates an object that represents a single <EMBED> tag in an HTML document.

The QNPInstance is responsible for creating an appropriate window if required (not all plugins have windows), and for interacting with the input/output facilities intrinsic to plugins.

Note that there is absolutely no guarantee regarding the order in which functions are called. Sometimes the browser will call newWindow() first, at other times, newStreamCreated() will be called first (assuming the <EMBED> tag has a SRC parameter).

None of Qt's GUI functionality may be used until after the first call to newWindow(). This includes any use of QPaintDevice (ie. QPixmap, QWidget, and all subclasses), QApplication, anything related to QPainter (QBrush, etc.), fonts, QMovie, QToolTip, etc. Useful classes which specifically can be used are QImage, QFile, and QBuffer.

This restriction can easily be accommodated by structuring your plugin so that the task of the QNPInstance is to gather data, while the task of the QNPWidget is to provide a graphical interface to that data,

Member Type Documentation

QNPInstance::InstanceMode

This enum type provides Qt-style names for three #defines in npapi.h:

  • QNPInstance::Embed - corresponds to NP_EMBED
  • QNPInstance::Full - corresponds to NP_FULL
  • QNPInstance::Background - corresponds to NP_BACKGROUND

QNPInstance::Reason

  • QNPInstance::ReasonDone
  • QNPInstance::ReasonBreak
  • QNPInstance::ReasonError
  • QNPInstance::ReasonUnknown

QNPInstance::StreamMode

  • QNPInstance::Normal
  • QNPInstance::Seek
  • QNPInstance::AsFile
  • QNPInstance::AsFileOnly

Member Function Documentation

QNPInstance::QNPInstance () [protected]

Creates a QNPInstance.

Can only be called from within a derived class created within QNPlugin::newInstance().

QNPInstance::~QNPInstance ()

Called when the plugin instance is about to disappear.

const char * QNPInstance::arg ( const char * name ) const

Returns the value of the named arguments, or 0 if no argument called name appears in the <EMBED> tag of this instance. If the argument appears, but has no value assigned, the empty string is returned. In summary:

Tag | Result
<EMBED ...> | arg("FOO") == 0
<EMBED FOO ...> | arg("FOO") == ""
<EMBED FOO=BAR ...> | arg("FOO") == "BAR"

int QNPInstance::argc () const

Returns the number of arguments to the instance. Note that you should not normally rely on the ordering of arguments, and also note that the SGML specification does not permit multiple arguments with the same name.

See also arg().

const char * QNPInstance::argn ( int i ) const

Returns the name of the i-th argument. See argc().

const char * QNPInstance::argv ( int i ) const

Returns the value of the i-th argument. See argc().

void * QNPInstance::getJavaPeer () const

Returns the Java object associated with the plug-in instance, an object of the plug-in's Java class, or 0 if the plug-in does not have a Java class, Java is disabled, or an error occurred.

The return value is actually a jref we use void* so as to avoid burdening plugins which do not require Java.

See also QNPlugin::getJavaClass() and QNPlugin::getJavaEnv().

void QNPInstance::getURL ( const char * url, const char * window = 0 )

Requests that the url be retrieved and sent to the named window. See Netscape's JavaScript documentation for an explanation of window names.

void QNPInstance::getURLNotify ( const char * url, const char * window = 0, void * data = 0 )

Print the instance full-page. By default, this returns FALSE, causing the browser to call the (embedded) print() function instead. Requests that the given url be retrieved and sent to the named window. See Netscape's JavaScript documentation for an explanation of window names. Passes the arguments including data to NPN_GetURLNotify.

Netscape: NPN_GetURLNotify method

InstanceMode QNPInstance::mode () const

Returns the mode of the plugin.

QNPStream * QNPInstance::newStream ( const char * mimetype, const char * window, bool as_file = FALSE )

This function is under development and is subject to change.

This function is not tested.

Requests the creation of a new data stream from the plug-in. The mime type and window are passed in mimetype and window. as_file holds the AsFileOnly flag. It is an interface to the NPN_NewStream function of the Netscape Plugin API.

bool QNPInstance::newStreamCreated ( QNPStream *, StreamMode & smode ) [virtual]

This function is called when a new stream has been created. The instance should return TRUE if it accepts the processing of the stream. If the instance requires the stream as a file, it should set smode to AsFileOnly, in which case the data will be delivered some time later to the streamAsFile() function. Otherwise, the data will be delivered in chunks to the write() function which must consume at least as much data as was returned by the most recent call to writeReady().

Note that the AsFileOnly method is not supported by Netscape 2.0 and MSIE 3.0.

QNPWidget * QNPInstance::newWindow () [virtual]

Called at most once, at some time after the QNPInstance is created. If the plugin requires a window, this function should return a derived class of QNPWidget that provides the required interface.

Example: grapher/grapher.cpp.

void QNPInstance::notifyURL ( const char * url, Reason r, void * notifyData ) [virtual]

This function is under development and is subject to change.

This function is not tested.

Called whenever a url is notified after a call to NPN_GetURLNotify with notifyData. The reason is given in r.

It is an encapsulation of the NPP_URLNotify function of the Netscape Plugin API.

See also: Netscape: NPP_URLNotify method

void QNPInstance::postURL ( const char * url, const char * window, uint len, const char * buf, bool file )

This function is under development and is subject to change.

This function is not tested.

It is an interface to the NPN_PostURL function of the Netscape Plugin API.

Passes url, window, buf, len, and file to NPN_PostURL.

void QNPInstance::print ( QPainter * ) [virtual]

This function is under development and is subject to change.

This function is not tested.

Print the instance embedded in a page.

It is an encapsulation of the NPP_Print function of the Netscape Plugin API.

bool QNPInstance::printFullPage () [virtual]

This function is under development and is subject to change.

This function is not tested.

It is an encapsulation of the NPP_Print function of the Netscape Plugin API.

void QNPInstance::status ( const char * msg )

Sets the status message in the browser containing this instance to msg.

void QNPInstance::streamAsFile ( QNPStream *, const char * fname ) [virtual]

Called when a stream is delivered as a single file called fname rather than as chunks. This may be simpler for a plugin to deal with, but precludes any incremental behavior.

Note that the AsFileOnly method is not supported by Netscape 2.0 and MSIE 3.0.

See also newStreamCreated() and newStream().

void QNPInstance::streamDestroyed ( QNPStream * ) [virtual]

Called when a stream is destroyed. At this point, the stream may be complete() and okay(). If it is not okay(), then an error has occurred. If it is okay(), but not complete(), then the user has cancelled the transmission: do not give an error message in this case.

const char * QNPInstance::userAgent () const

Returns the user agent (browser name) containing this instance.

QNPWidget * QNPInstance::widget ()

Returns the plugin window created by newWindow(), if any.

int QNPInstance::write ( QNPStream *, int offset, int len, void * buffer ) [virtual]

Called when incoming data is available for processing by the instance. The instance must consume at least the amount that it returned in the most recent call to writeReady(), but it may consume up to the amount given by len. buffer is the data available for consumption. The offset argument is merely an informational value indicating the total amount of data that has been consumed in prior calls.

This function should return the amount of data actually consumed.

Example: grapher/grapher.cpp.

int QNPInstance::writeReady ( QNPStream * ) [virtual]

Returns the minimum amount of data the instance is willing to receive from the given stream.

The default returns a very large value.

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


QNPInstance Member List

Complete Member List for QNPInstance

This is the complete list of member functions for QNPInstance, including inherited members.

  • QNPInstance()
  • ~QNPInstance()
  • arg()
  • argc()
  • argn()
  • argv()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • getJavaPeer()
  • getURL()
  • getURLNotify()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • mode()
  • name()
  • newStream()
  • newStreamCreated()
  • newWindow()
  • normalizeSignalSlot()
  • notifyURL()
  • objectTrees()
  • parent()
  • postURL()
  • print()
  • printFullPage()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • status()
  • streamAsFile()
  • streamDestroyed()
  • timerEvent()
  • tr()
  • trUtf8()
  • userAgent()
  • widget()
  • write()
  • writeReady()


QNPlugin Class

QNPlugin Class Reference

The QNPlugin class provides the plugin central factory.

This class is part of the Qt NSPlugin Extension. More...

#include <qnp.h>

List of all member functions.

Public Members

  • virtual ~QNPlugin ()
  • void getVersionInfo ( int & plugin_major, int & plugin_minor, int & browser_major, int & browser_minor )
  • virtual QNPInstance * newInstance () = 0
  • virtual const char * getMIMEDescription () const = 0
  • virtual const char * getPluginNameString () const = 0
  • virtual const char * getPluginDescriptionString () const = 0
  • virtual void * getJavaClass ()
  • virtual void unuseJavaClass ()
  • void * getJavaEnv () const

Static Public Members

  • QNPlugin * create ()
  • QNPlugin * actual ()

Protected Members

  • QNPlugin ()

Detailed Description

This class is defined in the Qt NSPlugin Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QNPlugin class provides the plugin central factory.

This class is the heart of the plugin. One instance of this object is created when the plugin is first needed, by calling QNPlugin::create(), which must be implemented in your plugin code to return some derived class of QNPlugin. The one QNPlugin object creates all instances for a single running Web-browser process.

Additionally, if Qt is linked to the plugin as a dynamic library, only one instance of QApplication will exist across all plugins that have been made with Qt. So, your plugin should tread lightly on global settings - do not, for example, use QApplication::setFont() - that will change the font in every widget of every Qt-based plugin currently loaded!

Member Function Documentation

QNPlugin::QNPlugin () [protected]

Creates a QNPlugin. This may only be used by the constructor derived class returned by the plugin's implementation of the QNPlugin::create() function.

QNPlugin::~QNPlugin () [virtual]

Destroys the QNPlugin. This is called by the plugin binding code just before the plugin is about to be unloaded from memory. If newWindow() has been called, a QApplication will still exist at this time, but will be deleted shortly after before the plugin is deleted.

QNPlugin * QNPlugin::actual () [static]

Returns the plugin most recently returned by QNPlugin::create().

QNPlugin * QNPlugin::create () [static]

This must be implemented by your plugin code. It should return a derived class of QNPlugin.

void * QNPlugin::getJavaClass () [virtual]

Override to return a reference to the Java class that represents the plugin. The default returns 0, indicating no class.

If you override this class, you must also override QNPlugin::unuseJavaClass().

The return value is actually a jref; we use void* so as to avoid burdening plugins which do not require Java.

See also getJavaEnv() and QNPInstance::getJavaPeer().

void * QNPlugin::getJavaEnv () const

Returns a pointer to the Java execution environment, or 0 if Java is disabled or an error occurred.

The return value is actually a JRIEnv*; we use void* so as to avoid burdening plugins which do not require Java.

See also getJavaClass() and QNPInstance::getJavaPeer().

const char * QNPlugin::getMIMEDescription () const [pure virtual]

Override this to return the MIME description of the data formats supported by your plugin. The format of this string is shown by the following example:

    const char* getMIMEDescription() const
    {
        return "image/x-png:png:PNG Image;"
               "image/png:png:PNG Image;"
               "image/x-portable-bitmap:pbm:PBM Image;"
               "image/x-portable-graymap:pgm:PGM Image;"
               "image/x-portable-pixmap:ppm:PPM Image;"
               "image/bmp:bmp:BMP Image;"
               "image/x-ms-bmp:bmp:BMP Image;"
               "image/x-xpixmap:xpm:XPM Image;"
               "image/xpm:xpm:XPM Image";
    }

const char * QNPlugin::getPluginDescriptionString () const [pure virtual]

Returns the plain-text description of the plugin.

const char * QNPlugin::getPluginNameString () const [pure virtual]

Returns the plain-text name of the plugin.

void QNPlugin::getVersionInfo ( int & plugin_major, int & plugin_minor, int & browser_major, int & browser_minor )

Populates *plugin_major and *plugin_minor with the version of the plugin API and populates *browser_major and *browser_minor with the version of the browser.

QNPInstance * QNPlugin::newInstance () [pure virtual]

Override this to return an appropriate derived class of QNPInstance.

void QNPlugin::unuseJavaClass () [virtual]

This function is called when the plugin is shutting down, with jc set to the value returned earlier by getJavaClass(). The function should unuse the Java class.

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


QNPlugin Member List

Complete Member List for QNPlugin

This is the complete list of member functions for QNPlugin, including inherited members.

  • QNPlugin()
  • ~QNPlugin()
  • actual()
  • create()
  • getJavaClass()
  • getJavaEnv()
  • getMIMEDescription()
  • getPluginDescriptionString()
  • getPluginNameString()
  • getVersionInfo()
  • newInstance()
  • unuseJavaClass()


QNPStream Class

QNPStream Class Reference

The QNPStream class provides a stream of data provided to a QNPInstance by the browser.

This class is part of the Qt NSPlugin Extension. More...

#include <qnp.h>

List of all member functions.

Public Members

  • ~QNPStream ()
  • const char * url () const
  • uint end () const
  • uint lastModified () const
  • const char * type () const
  • bool seekable () const
  • bool okay () const
  • bool complete () const
  • void requestRead ( int offset, uint length )
  • int write ( int len, void * buffer )
  • QNPInstance * instance ()
  • QNPStream ( QNPInstance * in, const char * mt, _NPStream * st, bool se )

Detailed Description

This class is defined in the Qt NSPlugin Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QNPStream class provides a stream of data provided to a QNPInstance by the browser.

Note that this is neither a QTextStream nor a QDataStream.

See also QNPInstance::write() and QNPInstance::newStreamCreated().

Member Function Documentation

QNPStream::QNPStream ( QNPInstance * in, const char * mt, _NPStream * st, bool se )

Creates a stream. Plugins should not call this, but rather QNPInstance::newStream() if a stream is required.

Takes a QNPInstance in, mime type mt, a pointer to an _NPStream st and a seekable flag se.

QNPStream::~QNPStream ()

Destroys the stream.

bool QNPStream::complete () const

Returns TRUE if the stream has received all the data from the source; otherwise returns FALSE.

uint QNPStream::end () const

Returns the length of the stream in bytes. Can be 0 for streams of unknown length.

QNPInstance * QNPStream::instance ()

Returns the QNPInstance for which this stream was created.

uint QNPStream::lastModified () const

Returns the time when the source of the stream was last modified.

bool QNPStream::okay () const

Returns TRUE if no errors have occurred on the stream; otherwise returns FALSE.

void QNPStream::requestRead ( int offset, uint length )

Requests the section of the stream, of length bytes from offset, be sent to the QNPInstance::write() function of the instance() of this stream.

bool QNPStream::seekable () const

Returns TRUE if the stream is seekable; otherwise returns FALSE.

const char * QNPStream::type () const

Returns the MIME type of the stream.

const char * QNPStream::url () const

Returns the URL from which the stream was created.

int QNPStream::write ( int len, void * buffer )

Writes len bytes from buffer to the stream.

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


QNPStream Member List

Complete Member List for QNPStream

This is the complete list of member functions for QNPStream, including inherited members.

  • QNPStream()
  • ~QNPStream()
  • complete()
  • end()
  • instance()
  • lastModified()
  • okay()
  • requestRead()
  • seekable()
  • type()
  • url()
  • write()


QNPWidget Class

QNPWidget Class Reference

The QNPWidget class provides a QWidget that is a Web-browser plugin window.

This class is part of the Qt NSPlugin Extension. More...

#include <qnp.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QNPWidget ()
  • ~QNPWidget ()
  • virtual void enterInstance ()
  • virtual void leaveInstance ()
  • QNPInstance * instance ()

Detailed Description

This class is defined in the Qt NSPlugin Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QNPWidget class provides a QWidget that is a Web-browser plugin window.

Derive from QNPWidget to create a widget that can be used as a Browser plugin window, or create one and add child widgets. Instances of QNPWidget may only be created when QNPInstance::newWindow() is called by the browser.

A common way to develop a plugin widget is to develop it as a stand-alone application window, then make it a child of a plugin widget to use it as a browser plugin. The technique is:

class MyPluginWindow : public QNPWidget
{
    QWidget* child;
public:
    MyPluginWindow()
    {
        // Some widget that is normally used as a top-level widget
        child = new MyIndependentlyDevelopedWidget();

        // Use the background color of the web page
        child->setBackgroundColor( backgroundColor() );

        // Fill the plugin widget
        child->setGeometry( 0, 0, width(), height() );
    }

    void resizeEvent(QResizeEvent*)
    {
        // Fill the plugin widget
        child->resize(size());
    }
};

The default implementation is an empty window.

Member Function Documentation

QNPWidget::QNPWidget ()

Creates a QNPWidget.

QNPWidget::~QNPWidget ()

Destroys the window. This will be called by the plugin binding code when the window is no longer required. The Web-browser will delete windows when they leave the page. The bindings will change the QWidget::winId() of the window when the window is resized, but this should not affect normal widget behavior.

void QNPWidget::enterInstance () [virtual]

Called when the mouse enters the plugin window. Does nothing by default.

Example: grapher/grapher.cpp.

QNPInstance * QNPWidget::instance ()

Returns the instance for which this widget is the window.

void QNPWidget::leaveInstance () [virtual]

Called when the mouse leaves the plugin window. Does nothing by default.

Example: grapher/grapher.cpp.

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


QNPWidget Member List

Complete Member List for QNPWidget

This is the complete list of member functions for QNPWidget, including inherited members.

  • QNPWidget()
  • ~QNPWidget()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • enterInstance()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • instance()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leaveInstance()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QObject类

QObject类参考

QObject类是所有Qt对象的基类。 详情请见……

#include <qobject.h>

继承了Qt。

被QAccel、QAccessibleObject、QAction、QApplication、QDataPump、QWidget、QCanvas、QStyle、QClipboard、QCopChannel、QDns、QLayout、QDragObject、QEditorFactory、QFileIconProvider、QNetworkProtocol、QServerSocket、QWSKeyboardHandler、QNetworkOperation、QNPInstance、QObjectCleanupHandler、QProcess、QSessionManager、QSignal、QSignalMapper、QSocket、QSocketNotifier、QSound、QSqlDatabase、QSqlDriver、QSqlForm、QStyleSheet、QTimer、QToolTipGroup、QTranslator、QUrlOperator、QValidator和QWSMouseHandler继承。

所有成员函数的列表。

公有成员

  • QObject ( QObject * parent = 0, const char * name = 0 )
  • virtual ~QObject ()
  • const char * className () const
  • QString tr ( const char * sourceText, const char * comment ) const
  • QString trUtf8 ( const char * sourceText, const char * comment ) const
  • QMetaObject * metaObject () const
  • virtual bool event ( QEvent * e )
  • virtual bool eventFilter ( QObject * watched, QEvent * e )
  • bool isA ( const char * clname ) const
  • bool inherits ( const char * clname ) const
  • const char * name () const
  • const char * name ( const char * defaultName ) const
  • virtual void setName ( const char * name )
  • bool isWidgetType () const
  • bool highPriority () const
  • bool signalsBlocked () const
  • void blockSignals ( bool block )
  • int startTimer ( int interval )
  • void killTimer ( int id )
  • void killTimers ()
  • QObject * child ( const char * objName, const char * inheritsClass = 0, bool recursiveSearch = TRUE )
  • const QObjectList * children () const
  • QObjectList * queryList ( const char * inheritsClass = 0, const char * objName = 0, bool regexpMatch = TRUE, bool recursiveSearch = TRUE ) const
  • virtual void insertChild ( QObject * obj )
  • virtual void removeChild ( QObject * obj )
  • void installEventFilter ( const QObject * obj )
  • void removeEventFilter ( const QObject * obj )
  • bool connect ( const QObject * sender, const char * signal, const char * member ) const
  • bool disconnect ( const char * signal = 0, const QObject * receiver = 0, const char * member = 0 )
  • bool disconnect ( const QObject * receiver, const char * member = 0 )
  • void dumpObjectTree ()
  • void dumpObjectInfo ()
  • virtual bool setProperty ( const char * name, const QVariant & value )
  • virtual QVariant property ( const char * name ) const
  • QObject * parent () const

公有槽

  • void deleteLater ()

信号

  • void destroyed ()
  • void destroyed ( QObject * obj )

静态公有成员

  • const QObjectList * objectTrees ()
  • bool connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member )
  • bool disconnect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member )

属性

  • QCString name - 这个对象的名称

保护成员

  • const QObject * sender ()
  • virtual void timerEvent ( QTimerEvent * )
  • virtual void childEvent ( QChildEvent * )
  • virtual void customEvent ( QCustomEvent * )
  • virtual void connectNotify ( const char * signal )
  • virtual void disconnectNotify ( const char * signal )
  • virtual bool checkConnectArgs ( const char * signal, const QObject * receiver, const char * member )

静态保护成员

  • QCString normalizeSignalSlot ( const char * signalSlot )

相关函数

  • void * qt_find_obj_child ( QObject * parent, const char * type, const char * name )

详细描述

QObject类是所有Qt对象的基类。

QObject是Qt对象模型的中心。这个模型的中心特征就是一种用于无缝对象通讯的被叫做信号和槽的非常强大的机制。你能够使用connect()把信号和槽连接起来并且可以用disconnect()来破坏这种连接。为了避免从不结束的通知循环，你可以调用blockSignals()临时地阻塞信号。保护函数connectNotify()和disconnectNotify()使跟踪连接成为可能。

QObject把它们自己组织在对象树中。当你创建一个QObject作为其它对象的父对象，这个对象会在父对象中自动调用insertChild()并且可以在父对象的children()列表中显示出来。父对象拥有这个对象，比如，它将在它的析构函数中自动删除它的孩子。你可以使用child()或者queryList()通过名称和任意的类型来查找一个对象，并且使用objectTrees()来获得树根的列表。

每个对象都有一个对象名称（name()），能够报告它的类名（className()）并且它在QObject继承层次中是否继承了另一个类（inherits()）。

当对象被删除时，它发射destroyed()信号。你可以捕获这个信号来避免对QObject的摇摆引用。QGuardedPtr类提供了一种文雅的方式来使用这个机制。

QObject可以通过event()接收事件并且过滤其它对象的事件。详细情况请参考installEventFilter()和eventFilter()。一个方便的处理者，childEvent()，能够被重新实现来捕获子对象事件。

最后但不是最不重要的一点，QObject提供了Qt中最基本的定时器，关于定时器的高级支持请参考QTimer。

注意Q_OBJECT宏对于任何实现信号、槽和属性的对象都是强制的。你也需要对源文件运行moc程序（元对象编译器）。我们强烈建议在QObject的所有子类中使用这个宏，而不管它是不是实际使用了信号、槽和属性，因为不这样做也许会导致普通函数会出现为定义的问题。

所有的Qt窗口部件继承了QObject。方便的函数isWidgetType()返回这个对象实际上是不是一个窗口部件。它比inherits( "QWidget" )快得多。

一些QObject函数，比如children()、objectTrees()和queryList()返回一个QObjectList。QObjectList是QObject的QPtrList。QObjectLists支持像QPtrLists同样的操作并且又一个迭代器类QObjectListIt。

也可以参考对象模型。

成员函数文档

QObject::QObject ( QObject * parent = 0, const char * name = 0 )

构造一个父对象为parent，叫做name的对象。

对象的父对象也许可以看做这个对象的所有者。例如，一个对话框是它包含的“OK”和“Cancel”按钮的父对象。

父对象的析构函数销毁所有的子对象。

设置parent为0时，构造一个没有父对象的对象。如果一个对象是窗口部件，它将会成为一个顶级窗口。

对象名称就是可以用来识别一个QObject的一些文本。它在和Qt设计器联合使用的时候特别有用。你可以使用child()来通过名称（和类型）找到一个对象。使用queryList()可以找到几个对象。

也可以参考parent()、name、child()和queryList()。

QObject::~QObject () [虚]

销毁这个对象，删除它的所有子对象。

到这个对象的信号和从这个对象发出的信号被自动地取消连接。

警告：所有子对象被删除。如果这些对象中的任何一个在栈中或者是全局的，迟早或稍后你的程序将会崩溃。我们不建议在父对象的外面保存值对象的指针。如果你要这么做，当对象销毁时，QObject::destroyed()信号会给你一个机会来进行检测。

void QObject::blockSignals ( bool block )

如果block为真，阻塞信号，或者如果block为假，取消信号阻塞。

如果信号被阻塞，被发射的信号消失在超空间。

实例：rot13/rot13.cpp。

bool QObject::checkConnectArgs ( const char * signal, const QObject * receiver, const char * member ) [虚 保护]

如果signal和member参数是协调的，返回真，否则返回假。（receiver参数通常被忽略。）

警告：我们建议你使用默认实现不要再重新实现这个函数。

QObject * QObject::child ( const char * objName, const char * inheritsClass = 0, bool recursiveSearch = TRUE )

搜索这个对象的子对象和任意的孙子对象，并且返回继承inheritsClass的被叫做objName的子对象。如果inheritsClass为0（默认），任何类都可以匹配。

如果recursiveSearch为真（默认），child()执行的是一个对于对象的子孙深度优先的搜索。

如果没有这样的对象，这个函数返回0。如果超过一个，所找到的第一个被返回，如果你需要它们的全部，使用queryList()。

void QObject::childEvent ( QChildEvent * ) [虚 保护]

这个事件处理器在子类中可以被重新实现来接收子对象事件。

当子对象被插入或移除，子对象事件被发送给对象。

注意事件类型（QEvent::type()）为QEvent::ChildInserted的事件被传递（通过QApplication::postEvent()）确认了子对象的构造函数在这个函数被调用之前已经完成。

如果子对象在被插入之后立即被移除，ChildInserted事件也许被抑制，但是ChildRemoved事件总是被发送。在这种情况下，一个ChildRemoved事件没有一个相对应的ChildInserted事件是可能的。

如果你基于ChildInserted事件改变状态，调用QWidget::constPolish()，或者在基于这种状态的函数中执行

        QApplication::sendPostedEvents( this, QEvent::ChildInserted );
一个著名的实例就是QWidget::sizeHint()。

也可以参考event()和QChildEvent。

在QMainWindow和QSplitter中被重新实现。

const QObjectList * QObject::children () const

返回子对象的列表，或者如果这个对象没有子对象返回0。

QObjectList类在qobjectlist.h头文件中被定义。

第一个子对象被添加为这个列表的第一个对象并且最后一个子对象被添加为这个列表的最后一个对象，比如，新的子对象被添加到列表的最后。

注意当QWidget子对象被升起或下降，列表的顺序会改变。一个被升起的窗口部件变为这个列表中的最后一个对象，并且一个被下降的窗口部件变为这个列表中的第一个对象。

也可以参考child()、queryList()、parent()、insertChild()和removeChild()。

const char * QObject::className () const

返回这个对象的类名。

这个函数是由元对象编译器生成的。

警告：如果类定义中缺少Q_OBJECT宏，这个函数就会返回错误的名称。

也可以参考name、inherits()、isA()和isWidgetType()。

实例：sql/overview/custom1/main.cpp。

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member ) [静态]

把从sender对象发送的signal和receiver对象中的member连接起来，并且如果连接成功返回真，否则返回假。

你必须在说明signal和member的时候使用SIGNAL()和SLOT()两个宏，例如：

    QLabel     *label  = new QLabel;
    QScrollBar *scroll = new QScrollBar;
    QObject::connect( scroll, SIGNAL(valueChanged(int)),
                      label,  SLOT(setNum(int)) );

这个实例确保了label总显示当前滚动条的值。

一个信号也可以被连接到另一个信号上：

    class MyWidget : public QWidget
    {
        Q_OBJECT
    public:
        MyWidget();

    signals:
        void myUsefulSignal();

    private:
        QPushButton *aButton;
    };

    MyWidget::MyWidget()
    {
        aButton = new QPushButton( this );
        connect( aButton, SIGNAL(clicked()), SIGNAL(myUsefulSignal()) );
    }

在这个实例中，MyWidget的构造函数传递一个来自私有成员变量的信号，并且使它在MyWidget的一个相关名称下可用。

一个信号可以被连接到多个槽和信号上。多个信号可以被连接到一个槽上。

如果一个信号被连接到几个槽上，当信号被发射的时候，槽被激活的顺序是任意的。

如果信号和槽被成功连接，返回真。如果它不能创建连接，返回假，例如，如果QObject不能检验signal或member的存在，或者如果它们的标签不协调。

也可以参考disconnect()。

实例：action/actiongroup/editor.cpp、action/main.cpp、addressbook/main.cpp、application/main.cpp、iconview/main.cpp、mdi/main.cpp和t2/main.cpp。

bool QObject::connect ( const QObject * sender, const char * signal, const char * member ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把从sender对象发送的signal和这个对象的member连接起来。

等于：QObject::connect(sender, signal, this, member)。

也可以参考disconnect()。

void QObject::connectNotify ( const char * signal ) [虚 保护]

当某个东西被连接到这个对象的signal时，这个虚函数被调用。

警告：这个函数违反了模块的面向对象的原则。不管如何，当你需要在某个东西连接到一个信号时执行昂贵的初始化时，这也许很有用。

也可以参考connect() and disconnectNotify().

void QObject::customEvent ( QCustomEvent * ) [虚 保护]

这个事件处理器可以在子类中重新实现来接收自定义事件。自定义事件就是至少类型值为QEvent::Type枚举变量中的“User”项的用户定义的事件，并且通常为QCustomEvent或QCustomEvent的子类。

也可以参考event()和QCustomEvent。

void QObject::deleteLater () [槽]

执行这个对象的延期删除。

不是立即删除，这个函数当Qt返回主事件循环时延期执行删除事件的处理。

void QObject::destroyed () [信号]

在对象被销毁之前，这个信号被立即发射。

在这个信号被发射之后，所有这个对象的子对象都被销毁。

void QObject::destroyed ( QObject * obj ) [信号]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在obj对象被销毁之前，这个信号被立即发射。

在这个信号被发射之后，所有这个对象的子对象都被销毁。

bool QObject::disconnect ( const QObject * sender, const char * signal, const QObject * receiver, const char * member ) [静态]

取消从sender对象发送的signal和对象receiver中的member的连接。

当这两个有关对象中的一个被销毁时，这个信号——槽连接就被移除了。

disconnect()通常被用在三种方式下，正如下面的例子所描述的。

  1. 取消连接到一个对象的信号的任何事物：
           disconnect( myObject, 0, 0, 0 );
    等于非静态重载函数
           myObject->disconnect();
  2. 取消连接到一个特定信号的任何事物：
           disconnect( myObject, SIGNAL(mySignal()), 0, 0 );
    等于非静态重载函数
           myObject->disconnect( SIGNAL(mySignal()) );
  3. 取消一个特定接收者的所有连接：
           disconnect( myObject, 0, myReceiver, 0 );
    等于非静态重载函数
           myObject->disconnect(  myReceiver );

0可以用做一个通配符，意义可能分别为“任何信号”、“任何接受对象”或者“一个接受对象中的任何槽”。

sender不能为0。（你不能在一个调用中取消来自多于一个对象的信号的连接。）

如果signal为0，它取消所有和这个对象的信号连接的receiver和member。如果不是，只由特定信号被取消联接。

如果receiver为0，它取消连接到signal的任何事物。如果不是，只有receiver中的槽被取消连接。

如果member为0，它取消连接到receiver的任何事物。如果不是，只有名为member的槽被取消联接并且其它所有槽被保留。如果receiver被省去，member必须为0，所以你不能取消所有对象中同一特定名称槽的连接。

也可以参考connect()。

bool QObject::disconnect ( const char * signal = 0, const QObject * receiver = 0, const char * member = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

取消和receiver中member连接的signal。

当这两个有关对象中的一个被销毁时，这个信号——槽连接就被移除了。

bool QObject::disconnect ( const QObject * receiver, const char * member = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

取消和receiver中member连接的这个信号中的所有信号。

当这两个有关对象中的一个被销毁时，这个信号——槽连接就被移除了。

void QObject::disconnectNotify ( const char * signal ) [虚 保护]

当和这个对象的signal连接的某个事物已经被取消联接时，这个虚函数被调用。

警告：这个函数违反了模块的面向对象的原则。不管如何，在对昂贵的资源访问进行最优化时，这个也许很有用处。

也可以参考disconnect() and connectNotify().

void QObject::dumpObjectInfo ()

调试输出这个对象的关于信号连接的消息等等。

在调试的时候这个函数很有用，但是如果库是在发布模式下（例如，没有任何调试信息）被编译的，它就不会做任何事情。

void QObject::dumpObjectTree ()

调试输出子对象树。

在调试的时候这个函数很有用，但是如果库是在发布模式下（例如，没有任何调试信息）被编译的，它就不会做任何事情。

bool QObject::event ( QEvent * e ) [虚]

这个虚函数会接收到一个对象的事件并且应该在e事件被识别和处理时返回真。

event()可以被重新实现来定义一个对象的行为。

也可以参考installEventFilter()、timerEvent()、QApplication::sendEvent()、QApplication::postEvent()和QWidget::event()。

在QWidget中被重新实现。

bool QObject::eventFilter ( QObject * watched, QEvent * e ) [虚]

如果这个对象已经被安装为watched对象的一个事件过滤器，就过滤事件。

在这个函数你的重新实现中，如果你想过滤出e事件，比如，停止它的进一步处理，返回真，否则返回假。

警告：如果你在这个函数中删除接收对象，请确认返回真。否则，Qt会把这个事件转给被删除的对象并且程序也许会崩溃。

也可以参考installEventFilter()。

在QAccel、QScrollView和QSpinBox中被重新实现。

bool QObject::highPriority () const

如果对象是一个高优先权的对象，返回真，或者如果它是一个标准优先权的对象，返回假。

高优先权对象被放置到QObject的子对象列表的开始，假设它们将被更频繁地引用。

bool QObject::inherits ( const char * clname ) const

如果这个对象是继承clname的类的实例，并且clname继承QObject，那么返回真，否则返回假。

一个类可以被认为继承了它自己。

实例：

        QTimer *t = new QTimer;         // QTimer继承QObject
        t->inherits( "QTimer" );        // 返回TRUE
        t->inherits( "QObject" );       // 返回TRUE
        t->inherits( "QButton" );       // 返回FALSE

        // QScrollBar继承QWidget和QRangeControl
        QScrollBar *s = new QScrollBar( 0 );
        s->inherits( "QWidget" );       // 返回TRUE
        s->inherits( "QRangeControl" ); // 返回FALSE

（QRangeControl不是一个QObject。）

也可以参考isA()和metaObject()。

实例：table/statistics/statistics.cpp、themes/metal.cpp和themes/wood.cpp。

void QObject::insertChild ( QObject * obj ) [虚]

插入对象obj到子对象列表中。

警告：这个函数不能被用来把一个窗口部件变为另一个窗口部件的子窗口部件。子窗口部件只能通过在构造函数中的父窗口部件参数设置来被创建或者通过调用QWidget::reparent()。

也可以参考removeChild()和QWidget::reparent()。

void QObject::installEventFilter ( const QObject * obj )

安装事件过滤器obj到这个对象。

事件过滤器就是接收所有被发送到这个对象的事件的对象。这个过滤器可以停止事件或者把它再转给这个对象。事件过滤器obj通过它的eventFilter()函数来接收事件。如果事件被过滤了（比如，停止了），eventFilter()函数必须返回真，否则它必须返回假。

如果有多个事件过滤器被安装到同一个对象上，最后一个被安装的事件过滤器将先被激活。

实例：

    #include <qwidget.h>

    class MyWidget : public QWidget
    {
        Q_OBJECT
    public:
        MyWidget( QWidget *parent = 0, const char *name = 0 );

    protected:
        bool eventFilter( QObject *, QEvent * );
    };

    MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
    {
        // 为父对象（如果有的话）安装一个过滤器
        if ( parent )
            parent->installEventFilter( this );
    }

    bool MyWidget::eventFilter( QObject *o, QEvent *e )
    {
        if ( e->type() == QEvent::KeyPress ) {
            // 对于键被按下进行特殊处理
            QKeyEvent *k = (QKeyEvent *)e;
            qDebug( "Ate key press %d", k->key() );
            return TRUE; // 吃掉了这个事件
        } else {
            // 标准事件处理
            return QWidget::eventFilter( o, e );
        }
    }

例如，QAccel类使用这种技术来截取快捷键被按下。

警告：如果在你的eventFilter()函数中你删除了接收对象，请确认返回真。否则，Qt会把这个事件转给被删除的对象并且程序也许会崩溃。

也可以参考removeEventFilter()、eventFilter()和event()。

bool QObject::isA ( const char * clname ) const

如果这个对象是clname类的实例，返回真，否则返回假。

实例：

    QTimer *t = new QTimer; // QTimer继承QObject
    t->isA( "QTimer" );     // 返回TRUE
    t->isA( "QObject" );    // 返回FALSE

也可以参考inherits()和metaObject()。

bool QObject::isWidgetType () const

如果这个对象是一个窗口部件，返回真，否则返回假。

调用这个函数等于调用inherits("QWidget")，但这个函数要快很多。

void QObject::killTimer ( int id )

通过定时器标识符id删除定时器。

当一个定时器事件开始时，定时器标识符由startTimer()返回。

也可以参考timerEvent()、startTimer()和killTimers()。

void QObject::killTimers ()

删除这个对象中已经开始的所有定时器。

警告：使用这个函数可能导致很难找到的bug：它会删除你在子类和超类中开始的定时器，这通常不是你所想要的。我们建议使用QTimer或者killTimer()。

也可以参考timerEvent()、startTimer()和killTimer()。

QMetaObject * QObject::metaObject () const

返回这个对象的元对象的指针。

元对象包含关于一个继承QObject的类的一些信息，比如，类名称、超类名称、属性、信号和槽。每个包含Q_OBJECT宏的类也都会有一个元对象。

在信号/槽连接机制和属性系统中需要元对象信息。函数isA()和inherits()也使用元对象。

const char * QObject::name () const

返回这个对象的名称。详细情况请参考“name”属性。

const char * QObject::name ( const char * defaultName ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回这个对象的名称，或者如果这个对象没有名称返回defaultName。

QCString QObject::normalizeSignalSlot ( const char * signalSlot ) [静态 保护]

通过删除不是必需的控制符号来普通化信号或槽定义signalSlot。

const QObjectList * QObject::objectTrees () [静态]

返回所有对象树的列表的指针（它们的根对象），或者如果没有对象返回0。

QObjectList类在qobjectlist.h头文件中被定义。

最近的根对象被创建为列表中的第一个对象并且第一个根对象被添加为列表的最后一个对象。

也可以参考children()、parent()、insertChild()和removeChild()。

QObject * QObject::parent () const

返回父对象的指针。

也可以参考children()。

QVariant QObject::property ( const char * name ) const [虚]

返回对象的name属性的值。

如果没有这样一个属性存在，返回变量是无效的。

关于所有可用属性的信息通过metaObject()提供。

也可以参考setProperty()、QVariant::isValid()、metaObject()、QMetaObject::propertyNames()和QMetaObject::property()。

QObjectList * QObject::queryList ( const char * inheritsClass = 0, const char * objName = 0, bool regexpMatch = TRUE, bool recursiveSearch = TRUE ) const

搜索这个对象的子对象和任意的子孙对象，并且返回继承inheritsClass的名称为objName的对象的列表。如果inheritsClass为0（默认），任何类都可以匹配。如果objName为0（默认），所有的对象名称都可以匹配。

如果regexpMatch为真（默认），objName是一个对象名称必须匹配的正则表达式。语法规则就是QRegExp。如果regexpMatch为假，objName就是对象名称必须正确匹配的字符串。

注意inheritsClass使用从QObject的单继承，方式和inherits()中的一样。根据inherits()，QMenuBar继承了QWidget，而不是QMenuData。这样也许和真是情况不太一致，但是这是使Qt能够支持更多种类编译器的最好方法。

最后，如果recursiveSearch为真（默认），queryList()就像第一代子对象那样搜索n代子孙对象。

如果所有这些看起来都比你需要的要复杂，更简单的函数child()也许是你想要的。

这里是一个人为的实例来使这个窗口中的所有按钮失效：

    QObjectList *l = topLevelWidget()->queryList( "QButton" );
    QObjectListIt it( *l ); // 遍历按钮
    QObject *obj;

    while ( (obj = it.current()) != 0 ) {
        // 对于每一个找到的对象……
        ++it;
        ((QButton*)obj)->setEnabled( FALSE );
    }
    delete l; // 删除这个列表，而不是对象

QObjectList类在qobjectlist.h头文件中被定义。

警告：你使用这个列表完成之后，就删除它。这个列表中包含的指针也许会在任何你不注意的时候失效（例如，一旦用户关闭一个窗口，你也许就得到了一个摇摆的指针）。

也可以参考child()、children()、parent()、inherits()、name和QRegExp。

void QObject::removeChild ( QObject * obj ) [虚]

从子对象列表中移除obj对象。

警告：这个函数将不会从屏幕上移除一个子窗口部件。它仅仅是从父窗口部件的子对象列表中移除它。

也可以参考insertChild()和QWidget::reparent()。

void QObject::removeEventFilter ( const QObject * obj )

从这个对象中移除事件过滤器对象obj。如果事件过滤器没有被安装，这个要求将被忽略。

当这个对象被销毁时，这个对象的所有事件过滤器都会自动地被移除。

移除事件过滤器总是安全的，甚至在事件过滤器被激活期间（比如，从eventFilter()函数中）。

也可以参考installEventFilter()、eventFilter()和event()。

const QObject * QObject::sender () [保护]

如果在任何函数调用或信号发射之前在槽中调用的话，返回发送消息的对象的指针。在所有其它情况下，返回未定义的值。

警告：在其它一些情况下，这个函数也会返回一些显然正确的东西。无论如何，在任何函数调用期间，它的值可能发生变化，取决于这次调用中什么信号—槽连接被激活。在Qt 3.0中这个值的变化要比2.x下多得多。

警告：这个函数违反了模块的面相对象的原则。不管如何，当许多信号连接到一个单一的槽上的时候，获得访问的发送者也许很有用处。如果槽是被做为普通C++函数调用的话，发送者是未定义的。

void QObject::setName ( const char * name ) [虚]

设置对象的名称为name。

bool QObject::setProperty ( const char * name, const QVariant & value ) [虚]

设置对象的name属性值为value。

如果操作成功，返回真，否则返回假。

关于所有可用属性的信息通过metaObject()提供。

也可以参考property()、metaObject()、QMetaObject::propertyNames()和QMetaObject::property()。

bool QObject::signalsBlocked () const

如果信号被阻塞，返回真，否则返回假。

默认情况下，信号不被阻塞。

也可以参考blockSignals()。

int QObject::startTimer ( int interval )

定时器开始计时并且返回一个定时器标识符，或者如果不能开始计时，返回0。

每interval毫秒出现一个定时器事件直到killTimer()或killTimers()被调用。如果interval为0，那么定时器事件将在每次没有窗口系统事件要处理的情况下出现。

当定时器事件发生时，虚函数timerEvent()被调用为QTimerEvent事件参数类。重新实现这个函数可以获得定时器事件。

如果多个定时器在运行，QTimerEvent::timerId()可以用来找到那个定时器被激活。

实例：

    class MyObject : public QObject
    {
        Q_OBJECT
    public:
        MyObject( QObject *parent = 0, const char *name = 0 );

    protected:
        void timerEvent( QTimerEvent * );
    };

    MyObject::MyObject( QObject *parent, const char *name )
        : QObject( parent, name )
    {
        startTimer( 50 );    // 50微妙定时器
        startTimer( 1000 );  // 1秒定时器
        startTimer( 60000 ); // 1分钟定时器
    }

    void MyObject::timerEvent( QTimerEvent *e )
    {
        qDebug( "timer event, id %d", e->timerId() );
    }

实际上没有间隔值的上限（超过1年也可以）。注意QTimer的精确度依赖与底下的操作系统和硬件。绝大多数平台都支持20毫秒的精确度，一些平台可以提供更精确的。如果Qt不能发送定时器滴答所要求的数量，它将会默默地丢弃一些。

QTimer类提供了单触发定时器和替代事件的定时器信号的高级编程接口。

也可以参考timerEvent()、killTimer()和killTimers()。

void QObject::timerEvent ( QTimerEvent * ) [虚 保护]

这个信号处理者可以在子类中重新实现而接收对象的定时器事件。

QTimer提供了定时器功能的高级接口，并且提供了关于定时器的更多说明。

也可以参考startTimer()、killTimer()、killTimers()和event()。

实例：biff/biff.cpp、dclock/dclock.cpp、forever/forever.cpp、grapher/grapher.cpp、qmag/qmag.cpp和xform/xform.cpp。

QString QObject::tr ( const char * sourceText, const char * comment ) const

返回sourceText的翻译版本，或者如果没有合适的版本返回sourceText它自己。翻译上下文是comment的QObject（默认为空）。所有使用Q_OBJECT宏的QObject对象有这个函数的重新实现，把子类名作为上下文。

也可以参考trUtf8()、QApplication::translate()和Qt中的国际化。

实例：network/networkprotocol/view.cpp。

QString QObject::trUtf8 ( const char * sourceText, const char * comment ) const

返回sourceText的翻译版本，或者如果没有合适的版本返回QString::fromUtf8(sourceText)。它是另一种tr(sourceText, comment)。

也可以参考tr()和QApplication::translate()。

属性文档

QCString name

这个属性保存的是这个对象的名称。

你可以通过名称（和类型）使用child()来找到一个对象。你可以通过queryList()来找到一系列对象。

对象名称可以通过构造函数或者setName()函数设置。对象名称在当前版本的Qt中不是非常有用，但是将在未来变得越来越重要。

如果对象没有名称，name()函数返回“unnamed”，所以printf()（在qDebug()中被使用）将不会被请求输出一个空指针。如果你希望没有名称的对象返回空指针，你可以调用name( 0 )。

        qDebug( "MyClass::setPrecision(): (%s) invalid precision %f",
                name(), newPrecision );

也可以参考className()、child()和queryList()。

通过setName()可以设置属性值并且通过name()来获得属性值。

相关函数

void * qt_find_obj_child ( QObject * parent, const char * type, const char * name )

返回一个继承了parent对象类型为type的名为name的对象的指针。

如果没有这样的对象，返回0。

        QListBox *c = (QListBox *) qt_find_obj_child( myWidget, "QListBox",
                                                      "my list box" );
        if ( c )
            c->insertItem( "another string" );

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qobject.h包含文件

qobject.h

这里是qobject.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qobject.h   3.0.5   edited Feb 4 07:26 $
**
** Definition of QObject class
**
** Created : 930418
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QOBJECT_H
#define QOBJECT_H

#ifndef QT_H
#include "qobjectdefs.h"
#include "qwindowdefs.h"
#include "qstring.h"
#include "qevent.h"
#include "qnamespace.h"
#endif // QT_H

#define QT_TR_NOOP(x) (x)
#define QT_TRANSLATE_NOOP(scope,x) (x)

class QMetaObject;
class QVariant;
class QMetaProperty;
class QPostEventList;
class QObjectPrivate;
struct QUObject;

class Q_EXPORT QObject: public Qt
{
    Q_OBJECT
    Q_PROPERTY( QCString name READ name WRITE setName )

public:
    QObject( QObject *parent=0, const char *name=0 );
    virtual ~QObject();

#ifdef Q_QDOC
    const char *className() const;
    QString tr( const char *, const char * ) const;
    QString trUtf8( const char *, const char * ) const;
    QMetaObject *metaObject() const;
#endif

    virtual bool event( QEvent * );
    virtual bool eventFilter( QObject *, QEvent * );

    bool	 isA( const char * )	 const;
    bool	 inherits( const char * ) const;

    const char  *name() const;
    const char  *name( const char * defaultName ) const;

    virtual void setName( const char *name );
    bool	 isWidgetType()	  const { return isWidget; }
    bool	 highPriority()	  const { return FALSE; }

    bool	 signalsBlocked()  const { return blockSig; }
    void	 blockSignals( bool b );

    int		 startTimer( int interval );
    void	 killTimer( int id );
    void	 killTimers();

    QObject           *child( const char *objName, const char *inheritsClass = 0, bool recursiveSearch = TRUE ); //### const in 4.0
    const QObjectList *children() const { return childObjects; }

    static const QObjectList *objectTrees();

    QObjectList	      *queryList( const char *inheritsClass = 0,
                  const char *objName = 0,
                  bool regexpMatch = TRUE,
                  bool recursiveSearch = TRUE ) const;

    virtual void insertChild( QObject * );
    virtual void removeChild( QObject * );

    void	 installEventFilter( const QObject * );
    void	 removeEventFilter( const QObject * );

    static bool  connect( const QObject *sender, const char *signal,
              const QObject *receiver, const char *member );
    bool	 connect( const QObject *sender, const char *signal,
              const char *member ) const;
    static bool  disconnect( const QObject *sender, const char *signal,
                 const QObject *receiver, const char *member );
    bool	 disconnect( const char *signal=0,
                 const QObject *receiver=0, const char *member=0 );
    bool	 disconnect( const QObject *receiver, const char *member=0 );
    static void 	 connectInternal( const QObject *sender, int signal_index, const QObject *receiver,
                  int membcode, int member_index );

    void	 dumpObjectTree();
    void	 dumpObjectInfo();

#ifndef QT_NO_PROPERTIES
    virtual bool setProperty( const char *name, const QVariant& value );
    virtual QVariant property( const char *name ) const;
#endif // QT_NO_PROPERTIES
#ifdef QT_NO_TRANSLATION
    static QString tr( const char *sourceText, const char * = 0);
#ifndef QT_NO_TEXTCODEC
    static QString trUtf8( const char *sourceText, const char * = 0);
#endif
#endif //QT_NO_TRANSLATION

signals:
    void	 destroyed();
    void	 destroyed( QObject* obj );

public:
    QObject	*parent() const { return parentObj; }

public slots:
    void	deleteLater();

private slots:
    void	 cleanupEventFilter( QObject* );

protected:
    bool	activate_filters( QEvent * );
    QConnectionList *receivers( const char* signal ) const;
    QConnectionList *receivers( int signal ) const;
    void	activate_signal( int signal );
    void	activate_signal( int signal, int );
    void	activate_signal( int signal, double );
    void	activate_signal( int signal, QString );
    void	activate_signal_bool( int signal, bool );
    void 	activate_signal( QConnectionList *clist, QUObject *o );

    const QObject *sender();

    virtual void timerEvent( QTimerEvent * );
    virtual void childEvent( QChildEvent * );
    virtual void customEvent( QCustomEvent * );

    virtual void connectNotify( const char *signal );
    virtual void disconnectNotify( const char *signal );
    virtual bool checkConnectArgs( const char *signal, const QObject *receiver,
                   const char *member );
    static QCString normalizeSignalSlot( const char *signalSlot );

private:
    uint	isSignal   : 1;
    uint	isWidget   : 1;
    uint	pendTimer  : 1;
    uint	blockSig   : 1;
    uint	wasDeleted : 1;
    uint	isTree : 1;

    const char	*objname;
    QObject	*parentObj;
    QObjectList *childObjects;
    QSignalVec *connections;
    QObjectList *senderObjects;
    QObjectList *eventFilters;
    QPostEventList *postedEvents;
    QObjectPrivate* d;

    static QMetaObject* staticQtMetaObject();

    friend class QApplication;
    friend class QBaseApplication;
    friend class QWidget;
    friend class QSignal;
    friend class QSenderObject;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QObject( const QObject & );
    QObject &operator=( const QObject & );
#endif
};

inline bool QObject::connect( const QObject *sender, const char *signal,
                  const char *member ) const
{
    return connect( sender, signal, this, member );
}

inline bool QObject::disconnect( const char *signal,
                 const QObject *receiver, const char *member )
{
    return disconnect( this, signal, receiver, member );
}

inline bool QObject::disconnect( const QObject *receiver, const char *member )
{
    return disconnect( this, 0, receiver, member );
}

class Q_EXPORT QSenderObject : public QObject		// object for sending signals
{
public:
    void setSender( QObject *s );
};

#ifdef QT_NO_TRANSLATION
inline QString QObject::tr( const char *sourceText, const char * ) {
    return QString::fromLatin1( sourceText );
}
#ifndef QT_NO_TEXTCODEC
inline QString QObject::trUtf8( const char *sourceText, const char * ) {
    return QString::fromUtf8( sourceText );
}
#endif
#endif //QT_NO_TRANSLATION

#endif // QOBJECT_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QObject成员列表

完整的QObject成员列表

这里是QObject成员函数的完整列表，包括继承的成员。

  • QObject()
  • ~QObject()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QObjectCleanupHandler Class

QObjectCleanupHandler Class Reference

The QObjectCleanupHandler class watches the lifetime of multiple QObjects. More...

#include <qobjectcleanuphandler.h>

Inherits QObject.

List of all member functions.

Public Members

  • QObjectCleanupHandler ()
  • ~QObjectCleanupHandler ()
  • QObject * add ( QObject * object )
  • void remove ( QObject * object )
  • bool isEmpty () const
  • void clear ()

Detailed Description

The QObjectCleanupHandler class watches the lifetime of multiple QObjects.

A QObjectCleanupHandler is useful whenever you need to know when a number of QObjects that are owned by someone else have been deleted. This is important, for example, when referencing memory in an application that has been allocated in a shared library.

Example:

    class FactoryComponent : public FactoryInterface, public QLibraryInterface
    {
    public:
        ...

        QObject *createObject();

        bool init();
        void cleanup();
        bool canUnload() const;

    private:
        QObjectCleanupHandler objects;
    };

    // allocate a new object, and add it to the cleanup handler
    QObject *FactoryComponent::createObject()
    {
        return objects.add( new QObject() );
    }

    // QLibraryInterface implementation
    bool FactoryComponent::init()
    {
        return TRUE;
    }

    void FactoryComponent::cleanup()
    {
    }

    // it is only safe to unload the library when all QObject's have been destroyed
    bool FactoryComponent::canUnload() const
    {
        return objects.isEmpty();
    }

See also Object Model.

Member Function Documentation

QObjectCleanupHandler::QObjectCleanupHandler ()

Constructs an empty QObjectCleanupHandler.

QObjectCleanupHandler::~QObjectCleanupHandler ()

Destroys the cleanup handler. All objects in this cleanup handler will be deleted.

QObject * QObjectCleanupHandler::add ( QObject * object )

Adds object to this cleanup handler and returns the pointer to the object.

void QObjectCleanupHandler::clear ()

Deletes all objects in this cleanup handler. The cleanup handler becomes empty.

bool QObjectCleanupHandler::isEmpty () const

Returns TRUE if this cleanup handler is empty or if all objects in this cleanup handler have been destroyed; otherwise return FALSE.

void QObjectCleanupHandler::remove ( QObject * object )

Removes the object from this cleanup handler. The object will not be destroyed.

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


qobjectcleanuphandler.h Include File

qobjectcleanuphandler.h

This is the verbatim text of the qobjectcleanuphandler.h include file. It is provided only for illustration; the copyright remains with Trolltech.

#ifndef QOBJECTCLEANUPHANDLER_H
#define QOBJECTCLEANUPHANDLER_H

#ifndef QT_H
#include <qobject.h>
#endif // QT_H

class QObjectList;

class Q_EXPORT QObjectCleanupHandler : public QObject
{
    Q_OBJECT

public:
    QObjectCleanupHandler();
    ~QObjectCleanupHandler();

    QObject* add( QObject* object );
    void remove( QObject *object );
    bool isEmpty() const;
    void clear();

private:
    QObjectList *cleanupObjects;

private slots:
    void objectDestroyed( QObject * );
};

#endif // QOBJECTCLEANUPHANDLER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QObjectCleanupHandler Member List

Complete Member List for QObjectCleanupHandler

This is the complete list of member functions for QObjectCleanupHandler, including inherited members.

  • QObjectCleanupHandler()
  • ~QObjectCleanupHandler()
  • add()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clear()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isEmpty()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • remove()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QObjectList类

QObjectList类参考

QObjectList类就是一个QObject的QPtrList。 详情请见……

#include <qobjectlist.h>

继承了QPtrList<QObject>。

所有成员函数的列表。

公有成员

  • QObjectList ()
  • QObjectList ( const QObjectList & list )
  • ~QObjectList ()
  • QObjectList & operator= ( const QObjectList & list )

详细描述

QObjectList类就是一个QObject的QPtrList。

QObjectList就是QPtrList<QObject>。这个列表可以使用继承函数，比如getFirst()、next()等等来遍历，或者使用QObjectListIt迭代器来遍历。

使用的实例可以参考QObject::queryList()。

也可以参考QObject、集合类和非GUI类。

成员函数文档

QObjectList::QObjectList ()

构造一个空的QObject列表。

QObjectList::QObjectList ( const QObjectList & list )

构造一个list的复制。

list的每一个项都被添加到这个列表中。只有指针被复制（浅复制）。

QObjectList::~QObjectList ()

移除列表中的所有对象指针并且销毁列表。

所有访问这个列表的迭代器都将被重置。

也可以参考setAutoDelete()。

QObjectList & QObjectList::operator= ( const QObjectList & list )

把list赋值给这个列表并且返回这个列表的引用。

这个列表首先被清空并且然后list的每一个项都被添加到这个列表中。只有指针被复制（浅复制），除非newItem()已经被重新实现。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qobjectlist.h包含文件

qobjectlist.h

这里是qobjectlist.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qobjectlist.h   3.0.5   edited Jun 5 21:12 $
**
** Definition of QObjectList
**
** Created : 940807
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QOBJECTLIST_H
#define QOBJECTLIST_H

#ifndef QT_H
#include "qobject.h"
#include "qptrlist.h"
#endif // QT_H

#if defined(Q_TEMPLATEDLL)
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrList<QObject>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrListIterator<QObject>;
#endif

class Q_EXPORT QObjectList : public QPtrList<QObject>
{
public:
    QObjectList() : QPtrList<QObject>() {}
    QObjectList( const QObjectList &list ) : QPtrList<QObject>(list) {}
   ~QObjectList() { clear(); }
    QObjectList &operator=(const QObjectList &list)
    { return (QObjectList&)QPtrList<QObject>::operator=(list); }
};

class Q_EXPORT QObjectListIt : public QPtrListIterator<QObject>
{
public:
    QObjectListIt( const QObjectList &l ) : QPtrListIterator<QObject>(l) {}
    QObjectListIt &operator=(const QObjectListIt &i)
    { return (QObjectListIt&)QPtrListIterator<QObject>::operator=(i); }
};

#endif // QOBJECTLIST_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QObjectList成员列表

完整的QObjectList成员列表

这里是QObjectList成员函数的完整列表，包括继承的成员。

  • QObjectList()
  • ~QObjectList()
  • append()
  • at()
  • autoDelete()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • current()
  • currentNode()
  • deleteItem()
  • find()
  • findNext()
  • findNextRef()
  • findRef()
  • first()
  • getFirst()
  • getLast()
  • inSort()
  • insert()
  • isEmpty()
  • last()
  • newItem()
  • next()
  • operator=()
  • operator==()
  • prepend()
  • prev()
  • read()
  • remove()
  • removeFirst()
  • removeLast()
  • removeNode()
  • removeRef()
  • setAutoDelete()
  • sort()
  • take()
  • takeNode()
  • toVector()
  • write()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QObjectListIt类

QObjectListIt类参考

QObjectListIt类为QObjectLists提供了迭代器。 详情请见……

#include <qobjectlist.h>

继承了QPtrListIterator<QObject>。

所有成员函数的列表。

公有成员

  • QObjectListIt ( const QObjectList & list )
  • QObjectListIt & operator= ( const QObjectListIt & it )

详细描述

QObjectListIt类为QObjectLists提供了迭代器。

QObjectListIt迭代器就是QPtrListIterator<QObject>。

使用的实例可以参考QObject::queryList()。

也可以参考QObjectList、集合类和非GUI类。

成员函数文档

QObjectListIt::QObjectListIt ( const QObjectList & list )

为list构造一个迭代器。当前迭代器的项被设置为指向list中的第一个项。

QObjectListIt & QObjectListIt::operator= ( const QObjectListIt & it )

赋值。完成迭代器it的复制并返回这个迭代器的引用。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QObjectListIt成员列表

完整的QObjectListIt成员列表

这里是QObjectListIt成员函数的完整列表，包括继承的成员。

  • QObjectListIt()
  • atFirst()
  • atLast()
  • count()
  • current()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator*()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPaintDevice类

QPaintDevice类参考

QPaintDevice类是所有可以绘制的对象的基类。 详情请见……

#include <qpaintdevice.h>

由QPixmap、QWidget、QPicture和QPrinter继承。

所有成员函数的列表。

公有成员

  • virtual ~QPaintDevice ()
  • bool isExtDev () const
  • bool paintingActive () const
  • virtual HDC handle () const
  • virtual Qt::HANDLE handle () const
  • Display * x11Display () const
  • int x11Screen () const
  • int x11Depth () const
  • int x11Cells () const
  • Qt::HANDLE x11Colormap () const
  • bool x11DefaultColormap () const
  • void * x11Visual () const
  • bool x11DefaultVisual () const

静态公有成员

  • Display * x11AppDisplay ()
  • int x11AppScreen ()
  • int x11AppDepth ()
  • int x11AppCells ()
  • int x11AppDpiX ()
  • int x11AppDpiY ()
  • Qt::HANDLE x11AppColormap ()
  • bool x11AppDefaultColormap ()
  • void * x11AppVisual ()
  • bool x11AppDefaultVisual ()
  • void x11SetAppDpiX ( int dpi )
  • void x11SetAppDpiY ( int dpi )

保护成员

  • QPaintDevice ( uint devflags )
  • virtual bool cmd ( int, QPainter *, QPDevCmdParam * )

相关函数

  • void bitBlt ( QPaintDevice * dst, int dx, int dy, const QPaintDevice * src, int sx, int sy, int sw, int sh, Qt::RasterOp rop, bool ignoreMask )
  • void bitBlt ( QPaintDevice * dst, const QPoint & dp, const QPaintDevice * src, const QRect & sr, RasterOp rop )

详细描述

QPaintDevice类是所有可以绘制的对象的基类。

一个绘制设备就是一个可以使用QPainter来绘制的二维空间的抽象。绘画的能力由子类QWidget、QPixmap、QPicture和QPrinter来实现。

绘制设备的默认坐标系统的原点在左上角。X向右增加，Y向下增加。单位是一个像素。这里有几种方法在使用绘制工具时来设置用户自定义的坐标系统，比如，使用QPainter::setWorldMatrix()。

实例（在一个绘制设备上绘画）：

    void MyWidget::paintEvent( QPaintEvent * )
    {
        QPainter p;                       // 我们的绘制工具
        p.begin( this );                  // 开始在窗口部件上绘制
        p.setPen( red );                  // 红色的外框
        p.setBrush( yellow );             // 用黄色填充
        p.drawEllipse( 10, 20, 100,100 ); // 在(10, 20)位置的100x100的椭圆
        p.end();                          // 绘制结束
    }

位块传送是从一个绘制设备向另一个（或者它自己）复制像素的非常有用的函数。它是由全局函数bitBlt()实现的。

实例：（向右滚动窗口部件内容10个像素）：

    bitBlt( myWidget, 10, 0, myWidget );

警告： 在任何绘制设备创建之前，Qt需要一个QApplication对象存在。绘制设备访问窗口系统资源，并且这些资源在一个应用程序对象没有创建之前是没有初始化的。

也可以参考图形类 and 图像处理类。

成员函数文档

QPaintDevice::QPaintDevice ( uint devflags ) [保护]

使用内部标记devflags构造一个绘制设备。这个构造函数只能由QPaintDevice的子类调用。

QPaintDevice::~QPaintDevice () [虚]

销毁绘制设备并且释放窗口系统资源。

bool QPaintDevice::cmd ( int, QPainter *, QPDevCmdParam * ) [虚 保护]

从绘制工具中解释绘画指令的内部虚函数。

由不直接支持绘制图画的子类实现（外部绘制设备，比如，QPicture）。

Qt::HANDLE QPaintDevice::handle () const [虚]

返回用于低级访问的绘制设备的窗口系统句柄。使用这个函数是不可移植的。

HANDLE的类型根据平台的不同而不同，详细情况请见qpaintdevice.h和qwindowdefs.h。

也可以参考x11Display()。

bool QPaintDevice::isExtDev () const

如果设备是一个外部绘制设备，返回真，否则返回假。

外部绘制设备不能作为bitBlt()的源。QPicture和QPrinter是外部绘制设备。

bool QPaintDevice::paintingActive () const

如果设备正在被绘制，比如某人已经调用了QPainter::begin()但还没有对这个设备调用QPainter::end()，返回真，否则返回假。

也可以参考QPainter::isActive()。

int QPaintDevice::x11AppCells () [静态]

返回X显示全部到应用程序的颜色映射的条目的数量（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Colormap()。

Qt::HANDLE QPaintDevice::x11AppColormap () [静态]

返回X显示全部到应用程序的颜色映射（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Cells()。

bool QPaintDevice::x11AppDefaultColormap () [静态]

返回X显示全部到应用程序的默认颜色映射（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Cells()。

bool QPaintDevice::x11AppDefaultVisual () [静态]

返回X显示全部到应用程序的默认视件（Visual）（仅X11下有效）。使用这个函数是不可移植的。

int QPaintDevice::x11AppDepth () [静态]

返回X显示全部到应用程序的深度（仅X11下有效）。使用这个函数是不可移植的。

也可以参考QPixmap::defaultDepth()。

Display * QPaintDevice::x11AppDisplay () [静态]

返回X显示全部到应用程序的指针（仅X11下有效）。使用这个函数是不可移植的。

也可以参考handle()。

int QPaintDevice::x11AppDpiX () [静态]

返回X显示的水平DPI（仅X11下有效）。使用这个函数是不可移植的。关于可移植的访问的相关信息请看QPaintDeviceMetrics。使用这个函数是不可移植的。

也可以参考x11AppDpiY()、x11SetAppDpiX()和QPaintDeviceMetrics::logicalDpiX()。

int QPaintDevice::x11AppDpiY () [静态]

返回X显示的垂直DPI（仅X11下有效）。使用这个函数是不可移植的。关于可移植的访问的相关信息请看QPaintDeviceMetrics。使用这个函数是不可移植的。

也可以参考x11AppDpiX()、x11SetAppDpiY()和QPaintDeviceMetrics::logicalDpiY()。

int QPaintDevice::x11AppScreen () [静态]

返回X显示全部到应用程序的屏幕数量（仅X11下有效）。使用这个函数是不可移植的。

void * QPaintDevice::x11AppVisual () [静态]

返回X显示全部到应用程序的视件（Visual）（仅X11下有效）。使用这个函数是不可移植的。

int QPaintDevice::x11Cells () const

返回X显示全部到绘制设备的颜色映射的条目的数量（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Colormap().

Qt::HANDLE QPaintDevice::x11Colormap () const

返回X显示全部到绘制设备的颜色映射（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Cells()。

bool QPaintDevice::x11DefaultColormap () const

返回X显示全部到绘制设备的默认颜色映射（仅X11下有效）。使用这个函数是不可移植的。

也可以参考x11Cells()。

bool QPaintDevice::x11DefaultVisual () const

返回X显示全部到绘制设备的默认视件（Visual）（仅X11下有效）。使用这个函数是不可移植的。

int QPaintDevice::x11Depth () const

返回X显示全部到绘制设备的深度（仅X11下有效）。使用这个函数是不可移植的。

也可以参考QPixmap::defaultDepth()。

Display * QPaintDevice::x11Display () const

返回X显示全部到绘制设备的指针（仅X11下有效）。使用这个函数是不可移植的。

也可以参考handle()。

int QPaintDevice::x11Screen () const

返回X显示全部到绘制设备的屏幕数量（仅X11下有效）。使用这个函数是不可移植的。

void QPaintDevice::x11SetAppDpiX ( int dpi ) [静态]

设置通过x11AppDpiX()返回的值为dpi。默认情况下决定于显示配置。这个值的变化将会使字体的边缘发生变化，并且许多其它的度量标准将不被推荐。使用这个函数是不可移植的。

也可以参考x11SetAppDpiY()。

void QPaintDevice::x11SetAppDpiY ( int dpi ) [静态]

设置通过x11AppDpiY()返回的值为dpi。默认情况下决定于显示配置。这个值的变化将会使字体的边缘发生变化，并且许多其它的度量标准将不被推荐。使用这个函数是不可移植的。

也可以参考x11SetAppDpiX()。

void * QPaintDevice::x11Visual () const

返回X显示全部到绘制设备的视件（Visual）（仅X11下有效）。使用这个函数是不可移植的。

相关函数

void bitBlt ( QPaintDevice * dst, int dx, int dy, const QPaintDevice * src, int sx, int sy, int sw, int sh, Qt::RasterOp rop, bool ignoreMask )

把一个像素块从src复制到dst，也许根据光栅操作 rop来合并每一个像素。sx和sy是src中的左上像素，默认为(0, 0)，dx和dy是dst的左上位置并且sw和sh是复制块的大小（默认情况下都是src的）。

rop的最普通的值是CopyROP和XorROP，Qt::RasterOp文档中定义了所有的可能值。

如果ignoreMask是真（默认是假）并且src是一个遮蔽的QPixmap，整个二进制块被src->mask()遮蔽。

如果src、dst、sw或sh为0，bitBlt()不会做任何事情。如果sw或sh为负，bitBlt()的复制会从sx开始（分别地，sy）并且到src右端点（分别地，下）结束。

src必须是一个QWidget或者QPixmap。比如，你不能从一个QPrinter做块复制。如果你试图从一个不支持的设备做块复制，bitBlt()将不会做任何事情。

如果src的深度比dst高，bitBlt()不会做任何事。如果你需要这样的操作，比如在一个8位的窗口部件绘制24位的像素映射，你必须使用drawPixmap()。

void bitBlt ( QPaintDevice * dst, const QPoint & dp, const QPaintDevice * src, const QRect & sr, RasterOp rop )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用了目标点dp和源矩形sr重载bitBlt()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qpaintdevice.h包含文件

qpaintdevice.h

这里是qpaintdevice.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qpaintdevice.h   3.0.5   edited Apr 23 23:32 $
**
** Definition of QPaintDevice class
**
** Created : 940721
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPAINTDEVICE_H
#define QPAINTDEVICE_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qrect.h"
#endif // QT_H

#if defined(Q_WS_QWS)
class QWSDisplay;
class QGfx;
#endif

class QIODevice;
class QString;

#if defined(Q_WS_X11)
struct QPaintDeviceX11Data;
#endif

union QPDevCmdParam {
    int			 ival;
    int			*ivec;
    QString	        *str;
    const QPoint	*point;
    const QRect		*rect;
    const QPointArray	*ptarr;
    const QPixmap	*pixmap;
    const QImage	*image;
    const QColor	*color;
    const QFont		*font;
    const QPen		*pen;
    const QBrush	*brush;
    const QRegion	*rgn;
    const QWMatrix	*matrix;
    QIODevice		*device;
};

class Q_EXPORT QPaintDevice				// device for QPainter
{
public:
    virtual ~QPaintDevice();

    int		devType() const;
    bool	isExtDev() const;
    bool	paintingActive() const;

    virtual void setResolution( int );
    virtual int resolution() const;

    // Windows:	  get device context
    // X-Windows: get drawable
#if defined(Q_WS_WIN)
    virtual HDC		handle() const;
#elif defined(Q_WS_X11)
    virtual Qt::HANDLE	handle() const;
    virtual Qt::HANDLE  x11RenderHandle() const;
#elif defined(Q_WS_MAC)
    virtual Qt::HANDLE      handle() const;
#elif defined(Q_WS_QWS)
    virtual Qt::HANDLE	handle() const;
#endif

#if defined(Q_WS_X11)
    Display 	   *x11Display() const;
    int		    x11Screen() const;
    int		    x11Depth() const;
    int		    x11Cells() const;
    Qt::HANDLE	    x11Colormap() const;
    bool	    x11DefaultColormap() const;
    void	   *x11Visual() const;
    bool	    x11DefaultVisual() const;

    static Display *x11AppDisplay();
    static int	    x11AppScreen();
    static int	    x11AppDepth();
    static int	    x11AppCells();
    static int	    x11AppDpiX();
    static int	    x11AppDpiY();
    static Qt::HANDLE   x11AppColormap();
    static bool     x11AppDefaultColormap();
    static void    *x11AppVisual();
    static bool	    x11AppDefaultVisual();
    static void	    x11SetAppDpiX(int);
    static void	    x11SetAppDpiY(int);
#endif

#if defined(Q_WS_QWS)
    static QWSDisplay *qwsDisplay();
    virtual unsigned char * scanLine(int) const;
    virtual int bytesPerLine() const;
    virtual QGfx * graphicsContext(bool clip_children=TRUE) const;
#endif

    enum PDevCmd {
    PdcNOP = 0, //  <void>
    PdcDrawPoint = 1, // point
    PdcDrawFirst = PdcDrawPoint,
    PdcMoveTo = 2, // point
    PdcLineTo = 3, // point
    PdcDrawLine = 4, // point,point
    PdcDrawRect = 5, // rect
    PdcDrawRoundRect = 6, // rect,ival,ival
    PdcDrawEllipse = 7, // rect
    PdcDrawArc = 8, // rect,ival,ival
    PdcDrawPie = 9, // rect,ival,ival
    PdcDrawChord = 10, // rect,ival,ival
    PdcDrawLineSegments = 11, // ptarr
    PdcDrawPolyline = 12, // ptarr
    PdcDrawPolygon = 13, // ptarr,ival
    PdcDrawCubicBezier = 14, // ptarr
    PdcDrawText = 15, // point,str
    PdcDrawTextFormatted = 16, // rect,ival,str
    PdcDrawPixmap = 17, // rect,pixmap
    PdcDrawImage = 18, // rect,image
    PdcDrawText2 = 19, // point,str
    PdcDrawText2Formatted = 20, // rect,ival,str
    PdcDrawLast = PdcDrawText2Formatted,

    // no painting commands below PdcDrawLast.

    PdcBegin = 30, //  <void>
    PdcEnd = 31, //  <void>
    PdcSave = 32, //  <void>
    PdcRestore = 33, //  <void>
    PdcSetdev = 34, // device - PRIVATE
    PdcSetBkColor = 40, // color
    PdcSetBkMode = 41, // ival
    PdcSetROP = 42, // ival
    PdcSetBrushOrigin = 43, // point
    PdcSetFont = 45, // font
    PdcSetPen = 46, // pen
    PdcSetBrush = 47, // brush
    PdcSetTabStops = 48, // ival
    PdcSetTabArray = 49, // ival,ivec
    PdcSetUnit = 50, // ival
    PdcSetVXform = 51, // ival
    PdcSetWindow = 52, // rect
    PdcSetViewport = 53, // rect
    PdcSetWXform = 54, // ival
    PdcSetWMatrix = 55, // matrix,ival
    PdcSaveWMatrix = 56,
    PdcRestoreWMatrix = 57,
    PdcSetClip = 60, // ival
    PdcSetClipRegion = 61, // rgn

    PdcReservedStart = 0, // codes 0-199 are reserved
    PdcReservedStop = 199 //   for Qt
    };

protected:
    QPaintDevice( uint devflags );

#if defined(Q_WS_WIN)
    HDC		hdc;				// device context
#elif defined(Q_WS_X11)
    Qt::HANDLE	hd;				// handle to drawable
    Qt::HANDLE  rendhd;                         // handle to RENDER pict

    void		 copyX11Data( const QPaintDevice * );
    void		 cloneX11Data( const QPaintDevice * );
    virtual void	 setX11Data( const QPaintDeviceX11Data* );
    QPaintDeviceX11Data* getX11Data( bool def=FALSE ) const;
#elif defined(Q_WS_MAC)
#if !defined( QMAC_NO_QUARTZ )
    CGContextRef ctx;
#endif
    void * hd;
#elif defined(Q_WS_QWS)
    Qt::HANDLE hd;
#endif

    virtual bool cmd( int, QPainter *, QPDevCmdParam * );
    virtual int	 metric( int ) const;
    virtual int	 fontMet( QFont *, int, const char * = 0, int = 0 ) const;
    virtual int	 fontInf( QFont *, int ) const;

    ushort	devFlags;			// device flags
    ushort	painters;			// refcount

    friend class QPainter;
    friend class QPaintDeviceMetrics;
#if defined(Q_WS_MAC)
#ifndef QMAC_NO_QUARTZ
    virtual CGContextRef macCGContext(bool clipped=TRUE) const;
#endif
    friend Q_EXPORT void unclippedScaledBitBlt( QPaintDevice *, int, int, int, int,
                        const QPaintDevice *, int, int, int, int, Qt::RasterOp, bool, bool );
#else
    friend Q_EXPORT void bitBlt( QPaintDevice *, int, int,
                 const QPaintDevice *,
                 int, int, int, int, Qt::RasterOp, bool );
#endif
#if defined(Q_WS_X11)
    friend void qt_init_internal( int *, char **, Display *, Qt::HANDLE, Qt::HANDLE );
#endif

private:
#if defined(Q_WS_X11)
    static Display *x_appdisplay;
    static int	    x_appscreen;
    static int	    x_appdepth;
    static int	    x_appcells;
    static Qt::HANDLE   x_appcolormap;
    static bool	    x_appdefcolormap;
    static void	   *x_appvisual;
    static bool     x_appdefvisual;

    QPaintDeviceX11Data* x11Data;
#endif

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPaintDevice( const QPaintDevice & );
    QPaintDevice &operator=( const QPaintDevice & );
#endif
};

Q_EXPORT
void bitBlt( QPaintDevice *dst, int dx, int dy,
         const QPaintDevice *src, int sx=0, int sy=0, int sw=-1, int sh=-1,
         Qt::RasterOp = Qt::CopyROP, bool ignoreMask=FALSE );

Q_EXPORT
void bitBlt( QPaintDevice *dst, int dx, int dy,
         const QImage *src, int sx=0, int sy=0, int sw=-1, int sh=-1,
         int conversion_flags=0 );

#if defined(Q_WS_X11)

struct Q_EXPORT QPaintDeviceX11Data : public QShared {
    Display*	x_display;
    int		x_screen;
    int		x_depth;
    int		x_cells;
    Qt::HANDLE	x_colormap;
    bool	x_defcolormap;
    void*	x_visual;
    bool	x_defvisual;
};

#endif

/*****************************************************************************
  Inline functions
 *****************************************************************************/

inline int QPaintDevice::devType() const
{ return devFlags & QInternal::DeviceTypeMask; }

inline bool QPaintDevice::isExtDev() const
{ return (devFlags & QInternal::ExternalDevice) != 0; }

inline bool QPaintDevice::paintingActive() const
{ return painters != 0; }

#if defined(Q_WS_X11)
inline Display *QPaintDevice::x11Display() const
{ return x11Data ? x11Data->x_display : x_appdisplay; }

inline int QPaintDevice::x11Screen() const
{ return x11Data ? x11Data->x_screen : x_appscreen; }

inline int QPaintDevice::x11Depth() const
{ return x11Data ? x11Data->x_depth : x_appdepth; }

inline int QPaintDevice::x11Cells() const
{ return x11Data ? x11Data->x_cells : x_appcells; }

inline Qt::HANDLE QPaintDevice::x11Colormap() const
{ return x11Data ? x11Data->x_colormap : x_appcolormap; }

inline bool QPaintDevice::x11DefaultColormap() const
{ return x11Data ? x11Data->x_defcolormap : x_appdefcolormap; }

inline void *QPaintDevice::x11Visual() const
{ return x11Data ? x11Data->x_visual : x_appvisual; }

inline bool QPaintDevice::x11DefaultVisual() const
{ return x11Data ? x11Data->x_defvisual : x_appdefvisual; }

inline Display *QPaintDevice::x11AppDisplay()
{ return x_appdisplay; }

inline int QPaintDevice::x11AppScreen()
{ return x_appscreen; }

inline int QPaintDevice::x11AppDepth()
{ return x_appdepth; }

inline int QPaintDevice::x11AppCells()
{ return x_appcells; }

inline Qt::HANDLE QPaintDevice::x11AppColormap()
{ return x_appcolormap; }

inline bool QPaintDevice::x11AppDefaultColormap()
{ return x_appdefcolormap; }

inline void *QPaintDevice::x11AppVisual()
{ return x_appvisual; }

inline bool QPaintDevice::x11AppDefaultVisual()
{ return x_appdefvisual; }

#endif // Q_WS_X11

Q_EXPORT
inline void bitBlt( QPaintDevice *dst, const QPoint &dp,
            const QPaintDevice *src, const QRect &sr =QRect(0,0,-1,-1),
            Qt::RasterOp rop=Qt::CopyROP, bool ignoreMask=FALSE )
{
    bitBlt( dst, dp.x(), dp.y(), src, sr.x(), sr.y(), sr.width(), sr.height(),
        rop, ignoreMask );
}

#endif // QPAINTDEVICE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPaintDevice成员列表

完整的QPaintDevice成员列表

这里是QPaintDevice成员函数的完整列表，包括继承的成员。

  • QPaintDevice()
  • ~QPaintDevice()
  • cmd()
  • handle()
  • isExtDev()
  • paintingActive()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPaintDeviceMetrics Class

QPaintDeviceMetrics Class Reference

The QPaintDeviceMetrics class provides information about a paint device. More...

#include <qpaintdevicemetrics.h>

List of all member functions.

Public Members

  • QPaintDeviceMetrics ( const QPaintDevice * pd )
  • int width () const
  • int height () const
  • int widthMM () const
  • int heightMM () const
  • int logicalDpiX () const
  • int logicalDpiY () const
  • int numColors () const
  • int depth () const

Detailed Description

The QPaintDeviceMetrics class provides information about a paint device.

Sometimes when drawing graphics it is necessary to obtain information about the physical characteristics of a paint device. This class provides the information. For example, to compute the aspect ratio of a paint device:

        QPaintDeviceMetrics pdm( myWidget );
        double aspect = (double)pdm.widthMM() / (double)pdm.heightMM();

QPaintDeviceMetrics contains methods to provide the width and height of a device in both pixels (width() and height()) and millimeters (widthMM() and heightMM()), the number of colors the device supports (numColors()), the number of bit planes (depth()), and the resolution of the device (logicalDpiX() and logicalDpiY()).

It is not always possible for QPaintDeviceMetrics to compute the values you ask for, particularly for external devices. The ultimate example is asking for the resolution of of a QPrinter that is set to "print to file": who knows what printer that file will end up on?

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QPaintDeviceMetrics::QPaintDeviceMetrics ( const QPaintDevice * pd )

Constructs a metric for the paint device pd.

int QPaintDeviceMetrics::depth () const

Returns the bit depth (number of bit planes) of the paint device.

int QPaintDeviceMetrics::height () const

Returns the height of the paint device in default coordinate system units (e.g. pixels for QPixmap and QWidget).

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

int QPaintDeviceMetrics::heightMM () const

Returns the height of the paint device, measured in millimeters.

int QPaintDeviceMetrics::logicalDpiX () const

Returns the horizontal resolution of the device in dots per inch, which is used when computing font sizes. For X, this is usually the same as could be computed from widthMM(), but it varies on Windows.

Examples: helpviewer/helpwindow.cpp and qwerty/qwerty.cpp.

int QPaintDeviceMetrics::logicalDpiY () const

Returns the vertical resolution of the device in dots per inch, which is used when computing font sizes. For X, this is usually the same as could be computed from heightMM(), but it varies on Windows.

Example: helpviewer/helpwindow.cpp.

int QPaintDeviceMetrics::numColors () const

Returns the number of different colors available for the paint device.

int QPaintDeviceMetrics::width () const

Returns the width of the paint device in default coordinate system units (e.g. pixels for QPixmap and QWidget).

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

int QPaintDeviceMetrics::widthMM () const

Returns the width of the paint device, measured in millimeters.

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


qpaintdevicemetrics.h Include File

qpaintdevicemetrics.h

This is the verbatim text of the qpaintdevicemetrics.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpaintdevicemetrics.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPaintDeviceMetrics class
**
** Created : 941109
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPAINTDEVICEMETRICS_H
#define QPAINTDEVICEMETRICS_H

#ifndef QT_H
#include "qpaintdevice.h"
#endif // QT_H

class Q_EXPORT QPaintDeviceMetrics			// paint device metrics
{
public:
    QPaintDeviceMetrics( const QPaintDevice * );

    enum {
    PdmWidth = 1,
    PdmHeight,
    PdmWidthMM,
    PdmHeightMM,
    PdmNumColors,
    PdmDepth,
    PdmDpiX,
    PdmDpiY,
    PdmPhysicalDpiX,
    PdmPhysicalDpiY
    };

    int	  width()	const	{ return (int)pdev->metric(PdmWidth); }
    int	  height()	const	{ return (int)pdev->metric(PdmHeight); }
    int	  widthMM()	const	{ return (int)pdev->metric(PdmWidthMM); }
    int	  heightMM()	const	{ return (int)pdev->metric(PdmHeightMM); }
    int	  logicalDpiX()	const	{ return (int)pdev->metric(PdmDpiX); }
    int	  logicalDpiY()	const	{ return (int)pdev->metric(PdmDpiY); }
    int	  physicalDpiX()const	{ return (int)pdev->metric(PdmPhysicalDpiX); }
    int	  physicalDpiY()const	{ return (int)pdev->metric(PdmPhysicalDpiY); }
    int	  numColors()	const	{ return (int)pdev->metric(PdmNumColors); }
    int	  depth()	const	{ return (int)pdev->metric(PdmDepth); }

private:
    QPaintDevice *pdev;
};

#endif // QPAINTDEVICEMETRICS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPaintDeviceMetrics Member List

Complete Member List for QPaintDeviceMetrics

This is the complete list of member functions for QPaintDeviceMetrics, including inherited members.

  • QPaintDeviceMetrics()
  • depth()
  • height()
  • heightMM()
  • logicalDpiX()
  • logicalDpiY()
  • numColors()
  • width()
  • widthMM()


QPainter类

QPainter类参考

QPainter类低水平的绘制，例如在窗口部件上。 详情请见……

#include <qpainter.h>

继承了Qt。

被QDirectPainter继承。

所有成员函数的列表。

公有成员

  • enum CoordinateMode { CoordDevice, CoordPainter }
  • QPainter ()
  • QPainter ( const QPaintDevice * pd, bool unclipped = FALSE )
  • QPainter ( const QPaintDevice * pd, const QWidget * copyAttributes, bool unclipped = FALSE )
  • ~QPainter ()
  • bool begin ( const QPaintDevice * pd, bool unclipped = FALSE )
  • bool begin ( const QPaintDevice * pd, const QWidget * copyAttributes, bool unclipped = FALSE )
  • bool end ()
  • QPaintDevice * device () const
  • QGfx * internalGfx ()
  • bool isActive () const
  • void flush ( const QRegion & region, CoordinateMode cm = CoordDevice )
  • void flush ()
  • void save ()
  • void restore ()
  • QFontMetrics fontMetrics () const
  • QFontInfo fontInfo () const
  • const QFont & font () const
  • void setFont ( const QFont & font )
  • const QPen & pen () const
  • void setPen ( const QPen & pen )
  • void setPen ( PenStyle style )
  • void setPen ( const QColor & color )
  • const QBrush & brush () const
  • void setBrush ( const QBrush & brush )
  • void setBrush ( BrushStyle style )
  • void setBrush ( const QColor & color )
  • QPoint pos () const
  • const QColor & backgroundColor () const
  • void setBackgroundColor ( const QColor & c )
  • BGMode backgroundMode () const
  • void setBackgroundMode ( BGMode m )
  • RasterOp rasterOp () const
  • void setRasterOp ( RasterOp r )
  • const QPoint & brushOrigin () const
  • void setBrushOrigin ( int x, int y )
  • void setBrushOrigin ( const QPoint & p )
  • bool hasViewXForm () const
  • bool hasWorldXForm () const
  • void setViewXForm ( bool enable )
  • QRect window () const
  • void setWindow ( const QRect & r )
  • void setWindow ( int x, int y, int w, int h )
  • QRect viewport () const
  • void setViewport ( const QRect & r )
  • void setViewport ( int x, int y, int w, int h )
  • void setWorldXForm ( bool enable )
  • const QWMatrix & worldMatrix () const
  • void setWorldMatrix ( const QWMatrix & m, bool combine = FALSE )
  • void saveWorldMatrix () (obsolete)
  • void restoreWorldMatrix () (obsolete)
  • void scale ( double sx, double sy )
  • void shear ( double sh, double sv )
  • void rotate ( double a )
  • void translate ( double dx, double dy )
  • void resetXForm ()
  • QPoint xForm ( const QPoint & pv ) const
  • QRect xForm ( const QRect & rv ) const
  • QPointArray xForm ( const QPointArray & av ) const
  • QPointArray xForm ( const QPointArray & av, int index, int npoints ) const
  • QPoint xFormDev ( const QPoint & pd ) const
  • QRect xFormDev ( const QRect & rd ) const
  • QPointArray xFormDev ( const QPointArray & ad ) const
  • QPointArray xFormDev ( const QPointArray & ad, int index, int npoints ) const
  • void setClipping ( bool enable )
  • bool hasClipping () const
  • QRegion clipRegion ( CoordinateMode m = CoordDevice ) const
  • void setClipRect ( const QRect & r, CoordinateMode m = CoordDevice )
  • void setClipRect ( int x, int y, int w, int h, CoordinateMode m = CoordDevice )
  • void setClipRegion ( const QRegion & rgn, CoordinateMode m = CoordDevice )
  • void drawPoint ( int x, int y )
  • void drawPoint ( const QPoint & p )
  • void drawPoints ( const QPointArray & a, int index = 0, int npoints = -1 )
  • void moveTo ( int x, int y )
  • void moveTo ( const QPoint & p )
  • void lineTo ( int x, int y )
  • void lineTo ( const QPoint & p )
  • void drawLine ( int x1, int y1, int x2, int y2 )
  • void drawLine ( const QPoint & p1, const QPoint & p2 )
  • void drawRect ( int x, int y, int w, int h )
  • void drawRect ( const QRect & r )
  • void drawWinFocusRect ( int x, int y, int w, int h )
  • void drawWinFocusRect ( int x, int y, int w, int h, const QColor & bgColor )
  • void drawWinFocusRect ( const QRect & r )
  • void drawWinFocusRect ( const QRect & r, const QColor & bgColor )
  • void drawRoundRect ( int x, int y, int w, int h, int xRnd = 25, int yRnd = 25 )
  • void drawRoundRect ( const QRect & r, int xRnd = 25, int yRnd = 25 )
  • void drawEllipse ( int x, int y, int w, int h )
  • void drawEllipse ( const QRect & r )
  • void drawArc ( int x, int y, int w, int h, int a, int alen )
  • void drawArc ( const QRect & r, int a, int alen )
  • void drawPie ( int x, int y, int w, int h, int a, int alen )
  • void drawPie ( const QRect & r, int a, int alen )
  • void drawChord ( int x, int y, int w, int h, int a, int alen )
  • void drawChord ( const QRect & r, int a, int alen )
  • void drawLineSegments ( const QPointArray & a, int index = 0, int nlines = -1 )
  • void drawPolyline ( const QPointArray & a, int index = 0, int npoints = -1 )
  • void drawPolygon ( const QPointArray & a, bool winding = FALSE, int index = 0, int npoints = -1 )
  • void drawConvexPolygon ( const QPointArray & pa, int index = 0, int npoints = -1 )
  • void drawCubicBezier ( const QPointArray & a, int index = 0 )
  • void drawPixmap ( int x, int y, const QPixmap & pixmap, int sx = 0, int sy = 0, int sw = -1, int sh = -1 )
  • void drawPixmap ( const QPoint & p, const QPixmap & pm, const QRect & sr )
  • void drawPixmap ( const QPoint & p, const QPixmap & pm )
  • void drawPixmap ( const QRect & r, const QPixmap & pm )
  • void drawImage ( int x, int y, const QImage & image, int sx = 0, int sy = 0, int sw = -1, int sh = -1, int conversionFlags = 0 )
  • void drawImage ( const QPoint &, const QImage &, const QRect & sr, int conversionFlags = 0 )
  • void drawImage ( const QPoint & p, const QImage & i, int conversion_flags = 0 )
  • void drawImage ( const QRect & r, const QImage & i )
  • void drawTiledPixmap ( int x, int y, int w, int h, const QPixmap & pixmap, int sx = 0, int sy = 0 )
  • void drawTiledPixmap ( const QRect & r, const QPixmap & pm, const QPoint & sp )
  • void drawTiledPixmap ( const QRect & r, const QPixmap & pm )
  • void drawPicture ( const QPicture & pic ) (obsolete)
  • void drawPicture ( int x, int y, const QPicture & pic )
  • void drawPicture ( const QPoint & p, const QPicture & pic )
  • void fillRect ( int x, int y, int w, int h, const QBrush & brush )
  • void fillRect ( const QRect & r, const QBrush & brush )
  • void eraseRect ( int x, int y, int w, int h )
  • void eraseRect ( const QRect & r )
  • enum TextDirection { Auto, RTL, LTR }
  • void drawText ( int x, int y, const QString &, int len = -1, TextDirection dir = Auto )
  • void drawText ( const QPoint &, const QString &, int len = -1, TextDirection dir = Auto )
  • void drawText ( int x, int y, const QString &, int pos, int len, TextDirection dir = Auto )
  • void drawText ( const QPoint & p, const QString &, int pos, int len, TextDirection dir = Auto )
  • void drawText ( int x, int y, int w, int h, int flags, const QString &, int len = -1, QRect * br = 0, QTextParag ** internal = 0 )
  • void drawText ( const QRect & r, int tf, const QString & str, int len = -1, QRect * brect = 0, QTextParag ** internal = 0 )
  • QRect boundingRect ( int x, int y, int w, int h, int flags, const QString &, int len = -1, QTextParag ** intern = 0 )
  • QRect boundingRect ( const QRect & r, int flags, const QString & str, int len = -1, QTextParag ** internal = 0 )
  • int tabStops () const
  • void setTabStops ( int ts )
  • int * tabArray () const
  • void setTabArray ( int * ta )
  • HDC handle () const

静态公有成员

  • void redirect ( QPaintDevice * pdev, QPaintDevice * replacement )

相关函数

  • void qDrawShadeLine ( QPainter * p, int x1, int y1, int x2, int y2, const QColorGroup & g, bool sunken, int lineWidth, int midLineWidth )
  • void qDrawShadeRect ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, int lineWidth, int midLineWidth, const QBrush * fill )
  • void qDrawShadePanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, int lineWidth, const QBrush * fill )
  • void qDrawWinButton ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, const QBrush * fill )
  • void qDrawWinPanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, const QBrush * fill )
  • void qDrawPlainRect ( QPainter * p, int x, int y, int w, int h, const QColor & c, int lineWidth, const QBrush * fill )

详细描述

QPainter类低水平的绘制，例如在窗口部件上。

绘制工具为做到绝大部分绘制图形用户界面程序的需要提供了高度优化的函数。QPainter可以绘制从简单的直线到像饼图和弦这样的复杂形状。它也可以绘制排列的文本和像素映射。通常，它在一个“自然的”坐标系统中绘制，但是它也可以在视和世界转换中做到这些。

绘图工具的典型用法是：

  • 构造一个绘图工具。
  • 设置画笔、画刷等等。
  • 绘制。
  • 销毁这个绘图工具。

绝大多数情况下，所有这些是在一个绘制事件中完成的。（实际上，99％的QPainter使用是在QWidget::paintEvent()的重新实现中，并且绘制工具已经为这种用法高度优化了。）这里是一个非常简单的实例：

    void SimpleExampleWidget::paintEvent()
    {
        QPainter paint( this );
        paint.setPen( Qt::blue );
        paint.drawText( rect(), AlignCenter, "The Text" );
    }

使用方法很简单并且这里有你可以使用的许多设置：

  • font()是当前设置的字体。如果你设置一个不可用的字体，Qt会找到一个相近的匹配。实际上，font()返回你使用setFont() 所设置的东西并且fontInfo()返回你实际使用的字体（这也许是相同的）。

  • brush()是当前设置的画刷，用来填充例如圆的颜色或者调色板。

  • pen()是当前设置的画笔，用来画线或者边缘的颜色或者点画。

  • backgroundMode()是Opaque或者Transparent，也就是是不是使用backgroundColor()。

  • 仅仅当backgroundMode()为Opaque并且pen()是一个点画的时候backgroundColor()才适用，它描述了在点画中背景像素的颜色。

  • rasterOp()是像素绘制和已经存在的像素是如何相互作用的。

  • brushOrigin()是平铺的画刷的原点，通常是窗口的原点。

  • viewport()、window()、worldMatrix()和很多其它的构成了绘制工具的坐标转换系统。关于这个的解释请参考坐标系统或者参考下面有关这些函数的非常简要的概述。

  • clipping()是指绘制工具是否裁剪。（绘制设备也裁剪。）如果绘制工具裁剪，它裁剪到clipRegion()。

  • pos()是当前位置，通过moveTo()设置并且通过lineTo()使用。

注意这些设置中的一些会镜像到一些绘制设备的设置中，例如QWidget::font()。QPainter::begin()（或者QPainter的构造函数）从绘制设备中复制这些属性。调用，例如QWidget::setFont()直到绘制工具开始在它上面绘制才会生效。

把所有的这些设置保存到内部栈中，restore()把它们弹出来。

QPainter的核心功能是绘制，并且这里有最简单的绘制函数：drawPoint()、drawPoints()、drawLine()、drawRect()、drawWinFocusRect()、drawRoundRect()、drawEllipse()、drawArc()、drawPie()、drawChord()、drawLineSegments()、drawPolyline()、drawPolygon()、drawConvexPolygon()和drawCubicBezier()。所有这些函数使用整数坐标，它们没有浮点数的版本，因为我们想使绘制尽可能快地进行。

这里有绘制像素映射/图像的函数，名为drawPixmap()、drawImage()和drawTiledPixmap()。drawPixmap()和drawImage()产生同样的结果，除了drawPixmap()在屏幕上更快一些并且drawImage()在QPrinter和QPicture上更快并且有时更好。

使用drawText()可以完成文本绘制，并且当你需要良好的定位，boundingRect()告诉你哪里是给定的drawText()命令将要绘制的。

这里有一个drawPicture()函数，用来使用这个绘制工具绘制整个QPicture的内容。drawPicture()是唯一忽视所有绘制工具设置的函数：QPicture有它自己的设置。

通常，QPainter在设备自己的坐标系统（通常是像素）上操作，但是QPainter也很好地支持坐标转换。关于更通用的概述和简单实例请参考坐标系统。

最常用到的函数是scale()、rotate()、translate()和shear()，所有这些在worldMatrix()上操作。setWorldMatrix()可以替换或者添加到当前设置的worldMatrix()。

setViewport()设置QPainter操作的矩形。默认是整个设备，这通常就很好了，除了在打印机上。setWindow()设置坐标系统，它是被映射到viewport()的矩形。在window()中绘制的东西最终会在viewport()中。窗口的默认就是和视口一样，并且如果你没有使用转换，它们会被优化，赢得一点点速度。

在所有坐标转换完成之后，QPainter能够把绘制裁剪到一个任意的矩形或者区域。如果QPainter裁剪了，hasClipping()为真并且clipRegion()返回裁剪区域。你可以使用setClipRegion()或setClipRect()来设置它。注意裁剪是很慢的。它是完全依赖系统的，但是单凭经验的方法，你可以假设绘制的速度与裁剪区域中的矩形数量成反比。

在QPainter的裁剪之后，绘制设备也可以被裁剪。例如，绝大多数窗口部件按子窗口部件的像素裁剪并且绝大多数打印机按接近纸的边缘裁剪。这些另外的裁剪不会受clipRegion()或hasClipping()的返回值影响。

QPainter也包括一些比较少用到的函数，它们在当它们被需要的时候是非常有用的。

isActive()指出绘制工具是否是激活的。begin()（和最常用的构造函数）使它激活。end()（和析构函数）释放它们。如果绘制工具是激活的，device()返回绘制工具在哪个绘制设备上绘制。

有时让其它什么在一个不平常的QPaintDevice上绘制是人们想要的。QPainter支持一个静态函数来做这些，redirect()。我们建议不要使用它，但是对于一些老手这是完美的。

setTabStops()和setTabArray()可以改变tab在哪里停止，但是它们极少被用到。

警告：注意QPainter不会试图在底层窗口系统的左边限制周围工作。坐标在+/-4000时，一些平台的行为可能就不正确了。

请参考QPaintDevice、QWidget、QPixmap、QPrinter、QPicture、应用程序预演、坐标系统概述、图像类和图像处理类。

成员类型文档

QPainter::CoordinateMode

  • QPainter::CoordDevice
  • QPainter::CoordPainter

请参考clipRegion()。

QPainter::TextDirection

  • QPainter::Auto
  • QPainter::RTL - 从右到左
  • QPainter::LTR - 从左到右

请参考drawText()。

成员函数文档

QPainter::QPainter ()

构造绘制工具。

注意所有绘制工具的设置（setPen、setBrush等等）在当begin()被调用时会被重新设置为默认值。

请参考begin()和end()。

QPainter::QPainter ( const QPaintDevice * pd, bool unclipped = FALSE )

构造一个立即开始在绘制设备pd绘制的绘制工具。如果unclipped为真，依赖于底层图形系统，绘制工具将在绘制设备的子对象上绘制。

这个构造函数对短期的绘制工具是很方便的，例如，在一个绘制事件中并且也该被立即使用。构造函数为你调用begin()并且QPainter的析构函数会自动调用end()。

这是使用begin()和end()的实例：

        void MyWidget::paintEvent( QPaintEvent * )
        {
            QPainter p;
            p.begin( this );
            p.drawLine( ... );  // 绘制代码
            p.end();
        }

使用这个构造函数的相同实例：

        void MyWidget::paintEvent( QPaintEvent * )
        {
            QPainter p( this );
            p.drawLine( ... );  // 绘制代码
        }

请参考begin()和end()。

QPainter::QPainter ( const QPaintDevice * pd, const QWidget * copyAttributes, bool unclipped = FALSE )

构造一个立即开始在绘制设备pd绘制的绘制工具，默认参数来自于copyAttributes。如果unclipped为真，依赖于底层图形系统，绘制工具将在绘制设备的子对象上绘制（尽管这个不是在所有平台上都被支持）。

请参考begin()。

QPainter::~QPainter ()

销毁绘制工具。

const QColor & QPainter::backgroundColor () const

返回当前背景色。

请参考setBackgroundColor()和QColor。

BGMode QPainter::backgroundMode () const

返回当前背景模式。

请参考setBackgroundMode()和BGMode。

bool QPainter::begin ( const QPaintDevice * pd, bool unclipped = FALSE )

开始在绘制设备pd上绘制并且如果成功返回真，否则返回假。如果unclipped为真，绘制在绘制设备的边缘将不会被裁剪（尽管这不是在所有平台上被支持）。

发生的错误是严重的问题，例如这些：

        p->begin( 0 ); // 不可能——绘制设备不能为0

        QPixmap pm( 0, 0 );
        p->begin( pm ); // 不可能——pm.isNull();

        p->begin( myWidget );
        p2->begin( myWidget ); // 不可能——在同一时间只能有一个绘制工具

注意绝大部分时间，你可以使用一个构造函数来代替begin()，并且end()会在析构函数中被自动完成。

警告：在同一时间绘制设备上只能有一个绘制工具。

请参考end()和flush()。

实例：aclock/aclock.cpp、application/application.cpp、desktop/desktop.cpp、hello/hello.cpp、picture/picture.cpp、t10/cannon.cpp和xform/xform.cpp。

bool QPainter::begin ( const QPaintDevice * pd, const QWidget * copyAttributes, bool unclipped = FALSE )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本在绘制设备pd上打开绘制工具并且从copyAttributes设置初始画笔、背景颜色和字体，当unclipped为真，在绘制设备的子对象上进行绘制。这等于：

        QPainter p;
        p.begin( pd );
        p.setPen( copyAttributes->foregroundColor() );
        p.setBackgroundColor( copyAttributes->backgroundColor() );
        p.setFont( copyAttributes->font() );

这个开始函数便于双重缓冲。当你在一个像素映射上绘制，而不是直接在窗口部件上绘制（稍后用bitBlt把这个像素映射放到窗口部件中），你将需要设置窗口部件的字体等等。这个函数正确地做到了这些。

实例：

        void MyWidget::paintEvent( QPaintEvent * )
        {
            QPixmap pm(size());
            QPainter p;
            p.begin(&pm, this);
            // ……绘制操作可能有闪烁……
            p.end();
            bitBlt(this, 0, 0, &pm);
        }

请参考end()。

QRect QPainter::boundingRect ( int x, int y, int w, int h, int flags, const QString &, int len = -1, QTextParag ** intern = 0 )

返回相对应的drawText()函数所要打印的对齐的文本的边界矩形，如果len>-1，使用字符串的len个字符，或者如果len为-1，使用整个字符串。绘制已经相应的边界矩形，由点(x, y)以及宽w和高h来约束。

flags参数是下列标记的位或运算结果：

标记 | 意义
AlignAuto | 根据语言对齐，通常是左。
AlignLeft | 左对齐。
AlignRight | 右对齐。
AlignHCenter | 水平中间对齐。
AlignTop | 上对齐。
AlignBottom | 下对齐。
AlignVCenter | 垂直中间对齐。
AlignCenter | （==AlignHCenter | AlignVCenter）。
SingleLine | 在文本中忽略换行符。
ExpandTabs | 扩展tab。
ShowPrefix | 把“&x”解释为“x”。
WordBreak | 打断文本来适应矩形。

水平对齐默认为AlignLeft并且垂直对齐默认为AlignTop。

如果几种同一方向上（水平或垂直）的对齐标记一起使用，对齐结果是不确定的。

intern参数不应该被使用。

请参考Qt::TextFlags。

QRect QPainter::boundingRect ( const QRect & r, int flags, const QString & str, int len = -1, QTextParag ** internal = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回相对应的drawText()函数所要打印的对齐的文本的边界矩形，如果len>-1，使用字符串的len个字符，或者如果len为-1，使用整个字符串。绘制已经相应的边界矩形，由矩形r来约束。

intern参数不应该被使用。

请参考drawText()、fontMetrics()、QFontMetrics::boundingRect()和Qt::TextFlags。

const QBrush & QPainter::brush () const

返回绘制工具的当前画刷。

请参考QPainter::setBrush()。

实例：themes/metal.cpp和themes/wood.cpp。

const QPoint & QPainter::brushOrigin () const

返回画刷原点的当前设置。

请参考setBrushOrigin()。

QRegion QPainter::clipRegion ( CoordinateMode m = CoordDevice ) const

返回当前设置的裁剪区域。注意裁剪区域是在物理设备坐标内给定的并且如果m是CoordDevice （默认），不服从任何坐标变换。如果m是CoordPainter，返回的区域是在模型坐标中。

请参考setClipRegion()、setClipRect()、setClipping()和QPainter::CoordinateMode。

实例： themes/wood.cpp。

QPaintDevice * QPainter::device () const

返回绘制工具当前正在绘制的绘制设备，如果绘制工具没有激活，返回0。

请参考QPaintDevice::paintingActive()。

实例：helpviewer/helpwindow.cpp和listboxcombo/listboxcombo.cpp。

void QPainter::drawArc ( int x, int y, int w, int h, int a, int alen )

绘制由矩形(x, y, w, h)确定的弧，开始角度为a，并且弧长为alen。

角度a和alen是1/16度，也就是说一个完整的圆等于5760（16*360）。正数的a和alen意味着逆时针方向并且负值意味着顺时针方向。0度在3点的时钟位置。

实例：

        QPainter p( myWidget );
        p.drawArc( 10,10, 70,100, 100*16, 160*16 ); // 绘制一个“(”这样的弧

请参考drawPie()和drawChord()。

void QPainter::drawArc ( const QRect & r, int a, int alen )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制由矩形r确定的弧，开始角度为a，并且弧长为alen。

void QPainter::drawChord ( int x, int y, int w, int h, int a, int alen )

绘制由矩形(x, y, w, h)确定的弦，开始角度为a，并且弧长为alen。

这个弦由当前brush()填充。

角度a和alen是1/16度，也就是说一个完整的圆等于5760（16*360）。正数的a和alen意味着逆时针方向并且负值意味着顺时针方向。0度在3点的时钟位置。

请参考drawArc()和drawPie()。

void QPainter::drawChord ( const QRect & r, int a, int alen )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制由矩形r确定的弦，开始角度为a，并且弧长为alen。

void QPainter::drawConvexPolygon ( const QPointArray & pa, int index = 0, int npoints = -1 )

绘制pa中从pa[index]开始（index默认为0）的npoints个点确定的凸多边形。

如果提供的多边形不是凸的，结果是不确定的。

在一些平台上（例如X窗口），这个比drawPolygon()更快。

实例： aclock/aclock.cpp。

void QPainter::drawCubicBezier ( const QPointArray & a, int index = 0 )

绘制a中从a[index]开始（index默认为0）的控制点确定的三次贝塞尔曲线。

在a[index + 3]之后的控制点被忽略。如果没有足够的控制点，就什么也不发生。

void QPainter::drawEllipse ( int x, int y, int w, int h )

绘制中心在(x + w/2, y + h/2)并且大小为(w, h)的椭圆。

实例：drawdemo/drawdemo.cpp、picture/picture.cpp和tictac/tictac.cpp。

void QPainter::drawEllipse ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制在r内适合的的椭圆。

void QPainter::drawImage ( int x, int y, const QImage & image, int sx = 0, int sy = 0, int sw = -1, int sh = -1, int conversionFlags = 0 )

在(x, y)点绘制从(sx, sy)开始，sw、sh分别为宽高的像素区域，如果图片需要被转换为像素映射，使用conversionFlags。conversionFlags的默认值为0，关于其它值有什么作用请参考convertFromImage()。

如果device()是QPixmap或QWidget，这个函数可以把image转换为像素映射然后再绘制它；如果device()是QPrinter或QPicture，它会直接绘制它。

当在QPrinter上绘制时，图像中的alpha掩码将被忽略。

请参考drawPixmap()和QPixmap::convertFromImage()。

实例： canvas/canvas.cpp。

void QPainter::drawImage ( const QPoint &, const QImage &, const QRect & sr, int conversionFlags = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在给定的点绘制图像中的矩形sr。

void QPainter::drawImage ( const QPoint & p, const QImage & i, int conversion_flags = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在点p绘制图像i。

如果图像需要被修改来适应低分辨率的结果（例如从32位转换为8位），使用conversion_flags来指定你希望发生什么。

请参考Qt::ImageConversionFlags。

void QPainter::drawImage ( const QRect & r, const QImage & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在矩形r中绘制图像i。如果图像和矩形的大小不同，图像将被伸缩来适应矩形。

void QPainter::drawLine ( int x1, int y1, int x2, int y2 )

绘制从(x1, y1)到(x2, y2)的直线并且设置当前画笔位置为(x2, y2)。

请参考pen()。

实例：aclock/aclock.cpp、drawlines/connect.cpp、progress/progress.cpp、splitter/splitter.cpp、themes/metal.cpp和themes/wood.cpp。

void QPainter::drawLine ( const QPoint & p1, const QPoint & p2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制从点p1到点p2的直线。

void QPainter::drawLineSegments ( const QPointArray & a, int index = 0, int nlines = -1 )

绘制a中，从a[index]开始（index默认为0）的点确定的nlines条分隔的线。如果nlines为-1（默认），直到数组结束所有的点都被使用（也就是绘制(a.size()-index)/2个线）。

绘制的第一条线是从a[index]到a[index+1]。绘制的第二条线是从a[index+2]到a[index+3]，等等。

请参考drawPolyline()、drawPolygon()和QPen。

void QPainter::drawPicture ( int x, int y, const QPicture & pic )

在(x, y)重放图片pic。

当这个函数被调用时，如果(x, y) = (0, 0)，它就和QPicture::play()一样了。

实例：picture/picture.cpp和xform/xform.cpp。

void QPainter::drawPicture ( const QPicture & pic )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用另外一个(0, 0)位移的QPainter::drawPicture()函数来替代它。

void QPainter::drawPicture ( const QPoint & p, const QPicture & pic )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在点p绘制图片pic。

void QPainter::drawPie ( int x, int y, int w, int h, int a, int alen )

绘制由矩形(x, y, w, h)确定的饼图，开始角度为a，并且弧长为alen。

这个饼图由当前的brush()填充。

角度a和alen是1/16度，也就是说一个完整的圆等于5760（16*360）。正数的a和alen意味着逆时针方向并且负值意味着顺时针方向。0度在3点的时钟位置。

请参考drawArc()和drawChord()。

实例：drawdemo/drawdemo.cpp、grapher/grapher.cpp、t10/cannon.cpp和t9/cannon.cpp。

void QPainter::drawPie ( const QRect & r, int a, int alen )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制由矩形r确定的饼图，开始角度为a，并且弧长为alen。

void QPainter::drawPixmap ( int x, int y, const QPixmap & pixmap, int sx = 0, int sy = 0, int sw = -1, int sh = -1 )

通过把pixmap的一部分复制到绘制设备中，在(x, y)绘制一个像素映射。

(x, y)指定了要被绘制的绘制设备的左上点。(sx, sy)指定了要被绘制的pixmap中的左上点。默认为(0, 0)。

(sw, sh)指定了要被绘制的pixmap的大小。默认(-1, -1)，意思是一直到像素映射的右下。

当在QPrinter上绘制时，当前像素映射的遮蔽或者它的alpha通道被忽略。

请参考bitBlt()和QPixmap::setMask()。

实例：grapher/grapher.cpp、picture/picture.cpp、qdir/qdir.cpp、qtimage/qtimage.cpp、showimg/showimg.cpp、t10/cannon.cpp和xform/xform.cpp。

void QPainter::drawPixmap ( const QPoint & p, const QPixmap & pm, const QRect & sr )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制像素映射pm中的矩形sr，原点就放在点p处。

void QPainter::drawPixmap ( const QPoint & p, const QPixmap & pm )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制像素映射pm，原点就放在点p处。

void QPainter::drawPixmap ( const QRect & r, const QPixmap & pm )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在矩形r中绘制像素映射pm。如果像素映射和矩形大小不同，像素映射被拉伸来适合这个矩形。

void QPainter::drawPoint ( int x, int y )

使用当前画笔在(x, y)绘制一个单一点。

请参考QPen。

实例：desktop/desktop.cpp和drawlines/connect.cpp。

void QPainter::drawPoint ( const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制点p。

void QPainter::drawPoints ( const QPointArray & a, int index = 0, int npoints = -1 )

使用当前画笔绘制一组点a。

如果index为非零（默认为0），只有从index开始的点被绘制。如果npoints为负数（默认），从index开始剩余的所有点都被绘制。如果index为0或者正数，则index个点被绘制。

void QPainter::drawPolygon ( const QPointArray & a, bool winding = FALSE, int index = 0, int npoints = -1 )

绘制a中，从a[index]开始（index默认为0）的npoints个点确定的多边形。

如果npoints为－1（默认），直到数组的最后的所有点都被使用（也就是说a.size()-index条线确定的多边形）。

第一个点总是被连接到最后一个点上。

多边形被当前brush()填充。如果winding为真，多边形会被使用缠绕填充算法（winding fill algorithm）填充。如果winding为假，多边形会被使用奇偶（交错）填充算法（even-odd (alternative) fill algorithm）填充。

请参考drawLineSegments()、drawPolyline()和QPen。

实例：desktop/desktop.cpp和picture/picture.cpp。

void QPainter::drawPolyline ( const QPointArray & a, int index = 0, int npoints = -1 )

绘制a中，从a[index]开始（index默认为0）的npoints个点确定的多边形。

如果npoints为－1（默认），直到数组的最后的所有点都被使用（也就是说a.size()-index条线确定的多边形）。

请参考drawLineSegments()、drawPolygon()和QPen。

实例：scribble/scribble.cpp和themes/metal.cpp。

void QPainter::drawRect ( int x, int y, int w, int h )

绘制左上角在(x, y)并且宽为w、高为h的矩形。

请参考QPen和drawRoundRect()。

实例：drawdemo/drawdemo.cpp、picture/picture.cpp、t10/cannon.cpp、t11/cannon.cpp、t9/cannon.cpp、tooltip/tooltip.cpp和trivial/trivial.cpp。

void QPainter::drawRect ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制矩形r。

void QPainter::drawRoundRect ( int x, int y, int w, int h, int xRnd = 25, int yRnd = 25 )

绘制左上角在(x, y)并且宽为w、高为h的圆角矩形。

xRnd和yRnd参数指定了角有多圆。0构成了直角，99是最圆。

宽和高包括所有的绘制的线。

请参考drawRect()和QPen。

实例：drawdemo/drawdemo.cpp和themes/wood.cpp。

void QPainter::drawRoundRect ( const QRect & r, int xRnd = 25, int yRnd = 25 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制一个圆角矩形r，在每个角的x位置xRnd、y位置yRnd绘制圆角。

void QPainter::drawText ( const QPoint & p, const QString &, int pos, int len, TextDirection dir = Auto )

在点p从位置pos开始绘制文本那。如果len为-1，整个字符串被绘制。否则只是绘制开始的len个字符。文本的方向由dir确定。

请参考QPainter::TextDirection。

实例：desktop/desktop.cpp、drawdemo/drawdemo.cpp、grapher/grapher.cpp、picture/picture.cpp、progress/progress.cpp、t8/cannon.cpp和trivial/trivial.cpp。

void QPainter::drawText ( int x, int y, const QString &, int len = -1, TextDirection dir = Auto )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在位置(x, y)绘制给定文本。如果len为1，整个字符串被绘制。否则只是绘制开始的len个字符。文本的方向由dir确定。

请参考QPainter::TextDirection。

void QPainter::drawText ( const QPoint &, const QString &, int len = -1, TextDirection dir = Auto )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在给定的点绘制文本。

请参考QPainter::TextDirection。

void QPainter::drawText ( int x, int y, const QString &, int pos, int len, TextDirection dir = Auto )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在点(x, y)从位置pos开始绘制文本那。如果len为-1，整个字符串被绘制。否则只是绘制开始的len个字符。文本的方向由dir确定。

void QPainter::drawText ( int x, int y, int w, int h, int flags, const QString &, int len = -1, QRect * br = 0, QTextParag ** internal = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在从(x, y)开始，宽为w，高为h的矩形中绘制给定文本。如果len为-1，整个字符串被绘制。否则只是绘制开始的len个字符。文本的标记由flags参数中的Qt::AlignmentFlags和Qt::TextFlags或运算的结果给定。br（如果非零）参数只是在内部使用。

void QPainter::drawText ( const QRect & r, int tf, const QString & str, int len = -1, QRect * brect = 0, QTextParag ** internal = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在矩形r中从str中绘制最多len个字符。

注意r.y()的意思和两个drawText()的变体不同。

这个函数绘制格式化的文本。tf文本格式是Qt::AlignmentFlags和Qt::TextFlags或运算的结果。

水平对齐方式默认为AlignAuto并且垂直对齐方式默认为AlignTop。

brect（如果非零）被设置为输出的矩形的实际边界。internal还是用于内部。

请参考boundingRect()。

void QPainter::drawTiledPixmap ( int x, int y, int w, int h, const QPixmap & pixmap, int sx = 0, int sy = 0 )

在指定的矩形中绘制平铺的pixmap。

(x, y)指定了绘制设备的左上角，宽和高由w和h给定。(sx, sy)指定了所要绘制的pixmap的左上角。默认为(0, 0)。

调用drawTiledPixmap()和在一个区域上使用一个像素映射多次调用drawPixmap()相似，但是根据底下的窗口系统，这个有更多潜在的效率。

请参考drawPixmap()。

void QPainter::drawTiledPixmap ( const QRect & r, const QPixmap & pm, const QPoint & sp )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在原点在sp的矩形r中绘制平铺的pm。

void QPainter::drawTiledPixmap ( const QRect & r, const QPixmap & pm )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在矩形r中绘制平铺的pm。

void QPainter::drawWinFocusRect ( int x, int y, int w, int h, const QColor & bgColor )

绘制一个左上角在(x, y)并且宽为w、高为h的窗口焦点矩形，使用的画笔颜色和bgColor形成反差。

这个函数绘制点画矩形（XOR不被使用）用来指出键盘焦点（当QApplication::style()是WindowStyle的时候）。

用来绘制矩形的画笔颜色不是黑色就是白色，依赖于bgColor的颜色（请参考QColor::gray()）。

警告：如果坐标系统已经被旋转或者修剪，这个函数什么也不绘制。

请参考drawRect()和QApplication::style()。

void QPainter::drawWinFocusRect ( int x, int y, int w, int h )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制一个左上角在(x, y)并且宽为w、高为h的窗口焦点矩形。

这个函数绘制点画矩形（XOR不被使用）用来指出键盘焦点（当QApplication::style()是WindowStyle的时候）。

警告：如果坐标系统已经被旋转或者修剪，这个函数什么也不绘制。

请参考drawRect()和QApplication::style()。

void QPainter::drawWinFocusRect ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制矩形r作为窗口焦点矩形。

void QPainter::drawWinFocusRect ( const QRect & r, const QColor & bgColor )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用背景色bgColor绘制矩形r作为窗口焦点矩形。

bool QPainter::end ()

结束绘制。绘制时使用的任何资源都被释放。

注意虽然你几乎不需要调用end()，析构函数将会执行它，但是至少还有一种情况需要它，就是双重缓冲。

        QPainter p( myPixmap, this )
        // ...
        p.end(); // 停止在myPixmap上的绘制
        p.begin( this );
        p.drawPixmap( myPixmap );

因为当它正在被绘制的时候，你不能绘制一个QPixmap，它需要关闭激活的绘制工具。

请参考begin()和isActive()。

实例：aclock/aclock.cpp、application/application.cpp、desktop/desktop.cpp、hello/hello.cpp、picture/picture.cpp、t10/cannon.cpp和xform/xform.cpp。

void QPainter::eraseRect ( int x, int y, int w, int h )

擦除x、y、w、h中的区域。等价于fillRect( x, y, w, h, backgroundColor() )。

实例：listboxcombo/listboxcombo.cpp和showimg/showimg.cpp。

void QPainter::eraseRect ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

擦除矩形r中的区域。

void QPainter::fillRect ( int x, int y, int w, int h, const QBrush & brush )

在矩形(x, y, w, h)中使用brush填充。

你可以指定QColor作为brush，因为QBrush的一个构造函数可以得到QColor参数并且创建一个实心模式的画刷。

请参考drawRect()。

实例：listboxcombo/listboxcombo.cpp、progress/progress.cpp、qdir/qdir.cpp、qfd/fontdisplayer.cpp、themes/metal.cpp和themes/wood.cpp。

void QPainter::fillRect ( const QRect & r, const QBrush & brush )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在矩形r中使用brush填充。

void QPainter::flush ( const QRegion & region, CoordinateMode cm = CoordDevice )

使用裁剪模式cm刷新在区域region中的任何缓存的绘制操作。

如果平台不支持刷新一个指定区域，这个刷新将更新整个设备。

请参考CoordinateMode。

void QPainter::flush ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

刷新任何缓存的绘制操作。

const QFont & QPainter::font () const

返回当前设置的绘图工具字体。

请参考setFont()和QFont。

实例： fileiconview/qfileiconview.cpp。

QFontInfo QPainter::fontInfo () const

如果绘图工具是激活的，返回绘图工具的字体信息。它不能获得未激活的绘图工具的字体信息，所以如果绘图工具未激活，返回值是未定义的。

请参考fontMetrics()和isActive()。

QFontMetrics QPainter::fontMetrics () const

如果绘图工具是激活的，返回绘图工具的字体规格。它不能获得未激活的绘图工具的字体规格，所以如果绘图工具未激活，返回值是未定义的。

请参考fontInfo()和isActive()。

实例：action/application.cpp、application/application.cpp、desktop/desktop.cpp、drawdemo/drawdemo.cpp、helpviewer/helpwindow.cpp、mdi/application.cpp和qwerty/qwerty.cpp。

HDC QPainter::handle () const

返回绘制中使用的由平台决定的句柄。使用这个函数是无法移植的。

bool QPainter::hasClipping () const

如果裁剪已经被设置，返回真，否则返回假。

请参考setClipping()。

实例： themes/wood.cpp。

bool QPainter::hasViewXForm () const

如果视转换生效，返回真，否则返回假。

请参考setViewXForm()和xForm()。

bool QPainter::hasWorldXForm () const

如果世界转换生效，返回真，否则返回假。

请参考setWorldXForm()。

bool QPainter::isActive () const

如果绘图工具正在激活绘制，也就是说begin()已经被调用并且end()还没有被调用，返回真，否则返回假。

请参考QPaintDevice::paintingActive()。

实例： desktop/desktop.cpp。

void QPainter::lineTo ( int x, int y )

绘制从当前画笔位置到(x, y)的线并且设置(x, y)为新的当前画笔位置。

请参考QPen、moveTo()、drawLine()和pos()。

void QPainter::lineTo ( const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

绘制到典p的线。

void QPainter::moveTo ( int x, int y )

设置当前画笔位置为(x, y)。

请参考lineTo()和pos()。

void QPainter::moveTo ( const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置当前画笔位置为点p。

const QPen & QPainter::pen () const

返回绘图工具的当前画笔。

请参考setPen()。

实例：progress/progress.cpp和themes/wood.cpp。

QPoint QPainter::pos () const

返回画笔的当前位置。

请参考moveTo()。

RasterOp QPainter::rasterOp () const

返回当前的光栅操作。

请参考setRasterOp()和RasterOp。

void QPainter::redirect ( QPaintDevice * pdev, QPaintDevice * replacement ) [static]

重定向绘制设备pdev的所有绘制指令到另一个绘制设备replacement，除非replacement为0。如果replacement为0，pdev的重定向被移除。

通常情况下，你将可能发现调用QPixmap::grabWidget()或者QPixmap::grabWindow()是更容易的解决方法。

void QPainter::resetXForm ()

重置使用translate()、scale()、shear()、rotate()、setWorldMatrix()、setViewport()和setWindow()完成的任何转换。

请参考worldMatrix()、viewport()和window()。

void QPainter::restore ()

恢复当前绘图工具状态（从栈中弹出一个保存的状态）。

请参考save()。

实例： aclock/aclock.cpp。

void QPainter::restoreWorldMatrix ()

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

我们建议使用restore()来替代它。

void QPainter::rotate ( double a )

逆时针方向旋转坐标系统a度。

请参考translate()、scale()、shear()、resetXForm()、setWorldMatrix()和xForm()。

实例：aclock/aclock.cpp、t10/cannon.cpp和t9/cannon.cpp。

void QPainter::save ()

保存当前绘图工具状态（把状态压到栈中）。save()必须被一个相对应的restore()跟随。end()将释放栈。

请参考restore()。

实例： aclock/aclock.cpp。

void QPainter::saveWorldMatrix ()

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

我们建议使用save()来替代它。

void QPainter::scale ( double sx, double sy )

通过(sx, sy)拉伸坐标系统。

请参考translate()、shear()、rotate()、resetXForm()、setWorldMatrix()和xForm()。

实例： xform/xform.cpp。

void QPainter::setBackgroundColor ( const QColor & c )

设置绘图工具的背景色为c。

背景色是当绘制不透明文本、点画线和位图时填充的颜色。背景色在透明背景模式（这是默认的）下无效。

请参考backgroundColor()、setBackgroundMode()和BackgroundMode。

void QPainter::setBackgroundMode ( BGMode m )

设置绘图工具的背景模式为m，它必须是TransparentMode（默认）或者OpaqueMode。

透明模式绘制不设置背景像素绘制点画线和文本。不透明模式使用当前背景颜色填充这些空间。

注意为了绘制透明的位图和像素映射，你必须使用QPixmap::setMask()。

请参考backgroundMode()和setBackgroundColor()。

实例： picture/picture.cpp。

void QPainter::setBrush ( BrushStyle style )

设置绘图工具的画刷为黑色和特定的style。

请参考brush()和QBrush。

实例：aclock/aclock.cpp、drawdemo/drawdemo.cpp、picture/picture.cpp、t10/cannon.cpp、t9/cannon.cpp、themes/wood.cpp和tooltip/tooltip.cpp。

void QPainter::setBrush ( const QBrush & brush )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具的画刷为brush。

brush定义了外形如何被填充。

请参考brush()。

void QPainter::setBrush ( const QColor & color )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具的画刷具有风格SolidPattern和特定的color。

请参考brush()和QBrush。

void QPainter::setBrushOrigin ( int x, int y )

设置画刷原点为(x, y)。

画刷原点指定绘图工具的画刷的(0, 0)坐标。这个设置只适用于模式画刷和像素映射画刷。

请参考brushOrigin()。

void QPainter::setBrushOrigin ( const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置画刷原点为点p。

void QPainter::setClipRect ( int x, int y, int w, int h, CoordinateMode m = CoordDevice )

设置裁剪区域为矩形x、y、w、h并且使裁剪生效。裁剪模式被设置为m。

注意裁剪区域是在物理设备坐标中给定的并且如果m等于CoordDevice（默认），不服从任何坐标转换。如果m等于CoordPainter，返回的区域在模型坐标中。

请参考setClipRegion()、clipRegion()、setClipping()和QPainter::CoordinateMode。

实例：grapher/grapher.cpp、progress/progress.cpp、qtimage/qtimage.cpp、showimg/showimg.cpp、splitter/splitter.cpp和trivial/trivial.cpp。

void QPainter::setClipRect ( const QRect & r, CoordinateMode m = CoordDevice )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置裁剪区域为矩形r并且使裁剪生效。裁剪模式被设置为m。

请参考CoordinateMode。

void QPainter::setClipRegion ( const QRegion & rgn, CoordinateMode m = CoordDevice )

设置裁剪区域为rgn并且使裁剪生效。裁剪模式被设置为m。

注意裁剪区域是在物理设备坐标中给定的并且不服从任何坐标转换。

请参考setClipRect()、clipRegion()、setClipping()和CoordinateMode。

实例：qfd/fontdisplayer.cpp和themes/wood.cpp。

void QPainter::setClipping ( bool enable )

如果enable为真，使裁剪生效，或者如果enable为假，使裁剪失效。

请参考hasClipping()、setClipRect()和setClipRegion()。

实例： themes/wood.cpp。

void QPainter::setFont ( const QFont & font )

设置绘图工具的字体为font。

这个字体被后面的drawText()函数使用。文本颜色和画笔颜色相同。

请参考font()和drawText()。

实例：application/application.cpp、drawdemo/drawdemo.cpp、grapher/grapher.cpp、hello/hello.cpp、picture/picture.cpp、t13/cannon.cpp和xform/xform.cpp。

void QPainter::setPen ( const QPen & pen )

设置新的绘图工具画笔。

pen定义了如何绘制线和轮廓，并且它也定义了文本颜色。

请参考pen()。

实例：desktop/desktop.cpp、drawdemo/drawdemo.cpp、progress/progress.cpp、t10/cannon.cpp、t9/cannon.cpp、themes/metal.cpp和themes/wood.cpp。

void QPainter::setPen ( PenStyle style )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具画笔有风格style、宽为0并且为黑色。

请参考pen()和QPen。

void QPainter::setPen ( const QColor & color )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具画笔有风格SolidLine、宽为0并且为特定的color。

请参考pen()和QPen。

void QPainter::setRasterOp ( RasterOp r )

设置光栅操作为r。默认为CopyROP。

请参考rasterOp()和Qt::RasterOp。

void QPainter::setTabArray ( int * ta )

设置tab stop数组为ta。这将把tab stop放到ta[0]、ta[1]等等。这个数组是以零结束的。

如果tab数组和tab stop大小被设置，tab数组先生效。

请参考tabArray()、setTabStops()、drawText()和fontMetrics()。

void QPainter::setTabStops ( int ts )

设置tab stop宽度为ts，也就是说在ts、2*ts、3*ts等等定位tab stop。

当绘制设置了ExpandTabs的格式化文本时，tab stop被用到。只有在没有tab数组被设置（这是默认的情况）的情况下，这个确定的tab stop值被使用。

请参考tabStops()、setTabArray()、drawText()和fontMetrics()。

void QPainter::setViewXForm ( bool enable )

如果enable为真，使视转换生效，或者如果enable为假，使视转换失效。

请参考hasViewXForm()、setWindow()、setViewport()、setWorldMatrix()、setWorldXForm()和xForm()。

void QPainter::setViewport ( int x, int y, int w, int h )

设置绘图工具的视口矩形视转换并且使视转换生效。

视口矩形是视转换的一部分。视口指定了设备坐标系统并且被x、y、w宽和h高参数指定。它的姐妹window()指定了逻辑坐标系统。

默认视口矩形和设备矩形一样。关于坐标转换的概述请参考坐标系统概述。

请参考viewport()、setWindow()、setViewXForm()、setWorldMatrix()、setWorldXForm()和xForm()。

实例： aclock/aclock.cpp。

void QPainter::setViewport ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具的视口为矩形r。

void QPainter::setWindow ( int x, int y, int w, int h )

设置绘图工具的窗口矩形视转换并且使视转换生效。

窗口矩形是视转换的一部分。窗口指定了逻辑坐标系统并且被x、y、w宽和h高参数指定。它的姐妹viewport()指定了设备坐标系统。

默认窗口矩形和设备矩形一样。关于坐标转换的概述请参考坐标系统概述。

请参考window()、setViewport()、setViewXForm()、setWorldMatrix()和setWorldXForm()。

实例：aclock/aclock.cpp和drawdemo/drawdemo.cpp。

void QPainter::setWindow ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置绘图工具的窗口为矩形r。

void QPainter::setWorldMatrix ( const QWMatrix & m, bool combine = FALSE )

设置世界变换矩阵为m并且使世界变换生效。

如果combine为真，那么m与当前变换矩阵组合，否则m替代当前变换矩阵。

如果m是单位矩阵并且combine为假，这个函数调用setWorldXForm(FALSE)。（单位矩阵是QWMatrix::m11()和QWMatrix::m22()为1.0并且其它为0.0的矩阵。）

在视变换（也就是window和viewport）之后世界变换被应用。

下列的函数不使用QWMatrix就可以转换坐标系统：

  • translate()
  • scale()
  • shear()
  • rotate()

它们在绘制工具的worldMatrix()上操作并且像这样重新实现：

        void QPainter::rotate( double a )
        {
            QWMatrix m;
            m.rotate( a );
            setWorldMatrix( m, TRUE );
        }

注意当你在QPicture中绘制时，你应该总是使用combine。否则它也许不可能会使用其它变换来重放图片。使用translate()、scale()等等是安全的。

关于坐标系统的简要概述，请参考坐标系统概述。

请参考worldMatrix()、setWorldXForm()、setWindow()、setViewport()、setViewXForm()、xForm()和QWMatrix。

实例：drawdemo/drawdemo.cpp和xform/xform.cpp。

void QPainter::setWorldXForm ( bool enable )

如果enable为真，使世界变换生效，或者如果enable为假，使世界变换失效。世界变换矩阵不被改变。

请参考setWorldMatrix()、setWindow()、setViewport()、setViewXForm()和xForm()。

void QPainter::shear ( double sh, double sv )

使用(sh, sv)来裁剪坐标系统。

请参考translate()、scale()、rotate()、resetXForm()、setWorldMatrix()和xForm()。

int * QPainter::tabArray () const

返回当前设置的tab stop数组。

请参考setTabArray()。

int QPainter::tabStops () const

返回当前的tab stop设置。

请参考setTabStops()。

void QPainter::translate ( double dx, double dy )

使用(dx, dy)变换坐标系统。这次调用之后，(dx, dy)被添加到所有点上。

例如，下面这个代码在同一个点上绘制两次：

        void MyWidget::paintEvent()
        {
            QPainter paint( this );

            paint.drawPoint( 0, 0 );

            paint.translate( 100.0, 40.0 );
            paint.drawPoint( -100, -40 );
        }

请参考scale()、shear()、rotate()、resetXForm()、setWorldMatrix()和xForm()。

实例：helpviewer/helpwindow.cpp、t10/cannon.cpp、t9/cannon.cpp、themes/metal.cpp、themes/wood.cpp和xform/xform.cpp。

QRect QPainter::viewport () const

返回视口矩形。

请参考setViewport()和setViewXForm()。

实例： aclock/aclock.cpp。

QRect QPainter::window () const

返回窗口矩形。

请参考setWindow()和setViewXForm()。

const QWMatrix & QPainter::worldMatrix () const

返回世界变换矩阵。

请参考setWorldMatrix()。

QPoint QPainter::xForm ( const QPoint & pv ) const

返回从模式坐标中的点pv到系统坐标的变换。

请参考xFormDev()和QWMatrix::map()。

QRect QPainter::xForm ( const QRect & rv ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从模式坐标中的矩形rv到系统坐标的变换。

如果世界变换生效并且已经指定旋转或者裁剪，那么边界矩形被返回。

请参考xFormDev()和QWMatrix::map()。

QPointArray QPainter::xForm ( const QPointArray & av ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从模式坐标中的点的数组av到系统坐标的变换。

请参考xFormDev()和QWMatrix::map()。

QPointArray QPainter::xForm ( const QPointArray & av, int index, int npoints ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从模式坐标中的点的数组av到系统坐标的变换。index是数组中的第一个点并且npoints表示被变换的点的个数。如果npoints为负数，数组中从av[index]开始的所有点都被变换。

返回数组由所有变换后的点组成。

实例：

        QPointArray a(10);
        QPointArray b;
        b = painter.xForm(a, 2, 4);  // b.size() == 4
        b = painter.xForm(a, 2, -1); // b.size() == 8

请参考xFormDev()和QWMatrix::map()。

QRect QPainter::xFormDev ( const QRect & rd ) const

返回从系统坐标中的矩形rd到模式坐标的变换。

如果世界变换生效并且已经指定旋转或者裁剪，那么边界矩形被返回。

请参考xForm()和QWMatrix::map()。

QPoint QPainter::xFormDev ( const QPoint & pd ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从系统坐标中的点pd到模式坐标的变换。

请参考xForm()和QWMatrix::map()。

QPointArray QPainter::xFormDev ( const QPointArray & ad ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从系统坐标中的点的数组ad到模式坐标的变换。

请参考xForm()和QWMatrix::map()。

QPointArray QPainter::xFormDev ( const QPointArray & ad, int index, int npoints ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回从系统坐标中的点的数组ad到模式坐标的变换。index是数组中的第一个点并且npoints表示被变换的点的个数。如果npoints为负数，数组中从ad[index]开始的所有点都被变换。

返回数组由所有变换后的点组成。

实例：

        QPointArray a(10);
        QPointArray b;
        b = painter.xFormDev(a, 1, 3);  // b.size() == 3
        b = painter.xFormDev(a, 1, -1); // b.size() == 9

请参考xForm()和QWMatrix::map()。

相关函数

void qDrawPlainRect ( QPainter * p, int x, int y, int w, int h, const QColor & c, int lineWidth, const QBrush * fill )

#include <qdrawutil.h>

使用绘图工具p绘制由（x、y、w、h）指定的简单矩形。

颜色参数c指定了线的颜色。

lineWidth参数指定了线宽。

只要fill不为0，矩形内部就被*fill画刷填充。

如果你想使用一个QFrame窗口部件替代，你可以把它显示为一个简单矩形，例如QFrame::setFrameStyle( QFrame::Box | QFrame::Plain )。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawShadeRect()和QStyle::drawPrimitive()。

void qDrawShadeLine ( QPainter * p, int x1, int y1, int x2, int y2, const QColorGroup & g, bool sunken, int lineWidth, int midLineWidth )

#include <qdrawutil.h>

使用绘图工具p绘制水平的（y1 == y2）或者垂直的（x1 == x2）阴影线。

如果y1 != y2并且x1 != x2（也就是说这个线既不是水平的也不是垂直的），就什么也不绘制。

颜色组参数g指定了阴影色（light、dark和middle色）。

如果sunken为真，线看起来下陷，或者如果sunken为假，线看起来上凸。

lineWidth参数指定了每条线的线宽。它不是总线宽。

midLineWidth参数指定了使用QColorGroup::mid()颜色绘制的中间线的宽度。

如果你想使用一个QFrame窗口部件替代，你可以把它显示为一个简单阴影线，例如QFrame::setFrameStyle( QFrame::HLine | QFrame::Sunken )。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawShadeRect()、qDrawShadePanel()和QStyle::drawPrimitive()。

void qDrawShadePanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, int lineWidth, const QBrush * fill )

#include <qdrawutil.h>

使用绘图工具p绘制由（x、y、w、h）指定的阴影面板。

颜色组参数g指定了阴影色（light、dark和middle色）。

如果sunken为真，面板看起来下陷，或者如果sunken为假，面板看起来上凸。

lineWidth参数指定了线宽。

只要fill不为0，面板内部就被*fill画刷填充。

如果你想使用一个QFrame窗口部件替代，你可以把它显示为一个阴影面板，例如QFrame::setFrameStyle( QFrame::Panel | QFrame::Sunken )。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawWinPanel()、qDrawShadeLine()、qDrawShadeRect()和QStyle::drawPrimitive()。

void qDrawShadeRect ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, int lineWidth, int midLineWidth, const QBrush * fill )

#include <qdrawutil.h>

使用绘图工具p绘制由（x、y、w、h）指定的阴影矩形。

颜色组参数g指定了阴影色（light、dark和middle色）。

如果sunken为真，矩形看起来下陷，或者如果sunken为假，矩形看起来上凸。

lineWidth参数指定了每条线的线宽。它不是总线宽。

midLineWidth参数指定了使用QColorGroup::mid()颜色绘制的中间线的宽度。

只要fill不为0，矩形内部就被*fill画刷填充。

如果你想使用一个QFrame窗口部件替代，你可以把它显示为一个阴影矩形，例如QFrame::setFrameStyle( QFrame::Box | QFrame::Raised )。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawShadeLine()、qDrawShadePanel()、qDrawPlainRect()、QStyle::drawItem()、QStyle::drawControl()和QStyle::drawComplexControl()。

void qDrawWinButton ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, const QBrush * fill )

#include <qdrawutil.h>

使用绘图工具p绘制由（x、y、w、h）指定的Windows风格的按钮。

颜色组参数g指定了阴影色（light、dark和middle色）。

如果sunken为真，按钮看起来下陷，或者如果sunken为假，按钮看起来上凸。

线宽为2像素。

只要fill不为0，按钮内部就被*fill画刷填充。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawWinPanel()和QStyle::drawControl()。

void qDrawWinPanel ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool sunken, const QBrush * fill )

#include <qdrawutil.h>

使用绘图工具p绘制由（x、y、w、h）指定的Windows风格的面板。

颜色组参数g指定了阴影色（light、dark和middle色）。

如果sunken为真，面板看起来下陷，或者如果sunken为假，面板看起来上凸。

线宽为2像素。

只要fill不为0，面板内部就被*fill画刷填充。

如果你想使用一个QFrame窗口部件替代，你可以把它显示为一个Windows风格的面板，例如QFrame::setFrameStyle( QFrame::WinPanel | QFrame::Raised )。

警告：这个函数不会考虑QWidget::style()或者QApplication::style()。在QStyle中使用这个绘制函数可以使窗口部件遵循当前图形用户界面风格。

请参考qDrawShadePanel()、qDrawWinButton()和QStyle::drawPrimitive()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qpainter.h包含文件

qpainter.h

这里是qpainter.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qpainter.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPainter class
**
** Created : 940112
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPAINTER_H
#define QPAINTER_H

#ifndef QT_H
#include "qcolor.h"
#include "qfontmetrics.h"
#include "qfontinfo.h"
#include "qregion.h"
#include "qpen.h"
#include "qbrush.h"
#include "qpointarray.h"
#include "qwmatrix.h"
#endif // QT_H

class QGfx;
class QTextCodec;
class QTextParag;
class QPaintDevice;
#if defined( Q_WS_MAC )
class QMacSavedPortInfo;
#endif
class QPainterPrivate;

class Q_EXPORT QPainter : public Qt
{
public:
    enum CoordinateMode { CoordDevice, CoordPainter };

    QPainter();
    QPainter( const QPaintDevice *, bool unclipped = FALSE );
    QPainter( const QPaintDevice *, const QWidget *, bool unclipped = FALSE );
   ~QPainter();

    bool	begin( const QPaintDevice *, bool unclipped = FALSE );
    bool	begin( const QPaintDevice *, const QWidget *, bool unclipped = FALSE );
    bool	end();
    QPaintDevice *device() const;

#ifdef Q_WS_QWS
    QGfx * internalGfx();
#endif

    static void redirect( QPaintDevice *pdev, QPaintDevice *replacement );

    bool	isActive() const;

    void	flush( const QRegion &region, CoordinateMode cm = CoordDevice );
    void	flush();
    void	save();
    void	restore();

  // Drawing tools

    QFontMetrics fontMetrics()	const;
    QFontInfo	 fontInfo()	const;

    const QFont &font()		const;
    void	setFont( const QFont & );
    const QPen &pen()		const;
    void	setPen( const QPen & );
    void	setPen( PenStyle );
    void	setPen( const QColor & );
    const QBrush &brush()	const;
    void	setBrush( const QBrush & );
    void	setBrush( BrushStyle );
    void	setBrush( const QColor & );
    QPoint	pos() const;

  // Drawing attributes/modes

    const QColor &backgroundColor() const;
    void	setBackgroundColor( const QColor & );
    BGMode	backgroundMode() const;
    void	setBackgroundMode( BGMode );
    RasterOp	rasterOp()	const;
    void	setRasterOp( RasterOp );
    const QPoint &brushOrigin() const;
    void	setBrushOrigin( int x, int y );
    void	setBrushOrigin( const QPoint & );

  // Scaling and transformations

//    PaintUnit unit()	       const;		// get set painter unit
//    void	setUnit( PaintUnit );		// NOT IMPLEMENTED!!!

    bool	hasViewXForm() const;
    bool	hasWorldXForm() const;

#ifndef QT_NO_TRANSFORMATIONS
    void	setViewXForm( bool );		// set xform on/off
    QRect	window()       const;		// get window
    void	setWindow( const QRect & );	// set window
    void	setWindow( int x, int y, int w, int h );
    QRect	viewport()   const;		// get viewport
    void	setViewport( const QRect & );	// set viewport
    void	setViewport( int x, int y, int w, int h );

    void	setWorldXForm( bool );		// set world xform on/off
    const QWMatrix &worldMatrix() const;	// get/set world xform matrix
    void	setWorldMatrix( const QWMatrix &, bool combine=FALSE );

    void	saveWorldMatrix();
    void	restoreWorldMatrix();

    void	scale( double sx, double sy );
    void	shear( double sh, double sv );
    void	rotate( double a );
#endif
    void	translate( double dx, double dy );
    void	resetXForm();
    double	translationX() const;
    double	translationY() const;

    QPoint	xForm( const QPoint & ) const;	// map virtual -> device
    QRect	xForm( const QRect & )	const;
    QPointArray xForm( const QPointArray & ) const;
    QPointArray xForm( const QPointArray &, int index, int npoints ) const;
    QPoint	xFormDev( const QPoint & ) const; // map device -> virtual
    QRect	xFormDev( const QRect & )  const;
    QPointArray xFormDev( const QPointArray & ) const;
    QPointArray xFormDev( const QPointArray &, int index, int npoints ) const;

  // Clipping

    void	setClipping( bool );		// set clipping on/off
    bool	hasClipping() const;
    QRegion clipRegion( CoordinateMode = CoordDevice ) const;
    void	setClipRect( const QRect &, CoordinateMode = CoordDevice );	// set clip rectangle
    void	setClipRect( int x, int y, int w, int h, CoordinateMode = CoordDevice );
    void	setClipRegion( const QRegion &, CoordinateMode = CoordDevice );// set clip region

  // Graphics drawing functions

    void	drawPoint( int x, int y );
    void	drawPoint( const QPoint & );
    void	drawPoints( const QPointArray& a,
                int index=0, int npoints=-1 );
    void	moveTo( int x, int y );
    void	moveTo( const QPoint & );
    void	lineTo( int x, int y );
    void	lineTo( const QPoint & );
    void	drawLine( int x1, int y1, int x2, int y2 );
    void	drawLine( const QPoint &, const QPoint & );
    void	drawRect( int x, int y, int w, int h );
    void	drawRect( const QRect & );
    void	drawWinFocusRect( int x, int y, int w, int h );
    void	drawWinFocusRect( int x, int y, int w, int h,
                  const QColor &bgColor );
    void	drawWinFocusRect( const QRect & );
    void	drawWinFocusRect( const QRect &,
                  const QColor &bgColor );
    void	drawRoundRect( int x, int y, int w, int h, int = 25, int = 25 );
    void	drawRoundRect( const QRect &, int = 25, int = 25 );
    void	drawEllipse( int x, int y, int w, int h );
    void	drawEllipse( const QRect & );
    void	drawArc( int x, int y, int w, int h, int a, int alen );
    void	drawArc( const QRect &, int a, int alen );
    void	drawPie( int x, int y, int w, int h, int a, int alen );
    void	drawPie( const QRect &, int a, int alen );
    void	drawChord( int x, int y, int w, int h, int a, int alen );
    void	drawChord( const QRect &, int a, int alen );
    void	drawLineSegments( const QPointArray &,
                  int index=0, int nlines=-1 );
    void	drawPolyline( const QPointArray &,
                  int index=0, int npoints=-1 );
    void	drawPolygon( const QPointArray &, bool winding=FALSE,
                 int index=0, int npoints=-1 );
    void	drawConvexPolygon( const QPointArray &,
                 int index=0, int npoints=-1 );
#ifndef QT_NO_BEZIER
    void	drawCubicBezier( const QPointArray &, int index=0 );
#endif
    void	drawPixmap( int x, int y, const QPixmap &,
                int sx=0, int sy=0, int sw=-1, int sh=-1 );
    void	drawPixmap( const QPoint &, const QPixmap &,
                const QRect &sr );
    void	drawPixmap( const QPoint &, const QPixmap & );
    void	drawPixmap( const QRect &, const QPixmap & );
    void	drawImage( int x, int y, const QImage &,
               int sx = 0, int sy = 0, int sw = -1, int sh = -1,
               int conversionFlags = 0 );
    void	drawImage( const QPoint &, const QImage &,
               const QRect &sr, int conversionFlags = 0 );
    void	drawImage( const QPoint &, const QImage &,
               int conversion_flags = 0 );
    void	drawImage( const QRect &, const QImage & );
    void	drawTiledPixmap( int x, int y, int w, int h, const QPixmap &,
                 int sx=0, int sy=0 );
    void	drawTiledPixmap( const QRect &, const QPixmap &,
                 const QPoint & );
    void	drawTiledPixmap( const QRect &, const QPixmap & );
#ifndef QT_NO_PICTURE
    void	drawPicture( const QPicture & );
    void	drawPicture( int x, int y, const QPicture & );
    void	drawPicture( const QPoint &, const QPicture & );
#endif

    void	fillRect( int x, int y, int w, int h, const QBrush & );
    void	fillRect( const QRect &, const QBrush & );
    void	eraseRect( int x, int y, int w, int h );
    void	eraseRect( const QRect & );

  // Text drawing functions

    enum TextDirection {
    Auto,
    RTL,
    LTR
    };

    void	drawText( int x, int y, const QString &, int len = -1, TextDirection dir = Auto );
    void	drawText( const QPoint &, const QString &, int len = -1, TextDirection dir = Auto );

    void     drawText( int x, int y, const QString &, int pos, int len, TextDirection dir = Auto );
    void     drawText( const QPoint &p, const QString &, int pos, int len, TextDirection dir = Auto );

    void	drawText( int x, int y, int w, int h, int flags,
              const QString&, int len = -1, QRect *br=0,
              QTextParag **intern=0 );
    void	drawText( const QRect &, int flags,
              const QString&, int len = -1, QRect *br=0,
              QTextParag **intern=0 );

    //#####    void	drawText( const QPoint &, const QString &, int flags, int rotation = 0);

  // Text drawing functions

    QRect	boundingRect( int x, int y, int w, int h, int flags,
                  const QString&, int len = -1, QTextParag **intern=0 );
    QRect	boundingRect( const QRect &, int flags,
                  const QString&, int len = -1, QTextParag **intern=0 );

    int		tabStops() const;
    void	setTabStops( int );
    int	       *tabArray() const;
    void	setTabArray( int * );

    // Other functions

#if defined(Q_WS_WIN)
    HDC		handle() const;
#elif defined(Q_WS_X11)
    HANDLE	handle() const;
#endif

    static void initialize();
    static void cleanup();

private:
    void	init();
    void        destroy();
    void	updateFont();
    void	updatePen();
    void	updateBrush();
#ifndef QT_NO_TRANSFORMATIONS
    void	updateXForm();
    void	updateInvXForm();
#endif
    void	map( int, int, int *rx, int *ry ) const;
    void	map( int, int, int, int, int *, int *, int *, int * ) const;
    void	mapInv( int, int, int *, int * ) const;
    void	mapInv( int, int, int, int, int *, int *, int *, int * ) const;
    void	drawPolyInternal( const QPointArray &, bool close=TRUE );
    void	drawWinFocusRect( int x, int y, int w, int h, bool xorPaint,
                  const QColor &penColor );

    enum { IsActive=0x01, ExtDev=0x02, IsStartingUp=0x04, NoCache=0x08,
       VxF=0x10, WxF=0x20, ClipOn=0x40, SafePolygon=0x80, MonoDev=0x100,
       DirtyFont=0x200, DirtyPen=0x400, DirtyBrush=0x800,
       RGBColor=0x1000, FontMet=0x2000, FontInf=0x4000, CtorBegin=0x8000,
           UsePrivateCx = 0x10000, VolatileDC = 0x20000, Qt2Compat = 0x40000 };
    uint	flags;
    bool	testf( uint b ) const { return (flags&b)!=0; }
    void	setf( uint b )	{ flags |= b; }
    void	setf( uint b, bool v );
    void	clearf( uint b )	{ flags &= (uint)(~b); }
    void	fix_neg_rect( int *x, int *y, int *w, int *h );

    QPainterPrivate *d;
    QPaintDevice *pdev;
    QColor	bg_col;
    uchar	bg_mode;
    uchar	rop;
    uchar	pu;
    QPoint	bro;
    QFont	cfont;
    QFont *pfont; 	// font used for metrics (might be different for printers)
    QPen	cpen;
    QBrush	cbrush;
    QRegion	crgn;
    int		tabstops;
    int	       *tabarray;
    int		tabarraylen;
    bool	block_ext;	// for temporary blocking of external devices

    // Transformations
#ifndef QT_NO_TRANSFORMATIONS
    QCOORD	wx, wy, ww, wh;
    QCOORD	vx, vy, vw, vh;
    QWMatrix	wxmat;

    // Cached composition (and inverse) of transformations
    QWMatrix	xmat;
    QWMatrix	ixmat;

    double	m11() const { return xmat.m11(); }
    double      m12() const { return xmat.m12(); }
    double      m21() const { return xmat.m21(); }
    double      m22() const { return xmat.m22(); }
    double      dx() const { return xmat.dx(); }
    double      dy() const { return xmat.dy(); }
    double	im11() const { return ixmat.m11(); }
    double      im12() const { return ixmat.m12(); }
    double      im21() const { return ixmat.m21(); }
    double      im22() const { return ixmat.m22(); }
    double      idx() const { return ixmat.dx(); }
    double      idy() const { return ixmat.dy(); }

    int		txop;
    bool	txinv;

#else
    // even without transformations we still have translations
    int		xlatex;
    int		xlatey;
#endif

    void       *penRef;				// pen cache ref
    void       *brushRef;			// brush cache ref
    void       *ps_stack;
    void       *wm_stack;
    void	killPStack();

protected:
#ifdef Q_OS_TEMP
    QPoint	internalCurrentPos;
#endif
#if defined(Q_WS_WIN)
    QT_WIN_PAINTER_MEMBERS
#elif defined(Q_WS_X11)
    Display    *dpy;				// current display
    int		scrn;				// current screen
    Qt::HANDLE	hd;				// handle to drawable
    Qt::HANDLE  rendhd;				// handle to Render Picture
    GC		gc;				// graphics context (standard)
    GC		gc_brush;			// graphics contect for brush
    QPoint	curPt;				// current point
    uint	clip_serial;			// clipping serial number
#elif defined(Q_WS_MAC)
    void initPaintDevice(bool force=FALSE);
#elif defined(Q_WS_QWS)
    QGfx * gfx;
#endif
    friend class QFontMetrics;
    friend class QFontInfo;
    friend void qt_format_text( const QFont &, const QRect &r,
             int tf, const QString& str, int len, QRect *brect,
             int tabstops, int* tabarray, int tabarraylen,
             QTextParag **internal, QPainter* painter );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPainter( const QPainter & );
    QPainter &operator=( const QPainter & );
#endif
};

/*****************************************************************************
  QPainter member functions
 *****************************************************************************/

inline QPaintDevice *QPainter::device() const
{
    return pdev;
}

inline bool QPainter::isActive() const
{
    return testf(IsActive);
}

inline const QFont &QPainter::font() const
{
    return cfont;
}

inline const QPen &QPainter::pen() const
{
    return cpen;
}

inline const QBrush &QPainter::brush() const
{
    return cbrush;
}

/*
inline PaintUnit QPainter::unit() const
{
    return (PaintUnit)pu;
}
*/

inline const QColor &QPainter::backgroundColor() const
{
    return bg_col;
}

inline Qt::BGMode QPainter::backgroundMode() const
{
    return (BGMode)bg_mode;
}

inline Qt::RasterOp QPainter::rasterOp() const
{
    return (RasterOp)rop;
}

inline const QPoint &QPainter::brushOrigin() const
{
    return bro;
}

inline bool QPainter::hasViewXForm() const
{
#ifndef QT_NO_TRANSFORMATIONS
    return testf(VxF);
#else
    return xlatex || xlatey;
#endif
}

inline bool QPainter::hasWorldXForm() const
{
#ifndef QT_NO_TRANSFORMATIONS
    return testf(WxF);
#else
    return xlatex || xlatey;
#endif
}

inline double QPainter::translationX() const
{
#ifndef QT_NO_TRANSFORMATIONS
    return worldMatrix().dx();
#else
    return xlatex;
#endif
}

inline double QPainter::translationY() const
{
#ifndef QT_NO_TRANSFORMATIONS
    return worldMatrix().dy();
#else
    return xlatey;
#endif
}

inline bool QPainter::hasClipping() const
{
    return testf(ClipOn);
}

inline int QPainter::tabStops() const
{
    return tabstops;
}

inline int *QPainter::tabArray() const
{
    return tabarray;
}

#if defined(Q_WS_WIN)
inline HDC QPainter::handle() const
{
    return hdc;
}
#elif defined(Q_WS_X11)
inline Qt::HANDLE QPainter::handle() const
{
    return hd;
}
#endif

inline void QPainter::setBrushOrigin( const QPoint &p )
{
    setBrushOrigin( p.x(), p.y() );
}

#ifndef QT_NO_TRANSFORMATIONS
inline void QPainter::setWindow( const QRect &r )
{
    setWindow( r.x(), r.y(), r.width(), r.height() );
}

inline void QPainter::setViewport( const QRect &r )
{
    setViewport( r.x(), r.y(), r.width(), r.height() );
}
#endif

inline void QPainter::setClipRect( int x, int y, int w, int h, CoordinateMode m )
{
    setClipRect( QRect(x,y,w,h), m );
}

inline void QPainter::drawPoint( const QPoint &p )
{
    drawPoint( p.x(), p.y() );
}

inline void QPainter::moveTo( const QPoint &p )
{
    moveTo( p.x(), p.y() );
}

inline void QPainter::lineTo( const QPoint &p )
{
    lineTo( p.x(), p.y() );
}

inline void QPainter::drawLine( const QPoint &p1, const QPoint &p2 )
{
    drawLine( p1.x(), p1.y(), p2.x(), p2.y() );
}

inline void QPainter::drawRect( const QRect &r )
{
    drawRect( r.x(), r.y(), r.width(), r.height() );
}

inline void QPainter::drawWinFocusRect( const QRect &r )
{
    drawWinFocusRect( r.x(), r.y(), r.width(), r.height() );
}

inline void QPainter::drawWinFocusRect( const QRect &r,const QColor &penColor )
{
    drawWinFocusRect( r.x(), r.y(), r.width(), r.height(), penColor );
}

inline void QPainter::drawRoundRect( const QRect &r, int xRnd, int yRnd )
{
    drawRoundRect( r.x(), r.y(), r.width(), r.height(), xRnd, yRnd );
}

inline void QPainter::drawEllipse( const QRect &r )
{
    drawEllipse( r.x(), r.y(), r.width(), r.height() );
}

inline void QPainter::drawArc( const QRect &r, int a, int alen )
{
    drawArc( r.x(), r.y(), r.width(), r.height(), a, alen );
}

inline void QPainter::drawPie( const QRect &r, int a, int alen )
{
    drawPie( r.x(), r.y(), r.width(), r.height(), a, alen );
}

inline void QPainter::drawChord( const QRect &r, int a, int alen )
{
    drawChord( r.x(), r.y(), r.width(), r.height(), a, alen );
}

inline void QPainter::drawPixmap( const QPoint &p, const QPixmap &pm,
                  const QRect &sr )
{
    drawPixmap( p.x(), p.y(), pm, sr.x(), sr.y(), sr.width(), sr.height() );
}

inline void QPainter::drawImage( const QPoint &p, const QImage &pm,
                                 const QRect &sr, int conversionFlags )
{
    drawImage( p.x(), p.y(), pm,
           sr.x(), sr.y(), sr.width(), sr.height(), conversionFlags );
}

inline void QPainter::drawTiledPixmap( const QRect &r, const QPixmap &pm,
                       const QPoint &sp )
{
    drawTiledPixmap( r.x(), r.y(), r.width(), r.height(), pm, sp.x(), sp.y() );
}

inline void QPainter::drawTiledPixmap( const QRect &r, const QPixmap &pm )
{
    drawTiledPixmap( r.x(), r.y(), r.width(), r.height(), pm, 0, 0 );
}

inline void QPainter::fillRect( const QRect &r, const QBrush &brush )
{
    fillRect( r.x(), r.y(), r.width(), r.height(), brush );
}

inline void QPainter::eraseRect( int x, int y, int w, int h )
{
    fillRect( x, y, w, h, backgroundColor() );
}

inline void QPainter::eraseRect( const QRect &r )
{
    fillRect( r.x(), r.y(), r.width(), r.height(), backgroundColor() );
}

inline void QPainter::drawText( const QPoint &p, const QString &s, int len, TextDirection dir )
{
    drawText( p.x(), p.y(), s, 0, len, dir );
}

inline void QPainter::drawText( const QPoint &p, const QString &s, int pos, int len, TextDirection dir )
{
    drawText( p.x(), p.y(), s, pos, len, dir );
}

inline void QPainter::drawText( int x, int y, int w, int h, int tf,
                const QString& str, int len, QRect *br, QTextParag **i )
{
    QRect r(x, y, w, h);
    drawText( r, tf, str, len, br, i );
}

inline QRect QPainter::boundingRect( int x, int y, int w, int h, int tf,
                     const QString& str, int len, QTextParag **i )
{
    QRect r(x, y, w, h);
    return boundingRect( r, tf, str, len, i );
}

#if defined(Q_WS_QWS)
inline QGfx * QPainter::internalGfx()
{
    return gfx;
}
#endif

#endif // QPAINTER_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPainter成员列表

完整的QPainter成员列表

这里是QPainter成员函数的完整列表，包括继承的成员。

  • QPainter()
  • ~QPainter()
  • backgroundColor()
  • backgroundMode()
  • begin()
  • boundingRect()
  • brush()
  • brushOrigin()
  • clipRegion()
  • device()
  • drawArc()
  • drawChord()
  • drawConvexPolygon()
  • drawCubicBezier()
  • drawEllipse()
  • drawImage()
  • drawLine()
  • drawLineSegments()
  • drawPicture()
  • drawPie()
  • drawPixmap()
  • drawPoint()
  • drawPoints()
  • drawPolygon()
  • drawPolyline()
  • drawRect()
  • drawRoundRect()
  • drawText()
  • drawTiledPixmap()
  • drawWinFocusRect()
  • end()
  • eraseRect()
  • fillRect()
  • flush()
  • font()
  • fontInfo()
  • fontMetrics()
  • handle()
  • hasClipping()
  • hasViewXForm()
  • hasWorldXForm()
  • isActive()
  • lineTo()
  • moveTo()
  • pen()
  • pos()
  • rasterOp()
  • redirect()
  • resetXForm()
  • restore()
  • restoreWorldMatrix()
  • rotate()
  • save()
  • saveWorldMatrix()
  • scale()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBrush()
  • setBrushOrigin()
  • setClipRect()
  • setClipRegion()
  • setClipping()
  • setFont()
  • setPen()
  • setRasterOp()
  • setTabArray()
  • setTabStops()
  • setViewXForm()
  • setViewport()
  • setWindow()
  • setWorldMatrix()
  • setWorldXForm()
  • shear()
  • tabArray()
  • tabStops()
  • translate()
  • viewport()
  • window()
  • worldMatrix()
  • xForm()
  • xFormDev()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPaintEvent Class

QPaintEvent Class Reference

The QPaintEvent class contains event parameters for paint events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QPaintEvent ( const QRegion & paintRegion, bool erased = TRUE )
  • QPaintEvent ( const QRect & paintRect, bool erased = TRUE )
  • const QRect & rect () const
  • const QRegion & region () const
  • bool erased () const

Detailed Description

The QPaintEvent class contains event parameters for paint events.

Paint events are sent to widgets that need to update themselves, for instance when part of a widget is exposed because a covering widget is moved.

The event contains a region() that needs to be updated, and a rect() that is the bounding rectangle of that region. Both are provided because many widgets can't make much use of region(), and rect() can be much faster than region().boundingRect(). Painting is clipped to region() during processing of a paint event.

The erased() function returns TRUE if the region() has been cleared to the widget's background (see QWidget::backgroundMode()), and FALSE if the region's contents are arbitrary.

See also QPainter, QWidget::update(), QWidget::repaint(), QWidget::paintEvent(), QWidget::backgroundMode, QRegion and Event Classes.

Member Function Documentation

QPaintEvent::QPaintEvent ( const QRegion & paintRegion, bool erased = TRUE )

Constructs a paint event object with the region that should be updated. The region is given by paintRegion. If erased is TRUE the region will be cleared before repainting.

QPaintEvent::QPaintEvent ( const QRect & paintRect, bool erased = TRUE )

Constructs a paint event object with the rectangle that should be updated. The region is given by paintRect. If erased is TRUE the region will be cleared before repainting.

bool QPaintEvent::erased () const

Returns TRUE if the paint event region (or rectangle) has been erased with the widget's background; otherwise returns FALSE.

const QRect & QPaintEvent::rect () const

Returns the rectangle that should be updated.

See also region() and QPainter::setClipRect().

Examples: life/life.cpp, qfd/fontdisplayer.cpp, showimg/showimg.cpp, t10/cannon.cpp, t11/cannon.cpp, t13/cannon.cpp and tooltip/tooltip.cpp.

const QRegion & QPaintEvent::region () const

Returns the region that should be updated.

See also rect() and QPainter::setClipRegion().

Examples: qfd/fontdisplayer.cpp and scribble/scribble.cpp.

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


QPaintEvent Member List

Complete Member List for QPaintEvent

This is the complete list of member functions for QPaintEvent, including inherited members.

  • QPaintEvent()
  • erased()
  • rect()
  • region()
  • spontaneous()
  • type()


QPair Class

QPair Class Reference

The QPair class is a value-based template class that provides a pair of elements. More...

#include <qpair.h>

List of all member functions.

Public Members

  • typedef T1 first_type
  • typedef T2 second_type
  • QPair ()
  • QPair ( const T1 & t1, const T2 & t2 )

Related Functions

  • QPair qMakePair ( T1 t1, T2 t2 )

Detailed Description

The QPair class is a value-based template class that provides a pair of elements.

QPair is a Qt implementation of an STL-like pair. It can be used in your application if the standard pair<> is not available.

QPair<T1, T2> defines a template instance to create a pair of values that contains two values of type T1 and T2. Please note that QPair does not store pointers to the two elements; it holds a copy of every member. This is why these kinds of classes are called value based. If you're interested in pointer based classes see, for example, QPtrList and QDict.

QPair holds one copy of type T1 and one copy of type T2, but does not provide iterators to access these elements. Rather, the two elements (first and second) are public member variables of the pair. QPair owns the contained elements. For more relaxed ownership semantics, see QPtrCollection and friends which are pointer-based containers.

Some classes cannot be used within a QPair: for example, all classes derived from QObject and thus all classes that implement widgets. Only "values" can be used in a QPair. To qualify as a value the class must provide:

  • A copy constructor
  • An assignment operator
  • A constructor that takes no argument

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient.

QPair uses an STL-like syntax to manipulate and address the objects it contains. See the QTL documentation for more information.

Functions that need to return two values can use a QPair. The qMakePair() convenience function makes it easy to create QPair objects.

See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

Member Type Documentation

QPair::first_type

The type of the first element in the pair.

QPair::second_type

The type of the second element in the pair.

Member Function Documentation

QPair::QPair ()

Constructs an empty pair. The first and second elements are default constructed.

QPair::QPair ( const T1 & t1, const T2 & t2 )

Constructs a pair and initializes the first element with t1 and the second element with t2.

Related Functions

QPair qMakePair ( T1 t1, T2 t2 )

This is a template convenience function. It is used to create a QPair<> object that contains t1 and t2. For example:

    QMap<QString,QString> m;
    m.insert( qMakePair("Clinton", "Bill") );

The above code is equivalent to:

    QMap<QString,QString> m;
    QPair<QString,QString> p( "Clinton", "Bill" );
    m.insert( p );

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


qpair.h Include File

qpair.h

This is the verbatim text of the qpair.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QPair class
**
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPAIR_H
#define QPAIR_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

template <class T1, class T2>
struct QPair
{
    typedef T1 first_type;
    typedef T2 second_type;

    QPair()
    : first( T1() ), second( T2() )
    {}
    QPair( const T1& t1, const T2& t2 )
    : first( t1 ), second( t2 )
    {}

    T1 first;
    T2 second;
};

template <class T1, class T2>
Q_INLINE_TEMPLATES bool operator==( const QPair<T1, T2>& x, const QPair<T1, T2>& y )
{
    return x.first == y.first && x.second == y.second;
}

template <class T1, class T2>
Q_INLINE_TEMPLATES bool operator<( const QPair<T1, T2>& x, const QPair<T1, T2>& y )
{
    // x < y is TRUE if:
    // x.first is less than y.first,
    // or if x.second is less that y.second and x.first is the same as y.first
    return x.first < y.first ||	( !( y.first < x.first ) && x.second < y.second );
}

template <class T1, class T2>
Q_INLINE_TEMPLATES QPair<T1, T2> qMakePair( const T1& x, const T2& y )
{
    return QPair<T1, T2>( x, y );
}

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPair Member List

Complete Member List for QPair

This is the complete list of member functions for QPair, including inherited members.

  • QPair()


QPalette Class

QPalette Class Reference

The QPalette class contains color groups for each widget state. More...

#include <qpalette.h>

List of all member functions.

Public Members

  • QPalette ()
  • QPalette ( const QColor & button ) (obsolete)
  • QPalette ( const QColor & button, const QColor & background )
  • QPalette ( const QColorGroup & active, const QColorGroup & disabled, const QColorGroup & inactive )
  • QPalette ( const QPalette & p )
  • ~QPalette ()
  • QPalette & operator= ( const QPalette & p )
  • enum ColorGroup { Disabled, Active, Inactive, NColorGroups, Normal = Active }
  • const QColor & color ( ColorGroup gr, QColorGroup::ColorRole r ) const
  • const QBrush & brush ( ColorGroup gr, QColorGroup::ColorRole r ) const
  • void setColor ( ColorGroup gr, QColorGroup::ColorRole r, const QColor & c )
  • void setBrush ( ColorGroup gr, QColorGroup::ColorRole r, const QBrush & b )
  • void setColor ( QColorGroup::ColorRole r, const QColor & c )
  • void setBrush ( QColorGroup::ColorRole r, const QBrush & b )
  • QPalette copy () const
  • const QColorGroup & active () const
  • const QColorGroup & disabled () const
  • const QColorGroup & inactive () const
  • const QColorGroup & normal () const (obsolete)
  • void setActive ( const QColorGroup & g )
  • void setDisabled ( const QColorGroup & g )
  • void setInactive ( const QColorGroup & g )
  • void setNormal ( const QColorGroup & cg ) (obsolete)
  • bool operator== ( const QPalette & p ) const
  • bool operator!= ( const QPalette & p ) const
  • bool isCopyOf ( const QPalette & p )
  • int serialNumber () const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QPalette & p )
  • QDataStream & operator>> ( QDataStream & s, QPalette & p )

Detailed Description

The QPalette class contains color groups for each widget state.

A palette consists of three color groups: active, disabled, and inactive. All widgets contain a palette, and all widgets in Qt use their palette to draw themselves. This makes the user interface easily configurable and easier to keep consistent.

If you create a new widget we strongly recommend that you use the colors in the palette rather than hard-coding specific colors.

The color groups:

  • The active() group is used for the window that has keyboard focus.
  • The inactive() group is used for other windows.
  • The disabled() group is used for widgets (not windows) that are disabled for some reason.

Both active and inactive windows can contain disabled widgets. (Disabled widgets are often called inaccessible or grayed out.)

In Motif style, active() and inactive() look the same. In Windows 2000 style and Macintosh Platinum style, the two styles look slightly different.

There are setActive(), setInactive(), and setDisabled() functions to modify the palette. (Qt also supports a normal() group; this is an obsolete alias for active(), supported for backwards compatibility.)

Colors and brushes can be set for particular roles in any of a palette's color groups with setColor() and setBrush().

You can copy a palette using the copy constructor and test to see if two palettes are identical using isCopyOf().

See also QApplication::setPalette(), QWidget::palette, QColorGroup, QColor, Widget Appearance and Style, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Type Documentation

QPalette::ColorGroup

  • QPalette::Disabled
  • QPalette::Active
  • QPalette::Inactive
  • QPalette::NColorGroups
  • QPalette::Normal - synonym for Active

Member Function Documentation

QPalette::QPalette ()

Constructs a palette that consists of color groups with only black colors.

QPalette::QPalette ( const QColor & button )

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

Constructs a palette from the button color. The other colors are automatically calculated, based on this color. Background will be the button color as well.

QPalette::QPalette ( const QColor & button, const QColor & background )

Constructs a palette from a button color and a background. The other colors are automatically calculated, based on these colors.

QPalette::QPalette ( const QColorGroup & active, const QColorGroup & disabled, const QColorGroup & inactive )

Constructs a palette that consists of the three color groups active, disabled and inactive. See the Detailed Description for definitions of the color groups and QColorGroup::ColorRole for definitions of each color role in the three groups.

See also QColorGroup and QColorGroup::ColorRole.

QPalette::QPalette ( const QPalette & p )

Constructs a copy of p.

This constructor is fast (it uses copy-on-write).

QPalette::~QPalette ()

Destroys the palette.

const QColorGroup & QPalette::active () const

Returns the active color group of this palette.

See also QColorGroup, setActive(), inactive() and disabled().

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

const QBrush & QPalette::brush ( ColorGroup gr, QColorGroup::ColorRole r ) const

Returns the brush in color group gr, used for color role r.

See also color(), setBrush() and QColorGroup::ColorRole.

const QColor & QPalette::color ( ColorGroup gr, QColorGroup::ColorRole r ) const

Returns the color in color group gr, used for color role r.

See also brush(), setColor() and QColorGroup::ColorRole.

QPalette QPalette::copy () const

Returns a deep copy of this palette.

Warning: This is slower than the copy constructor and assignment operator and offers no benefits.

const QColorGroup & QPalette::disabled () const

Returns the disabled color group of this palette.

See also QColorGroup, setDisabled(), active() and inactive().

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

const QColorGroup & QPalette::inactive () const

Returns the inactive color group of this palette.

See also QColorGroup, setInactive(), active() and disabled().

bool QPalette::isCopyOf ( const QPalette & p )

Returns TRUE if this palette and p are copies of each other, i.e. one of them was created as a copy of the other and neither was subsequently modified; otherwise returns FALSE. This is much stricter than equality.

See also operator=() and operator==().

const QColorGroup & QPalette::normal () const

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

Returns the active color group. Use active() instead.

See also setActive() and active().

bool QPalette::operator!= ( const QPalette & p ) const

Returns TRUE (slowly) if this palette is different from p; otherwise returns FALSE (usually quickly).

QPalette & QPalette::operator= ( const QPalette & p )

Assigns p to this palette and returns a reference to this palette.

This is fast (it uses copy-on-write).

See also copy().

bool QPalette::operator== ( const QPalette & p ) const

Returns TRUE (usually quickly) if this palette is equal to p; otherwise returns FALSE (slowly).

int QPalette::serialNumber () const

Returns a number that uniquely identifies this QPalette object. The serial number is intended for caching. Its value may not be used for anything other than equality testing.

Note that QPalette uses copy-on-write, and the serial number changes during the lazy copy operation (detach()), not during a shallow copy (copy constructor or assignment).

See also QPixmap, QPixmapCache and QCache.

void QPalette::setActive ( const QColorGroup & g )

Sets the Active color group to g.

See also active(), setDisabled(), setInactive() and QColorGroup.

void QPalette::setBrush ( ColorGroup gr, QColorGroup::ColorRole r, const QBrush & b )

Sets the brush in color group gr, used for color role r, to b.

See also brush(), setColor() and QColorGroup::ColorRole.

void QPalette::setBrush ( QColorGroup::ColorRole r, const QBrush & b )

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

Sets the brush in for color role r in all three color groups to b.

See also brush(), setColor(), QColorGroup::ColorRole, active(), inactive() and disabled().

void QPalette::setColor ( ColorGroup gr, QColorGroup::ColorRole r, const QColor & c )

Sets the brush in color group gr, used for color role r, to the solid color c.

See also setBrush(), color() and QColorGroup::ColorRole.

Example: themes/themes.cpp.

void QPalette::setColor ( QColorGroup::ColorRole r, const QColor & c )

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

Sets the brush color used for color role r to color c in all three color groups.

See also color(), setBrush() and QColorGroup::ColorRole.

void QPalette::setDisabled ( const QColorGroup & g )

Sets the Disabled color group to g.

See also disabled(), setActive() and setInactive().

void QPalette::setInactive ( const QColorGroup & g )

Sets the Inactive color group to g.

See also active(), setDisabled(), setActive() and QColorGroup.

void QPalette::setNormal ( const QColorGroup & cg )

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

Sets the active color group to cg. Use setActive() instead.

See also setActive() and active().

Related Functions

QDataStream & operator<< ( QDataStream & s, const QPalette & p )

Writes the palette, p to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QPalette & p )

Reads a palette from the stream, s into the palette p, and returns a reference to the stream.

See also Format of the QDataStream operators.

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


qpalette.h Include File

qpalette.h

This is the verbatim text of the qpalette.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpalette.h   3.0.5   edited Mar 4 11:28 $
**
** Definition of QColorGroup and QPalette classes
**
** Created : 950323
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPALETTE_H
#define QPALETTE_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qcolor.h"
#include "qshared.h"
#include "qbrush.h" // QColor->QBrush conversion
#endif // QT_H

#ifndef QT_NO_PALETTE

class QColorGroupPrivate;

class Q_EXPORT QColorGroup
{
public:
    QColorGroup();
    QColorGroup( const QColor &foreground, const QColor &button,
         const QColor &light, const QColor &dark, const QColor &mid,
         const QColor &text, const QColor &base );
    QColorGroup( const QBrush &foreground, const QBrush &button,
         const QBrush &light, const QBrush &dark, const QBrush &mid,
         const QBrush &text, const QBrush &bright_text,
         const QBrush &base, const QBrush &background);
    QColorGroup( const QColorGroup & );

   ~QColorGroup();

    QColorGroup& operator =(const QColorGroup&);

    // Do not change the order, the serialization format depends on it
    enum ColorRole { Foreground, Button, Light, Midlight, Dark, Mid,
             Text, BrightText, ButtonText, Base, Background, Shadow,
             Highlight, HighlightedText, Link, LinkVisited,
             NColorRoles };

    const QColor &color( ColorRole ) const;
    const QBrush &brush( ColorRole ) const;
    void setColor( ColorRole, const QColor & );
    void setBrush( ColorRole, const QBrush & );

    const QColor &foreground()	const	{ return br[Foreground].color(); }
    const QColor &button()	const	{ return br[Button].color(); }
    const QColor &light()	const	{ return br[Light].color(); }
    const QColor &dark()	const	{ return br[Dark].color(); }
    const QColor &mid()		const	{ return br[Mid].color(); }
    const QColor &text()	const	{ return br[Text].color(); }
    const QColor &base()	const	{ return br[Base].color(); }
    const QColor &background()	const	{ return br[Background].color(); }

    const QColor &midlight()	const	{ return br[Midlight].color(); }
    const QColor &brightText()	const	{ return br[BrightText].color(); }
    const QColor &buttonText()	const	{ return br[ButtonText].color(); }
    const QColor &shadow()	const	{ return br[Shadow].color(); }
    const QColor &highlight()	const	{ return br[Highlight].color(); }
    const QColor &highlightedText() const{return br[HighlightedText].color(); }
    const QColor &link()        const   { return br[Link].color(); }
    const QColor &linkVisited() const   { return br[LinkVisited].color(); }

    bool	operator==( const QColorGroup &g ) const;
    bool	operator!=( const QColorGroup &g ) const
    { return !(operator==(g)); }

private:
    QBrush *br;
    QColorGroupPrivate * d;

    friend class QPalette;
};

class Q_EXPORT QPalette
{
public:
    QPalette();
    QPalette( const QColor &button );
    QPalette( const QColor &button, const QColor &background );
    QPalette( const QColorGroup &active, const QColorGroup &disabled,
          const QColorGroup &inactive );
    QPalette( const QPalette & );
    ~QPalette();
    QPalette &operator=( const QPalette & );

    enum ColorGroup { Disabled, Active, Inactive, NColorGroups, Normal=Active };

    const QColor &color( ColorGroup, QColorGroup::ColorRole ) const;
    const QBrush &brush( ColorGroup, QColorGroup::ColorRole ) const;
    void setColor( ColorGroup, QColorGroup::ColorRole, const QColor & );
    void setBrush( ColorGroup, QColorGroup::ColorRole, const QBrush & );

    void setColor( QColorGroup::ColorRole, const QColor & );
    void setBrush( QColorGroup::ColorRole, const QBrush & );

    QPalette	copy() const;

    const QColorGroup &active() const { return data->active; }
    const QColorGroup &disabled() const { return data->disabled; }
    const QColorGroup &inactive() const { return data->inactive; }
#ifndef QT_NO_COMPAT
    const QColorGroup &normal() const { return active(); }
#endif

    void	setActive( const QColorGroup & );
    void	setDisabled( const QColorGroup & );
    void	setInactive( const QColorGroup & );
#ifndef QT_NO_COMPAT
    void	setNormal( const QColorGroup & cg ) { setActive(cg); }
#endif

    bool	operator==( const QPalette &p ) const;
    bool	operator!=( const QPalette &p ) const
              { return !(operator==(p)); }
    bool	isCopyOf( const QPalette & );

    int		serialNumber() const	{ return data->ser_no; }

    static QColorGroup::ColorRole foregroundRoleFromMode( Qt::BackgroundMode mode );
    static QColorGroup::ColorRole backgroundRoleFromMode( Qt::BackgroundMode mode);

private:
    void	detach();
    const QBrush &directBrush( ColorGroup, QColorGroup::ColorRole ) const;
    void directSetBrush( ColorGroup, QColorGroup::ColorRole, const QBrush& );

    struct QPalData : public QShared {
    QColorGroup disabled;
    QColorGroup active;
    int	    ser_no;
    QColorGroup inactive;
    } *data;
};

/*****************************************************************************
  QColorGroup/QPalette stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QColorGroup & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QColorGroup & );

Q_EXPORT QDataStream &operator<<( QDataStream &, const QPalette & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPalette & );
#endif // QT_NO_DATASTREAM

#endif // QT_NO_PALETTE
#endif // QPALETTE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPalette Member List

Complete Member List for QPalette

This is the complete list of member functions for QPalette, including inherited members.

  • QPalette()
  • ~QPalette()
  • active()
  • brush()
  • color()
  • copy()
  • disabled()
  • inactive()
  • isCopyOf()
  • normal()
  • operator!=()
  • operator=()
  • operator==()
  • serialNumber()
  • setActive()
  • setBrush()
  • setColor()
  • setDisabled()
  • setInactive()
  • setNormal()


QPen Class

QPen Class Reference

The QPen class defines how a QPainter should draw lines and outlines of shapes. More...

#include <qpen.h>

Inherits Qt.

List of all member functions.

Public Members

  • QPen ()
  • QPen ( PenStyle style )
  • QPen ( const QColor & color, uint width = 0, PenStyle style = SolidLine )
  • QPen ( const QColor & cl, uint w, PenStyle s, PenCapStyle c, PenJoinStyle j )
  • QPen ( const QPen & p )
  • ~QPen ()
  • QPen & operator= ( const QPen & p )
  • PenStyle style () const
  • void setStyle ( PenStyle s )
  • uint width () const
  • void setWidth ( uint w )
  • const QColor & color () const
  • void setColor ( const QColor & c )
  • PenCapStyle capStyle () const
  • void setCapStyle ( PenCapStyle c )
  • PenJoinStyle joinStyle () const
  • void setJoinStyle ( PenJoinStyle j )
  • bool operator== ( const QPen & p ) const
  • bool operator!= ( const QPen & p ) const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QPen & p )
  • QDataStream & operator>> ( QDataStream & s, QPen & p )

Detailed Description

The QPen class defines how a QPainter should draw lines and outlines of shapes.

A pen has a style, width, color, cap style and join style.

The pen style defines the line type. The default pen style is Qt::SolidLine. Setting the style to NoPen tells the painter to not draw lines or outlines.

When drawing 1 pixel wide diagonal lines you can either use a very fast algorithm (specified by a line width of 0, which is the default), or a slower but more accurate algorithm (specified by a line width of 1). For horizontal and vertical lines a line width of 0 is the same as a line width of 1. The cap and join style have no effect on 0-width lines.

The pen color defines the color of lines and text. The default line color is black. The QColor documentation lists predefined colors.

The cap style defines how the end points of lines are drawn. The join style defines how the joins between two lines are drawn when multiple connected lines are drawn (QPainter::drawPolyLine() etc.). The cap and join styles only apply to wide lines, i.e. when the width is 1 or greater.

Use the QBrush class to specify fill styles.

Example:

    QPainter painter;
    QPen     pen( red, 2 );             // red solid line, 2 pixels wide
    painter.begin( &anyPaintDevice );   // paint something
    painter.setPen( pen );              // set the red, wide pen
    painter.drawRect( 40,30, 200,100 ); // draw a rectangle
    painter.setPen( blue );             // set blue pen, 0 pixel width
    painter.drawLine( 40,30, 240,130 ); // draw a diagonal in rectangle
    painter.end();                      // painting done

See the Qt::PenStyle enum type for a complete list of pen styles.

With reference to the end points of lines, for wide (non-0-width) pens it depends on the cap style whether the end point is drawn or not. QPainter will try to make sure that the end point is drawn for 0-width pens, but this cannot be absolutely guaranteed because the underlying drawing engine is free to use any (typically accelerated) algorithm for drawing 0-width lines. On all tested systems, however, the end point of at least all non-diagonal lines are drawn.

A pen's color(), width(), style(), capStyle() and joinStyle() can be set in the constructor or later with setColor(), setWidth(), setStyle(), setCapStyle() and setJoinStyle(). Pens may also be compared and streamed.

See also QPainter, QPainter::setPen(), Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QPen::QPen ()

Constructs a default black solid line pen with 0 width, which renders lines 1 pixel wide (fast diagonals).

QPen::QPen ( PenStyle style )

Constructs a black pen with 0 width (fast diagonals) and style style.

See also setStyle().

QPen::QPen ( const QColor & color, uint width = 0, PenStyle style = SolidLine )

Constructs a pen with the specified color, width and style.

See also setWidth(), setStyle() and setColor().

QPen::QPen ( const QColor & cl, uint w, PenStyle s, PenCapStyle c, PenJoinStyle j )

Constructs a pen with the specified color cl and width w. The pen style is set to s, the pen cap style to c and the pen join style to j.

A line width of 0 will produce a 1 pixel wide line using a fast algorithm for diagonals. A line width of 1 will also produce a 1 pixel wide line, but uses a slower more accurate algorithm for diagonals. For horizontal and vertical lines a line width of 0 is the same as a line width of 1. The cap and join style have no effect on 0-width lines.

See also setWidth(), setStyle() and setColor().

QPen::QPen ( const QPen & p )

Constructs a pen that is a copy of p.

QPen::~QPen ()

Destroys the pen.

PenCapStyle QPen::capStyle () const

Returns the pen's cap style.

See also setCapStyle().

const QColor & QPen::color () const

Returns the pen color.

See also setColor().

Example: scribble/scribble.h.

PenJoinStyle QPen::joinStyle () const

Returns the pen's join style.

See also setJoinStyle().

bool QPen::operator!= ( const QPen & p ) const

Returns TRUE if the pen is different from p; otherwise returns FALSE.

Two pens are different if they have different styles, widths or colors.

See also operator==().

QPen & QPen::operator= ( const QPen & p )

Assigns p to this pen and returns a reference to this pen.

bool QPen::operator== ( const QPen & p ) const

Returns TRUE if the pen is equal to p; otherwise returns FALSE.

Two pens are equal if they have equal styles, widths and colors.

See also operator!=().

void QPen::setCapStyle ( PenCapStyle c )

Sets the pen's cap style to c.

The default value is FlatCap. The cap style has no effect on 0-width pens.

Pen Cap Styles

Warning: On Windows 95/98 and Macintosh, the cap style setting has no effect. Wide lines are rendered as if the cap style was SquareCap.

See also capStyle().

Example: themes/wood.cpp.

void QPen::setColor ( const QColor & c )

Sets the pen color to c.

See also color().

Examples: progress/progress.cpp and scribble/scribble.h.

void QPen::setJoinStyle ( PenJoinStyle j )

Sets the pen's join style to j.

The default value is MiterJoin. The join style has no effect on 0-width pens.

Pen Join Styles

Warning: On Windows 95/98 and Macintosh, the join style setting has no effect. Wide lines are rendered as if the join style was BevelJoin.

See also joinStyle().

Example: themes/wood.cpp.

void QPen::setStyle ( PenStyle s )

Sets the pen style to s.

See the Qt::PenStyle documentation for a list of all the styles.

Warning: On Windows 95/98 and Macintosh, the style setting (other than NoPen and SolidLine) has no effect for lines with width greater than 1.

See also style().

Example: chart/chartform_canvas.cpp.

void QPen::setWidth ( uint w )

Sets the pen width to w.

A line width of 0 will produce a 1 pixel wide line using a fast algorithm for diagonals. A line width of 1 will also produce a 1 pixel wide line, but uses a slower more accurate algorithm for diagonals. For horizontal and vertical lines a line width of 0 is the same as a line width of 1. The cap and join style have no effect on 0-width lines.

See also width().

Examples: progress/progress.cpp and scribble/scribble.h.

PenStyle QPen::style () const

Returns the pen style.

See also setStyle().

uint QPen::width () const

Returns the pen width.

See also setWidth().

Example: scribble/scribble.h.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QPen & p )

Writes the pen p to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QPen & p )

Reads a pen from the stream s into p and returns a reference to the stream.

See also Format of the QDataStream operators.

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


qpen.h Include File

qpen.h

This is the verbatim text of the qpen.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpen.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPen class
**
** Created : 940112
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPEN_H
#define QPEN_H

#ifndef QT_H
#include "qcolor.h"
#include "qshared.h"
#endif // QT_H

class Q_EXPORT QPen: public Qt
{
friend class QPainter;
public:
    QPen();
    QPen( PenStyle );
    QPen( const QColor &color, uint width=0, PenStyle style=SolidLine );
    QPen( const QColor &cl, uint w, PenStyle s, PenCapStyle c, PenJoinStyle j);
    QPen( const QPen & );
   ~QPen();
    QPen &operator=( const QPen & );

    PenStyle	style() const		{ return data->style; }
    void	setStyle( PenStyle );
    uint	width() const		{ return data->width; }
    void	setWidth( uint );
    const QColor &color() const		{ return data->color; }
    void	setColor( const QColor & );
    PenCapStyle	capStyle() const;
    void	setCapStyle( PenCapStyle );
    PenJoinStyle joinStyle() const;
    void	setJoinStyle( PenJoinStyle );

    bool	operator==( const QPen &p ) const;
    bool	operator!=( const QPen &p ) const
                    { return !(operator==(p)); }

private:
    QPen	copy()	const;
    void	detach();
    void	init( const QColor &, uint, uint );
    struct QPenData : public QShared {		// pen data
    PenStyle  style;
    uint	  width;
    QColor	  color;
    Q_UINT16  linest;
    } *data;
};

/*****************************************************************************
  QPen stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QPen & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPen & );
#endif

#endif // QPEN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPen Member List

Complete Member List for QPen

This is the complete list of member functions for QPen, including inherited members.

  • QPen()
  • ~QPen()
  • capStyle()
  • color()
  • joinStyle()
  • operator!=()
  • operator=()
  • operator==()
  • setCapStyle()
  • setColor()
  • setJoinStyle()
  • setStyle()
  • setWidth()
  • style()
  • width()


QPicture Class

QPicture Class Reference

The QPicture class is a paint device that records and replays QPainter commands. More...

#include <qpicture.h>

Inherits QPaintDevice.

List of all member functions.

Public Members

  • QPicture ( int formatVersion = -1 )
  • QPicture ( const QPicture & pic )
  • ~QPicture ()
  • bool isNull () const
  • uint size () const
  • const char * data () const
  • virtual void setData ( const char * data, uint size )
  • bool play ( QPainter * painter )
  • bool load ( QIODevice * dev, const char * format = 0 )
  • bool load ( const QString & fileName, const char * format = 0 )
  • bool save ( QIODevice * dev, const char * format = 0 )
  • bool save ( const QString & fileName, const char * format = 0 )
  • QRect boundingRect () const
  • QPicture & operator= ( const QPicture & p )

Protected Members

  • virtual int metric ( int m ) const
  • void detach ()
  • QPicture copy () const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QPicture & r )
  • QDataStream & operator>> ( QDataStream & s, QPicture & r )

Detailed Description

The QPicture class is a paint device that records and replays QPainter commands.

A picture serializes painter commands to an IO device in a platform-independent format. For example, a picture created under Windows can be read on a Sun SPARC.

Pictures are called meta-files on some platforms.

Qt pictures use a proprietary binary format. Unlike native picture (meta-file) formats on many window systems, Qt pictures have no limitations regarding their contents. Everything that can be painted can also be stored in a picture, e.g. fonts, pixmaps, regions, transformed graphics, etc.

QPicture is an implicitly shared class.

Example of how to record a picture:

    QPicture  pic;
    QPainter  p;
    p.begin( &pic );               // paint in picture
    p.drawEllipse( 10,20, 80,70 ); // draw an ellipse
    p.end();                       // painting done
    pic.save( "drawing.pic" );     // save picture

Example of how to replay a picture:

    QPicture  pic;
    pic.load( "drawing.pic" );     // load picture
    QPainter  p;
    p.begin( &myWidget );          // paint in myWidget
    p.drawPicture( pic );          // draw the picture
    p.end();                       // painting done

Pictures can also be drawn using play(). Some basic data about a picture is available, for example, size(), isNull() and boundingRect().

See also Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QPicture::QPicture ( int formatVersion = -1 )

Constructs an empty picture.

The formatVersion parameter may be used to create a QPicture that can be read by applications that are compiled with earlier versions of Qt.

  • formatVersion == 1 is binary compatible with Qt 1.x and later.
  • formatVersion == 2 is binary compatible with Qt 2.0.x and later.
  • formatVersion == 3 is binary compatible with Qt 2.1.x and later.
  • formatVersion == 4 is binary compatible with Qt 3.x.

Note that the default formatVersion is -1 which signifies the current release, i.e. for Qt 3.0 a formatVersion of 4 is the same as the default formatVersion of -1.

Reading pictures generated by earlier versions of Qt is supported and needs no special coding; the format is automatically detected.

QPicture::QPicture ( const QPicture & pic )

Constructs a shallow copy of pic.

QPicture::~QPicture ()

Destroys the picture.

QRect QPicture::boundingRect () const

Returns the picture's bounding rectangle or an invalid rectangle if the picture contains no data.

QPicture QPicture::copy () const [protected]

Returns a deep copy of the picture.

const char * QPicture::data () const

Returns a pointer to the picture data. The pointer is only valid until the next non-const function is called on this picture. The returned pointer is 0 if the picture contains no data.

See also size() and isNull().

void QPicture::detach () [protected]

Detaches from shared picture data and makes sure that this picture is the only one referring to the data.

If multiple pictures share common data, this picture makes a copy of the data and detaches itself from the sharing mechanism. Nothing is done if there is just a single reference.

bool QPicture::isNull () const

Returns TRUE if the picture contains no data; otherwise returns FALSE.

bool QPicture::load ( const QString & fileName, const char * format = 0 )

Loads a picture from the file specified by fileName and returns TRUE if successful; otherwise returns FALSE.

By default, the file will be interpreted as being in the native QPicture format. Specifying the format string is optional and is only needed for importing picture data stored in a different format.

Currently, the only external format supported is the W3C SVG format which requires the Qt XML module. The corresponding format string is "svg".

See also save().

Examples: picture/picture.cpp and xform/xform.cpp.

bool QPicture::load ( QIODevice * dev, const char * format = 0 )

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

dev is the device to use for loading.

int QPicture::metric ( int m ) const [virtual protected]

Internal implementation of the virtual QPaintDevice::metric() function.

Use the QPaintDeviceMetrics class instead.

A picture has the following hard-coded values: dpi=72, numcolors=16777216 and depth=24.

m is the metric to get.

QPicture & QPicture::operator= ( const QPicture & p )

Assigns a shallow copy of p to this picture and returns a reference to this picture.

bool QPicture::play ( QPainter * painter )

Replays the picture using painter, and returns TRUE if successful; otherwise returns FALSE.

This function does exactly the same as QPainter::drawPicture() with (x, y) = (0, 0).

bool QPicture::save ( const QString & fileName, const char * format = 0 )

Saves a picture to the file specified by fileName and returns TRUE if successful; otherwise returns FALSE.

Specifying the file format string is optional. It's not recommended unless you intend to export the picture data for use by a third party reader. By default the data will be saved in the native QPicture file format.

Currently, the only external format supported is the W3C SVG format which requires the Qt XML module. The corresponding format string is "svg".

See also load().

Example: picture/picture.cpp.

bool QPicture::save ( QIODevice * dev, const char * format = 0 )

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

dev is the device to use for saving.

void QPicture::setData ( const char * data, uint size ) [virtual]

Sets the picture data directly from data and size. This function copies the input data.

See also data() and size().

uint QPicture::size () const

Returns the size of the picture data.

See also data().

Related Functions

QDataStream & operator<< ( QDataStream & s, const QPicture & r )

Writes picture, r to the stream s and returns a reference to the stream.

QDataStream & operator>> ( QDataStream & s, QPicture & r )

Reads a picture from the stream s into picture r and returns a reference to the stream.

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


qpicture.h Include File

qpicture.h

This is the verbatim text of the qpicture.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpicture.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPicture class
**
** Created : 940729
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPICTURE_H
#define QPICTURE_H

#ifndef QT_H
#include "qpaintdevice.h"
#include "qbuffer.h"
#endif // QT_H

#ifndef QT_NO_PICTURE

class Q_EXPORT QPicture : public QPaintDevice		// picture class
{
public:
    QPicture( int formatVersion = -1 );
    QPicture( const QPicture & );
   ~QPicture();

    bool	isNull() const;

    uint	size() const;
    const char* data() const;
    virtual void setData( const char* data, uint size );

    bool	play( QPainter * );

    bool	load( QIODevice *dev, const char *format = 0 );
    bool	load( const QString &fileName, const char *format = 0 );
    bool	save( QIODevice *dev, const char *format = 0 );
    bool	save( const QString &fileName, const char *format = 0 );

    QRect boundingRect() const;

    QPicture& operator= (const QPicture&);

    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QPicture & );
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QPicture & );

protected:
    bool	cmd( int, QPainter *, QPDevCmdParam * );
    int		metric( int ) const;
    void	detach();
    QPicture	copy() const;

private:
    bool	exec( QPainter *, QDataStream &, int );

    struct QPicturePrivate : public QShared {
    bool	cmd( int, QPainter *, QPDevCmdParam * );
    bool	checkFormat();
    void	resetFormat();

    QBuffer	pictb;
    int	trecs;
    bool	formatOk;
    int	formatMajor;
    int	formatMinor;
    QRect	brect;
    } *d;
};

inline bool QPicture::isNull() const
{
    return d->pictb.buffer().isNull();
}

inline uint QPicture::size() const
{
    return d->pictb.buffer().size();
}

inline const char* QPicture::data() const
{
    return d->pictb.buffer().data();
}

/*****************************************************************************
  QPicture stream functions
 *****************************************************************************/

Q_EXPORT QDataStream &operator<<( QDataStream &, const QPicture & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPicture & );

#endif // QT_NO_PICTURE

#endif // QPICTURE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPicture Member List

Complete Member List for QPicture

This is the complete list of member functions for QPicture, including inherited members.

  • QPicture()
  • ~QPicture()
  • boundingRect()
  • cmd()
  • copy()
  • data()
  • detach()
  • handle()
  • isExtDev()
  • isNull()
  • load()
  • metric()
  • operator=()
  • paintingActive()
  • play()
  • save()
  • setData()
  • size()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()


QPixmap Class

QPixmap Class Reference

The QPixmap class is an off-screen, pixel-based paint device. More...

#include <qpixmap.h>

Inherits QPaintDevice and Qt.

Inherited by QBitmap and QCanvasPixmap.

List of all member functions.

Public Members

  • enum ColorMode { Auto, Color, Mono }
  • enum Optimization { DefaultOptim, NoOptim, MemoryOptim = NoOptim, NormalOptim, BestOptim }
  • QPixmap ()
  • QPixmap ( const QImage & image )
  • QPixmap ( int w, int h, int depth = -1, Optimization optimization = DefaultOptim )
  • QPixmap ( const QSize & size, int depth = -1, Optimization optimization = DefaultOptim )
  • QPixmap ( const QString & fileName, const char * format = 0, ColorMode mode = Auto )
  • QPixmap ( const QString & fileName, const char * format, int conversion_flags )
  • QPixmap ( const char * xpm[] )
  • QPixmap ( const QByteArray & img_data )
  • QPixmap ( const QPixmap & pixmap )
  • ~QPixmap ()
  • QPixmap & operator= ( const QPixmap & pixmap )
  • QPixmap & operator= ( const QImage & image )
  • bool isNull () const
  • int width () const
  • int height () const
  • QSize size () const
  • QRect rect () const
  • int depth () const
  • void fill ( const QColor & fillColor = Qt::white )
  • void fill ( const QWidget * widget, int xofs, int yofs )
  • void fill ( const QWidget * widget, const QPoint & ofs )
  • void resize ( int w, int h )
  • void resize ( const QSize & size )
  • const QBitmap * mask () const
  • void setMask ( const QBitmap & newmask )
  • bool selfMask () const
  • QBitmap createHeuristicMask ( bool clipTight = TRUE ) const
  • QPixmap xForm ( const QWMatrix & matrix ) const
  • QImage convertToImage () const
  • bool convertFromImage ( const QImage & image, ColorMode mode = Auto )
  • bool convertFromImage ( const QImage & img, int conversion_flags )
  • bool load ( const QString & fileName, const char * format = 0, ColorMode mode = Auto )
  • bool load ( const QString & fileName, const char * format, int conversion_flags )
  • bool loadFromData ( const uchar * buf, uint len, const char * format = 0, ColorMode mode = Auto )
  • bool loadFromData ( const uchar * buf, uint len, const char * format, int conversion_flags )
  • bool loadFromData ( const QByteArray & buf, const char * format = 0, int conversion_flags = 0 )
  • bool save ( const QString & fileName, const char * format, int quality = -1 ) const
  • int serialNumber () const
  • Optimization optimization () const
  • void setOptimization ( Optimization optimization )
  • virtual void detach ()
  • bool isQBitmap () const

Static Public Members

  • int defaultDepth ()
  • QPixmap grabWindow ( WId window, int x = 0, int y = 0, int w = -1, int h = -1 )
  • QPixmap grabWidget ( QWidget * widget, int x = 0, int y = 0, int w = -1, int h = -1 )
  • QWMatrix trueMatrix ( const QWMatrix & matrix, int w, int h )
  • const char * imageFormat ( const QString & fileName )
  • Optimization defaultOptimization ()
  • void setDefaultOptimization ( Optimization optimization )

Protected Members

  • QPixmap ( int w, int h, const uchar * bits, bool isXbitmap )
  • virtual int metric ( int m ) const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QPixmap & pixmap )
  • QDataStream & operator>> ( QDataStream & s, QPixmap & pixmap )

Detailed Description

The QPixmap class is an off-screen, pixel-based paint device.

QPixmap is one of the two classes Qt provides for dealing with images; the other is QImage. QPixmap is designed and optimized for drawing; QImage is designed and optimized for I/O and for direct pixel access/manipulation. There are (slow) functions to convert between QImage and QPixmap: convertToImage() and convertFromImage().

One common use of the QPixmap class is to enable smooth updating of widgets. Whenever something complex needs to be drawn, you can use a pixmap to obtain flicker-free drawing, like this:

  1. Create a pixmap with the same size as the widget.
  2. Fill the pixmap with the widget background color.
  3. Paint the pixmap.
  4. bitBlt() the pixmap contents onto the widget.

Pixel data in a pixmap is internal and is managed by the underlying window system. Pixels can be accessed only through QPainter functions, through bitBlt(), and by converting the QPixmap to a QImage.

You can easily display a QPixmap on the screen using QLabel::setPixmap(). For example, all the QButton subclasses support pixmap use.

The QPixmap class uses copy-on-write, so it is practical to pass QPixmap objects by value.

You can retrieve the width(), height(), depth() and size() of a pixmap. The enclosing rectangle is given by rect(). Pixmaps can be filled with fill() and resized with resize(). You can create and set a mask with createHeuristicMask() and setMask(). Use selfMask() to see if the pixmap is identical to its mask.

In addition to loading a pixmap from file using load() you can also loadFromData(). You can control optimization with setOptimization() and obtain a transformed version of the pixmap using xForm()

Note regarding Windows 95 and 98: on Windows 9x the system crashes if you create more than about 1000 pixmaps, independent of the size of the pixmaps or installed RAM. Windows NT and 2000 do not have this limitation.

Qt tries to work around the resource limitation. If you set the pixmap optimization to QPixmap::MemoryOptim and the width of your pixmap is less than or equal to 128 pixels, Qt stores the pixmap in a way that is very memory-efficient when there are many pixmaps.

If your application uses dozens or hundreds of pixmaps (for example on tool bar buttons and in popup menus), and you plan to run it on Windows 95 or Windows 98, we recommend using code like this:

        QPixmap::setDefaultOptimization( QPixmap::MemoryOptim );
        while ( ... ) {
            // load tool bar pixmaps etc.
            QPixmap *pixmap = new QPixmap(fileName);
        }
        QPixmap::setDefaultOptimization( QPixmap::NormalOptim );

See also QBitmap, QImage, QImageIO, Shared Classes, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Type Documentation

QPixmap::ColorMode

This enum type defines the color modes that exist for converting QImage objects to QPixmap.

  • QPixmap::Auto - Select Color or Mono on a case-by-case basis.
  • QPixmap::Color - Always create colored pixmaps.
  • QPixmap::Mono - Always create bitmaps.

QPixmap::Optimization

QPixmap has the choice of optimizing for speed or memory in a few places; the best choice varies from pixmap to pixmap but can generally be derived heuristically. This enum type defines a number of optimization modes that you can set for any pixmap to tweak the speed/memory tradeoffs:

  • QPixmap::DefaultOptim - Whatever QPixmap::defaultOptimization() returns. A pixmap with this optimization will have whatever the current default optimization is. If the default optimization is changed using setDefaultOptimization(), then this will not effect any pixmaps that have already been created.
  • QPixmap::NoOptim - No optimization (currently the same as MemoryOptim).
  • QPixmap::MemoryOptim - Optimize for minimal memory use.
  • QPixmap::NormalOptim - Optimize for typical usage. Often uses more memory than MemoryOptim, and is often faster.
  • QPixmap::BestOptim - Optimize for pixmaps that are drawn very often and where performance is critical. Generally uses more memory than NormalOptim and may provide a little more speed.

We recommend using DefaultOptim.

Member Function Documentation

QPixmap::QPixmap ()

Constructs a null pixmap.

See also isNull().

QPixmap::QPixmap ( const QImage & image )

Constructs a pixmap from the QImage image.

See also convertFromImage().

QPixmap::QPixmap ( int w, int h, int depth = -1, Optimization optimization = DefaultOptim )

Constructs a pixmap with w width, h height and depth bits per pixel. The pixmap is optimized in accordance with the optimization value.

The contents of the pixmap is uninitialized.

The depth can be either 1 (monochrome) or the depth of the current video mode. If depth is negative, then the hardware depth of the current video mode will be used.

If either w or h is zero, a null pixmap is constructed.

See also isNull() and QPixmap::Optimization.

QPixmap::QPixmap ( const QSize & size, int depth = -1, Optimization optimization = DefaultOptim )

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

Constructs a pixmap of size size, depth bits per pixel, optimized in accordance with the optimization value.

QPixmap::QPixmap ( const QString & fileName, const char * format = 0, ColorMode mode = Auto )

Constructs a pixmap from the file fileName. If the file does not exist or is of an unknown format, the pixmap becomes a null pixmap.

The fileName, format and mode parameters are passed on to load(). This means that the data in fileName is not compiled into the binary. If fileName contains a relative path (e.g. the filename only) the relevant file must be found relative to the runtime working directory.

See also QPixmap::ColorMode, isNull(), load(), loadFromData(), save() and imageFormat().

QPixmap::QPixmap ( const QString & fileName, const char * format, int conversion_flags )

Constructs a pixmap from the file fileName. If the file does not exist or is of an unknown format, the pixmap becomes a null pixmap.

The fileName, format and conversion_flags parameters are passed on to load(). This means that the data in fileName is not compiled into the binary. If fileName contains a relative path (e.g. the filename only) the relevant file must be found relative to the runtime working directory.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the conversion_flags to specify how you'd prefer this to happen.

See also Qt::ImageConversionFlags, isNull(), load(), loadFromData(), save() and imageFormat().

QPixmap::QPixmap ( const char * xpm[] )

Constructs a pixmap from xpm, which must be a valid XPM image.

Errors are silently ignored.

Note that it's possible to squeeze the XPM variable a little bit by using an unusual declaration:

        static const char * const start_xpm[]={
            "16 15 8 1",
            "a c #cec6bd",
        ....

The extra const makes the entire definition read-only, which is slightly more efficient (for example, when the code is in a shared library) and ROMable when the application is to be stored in ROM.

In order to use that sort of declaration you must cast the variable back to const char ** when you create the QPixmap.

QPixmap::QPixmap ( const QByteArray & img_data )

Constructs a pixmaps by loading from img_data. The data can be in any image format supported by Qt.

See also loadFromData().

QPixmap::QPixmap ( const QPixmap & pixmap )

Constructs a pixmap that is a copy of pixmap.

QPixmap::QPixmap ( int w, int h, const uchar * bits, bool isXbitmap ) [protected]

Constructs a monochrome pixmap, with width w and height h, that is initialized with the data in bits. The isXbitmap indicates whether the data is an X bitmap and defaults to FALSE. This constructor is protected and used by the QBitmap class.

QPixmap::~QPixmap ()

Destroys the pixmap.

bool QPixmap::convertFromImage ( const QImage & img, int conversion_flags )

Converts image img and sets this pixmap. Returns TRUE if successful; otherwise returns FALSE.

The conversion_flags argument is a bitwise-OR of the Qt::ImageConversionFlags. Passing 0 for conversion_flags sets all the default options.

Note that even though a QPixmap with depth 1 behaves much like a QBitmap, isQBitmap() returns FALSE.

If a pixmap with depth 1 is painted with color0 and color1 and converted to an image, the pixels painted with color0 will produce pixel index 0 in the image and those painted with color1 will produce pixel index 1.

See also convertToImage(), isQBitmap(), QImage::convertDepth(), defaultDepth() and QImage::hasAlphaBuffer().

Examples: canvas/canvas.cpp, qtimage/qtimage.cpp and themes/wood.cpp.

bool QPixmap::convertFromImage ( const QImage & image, ColorMode mode = Auto )

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

Converts image and sets this pixmap using color mode mode. Returns TRUE if successful; otherwise returns FALSE.

See also QPixmap::ColorMode.

QImage QPixmap::convertToImage () const

Converts the pixmap to a QImage. Returns a null image if it fails.

If the pixmap has 1-bit depth, the returned image will also be 1 bit deep. If the pixmap has 2- to 8-bit depth, the returned image has 8-bit depth. If the pixmap has greater than 8-bit depth, the returned image has 32-bit depth.

Note that for the moment, alpha masks on monochrome images are ignored.

See also convertFromImage().

Example: qmag/qmag.cpp.

QBitmap QPixmap::createHeuristicMask ( bool clipTight = TRUE ) const

Creates and returns a heuristic mask for this pixmap. It works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges.

The mask may not be perfect but it should be reasonable, so you can do things such as the following:

    pm->setMask( pm->createHeuristicMask() );

This function is slow because it involves transformation to a QImage, non-trivial computations and a transformation back to a QBitmap.

If clipTight is TRUE the mask is just large enough to cover the pixels; otherwise, the mask is larger than the data pixels.

See also QImage::createHeuristicMask().

int QPixmap::defaultDepth () [static]

Returns the default pixmap depth, i.e. the depth a pixmap gets if -1 is specified.

See also depth().

Optimization QPixmap::defaultOptimization () [static]

Returns the default pixmap optimization setting.

See also setDefaultOptimization(), setOptimization() and optimization().

int QPixmap::depth () const

Returns the depth of the pixmap.

The pixmap depth is also called bits per pixel (bpp) or bit planes of a pixmap. A null pixmap has depth 0.

See also defaultDepth(), isNull() and QImage::convertDepth().

void QPixmap::detach () [virtual]

This is a special-purpose function that detaches the pixmap from shared pixmap data.

A pixmap is automatically detached by Qt whenever its contents is about to change. This is done in all QPixmap member functions that modify the pixmap (fill(), resize(), convertFromImage(), load(), etc.), in bitBlt() for the destination pixmap and in QPainter::begin() on a pixmap.

It is possible to modify a pixmap without letting Qt know. You can first obtain the system-dependent handle() and then call system-specific functions (for instance, BitBlt under Windows) that modify the pixmap contents. In such cases, you can call detach() to cut the pixmap loose from other pixmaps that share data with this one.

detach() returns immediately if there is just a single reference or if the pixmap has not been initialized yet.

void QPixmap::fill ( const QColor & fillColor = Qt::white )

Fills the pixmap with the color fillColor.

Examples: chart/setdataform.cpp, desktop/desktop.cpp, grapher/grapher.cpp, hello/hello.cpp, t10/cannon.cpp, themes/metal.cpp and xform/xform.cpp.

void QPixmap::fill ( const QWidget * widget, int xofs, int yofs )

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

Fills the pixmap with the widget's background color or pixmap. If the background is empty, nothing is done. xofs, yofs is an offset in the widget.

void QPixmap::fill ( const QWidget * widget, const QPoint & ofs )

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

Fills the pixmap with the widget's background color or pixmap. If the background is empty, nothing is done.

The ofs point is an offset in the widget.

The point ofs is a point in the widget's coordinate system. The pixmap's top-left pixel will be mapped to the point ofs in the widget. This is significant if the widget has a background pixmap; otherwise the pixmap will simply be filled with the background color of the widget.

Example:

    void CuteWidget::paintEvent( QPaintEvent *e )
    {
        QRect ur = e->rect();            // rectangle to update
        QPixmap pix( ur.size() );        // Pixmap for double-buffering
        pix.fill( this, ur.topLeft() );  // fill with widget background

        QPainter p( &pix );
        p.translate( -ur.x(), -ur.y() ); // use widget coordinate system
                                         // when drawing on pixmap
        //    ... draw on pixmap ...

        p.end();

        bitBlt( this, ur.topLeft(), &pix );
    }

QPixmap QPixmap::grabWidget ( QWidget * widget, int x = 0, int y = 0, int w = -1, int h = -1 ) [static]

Creates a pixmap and paints widget in it.

If the widget has any children, then they are also painted in the appropriate positions.

If you specify x, y, w or h, only the rectangle you specify is painted. The defaults are 0, 0 (top-left corner) and -1,-1 (which means the entire widget).

(If w is negative, the function copies everything to the right border of the window. If h is negative, the function copies everything to the bottom of the window.)

If widget is 0, or if the rectangle defined by x, y, the modified w and the modified h does not overlap the widget->rect(), this function will return a null QPixmap.

This function actually asks widget to paint itself (and its children to paint themselves). QPixmap::grabWindow() grabs pixels off the screen, which is a bit faster and picks up exactly what's on-screen. This function works by calling paintEvent() with painter redirection turned on. If there are overlaying windows, grabWindow() will see them, but not this function.

If there is overlap, it returns a pixmap of the size you want, containing a rendering of widget. If the rectangle you ask for is a superset of widget, the areas outside widget are covered with the widget's background.

See also grabWindow(), QPainter::redirect() and QWidget::paintEvent().

QPixmap QPixmap::grabWindow ( WId window, int x = 0, int y = 0, int w = -1, int h = -1 ) [static]

Grabs the contents of the window window and makes a pixmap out of it. Returns the pixmap.

The arguments (x, y) specify the offset in the window, whereas (w, h) specify the width and height of the area to be copied.

If w is negative, the function copies everything to the right border of the window. If h is negative, the function copies everything to the bottom of the window.

Note that grabWindows() grabs pixels from the screen, not from the window. If there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too.

Note also that the mouse cursor is generally not grabbed.

The reason we use a window identifier and not a QWidget is to enable grabbing of windows that are not part of the application, window system frames, and so on.

Warning: Grabbing an area outside the screen is not safe in general. This depends on the underlying window system.

See also grabWidget().

Example: qmag/qmag.cpp.

int QPixmap::height () const

Returns the height of the pixmap.

See also width(), size() and rect().

Examples: desktop/desktop.cpp, movies/main.cpp, qtimage/qtimage.cpp, scribble/scribble.cpp, scrollview/scrollview.cpp, t10/cannon.cpp and xform/xform.cpp.

const char * QPixmap::imageFormat ( const QString & fileName ) [static]

Returns a string that specifies the image format of the file fileName, or 0 if the file cannot be read or if the format cannot be recognized.

The QImageIO documentation lists the supported image formats.

See also load() and save().

bool QPixmap::isNull () const

Returns TRUE if this is a null pixmap; otherwise returns FALSE.

A null pixmap has zero width, zero height and no contents. You cannot draw in a null pixmap or bitBlt() anything to it.

Resizing an existing pixmap to (0, 0) makes a pixmap into a null pixmap.

See also resize().

Examples: movies/main.cpp, qdir/qdir.cpp, qmag/qmag.cpp and scrollview/scrollview.cpp.

bool QPixmap::isQBitmap () const

Returns TRUE if this is a QBitmap; otherwise returns FALSE.

bool QPixmap::load ( const QString & fileName, const char * format, int conversion_flags )

Loads a pixmap from the file fileName at runtime. Returns TRUE if successful; otherwise returns FALSE.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file's format.

See the convertFromImage() documentation for a description of the conversion_flags argument.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also loadFromData(), save(), imageFormat(), QImage::load() and QImageIO.

Examples: picture/picture.cpp, scrollview/scrollview.cpp and xform/xform.cpp.

bool QPixmap::load ( const QString & fileName, const char * format = 0, ColorMode mode = Auto )

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

Loads a pixmap from the file fileName at runtime.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file's format.

The mode is used to specify the color mode of the pixmap.

See also QPixmap::ColorMode.

bool QPixmap::loadFromData ( const uchar * buf, uint len, const char * format, int conversion_flags )

Loads a pixmap from the binary data in buf (len bytes). Returns TRUE if successful; otherwise returns FALSE.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file's format.

See the convertFromImage() documentation for a description of the conversion_flags argument.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also load(), save(), imageFormat(), QImage::loadFromData() and QImageIO.

bool QPixmap::loadFromData ( const uchar * buf, uint len, const char * format = 0, ColorMode mode = Auto )

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

Loads a pixmap from the binary data in buf (len bytes) using color mode mode. Returns TRUE if successful; otherwise returns FALSE.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file's format.

See also QPixmap::ColorMode.

bool QPixmap::loadFromData ( const QByteArray & buf, const char * format = 0, int conversion_flags = 0 )

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

const QBitmap * QPixmap::mask () const

Returns the mask bitmap, or 0 if no mask has been set.

See also setMask() and QBitmap.

int QPixmap::metric ( int m ) const [virtual protected]

Internal implementation of the virtual QPaintDevice::metric() function.

Use the QPaintDeviceMetrics class instead.

m is the metric to get.

QPixmap & QPixmap::operator= ( const QPixmap & pixmap )

Assigns the pixmap pixmap to this pixmap and returns a reference to this pixmap.

QPixmap & QPixmap::operator= ( const QImage & image )

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

Converts the image image to a pixmap that is assigned to this pixmap. Returns a reference to the pixmap.

See also convertFromImage().

Optimization QPixmap::optimization () const

Returns the optimization setting for this pixmap.

The default optimization setting is QPixmap::NormalOptim. You can change this setting in two ways:

  • Call setDefaultOptimization() to set the default optimization for all new pixmaps.
  • Call setOptimization() to set the optimization for individual pixmaps.

See also setOptimization(), setDefaultOptimization() and defaultOptimization().

QRect QPixmap::rect () const

Returns the enclosing rectangle (0,0,width(),height()) of the pixmap.

See also width(), height() and size().

Example: xform/xform.cpp.

void QPixmap::resize ( int w, int h )

Resizes the pixmap to w width and h height. If either w or h is 0, the pixmap becomes a null pixmap.

If both w and h are greater than 0, a valid pixmap is created. New pixels will be uninitialized (random) if the pixmap is expanded.

Examples: desktop/desktop.cpp and grapher/grapher.cpp.

void QPixmap::resize ( const QSize & size )

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

Resizes the pixmap to size size.

bool QPixmap::save ( const QString & fileName, const char * format, int quality = -1 ) const

Saves the pixmap to the file fileName using the image file format format and a quality factor quality. quality must be in the range [0,100] or -1. Specify 0 to obtain small compressed files, 100 for large uncompressed files, and -1 to use the default settings. Returns TRUE if successful; otherwise returns FALSE.

See also load(), loadFromData(), imageFormat(), QImage::save() and QImageIO.

Example: qmag/qmag.cpp.

bool QPixmap::selfMask () const

Returns TRUE if the pixmap's mask is identical to the pixmap itself; otherwise returns FALSE.

See also mask().

int QPixmap::serialNumber () const

Returns a number that uniquely identifies the contents of this QPixmap object. This means that multiple QPixmap objects can have the same serial number as long as they refer to the same contents.

An example of where this is useful is for caching QPixmaps.

See also QPixmapCache.

void QPixmap::setDefaultOptimization ( Optimization optimization ) [static]

Sets the default pixmap optimization.

All new pixmaps that are created will use this default optimization. You may also set optimization for individual pixmaps using the setOptimization() function.

The initial default optimization setting is QPixmap::Normal.

See also defaultOptimization(), setOptimization() and optimization().

void QPixmap::setMask ( const QBitmap & newmask )

Sets a mask bitmap.

The newmask bitmap defines the clip mask for this pixmap. Every pixel in newmask corresponds to a pixel in this pixmap. Pixel value 1 means opaque and pixel value 0 means transparent. The mask must have the same size as this pixmap.

Warning: Setting the mask on a pixmap will cause any alpha channel data to be cleared. For example:

        QPixmap alpha( "image-with-alpha.png" );
        QPixmap alphacopy = alpha;
        alphacopy.setMask( alphacopy.mask() );
Now, alpha and alphacopy are visually different.

Setting a null mask resets the mask.

See also mask(), createHeuristicMask() and QBitmap.

void QPixmap::setOptimization ( Optimization optimization )

Sets pixmap drawing optimization for this pixmap.

The optimization setting affects pixmap operations, in particular drawing of transparent pixmaps (bitBlt() a pixmap with a mask set) and pixmap transformations (the xForm() function).

Pixmap optimization involves keeping intermediate results in a cache buffer and using the cache to speed up bitBlt() and xForm(). The cost is more memory consumption, up to twice as much as an unoptimized pixmap.

Use the setDefaultOptimization() to change the default optimization for all new pixmaps.

See also optimization(), setDefaultOptimization() and defaultOptimization().

Example: desktop/desktop.cpp.

QSize QPixmap::size () const

Returns the size of the pixmap.

See also width(), height() and rect().

Examples: movies/main.cpp and qtimage/qtimage.cpp.

QWMatrix QPixmap::trueMatrix ( const QWMatrix & matrix, int w, int h ) [static]

Returns the actual matrix used for transforming a pixmap with w width and h height and matrix matrix.

When transforming a pixmap with xForm(), the transformation matrix is internally adjusted to compensate for unwanted translation, i.e. xForm() returns the smallest pixmap containing all transformed points of the original pixmap.

This function returns the modified matrix, which maps points correctly from the original pixmap into the new pixmap.

See also xForm() and QWMatrix.

int QPixmap::width () const

Returns the width of the pixmap.

See also height(), size() and rect().

Examples: desktop/desktop.cpp, movies/main.cpp, qtimage/qtimage.cpp, scribble/scribble.cpp, scrollview/scrollview.cpp and xform/xform.cpp.

QPixmap QPixmap::xForm ( const QWMatrix & matrix ) const

Returns a copy of the pixmap that is transformed using matrix. The original pixmap is not changed.

The transformation matrix is internally adjusted to compensate for unwanted translation, i.e. xForm() returns the smallest image that contains all the transformed points of the original image.

See also trueMatrix(), QWMatrix, QPainter::setWorldMatrix() and QImage::xForm().

Examples: desktop/desktop.cpp, fileiconview/qfileiconview.cpp, movies/main.cpp, qmag/qmag.cpp, qtimage/qtimage.cpp and xform/xform.cpp.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QPixmap & pixmap )

Writes the pixmap pixmap to the stream s as a PNG image.

See also QPixmap::save() and Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QPixmap & pixmap )

Reads a pixmap from the stream s into the pixmap pixmap.

See also QPixmap::load() and Format of the QDataStream operators.

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


qpixmap.h Include File

qpixmap.h

This is the verbatim text of the qpixmap.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpixmap.h   3.0.5   edited Oct 17 2001 $
**
** Definition of QPixmap class
**
** Created : 940501
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPIXMAP_H
#define QPIXMAP_H

#ifndef QT_H
#include "qpaintdevice.h"
#include "qcolor.h" // char*->QColor conversion
#include "qstring.h" // char*->QString conversion
#include "qnamespace.h"
#endif // QT_H

class QGfx;
class QPixmapPrivate;

#if defined(Q_WS_WIN)
// Internal pixmap memory optimization class for Windows 9x
class QMultiCellPixmap;
#endif

class Q_EXPORT QPixmap : public QPaintDevice, public Qt
{
public:
    enum ColorMode { Auto, Color, Mono };
    enum Optimization { DefaultOptim, NoOptim, MemoryOptim=NoOptim,
            NormalOptim, BestOptim };

    QPixmap();
    QPixmap( const QImage& image );
    QPixmap( int w, int h,  int depth = -1, Optimization = DefaultOptim );
    QPixmap( const QSize &, int depth = -1, Optimization = DefaultOptim );
#ifndef QT_NO_IMAGEIO
    QPixmap( const QString& fileName, const char *format=0,
         ColorMode mode=Auto );
    QPixmap( const QString& fileName, const char *format,
         int conversion_flags );
    QPixmap( const char *xpm[] ); // ### in 4.0, 'const char * const xpm[]'?
    QPixmap( const QByteArray &data );
#endif
    QPixmap( const QPixmap & );
   ~QPixmap();

    QPixmap    &operator=( const QPixmap & );
    QPixmap    &operator=( const QImage	 & );

    bool	isNull()	const;

    int		width()		const { return data->w; }
    int		height()	const { return data->h; }
    QSize	size()		const { return QSize(data->w,data->h); }
    QRect	rect()		const { return QRect(0,0,data->w,data->h); }
    int		depth()		const { return data->d; }
    static int	defaultDepth();

    void	fill( const QColor &fillColor = Qt::white );
    void	fill( const QWidget *, int xofs, int yofs );
    void	fill( const QWidget *, const QPoint &ofs );
    void	resize( int width, int height );
    void	resize( const QSize & );

    const QBitmap *mask() const;
    void	setMask( const QBitmap & );
    bool	selfMask() const;
#ifndef QT_NO_IMAGE_HEURISTIC_MASK
    QBitmap	createHeuristicMask( bool clipTight = TRUE ) const;
#endif
    static  QPixmap grabWindow( WId, int x=0, int y=0, int w=-1, int h=-1 );
    static  QPixmap grabWidget( QWidget * widget,
                int x=0, int y=0, int w=-1, int h=-1 );

#ifndef QT_NO_PIXMAP_TRANSFORMATION
    QPixmap	    xForm( const QWMatrix & ) const;
    static QWMatrix trueMatrix( const QWMatrix &, int w, int h );
#endif

    QImage	convertToImage() const;
    bool	convertFromImage( const QImage &, ColorMode mode=Auto );
    bool	convertFromImage( const QImage &, int conversion_flags );
#ifndef QT_NO_IMAGEIO
    static const char* imageFormat( const QString &fileName );
    bool	load( const QString& fileName, const char *format=0,
              ColorMode mode=Auto );
    bool	load( const QString& fileName, const char *format,
              int conversion_flags );
    bool	loadFromData( const uchar *buf, uint len,
                  const char* format=0,
                  ColorMode mode=Auto );
    bool	loadFromData( const uchar *buf, uint len,
                  const char* format,
                  int conversion_flags );
    bool	loadFromData( const QByteArray &data,
                  const char* format=0,
                  int conversion_flags=0 );
    bool	save( const QString& fileName, const char* format, int quality = -1 ) const;
#endif

#if defined(Q_WS_WIN)
    HBITMAP	hbm()		const;
#endif

    int		serialNumber()	const;

    Optimization	optimization() const;
    void		setOptimization( Optimization );
    static Optimization defaultOptimization();
    static void		setDefaultOptimization( Optimization );

    virtual void detach();

    bool	isQBitmap() const;

#if defined(Q_WS_WIN)
    // These functions are internal and used by Windows 9x only
    bool	isMultiCellPixmap() const;
    HDC		multiCellHandle() const;
    HBITMAP	multiCellBitmap() const;
    int		multiCellOffset() const;
    int		allocCell();
    void	freeCell( bool = FALSE );
#endif

#if defined(Q_WS_QWS)
    virtual QGfx * graphicsContext(bool clip_children=TRUE) const;
    virtual unsigned char * scanLine(int) const;
    virtual int bytesPerLine() const;
    QRgb * clut() const;
    int numCols() const;
#elif defined(Q_WS_X11)
    static int x11SetDefaultScreen( int screen );
    void x11SetScreen( int screen );
#endif

#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const QPixmap& ) const { return FALSE; }
#endif

protected:
    QPixmap( int w, int h, const uchar *data, bool isXbitmap );
    int metric( int ) const;

#if defined(Q_WS_WIN)
    struct QMCPI {				// mem optim for win9x
    QMultiCellPixmap *mcp;
    int	offset;
    };
#endif

    struct QPixmapData : public QShared {	// internal pixmap data
    QCOORD	w, h;
    short	d;
    uint	uninit	 : 1;
    uint	bitmap	 : 1;
    uint	selfmask : 1;
#if defined(Q_WS_WIN)
    uint	mcp	 : 1;
#endif
    int	ser_no;
    QBitmap *mask;
#if defined(Q_WS_WIN)
    void   *bits;
    QPixmap *maskpm;
    union {
        HBITMAP hbm;    // if mcp == FALSE
        QMCPI  *mcpi;   // if mcp == TRUE
    } hbm_or_mcpi;
    bool hasRealAlpha;
#elif defined(Q_WS_X11)
    void   *ximage;
    void   *maskgc;
    QPixmap *alphapm;
#elif defined(Q_WS_MAC)
    ColorTable *clut;
#elif defined(Q_WS_QWS)
    int id; // ### should use QPaintDevice::hd, since it is there
    QRgb * clut;
    int numcols;
    int rw;
    int rh;
    bool hasAlpha;
#endif
    Optimization optim;
    } *data;
private:
    QPixmap( int w, int h, int depth, bool, Optimization );
    void	init( int, int, int, bool, Optimization );
    void	deref();
    QPixmap	copy( bool ignoreMask = FALSE ) const;
    static Optimization defOptim;
    friend Q_EXPORT void bitBlt( QPaintDevice *, int, int,
                 const QPaintDevice *,
                 int, int, int, int, RasterOp, bool );
    friend Q_EXPORT void bitBlt( QPaintDevice *, int, int,
                 const QImage* src,
                 int, int, int, int, int conversion_flags );

#if defined(Q_WS_X11) && !defined(QT_NO_XRENDER)
    friend void qt_x11_copy_alpha_pixmap(QPixmap *dst, const QPixmap *src);
    friend void qt_x11_blit_alpha_pixmap(QPixmap *dst, int dx, int dy,
                     const QPixmap *src, int sx = 0, int sy = 0,
                     int sw = -1, int sh = -1);
#endif

    friend class QBitmap;
    friend class QPaintDevice;
    friend class QPainter;
};

inline bool QPixmap::isNull() const
{
    return data->w == 0;
}

inline void QPixmap::fill( const QWidget *w, const QPoint &ofs )
{
    fill( w, ofs.x(), ofs.y() );
}

inline void QPixmap::resize( const QSize &s )
{
    resize( s.width(), s.height() );
}

inline const QBitmap *QPixmap::mask() const
{
    return data->mask;
}

inline bool QPixmap::selfMask() const
{
    return data->selfmask;
}

#if defined(Q_WS_WIN)
inline HBITMAP QPixmap::hbm() const
{
    return data->mcp ? 0 : data->hbm_or_mcpi.hbm;
}
#endif

inline int QPixmap::serialNumber() const
{
    return data->ser_no;
}

inline QPixmap::Optimization QPixmap::optimization() const
{
    return data->optim;
}

inline bool QPixmap::isQBitmap() const
{
    return data->bitmap;
}

#if defined(Q_WS_WIN)
inline bool QPixmap::isMultiCellPixmap() const
{
    return data->mcp;
}
#endif

/*****************************************************************************
  QPixmap stream functions
 *****************************************************************************/

#if !defined(QT_NO_DATASTREAM) && !defined(QT_NO_IMAGEIO)
Q_EXPORT QDataStream &operator<<( QDataStream &, const QPixmap & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPixmap & );
#endif

/*****************************************************************************
  QPixmap (and QImage) helper functions
 *****************************************************************************/

#ifndef QT_NO_PIXMAP_TRANSFORMATION
#  define QT_XFORM_TYPE_MSBFIRST 0
#  define QT_XFORM_TYPE_LSBFIRST 1
#  if defined(Q_WS_WIN)
#    define QT_XFORM_TYPE_WINDOWSPIXMAP 2
#  endif
bool qt_xForm_helper( const QWMatrix&, int, int, int, uchar*, int, int, int, uchar*, int, int, int );
#endif

#endif // QPIXMAP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPixmap Member List

Complete Member List for QPixmap

This is the complete list of member functions for QPixmap, including inherited members.

  • QPixmap()
  • ~QPixmap()
  • cmd()
  • convertFromImage()
  • convertToImage()
  • createHeuristicMask()
  • defaultDepth()
  • defaultOptimization()
  • depth()
  • detach()
  • fill()
  • grabWidget()
  • grabWindow()
  • handle()
  • height()
  • imageFormat()
  • isExtDev()
  • isNull()
  • isQBitmap()
  • load()
  • loadFromData()
  • mask()
  • metric()
  • operator=()
  • optimization()
  • paintingActive()
  • rect()
  • resize()
  • save()
  • selfMask()
  • serialNumber()
  • setDefaultOptimization()
  • setMask()
  • setOptimization()
  • size()
  • trueMatrix()
  • width()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xForm()


QPixmapCache Class

QPixmapCache Class Reference

The QPixmapCache class provides an application-global cache for pixmaps. More...

#include <qpixmapcache.h>

List of all member functions.

Static Public Members

  • int cacheLimit ()
  • void setCacheLimit ( int n )
  • QPixmap * find ( const QString & key )
  • bool find ( const QString & key, QPixmap & pm )
  • bool insert ( const QString & key, QPixmap * pm ) (obsolete)
  • bool insert ( const QString & key, const QPixmap & pm )
  • void clear ()

Detailed Description

The QPixmapCache class provides an application-global cache for pixmaps.

This class is a tool for optimized drawing with QPixmap. You can use it to store temporary pixmaps that are expensive to generate without using more storage space than cacheLimit(). Use insert() to insert pixmaps, find() to find them and clear() to empty the cache.

For example, QRadioButton has a non-trivial visual representation so we don't want to regenerate a pixmap whenever a radio button is displayed or changes state. In the function QRadioButton::drawButton(), we do not draw the radio button directly. Instead, we first check the global pixmap cache for a pixmap with the key "$qt_radio_nnn_", where nnn is a numerical value that specifies the the radio button state. If a pixmap is found, we bitBlt() it onto the widget and return. Otherwise, we create a new pixmap, draw the radio button in the pixmap, and finally insert the pixmap in the global pixmap cache, using the key above. The bitBlt() is ten times faster than drawing the radio button. All radio buttons in the program share the cached pixmap since QPixmapCache is application-global.

QPixmapCache contains no member data, only static functions to access the global pixmap cache. It creates an internal QCache for caching the pixmaps.

The cache associates a pixmap with a string (key). If two pixmaps are inserted into the cache using equal keys, then the last pixmap will hide the first pixmap. The QDict and QCache classes do exactly the same.

The cache becomes full when the total size of all pixmaps in the cache exceeds cacheLimit(). The initial cache limit is 1024 KByte (1 MByte); it is changed with setCacheLimit(). A pixmap takes roughly width*height*depth/8 bytes of memory.

See the QCache documentation for more details about the cache mechanism.

See also Environment Classes, Graphics Classes and Image Processing Classes.

Member Function Documentation

int QPixmapCache::cacheLimit () [static]

Returns the cache limit (in kilobytes).

The default setting is 1024 kilobytes.

See also setCacheLimit().

void QPixmapCache::clear () [static]

Removes all pixmaps from the cache.

QPixmap * QPixmapCache::find ( const QString & key ) [static]

Returns the pixmap associated with the key in the cache, or null if there is no such pixmap.

Warning: If valid, you should copy the pixmap immediately (this is fast). Subsequent insertions into the cache could cause the pointer to become invalid. For this reason, we recommend you use find(const QString&, QPixmap&) instead.

Example:

        QPixmap* pp;
        QPixmap p;
        if ( (pp=QPixmapCache::find("my_big_image", pm)) ) {
            p = *pp;
        } else {
            p.load("bigimage.png");
            QPixmapCache::insert("my_big_image", new QPixmap(p));
        }
        painter->drawPixmap(0, 0, p);

bool QPixmapCache::find ( const QString & key, QPixmap & pm ) [static]

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

Looks for a cached pixmap associated with the key in the cache. If a pixmap is found, the function sets pm to that pixmap and returns TRUE; otherwise leaves pm alone and returns FALSE.

Example:

        QPixmap p;
        if ( !QPixmapCache::find("my_big_image", pm) ) {
            pm.load("bigimage.png");
            QPixmapCache::insert("my_big_image", pm);
        }
        painter->drawPixmap(0, 0, p);

bool QPixmapCache::insert ( const QString & key, const QPixmap & pm ) [static]

Inserts a copy of the pixmap pm associated with the key into the cache.

All pixmaps inserted by the Qt library have a key starting with "$qt", so your own pixmap keys should never begin "$qt".

When a pixmap is inserted and the cache is about to exceed its limit, it removes pixmaps until there is enough room for the pixmap to be inserted.

The oldest pixmaps (least recently accessed in the cache) are deleted when more space is needed.

See also setCacheLimit().

bool QPixmapCache::insert ( const QString & key, QPixmap * pm ) [static]

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

Inserts the pixmap pm associated with key into the cache. Returns TRUE if successful, or FALSE if the pixmap is too big for the cache.

Note: pm must be allocated on the heap (using new).

If this function returns FALSE, you must delete pm yourself.

If this function returns TRUE, do not use pm afterwards or keep references to it because any other insertions into the cache, whether from anywhere in the application or within Qt itself, could cause the pixmap to be discarded from the cache and the pointer to become invalid.

Due to these dangers, we strongly recommend that you use insert(const QString&, const QPixmap&) instead.

void QPixmapCache::setCacheLimit ( int n ) [static]

Sets the cache limit to n kilobytes.

The default setting is 1024 kilobytes.

See also cacheLimit().

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


qpixmapcache.h Include File

qpixmapcache.h

This is the verbatim text of the qpixmapcache.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpixmapcache.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPixmapCache class
**
** Created : 950501
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPIXMAPCACHE_H
#define QPIXMAPCACHE_H

#ifndef QT_H
#include "qpixmap.h"
#endif // QT_H

class Q_EXPORT QPixmapCache				// global pixmap cache
{
public:
    static  int		cacheLimit();
    static  void	setCacheLimit( int );
    static  QPixmap    *find( const QString &key );
    static  bool	find( const QString &key, QPixmap& );
    static  bool	insert( const QString &key, QPixmap * );
    static  bool	insert( const QString &key, const QPixmap& );
    static  void	clear();
};

#endif // QPIXMAPCACHE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPixmapCache Member List

Complete Member List for QPixmapCache

This is the complete list of member functions for QPixmapCache, including inherited members.

  • cacheLimit()
  • clear()
  • find()
  • insert()
  • setCacheLimit()


QPlatinumStyle Class

QPlatinumStyle Class Reference

The QPlatinumStyle class provides Mac/Platinum look and feel. More...

#include <qplatinumstyle.h>

Inherits QWindowsStyle.

List of all member functions.

Public Members

  • QPlatinumStyle ()

Protected Members

  • QColor mixedColor ( const QColor & c1, const QColor & c2 ) const
  • void drawRiffles ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool horizontal ) const

Detailed Description

The QPlatinumStyle class provides Mac/Platinum look and feel.

This class implements the Platinum look and feel. It's an experimental class that tries to resemble a Macinosh-like GUI style with the QStyle system. The emulation is, however, far from being perfect yet.

See also Widget Appearance and Style.

Member Function Documentation

QPlatinumStyle::QPlatinumStyle ()

Constructs a QPlatinumStyle

void QPlatinumStyle::drawRiffles ( QPainter * p, int x, int y, int w, int h, const QColorGroup & g, bool horizontal ) const [protected]

Draws the nifty Macintosh decoration used on sliders using painter p and colorgroup g. x, y, w, h and horizontal specify the geometry and orientation of the riffles.

QColor QPlatinumStyle::mixedColor ( const QColor & c1, const QColor & c2 ) const [protected]

Mixes two colors c1 and c2 to a new color.

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


qplatinumstyle.h Include File

qplatinumstyle.h

This is the verbatim text of the qplatinumstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qplatinumstyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Platinum-like style class
**
** Created : 981231
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPLATINUMSTYLE_H
#define QPLATINUMSTYLE_H

#ifndef QT_H
#include "qwindowsstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE_PLATINUM

class QPalette;

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_PLATINUM
#else
#define Q_EXPORT_STYLE_PLATINUM Q_EXPORT
#endif

class Q_EXPORT_STYLE_PLATINUM QPlatinumStyle : public QWindowsStyle
{
    Q_OBJECT
public:
    QPlatinumStyle();
    virtual ~QPlatinumStyle();

    // new Style Stuff
    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl control,
                 QPainter *p,
                 const QWidget *widget,
                 const QRect &r,
                 const QColorGroup &cg,
                 SFlags how = Style_Default,
                 SCFlags sub = SC_All,
                 SCFlags subActive = SC_None,
                 const QStyleOption& = QStyleOption::Default ) const;

    QRect querySubControlMetrics( ComplexControl control,
                  const QWidget *widget,
                  SubControl sc,
                  const QStyleOption& = QStyleOption::Default ) const;

    int pixelMetric( PixelMetric metric, const QWidget *widget = 0 ) const;

    QRect subRect( SubRect r, const QWidget *widget ) const;

protected:
     QColor mixedColor(const QColor &, const QColor &) const;
    void drawRiffles( QPainter* p,  int x, int y, int w, int h,
              const QColorGroup &g, bool horizontal ) const;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPlatinumStyle( const QPlatinumStyle & );
    QPlatinumStyle& operator=( const QPlatinumStyle & );
#endif
};

#endif // QT_NO_STYLE_PLATINUM

#endif // QPLATINUMSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPlatinumStyle Member List

Complete Member List for QPlatinumStyle

This is the complete list of member functions for QPlatinumStyle, including inherited members.

  • QPlatinumStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • drawRiffles()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • mixedColor()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • visualRect()


QPNGImagePacker Class

QPNGImagePacker Class Reference

The QPNGImagePacker class creates well-compressed PNG animations. More...

#include <qpngio.h>

List of all member functions.

Public Members

  • QPNGImagePacker ( QIODevice * iod, int storage_depth, int conversionflags )
  • void setPixelAlignment ( int x )
  • bool packImage ( const QImage & img )

Detailed Description

The QPNGImagePacker class creates well-compressed PNG animations.

By using transparency, QPNGImagePacker allows you to build a PNG image from a sequence of QImages.

Images are added using packImage().

See also Graphics Classes and Image Processing Classes.

Member Function Documentation

QPNGImagePacker::QPNGImagePacker ( QIODevice * iod, int storage_depth, int conversionflags )

Creates an image packer that writes PNG data to IO device iod using a storage_depth bit encoding (use 8 or 32, depending on the desired quality and compression requirements).

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the conversionflags to specify how you'd prefer this to happen.

See also Qt::ImageConversionFlags.

bool QPNGImagePacker::packImage ( const QImage & img )

Adds the image img to the PNG animation, analyzing the differences between this and the previous image to improve compression.

void QPNGImagePacker::setPixelAlignment ( int x )

Aligns pixel differences to x pixels. For example, using 8 can improve playback on certain hardware. Normally the default of 1-pixel alignment (i.e. no alignment) gives better compression and performance.

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


QPNGImagePacker Member List

Complete Member List for QPNGImagePacker

This is the complete list of member functions for QPNGImagePacker, including inherited members.

  • QPNGImagePacker()
  • packImage()
  • setPixelAlignment()


qpngio.h Include File

qpngio.h

This is the verbatim text of the qpngio.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpngio.h   3.0.5   edited Oct 12 2001 $
**
** Definition of PNG QImage IOHandler
**
** Created : 970521
**
** Copyright (C) 1992-1998 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPNGIO_H
#define QPNGIO_H

#ifndef QT_H
#include "qimage.h"
#endif // QT_H

#ifndef QT_NO_IMAGEIO_PNG

void qInitPngIO();

class QIODevice;

#ifndef Q_PNGEXPORT
#if !defined(QT_PLUGIN)
#define Q_PNGEXPORT Q_EXPORT
#else
#define Q_PNGEXPORT
#endif
#endif

class Q_PNGEXPORT QPNGImageWriter {
public:
    QPNGImageWriter(QIODevice*);
    ~QPNGImageWriter();

    enum DisposalMethod { Unspecified, NoDisposal, RestoreBackground, RestoreImage };
    void setDisposalMethod(DisposalMethod);
    void setLooping(int loops=0); // 0 == infinity
    void setFrameDelay(int msecs);
    void setGamma(float);

    bool writeImage(const QImage& img, int x, int y);
    bool writeImage(const QImage& img, int quality, int x, int y);
    bool writeImage(const QImage& img)
    { return writeImage(img, 0, 0); }
    bool writeImage(const QImage& img, int quality)
    { return writeImage(img, quality, 0, 0); }

    QIODevice* device() { return dev; }

private:
    QIODevice* dev;
    int frames_written;
    DisposalMethod disposal;
    int looping;
    int ms_delay;
    float gamma;
};

class Q_PNGEXPORT QPNGImagePacker : public QPNGImageWriter {
public:
    QPNGImagePacker(QIODevice*, int depth, int convflags);

    void setPixelAlignment(int x);
    bool packImage(const QImage& img);

private:
    QImage previous;
    int depth;
    int convflags;
    int alignx;
};

#endif // QT_NO_IMAGEIO_PNG

#endif // QPNGIO_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPoint类

QPoint类参考

QPoint类定义了平面上的一个点。 详情请见……

#include <qpoint.h>

所有成员函数的列表。

公有成员

  • QPoint ()
  • QPoint ( int xpos, int ypos )
  • bool isNull () const
  • int x () const
  • int y () const
  • void setX ( int x )
  • void setY ( int y )
  • int manhattanLength () const
  • QCOORD & rx ()
  • QCOORD & ry ()
  • QPoint & operator+= ( const QPoint & p )
  • QPoint & operator-= ( const QPoint & p )
  • QPoint & operator*= ( int c )
  • QPoint & operator*= ( double c )
  • QPoint & operator/= ( int c )
  • QPoint & operator/= ( double c )

相关函数

  • bool operator== ( const QPoint & p1, const QPoint & p2 )
  • bool operator!= ( const QPoint & p1, const QPoint & p2 )
  • const QPoint operator+ ( const QPoint & p1, const QPoint & p2 )
  • const QPoint operator- ( const QPoint & p1, const QPoint & p2 )
  • const QPoint operator* ( const QPoint & p, int c )
  • const QPoint operator* ( int c, const QPoint & p )
  • const QPoint operator* ( const QPoint & p, double c )
  • const QPoint operator* ( double c, const QPoint & p )
  • const QPoint operator- ( const QPoint & p )
  • const QPoint operator/ ( const QPoint & p, int c )
  • const QPoint operator/ ( const QPoint & p, double c )
  • QDataStream & operator<< ( QDataStream & s, const QPoint & p )
  • QDataStream & operator>> ( QDataStream & s, QPoint & p )

详细描述

QPoint类定义了平面上的一个点。

一个点由一个x坐标和一个y坐标确定。

坐标类型是QCOORD（一个32位整数）。QCOORD的最小值是QCOORD_MIN（-2147483648），最大值是QCOORD_MAX（2147483647）。

坐标可以通过函数x()和y()来访问，它们可以由setX()和setY()来设置并且由rx()由ry()来参考。

假设一个点p，下面的语句都是等价的：

        p.setX( p.x() + 1 );
        p += QPoint( 1, 0 );
        p.rx()++;

一个QPoint也可以用作是一个矢量。QPoint的加法和减法也像矢量一样定义了（每个分量分别的被相加或者相减）。你可以把一个QPoint与一个int或者一个double做乘法或者除法。函数manhattanLength()像对矢量那样给出了QPoint一个比较廉价的长度接近值的说明。

Example:

        //QPoint oldPos在其它什么地方定义过了
        MyWidget::mouseMoveEvent( QMouseEvent *e )
        {
            QPoint vector = e->pos() - oldPos;
            if ( vector.manhattanLength() > 3 )
            ... //鼠标从oldPos移动超过3个象素
        }

QPoint可以进行比较得出相等或者不等，并且它们可以写到QStream或者从QStream中读出。

也可以参考QPointArray、QSize、QRect、图形类和图像处理类。

成员函数文档

QPoint::QPoint ()

构造一个坐标为(0,0)的点（isNull()返回真）。

QPoint::QPoint ( int xpos, int ypos )

构造一个x值为xpos，y值为ypos的点。

bool QPoint::isNull () const

如果x值和y值都是0的话，返回真，否则返回假。

int QPoint::manhattanLength () const

返回x()和y()的绝对值得和，就是传统上的从原点开始的矢量的“曼哈顿长度”。这个传统的出现是因为这样的距离适用于在矩形方格上旅行的履行者们，就像曼哈顿的街道一样。

这个很有用的，并且运算很快，和真实长度sqrt(pow(x(),2)+pow(y(),2))很接近。

QPoint & QPoint::operator*= ( int c )

用c与这个点的x和y做乘法，并且返回这个点的引用。

实例：

        QPoint p( -1, 4 );
        p *= 2;            // p变成了(-2,8)

QPoint & QPoint::operator*= ( double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

用c与这个点的x和y做乘法，并且返回这个点的引用。

实例：

        QPoint p( -1, 4 );
        p *= 2.5;          // p变成了(-3,10)

注意这个结果被取整了，因为点是用整数保存的。

QPoint & QPoint::operator+= ( const QPoint & p )

把点p加到这个点上，并且返回这个点的引用。

实例：

        QPoint p(  3, 7 );
        QPoint q( -1, 4 );
        p += q;            // p变成了(2,11)

QPoint & QPoint::operator-= ( const QPoint & p )

从这个点上减去点p，并且返回这个点的引用。

实例：

        QPoint p(  3, 7 );
        QPoint q( -1, 4 );
        p -= q;            // p变成了(4,3)

QPoint & QPoint::operator/= ( int c )

x和y都除以c，并且返回这个点的引用。

实例：

        QPoint p( -2, 8 );
        p /= 2;            // p变成了(-1,4)

QPoint & QPoint::operator/= ( double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

x和y都除以c，并且返回这个点的引用。

实例：

        QPoint p( -3, 10 );
        p /= 2.5;           // p变成了(-1,4)

注意这个结果被取整了，因为点是用整数保存的。

QCOORD & QPoint::rx ()

返回这个点的x坐标的引用。

使用这个引用可以直接操作x。

实例：

        QPoint p( 1, 2 );
        p.rx()--;         // p变成了(0, 2)

也可以参考ry()。

QCOORD & QPoint::ry ()

返回这个点的y坐标的引用。

使用这个引用可以直接操作y。

实例：

        QPoint p( 1, 2 );
        p.ry()++;         // p变成了(1, 3)

也可以参考rx()。

void QPoint::setX ( int x )

设置这个点的x坐标为x。

也可以参考x()和setY()。

实例：t14/cannon.cpp。

void QPoint::setY ( int y )

设置这个点的y坐标为y。

也可以参考y()和setX()。

实例：t14/cannon.cpp。

int QPoint::x () const

返回这个点的x坐标。

也可以参考setX()和y()。

实例：canvas/canvas.cpp、chart/canvasview.cpp、dirview/dirview.cpp、fileiconview/qfileiconview.cpp、life/life.cpp、t14/cannon.cpp和themes/wood.cpp。

int QPoint::y () const

返回这个点的y坐标。

也可以参考setY()和x()。

实例：canvas/canvas.cpp、chart/canvasview.cpp、fileiconview/qfileiconview.cpp、life/life.cpp、t14/cannon.cpp和themes/wood.cpp。

相关函数

bool operator!= ( const QPoint & p1, const QPoint & p2 )

如果p1和p2相等，返回真，否则返回假。

const QPoint operator* ( const QPoint & p, int c )

返回由p的分量和c相乘构成的QPoint。

const QPoint operator* ( int c, const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

返回由p的分量和c相乘构成的QPoint。

const QPoint operator* ( const QPoint & p, double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

返回由p的分量和c相乘构成的QPoint。

注意这个结果被取整了，因为点是用整数保存的。

const QPoint operator* ( double c, const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

返回由p的分量和c相乘构成的QPoint。

注意这个结果被取整了，因为点是用整数保存的。

const QPoint operator+ ( const QPoint & p1, const QPoint & p2 )

返回p1和p2的和，每个分量都分别相加。

const QPoint operator- ( const QPoint & p1, const QPoint & p2 )

返回p1减去p2得到的结果，每个分量都分别相减。

const QPoint operator- ( const QPoint & p )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

返回p每个分量都变号后构成的QPoint，和QPoint(0,0) - p是一样的。

const QPoint operator/ ( const QPoint & p, int c )

返回p每个分量除以c后构成的QPoint。

const QPoint operator/ ( const QPoint & p, double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

返回p每个分量除以c后构成的QPoint。

注意这个结果被取整了，因为点是用整数保存的。

QDataStream & operator<< ( QDataStream & s, const QPoint & p )

把点p写到流s中并且返回流的引用。

也可以参考QDataStream操作符的格式。

bool operator== ( const QPoint & p1, const QPoint & p2 )

如果p1和p2相等，返回真，否则返回假。

QDataStream & operator>> ( QDataStream & s, QPoint & p )

从流s中读取一个QPoint到点p并且返回这个流的引用。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qpoint.h包含文件

qpoint.h

这里是qpoint.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qpoint.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPoint class
**
** Created : 931028
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPOINT_H
#define QPOINT_H

#ifndef QT_H
#include "qwindowdefs.h"
#endif // QT_H

class Q_EXPORT QPoint
{
public:
    QPoint();
    QPoint( int xpos, int ypos );

    bool   isNull()	const;

    int	   x()		const;
    int	   y()		const;
    void   setX( int x );
    void   setY( int y );

    int manhattanLength() const;

    QCOORD &rx();
    QCOORD &ry();

    QPoint &operator+=( const QPoint &p );
    QPoint &operator-=( const QPoint &p );
    QPoint &operator*=( int c );
    QPoint &operator*=( double c );
    QPoint &operator/=( int c );
    QPoint &operator/=( double c );

    friend inline bool	 operator==( const QPoint &, const QPoint & );
    friend inline bool	 operator!=( const QPoint &, const QPoint & );
    friend inline const QPoint operator+( const QPoint &, const QPoint & );
    friend inline const QPoint operator-( const QPoint &, const QPoint & );
    friend inline const QPoint operator*( const QPoint &, int );
    friend inline const QPoint operator*( int, const QPoint & );
    friend inline const QPoint operator*( const QPoint &, double );
    friend inline const QPoint operator*( double, const QPoint & );
    friend inline const QPoint operator-( const QPoint & );
    friend inline const QPoint operator/( const QPoint &, int );
    friend inline const QPoint operator/( const QPoint &, double );

private:
    static void warningDivByZero();

#if defined(Q_OS_MAC)
    QCOORD yp;
    QCOORD xp;
#else
    QCOORD xp;
    QCOORD yp;
#endif
};

/*****************************************************************************
  QPoint stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QPoint & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPoint & );
#endif

/*****************************************************************************
  QPoint inline functions
 *****************************************************************************/

inline QPoint::QPoint()
{ xp=0; yp=0; }

inline QPoint::QPoint( int xpos, int ypos )
{ xp=(QCOORD)xpos; yp=(QCOORD)ypos; }

inline bool QPoint::isNull() const
{ return xp == 0 && yp == 0; }

inline int QPoint::x() const
{ return xp; }

inline int QPoint::y() const
{ return yp; }

inline void QPoint::setX( int x )
{ xp = (QCOORD)x; }

inline void QPoint::setY( int y )
{ yp = (QCOORD)y; }

inline QCOORD &QPoint::rx()
{ return xp; }

inline QCOORD &QPoint::ry()
{ return yp; }

inline QPoint &QPoint::operator+=( const QPoint &p )
{ xp+=p.xp; yp+=p.yp; return *this; }

inline QPoint &QPoint::operator-=( const QPoint &p )
{ xp-=p.xp; yp-=p.yp; return *this; }

inline QPoint &QPoint::operator*=( int c )
{ xp*=(QCOORD)c; yp*=(QCOORD)c; return *this; }

inline QPoint &QPoint::operator*=( double c )
{ xp=(QCOORD)(xp*c); yp=(QCOORD)(yp*c); return *this; }

inline bool operator==( const QPoint &p1, const QPoint &p2 )
{ return p1.xp == p2.xp && p1.yp == p2.yp; }

inline bool operator!=( const QPoint &p1, const QPoint &p2 )
{ return p1.xp != p2.xp || p1.yp != p2.yp; }

inline const QPoint operator+( const QPoint &p1, const QPoint &p2 )
{ return QPoint(p1.xp+p2.xp, p1.yp+p2.yp); }

inline const QPoint operator-( const QPoint &p1, const QPoint &p2 )
{ return QPoint(p1.xp-p2.xp, p1.yp-p2.yp); }

inline const QPoint operator*( const QPoint &p, int c )
{ return QPoint(p.xp*c, p.yp*c); }

inline const QPoint operator*( int c, const QPoint &p )
{ return QPoint(p.xp*c, p.yp*c); }

inline const QPoint operator*( const QPoint &p, double c )
{ return QPoint((QCOORD)(p.xp*c), (QCOORD)(p.yp*c)); }

inline const QPoint operator*( double c, const QPoint &p )
{ return QPoint((QCOORD)(p.xp*c), (QCOORD)(p.yp*c)); }

inline const QPoint operator-( const QPoint &p )
{ return QPoint(-p.xp, -p.yp); }

inline QPoint &QPoint::operator/=( int c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0 )
    warningDivByZero();
#endif
    xp/=(QCOORD)c;
    yp/=(QCOORD)c;
    return *this;
}

inline QPoint &QPoint::operator/=( double c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0.0 )
    warningDivByZero();
#endif
    xp=(QCOORD)(xp/c);
    yp=(QCOORD)(yp/c);
    return *this;
}

inline const QPoint operator/( const QPoint &p, int c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0 )
    QPoint::warningDivByZero();
#endif
    return QPoint(p.xp/c, p.yp/c);
}

inline const QPoint operator/( const QPoint &p, double c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0.0 )
    QPoint::warningDivByZero();
#endif
    return QPoint((QCOORD)(p.xp/c), (QCOORD)(p.yp/c));
}

#endif // QPOINT_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPoint成员列表

完整的QPoint成员列表

这里是QPoint成员函数的完整列表，包括继承的成员。

  • QPoint()
  • isNull()
  • manhattanLength()
  • operator*=()
  • operator+=()
  • operator-=()
  • operator/=()
  • rx()
  • ry()
  • setX()
  • setY()
  • x()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPointArray Class

QPointArray Class Reference

The QPointArray class provides an array of points. More...

#include <qpointarray.h>

Inherits QMemArray<QPoint>.

List of all member functions.

Public Members

  • QPointArray ()
  • ~QPointArray ()
  • QPointArray ( int size )
  • QPointArray ( const QPointArray & a )
  • QPointArray ( const QRect & r, bool closed = FALSE )
  • QPointArray & operator= ( const QPointArray & a )
  • QPointArray copy () const
  • void translate ( int dx, int dy )
  • QRect boundingRect () const
  • void point ( uint index, int * x, int * y ) const
  • QPoint point ( uint index ) const
  • void setPoint ( uint index, int x, int y )
  • void setPoint ( uint i, const QPoint & p )
  • bool putPoints ( int index, int nPoints, int firstx, int firsty, ... )
  • bool putPoints ( int index, int nPoints, const QPointArray & from, int fromIndex = 0 )
  • void makeArc ( int x, int y, int w, int h, int a1, int a2 )
  • void makeEllipse ( int x, int y, int w, int h )
  • void makeArc ( int x, int y, int w, int h, int a1, int a2, const QWMatrix & xf )
  • QPointArray cubicBezier () const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QPointArray & a )
  • QDataStream & operator>> ( QDataStream & s, QPointArray & a )

Detailed Description

The QPointArray class provides an array of points.

A QPointArray is an array of QPoint objects. In addition to the functions provided by QMemArray, QPointArray provides some point-specific functions.

For convenient reading and writing of the point data use setPoints(), putPoints(), point(), and setPoint().

For geometry operations: boundingRect() and translate(). There is also a QWMatrix::map() function for more general transformation of QPointArrays. You can also create arcs and ellipses with makeArc() and makeEllipse().

Among others, QPointArray is used by QPainter::drawLineSegments(), QPainter::drawPolyline(), QPainter::drawPolygon() and QPainter::drawCubicBezier().

Note that because this class is a QMemArray, copying an array and modifying the copy modifies the original as well, i.e. a shallow copy. If you need a deep copy use copy() or detach(), for example:

        void drawGiraffe( const QPointArray & r, QPainter * p )
        {
            QPointArray tmp = r;
            tmp.detach();
            // some code that modifies tmp
            p->drawPoints( tmp );
        }

If you forget the tmp.detach(), the const array will be modified.

See also QPainter, QWMatrix, QMemArray, Graphics Classes, Image Processing Classes and Implicitly and Explicitly Shared Classes.

Member Function Documentation

QPointArray::QPointArray ()

Constructs a null point array.

See also isNull().

QPointArray::QPointArray ( int size )

Constructs a point array with room for size points. Makes a null array if size == 0.

See also resize() and isNull().

QPointArray::QPointArray ( const QPointArray & a )

Constructs a shallow copy of the point array a.

See also copy().

QPointArray::QPointArray ( const QRect & r, bool closed = FALSE )

Constructs a point array from the rectangle r.

If closed is FALSE, then the point array just contains the following four points in the listed order: r.topLeft(), r.topRight(), r.bottomRight() and r.bottomLeft().

If closed is TRUE, then a fifth point is set to r.topLeft().

QPointArray::~QPointArray ()

Destroys the point array.

QRect QPointArray::boundingRect () const

Returns the bounding rectangle of the points in the array, or QRect(0,0,0,0) if the array is empty.

QPointArray QPointArray::copy () const

Creates a deep copy of the array.

QPointArray QPointArray::cubicBezier () const

Returns the Bezier points for the four control points in this array.

void QPointArray::makeArc ( int x, int y, int w, int h, int a1, int a2 )

Sets the points of the array to those describing an arc of an ellipse with size, width w by height h, and position (x, y), starting from angle a1 and spanning by angle a2. The resulting array has sufficient resolution for pixel accuracy (see the overloaded function which takes an additional QWMatrix parameter).

Angles are specified in 16ths of a degree, i.e. a full circle equals 5760 (16*360). Positive values mean counter-clockwise, whereas negative values mean the clockwise direction. Zero degrees is at the 3 o'clock position.

See the angle diagram.

void QPointArray::makeArc ( int x, int y, int w, int h, int a1, int a2, const QWMatrix & xf )

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

Sets the points of the array to those describing an arc of an ellipse with width w and height h and position (x, y), starting from angle a1, and spanning angle by a2, and transformed by the matrix xf. The resulting array has sufficient resolution for pixel accuracy.

Angles are specified in 16ths of a degree, i.e. a full circle equals 5760 (16*360). Positive values mean counter-clockwise, whereas negative values mean the clockwise direction. Zero degrees is at the 3 o'clock position.

See the angle diagram.

void QPointArray::makeEllipse ( int x, int y, int w, int h )

Sets the points of the array to those describing an ellipse with size, width w by height h, and position (x, y).

The returned array has sufficient resolution for use as pixels.

QPointArray & QPointArray::operator= ( const QPointArray & a )

Assigns a shallow copy of a to this point array and returns a reference to this point array.

Equivalent to assign(a).

See also copy().

void QPointArray::point ( uint index, int * x, int * y ) const

Reads the coordinates of the point at position index within the array and writes them into *x and *y.

QPoint QPointArray::point ( uint index ) const

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

Returns the point at position index within the array.

bool QPointArray::putPoints ( int index, int nPoints, int firstx, int firsty, ... )

Copies nPoints points from the variable argument list into this point array from position index, and resizes the point array if index+nPoints exceeds the size of the array.

Returns TRUE if successful, or FALSE if the array could not be resized (typically due to lack of memory).

The example code creates an array with three points (4,5), (6,7) and (8,9), by expanding the array from 1 to 3 points:

        QPointArray a( 1 );
        a[0] = QPoint( 4, 5 );
        a.putPoints( 1, 2, 6,7, 8,9 ); // index == 1, points == 2

This has the same result, but here putPoints overwrites rather than extends:

        QPointArray a( 3 );
        a.putPoints( 0, 3, 4,5, 0,0, 8,9 );
        a.putPoints( 1, 1, 6,7 );

The points are given as a sequence of integers, starting with firstx then firsty, and so on.

See also resize().

bool QPointArray::putPoints ( int index, int nPoints, const QPointArray & from, int fromIndex = 0 )

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

This version of the function copies nPoints from from into this array, starting at index in this array and fromIndex in from. fromIndex is 0 by default.

        QPointArray a;
        a.putPoints( 0, 3, 1,2, 0,0, 5,6 );
        // a is now the three-point array ( 1,2, 0,0, 5,6 );
        QPointArray b;
        b.putPoints( 0, 3, 4,4, 5,5, 6,6 );
        // b is now ( 4,4, 5,5, 6,6 );
        a.putPoints( 2, 3, b );
        // a is now ( 1,2, 0,0, 4,4, 5,5, 6,6 );

void QPointArray::setPoint ( uint index, int x, int y )

Sets the point at position index in the array to (x, y).

Example: themes/wood.cpp.

void QPointArray::setPoint ( uint i, const QPoint & p )

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

Sets the point at array index i to p.

void QPointArray::translate ( int dx, int dy )

Translates all points in the array by (dx, dy).

Related Functions

QDataStream & operator<< ( QDataStream & s, const QPointArray & a )

Writes the point array, a to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QPointArray & a )

Reads a point array, a from the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

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


qpointarray.h Include File

qpointarray.h

This is the verbatim text of the qpointarray.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpointarray.h   3.0.5   edited Jun 5 21:12 $
**
** Definition of QPointArray class
**
** Created : 940213
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPOINTARRAY_H
#define QPOINTARRAY_H

#ifndef QT_H
#include "qmemarray.h"
#include "qpoint.h"
#endif // QT_H

#if defined(Q_TEMPLATEDLL)
Q_TEMPLATE_EXTERN template class Q_EXPORT QMemArray<QPoint>;
#endif

class Q_EXPORT QPointArray : public QMemArray<QPoint>
{
public:
    QPointArray() {}
    ~QPointArray() {}
    QPointArray( int size ) : QMemArray<QPoint>( size ) {}
    QPointArray( const QPointArray &a ) : QMemArray<QPoint>( a ) {}
    QPointArray( const QRect &r, bool closed=FALSE );
    QPointArray( int nPoints, const QCOORD *points );

    QPointArray	 &operator=( const QPointArray &a )
    { return (QPointArray&)assign( a ); }

    QPointArray copy() const
    { QPointArray tmp; return *((QPointArray*)&tmp.duplicate(*this)); }

    void    translate( int dx, int dy );
    QRect   boundingRect() const;

    void    point( uint i, int *x, int *y ) const;
    QPoint  point( uint i ) const;
    void    setPoint( uint i, int x, int y );
    void    setPoint( uint i, const QPoint &p );
    bool    setPoints( int nPoints, const QCOORD *points );
    bool    setPoints( int nPoints, int firstx, int firsty, ... );
    bool    putPoints( int index, int nPoints, const QCOORD *points );
    bool    putPoints( int index, int nPoints, int firstx, int firsty, ... );
    bool    putPoints( int index, int nPoints,
               const QPointArray & from, int fromIndex=0 );

    void    makeArc( int x, int y, int w, int h, int a1, int a2 );
    void    makeEllipse( int x, int y, int w, int h );
    void    makeArc( int x, int y, int w, int h, int a1, int a2,
             const QWMatrix& );
    QPointArray cubicBezier() const;

    void*  shortPoints( int index = 0, int nPoints = -1 ) const;
    static void cleanBuffers();

protected:
    static uint splen;
    static void* sp;
};

/*****************************************************************************
  QPointArray stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QPointArray & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QPointArray & );
#endif

/*****************************************************************************
  Misc. QPointArray functions
 *****************************************************************************/

inline void QPointArray::setPoint( uint i, const QPoint &p )
{
    setPoint( i, p.x(), p.y() );
}

#endif // QPOINTARRAY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPointArray Member List

Complete Member List for QPointArray

This is the complete list of member functions for QPointArray, including inherited members.

  • QPointArray()
  • ~QPointArray()
  • assign()
  • at()
  • begin()
  • boundingRect()
  • bsearch()
  • contains()
  • copy()
  • count()
  • cubicBezier()
  • data()
  • detach()
  • duplicate()
  • end()
  • fill()
  • find()
  • isEmpty()
  • isNull()
  • makeArc()
  • makeEllipse()
  • nrefs()
  • operator const type *()
  • operator!=()
  • operator=()
  • operator==()
  • operator[]()
  • point()
  • putPoints()
  • resetRawData()
  • resize()
  • setPoint()
  • setRawData()
  • size()
  • sort()
  • translate()
  • truncate()


QPopupMenu Class

QPopupMenu Class Reference

The QPopupMenu class provides a popup menu widget. More...

#include <qpopupmenu.h>

Inherits QFrame and QMenuData.

List of all member functions.

Public Members

  • QPopupMenu ( QWidget * parent = 0, const char * name = 0 )
  • ~QPopupMenu ()
  • void popup ( const QPoint & pos, int indexAtPoint = -1 )
  • virtual void updateItem ( int id )
  • virtual void setCheckable ( bool )
  • bool isCheckable () const
  • int exec ()
  • int exec ( const QPoint & pos, int indexAtPoint = 0 )
  • virtual void setActiveItem ( int i )
  • int idAt ( int index ) const
  • int idAt ( const QPoint & pos ) const
  • int insertTearOffHandle ( int id = -1, int index = -1 )

Signals

  • void activated ( int id )
  • void highlighted ( int id )
  • void aboutToShow ()
  • void aboutToHide ()

Important Inherited Members

  • int insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )
  • int insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )
  • int insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )
  • int insertItem ( QWidget * widget, int id = -1, int index = -1 )
  • int insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )
  • int insertSeparator ( int index = -1 )
  • void removeItem ( int id )
  • void removeItemAt ( int index )
  • void clear ()
  • QKeySequence accel ( int id ) const
  • void setAccel ( const QKeySequence & key, int id )
  • QIconSet * iconSet ( int id ) const
  • QString text ( int id ) const
  • QPixmap * pixmap ( int id ) const
  • void setWhatsThis ( int id, const QString & text )
  • QString whatsThis ( int id ) const
  • void changeItem ( int id, const QString & text )
  • void changeItem ( int id, const QPixmap & pixmap )
  • void changeItem ( int id, const QIconSet & icon, const QString & text )
  • void changeItem ( int id, const QIconSet & icon, const QPixmap & pixmap )
  • bool isItemEnabled ( int id ) const
  • void setItemEnabled ( int id, bool enable )
  • bool isItemChecked ( int id ) const
  • void setItemChecked ( int id, bool check )
  • bool connectItem ( int id, const QObject * receiver, const char * member )
  • bool disconnectItem ( int id, const QObject * receiver, const char * member )
  • bool setItemParameter ( int id, int param )
  • int itemParameter ( int id ) const

Properties

  • bool checkable - whether the display of check marks on menu items is enabled

Protected Members

  • int itemHeight ( int row ) const
  • int itemHeight ( QMenuItem * mi ) const
  • void drawItem ( QPainter * p, int tab_, QMenuItem * mi, bool act, int x, int y, int w, int h )
  • virtual void drawContents ( QPainter * p )
  • int columns () const

Detailed Description

The QPopupMenu class provides a popup menu widget.

A popup menu widget is a selection menu. It can be either a pull-down menu in a menu bar or a standalone context (popup) menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item or hits the specified shortcut key. Use QMenuBar::insertItem() to insert a popup menu into a menu bar. Show a context menu either asynchronously with popup() or synchronously with exec().

Technically, a popup menu consists of a list of menu items. You add items with insertItem(). An item is either a string, a pixmap or a custom item that provides its own drawing function (see QCustomMenuItem). In addition, items can have an optional icon drawn on the very left side and an accelerator key such as "Ctrl+X".

There are three kinds of menu items: separators, menu items that perform an action and menu items that show a submenu. Separators are inserted with insertSeparator(). For submenus, you pass a pointer to a QPopupMenu in your call to insertItem(). All other items are considered action items.

When inserting action items you usually specify a receiver and a slot. The receiver will be notifed whenever the item is selected. In addition, QPopupMenu provides two signals, activated() and highlighted(), which signal the identifier of the respective menu item. It is sometimes practical to connect several items to one slot. To distinguish between them, specify a slot that takes an integer argument and use setItemParameter() to associate a unique value with each item.

You clear a popup menu with clear() and remove single items with removeItem() or removeItemAt().

A popup menu can display check marks for certain items when enabled with setCheckable(TRUE). You check or uncheck items with setItemChecked().

Items are either enabled or disabled. You toggle their state with setItemEnabled(). Just before a popup menu becomes visible, it emits the aboutToShow() signal. You can use this signal to set the correct enabled/disabled states of all menu items before the user sees it. The corresponding aboutToHide() signal is emitted when the menu hides again.

You can provide What's This? help for single menu items with setWhatsThis(). See QWhatsThis for general information about this kind of lightweight online help.

For ultimate flexibility, you can also add entire widgets as items into a popup menu (for example, a color selector).

A QPopupMenu can also provide a tear-off menu. A tear-off menu is a top-level window that contains a copy of the menu. This makes it possible for the user to "tear off" frequently used menus and position them in a convenient place on the screen. If you want that functionality for a certain menu, insert a tear-off handle with insertTearOffHandle(). If you want to include custom widgets in a tear-off menu, you should connect to the popup menu's signal (using connectItem() and the item ID that insertTearOffHandle() returns), and add the custom widgets you want to include. When using tear-off menus, bear in mind that the concept isn't typically used on Microsoft Windows so users may not be familiar with it. Consider using a QToolBar instead.

menu/menu.cpp is a typical example of QMenuBar and QPopupMenu use.

See also QMenuBar, GUI Design Handbook: Menu, Drop-Down and Pop-Up, Main Window and Related Classes and Basic Widgets.

Member Function Documentation

QPopupMenu::QPopupMenu ( QWidget * parent = 0, const char * name = 0 )

Constructs a popup menu with parent as a parent and name as object name.

Although a popup menu is always a top-level widget, if a parent is passed the popup menu will be deleted when that parent is destroyed (as with any other QObject).

QPopupMenu::~QPopupMenu ()

Destroys the popup menu.

void QPopupMenu::aboutToHide () [signal]

This signal is emitted just before the popup menu is hidden after it has been displayed.

Warning: Do not open a widget in a slot connected to this signal.

See also aboutToShow(), setItemEnabled(), setItemChecked(), insertItem() and removeItem().

void QPopupMenu::aboutToShow () [signal]

This signal is emitted just before the popup menu is displayed. You can connect it to any slot that sets up the menu contents (e.g. to ensure that the right items are enabled).

See also aboutToHide(), setItemEnabled(), setItemChecked(), insertItem() and removeItem().

Example: mdi/application.cpp.

QKeySequence QMenuData::accel ( int id ) const

Returns the accelerator key that has been defined for the menu item id, or 0 if it has no accelerator key.

See also setAccel(), QAccel and qnamespace.h.

void QPopupMenu::activated ( int id ) [signal]

This signal is emitted when a menu item is selected; id is the id of the selected item.

Normally, you connect each menu item to a single slot using QMenuData::insertItem(), but sometimes you will want to connect several items to a single slot (most often if the user selects from an array). This signal is useful in such cases.

See also highlighted() and QMenuData::insertItem().

Examples: grapher/grapher.cpp, helpviewer/helpwindow.cpp, qdir/qdir.cpp, qwerty/qwerty.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

void QMenuData::changeItem ( int id, const QString & text )

Changes the text of the menu item id to text. If the item has an icon, the icon remains unchanged.

See also text().

void QMenuData::changeItem ( int id, const QPixmap & pixmap )

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

Changes the pixmap of the menu item id to the pixmap pixmap. If the item has an icon, the icon is unchanged.

See also pixmap().

void QMenuData::changeItem ( int id, const QIconSet & icon, const QString & text )

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

Changes the iconset and text of the menu item id to the icon and text respectively.

See also pixmap().

void QMenuData::changeItem ( int id, const QIconSet & icon, const QPixmap & pixmap )

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

Changes the iconset and pixmap of the menu item id to icon and pixmap respectively.

See also pixmap().

void QMenuData::clear ()

Removes all menu items.

See also removeItem() and removeItemAt().

Examples: mdi/application.cpp and qwerty/qwerty.cpp.

int QPopupMenu::columns () const [protected]

If a popup menu does not fit on the screen it lays itself out so that it does fit, it is style dependant what layout means (ie on Windows it will use multiple columns).

This functions returns the number of columns necessary.

See also sizeHint.

bool QMenuData::connectItem ( int id, const QObject * receiver, const char * member )

Connects the menu item with identifier id to receiver's member slot or signal.

The receiver's slot/signal is activated when the menu item is activated.

See also disconnectItem() and setItemParameter().

Example: menu/menu.cpp.

bool QMenuData::disconnectItem ( int id, const QObject * receiver, const char * member )

Disconnects the receiver's member from the menu item with identifier id.

All connections are removed when the menu data object is destroyed.

See also connectItem() and setItemParameter().

void QPopupMenu::drawContents ( QPainter * p ) [virtual protected]

Draws all menu items using painter p.

Reimplemented from QFrame.

void QPopupMenu::drawItem ( QPainter * p, int tab_, QMenuItem * mi, bool act, int x, int y, int w, int h ) [protected]

Draws menu item mi in the area x, y, w, h, using painter p. The item is drawn active if act is TRUE or drawn inactive if act is FALSE. The rightmost tab_ pixels are used for accelerator text.

See also QStyle::drawControl().

int QPopupMenu::exec ()

Executes this popup synchronously.

This is equivalent to exec(mapToGlobal(QPoint(0,0))). In most situations you'll want to specify the position yourself, for example at the current mouse position:

      exec(QCursor::pos());
or aligned to a widget:
      exec(somewidget.mapToGlobal(QPoint(0,0)));

Examples: fileiconview/qfileiconview.cpp and scribble/scribble.cpp.

int QPopupMenu::exec ( const QPoint & pos, int indexAtPoint = 0 )

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

Executes this popup synchronously.

Opens the popup menu so that the item number indexAtPoint will be at the specified global position pos. To translate a widget's local coordinates into global coordinates, use QWidget::mapToGlobal().

The return code is the id of the selected item in either the popup menu or one of its submenus, or -1 if no item is selected (normally because the user presses Escape).

Note that all signals are emitted as usual. If you connect a menu item to a slot and call the menu's exec(), you get the result both via the signal-slot connection and in the return value of exec().

Common usage is to position the popup at the current mouse position:

      exec(QCursor::pos());
or aligned to a widget:
      exec(somewidget.mapToGlobal(QPoint(0,0)));

When positioning a popup with exec() or popup(), bear in mind that you cannot rely on the popup menu's current size(). For performance reasons, the popup adapts its size only when necessary. So in many cases, the size before and after the show is different. Instead, use sizeHint(). It calculates the proper size depending on the menu's current contents.

See also popup() and sizeHint.

void QPopupMenu::highlighted ( int id ) [signal]

This signal is emitted when a menu item is highlighted; id is the id of the highlighted item.

See also activated() and QMenuData::insertItem().

QIconSet * QMenuData::iconSet ( int id ) const

Returns the icon set that has been set for menu item id, or 0 if no icon set has been set.

See also changeItem(), text() and pixmap().

int QPopupMenu::idAt ( int index ) const

Returns the identifier of the menu item at position index in the internal list, or -1 if index is out of range.

See also QMenuData::setId() and QMenuData::indexOf().

Example: scrollview/scrollview.cpp.

int QPopupMenu::idAt ( const QPoint & pos ) const

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

Returns the id of the item at pos, or -1 if there is no item there or if it is a separator item.

int QMenuData::insertItem ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

The family of insertItem() functions inserts menu items into a popup menu or a menu bar.

A menu item is usually either a text string or a pixmap, both with an optional icon or keyboard accelerator. For special cases it is also possible to insert custom items (see QCustomMenuItem) or even widgets into popup menus.

Some insertItem() members take a popup menu as an additional argument. Use this to insert submenus to existing menus or pulldown menus to a menu bar.

The number of insert functions may look confusing, but they are actually quite simple to use.

This default version inserts a menu item with the text text, the accelerator key accel, an id and an optional index and connects it to the slot member in the object receiver.

Example:

    QMenuBar   *mainMenu = new QMenuBar;
    QPopupMenu *fileMenu = new QPopupMenu;
    fileMenu->insertItem( "New",  myView, SLOT(newFile()), CTRL+Key_N );
    fileMenu->insertItem( "Open", myView, SLOT(open()),    CTRL+Key_O );
    mainMenu->insertItem( "File", fileMenu );

Not all insert functions take an object/slot parameter or an accelerator key. Use connectItem() and setAccel() on these items.

If you need to translate accelerators, use tr() with a string description that use pass to the QKeySequence constructor:

    fileMenu->insertItem( tr("Open"), myView, SLOT(open()),
                         tr("Ctrl+O") );

In the example above, pressing Ctrl+N or selecting "Open" from the menu activates the myView->open() function.

Some insert functions take a QIconSet parameter to specify the little menu item icon. Note that you can always pass a QPixmap object instead.

The index specifies the position in the menu. The menu item is appended at the end of the list if index is negative.

Note that keyboard accelerators in Qt are not application-global, instead they are bound to a certain top-level window. For example, accelerators in QPopupMenu items only work for menus that are associated with a certain window. This is true for popup menus that live in a menu bar since their accelerators will then be installed in the menu bar itself. This also applies to stand-alone popup menus that have a top-level widget in their parentWidget() chain. The menu will then install its accelerator object on that top-level widget. For all other cases use an independent QAccel object.

Warning: Be careful when passing a literal 0 to insertItem() because some C++ compilers choose the wrong overloaded function. Cast the 0 to what you mean, e.g. (QObject*)0.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

Examples: addressbook/mainwindow.cpp, canvas/canvas.cpp, mdi/application.cpp, menu/menu.cpp, qwerty/qwerty.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, accelerator accel, optional id id, and optional index. The menu item is connected it to the receiver's member slot. The icon will be displayed to the left of the text in the item.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, const QObject * receiver, const char * member, const QKeySequence & accel = 0, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, accelerator accel, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item. The item is connected to the member slot in the receiver object.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel(), connectItem(), QAccel and qnamespace.h.

int QMenuData::insertItem ( const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with text text, optional id id, and optional index.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with text text, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QString & text, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, text text, submenu popup, optional id id, and optional index. The icon will be displayed to the left of the text in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, optional id id, and optional index.

To look best when being highlighted as a menu item, the pixmap should provide a mask (see QPixmap::mask()).

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with pixmap pixmap, submenu popup, optional id id, and optional index.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( const QIconSet & icon, const QPixmap & pixmap, QPopupMenu * popup, int id = -1, int index = -1 )

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

Inserts a menu item with icon icon, pixmap pixmap submenu popup, optional id id, and optional index. The icon will be displayed to the left of the pixmap in the item.

The popup must be deleted by the programmer or by its parent widget. It is not deleted when this menu item is removed or when the menu is deleted.

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem(), changeItem(), setAccel() and connectItem().

int QMenuData::insertItem ( QWidget * widget, int id = -1, int index = -1 )

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

Inserts a menu item that consists of the widget widget with optional id id, and optional index.

Ownership of widget is transferred to the popup menu or to the menu bar.

Theoretically, any widget can be inserted into a popup menu. In practice, this only makes sense with certain widgets.

If a widget is not focus-enabled (see QWidget::isFocusEnabled()), the menu treats it as a separator; this means that the item is not selectable and will never get focus. In this way you can, for example, simply insert a QLabel if you need a popup menu with a title.

If the widget is focus-enabled it will get focus when the user traverses the popup menu with the arrow keys. If the widget does not accept ArrowUp and ArrowDown in its key event handler, the focus will move back to the menu when the respective arrow key is hit one more time. This works with a QLineEdit, for example. If the widget accepts the arrow key itself, it must also provide the possibility to put the focus back on the menu again by calling QWidget::focusNextPrevChild(). Futhermore, if the embedded widget closes the menu when the user made a selection, this can be done safely by calling

    if ( isVisible() &&
         parentWidget() &&
         parentWidget()->inherits("QPopupMenu") )
        parentWidget()->close();

Returns the allocated menu identifier number (id if id >= 0).

See also removeItem().

int QMenuData::insertItem ( const QIconSet & icon, QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with an icon and with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertItem ( QCustomMenuItem * custom, int id = -1, int index = -1 )

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

Inserts a custom menu item custom with optional id id, and optional index.

This only works with popup menus. It is not supported for menu bars. Ownership of custom is transferred to the popup menu.

If you want to connect a custom item to a certain slot, use connectItem().

Returns the allocated menu identifier number (id if id >= 0).

See also connectItem(), removeItem() and QCustomMenuItem.

int QMenuData::insertSeparator ( int index = -1 )

Inserts a separator at position index. The separator becomes the last menu item if index is negative.

In a popup menu a separator is rendered as a horizontal line. In a Motif menu bar a separator is spacing, so the rest of the items (normally just "Help") are drawn right-justified. In a Windows menu bar separators are ignored (to comply with the Windows style guidelines).

Examples: addressbook/mainwindow.cpp, mdi/application.cpp, menu/menu.cpp, progress/progress.cpp, scrollview/scrollview.cpp, showimg/showimg.cpp and sound/sound.cpp.

int QPopupMenu::insertTearOffHandle ( int id = -1, int index = -1 )

Inserts a tear-off handle into the menu. A tear-off handle is a special menu item that creates a copy of the menu when the menu is selected. This "torn-off" copy lives in a separate window. It contains the same menu items as the original menu, with the exception of the tear-off handle.

The handle item is assigned the identifier id or an automatically generated identifier if id is < 0. The generated identifiers (negative integers) are guaranteed to be unique within the entire application.

The index specifies the position in the menu. The tear-off handle is appended at the end of the list if index is negative.

Example: menu/menu.cpp.

bool QPopupMenu::isCheckable () const

Returns TRUE if the display of check marks on menu items is enabled; otherwise returns FALSE. See the "checkable" property for details.

bool QMenuData::isItemChecked ( int id ) const

Returns TRUE if the menu item with the id id has been checked; otherwise returns FALSE.

See also setItemChecked().

Examples: canvas/canvas.cpp, progress/progress.cpp and showimg/showimg.cpp.

bool QMenuData::isItemEnabled ( int id ) const

Returns TRUE if the item with identifier id is enabled; otherwise returns FALSE

See also setItemEnabled().

int QPopupMenu::itemHeight ( int row ) const [protected]

Calculates the height in pixels of the item in row row.

int QPopupMenu::itemHeight ( QMenuItem * mi ) const [protected]

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

Calculates the height in pixels of the menu item mi.

int QMenuData::itemParameter ( int id ) const

Returns the parameter of the activation signal of item id.

If no parameter has been specified for this item with setItemParameter(), the value defaults to id.

See also connectItem(), disconnectItem() and setItemParameter().

QPixmap * QMenuData::pixmap ( int id ) const

Returns the pixmap that has been set for menu item id, or 0 if no pixmap has been set.

See also changeItem(), text() and iconSet().

void QPopupMenu::popup ( const QPoint & pos, int indexAtPoint = -1 )

Displays the popup menu so that the item number indexAtPoint will be at the specified global position pos. To translate a widget's local coordinates into global coordinates, use QWidget::mapToGlobal().

When positioning a popup with exec() or popup(), bear in mind that you cannot rely on the popup menu's current size(). For performance reasons, the popup adapts its size only when necessary, so in many cases, the size before and after the show is different. Instead, use sizeHint(). It calculates the proper size depending on the menu's current contents.

Examples: listviews/listviews.cpp and qtimage/qtimage.cpp.

void QMenuData::removeItem ( int id )

Removes the menu item that has the identifier id.

See also removeItemAt() and clear().

Example: chart/chartform.cpp.

void QMenuData::removeItemAt ( int index )

Removes the menu item at position index.

See also removeItem() and clear().

void QMenuData::setAccel ( const QKeySequence & key, int id )

Sets the accelerator key for the menu item id to key.

An accelerator key consists of a key code and a combination of the modifiers SHIFT, CTRL, ALT or UNICODE_ACCEL (OR'ed or added). The header file qnamespace.h contains a list of key codes.

Defining an accelerator key produces a text that is added to the menu item; for instance, CTRL + Key_O produces "Ctrl+O". The text is formatted differently for different platforms.

Note that keyboard accelerators in Qt are not application-global, instead they are bound to a certain top-level window. For example, accelerators in QPopupMenu items only work for menus that are associated with a certain window. This is true for popup menus that live in a menu bar since their accelerators will then be installed in the menu bar itself. This also applies to stand-alone popup menus that have a top-level widget in their parentWidget() chain. The menu will then install its accelerator object on that top-level widget. For all other cases use an independent QAccel object.

Example:

    QMenuBar *mainMenu = new QMenuBar;
    QPopupMenu *fileMenu = new QPopupMenu;       // file sub menu
    fileMenu->insertItem( "Open Document", 67 ); // add "Open" item
    fileMenu->setAccel( CTRL + Key_O, 67 );      // Control and O to open
    fileMenu->insertItem( "Quit", 69 );          // add "Quit" item
    fileMenu->setAccel( CTRL + ALT + Key_Delete, 69 );
    mainMenu->insertItem( "File", fileMenu );    // add the file menu

If you need to translate accelerators, use tr() with a string:

    fileMenu->setAccel( tr("Ctrl+O"), 67 );

You can also specify the accelerator in the insertItem() function. You may prefer to use QAction to associate accelerators with menu items.

See also accel(), insertItem(), QAccel and QAction.

Example: menu/menu.cpp.

void QPopupMenu::setActiveItem ( int i ) [virtual]

Sets the currently active item to i and repaints as necessary.

void QPopupMenu::setCheckable ( bool ) [virtual]

Sets whether the display of check marks on menu items is enabled. See the "checkable" property for details.

void QMenuData::setItemChecked ( int id, bool check )

If check is TRUE, checks the menu item with id id; otherwise unchecks the menu item with id id. Calls QPopupMenu::setCheckable( TRUE ) if necessary.

See also isItemChecked().

Examples: canvas/canvas.cpp, grapher/grapher.cpp, mdi/application.cpp, menu/menu.cpp, progress/progress.cpp, scrollview/scrollview.cpp and showimg/showimg.cpp.

void QMenuData::setItemEnabled ( int id, bool enable )

If enable is TRUE, enables the menu item with identifier id; otherwise disables the menu item with identifier id.

See also isItemEnabled().

Examples: mdi/application.cpp, menu/menu.cpp, progress/progress.cpp and showimg/showimg.cpp.

bool QMenuData::setItemParameter ( int id, int param )

Sets the parameter of the activation signal of item id to param.

If any receiver takes an integer parameter, this value is passed.

See also connectItem(), disconnectItem() and itemParameter().

Example: mdi/application.cpp.

void QMenuData::setWhatsThis ( int id, const QString & text )

Sets text as What's This help for the menu item with identifier id.

See also whatsThis().

Examples: application/application.cpp and mdi/application.cpp.

QString QMenuData::text ( int id ) const

Returns the text that has been set for menu item id, or a null string if no text has been set.

See also changeItem(), pixmap() and iconSet().

Examples: qdir/qdir.cpp and showimg/showimg.cpp.

void QPopupMenu::updateItem ( int id ) [virtual]

Updates the item with identity id.

Reimplemented from QMenuData.

QString QMenuData::whatsThis ( int id ) const

Returns the What's This help text for the item with identifier id or QString::null if no text has yet been defined.

See also setWhatsThis().

Property Documentation

bool checkable

This property holds whether the display of check marks on menu items is enabled.

When TRUE, the display of check marks on menu items is enabled. Checking is always enabled when in Windows-style.

See also QMenuData::setItemChecked().

Set this property's value with setCheckable() and get this property's value with isCheckable().

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


qpopupmenu.h Include File

qpopupmenu.h

This is the verbatim text of the qpopupmenu.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qpopupmenu.h   3.0.5   edited May 27 04:06 $
**
** Definition of QPopupMenu class
**
** Created : 941128
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPOPUPMENU_H
#define QPOPUPMENU_H

#ifndef QT_H
#include "qframe.h"
#include "qmenudata.h"
#endif // QT_H

#ifndef QT_NO_POPUPMENU
class QPopupMenuPrivate;

class Q_EXPORT QPopupMenu : public QFrame, public QMenuData
{
    Q_OBJECT
    Q_PROPERTY( bool checkable READ isCheckable WRITE setCheckable )
public:
    QPopupMenu( QWidget* parent=0, const char* name=0 );
    ~QPopupMenu();

    void	popup( const QPoint & pos, int indexAtPoint = -1 ); // open
    void	updateItem( int id );

    virtual void	setCheckable( bool );
    bool	isCheckable() const;

    void	setFont( const QFont & );
    void	show();
    void	hide();

    int		exec();
    int 	exec( const QPoint & pos, int indexAtPoint = 0 ); // modal

    virtual void	setActiveItem( int );
    QSize	sizeHint() const;

    int 	idAt( int index ) const { return QMenuData::idAt( index ); }
    int 	idAt( const QPoint& pos ) const;

    bool 	customWhatsThis() const;

    int		insertTearOffHandle( int id=-1, int index=-1 );

    void	activateItemAt( int index );
    QRect	itemGeometry( int index );

signals:
    void	activated( int itemId );
    void	highlighted( int itemId );
    void	activatedRedirect( int itemId ); // to parent menu
    void	highlightedRedirect( int itemId );
    void	aboutToShow();
    void	aboutToHide();

protected:
    int 	itemHeight( int ) const;
    int 	itemHeight( QMenuItem* mi ) const;
    void 	drawItem( QPainter* p, int tab, QMenuItem* mi,
           bool act, int x, int y, int w, int h);

    void 	drawContents( QPainter * );

    void 	closeEvent( QCloseEvent *e );
    void	paintEvent( QPaintEvent * );
    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	keyPressEvent( QKeyEvent * );
    void	focusInEvent( QFocusEvent * );
    void	focusOutEvent( QFocusEvent * );
    void	timerEvent( QTimerEvent * );
    void	leaveEvent( QEvent * );
    void 	styleChange( QStyle& );
    int 	columns() const;

    bool	focusNextPrevChild( bool next );

    int		itemAtPos( const QPoint &, bool ignoreSeparator = TRUE ) const;

private slots:
    void	subActivated( int itemId );
    void	subHighlighted( int itemId );
#ifndef QT_NO_ACCEL
    void	accelActivated( int itemId );
    void	accelDestroyed();
#endif
    void	popupDestroyed( QObject* );
    void	modalActivation( int );

    void	subMenuTimer();
    void	subScrollTimer();
    void	allowAnimation();
    void     toggleTearOff();

    void        performDelayedChanges();

private:
    void        updateScrollerState();
    void	menuContentsChanged();
    void	menuStateChanged();
    void        performDelayedContentsChanged();
    void        performDelayedStateChanged();
    void	menuInsPopup( QPopupMenu * );
    void	menuDelPopup( QPopupMenu * );
    void	frameChanged();

    void	actSig( int, bool = FALSE );
    void	hilitSig( int );
    virtual void setFirstItemActive();
    void	hideAllPopups();
    void	hidePopups();
    bool	tryMenuBar( QMouseEvent * );
    void	byeMenuBar();

    void	updateSize();
    void	updateRow( int row );
#ifndef QT_NO_ACCEL
    void	updateAccel( QWidget * );
    void	enableAccel( bool );
#endif
    QPopupMenuPrivate  *d;
#ifndef QT_NO_ACCEL
    QAccel     *autoaccel;
#endif

#if defined(Q_WS_MAC) && !defined(QMAC_QMENUBAR_NO_NATIVE)
    uint mac_dirty_popup : 1;
#endif

    int popupActive;
    int tab;
    uint accelDisabled : 1;
    uint checkable : 1;
    uint connectModalRecursionSafety : 1;
    uint tornOff : 1;
    uint pendingDelayedContentsChanges : 1;
    uint pendingDelayedStateChanges : 1;
    int maxPMWidth;
    int ncols;
    bool	snapToMouse;
    bool	tryMouseEvent( QPopupMenu *, QMouseEvent * );

    friend class QMenuData;
    friend class QMenuBar;

    void connectModal(QPopupMenu* receiver, bool doConnect);

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPopupMenu( const QPopupMenu & );
    QPopupMenu &operator=( const QPopupMenu & );
#endif
};

#endif // QT_NO_POPUPMENU

#endif // QPOPUPMENU_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPopupMenu Member List

Complete Member List for QPopupMenu

This is the complete list of member functions for QPopupMenu, including inherited members.

  • QPopupMenu()
  • ~QPopupMenu()
  • aboutToHide()
  • aboutToShow()
  • accel()
  • acceptDrops()
  • activateItemAt()
  • activated()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • changeItem()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectItem()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectItem()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawItem()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • find()
  • findItem()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • highlighted()
  • icon()
  • iconSet()
  • iconText()
  • iconify()
  • idAt()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertItem()
  • insertSeparator()
  • insertTearOffHandle()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isCheckable()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isItemActive()
  • isItemChecked()
  • isItemEnabled()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • itemHeight()
  • itemParameter()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • menuContentsChanged()
  • menuDelPopup()
  • menuInsPopup()
  • menuStateChanged()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • popup()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeItem()
  • removeItemAt()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveItem()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCheckable()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setId()
  • setItemChecked()
  • setItemEnabled()
  • setItemParameter()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • setWhatsThis()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateItem()
  • updateMask()
  • visibleRect()
  • whatsThis()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QPrinter Class

QPrinter Class Reference

The QPrinter class is a paint device that paints on a printer. More...

#include <qprinter.h>

Inherits QPaintDevice.

List of all member functions.

Public Members

  • enum PrinterMode { ScreenResolution, PrinterResolution, HighResolution, Compatible }
  • QPrinter ( PrinterMode m = ScreenResolution )
  • ~QPrinter ()
  • enum Orientation { Portrait, Landscape }
  • enum PageSize { A4, B5, Letter, Legal, Executive, A0, A1, A2, A3, A5, A6, A7, A8, A9, B0, B1, B10, B2, B3, B4, B6, B7, B8, B9, C5E, Comm10E, DLE, Folio, Ledger, Tabloid, Custom, NPageSize = Custom }
  • enum PageOrder { FirstPageFirst, LastPageFirst }
  • enum ColorMode { GrayScale, Color }
  • enum PaperSource { OnlyOne, Lower, Middle, Manual, Envelope, EnvelopeManual, Auto, Tractor, SmallFormat, LargeFormat, LargeCapacity, Cassette, FormSource }
  • QString printerName () const
  • virtual void setPrinterName ( const QString & name )
  • bool outputToFile () const
  • virtual void setOutputToFile ( bool enable )
  • QString outputFileName () const
  • virtual void setOutputFileName ( const QString & fileName )
  • QString printProgram () const
  • virtual void setPrintProgram ( const QString & printProg )
  • QString printerSelectionOption () const
  • virtual void setPrinterSelectionOption ( const QString & option )
  • QString docName () const
  • virtual void setDocName ( const QString & name )
  • QString creator () const
  • virtual void setCreator ( const QString & creator )
  • Orientation orientation () const
  • virtual void setOrientation ( Orientation orientation )
  • PageSize pageSize () const
  • virtual void setPageSize ( PageSize newPageSize )
  • short winPageSize () const
  • virtual void setPageOrder ( PageOrder newPageOrder )
  • PageOrder pageOrder () const
  • virtual void setResolution ( int dpi )
  • virtual int resolution () const
  • virtual void setColorMode ( ColorMode newColorMode )
  • ColorMode colorMode () const
  • virtual void setFullPage ( bool fp )
  • bool fullPage () const
  • QSize margins () const
  • int fromPage () const
  • int toPage () const
  • virtual void setFromTo ( int fromPage, int toPage )
  • int minPage () const
  • int maxPage () const
  • virtual void setMinMax ( int minPage, int maxPage )
  • int numCopies () const
  • virtual void setNumCopies ( int numCopies )
  • bool newPage ()
  • bool abort ()
  • bool aborted () const
  • bool setup ( QWidget * parent = 0 )
  • PaperSource paperSource () const
  • virtual void setPaperSource ( PaperSource source )

Detailed Description

The QPrinter class is a paint device that paints on a printer.

On Windows it uses the built-in printer drivers. On X11 it generates postscript and sends that to lpr, lp, or another print command.

QPrinter is used in much the same way as QWidget and QPixmap are used. The big difference is that you must keep track of the pages.

QPrinter supports a number of settable parameters, most of which can be changed by the end user when the application calls QPrinter::setup().

The most important parameters are:

  • setOrientation() tells QPrinter which page orientation to use (virtual).
  • setPageSize() tells QPrinter what page size to expect from the printer.
  • setResolution() tells QPrinter what resolution you wish the printer to provide (in dpi).
  • setFullPage() tells QPrinter whether you want to deal with the full page or just with the part the printer can draw on. The default is FALSE, so that by default you should be able to paint on (0,0). If TRUE the origin of the coordinate system will be in the top left corner of the paper and most probably the printer will not be able to paint something there due to it's physical margins.
  • setNumCopies() tells QPrinter how many copies of the document it should print.
  • setMinMax() tells QPrinter and QPrintDialog what the allowed range for fromPage() and toPage() are.

Except where noted, you can only call the set functions before setup(), or between QPainter::end() and setup(). (Some may take effect between setup() and begin(), or between begin() and end(), but that's strictly undocumented and such behaviour may differ depending on platform.)

There are also some settings that the user sets (through the printer dialog) and that applications are expected to obey:

  • pageOrder() tells the application program whether to print first-page-first or last-page-first.

  • colorMode() tells the application program whether to print in color or grayscale. (If you print in color and the printer does not support color, Qt will try to approximate. The document may take longer to print, but the quality should not be made visibly poorer.)

  • fromPage() and toPage() indicate what pages the application program should print.

  • paperSource() tells the application progam which paper source to print from.

You can of course call these functions to establish defaults before you ask the user through QPrinter::setup().

Once you start printing, calling newPage() is essential. You will probably also need to look at the QPaintDeviceMetrics for the printer (see the print function in the Application walk-through). Note that the paint device metrics are valid only after the QPrinter has been set up, i.e. after setup() has returned successfully.

If you want to abort the print job, abort() will try its best to stop printing. It may cancel the entire job or just some of it.

The TrueType font embedding for Qt's postscript driver uses code by David Chappell of Trinity College Computing Center.

Copyright 1995, Trinity College Computing Center. Written by David Chappell.

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.

TrueType font support. These functions allow PPR to generate PostScript fonts from Microsoft compatible TrueType font files.

The functions in this file do most of the work to convert a TrueType font to a type 3 PostScript font.

Most of the material in this file is derived from a program called "ttf2ps" which L. S. Ng posted to the usenet news group "comp.sources.postscript". The author did not provide a copyright notice or indicate any restrictions on use.

Last revised 11 July 1995.

See also Graphics Classes and Image Processing Classes.

Member Type Documentation

QPrinter::ColorMode

This enum type is used to indicate whether QPrinter should print in color or not.

  • QPrinter::Color - print in color if available, otherwise in grayscale.
  • QPrinter::GrayScale - print in grayscale, even on color printers. Might be a little faster than Color. This is the default.

QPrinter::Orientation

This enum type (not to be confused with Qt::Orientation) is used to specify each page's orientation.

  • QPrinter::Portrait - the page's height is greater than its width (the default).
  • QPrinter::Landscape - the page's width is greater than its height.

This type interacts with QPrinter::PageSize and QPrinter::setFullPage() to determine the final size of the page available to the application.

QPrinter::PageOrder

This enum type is used by QPrinter to tell the application program how to print.

  • QPrinter::FirstPageFirst - the lowest-numbered page should be printed first.
  • QPrinter::LastPageFirst - the highest-numbered page should be printed first.

QPrinter::PageSize

This enum type specifies what paper size QPrinter should use. QPrinter does not check that the paper size is available; it just uses this information, together with QPrinter::Orientation and QPrinter::setFullPage(), to determine the printable area (see QPaintDeviceMetrics).

The defined sizes (with setFullPage(TRUE)) are:

  • QPrinter::A0 - 841 x 1189 mm
  • QPrinter::A1 - 594 x 841 mm
  • QPrinter::A2 - 420 x 594 mm
  • QPrinter::A3 - 297 x 420 mm
  • QPrinter::A4 - 210 x 297 mm, 8.26 x 11.7 inches
  • QPrinter::A5 - 148 x 210 mm
  • QPrinter::A6 - 105 x 148 mm
  • QPrinter::A7 - 74 x 105 mm
  • QPrinter::A8 - 52 x 74 mm
  • QPrinter::A9 - 37 x 52 mm
  • QPrinter::B0 - 1030 x 1456 mm
  • QPrinter::B1 - 728 x 1030 mm
  • QPrinter::B10 - 32 x 45 mm
  • QPrinter::B2 - 515 x 728 mm
  • QPrinter::B3 - 364 x 515 mm
  • QPrinter::B4 - 257 x 364 mm
  • QPrinter::B5 - 182 x 257 mm, 7.17 x 10.13 inches
  • QPrinter::B6 - 128 x 182 mm
  • QPrinter::B7 - 91 x 128 mm
  • QPrinter::B8 - 64 x 91 mm
  • QPrinter::B9 - 45 x 64 mm
  • QPrinter::C5E - 163 x 229 mm
  • QPrinter::Comm10E - 105 x 241 mm, US Common #10 Envelope
  • QPrinter::DLE - 110 x 220 mm
  • QPrinter::Executive - 7.5 x 10 inches, 191 x 254 mm
  • QPrinter::Folio - 210 x 330 mm
  • QPrinter::Ledger - 432 x 279 mm
  • QPrinter::Legal - 8.5 x 14 inches, 216 x 356 mm
  • QPrinter::Letter - 8.5 x 11 inches, 216 x 279 mm
  • QPrinter::Tabloid - 279 x 432 mm
  • QPrinter::Custom
  • QPrinter::NPageSize - (internal)

With setFullPage(FALSE) (the default), the metrics will be a bit smaller; how much depends on the printer in use.

QPrinter::PaperSource

This enum type specifies what paper source QPrinter is to use. QPrinter does not check that the paper source is available; it just uses this information to try and set the paper source. Whether it will set the paper source depends on whether the printer has that particular source.

Note: this is currently only implemented for Windows.

  • QPrinter::OnlyOne
  • QPrinter::Lower
  • QPrinter::Middle
  • QPrinter::Manual
  • QPrinter::Envelope
  • QPrinter::EnvelopeManual
  • QPrinter::Auto
  • QPrinter::Tractor
  • QPrinter::SmallFormat
  • QPrinter::LargeFormat
  • QPrinter::LargeCapacity
  • QPrinter::Cassette
  • QPrinter::FormSource

QPrinter::PrinterMode

This enum describes the mode the printer should work in. It basically presets a certain resolution and working mode.

  • QPrinter::ScreenResolution - Sets the resolution of the print device to the screen resolution. This has the big advantage that the results obtained when painting on the printer will match more or less exactly the visible output on the screen. It is the easiest to use, as font metrics on the screen and on the printer are the same. This is the default value.
  • QPrinter::PrinterResolution - Use the physical resolution of the printer on Windows. On Unix, set the postscript resolution to 72 dpi.
  • QPrinter::HighResolution - Use printer resolution on windows, set the resolution of the postscript driver to 600dpi.
  • QPrinter::Compatible - Almost the same as PrinterResolution, but keeps some peculiarities of the Qt 2.x printer driver. This is useful for applications ported from Qt 2.x to Qt 3.x.

Member Function Documentation

QPrinter::QPrinter ( PrinterMode m = ScreenResolution )

Constructs a printer paint device with mode m.

See also QPrinter::PrinterMode.

QPrinter::~QPrinter ()

Destroys the printer paint device and cleans up.

bool QPrinter::abort ()

Aborts the print job. Returns TRUE if successful; otherwise returns FALSE.

See also aborted().

bool QPrinter::aborted () const

Returns TRUE is the printer job was aborted; otherwise returns FALSE.

See also abort().

ColorMode QPrinter::colorMode () const

Returns the current color mode. The default color mode is Color.

See also setColorMode().

QString QPrinter::creator () const

Returns the name of the application that created the document.

See also setCreator().

QString QPrinter::docName () const

Returns the document name.

See also setDocName().

int QPrinter::fromPage () const

Returns the from-page setting. The default value is 0.

If fromPage() and toPage() both return 0 this signifies 'print the whole document'.

The programmer is responsible for reading this setting and printing accordingly.

See also setFromTo() and toPage().

bool QPrinter::fullPage () const

Returns TRUE if the origin of the printer's coordinate system is at the corner of the sheet and FALSE if it is at the edge of the printable area.

See setFullPage() for details and caveats.

See also setFullPage(), PageSize and QPaintDeviceMetrics.

QSize QPrinter::margins () const

Returns the width of the left margin and the height of the top margin of the printer. On Unix, this is a best-effort guess, not based on perfect knowledge.

If you have called setFullPage( TRUE ), margins().width() may be treated as the smallest sane left/right margin you can use, and margins().height() as the smallest sane top/bottom margins you can use.

If you have called setFullPage( FALSE ) (this is the default), margins() is automatically subtracted from the pageSize() by QPrinter.

See also setFullPage(), QPaintDeviceMetrics and PageSize.

int QPrinter::maxPage () const

Returns the max-page setting. A user can't choose a higher page number than maxPage() when they select a print range. The default value is 0.

See also minPage(), setMinMax() and setFromTo().

int QPrinter::minPage () const

Returns the min-page setting, i.e. the lowest page number a user is allowed to choose. The default value is 0.

See also maxPage(), setMinMax() and setFromTo().

bool QPrinter::newPage ()

Advances to a new page on the printer. Returns TRUE if successful; otherwise returns FALSE.

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

int QPrinter::numCopies () const

Returns the number of copies to be printed. The default value is 1.

See also setNumCopies().

Orientation QPrinter::orientation () const

Returns the orientation setting. The default value is QPrinter::Portrait.

See also setOrientation().

QString QPrinter::outputFileName () const

Returns the name of the output file. There is no default file name.

See also setOutputFileName() and setOutputToFile().

bool QPrinter::outputToFile () const

Returns TRUE if the output should be written to a file, or FALSE if the output should be sent directly to the printer. The default setting is FALSE.

This function is currently only supported under X11.

See also setOutputToFile() and setOutputFileName().

PageOrder QPrinter::pageOrder () const

Returns the current page order.

The default page order is FirstPageFirst.

PageSize QPrinter::pageSize () const

Returns the printer page size. The default value is system-dependent.

See also setPageSize().

PaperSource QPrinter::paperSource () const

Returns the currently set paper source of the printer.

See also setPaperSource().

QString QPrinter::printProgram () const

Returns the name of the program that sends the print output to the printer.

The default is to return a null string; meaning that QPrinter will try to be smart in a system-dependent way. On X11 only, you can set it to something different to use a specific print program.

On Windows, this function returns the name of the printer device driver.

See also setPrintProgram() and setPrinterSelectionOption().

QString QPrinter::printerName () const

Returns the printer name. This value is initially set to the name of the default printer.

See also setPrinterName().

QString QPrinter::printerSelectionOption () const

Returns the printer options selection string. This is useful only if the print command has been explicitly set.

The default value (a null string) implies that the printer should be selected in a system-dependent manner.

Any other value implies that the given value should be used.

See also setPrinterSelectionOption().

int QPrinter::resolution () const [virtual]

Returns the current assumed resolution of the printer, as set by setResolution() or by the printer subsystem.

See also setResolution().

void QPrinter::setColorMode ( ColorMode newColorMode ) [virtual]

Sets the printer's color mode to newColorMode, which can be either Color (the default) or GrayScale.

See also colorMode().

void QPrinter::setCreator ( const QString & creator ) [virtual]

Sets the name of the application that created the document to creator.

This function is only applicable to the X11 version of Qt. If no creator name is specified, the creator will be set to "Qt" followed by some version number.

See also creator().

void QPrinter::setDocName ( const QString & name ) [virtual]

Sets the document name to name.

void QPrinter::setFromTo ( int fromPage, int toPage ) [virtual]

Sets the from-page and to-page settings to fromPage and toPage respectively.

The from-page and to-page settings specify what pages to print.

If fromPage() and toPage() both return 0 this signifies 'print the whole document'.

This function is useful mostly to set a default value that the user can override in the print dialog when you call setup().

See also fromPage(), toPage(), setMinMax() and setup().

void QPrinter::setFullPage ( bool fp ) [virtual]

Sets QPrinter to have the origin of the coordinate system at the top-left corner of the paper if fp is TRUE, or where it thinks the top-left corner of the printable area is if fp is FALSE.

The default is FALSE. You can (probably) print on (0,0), and QPaintDeviceMetrics will report something smaller than the size indicated by PageSize. (Note that QPrinter may be wrong on Unix systems - it does not have perfect knowledge of the physical printer.)

If you set fp to TRUE, QPaintDeviceMetrics will report the exact same size as indicated by PageSize, but you cannot print on all of that - you must take care of the output margins yourself.

See also PageSize, setPageSize(), QPaintDeviceMetrics and fullPage().

Example: helpviewer/helpwindow.cpp.

void QPrinter::setMinMax ( int minPage, int maxPage ) [virtual]

Sets the min-page and max-page settings to minPage and maxPage respectively.

The min-page and max-page restrict the from-page and to-page settings. When the printer setup dialog appears, the user cannot select a from page or a to page that are outside the range specified by min and max pages.

See also minPage(), maxPage(), setFromTo() and setup().

void QPrinter::setNumCopies ( int numCopies ) [virtual]

Sets the number of pages to be printed to numCopies.

The printer driver reads this setting and prints the specified number of copies.

See also numCopies() and setup().

void QPrinter::setOrientation ( Orientation orientation ) [virtual]

Sets the print orientation to orientation.

The orientation can be either QPrinter::Portrait or QPrinter::Landscape.

The printer driver reads this setting and prints using the specified orientation. On Windows this setting won't take effect until the printer dialog is shown (using QPrinter::setup()).

See also orientation().

void QPrinter::setOutputFileName ( const QString & fileName ) [virtual]

Sets the name of the output file to fileName.

Setting a null or empty name (0 or "") disables output to a file, i.e. calls setOutputToFile(FALSE). Setting a non-empty name enables output to a file, i.e. calls setOutputToFile(TRUE).

This function is currently only supported under X11.

See also outputFileName() and setOutputToFile().

void QPrinter::setOutputToFile ( bool enable ) [virtual]

Specifies whether the output should be written to a file or sent directly to the printer.

Will output to a file if enable is TRUE, or will output directly to the printer if enable is FALSE.

This function is currently only supported under X11.

See also outputToFile() and setOutputFileName().

void QPrinter::setPageOrder ( PageOrder newPageOrder ) [virtual]

Sets the page order to newPageOrder.

The page order can be QPrinter::FirstPageFirst or QPrinter::LastPageFirst. The application programmer is responsible for reading the page order and printing accordingly.

This function is useful mostly for setting a default value that the user can override in the print dialog when you call setup().

void QPrinter::setPageSize ( PageSize newPageSize ) [virtual]

Sets the printer page size to newPageSize if that size is supported. The result if undefined if newPageSize is not supported.

The default page size is system-dependent.

This function is useful mostly for setting a default value that the user can override in the print dialog when you call setup().

See also pageSize(), PageSize, setFullPage() and setResolution().

void QPrinter::setPaperSource ( PaperSource source ) [virtual]

Sets the paper source setting to source.

See also paperSource().

void QPrinter::setPrintProgram ( const QString & printProg ) [virtual]

Sets the name of the program that should do the print job to printProg.

On X11, this function sets the program to call with the PostScript output. On other platforms, it has no effect.

See also printProgram().

void QPrinter::setPrinterName ( const QString & name ) [virtual]

Sets the printer name to name.

The default printer will be used if no printer name is set.

Under X11, the PRINTER environment variable defines the default printer. Under any other window system, the window system defines the default printer.

See also printerName().

void QPrinter::setPrinterSelectionOption ( const QString & option ) [virtual]

Sets the printer to use option to select the printer. option is null by default (which implies that Qt should be smart enough to guess correctly), but it can be set to other values to use a specific printer selection option.

If the printer selection option is changed while the printer is active, the current print job may or may not be affected.

See also printerSelectionOption().

void QPrinter::setResolution ( int dpi ) [virtual]

Requests that the printer prints at dpi or as near to dpi as possible.

This setting affects the coordinate system as returned by, for example, QPaintDeviceMetrics and QPainter::viewport().

The value depends on the PrintingMode used in the QPrinter constructor. By default, the dpi value of the screen is used.

This function must be called before setup() to have an effect on all platforms.

See also resolution() and setPageSize().

bool QPrinter::setup ( QWidget * parent = 0 )

Opens a printer setup dialog, with parent parent, and asks the user to specify which printer they wish to use and what settings it should have.

Returns TRUE if the user pressed "OK" to print, or FALSE if the user cancelled the operation.

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

int QPrinter::toPage () const

Returns the to-page setting. The default value is 0.

If fromPage() and toPage() both return 0 this signifies 'print the whole document'.

The programmer is responsible for reading this setting and printing accordingly.

See also setFromTo() and fromPage().

short QPrinter::winPageSize () const

Returns the Windows page size value as used by the DEVMODE struct (Windows only). Using this function is not portable.

Use pageSize() to get the PageSize, e.g. 'A4', 'Letter', etc.

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


qprinter.h Include File

qprinter.h

This is the verbatim text of the qprinter.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qprinter.h   3.0.5   edited May 3 17:07 $
**
** Definition of QPrinter class
**
** Created : 940927
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPRINTER_H
#define QPRINTER_H

#ifndef QT_H
#include "qpaintdevice.h"
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_PRINTER

#ifdef Q_WS_WIN
#include "qt_windows.h"
#endif

#if defined(B0)
#undef B0 // Terminal hang-up.  We assume that you do not want that.
#endif

class QPrinterPrivate;

class Q_EXPORT QPrinter : public QPaintDevice
{
public:
    enum PrinterMode { ScreenResolution, PrinterResolution, HighResolution, Compatible };

    QPrinter( PrinterMode mode = ScreenResolution );
   ~QPrinter();

    enum Orientation { Portrait, Landscape };

    enum PageSize    { A4, B5, Letter, Legal, Executive,
               A0, A1, A2, A3, A5, A6, A7, A8, A9, B0, B1,
               B10, B2, B3, B4, B6, B7, B8, B9, C5E, Comm10E,
               DLE, Folio, Ledger, Tabloid, Custom, NPageSize = Custom };

    enum PageOrder   { FirstPageFirst, LastPageFirst };

    enum ColorMode   { GrayScale, Color };

    enum PaperSource { OnlyOne, Lower, Middle, Manual, Envelope,
                       EnvelopeManual, Auto, Tractor, SmallFormat,
                       LargeFormat, LargeCapacity, Cassette, FormSource };

    QString printerName() const;
    virtual void setPrinterName( const QString &);
    bool outputToFile() const;
    virtual void setOutputToFile( bool );
    QString outputFileName()const;
    virtual void setOutputFileName( const QString &);

    QString printProgram() const;
    virtual void setPrintProgram( const QString &);

    QString printerSelectionOption() const;
    virtual void setPrinterSelectionOption( const QString & );

    QString docName() const;
    virtual void setDocName( const QString &);
    QString creator() const;
    virtual void setCreator( const QString &);

    Orientation orientation()   const;
    virtual void setOrientation( Orientation );
    PageSize    pageSize()      const;
    virtual void setPageSize( PageSize );
#ifdef Q_WS_WIN
    short winPageSize() const;
#endif

    virtual void setPageOrder( PageOrder );
    PageOrder   pageOrder() const;

    void setResolution( int );
    int resolution() const;

    virtual void setColorMode( ColorMode );
    ColorMode   colorMode() const;

    virtual void        setFullPage( bool );
    bool                fullPage() const;
    QSize       margins()       const;

    int         fromPage()      const;
    int         toPage()        const;
    virtual void setFromTo( int fromPage, int toPage );
    int         minPage()       const;
    int         maxPage()       const;
    virtual void setMinMax( int minPage, int maxPage );
    int         numCopies()     const;
    virtual void setNumCopies( int );

    bool	collateCopiesEnabled() const;
    void	setCollateCopiesEnabled(bool );

    bool	collateCopies() const;
    void	setCollateCopies(bool );

    bool        newPage();
    bool        abort();
    bool        aborted()       const;

    bool        setup( QWidget *parent = 0 );

    PaperSource paperSource()   const;
    virtual void setPaperSource( PaperSource );

protected:
    bool        cmd( int, QPainter *, QPDevCmdParam * );
    int         metric( int ) const;

#if defined(Q_WS_WIN)
    virtual void        setActive();
    virtual void        setIdle();
#endif

private:
#if defined(Q_WS_X11) || defined(Q_WS_QWS)
    QPaintDevice *pdrv;
    int         pid;
#endif
#if defined(Q_WS_MAC)
    PMPageFormat pformat;
    PMPrintSettings psettings;
    PMPrintSession psession;
    bool prepare(PMPrintSettings *);
    bool prepare(PMPageFormat *);
#endif
#if defined(Q_WS_WIN)
    void        readPdlg( void* );
    void        readPdlgA( void* );
    void	writeDevmode( HANDLE );
    void	writeDevmodeA( HANDLE );
    void	reinit();

    bool        viewOffsetDone;
    QPainter*   painter;
    HANDLE hdevmode;
    HANDLE hdevnames;
#endif

    int         state;
    QString     printer_name;
    QString     option_string;
    QString     output_filename;
    bool        output_file;
    QString     print_prog;
    QString     doc_name;
    QString     creator_name;

    PageSize    page_size;
    PaperSource paper_source;
    PageOrder   page_order;
    ColorMode   color_mode;
    Orientation orient;
    uint	to_edge : 1;
    uint	appcolcopies : 1;
    uint	usercolcopies : 1;
    uint	res_set : 1;
    short       from_pg, to_pg;
    short       min_pg,  max_pg;
    short       ncopies;
    int         res;
    QPrinterPrivate *d;

private:        // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPrinter( const QPrinter & );
    QPrinter &operator=( const QPrinter & );
#endif
};

inline QString QPrinter::printerName() const
{ return printer_name; }

inline bool QPrinter::outputToFile() const
{ return output_file; }

inline QString QPrinter::outputFileName() const
{ return output_filename; }

inline QString QPrinter::printProgram() const
{ return print_prog; }

inline QString QPrinter::docName() const
{ return doc_name; }

inline QString QPrinter::creator() const
{ return creator_name; }

inline QPrinter::PageSize QPrinter::pageSize() const
{ return page_size; }

inline QPrinter::Orientation QPrinter::orientation() const
{ return orient; }

inline int QPrinter::fromPage() const
{ return from_pg; }

inline int QPrinter::toPage() const
{ return to_pg; }

inline int QPrinter::minPage() const
{ return min_pg; }

inline int QPrinter::maxPage() const
{ return max_pg; }

inline int QPrinter::numCopies() const
{ return ncopies; }

inline bool QPrinter::collateCopiesEnabled() const
{ return appcolcopies; }

inline void QPrinter::setCollateCopiesEnabled(bool v)
{ appcolcopies = v; }

inline bool QPrinter::collateCopies() const
{ return usercolcopies; }

#endif // QT_NO_PRINTER

#endif // QPRINTER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPrinter Member List

Complete Member List for QPrinter

This is the complete list of member functions for QPrinter, including inherited members.

  • QPrinter()
  • ~QPrinter()
  • abort()
  • aborted()
  • cmd()
  • colorMode()
  • creator()
  • docName()
  • fromPage()
  • fullPage()
  • handle()
  • isExtDev()
  • margins()
  • maxPage()
  • minPage()
  • newPage()
  • numCopies()
  • orientation()
  • outputFileName()
  • outputToFile()
  • pageOrder()
  • pageSize()
  • paintingActive()
  • paperSource()
  • printProgram()
  • printerName()
  • printerSelectionOption()
  • resolution()
  • setColorMode()
  • setCreator()
  • setDocName()
  • setFromTo()
  • setFullPage()
  • setMinMax()
  • setNumCopies()
  • setOrientation()
  • setOutputFileName()
  • setOutputToFile()
  • setPageOrder()
  • setPageSize()
  • setPaperSource()
  • setPrintProgram()
  • setPrinterName()
  • setPrinterSelectionOption()
  • setResolution()
  • setup()
  • toPage()
  • winPageSize()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()


QProcess Class

QProcess Class Reference

The QProcess class is used to start external programs and to communicate with them. More...

#include <qprocess.h>

Inherits QObject.

List of all member functions.

Public Members

  • QProcess ( QObject * parent = 0, const char * name = 0 )
  • QProcess ( const QString & arg0, QObject * parent = 0, const char * name = 0 )
  • QProcess ( const QStringList & args, QObject * parent = 0, const char * name = 0 )
  • ~QProcess ()
  • QStringList arguments () const
  • void clearArguments ()
  • virtual void setArguments ( const QStringList & args )
  • virtual void addArgument ( const QString & arg )
  • QDir workingDirectory () const
  • virtual void setWorkingDirectory ( const QDir & dir )
  • enum Communication { Stdin = 0x01, Stdout = 0x02, Stderr = 0x04, DupStderr = 0x08 }
  • void setCommunication ( int commFlags )
  • int communication () const
  • virtual bool start ( QStringList * env = 0 )
  • virtual bool launch ( const QString & buf, QStringList * env = 0 )
  • virtual bool launch ( const QByteArray & buf, QStringList * env = 0 )
  • bool isRunning () const
  • bool normalExit () const
  • int exitStatus () const
  • virtual QByteArray readStdout ()
  • virtual QByteArray readStderr ()
  • bool canReadLineStdout () const
  • bool canReadLineStderr () const
  • virtual QString readLineStdout ()
  • virtual QString readLineStderr ()
  • PID processIdentifier ()

Public Slots

  • void tryTerminate () const
  • void kill () const
  • virtual void writeToStdin ( const QByteArray & buf )
  • virtual void writeToStdin ( const QString & buf )
  • virtual void closeStdin ()

Signals

  • void readyReadStdout ()
  • void readyReadStderr ()
  • void processExited ()
  • void wroteToStdin ()
  • void launchFinished ()

Detailed Description

The QProcess class is used to start external programs and to communicate with them.

You can write to the started program's standard input, and can read the program's standard output and standard error. You can pass command line arguments to the program either in the constructor or with setArguments() or addArgument(). The program's working directory can be set with setWorkingDirectory(). If you need to set up environment variables pass them to the start() or launch() functions (see below). The processExited() signal is emitted if the program exits. The program's exit status is available from exitStatus(), although you could simply call normalExit() to see if the program terminated normally.

There are two different ways to start a process. If you just want to run a program, optionally passing data to its standard input at the beginning, use one of the launch() functions. If you want full control of the program's standard input (especially if you don't know all the data you want to send to standard input at the beginning), use the start() function.

If you use start() you can write to the program's standard input using writeToStdin() and you can close the standard input with closeStdin(). The wroteToStdin() signal is emitted if the data sent to standard input has been written. You can read from the program's standard output using readStdout() or readLineStdout(). These functions return an empty QByteArray if there is no data to read. The readyReadStdout() signal is emitted when there is data available to be read from standard output. Standard error has a set of functions that correspond to the standard output functions, i.e. readStderr(), readLineStderr() and readyReadStderr().

If you use one of the launch() functions the data you pass will be sent to the program's standard input which will be closed once all the data has been written. You should not use writeToStdin() or closeStdin() if you use launch(). If you need to send data to the program's standard input after it has started running use start() instead of launch().

Both start() and launch() can accept a string list of strings each of which has the format, key=value, where the keys are the names of environment variables.

You can test to see if a program is running with isRunning(). The program's process identifier is available from processIdentifier(). If you want to terminate a running program use tryTerminate(), but note that the program may ignore this. If you really want to terminate the program, without it having any chance to clean up, you can use kill().

As an example, suppose we want to start the uic command (a Qt command line tool used with Qt Designer) and perform some operations on the output (the uic outputs the code it generates to standard output by default). Suppose further that we want to run the program on the file "small_dialog.ui" with the command line options "-tr i18n". On the command line we would write:

    uic -tr i18n small_dialog.ui

A code snippet for this with the QProcess class might look like this:

    UicManager::UicManager()
    {

        proc = new QProcess( this );

        proc->addArgument( "uic" );
        proc->addArgument( "-tr" );
        proc->addArgument( "i18n" );
        proc->addArgument( "small_dialog.ui" );

        connect( proc, SIGNAL(readyReadStdout()),
                this, SLOT(readFromStdout()) );

        if ( !proc->start() ) {
            // error handling

        }
    }

    void UicManager::readFromStdout()
    {
        // Read and process the data.
        // Bear in mind that the data might be output in chunks.

    }

Although you may need quotes for a file named on the command line (e.g. if it contains spaces) you shouldn't use extra quotes for arguments passed to addArgument() or setArguments().

The readyReadStdout() signal is emitted when there is new data on standard output. This happens asynchronously: you don't know if more data will arrive later. In the above example you could connect the processExited() signal to the slot UicManager::readFromStdout() instead. If you do so, you will be certain that all the data is available when the slot is called. On the other hand, you must wait until the process has finished before doing any processing.

See also QSocket, Input/Output and Networking and Miscellaneous Classes.

Member Type Documentation

QProcess::Communication

This enum type defines the communication channels connected to the process.

  • QProcess::Stdin - Data can be written to the process's standard input.
  • QProcess::Stdout - Data can be read from the process's standard output.
  • QProcess::Stderr - Data can be read from the process's standard error.
  • QProcess::DupStderr - Both the process's standard error output and its standard output are written to its standard output. (Like Unix's dup2().) This means that nothing is sent to the standard error output. This is especially useful if your application requires that the output on standard output and on standard error must be read in the same order that they are produced. This is a flag, so to activate it you must pass Stdout|Stderr|DupStderr, or Stdin|Stdout|Stderr|DupStderr if you want to provide input, to the setCommunication() call.

See also setCommunication() and communication().

Member Function Documentation

QProcess::QProcess ( QObject * parent = 0, const char * name = 0 )

Constructs a QProcess object. The parent and name parameters are passed to the QObject constructor.

See also setArguments(), addArgument() and start().

QProcess::QProcess ( const QString & arg0, QObject * parent = 0, const char * name = 0 )

Constructs a QProcess with arg0 as the command to be executed. The parent and name parameters are passed to the QObject constructor.

The process is not started. You must call start() or launch() to start the process.

See also setArguments(), addArgument() and start().

QProcess::QProcess ( const QStringList & args, QObject * parent = 0, const char * name = 0 )

Constructs a QProcess with args as the arguments of the process. The first element in the list is the command to be executed. The other elements in the list are the arguments to this command. The parent and name parameters are passed to the QObject constructor.

The process is not started. You must call start() or launch() to start the process.

See also setArguments(), addArgument() and start().

QProcess::~QProcess ()

Destroys the instance.

If the process is running, it is not terminated! The standard input, standard output and standard error of the process are closed.

You can connect the destroyed() signal to the kill() slot, if you want the process to be terminated automatically when the instance is destroyed.

See also tryTerminate() and kill().

void QProcess::addArgument ( const QString & arg ) [virtual]

Adds arg to the end of the list of arguments.

The first element in the list of arguments is the command to be executed; the following elements are the command's arguments.

See also arguments() and setArguments().

Example: process/process.cpp.

QStringList QProcess::arguments () const

Returns the list of arguments that are set for the process. Arguments can be specified with the constructor or with the functions setArguments() and addArgument().

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myProcess.arguments();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also setArguments() and addArgument().

bool QProcess::canReadLineStderr () const

Returns TRUE if it's possible to read an entire line of text from standard error at this time; otherwise returns FALSE.

See also readLineStderr() and canReadLineStdout().

bool QProcess::canReadLineStdout () const

Returns TRUE if it's possible to read an entire line of text from standard output at this time; otherwise returns FALSE.

See also readLineStdout() and canReadLineStderr().

void QProcess::clearArguments ()

Clears the list of arguments that are set for the process.

See also setArguments() and addArgument().

void QProcess::closeStdin () [virtual slot]

Closes the process's standard input.

This function also deletes any pending data that has not been written to standard input.

See also wroteToStdin().

int QProcess::communication () const

Returns the communication required with the process, i.e. some combination of the Communication flags.

See also setCommunication().

int QProcess::exitStatus () const

Returns the exit status of the process or 0 if the process is still running. This function returns immediately and does not wait until the process is finished.

If normalExit() is FALSE (e.g. if the program was killed or crashed), this function returns 0, so you should check the return value of normalExit() before relying on this value.

See also normalExit() and processExited().

bool QProcess::isRunning () const

Returns TRUE if the process is running; otherwise returns FALSE.

See also normalExit(), exitStatus() and processExited().

void QProcess::kill () const [slot]

Terminates the process. This is not a safe way to end a process since the process will not be able to do any cleanup. tryTerminate() is safer, but processes can ignore a tryTerminate().

The nice way to end a process and to be sure that it is finished, is to do something like this:

        process->tryTerminate();
        QTimer::singleShot( 5000, process, SLOT( kill() ) );

This tries to terminate the process the nice way. If the process is still running after 5 seconds, it terminates the process the hard way. The timeout should be chosen depending on the time the process needs to do all its cleanup: use a higher value if the process is likely to do a lot of computation or I/O on cleanup.

The slot returns immediately: it does not wait until the process has finished. When the process terminates, the processExited() signal is emitted.

See also tryTerminate() and processExited().

bool QProcess::launch ( const QByteArray & buf, QStringList * env = 0 ) [virtual]

Runs the process and writes the data buf to the process's standard input. If all the data is written to standard input, standard input is closed. The command is searched for in the path for executable programs; you can also use an absolute path in the command itself.

If env is null, then the process is started with the same environment as the starting process. If env is non-null, then the values in the string list are interpreted as environment setttings of the form key=value and the process is started with these environment settings. For convenience, there is a small exception to this rule under Unix: if env does not contain any settings for the environment variable LD_LIBRARY_PATH, then this variable is inherited from the starting process.

Returns TRUE if the process could be started; otherwise returns FALSE.

Note that you should not use the slots writeToStdin() and closeStdin() on processes started with launch(), since the result is not well-defined. If you need these slots, use start() instead.

The process may or may not read the buf data sent to its standard input.

You can call this function even when a process that was started with this instance is still running. Be aware that if you do this the standard input of the process that was launched first will be closed, with any pending data being deleted, and the process will be left to run out of your control. Similarly, if the process could not be started the standard input will be closed and the pending data deleted. (On operating systems that have zombie processes, Qt will also wait() on the old process.)

The object emits the signal launchFinished() when this function call is finished. If the start was successful, this signal is emitted after all the data has been written to standard input. If the start failed, then this signal is emitted immediately.

See also start() and launchFinished().

bool QProcess::launch ( const QString & buf, QStringList * env = 0 ) [virtual]

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

The data buf is written to standard input with writeToStdin() using the QString::local8Bit() representation of the strings.

void QProcess::launchFinished () [signal]

This signal is emitted when the process was started with launch(). If the start was successful, this signal is emitted after all the data has been written to standard input. If the start failed, then this signal is emitted immediately.

This signal is especially useful if you want to know when you can safely delete the QProcess object when you are not intrested in reading from standard output or standard error.

See also launch() and QObject::deleteLater().

bool QProcess::normalExit () const

Returns TRUE if the process has exited normally; otherwise returns FALSE. This implies that this function returns FALSE if the process is still running.

See also isRunning(), exitStatus() and processExited().

void QProcess::processExited () [signal]

This signal is emitted when the process has exited.

See also isRunning(), normalExit(), exitStatus(), start() and launch().

Example: process/process.cpp.

PID QProcess::processIdentifier ()

Returns platform dependent information about the process. This can be used together with platform specific system calls.

Under Unix the return value is the PID of the process, or -1 if no process is belongs to this object.

Under Windows it is a pointer to the PROCESS_INFORMATION struct, or 0 if no process is belongs to this object.

Use of this function's return value is likely to be non-portable.

QString QProcess::readLineStderr () [virtual]

Reads a line of text from standard error, excluding any trailing newline or carriage return characters and returns it. Returns QString::null if canReadLineStderr() returns FALSE.

See also canReadLineStderr(), readyReadStderr(), readStderr() and readLineStdout().

QString QProcess::readLineStdout () [virtual]

Reads a line of text from standard output, excluding any trailing newline or carriage return characters, and returns it. Returns QString::null if canReadLineStdout() returns FALSE.

See also canReadLineStdout(), readyReadStdout(), readStdout() and readLineStderr().

QByteArray QProcess::readStderr () [virtual]

Reads the data that the process has written to standard error. When new data is written to standard error, the class emits the signal readyReadStderr().

If there is no data to read, this function returns a QByteArray of size 0: it does not wait until there is something to read.

See also readyReadStderr(), readLineStderr(), readStdout() and writeToStdin().

QByteArray QProcess::readStdout () [virtual]

Reads the data that the process has written to standard output. When new data is written to standard output, the class emits the signal readyReadStdout().

If there is no data to read, this function returns a QByteArray of size 0: it does not wait until there is something to read.

See also readyReadStdout(), readLineStdout(), readStderr() and writeToStdin().

Example: process/process.cpp.

void QProcess::readyReadStderr () [signal]

This signal is emitted when the process has written data to standard error. You can read the data with readStderr().

Note that this signal is only emitted when there is new data and not when there is old, but unread data. In the slot connected to this signal, you should always read everything that is available at that moment to make sure that you don't lose any data.

See also readStderr(), readLineStderr() and readyReadStdout().

void QProcess::readyReadStdout () [signal]

This signal is emitted when the process has written data to standard output. You can read the data with readStdout().

Note that this signal is only emitted when there is new data and not when there is old, but unread data. In the slot connected to this signal, you should always read everything that is available at that moment to make sure that you don't lose any data.

See also readStdout(), readLineStdout() and readyReadStderr().

Example: process/process.cpp.

void QProcess::setArguments ( const QStringList & args ) [virtual]

Sets args as the arguments for the process. The first element in the list is the command to be executed. The other elements in the list are the arguments to the command. Any previous arguments are deleted.

QProcess does perform argument substitutions; for example, if you specify "*" or "$DISPLAY", these values are passed to the process literally. If you want to have the same behavior as the shell provides, you must do the substitutions yourself; i.e. instead of specifying a "*" you must specify the list of all the filenames in the current directory, and instead of "$DISPLAY" you must specify the value of the environment variable DISPLAY.

Note for Windows users. The standard Windows shells, e.g. command.com and cmd.exe, do not perform file globbing, i.e. they do not convert a "*" on the command line into a list of files in the current directory. For this reason most Windows applications implement their own file globbing, and as a result of this, specifying an argument of "*" for a Windows application is likely to result in the application performing a file glob and ending up with a list of filenames.

See also arguments() and addArgument().

void QProcess::setCommunication ( int commFlags )

Sets commFlags as the communication required with the process.

commFlags is a bitwise OR of the flags defined by the Communication enum.

The default is Stdin|Stdout|Stderr.

See also communication().

void QProcess::setWorkingDirectory ( const QDir & dir ) [virtual]

Sets dir as the working directory for processes. This does not affect running processes; only processes that are started afterwards are affected.

Setting the working directory is especially useful for processes that try to access files with relative paths.

See also workingDirectory() and start().

bool QProcess::start ( QStringList * env = 0 ) [virtual]

Tries to run a process for the command and arguments that were specified with setArguments(), addArgument() or that were specified in the constructor. The command is searched for in the path for executable programs; you can also use an absolute path in the command itself.

If env is null, then the process is started with the same environment as the starting process. If env is non-null, then the values in the stringlist are interpreted as environment setttings of the form key=value and the process is started in these environment settings. For convenience, there is a small exception to this rule: under Unix, if env does not contain any settings for the environment variable LD_LIBRARY_PATH, then this variable is inherited from the starting process; under Windows the same applies for the environment variable PATH.

Returns TRUE if the process could be started; otherwise returns FALSE.

You can write data to the process's standard input with writeToStdin(). You can close standard input with closeStdin() and you can terminate the process with tryTerminate(), or with kill().

You can call this function even if you've used this instance to create a another process which is still running. In such cases, QProcess closes the old process's standard input and deletes pending data, i.e., you lose all control over the old process, but the old process is not terminated. This applies also if the process could not be started. (On operating systems that have zombie processes, Qt will also wait() on the old process.)

See also launch() and closeStdin().

Example: process/process.cpp.

void QProcess::tryTerminate () const [slot]

Asks the process to terminate. Processes can ignore this if they wish. If you want to be certain that the process really terminates, you can use kill() instead.

The slot returns immediately: it does not wait until the process has finished. When the process terminates, the processExited() signal is emitted.

See also kill() and processExited().

QDir QProcess::workingDirectory () const

Returns the working directory that was set with setWorkingDirectory(), or the current directory if none has been explicitly set.

See also setWorkingDirectory() and QDir::current().

void QProcess::writeToStdin ( const QByteArray & buf ) [virtual slot]

Writes the data buf to the process's standard input. The process may or may not read this data.

This function returns immediately; the QProcess class might write the data at a later point (you must enter the event loop for this to occur). When all the data is written to the process, the signal wroteToStdin() is emitted. This does not mean that the process actually read the data, since this class only detects when it was able to write the data to the operating system.

See also wroteToStdin(), closeStdin(), readStdout() and readStderr().

void QProcess::writeToStdin ( const QString & buf ) [virtual slot]

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

The string buf is handled as text using the QString::local8Bit() representation.

void QProcess::wroteToStdin () [signal]

This signal is emitted if the data sent to standard input (via writeToStdin()) was actually written to the process. This does not imply that the process really read the data, since this class only detects when it was able to write the data to the operating system. But it is now safe to close standard input without losing pending data.

See also writeToStdin() and closeStdin().

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


QProcess Examples

The following example programs show how to use the QProcess class.

Starting processes with IO redirection

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


qprocess.h Include File

qprocess.h

This is the verbatim text of the qprocess.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qprocess.h   3.0.5   edited Oct 12 2001 $
**
** Implementation of QProcess class
**
** Created : 20000905
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPROCESS_H
#define QPROCESS_H

#ifndef QT_H
#include "qobject.h"
#include "qstringlist.h"
#include "qdir.h"
#endif // QT_H

#ifndef QT_NO_PROCESS

class QProcessPrivate;

class Q_EXPORT QProcess : public QObject
{
    Q_OBJECT
public:
    QProcess( QObject *parent=0, const char *name=0 );
    QProcess( const QString& arg0, QObject *parent=0, const char *name=0 );
    QProcess( const QStringList& args, QObject *parent=0, const char *name=0 );
    ~QProcess();

    // set and get the arguments and working directory
    QStringList arguments() const;
    void clearArguments();
    virtual void setArguments( const QStringList& args );
    virtual void addArgument( const QString& arg );
#ifndef QT_NO_DIR
    QDir workingDirectory() const;
    virtual void setWorkingDirectory( const QDir& dir );
#endif

    // set and get the comms wanted
    enum Communication { Stdin=0x01, Stdout=0x02, Stderr=0x04, DupStderr=0x08 };
    void setCommunication( int c );
    int communication() const;

    // start the execution
    virtual bool start( QStringList *env=0 );
    virtual bool launch( const QString& buf, QStringList *env=0  );
    virtual bool launch( const QByteArray& buf, QStringList *env=0  );

    // inquire the status
    bool isRunning() const;
    bool normalExit() const;
    int exitStatus() const;

    // reading
    virtual QByteArray readStdout();
    virtual QByteArray readStderr();
    bool canReadLineStdout() const;
    bool canReadLineStderr() const;
    virtual QString readLineStdout();
    virtual QString readLineStderr();

    // get platform dependent process information
#if defined(Q_OS_WIN32)
    typedef void* PID;
#else
    typedef Q_LONG PID;
#endif
    PID processIdentifier();

    void flushStdin();

signals:
    void readyReadStdout();
    void readyReadStderr();
    void processExited();
    void wroteToStdin();
    void launchFinished();

public slots:
    // end the execution
    void tryTerminate() const;
    void kill() const;

    // input
    virtual void writeToStdin( const QByteArray& buf );
    virtual void writeToStdin( const QString& buf );
    virtual void closeStdin();

protected: // ### or private?
    void connectNotify( const char * signal );
    void disconnectNotify( const char * signal );
private:
    void setIoRedirection( bool value );
    void setNotifyOnExit( bool value );
    void setWroteStdinConnected( bool value );

    void init();
    void reset();
#if defined(Q_OS_WIN32)
    uint readStddev( HANDLE dev, char *buf, uint bytes );
#endif
    bool scanNewline( bool stdOut, QByteArray *store );

    QByteArray* bufStdout();
    QByteArray* bufStderr();
    void consumeBufStdout( int consume );
    void consumeBufStderr( int consume );

private slots:
    void socketRead( int fd );
    void socketWrite( int fd );
    void timeout();
    void closeStdinLaunch();

private:
    QProcessPrivate *d;
#ifndef QT_NO_DIR
    QDir        workingDir;
#endif
    QStringList _arguments;

    int  exitStat; // exit status
    bool exitNormal; // normal exit?
    bool ioRedirection; // automatically set be (dis)connectNotify
    bool notifyOnExit; // automatically set be (dis)connectNotify
    bool wroteToStdinConnected; // automatically set be (dis)connectNotify

    bool readStdoutCalled;
    bool readStderrCalled;
    int comms;

    friend class QProcessPrivate;
#if defined(Q_OS_UNIX)
    friend class QProcessManager;
    friend class QProc;
#endif
};

#endif // QT_NO_PROCESS

#endif // QPROCESS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QProcess Member List

Complete Member List for QProcess

This is the complete list of member functions for QProcess, including inherited members.

  • QProcess()
  • ~QProcess()
  • addArgument()
  • arguments()
  • blockSignals()
  • canReadLineStderr()
  • canReadLineStdout()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clearArguments()
  • closeStdin()
  • communication()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • exitStatus()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isRunning()
  • isWidgetType()
  • kill()
  • killTimer()
  • killTimers()
  • launch()
  • launchFinished()
  • metaObject()
  • name()
  • normalExit()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • processExited()
  • processIdentifier()
  • property()
  • queryList()
  • readLineStderr()
  • readLineStdout()
  • readStderr()
  • readStdout()
  • readyReadStderr()
  • readyReadStdout()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setArguments()
  • setCommunication()
  • setName()
  • setProperty()
  • setWorkingDirectory()
  • signalsBlocked()
  • start()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • tryTerminate()
  • workingDirectory()
  • writeToStdin()
  • wroteToStdin()


QProgressBar Class

QProgressBar Class Reference

The QProgressBar widget provides a horizontal progress bar. More...

#include <qprogressbar.h>

Inherits QFrame.

List of all member functions.

Public Members

  • QProgressBar ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • QProgressBar ( int totalSteps, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • int totalSteps () const
  • int progress () const
  • const QString & progressString () const
  • void setCenterIndicator ( bool on )
  • bool centerIndicator () const
  • void setIndicatorFollowsStyle ( bool )
  • bool indicatorFollowsStyle () const
  • bool percentageVisible () const
  • void setPercentageVisible ( bool )

Public Slots

  • void reset ()
  • virtual void setTotalSteps ( int totalSteps )
  • virtual void setProgress ( int progress )

Properties

  • bool centerIndicator - whether the indicator string should be centered
  • bool indicatorFollowsStyle - whether the display of the indicator string should follow the GUI style
  • bool percentageVisible - whether the current progress value is displayed
  • int progress - the current amount of progress
  • QString progressString - the current amount of progress as a string (read only)
  • int totalSteps - the total number of steps

Protected Members

  • virtual bool setIndicator ( QString & indicator, int progress, int totalSteps )

Detailed Description

The QProgressBar widget provides a horizontal progress bar.

A progress bar is used to give the user an indication of the progress of an operation and to reassure them that the application is still running.

The progress bar uses the concept of steps; you give it the total number of steps and the number of steps completed so far and it will display the percentage of steps that have been completed. You can specify the total number of steps in the constructor or later with setTotalSteps(). The current number of steps is set with setProgress(). The progress bar can be rewound to the beginning with reset().

See also QProgressDialog, GUI Design Handbook: Progress Indicator and Advanced Widgets.

See also QProgressDialog, GUI Design Handbook: Progress Indicator and Advanced Widgets.

Member Function Documentation

QProgressBar::QProgressBar ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a progress bar.

The total number of steps is set to 100 by default.

The parent, name and widget flags, f, are passed on to the QFrame::QFrame() constructor.

See also totalSteps.

QProgressBar::QProgressBar ( int totalSteps, QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a progress bar.

The totalSteps is the total number of steps that need to be completed for the operation which this progress bar represents. For example, if the operation is to examine 50 files, this value would be 50. Before examining the first file, call setProgress(0); call setProgress(50) after examining the last file .

The parent, name and widget flags, f, are passed to the QFrame::QFrame() constructor.

See also totalSteps and progress.

bool QProgressBar::centerIndicator () const

Returns TRUE if the indicator string should be centered; otherwise returns FALSE. See the "centerIndicator" property for details.

bool QProgressBar::indicatorFollowsStyle () const

Returns TRUE if the display of the indicator string should follow the GUI style; otherwise returns FALSE. See the "indicatorFollowsStyle" property for details.

bool QProgressBar::percentageVisible () const

Returns TRUE if the current progress value is displayed; otherwise returns FALSE. See the "percentageVisible" property for details.

int QProgressBar::progress () const

Returns the current amount of progress. See the "progress" property for details.

const QString & QProgressBar::progressString () const

Returns the current amount of progress as a string. See the "progressString" property for details.

void QProgressBar::reset () [slot]

Reset the progress bar. The progress bar "rewinds" and shows no progress.

Examples: fileiconview/mainwindow.cpp, network/ftpclient/ftpmainwindow.cpp and progressbar/progressbar.cpp.

void QProgressBar::setCenterIndicator ( bool on )

Sets whether the indicator string should be centered to on. See the "centerIndicator" property for details.

bool QProgressBar::setIndicator ( QString & indicator, int progress, int totalSteps ) [virtual protected]

This method is called to generate the text displayed in the center (or in some styles, to the left) of the progress bar.

The progress may be negative, indicating that the progress bar is in the "reset" state before any progress is set.

The default implementation is the percentage of completion or blank in the reset state. The percentage is calculated based on the progress and totalSteps. You can set the indicator text if you wish.

To allow efficient repainting of the progress bar, this method should return FALSE if the string is unchanged from the last call to this function.

void QProgressBar::setIndicatorFollowsStyle ( bool )

Sets whether the display of the indicator string should follow the GUI style. See the "indicatorFollowsStyle" property for details.

void QProgressBar::setPercentageVisible ( bool )

Sets whether the current progress value is displayed. See the "percentageVisible" property for details.

void QProgressBar::setProgress ( int progress ) [virtual slot]

Sets the current amount of progress to progress. See the "progress" property for details.

void QProgressBar::setTotalSteps ( int totalSteps ) [virtual slot]

Sets the total number of steps to totalSteps. See the "totalSteps" property for details.

int QProgressBar::totalSteps () const

Returns the total number of steps. See the "totalSteps" property for details.

Property Documentation

bool centerIndicator

This property holds whether the indicator string should be centered.

Changing this property sets QProgressBar::indicatorFollowsStyle to FALSE. The default is TRUE.

Set this property's value with setCenterIndicator() and get this property's value with centerIndicator().

bool indicatorFollowsStyle

This property holds whether the display of the indicator string should follow the GUI style.

The default is TRUE.

See also centerIndicator.

Set this property's value with setIndicatorFollowsStyle() and get this property's value with indicatorFollowsStyle().

bool percentageVisible

This property holds whether the current progress value is displayed.

The default is TRUE.

See also centerIndicator and indicatorFollowsStyle.

Set this property's value with setPercentageVisible() and get this property's value with percentageVisible().

int progress

This property holds the current amount of progress.

This property is -1 if the progress counting has not started.

Set this property's value with setProgress() and get this property's value with progress().

QString progressString

This property holds the current amount of progress as a string.

This property is QString::null if the progress counting has not started.

Get this property's value with progressString().

int totalSteps

This property holds the total number of steps.

If totalSteps is null, the progress bar will display a busy indicator.

See also

Set this property's value with setTotalSteps() and get this property's value with totalSteps().

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


qprogressbar.h Include File

qprogressbar.h

This is the verbatim text of the qprogressbar.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qprogressbar.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QProgressBar class
**
** Created : 970520
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPROGRESSBAR_H
#define QPROGRESSBAR_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_PROGRESSBAR

class QProgressBarPrivate;

class Q_EXPORT QProgressBar : public QFrame
{
    Q_OBJECT
    Q_PROPERTY( int totalSteps READ totalSteps WRITE setTotalSteps )
    Q_PROPERTY( int progress READ progress WRITE setProgress )
    Q_PROPERTY( QString progressString READ progressString )
    Q_PROPERTY( bool centerIndicator READ centerIndicator WRITE setCenterIndicator )
    Q_PROPERTY( bool indicatorFollowsStyle READ indicatorFollowsStyle WRITE setIndicatorFollowsStyle )
    Q_PROPERTY( bool percentageVisible READ percentageVisible WRITE setPercentageVisible )

public:
    QProgressBar( QWidget* parent=0, const char* name=0, WFlags f=0 );
    QProgressBar( int totalSteps, QWidget* parent=0, const char* name=0, WFlags f=0 );

    int		totalSteps() const;
    int		progress()   const;
    const QString &progressString() const;

    QSize	sizeHint() const;
    QSize	minimumSizeHint() const;

    void	setCenterIndicator( bool on );
    bool	centerIndicator() const;

    void        setIndicatorFollowsStyle( bool );
    bool	indicatorFollowsStyle() const;

    bool	percentageVisible() const;
    void	setPercentageVisible( bool );

    void	show();

public slots:
    void	reset();
    virtual void setTotalSteps( int totalSteps );
    virtual void setProgress( int progress );

protected:
    void	drawContents( QPainter * );
    virtual bool setIndicator( QString & progress_str, int progress,
                   int totalSteps );
    void styleChange( QStyle& );

private:
    int		total_steps;
    int		progress_val;
    int		percentage;
    QString	progress_str;
    bool        center_indicator    : 1;
    bool        auto_indicator	    : 1;
    bool	percentage_visible  : 1;
    QProgressBarPrivate * d;
    void         initFrame();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QProgressBar( const QProgressBar & );
    QProgressBar &operator=( const QProgressBar & );
#endif
};

inline int QProgressBar::totalSteps() const
{
    return total_steps;
}

inline int QProgressBar::progress() const
{
    return progress_val;
}

inline const QString &QProgressBar::progressString() const
{
    return progress_str;
}

inline bool QProgressBar::centerIndicator() const
{
    return center_indicator;
}

inline bool QProgressBar::indicatorFollowsStyle() const
{
    return auto_indicator;
}

inline bool QProgressBar::percentageVisible() const
{
    return percentage_visible;
}

#endif // QT_NO_PROGRESSBAR

#endif // QPROGRESSBAR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QProgressBar Member List

Complete Member List for QProgressBar

This is the complete list of member functions for QProgressBar, including inherited members.

  • QProgressBar()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • centerIndicator()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indicatorFollowsStyle()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • percentageVisible()
  • polish()
  • pos()
  • progress()
  • progressString()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • reset()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCenterIndicator()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setIndicator()
  • setIndicatorFollowsStyle()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPercentageVisible()
  • setProgress()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTotalSteps()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • totalSteps()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QProgressDialog类

QProgressDialog类参考

QProgressDialog类提供了慢操作的进度的反馈。 详情请见……

#include <qprogressdialog.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • QProgressDialog ( QWidget * creator = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )
  • QProgressDialog ( const QString & labelText, const QString & cancelButtonText, int totalSteps, QWidget * creator = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )
  • ~QProgressDialog ()
  • void setLabel ( QLabel * label )
  • void setCancelButton ( QPushButton * cancelButton )
  • void setBar ( QProgressBar * bar )
  • bool wasCancelled () const
  • int totalSteps () const
  • int progress () const
  • virtual QSize sizeHint () const
  • QString labelText () const
  • void setAutoReset ( bool b )
  • bool autoReset () const
  • void setAutoClose ( bool b )
  • bool autoClose () const
  • int minimumDuration () const

公有槽

  • void cancel ()
  • void reset ()
  • void setTotalSteps ( int totalSteps )
  • void setProgress ( int progress )
  • void setLabelText ( const QString & )
  • void setCancelButtonText ( const QString & cancelButtonText )
  • void setMinimumDuration ( int ms )

信号

  • void cancelled ()

属性

  • bool autoClose - 通过reset()对话框是否隐藏
  • bool autoReset - 一旦progress()等于totalSteps()，进度对话框是否调用reset()
  • QString labelText - 标签的文本
  • int minimumDuration - 进度就应该在对话框打开之前运行的时间
  • int progress - 进度当前的进度
  • int totalSteps - 步数的总量
  • bool wasCancelled - 对话框是否被取消 （只读）

保护槽

  • void forceShow ()

详细描述

QProgressDialog类提供了慢操作的进度的反馈。

进度对话框用于给用户这个操作还要有多长时间的指示，并且证明这个应用程序还没有冻结。它也给用于一个中止这个操作运行的机会。

进度对话框的一个常见问题是很难知道什么时候使用它们，操作在不同的硬件会占用不同的时间。QProgessDialog提供了对这个问题的解决方案：它估计操作将占用的时间（基于没步的时间），并且如果它超过minimumDuration()（默认为4秒）才显示自己。

使用setTotalSteps()（或者在构造函数中）设置操作中的“步”数并且调用setProgress()作为操作进度。步值的选择是任意的。它可以是复制的文件数，接收的字节数，在你的算法的主循环中的反复次数，或者一些其它的适合单元。进度从0开始，并且当你把totalSteps()作为参数调用setProgress()，这个进度对话框会显示这个操作已经完成。

对话框会在操作结束的时候自动重置并且隐藏自己。使用setAutoReset()和setAutoClose()可以改变这个行为。

这里有使用QProgressDialog的两种方法：模式和非模式。

对于程序员，使用模式QProgressDialog是更简单的，但是你必须调用qApp->processEvents()来保持事件循环的运行来确保应用程序没有冻结。在循环中执行这个操作，在间隔中调用setProgress()，并且检查wasCancelled()的取消。例如：

QProgressDialog progress( "Copying files...", "Abort Copy", numFiles,
                          this, "progress", TRUE );
for ( int i = 0; i < numFiles; i++ ) {
    progress.setProgress( i );
    qApp->processEvents();

    if ( progress.wasCancelled() )
        break;
    //……复制文件
}
progress.setProgress( numFiles );

非模式进度对话框适合发生在后台的操作，用户还可以和应用程序进行交互。这样的操作通常是基于QTimer（或者QObject::timerEvent()）、QSocketNotifier或QUrlOperator，或者在一个独立的进度中执行。你的主窗口的状态条中的QProgressBar常常可以做为模式进度对话框的替代。

你需要拥有一个正在运行的时间循环，把cancelled()信号和停止这个操作的槽连接起来，并且在间隔中调用setProgress()。例如：

Operation::Operation( QObject *parent = 0 )
    : QObject( parent ), steps( 0 )
{
    pd = new QProgressDialog( "Operation in progress.", "Cancel", 100 );
    connect( pd, SIGNAL(cancelled()), this, SLOT(cancel()) );
    t = new QTimer( this );
    connect( t, SIGNAL(timeout()), this, SLOT(perform()) );
    t->start( 0 );
}

void Operation::perform()
{
    pd->setProgress( steps );
    //……执行操作的一个半分比
    steps++;
    if ( steps > pd->totalSteps() )
        t->stop();
}

void Operation::cancel()
{
    t->stop();
    //……清除
}

你可以通过使用setLabel()、setBar()和setCancelButton()用自定制的窗口部件来替换子窗口部件来定制这两种进度对话框。

也可以参考QDialog、QProgressBar、图形用户界面设计手册：进度指示器和Dialog Classes。

成员函数文档

QProgressDialog::QProgressDialog ( QWidget * creator = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )

构造一个进度对话框。

默认设置：

  • 标签文本为空。
  • 取消按钮文本是（被翻译的）“Cancel”。
  • 步数的总量是100。

creator窗口部件的顶级父对象变为这个对话框的父对象。name、modal和窗口部件标记f被传递给QDialog::QDialog()的构造函数。如果modal为假（默认），你必须有一个正在进行的事件循环来重新绘制这个对话框的变化。如果modal为真，这个对话框确保当需要的时候事件会被处理。

也可以参考labelText、setLabel()、setCancelButtonText()、setCancelButton()和totalSteps。

QProgressDialog::QProgressDialog ( const QString & labelText, const QString & cancelButtonText, int totalSteps, QWidget * creator = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )

构造一个进度对话框。

labelText是用于提行用户什么正在进行的文本。

cancelButtonText是显示在取消按钮上的文本，或者如果没有取消按钮被显示就为0。

totalSteps是这个进度对话框显示进度的操作的总步数。例如，如果这个操作检测50个文件，这个值就应该为50。在检测第一个文件之前，调用setProgress(0)。每一个问卷被处理的时候，调用setProgress(1)、setProgress(2)等等，在检测完最后一个文件之后调用setProgress(50)。

name、modal和窗口部件标记f被传递给QDialog::QDialog()的构造函数。如果modal为假（默认），你必须有一个正在进行的事件循环来重新绘制这个对话框的变化。如果modal为真，这个对话框确保当需要的时候事件会被处理。

creator参数是用来做为这个对话框的父对象的窗口部件。如果creator不是一个顶级窗口部件，传递给QDialog构造函数的这个参数将为0。

也可以参考labelText、setLabel()、setCancelButtonText()、setCancelButton()和totalSteps。

QProgressDialog::~QProgressDialog ()

销毁这个进度对话框。

bool QProgressDialog::autoClose () const

如果通过reset()对话框是隐藏的，返回真，否则返回假。详细情况请参考“autoClose”属性。

bool QProgressDialog::autoReset () const

如果一旦progress()等于totalSteps()，进度对话框调用reset()，返回真，否则返回假。详细情况请参考“autoReset”属性。

void QProgressDialog::cancel () [槽]

重置这个进度对话框。知道这个进度对话框被重置了，wasCancelled()变为真。这个进度对话框变隐藏了。

void QProgressDialog::cancelled () [信号]

当取消按钮被点击时，这个信号被发射。它默认被连接到cancel()槽。

也可以参考wasCancelled。

实例：progress/progress.cpp。

void QProgressDialog::forceShow () [保护 槽]

如果在算法已经开始并且minimumDuration毫秒数已经过去之后它还被隐藏，显示这个对话框。

也可以参考minimumDuration。

QString QProgressDialog::labelText () const

返回标签的文本。详细情况请参考“labelText”属性。

int QProgressDialog::minimumDuration () const

返回进度就应该在对话框打开之前运行的时间。详细情况请参考“minimumDuration”属性。

int QProgressDialog::progress () const

返回进度当前的进度。详细情况请参考“progress”属性。

void QProgressDialog::reset () [槽]

重置这个进度对话框。如果autoClose()为真，进度对话框变为隐藏。

也可以参考autoClose和autoReset。

void QProgressDialog::setAutoClose ( bool b )

设置通过reset()对话框是否隐藏为b。详细情况请参考“autoClose”属性。

void QProgressDialog::setAutoReset ( bool b )

设置一旦progress()等于totalSteps()，进度对话框是否调用reset()为b。详细情况请参考“autoReset”属性。

void QProgressDialog::setBar ( QProgressBar * bar )

设置进度条窗口部件为bar。进度对话框会重新定义大小来适合它。进度对话框会得到进度条bar，bar当需要的时候会被删除，所以不要在使用在栈中分配的进度条。

void QProgressDialog::setCancelButton ( QPushButton * cancelButton )

设置取消按钮为推动按钮cancelButton。进度对话框会得到这个按钮，它当需要的时候会被删除，所以不要在使用在栈中分配的对象，也就是使用new()来创建这个按钮。

也可以参考setCancelButtonText()。

void QProgressDialog::setCancelButtonText ( const QString & cancelButtonText ) [槽]

设置取消按钮的文本为cancelButtonText。

也可以参考setCancelButton()。

void QProgressDialog::setLabel ( QLabel * label )

设置标签为label。进度对话框会重新定义大小来适合它。进度对话框会得到这个标签，它当需要的时候会被删除，所以不要在使用在栈中分配的对象，也就是使用new()来创建这个标签。

也可以参考labelText。

实例：progress/progress.cpp。

void QProgressDialog::setLabelText ( const QString & ) [槽]

设置标签的文本。详细情况请参考“labelText”属性。

void QProgressDialog::setMinimumDuration ( int ms ) [槽]

设置进度就应该在对话框打开之前运行的时间为ms。详细情况请参考“minimumDuration”属性。

void QProgressDialog::setProgress ( int progress ) [槽]

设置进度当前的进度为progress。详细情况请参考“progress”属性。

void QProgressDialog::setTotalSteps ( int totalSteps ) [槽]

设置步数的总量为totalSteps。详细情况请参考“totalSteps”属性。

QSize QProgressDialog::sizeHint () const [虚]

返回适合这个进度对话框内容的大小。如果需要进度对话框重新定义自己的大小，所以你应该不需要自己调用这个。

int QProgressDialog::totalSteps () const

返回步数的总量。详细情况请参考“totalSteps”属性。

bool QProgressDialog::wasCancelled () const

如果对话框被取消，返回真，否则返回假。详细情况请参考“wasCancelled”属性。

属性文档

bool autoClose

这个属性保存的是通过reset()对话框是否隐藏。

默认为真。

也可以参考autoReset。

通过setAutoClose()设置属性值并且通过autoClose()来获得属性值。

bool autoReset

这个属性保存的是一旦progress()等于totalSteps()，进度对话框是否调用reset()。

默认为真。

也可以参考autoClose。

通过setAutoReset()设置属性值并且通过autoReset()来获得属性值。

QString labelText

这个属性保存的是标签的文本。

默认文本为QString::null。

通过setLabelText()设置属性值并且通过labelText()来获得属性值。

int minimumDuration

这个属性保存的是进度就应该在对话框打开之前运行的时间。

如果正在进行的进度任务的被期待持续时间小于这个最小持续时间，对话框将不会显示。

如果被设置为0，一旦任何进度被设置，这个对话框就一直被显示。默认为4000毫秒。

通过setMinimumDuration()设置属性值并且通过minimumDuration()来获得属性值。

int progress

这个属性保存的是进度当前的进度。

对于正如所期望的运行的进度对话框，你应该初始化设置这个属性为0并且最后把它设置为QProgressDialog::totalSteps()，你可以在这之间调用setProgress()任意次。

警告： 如果进度对话框是模式的（请参考QProgressDialog::QProgressDialog())），这个函数调用QApplication::processEvents()，所以注意这个函数不会导致不受欢迎的重新进入你的代码。例如，不要在paintEvent()中使用QProgressDialog！

也可以参考totalSteps。

通过setProgress()设置属性值并且通过progress()来获得属性值。

int totalSteps

这个属性保存的是步数的总量。

默认为0。

通过setTotalSteps()设置属性值并且通过totalSteps()来获得属性值。

bool wasCancelled

这个属性保存的是对话框是否被取消。

也可以参考progress。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qprogressdialog.h包含文件

qprogressdialog.h

这里是qprogressdialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qprogressdialog.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QProgressDialog class
**
** Created : 970520
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPROGRESSDIALOG_H
#define QPROGRESSDIALOG_H

#ifndef QT_H
#include "qsemimodal.h"
#include "qlabel.h"       // ### remove or keep for users' convenience?
#include "qprogressbar.h" // ### remove or keep for users' convenience?
#endif // QT_H

#ifndef QT_NO_PROGRESSDIALOG

class QPushButton;
class QTimer;
class QProgressDialogData;

class Q_EXPORT QProgressDialog : public QDialog
{
    Q_OBJECT
    Q_PROPERTY( bool wasCancelled READ wasCancelled )
    Q_PROPERTY( int totalSteps READ totalSteps WRITE setTotalSteps )
    Q_PROPERTY( int progress READ progress WRITE setProgress )
    Q_PROPERTY( bool autoReset READ autoReset WRITE setAutoReset )
    Q_PROPERTY( bool autoClose READ autoClose WRITE setAutoClose )
    Q_PROPERTY( int minimumDuration READ minimumDuration WRITE setMinimumDuration )
    Q_PROPERTY( QString labelText READ labelText WRITE setLabelText )

public:
    QProgressDialog( QWidget* parent=0, const char* name=0, bool modal=FALSE,
             WFlags f=0 );
    QProgressDialog( const QString& labelText, const QString &cancelButtonText,
             int totalSteps, QWidget* parent=0, const char* name=0,
             bool modal=FALSE, WFlags f=0 );
    ~QProgressDialog();

    void	setLabel( QLabel * );
    void	setCancelButton( QPushButton * );
    void	setBar( QProgressBar * );

    bool	wasCancelled() const;

    int		totalSteps() const;
    int		progress()   const;

    QSize	sizeHint() const;

    QString     labelText() const;

    void setAutoReset( bool b );
    bool autoReset() const;
    void setAutoClose( bool b );
    bool autoClose() const;

public slots:
    void	cancel();
    void	reset();
    void	setTotalSteps( int totalSteps );
    void	setProgress( int progress );
    void	setLabelText( const QString &);
    void	setCancelButtonText( const QString &);

    void	setMinimumDuration( int ms );
public:
    int		minimumDuration() const;

signals:
    void	cancelled();

protected:
    void	resizeEvent( QResizeEvent * );
    void	closeEvent( QCloseEvent * );
    void	styleChange( QStyle& );
    void	showEvent( QShowEvent *e );

protected slots:
    void	forceShow();

private:
    void	   init( QWidget *creator, const QString& lbl, const QString &canc,
             int totstps);
    void	   layout();
    QLabel	  *label()  const;
    QProgressBar  *bar()    const;
    QProgressDialogData *d;
    QTimer	  *forceTimer;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QProgressDialog( const QProgressDialog & );
    QProgressDialog &operator=( const QProgressDialog & );
#endif
};

#endif // QT_NO_PROGRESSDIALOG

#endif // QPROGRESSDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QProgressDialog成员列表

完整的QProgressDialog成员列表

这里是QProgressDialog成员函数的完整列表，包括继承的成员。

  • QProgressDialog()
  • ~QProgressDialog()
  • accept()
  • acceptDrops()
  • adjustSize()
  • autoClose()
  • autoMask()
  • autoReset()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • cancel()
  • cancelled()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • forceShow()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • labelText()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumDuration()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • progress()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • reset()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoClose()
  • setAutoMask()
  • setAutoReset()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBar()
  • setBaseSize()
  • setCancelButton()
  • setCancelButtonText()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLabel()
  • setLabelText()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumDuration()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProgress()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTotalSteps()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • totalSteps()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wasCancelled()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrCollection类

QPtrCollection类参考

QPtrCollection类是绝大多数基于指针的Qt集合的基类。 详情请见……

#include <qptrcollection.h>

Inherited by QAsciiDict, QCache, QDict, QIntDict, QPtrList, QPtrDict and QPtrVector.

所有成员函数的列表。

公有成员

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )
  • virtual uint count () const = 0
  • virtual void clear () = 0
  • typedef void * Item

保护成员

  • QPtrCollection ()
  • QPtrCollection ( const QPtrCollection & source )
  • virtual ~QPtrCollection ()
  • virtual Item newItem ( Item d )
  • virtual void deleteItem ( Item d ) = 0

详细描述

QPtrCollection类是绝大多数基于指针的Qt集合的基类。

QPtrCollection类是Qt集合类 QDict、QPtrList等等的基类。Qt也包括基于值的集合，比如QValueList、QMap等等。

QPtrCollection仅仅知道集合内对象的数量和删除策略（请参考setAutoDelete()）。

集合的实现是使用Item（一般集合项）类型，它是一个void*。创建实际集合的模板类抛出Item为所需的类型。

也可以参考集合类和非GUI类。

成员类型文档

QPtrCollection::Item

这个类型是QPtrCollection中一般的“项”。

成员函数文档

QPtrCollection::QPtrCollection () [保护]

构造一个集合。构造函数是保护的，因为QPtrCollection是抽象类。

QPtrCollection::QPtrCollection ( const QPtrCollection & source ) [保护]

构造一个autoDelete()设置为假，source的一份复制。这个构造函数是保护的，因为QPtrCollection是抽象类。

注意如果source中autoDelete设置为打开的，复制它将会导致内存泄漏、读取被释放的内存或者两者都有的风险。

QPtrCollection::~QPtrCollection () [虚 保护]

销毁这个集合。这个析构函数是保护的，因为QPtrCollection是抽象类。

bool QPtrCollection::autoDelete () const

返回自动删除选项的设置。默认值为FALSE。

也可以参考setAutoDelete()。

void QPtrCollection::clear () [纯虚]

从集合中移除所有的对象。如果自动删除被设置为生效，这些对象将被删除。

也可以参考setAutoDelete()。

在QAsciiDict、QCache、QDict、QIntDict、QPtrList、QPtrDict和QPtrVector中被重新实现。

uint QPtrCollection::count () const [纯虚]

返回集合中对象的数量。

在QAsciiDict、QCache、QDict、QIntDict、QPtrList、QPtrDict和QPtrVector中被重新实现。

void QPtrCollection::deleteItem ( Item d ) [纯虚 保护]

如果你想能够删除集合中的项，请实现这个函数。

删除一个要从集合中移除的项。

这个函数不得不在集合模板类中重新实现，并且必须只能在自动删除生效的情况下删除d这一项。

警告：如果你重新实现这个函数，你也必须重新实现析构函数并且在你的析构函数中调用虚函数clear()。这是由于C++中虚函数和析构函数工作的方式：被继承类的虚函数不能被一个析构函数调用。如果你不这么做，当容器被破坏时，你的deleteItem()函数将不会被调用。

也可以参考newItem()和setAutoDelete()。

Item QPtrCollection::newItem ( Item d ) [虚 保护]

虚函数创建一个要被插入到集合中的对象的复制。

默认的实现是返回d指针，比如，没有复制被完成。

在几何模板类中这个函数极少被重新实现。对被插入的东西做复制不是共有的实践。

也可以参考deleteItem()。

void QPtrCollection::setAutoDelete ( bool enable )

如果enable为真，设置集合可以自动删除它的内容，并且如果enable为假，就永远不能删除它们。

如果自动删除被打开，当集合自己被删除时，集合中的所有项也都要被删除。如果集合有的仅仅是指向项的指针，这个很有用。

为了安全，默认设置是假。如果你把它打开，对于集合的复制你要注意些——你自己也许会发现两个集合删除同一个项。

注意在子类中自动删除设置也许会影响其它函数。例如，一个有remove()函数的子类将会从它的数据结构中移除这个项，并且如果自动删除生效，也将会删除这个项。

也可以参考autoDelete()。

实例：grapher/grapher.cpp、scribble/scribble.cpp和table/bigtable/main.cpp。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qptrcollection.h包含文件

qptrcollection.h

这里是qptrcollection.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
**
** Definition of base class for all pointer based collection classes
**
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRCOLLECTION_H
#define QPTRCOLLECTION_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

class QGVector;
class QGList;
class QGDict;

class Q_EXPORT QPtrCollection			// inherited by all collections
{
public:
    bool autoDelete()	const	       { return del_item; }
    void setAutoDelete( bool enable )  { del_item = enable; }

    virtual uint  count() const = 0;
    virtual void  clear() = 0;			// delete all objects

    typedef void *Item;				// generic collection item

protected:
    QPtrCollection() { del_item = FALSE; }		// no deletion of objects
    QPtrCollection(const QPtrCollection &) { del_item = FALSE; }
    virtual ~QPtrCollection() {}

    bool del_item;				// default FALSE

    virtual Item     newItem( Item );		// create object
    virtual void     deleteItem( Item ) = 0;	// delete object
};

#ifndef QT_NO_COMPAT
#define QCollection QPtrCollection
#endif

#endif // QPTRCOLLECTION_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrCollection成员列表

完整的QPtrCollection成员列表

这里是QPtrCollection成员函数的完整列表，包括继承的成员。

  • QPtrCollection()
  • ~QPtrCollection()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • newItem()
  • setAutoDelete()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrDict Class

QPtrDict Class Reference

The QPtrDict class is a template class that provides a dictionary based on void* keys. More...

#include <qptrdict.h>

Inherits QPtrCollection.

List of all member functions.

Public Members

  • QPtrDict ( int size = 17 )
  • QPtrDict ( const QPtrDict<type> & dict )
  • ~QPtrDict ()
  • QPtrDict<type> & operator= ( const QPtrDict<type> & dict )
  • virtual uint count () const
  • uint size () const
  • bool isEmpty () const
  • void insert ( void * key, const type * item )
  • void replace ( void * key, const type * item )
  • bool remove ( void * key )
  • type * take ( void * key )
  • type * find ( void * key ) const
  • type * operator[] ( void * key ) const
  • virtual void clear ()
  • void resize ( uint newsize )
  • void statistics () const

Important Inherited Members

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

Protected Members

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item ) const

Detailed Description

The QPtrDict class is a template class that provides a dictionary based on void* keys.

QPtrDict is implemented as a template class. Define a template instance QPtrDict<X> to create a dictionary that operates on pointers to X (X*).

A dictionary is a collection of key-value pairs. The key is a void* used for insertion, removal and lookup. The value is a pointer. Dictionaries provide very fast insertion and lookup.

Example:

    QPtrDict<char> extra;

    QLineEdit *le1 = new QLineEdit( this );
    le1->setText( "Simpson" );
    QLineEdit *le2 = new QLineEdit( this );
    le2->setText( "Homer" );
    QLineEdit *le3 = new QLineEdit( this );
    le3->setText( "45" );

    extra.insert( le1, "Surname" );
    extra.insert( le2, "Forename" );
    extra.insert( le3, "Age" );

    QPtrDictIterator<char> it( extra ); // See QPtrDictIterator
    for( ; it.current(); ++it )
        cout << it.current() << endl;
    cout << endl;

    if ( extra[le1] ) // Prints "Surname: Simpson"
        cout << extra[le1] << ": " << le1->text() << endl;
    if ( extra[le2] ) // Prints "Forename: Homer"
        cout << extra[le2] << ": " << le2->text() << endl;

    extra.remove( le1 ); // Removes le1 from the dictionary
    cout << le1->text() << endl; // Prints "Simpson"
In this example we use a dictionary to add an extra property (a char*) to the line edits we're using.

See QDict for full details, including the choice of dictionary size, and how deletions are handled.

See also QPtrDictIterator, QDict, QAsciiDict, QIntDict, Collection Classes, Collection Classes and Non-GUI Classes.

Member Function Documentation

QPtrDict::QPtrDict ( int size = 17 )

Constructs a dictionary using an internal hash array with the size size.

Setting size to a suitably large prime number (equal to or greater than the expected number of entries) makes the hash distribution better and hence the lookup faster.

QPtrDict::QPtrDict ( const QPtrDict<type> & dict )

Constructs a copy of dict.

Each item in dict is inserted into this dictionary. Only the pointers are copied (shallow copy).

QPtrDict::~QPtrDict ()

Removes all items from the dictionary and destroys it.

All iterators that access this dictionary will be reset.

See also setAutoDelete().

bool QPtrCollection::autoDelete () const

Returns the setting of the auto-delete option. The default is FALSE.

See also setAutoDelete().

void QPtrDict::clear () [virtual]

Removes all items from the dictionary.

The removed items are deleted if auto-deletion is enabled.

All dictionary iterators that access this dictionary will be reset.

See also remove(), take() and setAutoDelete().

Reimplemented from QPtrCollection.

uint QPtrDict::count () const [virtual]

Returns the number of items in the dictionary.

See also isEmpty().

Reimplemented from QPtrCollection.

type * QPtrDict::find ( void * key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the last item that was inserted will be found.

Equivalent to the [] operator.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also operator[]().

void QPtrDict::insert ( void * key, const type * item )

Inserts the key with the item into the dictionary.

The key does not have to be a unique dictionary key. If multiple items are inserted with the same key, only the last item will be visible.

Null items are not allowed.

See also replace().

bool QPtrDict::isEmpty () const

Returns TRUE if the dictionary is empty; otherwise returns FALSE.

See also count().

QPtrDict<type> & QPtrDict::operator= ( const QPtrDict<type> & dict )

Assigns dict to this dictionary and returns a reference to this dictionary.

This dictionary is first cleared and then each item in dict is inserted into the dictionary. Only the pointers are copied (shallow copy), unless newItem() has been reimplemented.

type * QPtrDict::operator[] ( void * key ) const

Returns the item associated with key, or null if the key does not exist in the dictionary.

This function uses an internal hashing algorithm to optimize lookup.

If there are two or more items with equal keys, then the last item that was inserted will be found.

Equivalent to the find() function.

Warning: Your application will crash if you call find() on an empty dictionary; you can check with isEmpty() or count(). We don't perform this check for efficiency reasons.

See also find().

QDataStream & QPtrDict::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

Reads a dictionary item from the stream s and returns a reference to the stream.

The default implementation sets item to 0.

See also write().

bool QPtrDict::remove ( void * key )

Removes the item associated with key from the dictionary. Returns TRUE if successful, or FALSE if the key does not exist in the dictionary.

If there are two or more items with equal keys, then the last item that was inserted of will be removed.

The removed item is deleted if auto-deletion is enabled.

All dictionary iterators that refer to the removed item will be set to point to the next item in the dictionary traversal order.

See also take(), clear() and setAutoDelete().

void QPtrDict::replace ( void * key, const type * item )

If the dictionary has key key, this key's item is replaced with item. If the dictionary doesn't contain key key, item is inserted into the dictionary using key key.

Null items are not allowed.

Equivalent to

    QPtrDict<char> dict;
        ...
    if ( dict.find( key ) )
        dict.remove( key );
    dict.insert( key, item );

If there are two or more items with equal keys, then the last inserted of these will be replaced.

See also insert().

void QPtrDict::resize ( uint newsize )

Changes the size of the hash table to newsize. The contents of the dictionary are preserved, but all iterators on the dictionary become invalid.

void QPtrCollection::setAutoDelete ( bool enable )

Sets the collection to auto-delete its contents if enable is TRUE and to never delete them if enable is FALSE.

If auto-deleting is turned on, all the items in a collection are deleted when the collection itself is deleted. This is convenient if the collection has the only pointer to the items.

The default setting is FALSE, for safety. If you turn it on, be careful about copying the collection - you might find yourself with two collections deleting the same items.

Note that the auto-delete setting may also affect other functions in subclasses. For example, a subclass that has a remove() function will remove the item from its data structure, and if auto-delete is enabled, will also delete the item.

See also autoDelete().

Examples: grapher/grapher.cpp, scribble/scribble.cpp and table/bigtable/main.cpp.

uint QPtrDict::size () const

Returns the size of the internal hash table (as specified in the constructor).

See also count().

void QPtrDict::statistics () const

Debugging-only function that prints out the dictionary distribution using qDebug().

type * QPtrDict::take ( void * key )

Takes the item associated with key out of the dictionary without deleting it (even if auto-deletion is enabled).

If there are two or more items with equal keys, then the last item that was inserted of will be removed.

Returns a pointer to the item taken out, or null if the key does not exist in the dictionary.

All dictionary iterators that refer to the taken item will be set to point to the next item in the dictionary traversal order.

See also remove(), clear() and setAutoDelete().

QDataStream & QPtrDict::write ( QDataStream & s, QPtrCollection::Item ) const [virtual protected]

Writes a dictionary item to the stream s and returns a reference to the stream.

See also read().

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


qptrdict.h Include File

qptrdict.h

This is the verbatim text of the qptrdict.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QPtrDict template class
**
** Created : 970415
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRDICT_H
#define QPTRDICT_H

#ifndef QT_H
#include "qgdict.h"
#endif // QT_H

template<class type>
class QPtrDict
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGDict
#endif
{
public:
    QPtrDict(int size=17) : QGDict(size,PtrKey,0,0) {}
    QPtrDict( const QPtrDict<type> &d ) : QGDict(d) {}
   ~QPtrDict()				{ clear(); }
    QPtrDict<type> &operator=(const QPtrDict<type> &d)
            { return (QPtrDict<type>&)QGDict::operator=(d); }
    uint  count()   const		{ return QGDict::count(); }
    uint  size()    const		{ return QGDict::size(); }
    bool  isEmpty() const		{ return QGDict::count() == 0; }
    void  insert( void *k, const type *d )
                    { QGDict::look_ptr(k,(Item)d,1); }
    void  replace( void *k, const type *d )
                    { QGDict::look_ptr(k,(Item)d,2); }
    bool  remove( void *k )		{ return QGDict::remove_ptr(k); }
    type *take( void *k )		{ return (type*)QGDict::take_ptr(k); }
    type *find( void *k ) const
        { return (type *)((QGDict*)this)->QGDict::look_ptr(k,0,0); }
    type *operator[]( void *k ) const
        { return (type *)((QGDict*)this)->QGDict::look_ptr(k,0,0); }
    void  clear()			{ QGDict::clear(); }
    void  resize( uint n )		{ QGDict::resize(n); }
    void  statistics() const		{ QGDict::statistics(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream &, QPtrCollection::Item & );
    virtual QDataStream& write( QDataStream &, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QPtrDict<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type>
inline void QPtrDict<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QPtrDictIterator
: public QGDictIterator
{
public:
    QPtrDictIterator(const QPtrDict<type> &d) :QGDictIterator((QGDict &)d) {}
   ~QPtrDictIterator()	      {}
    uint  count()   const     { return dict->count(); }
    bool  isEmpty() const     { return dict->count() == 0; }
    type *toFirst()	      { return (type *)QGDictIterator::toFirst(); }
    operator type *()  const  { return (type *)QGDictIterator::get(); }
    type *current()    const  { return (type *)QGDictIterator::get(); }
    void *currentKey() const  { return QGDictIterator::getKeyPtr(); }
    type *operator()()	      { return (type *)QGDictIterator::operator()(); }
    type *operator++()	      { return (type *)QGDictIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGDictIterator::operator+=(j);}
};

#endif // QPTRDICT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QPtrDict Member List

Complete Member List for QPtrDict

This is the complete list of member functions for QPtrDict, including inherited members.

  • QPtrDict()
  • ~QPtrDict()
  • autoDelete()
  • clear()
  • count()
  • deleteItem()
  • find()
  • insert()
  • isEmpty()
  • newItem()
  • operator=()
  • operator[]()
  • read()
  • remove()
  • replace()
  • resize()
  • setAutoDelete()
  • size()
  • statistics()
  • take()
  • write()


QPtrDictIterator Class

QPtrDictIterator Class Reference

The QPtrDictIterator class provides an iterator for QPtrDict collections. More...

#include <qptrdict.h>

List of all member functions.

Public Members

  • QPtrDictIterator ( const QPtrDict<type> & dict )
  • ~QPtrDictIterator ()
  • uint count () const
  • bool isEmpty () const
  • type * toFirst ()
  • operator type * () const
  • type * current () const
  • void * currentKey () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )

Detailed Description

The QPtrDictIterator class provides an iterator for QPtrDict collections.

QPtrDictIterator is implemented as a template class. Define a template instance QPtrDictIterator<X> to create a dictionary iterator that operates on QPtrDict<X> (dictionary of X*).

Example:

    QPtrDict<char> extra;

    QLineEdit *le1 = new QLineEdit( this );
    le1->setText( "Simpson" );
    QLineEdit *le2 = new QLineEdit( this );
    le2->setText( "Homer" );
    QLineEdit *le3 = new QLineEdit( this );
    le3->setText( "45" );

    extra.insert( le1, "Surname" );
    extra.insert( le2, "Forename" );
    extra.insert( le3, "Age" );

    QPtrDictIterator<char> it( extra );
    for( ; it.current(); ++it ) {
        QLineEdit *le = (QLineEdit)it.currentKey();
        cout << it.current() << ": " << le->text() << endl;
    }
    cout << endl;

    // Output (random order):
    //  Forename: Homer
    //  Age: 45
    //  Surname: Simpson
In the example we insert some line edits into a dictionary, then iterate over the dictionary printing the strings associated with those line edits.

Multiple iterators may independently traverse the same dictionary. A QPtrDict knows about all iterators that are operating on the dictionary. When an item is removed from the dictionary, QPtrDict updates all iterators that refer the removed item to point to the next item in the traversing order.

See also QPtrDict, Collection Classes and Non-GUI Classes.

Member Function Documentation

QPtrDictIterator::QPtrDictIterator ( const QPtrDict<type> & dict )

Constructs an iterator for dict. The current iterator item is set to point on the first item in the dict.

QPtrDictIterator::~QPtrDictIterator ()

Destroys the iterator.

uint QPtrDictIterator::count () const

Returns the number of items in the dictionary this iterator operates on.

See also isEmpty().

type * QPtrDictIterator::current () const

Returns a pointer to the current iterator item.

void * QPtrDictIterator::currentKey () const

Returns the key for the current iterator item.

bool QPtrDictIterator::isEmpty () const

Returns TRUE if the dictionary is empty; otherwise returns FALSE.

See also count().

QPtrDictIterator::operator type * () const

Cast operator. Returns a pointer to the current iterator item. Same as current().

type * QPtrDictIterator::operator() ()

Makes the succeeding item current and returns the original current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QPtrDictIterator::operator++ ()

Prefix ++ makes the succeeding item current and returns the new current item.

If the current iterator item was the last item in the dictionary or if it was null, null is returned.

type * QPtrDictIterator::operator+= ( uint jump )

Sets the current item to the item jump positions after the current item and returns a pointer to that item.

If that item is beyond the last item or if the dictionary is empty, it sets the current item to null and returns null.

type * QPtrDictIterator::toFirst ()

Sets the current iterator item to point to the first item in the dictionary and returns a pointer to the item. If the dictionary is empty, it sets the current item to null and returns null.

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


QPtrDictIterator Member List

Complete Member List for QPtrDictIterator

This is the complete list of member functions for QPtrDictIterator, including inherited members.

  • QPtrDictIterator()
  • ~QPtrDictIterator()
  • count()
  • current()
  • currentKey()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator++()
  • operator+=()
  • toFirst()


QPtrList类

QPtrList类参考

QPtrList类是一个提供双向链表的模板类。 详情请见……

#include <qptrlist.h>

继承了QPtrCollection。

被QObjectList、QSortedList和QStrList继承。

所有成员函数的列表。

公有成员

  • QPtrList ()
  • QPtrList ( const QPtrList<type> & list )
  • ~QPtrList ()
  • QPtrList<type> & operator= ( const QPtrList<type> & list )
  • bool operator== ( const QPtrList<type> & list ) const
  • virtual uint count () const
  • bool isEmpty () const
  • bool insert ( uint index, const type * item )
  • void inSort ( const type * item )
  • void prepend ( const type * item )
  • void append ( const type * item )
  • bool remove ( uint index )
  • bool remove ()
  • bool remove ( const type * item )
  • bool removeRef ( const type * item )
  • void removeNode ( QLNode * node )
  • bool removeFirst ()
  • bool removeLast ()
  • type * take ( uint index )
  • type * take ()
  • type * takeNode ( QLNode * node )
  • virtual void clear ()
  • void sort ()
  • int find ( const type * item )
  • int findNext ( const type * item )
  • int findRef ( const type * item )
  • int findNextRef ( const type * item )
  • uint contains ( const type * item ) const
  • uint containsRef ( const type * item ) const
  • type * at ( uint index )
  • int at () const
  • type * current () const
  • QLNode * currentNode () const
  • type * getFirst () const
  • type * getLast () const
  • type * first ()
  • type * last ()
  • type * next ()
  • type * prev ()
  • void toVector ( QGVector * vec ) const

重要的继承成员

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

保护成员

  • virtual int compareItems ( QPtrCollection::Item item1, QPtrCollection::Item item2 )
  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item item ) const

详细描述

QPtrList类是一个提供双向链表的模板类。

QValueList是可以替代这个类的的一个可兼容STL的的选择。

定义一个模板实例QPtrList<X>就创建了一个操作X（X*）指针的列表。

这个列表类是可以索引的并且有一个当前索引和一个当前项。第一项对应的是索引0。如果当前项为空，则当前索引为-1。

使用prepend()、insert()或append()可以插入项。可以使用remove()、removeRef()、removeFirst()和removeLast()来移除项。你可以使用find()、findNext()、findRef()或findNextRef()来搜索一个项。列表可以使用sort()来排序。你可以使用contains()或containsRef()来得到一个项出现的次数。你也可以使用current()来得到指向当前项的指针，用at()来得到一个在特定索引位置的项的指针，用getFirst()和getLast()来得到第一个或最后一个项的指针。你也可以使用first()、last()、next()和prev()（它们都会更新current()）来遍历列表。列表的删除属性可以用setAutoDelete()来设置。

实例：

    class Employee
    {
    public:
        Employee() : sn( 0 ) { }
        Employee( const QString& forename, const QString& surname, int salary )
            : fn( forename ), sn( surname ), sal( salary )
        { }

        void setSalary( int salary ) { sal = salary; }

        QString forename() const { return fn; }
        QString surname() const { return sn; }
        int salary() const { return sal; }

    private:
        QString fn;
        QString sn;
        int sal;
    };

    QPtrList<Employee> list;
    list.setAutoDelete( TRUE ); // list列表拥有了这个对象

    list.append( new Employee("John", "Doe", 50000) );
    list.append( new Employee("Jane", "Williams", 80000) );
    list.append( new Employee("Tom", "Jones", 60000) );

    Employee *employee;
    for ( employee = list.first(); employee; employee = list.next() )
        cout << employee->surname().latin1() << ", " <<
                employee->forename().latin1() << " earns " <<
                employee->salary() << endl;
    cout << endl;

    // 对于非常大的列表是很没有效率的
    for ( uint i = 0; i < list.count(); ++i )
        if ( list.at(i) )
            cout << list.at( i )->surname().latin1() << endl;

输出是

    Doe, John earns 50000
    Williams, Jane earns 80000
    Jones, Tom earns 60000

    Doe
    Williams
    Jones

QPtrList有几个函数可以遍历列表，但是使用QPtrListIterator会更实用。多重列表的迭代器也可以遍历同一个列表，它们之间以及和当前列表项无关。

在上面的例子中，我们调用setAutoDelete(TRUE)使自动删除生效就是说列表在移除项的时候一起删除它。默认选项是当它们被移除的时候不被删除，但是我们的例子中对没有列表项没有其它的引用，所以如果不这么做的话会导致内存泄漏。

列表项被作为void*存储在内部的QLNode终了，它也保存指向前一个和后一个列表项的指针。currentNode()、removeNode()和takeNode()函数可以直接操作QLNode，但是必须仔细使用它们。节点的数据部分可以使用QLNode::getData()得到。

当向列表插入一个项的时候，只有指针被复制，而不是项自身，比如，我们做了一个浅复制。当一个项被插入时，也是可以让列表复制这个项的所有数据（深复制）。insert()、inSort()和append()在项被插入时调用虚函数QPtrCollection::newItem()。如果你想深复制，请继承这个列表并重新实现它。

当从列表中移除一个项时，虚函数QPtrCollection::deleteItem()被调用。QPtrList的默认实现是如果自动删除生效，就删除这个项。

虚函数compareItems()可以被重新实现用来比较两个列表项。这个函数被所有需要比较列表项的列表函数调用，比如remove(const type*)。如果你只想处理指针，又可以替代比较指针的函数，比如removeRef(const type*)。这些函数比那些调用compareItems()的稍微快些。

qstrlist.h中定义的QStrList是一个char*的列表。它重新实现了newItem()、deleteItem()和compareItems()。

也可以参考QPtrListIterator、集合类和非GUI类。

成员函数文档

QPtrList::QPtrList ()

构造一个空的列表。

QPtrList::QPtrList ( const QPtrList<type> & list )

构造一个list的复制。

list的每一个项都被添加到这个列表中。只有指针被复制（浅复制）。

QPtrList::~QPtrList ()

移除列表中的所有项并且销毁这个列表。

访问这个列表的所有列表迭代器都会被重置。

也可以参考setAutoDelete()。

void QPtrList::append ( const type * item )

在列表的最后插入item。

被插入的项变为当前列表项。这和insert( count(), item )是相同的。

item必须不是一个空指针。

也可以参考insert()、current()和prepend()。

实例：customlayout/border.cpp、customlayout/card.cpp、customlayout/flow.cpp、grapher/grapher.cpp、listviews/listviews.cpp、listviews/listviews.h和qwerty/qwerty.cpp。

type * QPtrList::at ( uint index )

返回一个在列表index位置的项的指针，如果索引超出范围，返回空。

如果index有效，设置这个项为当前列表项。有效范围是0……(count() - 1)。

这个函数是非常有效的。它从第一项、最后一项或当前项中最接近index的开始扫描。

也可以参考current()。

实例：customlayout/border.cpp、customlayout/card.cpp、customlayout/flow.cpp、dirview/dirview.cpp、fileiconview/qfileiconview.cpp、mdi/application.cpp和qwerty/qwerty.cpp。

int QPtrList::at () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回当前列表项的索引。如果当前项为空，返回值为-1。

也可以参考current()。

bool QPtrCollection::autoDelete () const

返回自动删除选项的设置。默认为假。

也可以参考setAutoDelete()。

void QPtrList::clear () [虚]

移除列表中所有项。

如果自动删除生效，被移除的项目将被删除。

所有访问这个列表的列表迭代器都将被重置。

也可以参考remove()、take()和setAutoDelete()。

从QPtrCollection中重新实现。

int QPtrList::compareItems ( QPtrCollection::Item item1, QPtrCollection::Item item2 ) [虚 保护]

这个虚函数比较两个列表项。

返回：

  • 如果item1==item2，返回0
  • 如果item1!=item2，返回非0

这个函数返回int而不是bool，这样可以重新实现返回三个值并且使用它来排序：

  • 如果item1 == item2，返回0
  • 如果item1>item2，返回>0（正整数）
  • 如果item1<item2，返回<0（负整数）

inSort()需要compareItems()像这里所描述的这样来被实现。

这个函数不应该修改列表，因为一些常量函数调用compareItems()。

默认实现是比较指针。

uint QPtrList::contains ( const type * item ) const

计算并且返回item在列表中出现的次数。

当在列表中搜索item时，compareItems()函数被调用。如果compareItems()没有被重新实现，调用containsRef()是更有效率的。

这个函数不影响当前列表项。

也可以参考containsRef()和compareItems()。

uint QPtrList::containsRef ( const type * item ) const

计算并且返回item在列表中出现的次数。

调用这个函数比contains()快多了，因为contains()使用compareItems()来用item与列表中的每一个项进行比较。这个函数只比较指针。

这个函数不影响当前列表项。

也可以参考contains()。

uint QPtrList::count () const [虚]

返回列表中项的数量。

也可以参考isEmpty()。

实例：customlayout/border.cpp、customlayout/card.cpp、customlayout/flow.cpp、fileiconview/qfileiconview.cpp、grapher/grapher.cpp、mdi/application.cpp和qwerty/qwerty.cpp。

从QPtrCollection中重新实现的。

type * QPtrList::current () const

返回一个指向当前列表项的指针。当前列表项可能为空（意味着当前索引为-1）。

也可以参考at()。

QLNode * QPtrList::currentNode () const

返回指向当前列表节点的指针。

节点可以被保存并且稍后使用removeNode()移除。这样做的优点是可以直接移除这个项，而不用搜索列表。

警告：不要调用这个函数，除非你是专家。

也可以参考removeNode()、takeNode()和current()。

int QPtrList::find ( const type * item )

找到item在列表中第一次出现的位置。

如果这个项被找到，列表会设置当前项指向找到的项，并且返回这个项的索引。如果没有被找到，列表设置当前项为空，当前索引为-1，并且返回-1。

当在列表中搜索这个项时，compareItems()函数被调用。如果compareItems()没有被重新实现，调用findRef()是更有效率的。

也可以参考findNext()、findRef()、compareItems()和current()。

int QPtrList::findNext ( const type * item )

从当前列表项，找到item在列表中下一次出现的位置。

如果这个项被找到，列表会设置当前项指向找到的项，并且返回这个项的索引。如果没有被找到，列表设置当前项为空，当前索引为-1，并且返回-1。

当在列表中搜索这个项时，compareItems()函数被调用。如果compareItems()没有被重新实现，调用findNextRef()是更有效率的。

也可以参考find()、findNextRef()、compareItems()和current()。

int QPtrList::findNextRef ( const type * item )

从当前列表项，找到item在列表中下一次出现的位置。

如果这个项被找到，列表会设置当前项指向找到的项，并且返回这个项的索引。如果没有被找到，列表设置当前项为空，当前索引为-1，并且返回-1。

调用这个函数比findNext()快得多，因为findNext()是使用compareItems()来用item与列表中的每一个项进行比较。这个函数只比较指针。

也可以参考findRef()、findNext()和current()。

int QPtrList::findRef ( const type * item )

找到item在列表中第一次出现的位置。

如果这个项被找到，列表会设置当前项指向找到的项，并且返回这个项的索引。如果没有被找到，列表设置当前项为空，当前索引为-1，并且返回-1。

调用这个函数比find()快得多，因为find()是使用compareItems()来用item与列表中的每一个项进行比较。这个函数只比较指针。

也可以参考findNextRef()、find()和current()。

type * QPtrList::first ()

返回指向列表中第一个项的指针并且使它成为当前列表项，或者如果列表为空当前项就为空。

也可以参考getFirst()、last()、next()、prev()和current()。

实例：grapher/grapher.cpp、listviews/listviews.h和showimg/showimg.cpp。

type * QPtrList::getFirst () const

返回指向列表中第一个项的指针，如果列表为空返回空。

这个函数不影响当前列表项。

也可以参考first()和getLast()。

type * QPtrList::getLast () const

Returns a pointer to the last item in the list, or null if the list is empty. 返回指向列表中最后一个项的指针，如果列表为空返回空。

这个函数不影响当前列表项。

也可以参考last()和getFirst()。

void QPtrList::inSort ( const type * item )

把item插入到列表中它被排序的位置。

排序依靠的是虚函数compareItems()。为了维护这个派逊，所有的项都必须使用inSort()来插入。

被插入的项变为当前项。

item必须不能是一个空指针。

请注意inSort()很慢。如果你想先向列表插入很多项，插入完之后再排序，你应该使用sort()。inSort()进行了O(n)次比较。这就意味着插入n个项到你的列表需要比较O(n^2)次，而sort()做同样的工作只需要O(n*log n)次。所以只有在你有一个预先排好序的列表并且想向其中插入少量的项时，再使用inSort()。

也可以参考insert()、compareItems()、current()和sort()。

bool QPtrList::insert ( uint index, const type * item )

插入item到列表的index位置。

如果成功返回真，或者如果index超出范围返回假。有效的范围是从0到count()（包括count()）。如果index==count()，项就被添加。

被插入的项变为当前项。

item必须不能是一个空指针。

也可以参考append()和current()。

bool QPtrList::isEmpty () const

如果列表是空的，返回真，否则返回假。

也可以参考count()。

type * QPtrList::last ()

返回指向列表最后一项的指针，并且把这一项变为当前列表项，如果列表为空，当前列表项为空。

也可以参考getLast()、first()、next()、prev()和current()。

type * QPtrList::next ()

返回指向当前项的下一项的指针。如果当前项为空或者它是最后一项，返回空。

把下一项作为当前项。如果当前项在这次函数调用之前就是最后一项了，当前项将被设置为空。如果当前项为空，这个函数就什么都不做。

也可以参考first()、last()、prev()和current()。

实例：grapher/grapher.cpp、listviews/listviews.h和showimg/showimg.cpp。

QPtrList<type> & QPtrList::operator= ( const QPtrList<type> & list )

把list赋值给这个列表并且返回这个列表的引用。

这个列表首先被清空，然后list中的每个项都被添加到这个列表中。只有指针被复制（浅复制），除非newItem()被重新实现了。

bool QPtrList::operator== ( const QPtrList<type> & list ) const

把这个列表和list进行比较。如果这个列表包含相同的数据，返回真，否则返回假。

void QPtrList::prepend ( const type * item )

在列表开始的位置插入item。

被插入项变为当前列表项。这和insert( 0, item )是相同的。

item必须不能是一个空指针。

也可以参考append()、insert()和current()。

type * QPtrList::prev ()

返回指向当前项的前一个项的指针。如果当前项为空或者等于第一项，返回空。

把前一项作为当前项。如果当前项在这次函数调用之前就是第一项了，当前项被设置为空。如果当前项为空，这个函数就什么都不做。

也可以参考first()、last()、next()和current()。

QDataStream & QPtrList::read ( QDataStream & s, QPtrCollection::Item & item ) [虚 保护]

从流s中读取一个列表项并且返回流的引用。

默认实习是设置item为0。

也可以参考write()。

bool QPtrList::remove ( uint index )

移除列表中index位置的项。

如果成功返回真，或者如果index超出范围返回假。有效范围是0……(count() - 1)（包括count()-1）。

如果自动删除生效，被移除的项目将被删除。

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考take()、clear()、setAutoDelete()、current()和removeRef()。

bool QPtrList::remove ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

移除当前列表项。

如果成功返回真，或者如果当前项为空，返回假。

如果自动删除生效，被移除的项目将被删除。

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。如果列表为空，当前项为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考take()、clear()、setAutoDelete()、current()和removeRef()。

bool QPtrList::remove ( const type * item )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

移除列表中第一次出现的item。

如果成功返回真，或者如果当前项为空，返回假。

如果自动删除生效，被移除的项目将被删除。

当在列表中搜索这个项的时候，compareItems()函数被调用。如果compareItems()没有被重新实现，调用removeRef()是更加有效率的。

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考removeRef()、take()、clear()、setAutoDelete()、compareItems()和current()。

bool QPtrList::removeFirst ()

移除列表中的第一项。如果成功返回真，或者如果列表是空的返回假。

如果自动删除生效，被移除的项目将被删除。

列表中的第一项变为新的当前列表项。如果列表变空了，当前列表项被设置为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考removeLast()、setAutoDelete()、current()和remove()。

bool QPtrList::removeLast ()

移除列表中的最后一项。如果成功返回真，或者如果列表是空的返回假。

如果自动删除生效，被移除的项目将被删除。

列表中的最后一项变为新的当前列表项。如果列表变空了，当前列表项被设置为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考removeFirst()、setAutoDelete()和current()。

void QPtrList::removeNode ( QLNode * node )

移除列表中的node节点。

这个节点必须存在于列表中，否则程序可能会崩溃。

如果自动删除生效，被移除的项目将被删除。

列表中的第一项变为新的当前列表项。如果列表变空了，当前列表项被设置为空。

所有指向被移除的列表迭代器都被指向这项的下一项或者如果被移除的项是最后一项，则指向它的前一项。

警告：不要调用这个函数，除非你是专家。

也可以参考takeNode()、currentNode()、remove()和removeRef()。

bool QPtrList::removeRef ( const type * item )

移除列表中第一次出现的item。

如果成功返回真，或者如果这个项在列表中没有被找到，返回假。

如果自动删除生效，被移除的项目将被删除。

列表一直被扫描，直到指针item被找到为止。如果它被发现，它就会被移除。

等价于：

    if ( list.findRef( item ) != -1 )
        list.remove();

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。如果列表变空了，当前列表项被设置为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考remove()、clear()、setAutoDelete()和current()。

void QPtrCollection::setAutoDelete ( bool enable )

如果enable为真，设置集合可以自动删除它的内容，并且如果enable为假，就永远不能删除它们。

如果自动删除被打开，当集合本身被删除的时候，集合内所有的项也都被删除。如果只有这个集合指向它的项时，这个方法很方便。

为了安全，默认设置是假。如果你把它打开，对于集合的复制你要注意些——你自己也许会发现两个集合删除同一个项。

注意在子类中自动删除设置也许会影响其它函数。例如，一个有remove()函数的子类将会从它的数据结构中移除这个项，并且如果自动删除生效，也将会删除这个项。

也可以参考autoDelete().

实例：grapher/grapher.cpp、scribble/scribble.cpp和table/bigtable/main.cpp。

void QPtrList::sort ()

使用虚函数compareItems()的结果排序这个列表。

排序中使用堆排序算法。它对n项排序需要O(n*log n)次比较。这是排序问题中接近最佳的解决方案。

如果你的列表中的项支持操作符<和操作符==，你最好离开QSortedList，因为它使用这两个操作符为你实现了compareItems()函数。

也可以参考inSort()。

type * QPtrList::take ( uint index )

把列表中在index位置的项拿出来，而不删除它（尽管如果自动删除是生效的。）

返回指向你从列表中拿出的项的指针，或者如果索引超出范围，返回空。有效范围是0..(count() - 1)（包括count()-1）。

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。如果列表变空了，当前列表项被设置为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考remove()、clear()和current()。

实例：customlayout/border.cpp、customlayout/card.cpp和customlayout/flow.cpp。

type * QPtrList::take ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把列表中在index位置的项拿出来，而不删除它（尽管如果自动删除是生效的。）

返回指向你从列表中拿出的项的指针，或者如果索引超出范围，返回空。有效范围是0..(count() - 1)（包括count()-1）。

如果被移除的项不是列表中最后一项，被移除的项之后的项变为新的当前列表项。如果最后一项被移除，新的最后一项变为当前项。如果列表变空了，当前列表项被设置为空。

所有指向被移除项的列表迭代器都将会被指向新的当前项。

也可以参考remove()、clear()和current()。

type * QPtrList::takeNode ( QLNode * node )

把列表中的节点node拿出来，而不删除它（尽管如果自动删除是生效的。）返回指向你从列表中拿出的项的指针。

这个节点必须存在于列表中，否则程序可能会崩溃。

列表中的第一项变为新的当前列表项。如果列表变空了，当前列表项被设置为空。

所有指向被移除的列表迭代器都被指向这项的下一项或者如果被移除的项是最后一项，则指向它的前一项。

警告：不要调用这个函数，除非你是专家。

也可以参考removeNode()和currentNode()。

void QPtrList::toVector ( QGVector * vec ) const

存储所有的列表项到矢量vec中。

矢量必须和项的类型相同，否则结果将会是不确定的。

QDataStream & QPtrList::write ( QDataStream & s, QPtrCollection::Item item ) const [虚 保护]

写一个列表项item到流s中并且返回流的引用。

默认实现是不做任何事。

也可以参考read().

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qptrlist.h包含文件

qptrlist.h

这里是qptrlist.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QPtrList template/macro class
**
** Created :
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRLIST_H
#define QPTRLIST_H

#ifndef QT_H
#include "qglist.h"
#endif // QT_H

template<class type>
class QPtrList
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGList
#endif
{
public:
    QPtrList()				{}
    QPtrList( const QPtrList<type> &l ) : QGList(l) {}
    ~QPtrList()				{ clear(); }
    QPtrList<type> &operator=(const QPtrList<type> &l)
            { return (QPtrList<type>&)QGList::operator=(l); }
    bool operator==( const QPtrList<type> &list ) const
    { return QGList::operator==( list ); }
    uint  count()   const		{ return QGList::count(); }
    bool  isEmpty() const		{ return QGList::count() == 0; }
    bool  insert( uint i, const type *d){ return QGList::insertAt(i,(QPtrCollection::Item)d); }
    void  inSort( const type *d )	{ QGList::inSort((QPtrCollection::Item)d); }
    void  prepend( const type *d )	{ QGList::insertAt(0,(QPtrCollection::Item)d); }
    void  append( const type *d )	{ QGList::append((QPtrCollection::Item)d); }
    bool  remove( uint i )		{ return QGList::removeAt(i); }
    bool  remove()			{ return QGList::remove((QPtrCollection::Item)0); }
    bool  remove( const type *d )	{ return QGList::remove((QPtrCollection::Item)d); }
    bool  removeRef( const type *d )	{ return QGList::removeRef((QPtrCollection::Item)d); }
    void  removeNode( QLNode *n )	{ QGList::removeNode(n); }
    bool  removeFirst()			{ return QGList::removeFirst(); }
    bool  removeLast()			{ return QGList::removeLast(); }
    type *take( uint i )		{ return (type *)QGList::takeAt(i); }
    type *take()			{ return (type *)QGList::take(); }
    type *takeNode( QLNode *n )		{ return (type *)QGList::takeNode(n); }
    void  clear()			{ QGList::clear(); }
    void  sort()			{ QGList::sort(); }
    int	  find( const type *d )		{ return QGList::find((QPtrCollection::Item)d); }
    int	  findNext( const type *d )	{ return QGList::find((QPtrCollection::Item)d,FALSE); }
    int	  findRef( const type *d )	{ return QGList::findRef((QPtrCollection::Item)d); }
    int	  findNextRef( const type *d ){ return QGList::findRef((QPtrCollection::Item)d,FALSE);}
    uint  contains( const type *d ) const { return QGList::contains((QPtrCollection::Item)d); }
    uint  containsRef( const type *d ) const
                    { return QGList::containsRef((QPtrCollection::Item)d); }
    type *at( uint i )			{ return (type *)QGList::at(i); }
    int	  at() const			{ return QGList::at(); }
    type *current()  const		{ return (type *)QGList::get(); }
    QLNode *currentNode()  const	{ return QGList::currentNode(); }
    type *getFirst() const		{ return (type *)QGList::cfirst(); }
    type *getLast()  const		{ return (type *)QGList::clast(); }
    type *first()			{ return (type *)QGList::first(); }
    type *last()			{ return (type *)QGList::last(); }
    type *next()			{ return (type *)QGList::next(); }
    type *prev()			{ return (type *)QGList::prev(); }
    void  toVector( QGVector *vec )const{ QGList::toVector(vec); }

#ifdef Q_QDOC
protected:
    virtual int compareItems( QPtrCollection::Item, QPtrCollection::Item );
    virtual QDataStream& read( QDataStream&, QPtrCollection::Item& );
    virtual QDataStream& write( QDataStream&, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QPtrList<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QPtrList<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

template<class type>
class QPtrListIterator
: public QGListIterator
{
public:
    QPtrListIterator(const QPtrList<type> &l) :QGListIterator((QGList &)l) {}
   ~QPtrListIterator()	      {}
    uint  count()   const     { return list->count(); }
    bool  isEmpty() const     { return list->count() == 0; }
    bool  atFirst() const     { return QGListIterator::atFirst(); }
    bool  atLast()  const     { return QGListIterator::atLast(); }
    type *toFirst()	      { return (type *)QGListIterator::toFirst(); }
    type *toLast()	      { return (type *)QGListIterator::toLast(); }
    operator type *() const   { return (type *)QGListIterator::get(); }
    type *operator*()         { return (type *)QGListIterator::get(); }

    // No good, since QPtrList<char> (ie. QStrList fails...
    //
    // MSVC++ gives warning
    // Sunpro C++ 4.1 gives error
    //    type *operator->()        { return (type *)QGListIterator::get(); }

    type *current()   const   { return (type *)QGListIterator::get(); }
    type *operator()()	      { return (type *)QGListIterator::operator()();}
    type *operator++()	      { return (type *)QGListIterator::operator++(); }
    type *operator+=(uint j)  { return (type *)QGListIterator::operator+=(j);}
    type *operator--()	      { return (type *)QGListIterator::operator--(); }
    type *operator-=(uint j)  { return (type *)QGListIterator::operator-=(j);}
    QPtrListIterator<type>& operator=(const QPtrListIterator<type>&it)
                  { QGListIterator::operator=(it); return *this; }
};

#ifndef QT_NO_COMPAT
#define QList QPtrList
#define QListIterator QPtrListIterator
#endif

#endif // QPTRLIST_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrList成员列表

完整的QPtrList成员列表

这里是QPtrList成员函数的完整列表，包括继承的成员。

  • QPtrList()
  • ~QPtrList()
  • append()
  • at()
  • autoDelete()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • current()
  • currentNode()
  • deleteItem()
  • find()
  • findNext()
  • findNextRef()
  • findRef()
  • first()
  • getFirst()
  • getLast()
  • inSort()
  • insert()
  • isEmpty()
  • last()
  • newItem()
  • next()
  • operator=()
  • operator==()
  • prepend()
  • prev()
  • read()
  • remove()
  • removeFirst()
  • removeLast()
  • removeNode()
  • removeRef()
  • setAutoDelete()
  • sort()
  • take()
  • takeNode()
  • toVector()
  • write()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrListIterator类

QPtrListIterator类参考

QPtrListIterator类提供了QPtrList集合的迭代器。 详情请见……

#include <qptrlist.h>

被QObjectListIt和QStrListIterator继承。

所有成员函数的列表。

公有成员

  • QPtrListIterator ( const QPtrList<type> & list )
  • ~QPtrListIterator ()
  • uint count () const
  • bool isEmpty () const
  • bool atFirst () const
  • bool atLast () const
  • type * toFirst ()
  • type * toLast ()
  • operator type * () const
  • type * operator* ()
  • type * current () const
  • type * operator() ()
  • type * operator++ ()
  • type * operator+= ( uint jump )
  • type * operator-- ()
  • type * operator-= ( uint jump )
  • QPtrListIterator<type> & operator= ( const QPtrListIterator<type> & it )

详细描述

QPtrListIterator类提供了QPtrList集合的迭代器。

定义一个模板实例QPtrListIterator<X>就创建一个在QPtrList<X>（X*的列表）的一个列表迭代器。

下面的实例和QPtrList类文档中的实例相似，但是它使用了QPtrListIterator。类Employee是在那里定义的。

    QPtrList<Employee> list;

    list.append( new Employee("John", "Doe", 50000) );
    list.append( new Employee("Jane", "Williams", 80000) );
    list.append( new Employee("Tom", "Jones", 60000) );

    QPtrListIterator<Employee> it( list );
    Employee *employee;
    while ( (employee = it.current()) != 0 ) {
        ++it;
        cout << employee->surname().latin1() << ", " <<
                employee->forename().latin1() << " earns " <<
                employee->salary() << endl;
    }

输出是

    Doe, John earns 50000
    Williams, Jane earns 80000
    Jones, Tom earns 60000

使用列表迭代器识别使用QPtrList的成员函数first()、next()、current()等等更加强壮的遍历方法，并且许多迭代器可以同时分别地遍历同一个列表。

一个迭代器中有一个它自己的当前列表项并且能够得到下一个和上一个列表项。它不能以任何方式修改这个列表。

当一个项从列表中被移除，所有指向这个项地迭代器都会被更新为指向QPtrList::current()而避免摇摆引用。

也可以参考QPtrList、集合类和非GUI 类。

成员函数文档

QPtrListIterator::QPtrListIterator ( const QPtrList<type> & list )

为list构造一个迭代器。当前迭代器项被设置为指向list中的第一项。

QPtrListIterator::~QPtrListIterator ()

销毁这个迭代器。

bool QPtrListIterator::atFirst () const

如果当前迭代器项是列表的第一个项，返回真，否则返回假。

也可以参考toFirst()和atLast()。

bool QPtrListIterator::atLast () const

如果当前迭代器项是列表的最后一个项，返回真，否则返回假。

也可以参考toLast()和atFirst()。

uint QPtrListIterator::count () const

返回这个迭代器操作的列表的项的数量。

也可以参考isEmpty()。

实例：customlayout/card.cpp。

type * QPtrListIterator::current () const

返回指向当前迭代器项的指针。如果迭代器被放置到列表的第一项之前或者最后一项之后，返回的是空指针。

实例：canvas/canvas.cpp、customlayout/card.cpp和customlayout/flow.cpp。

bool QPtrListIterator::isEmpty () const

如果列表是空的，返回真，否则返回假。

也可以参考count()。

QPtrListIterator::operator type * () const

抛出操作符。返回指向当前迭代器项的指针。和current()一样。

type * QPtrListIterator::operator() ()

让当前项后的一项变为当前向并且返回原来的当前项。

如果当前迭代器项是列表中的最后一项或者如果它为空，返回空。

type * QPtrListIterator::operator* ()

星号操作符。返回指向当前迭代器项的指针。和current()一样。

type * QPtrListIterator::operator++ ()

前置++让当前项后的一项变为当前向并且返回原来的当前项。

如果当前迭代器项是列表中的最后一项或者如果它为空，返回空。

type * QPtrListIterator::operator+= ( uint jump )

设置当前项跳到当前项之后jump个位置的项并且返回指向那个项的指针。

如果那个项已经超过最后一个项或者如果列表为空，它设置当前项为空并且返回空。

type * QPtrListIterator::operator-- ()

前置-让当前向的前一项变为当前向并且返回原来的当前项。

如果当前迭代器项是列表中的最后一项或者如果它为空，返回空。

type * QPtrListIterator::operator-= ( uint jump )

设置当前项跳到当前项之前jump个位置的项并且返回指向那个项的指针。

如果那个项已经超过第一个项或者如果列表为空，它设置当前项为空并且返回空。

QPtrListIterator<type> & QPtrListIterator::operator= ( const QPtrListIterator<type> & it )

赋值。做迭代器it的复制并且返回这个迭代器的引用。

type * QPtrListIterator::toFirst ()

设置当前迭代器指向列表中的第一个项并且返回指向这个项的指针。如果列表为空，设置当前项为空并且返回空。

也可以参考toLast()和atFirst()。

type * QPtrListIterator::toLast ()

设置当前迭代器指向列表中的最后一个项并且返回指向这个项的指针。如果列表为空，设置当前项为空并且返回空。

也可以参考toFirst()和atLast()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrListIterator成员列表

完整的QPtrListIterator成员列表

这里是QPtrListIterator成员函数的完整列表，包括继承的成员。

  • QPtrListIterator()
  • ~QPtrListIterator()
  • atFirst()
  • atLast()
  • count()
  • current()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator*()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrQueue类

QPtrQueue类参考

QPtrQueue类是一个提供队列的模板类。 详情请见……

#include <qptrqueue.h>

所有成员函数的列表。

公有成员

  • QPtrQueue ()
  • QPtrQueue ( const QPtrQueue<type> & queue )
  • ~QPtrQueue ()
  • QPtrQueue<type> & operator= ( const QPtrQueue<type> & queue )
  • bool autoDelete () const
  • void setAutoDelete ( bool enable )
  • uint count () const
  • bool isEmpty () const
  • void enqueue ( const type * d )
  • type * dequeue ()
  • bool remove ()
  • void clear ()
  • type * head () const
  • operator type * () const
  • type * current () const

保护成员

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item item ) const

详细描述

QPtrQueue类是一个提供队列的模板类。

QValueVector是可以替代这个类的的一个可兼容STL的的选择。

定义一个模板实例QPtrQueue<X>就创建了一个操作X（X*）指针的队列。

队列就是先进先出的结构。可以通过enqueue()把项添加到队列末尾并且可以通过dequeue()从队列开始处重新得到项。你可以使用head()来查看头项而不用把它从队列中拿出来。

你可以用setAutoDelete()来控制队列删除策略。

为了兼容QPtrCollection类，current()和remove()都被提供，两个都基于head()操作。

也可以参考QPtrList、QPtrStack、集合类和非GUI类。

成员函数文档

QPtrQueue::QPtrQueue ()

创建一个autoDelete()被设置为假的空队列。

QPtrQueue::QPtrQueue ( const QPtrQueue<type> & queue )

从queue创建一个队列。

只有指针被复制，项没有被复制。autoDelete()标记被设置为假。

QPtrQueue::~QPtrQueue ()

销毁这个队列。如果autoDelete()为真，队列中的项被删除。

bool QPtrQueue::autoDelete () const

返回自动删除选项的设置。默认为假。

也可以参考setAutoDelete()。

void QPtrQueue::clear ()

从队列中移除所有项，并且如果autoDelete()为真，就删除它们。

也可以参考remove()。

uint QPtrQueue::count () const

返回队列中项的数量。

也可以参考isEmpty()。

type * QPtrQueue::current () const

返回队列中头项的引用。队列没有被改变。

也可以参考dequeue()和isEmpty()。

type * QPtrQueue::dequeue ()

从队列中得到头项并且返回它的指针。

也可以参考enqueue()和count()。

void QPtrQueue::enqueue ( const type * d )

把项d添加到队列末尾。

也可以参考count()和dequeue()。

type * QPtrQueue::head () const

返回队列中头项的引用。队列没有被改变。

也可以参考dequeue()和isEmpty()。

bool QPtrQueue::isEmpty () const

如果队列是空的，返回真，否则返回假。

也可以参考count()、dequeue()和head()。

QPtrQueue::operator type * () const

返回队列中头项的引用。队列没有被改变。

也可以参考dequeue()和isEmpty()。

QPtrQueue<type> & QPtrQueue::operator= ( const QPtrQueue<type> & queue )

把queue赋值给这个队列并且返回这个队列的引用。

这个队列首先被清空并且然后queue中的每一个项都被添加到这个队列中。只有指针被复制。

注意autoDelete()标记没有被修改。如果queue和这个队列中都设置为真，删除这个两个队列将导致对项双重删除。

QDataStream & QPtrQueue::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

从流s读取一个队列项item并且返回流的引用。

默认实现是设置item为0。

也可以参考write()。

bool QPtrQueue::remove ()

从队列中移除头项并且如果队列中还有项返回真，或者如果队列空了返回假。

如果autoDelete()为真，就删除这个项。

也可以参考head()、isEmpty()和dequeue()。

void QPtrQueue::setAutoDelete ( bool enable )

如果enable为真，设置队列自动删除它的内容并且如果enable为假，就不删除它们。

如果自动删除被打开，当队列被删除时，队列中的所有项都会被删除。如果队列拥有项的唯一指针，这个将是非常方便的。

为了安全，默认设置为假。如果你把它打开，在复制队列时请注意。你也许会发现你自己的两个队列删除相同的项。

也可以参考autoDelete()。

QDataStream & QPtrQueue::write ( QDataStream & s, QPtrCollection::Item item ) const [virtual protected]

写一个队列项item到流s中并且返回流的引用。

默认实现是不做任何事。

也可以参考read()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qptrqueue.h包含文件

qptrqueue.h

这里是qptrqueue.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QPtrQueue template/macro class
**
** Created : 920917
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRQUEUE_H
#define QPTRQUEUE_H

#ifndef QT_H
#include "qglist.h"
#endif // QT_H

template<class type>
class QPtrQueue : protected QGList
{
public:
    QPtrQueue()				{}
    QPtrQueue( const QPtrQueue<type> &q ) : QGList(q) {}
    ~QPtrQueue()			{ clear(); }
    QPtrQueue<type>& operator=(const QPtrQueue<type> &q)
            { return (QPtrQueue<type>&)QGList::operator=(q); }
    bool  autoDelete() const		{ return QPtrCollection::autoDelete(); }
    void  setAutoDelete( bool del )	{ QPtrCollection::setAutoDelete(del); }
    uint  count()   const		{ return QGList::count(); }
    bool  isEmpty() const		{ return QGList::count() == 0; }
    void  enqueue( const type *d )	{ QGList::append(Item(d)); }
    type *dequeue()			{ return (type *)QGList::takeFirst();}
    bool  remove()			{ return QGList::removeFirst(); }
    void  clear()			{ QGList::clear(); }
    type *head()    const		{ return (type *)QGList::cfirst(); }
      operator type *() const	{ return (type *)QGList::cfirst(); }
    type *current() const		{ return (type *)QGList::cfirst(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream&, QPtrCollection::Item& );
    virtual QDataStream& write( QDataStream&, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QPtrQueue<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QPtrQueue<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

#ifndef QT_NO_COMPAT
#define QQueue QPtrQueue
#endif

#endif // QPTRQUEUE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrQueue成员列表

完整的QPtrQueue成员列表

这里是QPtrQueue成员函数的完整列表，包括继承的成员。

  • QPtrQueue()
  • ~QPtrQueue()
  • autoDelete()
  • clear()
  • count()
  • current()
  • dequeue()
  • enqueue()
  • head()
  • isEmpty()
  • operator type *()
  • operator=()
  • read()
  • remove()
  • setAutoDelete()
  • write()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrStack类

QPtrStack类参考

QPtrQueue类是一个提供栈的模板类。 详情请见……

#include <qptrstack.h>

所有成员函数的列表。

公有成员

  • QPtrStack ()
  • QPtrStack ( const QPtrStack<type> & s )
  • ~QPtrStack ()
  • QPtrStack<type> & operator= ( const QPtrStack<type> & s )
  • bool autoDelete () const
  • void setAutoDelete ( bool enable )
  • uint count () const
  • bool isEmpty () const
  • void push ( const type * d )
  • type * pop ()
  • bool remove ()
  • void clear ()
  • type * top () const
  • operator type * () const
  • type * current () const

保护成员

  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item item ) const

详细描述

QPtrQueue类是一个提供栈的模板类。

QValueStack是可以替代这个类的的一个可兼容STL的的选择。

定义一个模板实例QPtrStack<X>就创建了一个操作X（X*）指针的队列。

栈就是后进先出的结构。可以通过push()把项添加到栈的顶端并且可以通过pop()可以重新获得顶端的项。使用top()可以得到栈的顶端元素的应用而不改变它。

你可以用setAutoDelete()来控制栈删除策略。

为了兼容QPtrCollection类，current()和remove()都被提供，两个都基于top()操作。

也可以参考QPtrList、QPtrQueue和非GUI类。

成员函数文档

QPtrStack::QPtrStack ()

创建一个空栈。

QPtrStack::QPtrStack ( const QPtrStack<type> & s )

通过浅复制另一个栈s来构造一个栈。

QPtrStack::~QPtrStack ()

销毁这个栈。如果autoDelete()为真，栈中的项被删除。

bool QPtrStack::autoDelete () const

和QPtrCollection::autoDelete()相同。

也可以参考setAutoDelete()。

void QPtrStack::clear ()

从栈中移除所有项，并且如果autoDelete()为真，就删除它们。

也可以参考remove()。

uint QPtrStack::count () const

返回栈中项的数量。

也可以参考isEmpty()。

type * QPtrStack::current () const

返回栈中顶端元素的引用（最近被放入的）。栈不被改变。

bool QPtrStack::isEmpty () const

如果栈没有任何元素可以被弹出，返回真，否则返回假。

QPtrStack::operator type * () const

返回栈中顶端元素的引用（最近被放入的）。栈不被改变。

QPtrStack<type> & QPtrStack::operator= ( const QPtrStack<type> & s )

通过给另一个栈s做浅复制来设置这个栈的内容。如果autoDelete()设置为真，这个栈当前的元素将被删除。

type * QPtrStack::pop ()

从栈中删除顶端项并且返回它。

void QPtrStack::push ( const type * d )

把元素d添加到栈的顶端。后进先出。

QDataStream & QPtrStack::read ( QDataStream & s, QPtrCollection::Item & item ) [virtual protected]

从流s中读取一个栈项item并且返回流的引用。

默认实现是设置item为0。

也可以参考write()。

bool QPtrStack::remove ()

从栈中移除顶端项并且如果autoDelete()为真就删除它。如果有元素可以弹出，返回真，否则返回假。

也可以参考clear()。

void QPtrStack::setAutoDelete ( bool enable )

定义这个栈是否自动删除它的内容。和QPtrCollection::setAutoDelete()一样。

如果enable为真，栈会自动删除它的内容，如果enable为假，栈不会删除它的内容。

也可以参考autoDelete()。

type * QPtrStack::top () const

返回栈中顶端元素的引用（最近被放入的）。栈不被改变。

QDataStream & QPtrStack::write ( QDataStream & s, QPtrCollection::Item item ) const [virtual protected]

写一个栈项item到流s中并且返回流的引用。

默认实现是不做任何事。

也可以参考read().

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qptrstack.h包含文件

qptrstack.h

这里是qptrstack.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QPtrStack pointer based template class
**
** Created : 920917
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRSTACK_H
#define QPTRSTACK_H

#ifndef QT_H
#include "qglist.h"
#endif // QT_H

template<class type>
class QPtrStack : protected QGList
{
public:
    QPtrStack()				{ }
    QPtrStack( const QPtrStack<type> &s ) : QGList( s ) { }
    ~QPtrStack()			{ clear(); }
    QPtrStack<type> &operator=(const QPtrStack<type> &s)
            { return (QPtrStack<type>&)QGList::operator=(s); }
    bool  autoDelete() const		{ return QPtrCollection::autoDelete(); }
    void  setAutoDelete( bool del )	{ QPtrCollection::setAutoDelete(del); }
    uint  count()   const		{ return QGList::count(); }
    bool  isEmpty() const		{ return QGList::count() == 0; }
    void  push( const type *d )		{ QGList::insertAt(0,Item(d)); }
    type *pop()				{ return (type *)QGList::takeFirst(); }
    bool  remove()			{ return QGList::removeFirst(); }
    void  clear()			{ QGList::clear(); }
    type *top()	    const		{ return (type *)QGList::cfirst(); }
      operator type *() const	{ return (type *)QGList::cfirst(); }
    type *current() const		{ return (type *)QGList::cfirst(); }

#ifdef Q_QDOC
protected:
    virtual QDataStream& read( QDataStream&, QPtrCollection::Item& );
    virtual QDataStream& write( QDataStream&, QPtrCollection::Item ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QPtrStack<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QPtrStack<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

#ifndef QT_NO_COMPAT
#define QStack QPtrStack
#endif

#endif // QPTRSTACK_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrStack成员列表

完整的QPtrStack成员列表

这里是QPtrStack成员函数的完整列表，包括继承的成员。

  • QPtrStack()
  • ~QPtrStack()
  • autoDelete()
  • clear()
  • count()
  • current()
  • isEmpty()
  • operator type *()
  • operator=()
  • pop()
  • push()
  • read()
  • remove()
  • setAutoDelete()
  • top()
  • write()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrVector类

QPtrVector类参考

QPtrVector类是提供矢量（数组）的模板集合类。 详情请见……

#include <qptrvector.h>

继承了QPtrCollection。

所有成员函数的列表。

公有成员

  • QPtrVector ()
  • QPtrVector ( uint size )
  • QPtrVector ( const QPtrVector<type> & v )
  • ~QPtrVector ()
  • QPtrVector<type> & operator= ( const QPtrVector<type> & v )
  • bool operator== ( const QPtrVector<type> & v ) const
  • type ** data () const
  • uint size () const
  • virtual uint count () const
  • bool isEmpty () const
  • bool isNull () const
  • bool resize ( uint size )
  • bool insert ( uint i, const type * d )
  • bool remove ( uint i )
  • type * take ( uint i )
  • virtual void clear ()
  • bool fill ( const type * d, int size = -1 )
  • void sort ()
  • int bsearch ( const type * d ) const
  • int findRef ( const type * d, uint i = 0 ) const
  • int find ( const type * d, uint i = 0 ) const
  • uint containsRef ( const type * d ) const
  • uint contains ( const type * d ) const
  • type * operator[] ( int i ) const
  • type * at ( uint i ) const
  • void toList ( QGList * list ) const

重要继承成员

  • bool autoDelete () const
  • void setAutoDelete ( bool enable )

保护成员

  • virtual int compareItems ( QPtrCollection::Item d1, QPtrCollection::Item d2 )
  • virtual QDataStream & read ( QDataStream & s, QPtrCollection::Item & item )
  • virtual QDataStream & write ( QDataStream & s, QPtrCollection::Item item ) const

详细描述

QPtrVector类是提供矢量（数组）的模板集合类。

QValueVector是可以替代这个类的的一个可兼容STL的的选择。

QPtrVector被设计为一个模板类。定义一个模板实例QPtrVector<X>就创建了一个操作X（X*）指针的矢量。

矢量和数组是相同的。QPtrVector和QMemArray的主要不同就是QPtrVector存储元素的指针，而QMemArray存储元素自身（比如，QMemArray是基于类的并且QPtrVector是基于指针的）。

可以使用insert()或fill()把项添加到矢量中。可以使用remove()来移除项。你可以使用at()得到一个指定索引位置的项的指针。

除非是相反的状态，如果自动删除生效，所有从矢量中移除项的函数也都会将它们指向的元素删除。默认情况下，自动删除是失效的，请参考setAutoDelete()。这个行为可以通过在子类中重新实现虚函数deleteItem()来改变。

比较项的函数（比如find()和sort()）也都使用虚函数compareItems()。这个函数的默认实现只是比较指针值。在子类中中心实现compareItems()来获得基于项的内容的搜索和排序。你可以使用findRef()在矢量中执行一个对指针的线性搜索，或者使用bsearch()在一个排好序的矢量中执行一个二进制搜索。你可以使用contains()或containsRef()来统计一个项在矢量中出现的次数。

也可以参考QMemArray和非GUI类。

成员函数文档

QPtrVector::QPtrVector ()

构造一个零矢量。

也可以参考isNull()。

QPtrVector::QPtrVector ( uint size )

构造一个空间为size项的矢量。如果size==0，构造一个零矢量。

矢量中所有size个位置都被初始化为0。

也可以参考size()、resize()和isNull()。

QPtrVector::QPtrVector ( const QPtrVector<type> & v )

构造一个v的复制。只有指针被复制（比如，浅复制）。

QPtrVector::~QPtrVector ()

从矢量中移除所有的项，并且销毁矢量自己。

也可以参考clear()。

type * QPtrVector::at ( uint i ) const

返回在i位置的项，或者如果在那个位置没有项，返回0。i必须小于size()。

bool QPtrCollection::autoDelete () const

返回自动删除选项的设置。默认为假。

也可以参考setAutoDelete()。

int QPtrVector::bsearch ( const type * d ) const

在一个排好序的数组中，使用二进制搜索找到d第一次出现的位置。对于一个排好序的数组，这个比做线性搜索的find()要快很多。

返回d的位置，或者如果d没有被找到返回-1。d必须不能为0。

比较项使用虚函数compareItems()。

也可以参考sort()和find()。

void QPtrVector::clear () [虚]

从矢量中删除所有项，并且销毁矢量自己。

矢量变为一个零矢量。

也可以参考isNull()。

从QPtrCollection中重新实现的。

int QPtrVector::compareItems ( QPtrCollection::Item d1, QPtrCollection::Item d2 ) [虚 保护]

这个虚函数比较两个列表项：

返回：

  • 如果d1==d2，返回0
  • 如果d1!=d2，返回非0

这个函数返回int而不是bool，这样重新实现就可以返回3个值并且用来进行排序：

  • 如果d1==d2，返回0
  • 如果d1>d2，返回>0（正整数）
  • 如果d1<d2，返回<0（负整数）

sort()和bsearch()函数需要compareItems()像这里所描述的那样被实现。

这个函数不应该修改矢量因为一些常量函数会调用compareItems()。

uint QPtrVector::contains ( const type * d ) const

返回矢量中项d出现的次数。

比较项使用虚函数compareItems()。

也可以参考containsRef()。

uint QPtrVector::containsRef ( const type * d ) const

返回矢量中项指针d出现的次数。

这个函数不使用compareItems()来比较项。

也可以参考findRef()。

uint QPtrVector::count () const [虚]

返回矢量中项的数量。如果count()==0，这个矢量为空。

也可以参考isEmpty()和size()。

从QPtrCollection中重新实现。

type ** QPtrVector::data () const

返回指向实际矢量数据（type*的数组）的指针。

如果data()==0（零指针），矢量为零矢量。

也可以参考isNull()。

bool QPtrVector::fill ( const type * d, int size = -1 )

在矢量的所有位置插入项d。任何存在的项都被移除。如果d为0，这个矢量变为空。

如果size>=0，矢量首先被重新定义大小为size。默认情况下，size为-1。

如果成功，返回真，或者如果内存不能被分配（只有在重定义大小被需要的时候），返回假。

也可以参考resize()、insert()和isEmpty()。

int QPtrVector::find ( const type * d, uint i = 0 ) const

在矢量中使用线性搜索找到项d第一次出现的位置。这个搜索从i位置开始，i必须小于size()。i默认为0，比如，搜索从矢量的开始处开始。

返回d的位置，或者如果d没有被找到，返回-1。

比较项使用虚函数compareItems()。

使用更快的bsearch()来搜索一个排好序的矢量。

也可以参考findRef()和bsearch()。

int QPtrVector::findRef ( const type * d, uint i = 0 ) const

在矢量中使用线性搜索找到项指针d第一次出现的位置。这个搜索从i位置开始，i必须小于size()。i默认为0，比如，搜索从矢量的开始处开始。

返回d的位置，或者如果d没有被找到，返回-1。

这个函数不使用compareItems()来比较项。

使用更快的bsearch()来搜索一个排好序的矢量。

也可以参考find()和bsearch()。

bool QPtrVector::insert ( uint i, const type * d )

设置矢量中的位置i来包含项d。i必须小于size()。在i位置的任何以前的元素被移除了。

也可以参考at()。

bool QPtrVector::isEmpty () const

如果矢量为空，返回真，否则返回假。

也可以参考count()。

bool QPtrVector::isNull () const

如果矢量为零，返回真，否则返回假。

一个零矢量中size()== 0并且data()==0。

也可以参考size()。

QPtrVector<type> & QPtrVector::operator= ( const QPtrVector<type> & v )

把v赋值给这个矢量并且返回这个矢量的引用。

这个矢量首先被清空并且然后v所有的项都被复制到矢量中。只有指针被复制（比如，浅复制）。

也可以参考clear()。

bool QPtrVector::operator== ( const QPtrVector<type> & v ) const

如果这个矢量和v相等，返回真，否则返回假。

type * QPtrVector::operator[] ( int i ) const

返回在位置i的项，或者如果在那个位置没有项，返回0。i必须小于size()。

等于at( i )。

也可以参考at()。

QDataStream & QPtrVector::read ( QDataStream & s, QPtrCollection::Item & item ) [虚 保护]

从流s中读入一个矢量项item并且返回流的引用。

默认实现是设置item为0。

也可以参考write()。

bool QPtrVector::remove ( uint i )

如果有的话，移除矢量中位置i的项。i必须小于size()。

只要i不超出范围，就返回真。

也可以参考take()和at()。

bool QPtrVector::resize ( uint size )

重定义（扩大或缩小）矢量的大小为size。如果size==0，数组变为零数组。

矢量中在size位置的或者超出的任何项被一出了。新的位置被初始化为0。

如果成功，返回真，或者如果内存不能被分配，返回假。

也可以参考size()和isNull()。

void QPtrCollection::setAutoDelete ( bool enable )

如果enable为真，设置集合自动删除它的内容并且如果enable为假，就从不删除它们。

如果自动删除被打开，当集合被删除时，集合中的所有项都会被删除。如果集合拥有项的唯一指针，这个将是非常方便的。

为了安全，默认设置为假。如果你把它打开，在复制集合时请注意。你也许会发现你自己的两个集合删除相同的项。

注意在子类中自动删除设置也许会影响其它函数。例如，一个有remove()函数的子类将会从它的数据结构中移除这个项，并且如果自动删除生效，也将会删除这个项。

也可以参考autoDelete()。

矢量：grapher/grapher.cpp、scribble/scribble.cpp和table/bigtable/main.cpp。

uint QPtrVector::size () const

返回矢量的大小，比如矢量位置的数量。这也是矢量中可以保存元素的最大数量。

如果size()==0，这个矢量为空矢量。

也可以参考isNull()、resize()和count()。

void QPtrVector::sort ()

按升序排列项。任何空的位置将被放在最后面。

比较项使用虚函数compareItems()。

也可以参考bsearch()。

type * QPtrVector::take ( uint i )

返回矢量中位置i的项，并且从矢量中移除项。i必须小于size()。如果在位置i没有项，返回0。

与remove()形成对照，这个函数不调用deleteItem()来比较项。

也可以参考remove()和at()。

void QPtrVector::toList ( QGList * list ) const

复制这个矢量的所有项到列表list中。list首先被清空并且然后被添加到list中。

也可以参考QPtrList、QPtrStack和QPtrQueue。

QDataStream & QPtrVector::write ( QDataStream & s, QPtrCollection::Item item ) const [虚 保护]

写一个矢量项item到流s中并且返回流的引用。

默认实现是不做任何事。

也可以参考read()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qptrvector.h包含文件

qptrvector.h

这里是qptrvector.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QPtrVector pointer based template class
**
** Created : 930907
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPTRVECTOR_H
#define QPTRVECTOR_H

#ifndef QT_H
#include "qgvector.h"
#endif // QT_H

template<class type>
class QPtrVector
#ifdef Q_QDOC
    : public QPtrCollection
#else
    : public QGVector
#endif
{
public:
    QPtrVector()				{ }
    QPtrVector( uint size ) : QGVector(size) { }
    QPtrVector( const QPtrVector<type> &v ) : QGVector( v ) { }
    ~QPtrVector()				{ clear(); }
    QPtrVector<type> &operator=(const QPtrVector<type> &v)
            { return (QPtrVector<type>&)QGVector::operator=(v); }
    bool operator==( const QPtrVector<type> &v ) const { return QGVector::operator==(v); }
    type **data()   const		{ return (type **)QGVector::data(); }
    uint  size()    const		{ return QGVector::size(); }
    uint  count()   const		{ return QGVector::count(); }
    bool  isEmpty() const		{ return QGVector::count() == 0; }
    bool  isNull()  const		{ return QGVector::size() == 0; }
    bool  resize( uint size )		{ return QGVector::resize(size); }
    bool  insert( uint i, const type *d){ return QGVector::insert(i,(Item)d); }
    bool  remove( uint i )		{ return QGVector::remove(i); }
    type *take( uint i )		{ return (type *)QGVector::take(i); }
    void  clear()			{ QGVector::clear(); }
    bool  fill( const type *d, int size=-1 )
                    { return QGVector::fill((Item)d,size);}
    void  sort()			{ QGVector::sort(); }
    int	  bsearch( const type *d ) const{ return QGVector::bsearch((Item)d); }
    int	  findRef( const type *d, uint i=0 ) const
                    { return QGVector::findRef((Item)d,i);}
    int	  find( const type *d, uint i= 0 ) const
                    { return QGVector::find((Item)d,i); }
    uint  containsRef( const type *d ) const
                { return QGVector::containsRef((Item)d); }
    uint  contains( const type *d ) const
                    { return QGVector::contains((Item)d); }
    type *operator[]( int i ) const	{ return (type *)QGVector::at(i); }
    type *at( uint i ) const		{ return (type *)QGVector::at(i); }
    void  toList( QGList *list ) const	{ QGVector::toList(list); }

#ifdef Q_QDOC
protected:
    virtual int compareItems( QPtrCollection::Item d1, QPtrCollection::Item d2 );
    virtual QDataStream& read( QDataStream &s, QPtrCollection::Item &d );
    virtual QDataStream& write( QDataStream &s, QPtrCollection::Item d ) const;
#endif

private:
    void  deleteItem( Item d );
};

#if !defined(Q_BROKEN_TEMPLATE_SPECIALIZATION)
template<> inline void QPtrVector<void>::deleteItem( QPtrCollection::Item )
{
}
#endif

template<class type> inline void QPtrVector<type>::deleteItem( QPtrCollection::Item d )
{
    if ( del_item ) delete (type *)d;
}

#ifndef QT_NO_COMPAT
#define QVector QPtrVector
#endif

#endif // QVECTOR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPtrVector成员列表

完整的QPtrVector成员列表

这里是QPtrVector成员函数的完整列表，包括继承的成员。

  • QPtrVector()
  • ~QPtrVector()
  • at()
  • autoDelete()
  • bsearch()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • data()
  • deleteItem()
  • fill()
  • find()
  • findRef()
  • insert()
  • isEmpty()
  • isNull()
  • newItem()
  • operator=()
  • operator==()
  • operator[]()
  • read()
  • remove()
  • resize()
  • setAutoDelete()
  • size()
  • sort()
  • take()
  • toList()
  • write()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPushButton类

QPushButton类参考

QPushButton窗口部件提供了命令按钮。 详情请见……

#include <qpushbutton.h>

继承了QButton。

所有成员函数的列表。

公有成员

  • QPushButton ( QWidget * parent, const char * name = 0 )
  • QPushButton ( const QString & text, QWidget * parent, const char * name = 0 )
  • QPushButton ( const QIconSet & icon, const QString & text, QWidget * parent, const char * name = 0 )
  • ~QPushButton ()
  • void setToggleButton ( bool )
  • bool autoDefault () const
  • virtual void setAutoDefault ( bool autoDef )
  • bool isDefault () const
  • virtual void setDefault ( bool def )
  • virtual void setIsMenuButton ( bool enable ) （废弃）
  • bool isMenuButton () const （废弃）
  • void setPopup ( QPopupMenu * popup )
  • QPopupMenu * popup () const
  • void setIconSet ( const QIconSet & )
  • QIconSet * iconSet () const
  • void setFlat ( bool )
  • bool isFlat () const

公有槽

  • virtual void setOn ( bool )

重要得继承成员

  • QString text () const
  • virtual void setText ( const QString & )
  • const QPixmap * pixmap () const
  • virtual void setPixmap ( const QPixmap & )
  • QKeySequence accel () const
  • virtual void setAccel ( const QKeySequence & )
  • bool isToggleButton () const
  • virtual void setDown ( bool )
  • bool isDown () const
  • bool isOn () const
  • ToggleState state () const
  • bool autoRepeat () const
  • virtual void setAutoRepeat ( bool )
  • bool isExclusiveToggle () const
  • QButtonGroup * group () const
  • void toggle ()
  • void pressed ()
  • void released ()
  • void clicked ()
  • void toggled ( bool on )
  • void stateChanged ( int state )

属性

  • bool autoDefault - 推动按钮是否是自动默认按钮
  • bool autoMask - 按钮中自动面具特征是否有效 （只读）
  • bool default - 推动按钮是否是默认按钮
  • bool flat - 边缘是否失效
  • QIconSet iconSet - 推动按钮上的图标
  • bool menuButton - 推动按钮是否有一个菜单按钮在上面 （废弃）
  • bool on - 推动按钮是否被切换
  • bool toggleButton - 按钮是不是切换按钮

详细描述

QPushButton窗口部件提供了命令按钮。

推动按钮或者命令按钮或许是任何图形用户界面中最常用到的窗口部件。推动（点击）按钮来命令计算机执行一些操作，或者回答一个问题。典型的按钮有确定（OK）、应用（Apply）、撤销（Cancel）、关闭（Close）、是（Yes）、否（No）和帮助（Help）。

命令按钮是矩形的并且通常显示一个文本标签来描述它的操作。标签中有下划线的字母（在文本中它的前面被“&”标明）表明快捷键，例如：

    QPushButton *pb = new QPushButton( "&Download", this );
在这个实例中加速键是Alt+D，并且文本标签将被显示为Download。

推动按钮可以显示文本标签或者像素映射，并且和一个可选的小图标。这些可以通过使用构造函数来设置并且在这之后用setText()、setPixmap()和setIconSet()来改变。如果按钮失效，文本或像素映射和图标的外观将被按照图形用户界面的风格来操作表明按钮看起来是失效的。

当推动按钮被鼠标、空格键或者键盘快捷键激活，它发射clicked()信号。连接这个信号来执行按钮的操作。推动按钮也提供不太常用的信号，例如，pressed()和released()。

菜单中的命令按钮默认情况下是自动默认按钮，也就是说当它们接受到键盘焦点时，它们将自动变为默认推动按钮。默认按钮就是一个当用户在对话框中敲击回车键或换行键时被激活的推动按钮。你可以使用setAutoDefault()来改变这一点。注意自动默认按钮会保留一小点额外区域来绘制默认按钮指示器。如果你不想要你的按钮周围的这些空间，调用setAutoDefault(FALSE)。

因为如此的重要，按钮窗口部件在过去的时代中已经发展并提供了大量的变体。Microsoft风格指南现在显示Windows推动按钮大约有10种不同状态并且文本暗示有当所有的特种组合都被考虑进去的时候，大约有几十种或更多的情况。

最重要的模式或状态有：

  • 可用或不可用（变灰，失效）。
  • 标准推动按钮、切换推动按钮或菜单按钮。
  • 开或关（仅对切换推动按钮）。
  • 默认或普通。对话框中的默认按钮通常可以被使用回车键或换行键“点击”。
  • 自动重复或者不自动重复。
  • 被按下或者没有被按下。

作为一个通用规则，当在用户点击在应用程序或者对话框窗口中点击时（比如应用、撤销、关闭和帮助）并且窗口部件被假设有一个宽的矩形形状的文本标签，应用程序或者对话框窗口要执行一个操作时，使用推动按钮。改变窗口的状态，而不是执行操作的小的、通常正方形的按钮（比如QFileDialog右上角的按钮）不是命令按钮，而是工具按钮。Qt为这些按钮提供了一个特殊类（QToolButton）。

如果你需要切换行为（请参考setToggleButton()）或者当一个按钮被像滚动条那样的箭头被按下时，按钮自动重复激活信号（请参考setAutoRepeat()），命令按钮可能不是你想要的。如果拿不准，请使用工具按钮。

命令按钮的一个变体是菜单按钮。它们提供了不仅一个命令，而是几个，因为当它们被按下时，它们弹出一个选项菜单。使用setPopup()方式来关联一个弹出菜单到一个推动按钮。

其他按钮类是选项按钮（请参考QRadioButton）和选择框（请参考QCheckBox）。

在Qt中，QButton基类提供了绝大多数模式和其它应用编程接口，并且QPushButton提供了图形用户界面逻辑。关于应用编程接口的更多信息请参考QButton。

也可以参考QToolButton、QRadioButton、QCheckBox、GUI Design Handbook: Push Button和基本窗口部件。

成员函数文档

QPushButton::QPushButton ( QWidget * parent, const char * name = 0 )

构造一个没有文本的推动按钮。

参数parent和name被发送给QWidget的构造函数。

QPushButton::QPushButton ( const QString & text, QWidget * parent, const char * name = 0 )

构造一个名称为name、父对象为parent并且文本为text的推动按钮。

QPushButton::QPushButton ( const QIconSet & icon, const QString & text, QWidget * parent, const char * name = 0 )

构造一个图标为icon、文本为text的推动按钮。

注意你也可以传递一个QPixmap作为一个图标（感谢由C++提供的隐含类型转换）。

参数parent和name被发送给QWidget的构造函数。

QPushButton::~QPushButton ()

销毁这个推动按钮。

QKeySequence QButton::accel () const

返回这个按钮关联的快捷键。详细情况请参考“accel”属性。

bool QPushButton::autoDefault () const

如果这个推动是自动默认按钮，返回真，否则返回假。详细情况请参考“autoDefault”属性。

bool QButton::autoRepeat () const

如果自动重复生效，返回真，否则返回假。详细情况请参考“autoRepeat”自动重复。

void QButton::clicked () [信号]

当这个按钮被激活时（也就是说当鼠标光标在按钮时，并且被先按下再释放）、当快捷键被按下时或者当animateClick()被调用时，这个信号被发射。如果你调用setDown()，这个信号不被发射。

如果你想把几个按钮连接到一个相同的槽，QButtonGroup::clicked()信号可以做同样的工作。

也可以参考pressed()、released()、toggled()、autoRepeat和down。

实例：fonts/simple-qfont-demo/viewer.cpp、listbox/listbox.cpp、network/clientserver/client/client.cpp、network/ftpclient/ftpmainwindow.cpp、 richtext/richtext.cpp、t2/main.cpp和t4/main.cpp。

QButtonGroup * QButton::group () const

返回这个按钮所属于的组。

如果这个按钮不是任何一个QButtonGroup的成员，这个函数返回0。

也可以参考QButtonGroup。

QIconSet * QPushButton::iconSet () const

返回这个推动按钮的图标。详细情况请参考“iconSet”属性。

bool QPushButton::isDefault () const

如果这个推动按钮是默认按钮，返回真，否则返回假。详细情况请参考“default”属性。

bool QButton::isDown () const

如果这个按钮被按下，返回真，否则返回假。详细情况请参考“down”属性。

bool QButton::isExclusiveToggle () const

如果按钮是排它的，返回真，否则返回假。详细情况请参考“exclusiveToggle”属性。

bool QPushButton::isFlat () const

如果边缘失效，返回真，否则返回假。详细情况请参考“flat”属性。

bool QPushButton::isMenuButton () const

如果这个推动按钮有一个菜单按钮在上面，返回真，否则返回假。详细情况请参考“menuButton”属性。

bool QButton::isOn () const

如果按钮被切换，返回真，否则返回假。详细情况请参考“on”属性。

bool QButton::isToggleButton () const

如果按钮是一个切换按钮，返回真，否则返回假。详细情况请参考“toggleButton”属性。

const QPixmap * QButton::pixmap () const

返回这个按钮上显示的像素映射。详细情况请参考“pixmap”属性。

QPopupMenu * QPushButton::popup () const

返回这个按钮关联的弹出菜单或者如果没有弹出菜单被定义，返回0。

也可以参考setPopup()。

void QButton::pressed () [信号]

当这个按钮被按下，这个信号被发射。

也可以参考released()和clicked()。

实例：network/httpd/httpd.cpp和popup/popup.cpp。

void QButton::released () [信号]

当这个按钮被释放，这个信号被发射。

也可以参考pressed()、clicked()和toggled()。

void QButton::setAccel ( const QKeySequence & ) [虚]

设置按钮的相关快捷键。详细情况请参考“accel”属性。

void QPushButton::setAutoDefault ( bool autoDef ) [虚]

设置这个推动按钮是否是自动默认按钮为autoDef。详细情况请参考“autoDefault”。

void QButton::setAutoRepeat ( bool ) [虚]

设置autoRepeat是否生效。详细情况请参考“autoRepeat”属性。

void QPushButton::setDefault ( bool def ) [虚]

设置这个推动按钮是否是默认按钮为def。详细情况请参考“default”属性。

void QButton::setDown ( bool ) [虚]

设置按钮是否被按下。详细情况请参考“down”属性。

void QPushButton::setFlat ( bool )

设置边缘是否失效。详细情况请参考“flat”属性。

void QPushButton::setIconSet ( const QIconSet & )

设置这个推动按钮上的图标。详细情况请参考“iconSet”属性。

void QPushButton::setIsMenuButton ( bool enable ) [虚]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QPushButton::setOn ( bool ) [虚 槽]

设置这个推动按钮是否被切换。详细情况请参考“on”属性。

void QButton::setPixmap ( const QPixmap & ) [虚]

设置这个按钮上显示的像素映射。详细情况请参考“pixmap”属性。

void QPushButton::setPopup ( QPopupMenu * popup )

把弹出菜单popup和这个推动按钮关联起来并且这样就把它变为一个菜单按钮。

这个弹出菜单的所有权并不被转让给这个推动按钮。

也可以参考popup()。

实例：qdir/qdir.cpp。

void QButton::setText ( const QString & ) [虚]

设置这个按钮上显示的文本。详细情况请参考“text”属性。

void QPushButton::setToggleButton ( bool )

设置这个按钮是否是切换按钮。详细情况请参考“toggleButton”属性。

ToggleState QButton::state () const

如果这个按钮被切换，返回真，否则返回假。详细情况请参考“toggleState”属性。

void QButton::stateChanged ( int state ) [信号]

只要切换按钮改变状态，这个信号就被发射。如果这个按钮是开的，state为2，如果它在“没有变化”状态，为1，或者如果按钮是关的，为0。

这也许是一个用户操作、toggle()槽激活、setState(),或者因为setOn()被调用的结果。

也可以参考clicked()。

QString QButton::text () const

返回这个按钮上显示的文本。详细情况请参考“text”属性。

void QButton::toggle () [槽]

切换切换按钮的状态。

也可以参考on、toggled()和toggleButton。

void QButton::toggled ( bool on ) [信号]

只要切换按钮改变状态，这个信号就被发射。如果这个按钮是开的，on为真，或者如果按钮是关的，为假。

这也许是一个用户操作、toggle()槽激活或者因为setOn()被调用的结果。

也可以参考clicked()。

实例：listbox/listbox.cpp。

属性文档

QKeySequence accel

这个属性保存的是按钮相关的快捷键。

如果没有快捷键被设置，这个属性为0。如果你设置这个属性为0，那么任何当前的快捷键都被删除。

使用setAccel()来设置属性值并且使用accel()来得到属性值。

bool autoDefault

这个属性保存的是推动按钮是否是默认按钮。

如果这个属性为真，那么这个推动按钮在对话框中就是自动默认按钮。

当对话框接收到键盘输入焦点时，对话框中的自动默认阿牛自动变为默认推动按钮。

在一些图形用户界面风格中，默认按钮周围被绘制一个额外的框架，等于3个像素或更多。Qt会在自动默认按钮周围自动保留这些空间，也就是说，自动默认按钮也许回比它的大小提示稍大。

对于父对象为QDialog的按钮，属性默认值为真，其它为假。

使用setAutoDefault()来设置属性值并且通过autoDefault()来获得属性值。

bool autoMask

这个属性保存的是按钮中自动面具特征是否有效。

也可以参考QWidget::autoMask。

bool autoRepeat

这个属性保存的是自动重复是否生效。

如果autoRepeat生效，那么如果按钮是按下的，clicked()信号会被定期发送。这个属性对切换按钮没有效果。autoRepeat默认是关闭的。

使用setAutoRepeat()来设置这个属性值并且使用autoRepeat()来得到这个属性值。

bool default

这个属性保存的是推动按钮是否是默认按钮。

如果这个属性被设置为真，那么如果用户在对话框中敲击回车键，这个推动按钮将被按下。

当用户按下回车键，当前默认按钮得到点击，而与当前对话框中那个窗口部件拥有键盘输入焦点无关。同一时刻只能有一个推动按钮被设置为默认按钮。这个按钮然后被显示有一个额外的框架（这依赖于图形用户界面风格）。

只有在对话框中，默认按钮行为才被提供。通常当按钮得到焦点，换行键或者空格键被按下时，按钮被点击。

这个属性默认值为假。

通过setDefault()可以设置属性值并且通过isDefault()来获得属性值。

bool flat

这个属性保存的是边缘是否有效。

这个属性默认值为假。

通过setFlat()可以设置属性值并且通过isFlat()来获得属性值。

QIconSet iconSet

这个属性保存的是推动按钮上的图标。

如果这个推动按钮没有图标，这个属性将返回0。

通过setIconSet()可以设置属性并且通过iconSet()来获得属性值。

bool menuButton

这个属性保存的是推动按钮上是否有一个菜单按钮。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

如果这个属性被设置为真，那么在推动按钮上会绘制一个向下的箭头来表明如果用户在箭头上点击将会弹出一个菜单。

通过isMenuButton()来得到属性值。

bool on

这个属性保存的是按钮是否被切换。

这个属性只有对于切换按钮才能被设置。

也可以参考on、toggle()、toggled()和toggleButton。

使用isOn()来得到这个属性值。

QPixmap pixmap

这个属性保存的是按钮上显示的像素映射。

如果这个像素映射是单色的（也就是，它是一个QBitmap或者它的色深为1）并且它没有一个面具，这个属性将被设置为它自己的面具。这样的目的是为了绘制透明位图，例如，这对于切换按钮是很重要的。

如果没有像素映射被设置，pixmap()返回0。

通过setPixmap()可以设置属性值并且通过pixmap()来得到属性值。

QString text

这个属性保存的是按钮上显示的文本。

如果按钮没有文本，这个属性将返回一个零字符串。如果文本中有一个“&”在里面，那么会使用“&”后面紧接着的字符自动创建快捷键。

这里没有默认文不能。

通过setText()可以设置属性值并且通过text()来获得属性值。

bool toggleButton

这个属性值保存的是按钮是不是切换按钮。

切换按钮和选择框类似有开/关状态。一个推动按钮初始化时不是切换按钮。

也可以参考on、toggle()、toggleButton和toggled()。

通过setToggleButton()可以设置属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qpushbutton.h包含文件

qpushbutton.h

这里是qpushbutton.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qpushbutton.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QPushButton class
**
** Created : 940221
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QPUSHBUTTON_H
#define QPUSHBUTTON_H

#ifndef QT_H
#include "qbutton.h"
#include "qiconset.h"
#endif // QT_H

#ifndef QT_NO_PUSHBUTTON
class QPushButtonPrivate;
class QPopupMenu;

class Q_EXPORT QPushButton : public QButton
{
    Q_OBJECT

    Q_PROPERTY( bool autoDefault READ autoDefault WRITE setAutoDefault )
    Q_PROPERTY( bool default READ isDefault WRITE setDefault )
    Q_PROPERTY( bool menuButton READ isMenuButton DESIGNABLE false )
    Q_PROPERTY( QIconSet iconSet READ iconSet WRITE setIconSet )
    Q_OVERRIDE( bool toggleButton WRITE setToggleButton )
    Q_OVERRIDE( bool on WRITE setOn )
    Q_PROPERTY( bool flat READ isFlat WRITE setFlat )
    Q_OVERRIDE( bool autoMask DESIGNABLE true SCRIPTABLE true )

public:
    QPushButton( QWidget *parent, const char* name=0 );
    QPushButton( const QString &text, QWidget *parent, const char* name=0 );
    QPushButton( const QIconSet& icon, const QString &text, QWidget *parent, const char* name=0 );
    ~QPushButton();

    QSize	sizeHint() const;

    void	move( int x, int y );
    void	move( const QPoint &p );
    void	resize( int w, int h );
    void	resize( const QSize & );
    void	setGeometry( int x, int y, int w, int h );

    void	setGeometry( const QRect & );

    void setToggleButton( bool );

    bool	autoDefault()	const	{ return autoDefButton; }
    virtual void setAutoDefault( bool autoDef );
    bool	isDefault()	const	{ return defButton; }
    virtual void setDefault( bool def );

    virtual void setIsMenuButton( bool enable ) {  // obsolete functions
    if ( (bool)hasMenuArrow == enable )
        return;
    hasMenuArrow = enable ? 1 : 0;
    update();
    updateGeometry();
    }
    bool	isMenuButton() const { return hasMenuArrow; }

    void setPopup( QPopupMenu* popup );
    QPopupMenu* popup() const;

    void setIconSet( const QIconSet& );
    QIconSet* iconSet() const;

    void setFlat( bool );
    bool isFlat() const;

public slots:
    virtual void setOn( bool );

protected:
    void	drawButton( QPainter * );
    void	drawButtonLabel( QPainter * );
    void	focusInEvent( QFocusEvent * );
    void	focusOutEvent( QFocusEvent * );
    void	resizeEvent( QResizeEvent * );
    void	updateMask();

private slots:
    void popupPressed();

private:
    void	init();

    uint	autoDefButton	: 1;
    uint	defButton	: 1;
    uint	flt		: 1;
    uint	reserved		: 1; // UNUSED
    uint	lastEnabled	: 1; // UNUSED
    uint	hasMenuArrow	: 1;

    QPushButtonPrivate* d;

    friend class QDialog;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QPushButton( const QPushButton & );
    QPushButton &operator=( const QPushButton & );
#endif
};

#endif // QT_NO_PUSHBUTTON

#endif // QPUSHBUTTON_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QPushButton成员列表

完整的QPushButton成员列表

这里是QPushButton成员函数的完整列表，包括继承的成员。

  • QPushButton()
  • ~QPushButton()
  • accel()
  • acceptDrops()
  • adjustSize()
  • animateClick()
  • autoDefault()
  • autoMask()
  • autoRepeat()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawButton()
  • drawButtonLabel()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • group()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • hitButton()
  • icon()
  • iconSet()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDefault()
  • isDesktop()
  • isDialog()
  • isDown()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusiveToggle()
  • isExtDev()
  • isFlat()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMenuButton()
  • isMinimized()
  • isModal()
  • isOn()
  • isPopup()
  • isToggleButton()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • popup()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoDefault()
  • setAutoMask()
  • setAutoRepeat()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDefault()
  • setDisabled()
  • setDown()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFlat()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconSet()
  • setIconText()
  • setIsMenuButton()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOn()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setPopup()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setState()
  • setStyle()
  • setTabOrder()
  • setText()
  • setToggleButton()
  • setToggleType()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • state()
  • stateChanged()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • toggle()
  • toggleType()
  • toggled()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QRadioButton Class

QRadioButton Class Reference

The QRadioButton widget provides a radio button with a text or pixmap label. More...

#include <qradiobutton.h>

Inherits QButton.

List of all member functions.

Public Members

  • QRadioButton ( QWidget * parent, const char * name = 0 )
  • QRadioButton ( const QString & text, QWidget * parent, const char * name = 0 )
  • bool isChecked () const

Public Slots

  • virtual void setChecked ( bool check )

Important Inherited Members

  • QString text () const
  • virtual void setText ( const QString & )
  • const QPixmap * pixmap () const
  • virtual void setPixmap ( const QPixmap & )
  • QKeySequence accel () const
  • virtual void setAccel ( const QKeySequence & )
  • bool isToggleButton () const
  • virtual void setDown ( bool )
  • bool isDown () const
  • bool isOn () const
  • ToggleState state () const
  • bool autoRepeat () const
  • virtual void setAutoRepeat ( bool )
  • bool isExclusiveToggle () const
  • QButtonGroup * group () const
  • void toggle ()
  • void pressed ()
  • void released ()
  • void clicked ()
  • void toggled ( bool on )
  • void stateChanged ( int state )

Properties

  • bool autoMask - whether the radio button is automatically masked (read only)
  • bool checked - whether the radio button is checked

Detailed Description

The QRadioButton widget provides a radio button with a text or pixmap label.

QRadioButton and QCheckBox are both option buttons. That is, they can be switched on (checked) or off (unchecked). The classes differ in how the choices for the user are restricted. Check boxes define "many of many" choices, whereas radio buttons provide a "one of many" choice. In a group of radio buttons only one button at a time can be checked; if the user selects another button, the previously selected button is switched off.

The easiest way to implement a "one of many" choice is simply to put the radio buttons into QButtonGroup.

Whenever a button is switched on or off it emits the signal toggled(). Connect to this signal if you want to trigger an action each time the button changes state. Otherwise, use isChecked() to query whether or not a particular button is selected.

Just like QPushButton, a radio button can display text or a pixmap. The text can be set in the constructor or with setText(); the pixmap is set with setPixmap().

See also QPushButton, QToolButton, GUI Design Handbook: Radio Button and Basic Widgets.

Member Function Documentation

QRadioButton::QRadioButton ( QWidget * parent, const char * name = 0 )

Constructs a radio button with no text.

The parent and name arguments are sent to the QWidget constructor.

QRadioButton::QRadioButton ( const QString & text, QWidget * parent, const char * name = 0 )

Constructs a radio button with the text text.

The parent and name arguments are sent to the QWidget constructor.

QKeySequence QButton::accel () const

Returns the accelerator associated with the button. See the "accel" property for details.

bool QButton::autoRepeat () const

Returns TRUE if autoRepeat is enabled; otherwise returns FALSE. See the "autoRepeat" property for details.

void QButton::clicked () [signal]

This signal is emitted when the button is activated (i.e. first pressed down and then released when the mouse cursor is inside the button), when the accelerator key is typed or when animateClick() is called. This signal is not emitted if you call setDown().

The QButtonGroup::clicked() signal does the same job, if you want to connect several buttons to the same slot.

See also pressed(), released(), toggled(), autoRepeat and down.

Examples: fonts/simple-qfont-demo/viewer.cpp, listbox/listbox.cpp, network/clientserver/client/client.cpp, network/ftpclient/ftpmainwindow.cpp, richtext/richtext.cpp, t2/main.cpp and t4/main.cpp.

QButtonGroup * QButton::group () const

Returns a pointer to the group of which this button is a member.

If the button is not a member of any QButtonGroup, this function returns 0.

See also QButtonGroup.

bool QRadioButton::isChecked () const

Returns TRUE if the radio button is checked; otherwise returns FALSE. See the "checked" property for details.

bool QButton::isDown () const

Returns TRUE if the button is pressed; otherwise returns FALSE. See the "down" property for details.

bool QButton::isExclusiveToggle () const

Returns TRUE if the button is an exclusive toggle; otherwise returns FALSE. See the "exclusiveToggle" property for details.

bool QButton::isOn () const

Returns TRUE if the button is toggled; otherwise returns FALSE. See the "on" property for details.

bool QButton::isToggleButton () const

Returns TRUE if the button is a toggle button; otherwise returns FALSE. See the "toggleButton" property for details.

const QPixmap * QButton::pixmap () const

Returns the pixmap shown on the button. See the "pixmap" property for details.

void QButton::pressed () [signal]

This signal is emitted when the button is pressed down.

See also released() and clicked().

Examples: network/httpd/httpd.cpp and popup/popup.cpp.

void QButton::released () [signal]

This signal is emitted when the button is released.

See also pressed(), clicked() and toggled().

void QButton::setAccel ( const QKeySequence & ) [virtual]

Sets the accelerator associated with the button. See the "accel" property for details.

void QButton::setAutoRepeat ( bool ) [virtual]

Sets whether autoRepeat is enabled. See the "autoRepeat" property for details.

void QRadioButton::setChecked ( bool check ) [virtual slot]

Sets whether the radio button is checked to check. See the "checked" property for details.

void QButton::setDown ( bool ) [virtual]

Sets whether the button is pressed. See the "down" property for details.

void QButton::setPixmap ( const QPixmap & ) [virtual]

Sets the pixmap shown on the button. See the "pixmap" property for details.

void QButton::setText ( const QString & ) [virtual]

Sets the text shown on the button. See the "text" property for details.

ToggleState QButton::state () const

Returns TRUE if the button is toggled; otherwise returns FALSE. See the "toggleState" property for details.

void QButton::stateChanged ( int state ) [signal]

This signal is emitted whenever a toggle button changes status. state is 2 if the button is on, 1 if it is in the "no change" state or 0 if the button is off.

This may be the result of a user action, toggle() slot activation, setState(), or because setOn() was called.

See also clicked().

QString QButton::text () const

Returns the text shown on the button. See the "text" property for details.

void QButton::toggle () [slot]

Toggles the state of a toggle button.

See also on, setOn(), toggled() and toggleButton.

void QButton::toggled ( bool on ) [signal]

This signal is emitted whenever a toggle button changes status. on is TRUE if the button is on, or FALSE if the button is off.

This may be the result of a user action, toggle() slot activation, or because setOn() was called.

See also clicked().

Example: listbox/listbox.cpp.

Property Documentation

QKeySequence accel

This property holds the accelerator associated with the button.

This property is 0 if there is no accelerator set. If you set this property to 0 then any current accelerator is removed.

Set this property's value with setAccel() and get this property's value with accel().

bool autoMask

This property holds whether the radio button is automatically masked.

See also QWidget::autoMask.

bool autoRepeat

This property holds whether autoRepeat is enabled.

If autoRepeat is enabled then the clicked() signal is emitted at regular intervals if the button is down. This property has no effect on toggle buttons. autoRepeat is off by default.

Set this property's value with setAutoRepeat() and get this property's value with autoRepeat().

bool checked

This property holds whether the radio button is checked.

This property will not effect any other radio buttons unless they have been placed in the same QButtonGroup. The default value is FALSE (unchecked).

Set this property's value with setChecked() and get this property's value with isChecked().

QPixmap pixmap

This property holds the pixmap shown on the button.

If the pixmap is monochrome (i.e., it is a QBitmap or its depth is 1) and it does not have a mask, this property will set the pixmap to be its own mask. The purpose of this is to draw transparent bitmaps which are important for toggle buttons, for example.

pixmap() returns 0 if no pixmap was set.

Set this property's value with setPixmap() and get this property's value with pixmap().

QString text

This property holds the text shown on the button.

This property will return a null string if the button has no text. If the text has an ampersand ('&') in it, then an accelerator is automatically created for it using the character after the '&' as the accelerator key.

There is no default text.

Set this property's value with setText() and get this property's value with text().

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


qradiobutton.h Include File

qradiobutton.h

This is the verbatim text of the qradiobutton.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qradiobutton.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QRadioButton class
**
** Created : 940222
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QRADIOBUTTON_H
#define QRADIOBUTTON_H

#ifndef QT_H
#include "qbutton.h"
#endif // QT_H

#ifndef QT_NO_RADIOBUTTON

class Q_EXPORT QRadioButton : public QButton
{
    Q_OBJECT
    Q_PROPERTY( bool checked READ isChecked WRITE setChecked )
    Q_OVERRIDE( bool autoMask DESIGNABLE true SCRIPTABLE true )

public:
    QRadioButton( QWidget *parent, const char* name=0 );
    QRadioButton( const QString &text, QWidget *parent, const char* name=0 );

    bool    isChecked() const;

    QSize    sizeHint() const;

public slots:
    virtual void    setChecked( bool check );

protected:
    bool    hitButton( const QPoint & ) const;
    void    drawButton( QPainter * );
    void    drawButtonLabel( QPainter * );
    void    updateMask();

    void    resizeEvent( QResizeEvent* );

private:
    void    init();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QRadioButton( const QRadioButton & );
    QRadioButton &operator=( const QRadioButton & );
#endif
};

inline bool QRadioButton::isChecked() const
{ return isOn(); }

#endif // QT_NO_RADIOBUTTON

#endif // QRADIOBUTTON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QRadioButton Member List

Complete Member List for QRadioButton

This is the complete list of member functions for QRadioButton, including inherited members.

  • QRadioButton()
  • accel()
  • acceptDrops()
  • adjustSize()
  • animateClick()
  • autoMask()
  • autoRepeat()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawButton()
  • drawButtonLabel()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • group()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • hitButton()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isChecked()
  • isDesktop()
  • isDialog()
  • isDown()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusiveToggle()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isOn()
  • isPopup()
  • isToggleButton()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setAutoRepeat()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setChecked()
  • setCursor()
  • setDisabled()
  • setDown()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOn()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setState()
  • setStyle()
  • setTabOrder()
  • setText()
  • setToggleButton()
  • setToggleType()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • state()
  • stateChanged()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • timerEvent()
  • toggle()
  • toggleType()
  • toggled()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QRangeControl类

QRangeControl类参考

QRangeControl类提供了一个范围内的一个整数值。 详情请见……

#include <qrangecontrol.h>

由QDial、QScrollBar、QSlider和QSpinBox继承。

所有成员函数的列表。

公有成员

  • QRangeControl ()
  • QRangeControl ( int minValue, int maxValue, int lineStep, int pageStep, int value )
  • virtual ~QRangeControl ()
  • int value () const
  • void setValue ( int value )
  • void addPage ()
  • void subtractPage ()
  • void addLine ()
  • void subtractLine ()
  • int minValue () const
  • int maxValue () const
  • void setRange ( int minValue, int maxValue )
  • void setMinValue ( int minVal )
  • void setMaxValue ( int maxVal )
  • int lineStep () const
  • int pageStep () const
  • void setSteps ( int lineStep, int pageStep )
  • int bound ( int v ) const

保护成员

  • int positionFromValue ( int logical_val, int span ) const
  • int valueFromPosition ( int pos, int span ) const
  • void directSetValue ( int value )
  • int prevValue () const
  • virtual void valueChange ()
  • virtual void rangeChange ()
  • virtual void stepChange ()

详细描述

QRangeControl类提供了一个范围内的一个整数值。

尽管QRangeControl最初始是为了QScrollBar窗口部件而设计的，但它也可以和像QSlider和QSpinBox这样的其它窗口部件关联使用。这里是这个类中五个主要概念：

  1. 当前值。这是QRangeControl所维护的一个有限制的整数。value()返回这个值，并且可以通过包括setValue()的几个函数来设置它。

  2. 最小值。这是value()可以返回的最小值。minValue()可以返回这个值，并且可以通过setRange()或构造函数来设置它。

  3. 最大值。这是value()可以返回的最大值。maxValue()可以返回这个值，并且可以通过setRange()或构造函数来设置它。

  4. 线步。这是QRangeControl所提供的比较小的两个自然步的差并且通常与用户按下方向键进行关联。线步可以由lineStep()返回并且可以使用setSteps()来设置。addLine()和subtractLine()这两个函数分别地用来给当前值增加或减少lineStep()。

  5. 页步。这是QRangeControl所提供的比较大的两个自然步的差并且通常与用户按下PageUp或PageDown进行关联。页步可以由pageStep()返回并且可以使用setSteps()来设置。addPage()和substractPage()这两个函数分别地用来给当前值增加或减少pageStep()。

单位（1）可以被看做事第三种步长。setValue()可以让你设置当前值为允许范围内的任何一个整数，对于n这一整数值，而不仅仅是minValue() + n * lineStep()。一些窗口部件也允许用户设置为任意值，而其它的也许只提供了lineStep()或pageStep()的倍数。

QRangeControl提供了适用于在屏幕上表示范围控制的更新和信号的发射的三个虚函数，叫做valueChange()、rangeChange()和stepChange()。

QRangeControl也提供了一个叫做bound()的函数，它可以强制任意整数变为这个范围控制所允许的范围中。

我们建议所有继承QRangeControl的窗口部件都至少提供一个叫做valueChanged()的信号，一些窗口部件也许需要提供addStep()、addPage()、substractStep()和substractPage()做为槽。

注意如果你计划实现一个使用QRangeControl的窗口部件，你不得不使用多重继承，因为QRangeControl并不是继承于QWidget的。

也可以参考杂项类。

成员函数文档

QRangeControl::QRangeControl ()

构造一个最小值为0、最大值为99、线步为1、页步为10并且初始值为0的范围控制。

QRangeControl::QRangeControl ( int minValue, int maxValue, int lineStep, int pageStep, int value )

构造一个最小值为minValue、最大值为maxValue、线步为lineStep、页步为pageStep并且初始值为value（已经使用bound()被保证在允许范围内）的范围控制。

QRangeControl::~QRangeControl () [虚]

销毁这个范围控制。

void QRangeControl::addLine ()

与setValue( value() + lineStep() )相同。

如果值发生改变，那么valueChange()被调用。

也可以参考subtractLine()、addPage()和setValue()。

void QRangeControl::addPage ()

与setValue( value() + pageStep() )相同。

如果值发生改变，那么valueChange()被调用。

也可以参考subtractPage()、addLine()和setValue()。

int QRangeControl::bound ( int v ) const

强制值v进入从minValue()到maxValue()所确定的范围内，并且返回结果。

这个函数的提供可以让你很容易地强制转换其它数值而不是value()进入允许范围。你不需要为了QRangeControl本身而调用它。

也可以参考setValue()、value()、minValue()和maxValue()。

void QRangeControl::directSetValue ( int value ) [保护]

不调用valueChange()而直接设置范围控制的值为value。

强制新value进入合法范围。

你将很少用到这个函数。可是，如果你想在valueChange()的重载函数中改变范围控制的值，而setValue()将会再次调用valueChange()，这时你就必须使用directSetValue()来替代它。

也可以参考setValue()。

int QRangeControl::lineStep () const

返回当前线步。

也可以参考setSteps()和pageStep()。

int QRangeControl::maxValue () const

返回当前范围的最大值。

也可以参考setMaxValue()、setRange()和minValue()。

int QRangeControl::minValue () const

返回当前范围的最小值。

也可以参考setMinValue()、setRange()和maxValue()。

int QRangeControl::pageStep () const

返回当前页步。

也可以参考setSteps()和lineStep()。

int QRangeControl::positionFromValue ( int logical_val, int span ) const [保护]

把logical_val转换为一个象素位置。minValue()映射为0，maxValue()映射为span并且其它值就被均匀地分布在两者之间。

这个函数可以处理整个整数范围而不会溢出。

当绘制一个范围控制时，比如在屏幕上的QScrollBar，调用这个函数是很有用的。

也可以参考valueFromPosition()。

int QRangeControl::prevValue () const [保护]

返回范围控制的上一个值。“上一个值”指的是在最后一次值的变化之前出现的值。设置一个新的范围也许会影响到值，因为这个值被强制在特定的范围之内。当范围控制被初始创建时，这个值和value()一样。

如果你调用setRange()导致当前值发生改变得话，prevValue()可能在当前合法范围之外。例如，如果一个范围是[0, 1000]并且当前值为500，setRange(0, 400)将会使value()返回400并且prevValue()返回500。

也可以参考value()和setRange()。

void QRangeControl::rangeChange () [虚 保护]

只要范围控制的范围发生改变，这个虚函数就会被调用。当范围发生改变时，你想被通知的话，你可以重新实现它。默认实现是什么都不做。

注意在范围发生改变之后，这个方法才被调用。

也可以参考setRange()、valueChange()和stepChange()。

在QDial、QSlider和QSpinBox中被重新实现。

void QRangeControl::setMaxValue ( int maxVal )

设置范围的当前最大值为maxVal。

如果需要，需要minValue()将会被调整来确保范围仍然有效。

也可以参考maxValue()和setMinValue()。

void QRangeControl::setMinValue ( int minVal )

设置范围的当前最小值为minValue。

如果需要，需要maxValue()将会被调整来确保范围仍然有效。

也可以参考minValue()和setMaxValue()。

void QRangeControl::setRange ( int minValue, int maxValue )

设置范围控制的最小值为minValue，最大值为maxValue。

如果新的最小值和最大值中的一个或两个与原先设定的不同，调用虚函数rangeChange()。如果因为当前值在新的范围之外，它需要被调整，那么调用虚函数valueChange()。

如果maxValue小于minValue，minValue变为合法的。

也可以参考minValue()和maxValue()。

实例：listbox/listbox.cpp、t12/lcdrange.cpp、t5/main.cpp、t6/main.cpp、 t8/lcdrange.cpp和xform/xform.cpp。

void QRangeControl::setSteps ( int lineStep, int pageStep )

设置范围控制的线步为lineStep，页步为pageStep。

如果新的线步和/或页步与以前的设定不同，调用虚函数stepChange()。

也可以参考lineStep()、pageStep()和setRange()。

void QRangeControl::setValue ( int value )

设定范围控制的值为value，并且强制它变为在合法范围内的值。

如果新的值和以前的值不同，调用虚函数valueChange()。旧的值也可以通过prevValue()得到。

也可以参考value().

void QRangeControl::stepChange () [虚 保护]

只要范围控制的线步/页步设置发生变化，这个虚函数就被调用。如果你需要在步长发生变化时，你想被通知的话，你可以重新实现它。默认实现是什么都不做。

注意在步长设置被改变之后，这个方法才被调用。

也可以参考setSteps()、rangeChange()和valueChange()。

void QRangeControl::subtractLine ()

与setValue( value() - lineStep() )相同。

如果值发生改变，那么valueChange()被调用。

也可以参考addLine()、subtractPage()和setValue()。

void QRangeControl::subtractPage ()

与setValue( value() - pageStep() )相同。

如果值发生改变，那么valueChange()被调用。

也可以参考addPage()、subtractLine()和setValue()。

int QRangeControl::value () const

返回当前范围控制的值。这个值已经被保证在[minValue(), maxValue()]范围内。

也可以参考setValue()和prevValue()。

void QRangeControl::valueChange () [虚 保护]

只要值发生变化，这个虚函数就被调用。如果你需要在值发生变化时，你想被通知的话，你可以重新实现它。默认实现是什么都不做。

注意在值发生变化之后，这个方法才被调用。以前的值可以通过prevValue()来得到。

也可以参考setValue()、addPage()、subtractPage()、addLine()、subtractLine()、rangeChange()和stepChange()。

在QDial、QSlider和QSpinBox中被重新实现。

int QRangeControl::valueFromPosition ( int pos, int span ) const [保护]

把像素位置pos转换为值。0映射为minValue()，span映射为maxValue()，并且其它值被平均分布在这两者之间。

这个函数可以用来操作整个整数范围而不会溢出。

当你真正实现一个范围控制窗口部件时，比如QScrollBar和想处理鼠标按下事件时，调用这个函数是很有用的。这个函数会映射屏幕坐标为合法值。

也可以参考positionFromValue()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qrangecontrol.h包含文件

qrangecontrol.h

这里是qrangecontrol.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qrangecontrol.h   3.0.5   edited Apr 9 15:48 $
**
** Definition of QRangeControl class
**
** Created : 940427
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QRANGECONTROL_H
#define QRANGECONTROL_H

#ifndef QT_H
#include "qglobal.h"
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_RANGECONTROL

class QRangeControlPrivate;

class Q_EXPORT QRangeControl
{
public:
    QRangeControl();
    QRangeControl( int minValue, int maxValue,
           int lineStep, int pageStep, int value );
    virtual ~QRangeControl();
    int		value()		const;
    void	setValue( int );
    void	addPage();
    void	subtractPage();
    void	addLine();
    void	subtractLine();

    int		minValue()	const;
    int		maxValue()	const;
    void	setRange( int minValue, int maxValue );
    void	setMinValue( int minVal );
    void	setMaxValue( int minVal );

    int		lineStep()	const;
    int		pageStep()	const;
    void	setSteps( int line, int page );

    int		bound( int ) const;

protected:
    int		positionFromValue( int val, int space ) const;
    int		valueFromPosition( int pos, int space ) const;
    void	directSetValue( int val );
    int		prevValue()	const;

    virtual void valueChange();
    virtual void rangeChange();
    virtual void stepChange();

private:
    int		minVal, maxVal;
    int		line, page;
    int		val, prevVal;

    QRangeControlPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QRangeControl( const QRangeControl & );
    QRangeControl &operator=( const QRangeControl & );
#endif
};

inline int QRangeControl::value() const
{ return val; }

inline int QRangeControl::prevValue() const
{ return prevVal; }

inline int QRangeControl::minValue() const
{ return minVal; }

inline int QRangeControl::maxValue() const
{ return maxVal; }

inline int QRangeControl::lineStep() const
{ return line; }

inline int QRangeControl::pageStep() const
{ return page; }

#endif // QT_NO_RANGECONTROL

#ifndef QT_NO_SPINWIDGET

class QSpinWidgetPrivate;
class Q_EXPORT QSpinWidget : public QWidget
{
    Q_OBJECT
public:
    QSpinWidget( QWidget* parent=0, const char* name=0 );
    ~QSpinWidget();

    void 	setEditWidget( QWidget * widget );
    QWidget * 	editWidget();

    QRect upRect() const;
    QRect downRect() const;

    void setUpEnabled( bool on );
    void setDownEnabled( bool on );

    bool isUpEnabled() const;
    bool isDownEnabled() const;

    enum ButtonSymbols { UpDownArrows, PlusMinus };
    virtual void	setButtonSymbols( ButtonSymbols bs );
    ButtonSymbols	buttonSymbols() const;

    void arrange();

signals:
    void stepUpPressed();
    void stepDownPressed();

public slots:
    void stepUp();
    void stepDown();

protected:
    void mousePressEvent( QMouseEvent *e );
    void resizeEvent( QResizeEvent* ev );
    void mouseReleaseEvent( QMouseEvent *e );
    void mouseMoveEvent( QMouseEvent *e );
#ifndef QT_NO_WHEELEVENT
    void wheelEvent( QWheelEvent * );
#endif
    void styleChange( QStyle& );
    void paintEvent( QPaintEvent * );
    void enableChanged( bool old );
    void windowActivationChange( bool );

private slots:
    void timerDone();
    void timerDoneEx();

private:
    QSpinWidgetPrivate * d;

    void updateDisplay();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSpinWidget( const QSpinWidget& );
    QSpinWidget& operator=( const QSpinWidget& );
#endif
};

#endif // QT_NO_SPINWIDGET

#endif // QRANGECONTROL_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QRangeControld成员列表

完整的QRangeControl成员列表

这里是QRangeControl成员函数的完整列表，包括继承的成员。

  • QRangeControl()
  • ~QRangeControl()
  • addLine()
  • addPage()
  • bound()
  • directSetValue()
  • lineStep()
  • maxValue()
  • minValue()
  • pageStep()
  • positionFromValue()
  • prevValue()
  • rangeChange()
  • setMaxValue()
  • setMinValue()
  • setRange()
  • setSteps()
  • setValue()
  • stepChange()
  • subtractLine()
  • subtractPage()
  • value()
  • valueChange()
  • valueFromPosition()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QRect类

QRect类参考

QRect类定了平面上的矩形。 详情请见……

#include <qrect.h>

所有成员函数的列表。

公有成员

  • QRect ()
  • QRect ( const QPoint & topLeft, const QPoint & bottomRight )
  • QRect ( const QPoint & topLeft, const QSize & size )
  • QRect ( int left, int top, int width, int height )
  • bool isNull () const
  • bool isEmpty () const
  • bool isValid () const
  • QRect normalize () const
  • int left () const
  • int top () const
  • int right () const
  • int bottom () const
  • QCOORD & rLeft ()
  • QCOORD & rTop ()
  • QCOORD & rRight ()
  • QCOORD & rBottom ()
  • int x () const
  • int y () const
  • void setLeft ( int pos )
  • void setTop ( int pos )
  • void setRight ( int pos )
  • void setBottom ( int pos )
  • void setX ( int x )
  • void setY ( int y )
  • QPoint topLeft () const
  • QPoint bottomRight () const
  • QPoint topRight () const
  • QPoint bottomLeft () const
  • QPoint center () const
  • void rect ( int * x, int * y, int * w, int * h ) const
  • void coords ( int * xp1, int * yp1, int * xp2, int * yp2 ) const
  • void moveTopLeft ( const QPoint & p )
  • void moveBottomRight ( const QPoint & p )
  • void moveTopRight ( const QPoint & p )
  • void moveBottomLeft ( const QPoint & p )
  • void moveCenter ( const QPoint & p )
  • void moveBy ( int dx, int dy )
  • void setRect ( int x, int y, int w, int h )
  • void setCoords ( int xp1, int yp1, int xp2, int yp2 )
  • void addCoords ( int xp1, int yp1, int xp2, int yp2 )
  • QSize size () const
  • int width () const
  • int height () const
  • void setWidth ( int w )
  • void setHeight ( int h )
  • void setSize ( const QSize & s )
  • QRect operator| ( const QRect & r ) const
  • QRect operator& ( const QRect & r ) const
  • QRect & operator|= ( const QRect & r )
  • QRect & operator&= ( const QRect & r )
  • bool contains ( const QPoint & p, bool proper = FALSE ) const
  • bool contains ( int x, int y, bool proper = FALSE ) const
  • bool contains ( const QRect & r, bool proper = FALSE ) const
  • QRect unite ( const QRect & r ) const
  • QRect intersect ( const QRect & r ) const
  • bool intersects ( const QRect & r ) const

相关函数

  • bool operator== ( const QRect & r1, const QRect & r2 )
  • bool operator!= ( const QRect & r1, const QRect & r2 )
  • QDataStream & operator<< ( QDataStream & s, const QRect & r )
  • QDataStream & operator>> ( QDataStream & s, QRect & r )

详细描述

QRect类定了平面上的矩形。

一个矩形在内部是由左上角和右下角表示的，但是通常它所表达到是一个左上角和一个大小。

坐标类型是QCOORD（和int一样在qwindowdefs.h中定义的）。QCOORD的最小值是QCOORD_MIN（-2147483648），最大值是QCOORD_MAX（2147483647）。

注意矩形的大小（宽和高）也许与你通常所用的所有不同。如果左上角和右下角相同，那么这个矩形的宽和高都为1。

通常情况下，width = right - left + 1并且height = bottom - top + 1。我们这样设计是因为这样就可以使矩形空间可以用在绘制函数中，它的宽高就说明了所要绘制的象素。例如，我们画一个宽和高都为1的矩形为一个单一点象素。

默认坐标系统的原点(0,0)在左上角。y轴的正方向向下，并且x轴的正方向从左到右。

一个QRect可以用一组上、左、宽、高四个整数，或者从两个QPoint或者从一个QPoint和一个QSize来构造。创建之后，空间可以被改变，比如使用setLeft()、setRight()、setTop()和setBottom()，或者通过设置，比如setWidth()、setHeight()和setSize()。空间也可以通过移动函数来改变，比如moveBy()、moveCenter()和moveBottomRight()等等。你也可以用addCoords()给矩形加上坐标。

你也可以通过contains()测试来看一个QRect是否包含一个特定点。你也可以通过intersects()测试来看两个QRect是否相交（也可以参考intersect()）。可以使用unite()来获得两个QRect的边界长方形。

也可以参考QPoint、QSize、图形类和图像处理类。

成员函数文档

QRect::QRect ()

构造一个无效的矩形。

QRect::QRect ( const QPoint & topLeft, const QPoint & bottomRight )

构造一个左上角为topLeft，右下角为bottomRight的矩形。

QRect::QRect ( const QPoint & topLeft, const QSize & size )

构造一个左上角为topLeft并且矩形大小为size的矩形。

QRect::QRect ( int left, int top, int width, int height )

构造一个上、左、宽、高分别为top、left、width和height的矩形。

实例（创建三个同样的矩形）：

        QRect r1( QPoint(100,200), QPoint(110,215) );
        QRect r2( QPoint(100,200), QSize(11,16) );
        QRect r3( 100, 200, 11, 16 );

void QRect::addCoords ( int xp1, int yp1, int xp2, int yp2 )

分别给矩形已经存在的坐标加上xp1、yp1、xp2和yp2。

int QRect::bottom () const

返回矩形的下坐标。

也可以参考top()、setBottom()、bottomLeft()和bottomRight()。

实例：desktop/desktop.cpp、helpviewer/helpwindow.cpp、qfd/fontdisplayer.cpp、scribble/scribble.cpp和themes/wood.cpp。

QPoint QRect::bottomLeft () const

返回矩形的左下位置。

也可以参考moveBottomLeft()、bottomRight()、topLeft()、topRight()、bottom()和left()。

实例：tictac/tictac.cpp。

QPoint QRect::bottomRight () const

返回矩形的右下位置。

也可以参考moveBottomRight()、bottomLeft()、topLeft()、topRight()、bottom()和right()。

实例：tictac/tictac.cpp。

QPoint QRect::center () const

返回矩形中心点。

也可以参考moveCenter()、topLeft()、topRight()、bottomLeft()和bottomRight()。

实例：tooltip/tooltip.cpp。

bool QRect::contains ( const QPoint & p, bool proper = FALSE ) const

如果点p在矩形内或者在矩形边缘上，返回真，否则返回假。

如果proper为真，这个函数只有在p在矩形里面时（不在边界上）的情况下，返回真。

实例：t14/cannon.cpp。

bool QRect::contains ( int x, int y, bool proper = FALSE ) const

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

如果点x、y在矩形内，返回真，否则返回假。

如果proper为真，这个函数只有在p在矩形里面时（不在边界上）的情况下，返回真。

bool QRect::contains ( const QRect & r, bool proper = FALSE ) const

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

如果矩形r在这个矩形里面，返回真，否则返回假。

如果proper为真，这个函数只有在p在矩形里面时（不在边界上）的情况下，返回真。

也可以参考unite()、intersect()和intersects()。

void QRect::coords ( int * xp1, int * yp1, int * xp2, int * yp2 ) const

提取矩形的参数作为左上点*xp1、*yp1和右下点*xp2、*yp2。

也可以参考setCoords()和rect()。

实例：themes/metal.cpp和themes/wood.cpp。

int QRect::height () const

返回矩形的高。这个高包括左和下边界，比如height = bottom - top + 1。

也可以参考width()、size()和setHeight()。

实例：aclock/aclock.cpp、desktop/desktop.cpp、movies/main.cpp、scribble/scribble.cpp、themes/metal.cpp、themes/wood.cpp和xform/xform.cpp。

QRect QRect::intersect ( const QRect & r ) const

返回这个矩形和矩形r交集。r.intersect(s)与r&s是相同的。

bool QRect::intersects ( const QRect & r ) const

如果这个矩形和矩形r相交（至少两个矩形有一个相同象素），返回真，否则返回假。

也可以参考intersect()和contains()。

实例：t11/cannon.cpp、t12/cannon.cpp、t13/cannon.cpp和t14/cannon.cpp。

bool QRect::isEmpty () const

如果这个矩形是空的，返回真，否则返回假。

一个空的矩形的left()>right()或者top()>bottom()。

一个空矩形是无效的。isEmpty()==!isValid()

也可以参考isNull()和isValid()。

bool QRect::isNull () const

如果一个矩形是零矩形，返回真，否则返回假。

一个零矩形的宽和高都设置为0，并且right()==left()-1并且bottom()==top()-1。

注意如果right()==left()并且bottom()==top()，那么这个矩形的宽和高都为1。

一个零矩形也是空的。

一个零矩形是无效的。

也可以参考isEmpty()和isValid()。

bool QRect::isValid () const

Returns TRUE if the rectangle is valid or FALSE if it is invalid (empty)。 如果一个矩形是有效的，反会诊，否则如果它是无效的（空的）就返回假。

一个有效的矩形中，left()<=right()和top()<=bottom()。

isValid()==!isEmpty()

也可以参考isNull()、isEmpty()和normalize()。

实例：themes/metal.cpp和tooltip/tooltip.cpp。

int QRect::left () const

返回矩形的左坐标.与x()相同.

也可以参考x()、top()、right()、setLeft()、topLeft()和bottomLeft()。

实例：aclock/aclock.cpp、desktop/desktop.cpp、qfd/fontdisplayer.cpp、scribble/scribble.cpp、tictac/tictac.cpp和xform/xform.cpp。

void QRect::moveBottomLeft ( const QPoint & p )

设置矩形的左下坐标为p，而大小不被改变。

也可以参考bottomLeft()、moveBottomRight()、moveTopLeft()、moveTopRight()、setBottom()和setLeft()。

实例：t10/cannon.cpp。

void QRect::moveBottomRight ( const QPoint & p )

设置矩形的右下坐标为p，而大小不被改变。

也可以参考bottomRight()、moveBottomLeft()、moveTopLeft()、moveTopRight()、setBottom()和setRight()。

void QRect::moveBy ( int dx, int dy )

矩形相对于当前位置在x轴上移动dx，在y轴上移动dy。（正值时，向右和/或下移动矩形。）

实例：helpviewer/helpwindow.cpp、themes/wood.cpp和xform/xform.cpp。

void QRect::moveCenter ( const QPoint & p )

设置矩形的中点为p，而大小不被改变。

也可以参考center()、moveTopLeft()、moveTopRight()、moveBottomLeft()和moveBottomRight()。

实例：t11/cannon.cpp和t12/cannon.cpp。

void QRect::moveTopLeft ( const QPoint & p )

设置矩形的左上坐标为p，而大小不被改变。

也可以参考topLeft()、moveTopRight()、moveBottomLeft()、moveBottomRight()、setTop()和setLeft()。

实例：xform/xform.cpp。

void QRect::moveTopRight ( const QPoint & p )

设置矩形的右上坐标为p，而大小不被改变。

也可以参考topRight()、moveTopLeft()、moveBottomLeft()、moveBottomRight()、setTop()和setRight()。

QRect QRect::normalize () const

返回一个标准化的矩形，比如，一个宽高都为非负的矩形。

如果left()>right()，交换左右，并且如果top()>bottom()，交换上下。

也可以参考isValid()。

实例：scribble/scribble.cpp。

QRect QRect::operator& ( const QRect & r ) const

返回这个矩形和矩形r的交集。

如果没有交集，返回一个空矩形。

也可以参考operator&=()、operator|()、isEmpty()、intersects()和contains()。

QRect & QRect::operator&= ( const QRect & r )

这个矩形和矩形r的交集。

QRect QRect::operator| ( const QRect & r ) const

返回这个矩形和矩形r的边界矩形。

一个非空矩形和一个空矩形或者一个无效矩形的边界矩形定义为一个非空矩形。

也可以参考operator|=()、operator&()、intersects()和contains()。

QRect & QRect::operator|= ( const QRect & r )

这个矩形和矩形r的并集。

QCOORD & QRect::rBottom ()

返回矩形的下坐标引用。

也可以参考rLeft()、rTop()和rRight()。

QCOORD & QRect::rLeft ()

返回矩形的左坐标引用。

也可以参考rTop()、rRight()和rBottom()。

QCOORD & QRect::rRight ()

返回矩形的右坐标引用。

也可以参考rLeft()、rTop()和rBottom()。

QCOORD & QRect::rTop ()

返回矩形的上坐标引用。

也可以参考rLeft()、rRight()和rBottom()。

void QRect::rect ( int * x, int * y, int * w, int * h ) const

提取矩形参数为位置*x、*y和宽*w和高*h。

也可以参考setRect()和coords()。

实例：themes/metal.cpp和themes/wood.cpp。

int QRect::right () const

返回矩形的右坐标。

也可以参考left()、setRight()、topRight()和bottomRight()。

实例：customlayout/flow.cpp、desktop/desktop.cpp、helpviewer/helpwindow.cpp、qfd/fontdisplayer.cpp、scribble/scribble.cpp、t11/cannon.cpp和themes/wood.cpp。

void QRect::setBottom ( int pos )

设置矩形的下边缘为pos。也许改变高度，但决不会改变矩形的上边缘。

也可以参考bottom()、setTop()和setHeight()。

实例：scribble/scribble.cpp。

void QRect::setCoords ( int xp1, int yp1, int xp2, int yp2 )

设置矩形的左上角的坐标为(xp1,yp1)，并且它的右下角坐标为(xp2,yp2)。

也可以参考coords()和setRect()。

void QRect::setHeight ( int h )

设置矩形的高为h。上边缘没有被移动，但是下边缘也许被移动。

也可以参考height()、setTop()、setBottom()和setSize()。

实例：desktop/desktop.cpp。

void QRect::setLeft ( int pos )

设置矩形的左边缘为pos。也许改变宽度，但决不会改变矩形的右边缘。

与setX()一样。

也可以参考left()、setTop()和setWidth()。

实例：scribble/scribble.cpp。

void QRect::setRect ( int x, int y, int w, int h )

设置矩形左上角坐标为(x,y)，并且它的大小为(w,h)。

也可以参考rect()和setCoords()。

实例：themes/wood.cpp。

void QRect::setRight ( int pos )

设置矩形的右边缘为pos。也许改变宽度，但决不会改变矩形的左边缘。

也可以参考right()、setLeft()和setWidth()。

实例：scribble/scribble.cpp。

void QRect::setSize ( const QSize & s )

设置矩形的大小为s。左上角不被移动。

也可以参考size()、setWidth()和setHeight()。

实例：xform/xform.cpp。

void QRect::setTop ( int pos )

设置矩形的上边缘为pos。也许改变高度，但决不会改变矩形的下边缘。

与setY()一样。

也可以参考top()、setBottom()和setHeight()。

实例：scribble/scribble.cpp。

void QRect::setWidth ( int w )

Sets the width of the rectangle to w。 The right edge is changed, but not the left edge. 设置矩形的宽为w。右边缘被改变，但是左边缘不会被改变。

也可以参考width()、setLeft()、setRight()和setSize()。

实例：desktop/desktop.cpp。

void QRect::setX ( int x )

设置矩形的x位置（它的左边）为x。也许会改变宽度，但是不会改变矩形的右边界。

与setLeft()一样。

也可以参考x()和setY()。

void QRect::setY ( int y )

设置矩形的y位置（它的上边）为y。也许会改变高度，但是不会改变矩形的下边界。

与setTop()一样。

也可以参考y()和setX()。

QSize QRect::size () const

返回矩形的大小。

也可以参考width()和height()。

实例：desktop/desktop.cpp、movies/main.cpp和t10/cannon.cpp。

int QRect::top () const

返回矩形的上坐标。与y()一样。

也可以参考y()、left()、bottom()、setTop()、topLeft()和topRight()。

实例：aclock/aclock.cpp、desktop/desktop.cpp、helpviewer/helpwindow.cpp、scribble/scribble.cpp、themes/wood.cpp、tictac/tictac.cpp和xform/xform.cpp。

QPoint QRect::topLeft () const

返回矩形的左上角位置。

也可以参考moveTopLeft()、topRight()、bottomLeft()、bottomRight()、left()和top()。

实例：t10/cannon.cpp和tictac/tictac.cpp。

QPoint QRect::topRight () const

返回矩形的右上角位置。

也可以参考moveTopRight()、topLeft()、bottomLeft()、bottomRight()、top()和right()。

实例：tictac/tictac.cpp。

QRect QRect::unite ( const QRect & r ) const

返回这个矩形和矩形r的边界矩形。r.unite(s)与r|s相同。

实例：t11/cannon.cpp、t12/cannon.cpp和xform/xform.cpp。

int QRect::width () const

返回矩形的宽度。宽度包括左和右边界，比如width = right - left + 1。

也可以参考height()、size()和setHeight()。

实例：aclock/aclock.cpp、customlayout/border.cpp、desktop/desktop.cpp、movies/main.cpp、themes/metal.cpp、themes/wood.cpp和xform/xform.cpp。

int QRect::x () const

返回矩形的左坐标。与left()一样。

也可以参考left()、y()和setX()。

实例：customlayout/border.cpp、desktop/desktop.cpp、movies/main.cpp、scribble/scribble.cpp、t12/cannon.cpp、themes/metal.cpp和themes/wood.cpp。

int QRect::y () const

返回矩形的上坐标。与top()一样。

也可以参考top()、x()和setY()。

实例：desktop/desktop.cpp、movies/main.cpp、scribble/scribble.cpp、t12/cannon.cpp、t14/cannon.cpp、themes/metal.cpp和themes/wood.cpp。

相关函数

bool operator!= ( const QRect & r1, const QRect & r2 )

如果r1和r2不同，返回真，否则返回假。

QDataStream & operator<< ( QDataStream & s, const QRect & r )

写这个QRectr到流s中，并且返回这个流的引用。

也可以参考QDataStream操作符的格式。

bool operator== ( const QRect & r1, const QRect & r2 )

如果r1和r2相等，返回真，否则返回假。

QDataStream & operator>> ( QDataStream & s, QRect & r )

从流s读一个QRect到r中，并且返回这个流的引用。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qrect.h包含文件

qrect.h

这里是qrect.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qrect.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QRect class
**
** Created : 931028
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QRECT_H
#define QRECT_H

#ifndef QT_H
#include "qsize.h"
#endif // QT_H

#if defined(topLeft)
#error "Macro definition of topLeft conflicts with QRect"
// don't just silently undo people's defines: #undef topLeft
#endif

class Q_EXPORT QRect					// rectangle class
{
public:
    QRect()	{ x1 = y1 = 0; x2 = y2 = -1; }
    QRect( const QPoint &topleft, const QPoint &bottomright );
    QRect( const QPoint &topleft, const QSize &size );
    QRect( int left, int top, int width, int height );

    bool   isNull()	const;
    bool   isEmpty()	const;
    bool   isValid()	const;
    QRect  normalize()	const;

    int	   left()	const;
    int	   top()	const;
    int	   right()	const;
    int	   bottom()	const;

    QCOORD &rLeft();
    QCOORD &rTop();
    QCOORD &rRight();
    QCOORD &rBottom();

    int	   x()		const;
    int	   y()		const;
    void   setLeft( int pos );
    void   setTop( int pos );
    void   setRight( int pos );
    void   setBottom( int pos );
    void   setX( int x );
    void   setY( int y );

    QPoint topLeft()	 const;
    QPoint bottomRight() const;
    QPoint topRight()	 const;
    QPoint bottomLeft()	 const;
    QPoint center()	 const;

    void   rect( int *x, int *y, int *w, int *h ) const;
    void   coords( int *x1, int *y1, int *x2, int *y2 ) const;

    void   moveTopLeft( const QPoint &p );
    void   moveBottomRight( const QPoint &p );
    void   moveTopRight( const QPoint &p );
    void   moveBottomLeft( const QPoint &p );
    void   moveCenter( const QPoint &p );
    void   moveBy( int dx, int dy );

    void   setRect( int x, int y, int w, int h );
    void   setCoords( int x1, int y1, int x2, int y2 );
    void   addCoords( int x1, int y1, int x2, int y2 );

    QSize  size()	const;
    int	   width()	const;
    int	   height()	const;
    void   setWidth( int w );
    void   setHeight( int h );
    void   setSize( const QSize &s );

    QRect  operator|(const QRect &r) const;
    QRect  operator&(const QRect &r) const;
    QRect&  operator|=(const QRect &r);
    QRect&  operator&=(const QRect &r);

    bool   contains( const QPoint &p, bool proper=FALSE ) const;
    bool   contains( int x, int y, bool proper=FALSE ) const;
    bool   contains( const QRect &r, bool proper=FALSE ) const;
    QRect  unite( const QRect &r ) const;
    QRect  intersect( const QRect &r ) const;
    bool   intersects( const QRect &r ) const;

    friend Q_EXPORT bool operator==( const QRect &, const QRect & );
    friend Q_EXPORT bool operator!=( const QRect &, const QRect & );

private:
#if defined(Q_OS_MAC)
    QCOORD y1;
    QCOORD x1;
    QCOORD y2;
    QCOORD x2;
#else
    QCOORD x1;
    QCOORD y1;
    QCOORD x2;
    QCOORD y2;
#endif
};

Q_EXPORT bool operator==( const QRect &, const QRect & );
Q_EXPORT bool operator!=( const QRect &, const QRect & );

/*****************************************************************************
  QRect stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QRect & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QRect & );
#endif

/*****************************************************************************
  QRect inline member functions
 *****************************************************************************/

inline QRect::QRect( int left, int top, int width, int height )
{
    x1 = (QCOORD)left;
    y1 = (QCOORD)top;
    x2 = (QCOORD)(left+width-1);
    y2 = (QCOORD)(top+height-1);
}

inline bool QRect::isNull() const
{ return x2 == x1-1 && y2 == y1-1; }

inline bool QRect::isEmpty() const
{ return x1 > x2 || y1 > y2; }

inline bool QRect::isValid() const
{ return x1 <= x2 && y1 <= y2; }

inline int QRect::left() const
{ return x1; }

inline int QRect::top() const
{ return y1; }

inline int QRect::right() const
{ return x2; }

inline int QRect::bottom() const
{ return y2; }

inline QCOORD &QRect::rLeft()
{ return x1; }

inline QCOORD & QRect::rTop()
{ return y1; }

inline QCOORD & QRect::rRight()
{ return x2; }

inline QCOORD & QRect::rBottom()
{ return y2; }

inline int QRect::x() const
{ return x1; }

inline int QRect::y() const
{ return y1; }

inline void QRect::setLeft( int pos )
{ x1 = (QCOORD)pos; }

inline void QRect::setTop( int pos )
{ y1 = (QCOORD)pos; }

inline void QRect::setRight( int pos )
{ x2 = (QCOORD)pos; }

inline void QRect::setBottom( int pos )
{ y2 = (QCOORD)pos; }

inline void QRect::setX( int x )
{ x1 = (QCOORD)x; }

inline void QRect::setY( int y )
{ y1 = (QCOORD)y; }

inline QPoint QRect::topLeft() const
{ return QPoint(x1, y1); }

inline QPoint QRect::bottomRight() const
{ return QPoint(x2, y2); }

inline QPoint QRect::topRight() const
{ return QPoint(x2, y1); }

inline QPoint QRect::bottomLeft() const
{ return QPoint(x1, y2); }

inline QPoint QRect::center() const
{ return QPoint((x1+x2)/2, (y1+y2)/2); }

inline int QRect::width() const
{ return  x2 - x1 + 1; }

inline int QRect::height() const
{ return  y2 - y1 + 1; }

inline QSize QRect::size() const
{ return QSize(x2-x1+1, y2-y1+1); }

inline bool QRect::contains( int x, int y, bool proper ) const
{
    if ( proper )
        return x > x1 && x < x2 &&
               y > y1 && y < y2;
    else
        return x >= x1 && x <= x2 &&
               y >= y1 && y <= y2;
}

#endif // QRECT_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QRect成员列表

完整的QRect成员列表

这里是QRect成员函数的完整列表，包括继承的成员。

  • QRect()
  • addCoords()
  • bottom()
  • bottomLeft()
  • bottomRight()
  • center()
  • contains()
  • coords()
  • height()
  • intersect()
  • intersects()
  • isEmpty()
  • isNull()
  • isValid()
  • left()
  • moveBottomLeft()
  • moveBottomRight()
  • moveBy()
  • moveCenter()
  • moveTopLeft()
  • moveTopRight()
  • normalize()
  • operator&()
  • operator&=()
  • operator|()
  • operator|=()
  • rBottom()
  • rLeft()
  • rRight()
  • rTop()
  • rect()
  • right()
  • setBottom()
  • setCoords()
  • setHeight()
  • setLeft()
  • setRect()
  • setRight()
  • setSize()
  • setTop()
  • setWidth()
  • setX()
  • setY()
  • size()
  • top()
  • topLeft()
  • topRight()
  • unite()
  • width()
  • x()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QRegExp Class

QRegExp Class Reference

The QRegExp class provides pattern matching using regular expressions. More...

#include <qregexp.h>

List of all member functions.

Public Members

  • QRegExp ()
  • QRegExp ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE )
  • QRegExp ( const QRegExp & rx )
  • ~QRegExp ()
  • QRegExp & operator= ( const QRegExp & rx )
  • bool operator== ( const QRegExp & rx ) const
  • bool operator!= ( const QRegExp & rx ) const
  • bool isEmpty () const
  • bool isValid () const
  • QString pattern () const
  • void setPattern ( const QString & pattern )
  • bool caseSensitive () const
  • void setCaseSensitive ( bool sensitive )
  • bool wildcard () const
  • void setWildcard ( bool wildcard )
  • bool minimal () const
  • void setMinimal ( bool minimal )
  • bool exactMatch ( const QString & str ) const
  • int match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const (obsolete)
  • int search ( const QString & str, int start = 0 ) const
  • int searchRev ( const QString & str, int start = -1 ) const
  • int matchedLength () const
  • QStringList capturedTexts ()
  • QString cap ( int nth = 0 )
  • int pos ( int nth = 0 )

Detailed Description

The QRegExp class provides pattern matching using regular expressions.

Regular expressions, or "regexps", provide a way to find patterns within text. This is useful in many contexts, for example:

  1. Validation. A regexp can be used to check whether a piece of text meets some criteria, e.g. is an integer or contains no whitespace.
  2. Searching. Regexps provide a much more powerful means of searching text than simple string matching does. For example we can create a regexp which says "find one of the words 'mail', 'letter' or 'correspondence' but not any of the words 'email', 'mailman' 'mailer', 'letterbox' etc."
  3. Search and Replace. A regexp can be used to replace a pattern with a piece of text, for example replace all occurrences of '&' with '&amp;' except where the '&' is already followed by 'amp;'.
  4. String Splitting. A regexp can be used to identify where a string should be split into its component fields, e.g. splitting tab-delimited strings.

We present a very brief introduction to regexps, a description of Qt's regexp language, some code examples, and finally the function documentation. QRegExp is modeled on Perl's regexp language, and also fully supports Unicode. QRegExp may also be used in the weaker 'wildcard' (globbing) mode which works in a similar way to command shells. A good text on regexps is Mastering Regular Expressions: Powerful Techniques for Perl and Other Tools by Jeffrey E. Friedl, ISBN 1565922573.

Experienced regexp users may prefer to skip the introduction and go directly to the relevant information.

  • Introduction
  • Characters and Abbreviations for Sets of Characters
  • Sets of Characters
  • Quantifiers
  • Capturing Text
  • Assertions
  • Wildcard Matching (globbing)
  • Notes for Perl Users
  • Code Examples

Introduction

Regexps are built up from expressions, quantifiers and assertions. The simplest form of expression is simply a character, e.g. x or 5. An expression can also be a set of characters. For example, [ABCD], will match an A or a B or a C or a D. As a shorthand we could write this as [A-D]. If we want to match any of the captital letters in the English alphabet we can write [A-Z]. A quantifier tells the regexp engine how many occurrences of the expression we want, e.g. x{1,1} means match an x which occurs at least once and at most once. We'll look at assertions and more complex expressions later.

Note that in general regexps cannot be used to check for balanced brackets or tags. For example if you want to match an opening html <b> and its closing </b> you can only use a regexp if you know that these tags are not nested; the html fragment, <b>bold <b>bolder</b></b> will not match as expected. If you know the maximum level of nesting it is possible to create a regexp that will match correctly, but for an unknown level of nesting regexps will fail.

We'll start by writing a regexp to match integers in the range 0 to 99. We will require at least one digit so we will start with [0-9]{1,1} which means match a digit exactly once. This regexp alone will match integers in the range 0 to 9. To match one or two digits we can increase the maximum number of occurrences so the regexp becomes [0-9]{1,2} meaning match a digit at least once and at most twice. However, this regexp as it stands will not match correctly. This regexp will match one or two digits within a string. To ensure that we match against the whole string we must use the anchor assertions. We need ^ (caret) which when it is the first character in the regexp means that the regexp must match from the beginning of the string. And we also need $ (dollar) which when it is the last character in the regexp means that the regexp must match until the end of the string. So now our regexp is ^[0-9]{1,2}$. Note that assertions, such as ^ and $, do not match any characters.

If you've seen regexps elsewhere they may have looked different from the ones above. This is because some sets of characters and some quantifiers are so common that they have special symbols to represent them. [0-9] can be replaced with the symbol \d. The quantifier to match exactly one occurrence, {1,1}, can be replaced with the expression itself. This means that x{1,1} is exactly the same as x alone. So our 0 to 99 matcher could be written ^\d{1,2}$. Another way of writing it would be ^\d\d{0,1}$, i.e. from the start of the string match a digit followed by zero or one digits. In practice most people would write it ^\d\d?$. The ? is a shorthand for the quantifier {0,1}, i.e. a minimum of no occurrences a maximum of one occurrence. This is used to make an expression optional. The regexp ^\d\d?$ means "from the beginning of the string match one digit followed by zero or one digits and then the end of the string".

Our second example is matching the words 'mail', 'letter' or 'correspondence' but without matching 'email', 'mailman', 'mailer', 'letterbox' etc. We'll start by just matching 'mail'. In full the regexp is, m{1,1}a{1,1}i{1,1}l{1,1}, but since each expression itself is automatically quantified by {1,1} we can simply write this as mail; an 'm' followed by an 'a' followed by an 'i' followed by an 'l'. The symbol '|' (bar) is used for alternation, so our regexp now becomes mail|letter|correspondence which means match 'mail' or 'letter' or 'correspondence'. Whilst this regexp will find the words we want it will also find words we don't want such as 'email'. We will start by putting our regexp in parentheses, (mail|letter|correspondence). Parentheses have two effects, firstly they group expressions together and secondly they identify parts of the regexp that we wish to capture. Our regexp still matches any of the three words but now they are grouped together as a unit. This is useful for building up more complex regexps. It is also useful because it allows us to examine which of the words actually matched. We need to use another assertion, this time \b "word boundary": \b(mail|letter|correspondence)\b. This regexp means "match a word boundary followed by the expression in parentheses followed by another word boundary". The \b assertion matches at a position in the regexp not a character in the regexp. A word boundary is any non-word character such as a space a newline or the beginning or end of the string.

For our third example we want to replace ampersands with the HTML entity '&amp;'. The regexp to match is simple: &, i.e. match one ampersand. Unfortunately this will mess up our text if some of the ampersands have already been turned into HTML entities. So what we really want to say is replace an ampersand providing it is not followed by 'amp;'. For this we need the negative lookahead assertion and our regexp becomes: &(?!amp;). The negative lookahead assertion is introduced with '(?!' and finishes at the ')'. It means that the text it contains, 'amp;' in our example, must not follow the expression that preceeds it.

Regexps provide a rich language that can be used in a variety of ways. For example suppose we want to count all the occurrences of 'Eric' and 'Eirik' in a string. Two valid regexps to match these are \b(Eric|Eirik)\b and \bEi?ri[ck]\b. We need the word boundary '\b' so we don't get 'Ericsson' etc. The second regexp actually matches more than we want, 'Eric', 'Erik', 'Eiric' and 'Eirik'.

We will implement some the examples above in the code examples section.

Characters and Abbreviations for Sets of Characters

  • c Any character represents itself unless it has a special regexp meaning. Thus c matches the character c.

  • \c A character that follows a backslash matches the character itself except where mentioned below. For example if you wished to match a literal caret at the beginning of a string you would write \^.

  • \a This matches the ASCII bell character (BEL, 0x07).
  • \f This matches the ASCII form feed character (FF, 0x0C).
  • \n This matches the ASCII line feed character (LF, 0x0A, Unix newline).
  • \r This matches the ASCII carriage return character (CR, 0x0D).
  • \t This matches the ASCII horizontal tab character (HT, 0x09).
  • \v This matches the ASCII vertical tab character (VT, 0x0B).
  • \xhhhh This matches the Unicode character corresponding to the hexadecimal number hhhh (between 0x0000 and 0xFFFF). \0ooo (i.e., \zero ooo) matches the ASCII/Latin-1 character corresponding to the octal number ooo (between 0 and 0377).
  • . (dot) This matches any character (including newline).
  • \d This matches a digit (see QChar::isDigit()).
  • \D This matches a non-digit.
  • \s This matches a whitespace (see QChar::isSpace()).
  • \S This matches a non-whitespace.
  • \w This matches a word character (see QChar::isLetterOrNumber()).
  • \W This matches a non-word character.
  • \n The n-th backreference, e.g. \1, \2, etc.

Note that the C++ compiler transforms backslashes in strings so to include a \ in a regexp you will need to enter it twice, i.e. \\.

Sets of Characters

Square brackets are used to match any character in the set of characters contained within the square brackets. All the character set abbreviations described above can be used within square brackets. Apart from the character set abbreviations and the following two exceptions no characters have special meanings in square brackets.

  • ^ The caret negates the character set if it occurs as the first character, i.e. immediately after the opening square bracket. For example, [abc] matches 'a' or 'b' or 'c', but [^abc] matches anything except 'a', 'b' and 'c'.

  • - The dash is used to indicate a range of characters, for example [W-Z] matches 'W' or 'X' or 'Y' or 'Z'.

Using the predefined character set abbreviations is more portable than using character ranges across platforms and languages. For example, [0-9] matches a digit in Western alphabets but \d matches a digit in any alphabet.

Note that in most regexp literature sets of characters are called "character classes".

Quantifiers

By default an expression is automatically quantified by {1,1}, i.e. it should occur exactly once. In the following list E stands for any expression. An expression is a character or an abbreviation for a set of characters or a set of characters in square brackets or any parenthesised expression.

  • E? Matches zero or one occurrence of E. This quantifier means "the previous expression is optional" since it will match whether or not the expression occurs in the string. It is the same as E{0,1}. For example dents? will match 'dent' and 'dents'.

  • E+ Matches one or more occurrences of E. This is the same as E{1,MAXINT}. For example, 0+ will match '0', '00', '000', etc.

  • E* Matches zero or more occurrences of E. This is the same as E{0,MAXINT}. The * quantifier is often used by a mistake. Since it matches zero or more occurrences it will match no occurrences at all. For example if we want to match strings that end in whitespace and use the regexp \s*$ we would get a match on every string. This is because we have said find zero or more whitespace followed by the end of string, so even strings that don't end in whitespace will match. The regexp we want in this case is \s+$ to match strings that have at least one whitespace at the end.

  • E{n} Matches exactly n occurrences of the expression. This is the same as repeating the expression n times. For example, x{5} is the same as xxxxx. It is also the same as E{n,n}, e.g. x{5,5}.

  • E{n,} Matches at least n occurrences of the expression. This is the same as E{n,MAXINT}.

  • E{,m} Matches at most m occurrences of the expression. This is the same as E{0,m}.

  • E{n,m} Matches at least n occurrences of the expression and at most m occurrences of the expression.

(MAXINT is implementation dependent but will not be smaller than 1024.)

If we wish to apply a quantifier to more than just the preceding character we can use parentheses to group characters together in an expression. For example, tag+ matches a 't' followed by an 'a' followed by at least one 'g', whereas (tag)+ matches at least one occurrence of 'tag'.

Note that quantifiers are "greedy". They will match as much text as they can. For example, 0+ will match as many zeros as it can from the first zero it finds, e.g. '2.0005'. Quantifiers can be made non-greedy, see setMinimal().

Capturing Text

Parentheses allow us to group elements together so that we can quantify and capture them. For example if we have the expression mail|letter|correspondence that matches a string we know that one of the words matched but not which one. Using parentheses allows us to "capture" whatever is matched within their bounds, so if we used (mail|letter|correspondence) and matched this regexp against the string "I sent you some email" we can use the cap() or capturedTexts() functions to extract the matched characters, in this case 'mail'.

We can use captured text within the regexp itself. To refer to the captured text we use backreferences which are indexed from 1, the same as for cap(). For example we could search for duplicate words in a string using \b(\w+)\W+\1\b which means match a word boundary followed by one or more word characters followed by one or more non-word characters followed by the same text as the first parenthesised expression followed by a word boundary.

If we want to use parentheses purely for grouping and not for capturing we can use the non-capturing syntax, e.g. (?:green|blue). Non-capturing parentheses begin '(?:' and end ')'. In this example we match either 'green' or 'blue' but we do not capture the match so we only know whether or not we matched but not which color we actually found. Using non-capturing parentheses is more efficient than using capturing parentheses since the regexp engine has to do less book-keeping.

Both capturing and non-capturing parentheses may be nested.

Assertions

Assertions make some statement about the text at the point where they occur in the regexp but they do not match any characters. In the following list E stands for any expression.

  • ^ The caret signifies the beginning of the string. If you wish to match a literal ^ you must escape it by writing \^. For example, ^#include will only match strings which begin with the characters '#include'. (When the caret is the first character of a character set it has a special meaning, see Sets of Characters.)

  • $ The dollar signifies the end of the string. For example \d\s*$ will match strings which end with a digit optionally followed by whitespace. If you wish to match a literal $ you must escape it by writing \$.

  • \b A word boundary. For example the regexp \bOK\b means match immediately after a word boundary (e.g. start of string or whitespace) the letter 'O' then the letter 'K' immediately before another word boundary (e.g. end of string or whitespace). But note that the assertion does not actually match any whitespace so if we write (\bOK\b) and we have a match it will only contain 'OK' even if the string is "Its OK now".

  • \B A non-word boundary. This assertion is true wherever \b is false. For example if we searched for \Bon\B in "Left on" the match would fail (space and end of string aren't non-word boundaries), but it would match in "tonne".

  • (?=E) Positive lookahead. This assertion is true if the expression matches at this point in the regexp. For example, const(?=\s+char) matches 'const' whenever it is followed by 'char', as in 'static const char *'. (Compare with const\s+char, which matches 'static const char *'.)

  • (?!E) Negative lookahead. This assertion is true if the expression does not match at this point in the regexp. For example, const(?!\s+char) matches 'const' except when it is followed by 'char'.

Wildcard Matching (globbing)

Most command shells such as bash or cmd support "file globbing", the ability to identify a group of files by using wildcards. The setWildcard() function is used to switch between regexp and wildcard mode. Wildcard matching is much simpler than full regexps and has only four features:

  • c Any character represents itself apart from those mentioned below. Thus c matches the character c.

  • ? This matches any single character. It is the same as . in full regexps.

  • * This matches zero or more of any characters. It is the same as .* in full regexps.

  • [...] Sets of characters can be represented in square brackets, similar to full regexps. Within the character class, like outside, backslash has no special meaning.

For example if we are in wildcard mode and have strings which contain filenames we could identify HTML files with *.html. This will match zero or more characters followed by a dot followed by 'h', 't', 'm' and 'l'.

Notes for Perl Users

Most of the character class abbreviations supported by Perl are supported by QRegExp, see characters and abbreviations for sets of characters.

In QRegExp, apart from within character classes, ^ always signifies the start of the string, so carets must always be escaped unless used for that purpose. In Perl the meaning of caret varies automagically depending on where it occurs so escaping it is rarely necessary. The same applies to $ which in QRegExp always signifies the end of the string.

QRegExp's quantifiers are the same as Perl's greedy quantifiers. Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern. For example, to match the Perl regexp ro+?m requires:

    QRegExp rx( "ro+m" );
    rx.setMinimal( TRUE );

The equivalent of Perl's /i option is setCaseSensitive(FALSE).

Perl's /g option can be emulated using a loop.

In QRegExp . matches any character, therefore all QRegExp regexps have the equivalent of Perl's /s option. QRegExp does not have an equivalent to Perl's /m option, but this can be emulated in various ways for example by splitting the input into lines or by looping with a regexp that searches for newlines.

Because QRegExp is string oriented there are no \A, \Z or \z assertions. The \G assertion is not supported but can be emulated in a loop.

Perl's $& is cap(0) or capturedTexts()[0]. There are no QRegExp equivalents for $`, $' or $+. Perl's capturing variables, $1, $2, ... correspond to cap(1) or capturedTexts()[1], cap(2) or capturedTexts()[2], etc.

To substitute a pattern use QString::replace().

Perl's extended /x syntax is not supported, nor are regexp comments (?#comment) or directives, e.g. (?i).

Both zero-width positive and zero-width negative lookahead assertions (?=pattern) and (?!pattern) are supported with the same syntax as Perl. Perl's lookbehind assertions, "independent" subexpressions and conditional expressions are not supported.

Non-capturing parentheses are also supported, with the same (?:pattern) syntax.

See QStringList::split() and QStringList::join() for equivalents to Perl's split and join functions.

Note: because C++ transforms \'s they must be written twice in code, e.g. \b must be written \\b.

Code Examples

    QRegExp rx( "^\\d\\d?$" );  // match integers 0 to 99
    rx.search( "123" );         // returns -1 (no match)
    rx.search( "-6" );          // returns -1 (no match)
    rx.search( "6" );           // returns 0 (matched as position 0)

The third string matches '6'. This is a simple validation regexp for integers in the range 0 to 99.

    QRegExp rx( "^\\S+$" );     // match strings without whitespace
    rx.search( "Hello world" ); // returns -1 (no match)
    rx.search( "This_is-OK" );  // returns 0 (matched at position 0)

The second string matches 'This_is-OK'. We've used the character set abbreviation '\S' (non-whitespace) and the anchors to match strings which contain no whitespace.

In the following example we match strings containing 'mail' or 'letter' or 'correspondence' but only match whole words i.e. not 'email'

    QRegExp rx( "\\b(mail|letter|correspondence)\\b" );
    rx.search( "I sent you an email" );     // returns -1 (no match)
    rx.search( "Please write the letter" ); // returns 17

The second string matches "Please write the letter". The word 'letter' is also captured (because of the parentheses). We can see what text we've captured like this:

    QString captured = rx.cap( 1 ); // captured contains "letter"

This will capture the text from the first set of capturing parentheses (counting capturing left parentheses from left to right). The parentheses are counted from 1 since cap( 0 ) is the whole matched regexp (equivalent to '&' in most regexp engines).

    QRegExp rx( "&(?!amp;)" );      // match ampersands but not &amp;
    QString line1 = "This & that";
    line1.replace( rx, "&amp;" );
    // line1 == "This &amp; that"
    QString line2 = "His &amp; hers & theirs";
    line2.replace( rx, "&amp;" );
    // line2 == "His &amp; hers &amp; theirs"

Here we've passed the QRegExp to QString's replace() function to replace the matched text with new text.

    QString str = "One Eric another Eirik, and an Ericsson."
                  " How many Eiriks, Eric?";
    QRegExp rx( "\\b(Eric|Eirik)\\b" ); // match Eric or Eirik
    int pos = 0;    // where we are in the string
    int count = 0;  // how many Eric and Eirik's we've counted
    while ( pos >= 0 ) {
        pos = rx.search( str, pos );
        if ( pos >= 0 ) {
            pos++;      // move along in str
            count++;    // count our Eric or Eirik
        }
    }

We've used the search() function to repeatedly match the regexp in the string. Note that instead of moving forward by one character at a time pos++ we could have written pos += rx.matchedLength() to skip over the already matched string. The count will equal 3, matching 'One Eric another Eirik, and an Ericsson. How many Eiriks, Eric?'; it doesn't match 'Ericsson' or 'Eiriks' because they are not bounded by non-word boundaries.

One common use of regexps is to split lines of delimited data into their component fields.

    str = "Trolltech AS\twww.trolltech.com\tNorway";
    QString company, web, country;
    rx.setPattern( "^([^\t]+)\t([^\t]+)\t([^\t]+)$" );
    if ( rx.search( str ) != -1 ) {
        company = rx.cap( 1 );
        web = rx.cap( 2 );
        country = rx.cap( 3 );
    }

In this example our input lines have the format company name, web address and country. Unfortunately the regexp is rather long and not very versatile -- the code will break if we add any more fields. A simpler and better solution is to look for the separator, '\t' in this case, and take the surrounding text. The QStringList split() function can take a separator string or regexp as an argument and split a string accordingly.

    QStringList field = QStringList::split( "\t", str );

Here field[0] is the company, field[1] the web address and so on.

To imitate the matching of a shell we can use wildcard mode.

    QRegExp rx( "*.html" );     // invalid regexp: * doesn't quantify anything
    rx.setWildcard( TRUE );     // now it's a valid wildcard regexp
    rx.search( "index.html" );  // returns 0 (matched at position 0)
    rx.search( "default.htm" ); // returns -1 (no match)
    rx.search( "readme.txt" );  // returns -1 (no match)

Wildcard matching can be convenient because of its simplicity, but any wildcard regexp can be defined using full regexps, e.g. .*\.html$. Notice that we can't match both .html and .htm files with a wildcard unless we use *.htm* which will also match 'test.html.bak'. A full regexp gives us the precision we need, .*\.html?$.

QRegExp can match case insensitively using setCaseSensitive(), and can use non-greedy matching, see setMinimal(). By default QRegExp uses full regexps but this can be changed with setWildcard(). Searching can be forward with search() or backward with searchRev(). Captured text can be accessed using capturedTexts() which returns a string list of all captured strings, or using cap() which returns the captured string for the given index. The pos() function takes a match index and returns the position in the string where the match was made (or -1 if there was no match).

See also QRegExpValidator, QString, QStringList, Miscellaneous Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

Member Function Documentation

QRegExp::QRegExp ()

Constructs an empty regexp.

See also isValid().

QRegExp::QRegExp ( const QString & pattern, bool caseSensitive = TRUE, bool wildcard = FALSE )

Constructs a regular expression object for the given pattern string. The pattern must be given using wildcard notation if wildcard is TRUE (default is FALSE). The pattern is case sensitive, unless caseSensitive is FALSE. Matching is greedy (maximal), but can be changed by calling setMinimal().

See also setPattern(), setCaseSensitive(), setWildcard() and setMinimal().

QRegExp::QRegExp ( const QRegExp & rx )

Constructs a regular expression as a copy of rx.

See also operator=().

QRegExp::~QRegExp ()

Destroys the regular expression and cleans up its internal data.

QString QRegExp::cap ( int nth = 0 )

Returns the text captured by the nth subexpression. The entire match has index 0 and the parenthesized subexpressions have indices starting from 1 (excluding non-capturing parentheses).

    QRegExp rxlen( "(\\d+)(?:\\s*)(cm|inch)" );
    int pos = rxlen.search( "Length: 189cm" );
    if ( pos > -1 ) {
        QString value = rxlen.cap( 1 ); // "189"
        QString unit = rxlen.cap( 2 );  // "cm"
        // ...
    }

The order of elements matched by cap() is as follows. The first element, cap(0), is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus cap(1) is the text of the first capturing parentheses, cap(2) is the text of the second, and so on.

Some patterns may lead to a number of matches which cannot be determined in advance, for example:

    QRegExp rx( "(\\d+)" );
    str = "Offsets: 12 14 99 231 7";
    QStringList list;
    pos = 0;
    while ( pos >= 0 ) {
        pos = rx.search( str, pos );
        if ( pos > -1 ) {
            list += rx.cap( 1 );
            pos  += rx.matchedLength();
        }
    }
    // list contains "12", "14", "99", "231", "7"

See also capturedTexts(), pos(), exactMatch(), search() and searchRev().

QStringList QRegExp::capturedTexts ()

Returns a list of the captured text strings.

The first string in the list is the entire matched string. Each subsequent list element contains a string that matched a (capturing) subexpression of the regexp.

For example:

    QRegExp rx( "(\\d+)(\\s*)(cm|inch(es)?)" );
    int pos = rx.search( "Length: 36 inches" );
    QStringList list = rx.capturedTexts();
    // list is now ( "36 inches", "36", " ", "inches", "es" )

The above example also captures elements that may be present but which we have no interest in. This problem can be solved by using non-capturing parentheses:

    QRegExp rx( "(\\d+)(?:\\s*)(cm|inch(?:es)?)" );
    int pos = rx.search( "Length: 36 inches" );
    QStringList list = rx.capturedTexts();
    // list is now ( "36 inches", "36", "inches" )

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = rx.capturedTexts();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

Some regexps can match an indeterminate number of times. For example if the input string is "Offsets: 12 14 99 231 7" and the regexp, rx, is (\d+)+, we would hope to get a list of all the numbers matched. However, after calling rx.search(str), capturedTexts() will return the list ( "12", "12" ), i.e. the entire match was "12" and the first subexpression matched was "12". The correct approach is to use cap() in a loop.

The order of elements in the string list is as follows. The first element is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus capturedTexts()[1] is the text of the first capturing parentheses, capturedTexts()[2] is the text of the second and so on (corresponding to $1, $2, etc., in some other regexp languages).

See also cap(), pos(), exactMatch(), search() and searchRev().

bool QRegExp::caseSensitive () const

Returns TRUE if case sensitivity is enabled, otherwise FALSE. The default is TRUE.

See also setCaseSensitive().

bool QRegExp::exactMatch ( const QString & str ) const

Returns TRUE if str is matched exactly by this regular expression otherwise it returns FALSE. You can determine how much of the string was matched by calling matchedLength().

For a given regexp string, R, exactMatch("R") is the equivalent of search("^R$") since exactMatch() effectively encloses the regexp in the start of string and end of string anchors, except that it sets matchedLength() differently.

For example, if the regular expression is blue, then exactMatch() returns TRUE only for input blue. For inputs bluebell, blutak and lightblue, exactMatch() returns FALSE and matchedLength() will return 4, 3 and 0 respectively.

Although const, this function sets matchedLength(), capturedTexts() and pos().

See also search(), searchRev() and QRegExpValidator.

bool QRegExp::isEmpty () const

Returns TRUE if the pattern string is empty, otherwise FALSE.

If you call exactMatch() with an empty pattern on an empty string it will return TRUE; otherwise it returns FALSE since it operates over the whole string. If you call search() with an empty pattern on any string it will return the start position (0 by default) since it will match at the start position, because the empty pattern matches the 'emptiness' at the start of the string, and the length of the match returned by matchedLength() will be 0.

See QString::isEmpty().

bool QRegExp::isValid () const

Returns TRUE if the regular expression is valid, or FALSE if it's invalid. An invalid regular expression never matches.

The pattern [a-z is an example of an invalid pattern, since it lacks a closing square bracket.

Note that the validity of a regexp may also depend on the setting of the wildcard flag, for example *.html is a valid wildcard regexp but an invalid full regexp.

int QRegExp::match ( const QString & str, int index = 0, int * len = 0, bool indexIsStart = TRUE ) const

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

Attempts to match in str, starting from position index. Returns the position of the match, or -1 if there was no match.

The length of the match is stored in *len, unless len is a null pointer.

If indexIsStart is TRUE (the default), the position index in the string will match the start of string anchor, ^, in the regexp, if present. Otherwise, position 0 in str will match.

Use search() and matchedLength() instead of this function.

If you really need the indexIsStart functionality, try this:

    QRegExp rx( "some pattern" );
    int pos = rx.search( str.mid(index) );
    if ( pos >= 0 )
        pos += index;
    int len = rx.matchedLength();

Where performance is important, you can replace str.mid(index) by QConstString(str.unicode() + index, str.length() - index).string(), which avoids copying the character data.

See also QString::mid() and QConstString.

Example: qmag/qmag.cpp.

int QRegExp::matchedLength () const

Returns the length of the last matched string, or -1 if there was no match.

See also exactMatch(), search() and searchRev().

bool QRegExp::minimal () const

Returns TRUE if minimal (non-greedy) matching is enabled, otherwise returns FALSE.

See also setMinimal().

bool QRegExp::operator!= ( const QRegExp & rx ) const

Returns TRUE if this regular expression is not equal to rx; otherwise FALSE.

See also operator==().

QRegExp & QRegExp::operator= ( const QRegExp & rx )

Copies the regular expression rx and returns a reference to the copy. The case sensitivity, wildcard and minimal matching options are copied as well.

bool QRegExp::operator== ( const QRegExp & rx ) const

Returns TRUE if this regular expression is equal to rx; otherwise returns FALSE.

Two QRegExp objects are equal if they have the same pattern strings and the same settings for case sensitivity, wildcard and minimal matching.

QString QRegExp::pattern () const

Returns the pattern string of the regular expression. The pattern has either regular expression syntax or wildcard syntax, depending on wildcard().

See also setPattern().

int QRegExp::pos ( int nth = 0 )

Returns the position of the nth captured text in the searched string. If nth is 0 (the default), pos() returns the position of the whole match.

Example:

    QRegExp rx( "/([a-z]+)/([a-z]+)" );
    rx.search( "Output /dev/null" );    // returns 7 (position of /dev/null)
    rx.pos( 0 );                        // returns 7 (position of /dev/null)
    rx.pos( 1 );                        // returns 8 (position of dev)
    rx.pos( 2 );                        // returns 12 (position of null)

For zero-length matches, pos() always returns -1. (For example, if cap(4) would return an empty string, pos(4) returns -1.) This is due to an implementation tradeoff.

See also capturedTexts(), exactMatch(), search() and searchRev().

int QRegExp::search ( const QString & str, int start = 0 ) const

Attempts to find a match in str from position start (0 by default). If start is -1, the search starts at the last character; if -2, at the next to last character; etc.

Returns the position of the first match, or -1 if there was no match.

You might prefer to use QString::find(), QString::contains() or even QStringList::grep(). To replace matches use QString::replace().

Example:

    QString str = "offsets: 1.23 .50 71.00 6.00";
    QRegExp rx( "\\d*\\.\\d+" );    // primitive floating point matching
    int count = 0;
    int pos = 0;
    while ( pos >= 0 ) {
        pos = rx.search( str, pos );
        pos += rx.matchedLength();
        count++;
    }
    // pos will be 9, 14, 18 and finally 24; count will end up as 4
The above example is slightly subtle. When the search fails to find a match, it returns -1 and matchedLength() is 0. So pos += matchedLength() will leave pos as -1 and the loop will terminate.

Although const, this function sets matchedLength(), capturedTexts() and pos().

See also searchRev() and exactMatch().

int QRegExp::searchRev ( const QString & str, int start = -1 ) const

Attempts to find a match backwards in str from position start. If start is -1 (the default), the search starts at the last character; if -2, at the next to last character; etc.

Returns the position of the first match, or -1 if there was no match.

Although const, this function sets matchedLength(), capturedTexts() and pos().

Warning: Searching backwards is much slower than searching forwards.

See also search() and exactMatch().

void QRegExp::setCaseSensitive ( bool sensitive )

Sets case sensitive matching to sensitive.

If sensitive is TRUE, \.txt$ matches readme.txt but not README.TXT.

See also caseSensitive().

void QRegExp::setMinimal ( bool minimal )

Enables or disables minimal matching. If minimal is FALSE, matching is greedy (maximal) which is the default.

For example, suppose we have the input string "We must be <b>bold</b>, very <b>bold</b>!" and the pattern <b>.*</b>. With the default greedy (maximal) matching, the match is "We must be <b>bold</b>, very <b>bold</b>!". But with minimal (non-greedy) matching the first match is: "We must be <b>bold</b>, very <b>bold</b>!" and the second match is "We must be <b>bold</b>, very <b>bold</b>!". In practice we might use the pattern <b>[^<]+</b>, although this will still fail for nested tags.

See also minimal().

void QRegExp::setPattern ( const QString & pattern )

Sets the pattern string to pattern. The case sensitivity, wildcard and minimal matching options are not changed.

See also pattern().

void QRegExp::setWildcard ( bool wildcard )

Sets the wildcard mode for the regular expression. The default is FALSE.

Setting wildcard to TRUE enables simple shell-like wildcard matching. (See wildcard matching (globbing).)

For example, r*.txt matches the string readme.txt in wildcard mode, but does not match readme.

See also wildcard().

bool QRegExp::wildcard () const

Returns TRUE if wildcard mode is enabled, otherwise FALSE. The default is FALSE.

See also setWildcard().

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


qregexp.h Include File

qregexp.h

This is the verbatim text of the qregexp.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qregexp.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QRegExp class
**
** Created : 950126
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QREGEXP_H
#define QREGEXP_H

#ifndef QT_H
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_REGEXP
class QRegExpEngine;
struct QRegExpPrivate;

class Q_EXPORT QRegExp
{
public:
    QRegExp();
    QRegExp( const QString& pattern, bool caseSensitive = TRUE,
         bool wildcard = FALSE );
    QRegExp( const QRegExp& rx );
    ~QRegExp();
    QRegExp& operator=( const QRegExp& rx );

    bool operator==( const QRegExp& rx ) const;
    bool operator!=( const QRegExp& rx ) const { return !operator==( rx ); }

    bool isEmpty() const;
    bool isValid() const;
    QString pattern() const;
    void setPattern( const QString& pattern );
    bool caseSensitive() const;
    void setCaseSensitive( bool sensitive );
#ifndef QT_NO_REGEXP_WILDCARD
    bool wildcard() const;
    void setWildcard( bool wildcard );
#endif
    bool minimal() const;
    void setMinimal( bool minimal );

    bool exactMatch( const QString& str ) const;
#ifndef QT_NO_COMPAT
    int match( const QString& str, int index = 0, int *len = 0,
           bool indexIsStart = TRUE ) const;
#endif
    int search( const QString& str, int start = 0 ) const;
    int searchRev( const QString& str, int start = -1 ) const;
    int matchedLength() const;
#ifndef QT_NO_REGEXP_CAPTURE
    QStringList capturedTexts();
    QString cap( int nth = 0 );
    int pos( int nth = 0 );
#endif

private:
    void compile( bool caseSensitive );

    QRegExpEngine *eng;
    QRegExpPrivate *priv;
};
#endif // QT_NO_REGEXP
#endif // QREGEXP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QRegExp Member List

Complete Member List for QRegExp

This is the complete list of member functions for QRegExp, including inherited members.

  • QRegExp()
  • ~QRegExp()
  • cap()
  • capturedTexts()
  • caseSensitive()
  • exactMatch()
  • isEmpty()
  • isValid()
  • match()
  • matchedLength()
  • minimal()
  • operator!=()
  • operator=()
  • operator==()
  • pattern()
  • pos()
  • search()
  • searchRev()
  • setCaseSensitive()
  • setMinimal()
  • setPattern()
  • setWildcard()
  • wildcard()


QRegExpValidator Class

QRegExpValidator Class Reference

The QRegExpValidator class is used to check a string against a regular expression. More...

#include <qvalidator.h>

Inherits QValidator.

List of all member functions.

Public Members

  • QRegExpValidator ( QObject * parent, const char * name = 0 )
  • QRegExpValidator ( const QRegExp & rx, QObject * parent, const char * name = 0 )
  • ~QRegExpValidator ()
  • virtual QValidator::State validate ( QString & input, int & pos ) const
  • void setRegExp ( const QRegExp & rx )
  • const QRegExp & regExp () const

Detailed Description

The QRegExpValidator class is used to check a string against a regular expression.

QRegExpValidator contains a regular expression, "regexp", used to determine whether an input string is Acceptable, Intermediate or Invalid.

The regexp is treated as if it begins with the start of string assertion, ^, and ends with the end of string assertion $ so the match is against the entire input string, or from the given position if a start position greater than zero is given.

For a brief introduction to Qt's regexp engine see QRegExp.

Example of use:

    // regexp: optional '-' followed by between 1 and 3 digits
    QRegExp rx( "-?\\d{1,3}" );
    QRegExpValidator validator( rx, 0 );

    QLineEdit *edit = new QLineEdit( split );
    edit->setValidator( &validator );

Below we present some examples of validators. In practice they would normally be associated with a widget as in the example above.

    // integers 1 to 9999
    QRegExp rx( "[1-9]\\d{0,3}" );
    // the validator treats the regexp as "^[1-9]\\d{0,3}$"
    QRegExpValidator v( rx, 0 );
    QString s;

    s = "0";     v.validate( s, 0 );    // returns Invalid
    s = "12345"; v.validate( s, 0 );    // returns Invalid
    s = "1";     v.validate( s, 0 );    // returns Acceptable

    rx.setPattern( "\\S+" );            // one or more non-whitespace characters
    v.setRegExp( rx );
    s = "myfile.txt";  v.validate( s, 0 ); // Returns Acceptable
    s = "my file.txt"; v.validate( s, 0 ); // Returns Invalid

    // A, B or C followed by exactly five digits followed by W, X, Y or Z
    rx.setPattern( "[A-C]\\d{5}[W-Z]" );
    v.setRegExp( rx );
    s = "a12345Z"; v.validate( s, 0 );  // Returns Invalid
    s = "A12345Z"; v.validate( s, 0 );  // Returns Acceptable
    s = "B12";     v.validate( s, 0 );  // Returns Intermediate

    // match most 'readme' files
    rx.setPattern( "read\\S?me(\.(txt|asc|1st))?" );
    rx.setCaseSensitive( FALSE );
    v.setRegExp( rx );
    s = "readme";      v.validate( s, 0 ); // Returns Acceptable
    s = "README.1ST";  v.validate( s, 0 ); // Returns Acceptable
    s = "read me.txt"; v.validate( s, 0 ); // Returns Invalid
    s = "readm";       v.validate( s, 0 ); // Returns Intermediate

See also QRegExp, QIntValidator, QDoubleValidator and Miscellaneous Classes.

Member Function Documentation

QRegExpValidator::QRegExpValidator ( QObject * parent, const char * name = 0 )

Constructs a validator that accepts any string (including an empty one) as valid. The object's parent is parent and its name is name.

QRegExpValidator::QRegExpValidator ( const QRegExp & rx, QObject * parent, const char * name = 0 )

Constructs a validator which accepts all strings that match the regular expression rx. The object's parent is parent and its name is name.

The match is made against the entire string, e.g. if the regexp is [A-Fa-f0-9]+ it will be treated as ^[A-Fa-f0-9]+$.

QRegExpValidator::~QRegExpValidator ()

Destroys the validator, freeing any resources allocated.

const QRegExp & QRegExpValidator::regExp () const

Returns the regular expression used for validation.

See also setRegExp().

void QRegExpValidator::setRegExp ( const QRegExp & rx )

Sets the regular expression used for validation to rx.

See also regExp().

QValidator::State QRegExpValidator::validate ( QString & input, int & pos ) const [virtual]

Returns Acceptable if input is matched by the regular expression for this validator, Intermediate if it has matched partially (i.e. could be a valid match if additional valid characters are added), and Invalid if input is not matched.

The start position is the beginning of the string unless pos is given and is > 0 in which case the regexp is matched from pos until the end of the string.

For example, if the regular expression is \w\d\d (that is, word-character, digit, digit) then "A57" is Acceptable, "E5" is Intermediate and "+9" is Invalid.

See also QRegExp::match().

Reimplemented from QValidator.

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


QRegExpValidator Member List

Complete Member List for QRegExpValidator

This is the complete list of member functions for QRegExpValidator, including inherited members.

  • QRegExpValidator()
  • ~QRegExpValidator()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fixup()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • regExp()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • setRegExp()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • validate()


QRegion Class

QRegion Class Reference

The QRegion class specifies a clip region for a painter. More...

#include <qregion.h>

List of all member functions.

Public Members

  • enum RegionType { Rectangle, Ellipse }
  • QRegion ()
  • QRegion ( int x, int y, int w, int h, RegionType t = Rectangle )
  • QRegion ( const QRect & r, RegionType t = Rectangle )
  • QRegion ( const QPointArray & a, bool winding = FALSE )
  • QRegion ( const QRegion & r )
  • QRegion ( const QBitmap & bm )
  • ~QRegion ()
  • QRegion & operator= ( const QRegion & r )
  • bool isNull () const
  • bool isEmpty () const
  • bool contains ( const QPoint & p ) const
  • bool contains ( const QRect & r ) const
  • void translate ( int dx, int dy )
  • QRegion unite ( const QRegion & r ) const
  • QRegion intersect ( const QRegion & r ) const
  • QRegion subtract ( const QRegion & r ) const
  • QRegion eor ( const QRegion & r ) const
  • QRect boundingRect () const
  • QMemArray<QRect> rects () const
  • const QRegion operator| ( const QRegion & r ) const
  • const QRegion operator+ ( const QRegion & r ) const
  • const QRegion operator& ( const QRegion & r ) const
  • const QRegion operator- ( const QRegion & r ) const
  • const QRegion operator^ ( const QRegion & r ) const
  • QRegion & operator|= ( const QRegion & r )
  • QRegion & operator+= ( const QRegion & r )
  • QRegion & operator&= ( const QRegion & r )
  • QRegion & operator-= ( const QRegion & r )
  • QRegion & operator^= ( const QRegion & r )
  • bool operator== ( const QRegion & r ) const
  • bool operator!= ( const QRegion & r ) const
  • HRGN handle () const

Related Functions

  • QDataStream & operator<< ( QDataStream & s, const QRegion & r )
  • QDataStream & operator>> ( QDataStream & s, QRegion & r )

Detailed Description

The QRegion class specifies a clip region for a painter.

QRegion is used with QPainter::setClipRegion() to limit the paint area to what needs to be painted. There is also a QWidget::repaint() that takes a QRegion parameter. QRegion is the best tool for reducing flicker.

A region can be created from a rectangle, an ellipse, a polygon or a bitmap. Complex regions may be created by combining simple regions using unite(), intersect(), subtract() or eor() (exclusive or). You can move a region using translate().

You can test whether a region isNull(), isEmpty() or if it contains() a QPoint or QRect. The bounding rectangle is given by boundingRect().

The function rects() gives a decomposition of the region into rectangles.

Example of using complex regions:

        void MyWidget::paintEvent( QPaintEvent * )
        {
            QPainter p;                         // our painter
            QRegion r1( QRect(100,100,200,80),  // r1 = elliptic region
                        QRegion::Ellipse );
            QRegion r2( QRect(100,120,90,30) ); // r2 = rectangular region
            QRegion r3 = r1.intersect( r2 );    // r3 = intersection
            p.begin( this );                    // start painting widget
            p.setClipRegion( r3 );              // set clip region
            ...                                 // paint clipped graphics
            p.end();                            // painting done
        }

QRegion is an implicitly shared class.

Due to window system limitations, the width and height of a region is limited to 65535 on Unix/X11.

See also QPainter::setClipRegion(), QPainter::setClipRect(), Graphics Classes and Image Processing Classes.

Member Type Documentation

QRegion::RegionType

Specifies the shape of the region to be created.

  • QRegion::Rectangle - the region covers the entire rectangle.
  • QRegion::Ellipse - the region is an ellipse inside the rectangle.

Member Function Documentation

QRegion::QRegion ()

Constructs a null region.

See also isNull().

QRegion::QRegion ( int x, int y, int w, int h, RegionType t = Rectangle )

Constructs a rectangular or elliptic region.

If t is Rectangle, the region is the filled rectangle (x, y, w, h). If t is Ellipse, the region is the filled ellipse with center at (x + w / 2, y + h / 2) and size (w ,h ).

QRegion::QRegion ( const QRect & r, RegionType t = Rectangle )

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

Create a region based on the rectange r with region type t.

If the rectangle is invalid a null region will be created.

See also QRegion::RegionType.

QRegion::QRegion ( const QPointArray & a, bool winding = FALSE )

Constructs a polygon region from the point array a.

If winding is TRUE, the polygon region is filled using the winding algorithm, otherwise the default even-odd fill algorithm is used.

This constructor may create complex regions that will slow down painting when used.

QRegion::QRegion ( const QRegion & r )

Constructs a new region which is equal to region r.

QRegion::QRegion ( const QBitmap & bm )

Constructs a region from the bitmap bm.

The resulting region consists of the pixels in bitmap bm that are color1, as if each pixel was a 1 by 1 rectangle.

This constructor may create complex regions that will slow down painting when used. Note that drawing masked pixmaps can be done much faster using QPixmap::setMask().

QRegion::~QRegion ()

Destroys the region.

QRect QRegion::boundingRect () const

Returns the bounding rectangle of this region. An empty region gives a rectangle that is QRect::isNull().

bool QRegion::contains ( const QPoint & p ) const

Returns TRUE if the region contains the point p; otherwise returns FALSE.

bool QRegion::contains ( const QRect & r ) const

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

Returns TRUE if the region overlaps the rectangle r; otherwise returns FALSE.

QRegion QRegion::eor ( const QRegion & r ) const

Returns a region which is the exclusive or (XOR) of this region and r.

The figure shows the exclusive or of two elliptical regions.

HRGN QRegion::handle () const

Returns the region's handle.

QRegion QRegion::intersect ( const QRegion & r ) const

Returns a region which is the intersection of this region and r.

The figure shows the intersection of two elliptical regions.

bool QRegion::isEmpty () const

Returns TRUE if the region is empty; otherwise returns FALSE. An empty region is a region that contains no points.

Example:

        QRegion r1( 10, 10, 20, 20 );
        QRegion r2( 40, 40, 20, 20 );
        QRegion r3;
        r1.isNull();             // FALSE
        r1.isEmpty();            // FALSE
        r3.isNull();             // TRUE
        r3.isEmpty();            // TRUE
        r3 = r1.intersect( r2 ); // r3 = intersection of r1 and r2
        r3.isNull();             // FALSE
        r3.isEmpty();            // TRUE
        r3 = r1.unite( r2 );     // r3 = union of r1 and r2
        r3.isNull();             // FALSE
        r3.isEmpty();            // FALSE

See also isNull().

bool QRegion::isNull () const

Returns TRUE if the region is a null region; otherwise returns FALSE.

A null region is a region that has not been initialized. A null region is always empty.

See also isEmpty().

bool QRegion::operator!= ( const QRegion & r ) const

Returns TRUE if the region is different from r; otherwise returns FALSE.

const QRegion QRegion::operator& ( const QRegion & r ) const

Applies the intersect() function to this region and r. r1&r2 is equivalent to r1.intersect(r2)

See also intersect().

QRegion & QRegion::operator&= ( const QRegion & r )

Applies the intersect() function to this region and r and assigns the result to this region. r1&=r2 is equivalent to r1=r1.intersect(r2)

See also intersect().

const QRegion QRegion::operator+ ( const QRegion & r ) const

Applies the unite() function to this region and r. r1+r2 is equivalent to r1.unite(r2)

See also unite() and operator|().

QRegion & QRegion::operator+= ( const QRegion & r )

Applies the unite() function to this region and r and assigns the result to this region. r1+=r2 is equivalent to r1=r1.unite(r2)

See also intersect().

const QRegion QRegion::operator- ( const QRegion & r ) const

Applies the subtract() function to this region and r. r1-r2 is equivalent to r1.subtract(r2)

See also subtract().

QRegion & QRegion::operator-= ( const QRegion & r )

Applies the subtract() function to this region and r and assigns the result to this region. r1-=r2 is equivalent to r1=r1.subtract(r2)

See also subtract().

QRegion & QRegion::operator= ( const QRegion & r )

Assigns r to this region and returns a reference to the region.

bool QRegion::operator== ( const QRegion & r ) const

Returns TRUE if the region is equal to r; otherwise returns FALSE.

const QRegion QRegion::operator^ ( const QRegion & r ) const

Applies the eor() function to this region and r. r1^r2 is equivalent to r1.eor(r2)

See also eor().

QRegion & QRegion::operator^= ( const QRegion & r )

Applies the eor() function to this region and r and assigns the result to this region. r1^=r2 is equivalent to r1=r1.eor(r2)

See also eor().

const QRegion QRegion::operator| ( const QRegion & r ) const

Applies the unite() function to this region and r. r1|r2 is equivalent to r1.unite(r2)

See also unite() and operator+().

QRegion & QRegion::operator|= ( const QRegion & r )

Applies the unite() function to this region and r and assigns the result to this region. r1|=r2 is equivalent to r1=r1.unite(r2)

See also unite().

QMemArray<QRect> QRegion::rects () const

Returns an array of non-overlapping rectangles that make up the region.

The union of all the rectangles is equal to the original region.

QRegion QRegion::subtract ( const QRegion & r ) const

Returns a region which is r subtracted from this region.

The figure shows the result when the ellipse on the right is subtracted from the ellipse on the left. (left-right )

void QRegion::translate ( int dx, int dy )

Translates (moves) the region dx along the X axis and dy along the Y axis.

QRegion QRegion::unite ( const QRegion & r ) const

Returns a region which is the union of this region and r.

The figure shows the union of two elliptical regions.

Related Functions

QDataStream & operator<< ( QDataStream & s, const QRegion & r )

Writes the region r to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QRegion & r )

Reads a region from the stream s into r and returns a reference to the stream.

See also Format of the QDataStream operators.

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


qregion.h Include File

qregion.h

This is the verbatim text of the qregion.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qregion.h   3.0.5   edited Jun 4 03:04 $
**
** Definition of QRegion class
**
** Created : 940514
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QREGION_H
#define QREGION_H

#ifndef QT_H
#include "qshared.h"
#include "qrect.h"
#endif // QT_H

class Q_EXPORT QRegion
{
public:
    enum RegionType { Rectangle, Ellipse };

    QRegion();
    QRegion( int x, int y, int w, int h, RegionType = Rectangle );
    QRegion( const QRect &, RegionType = Rectangle );
    QRegion( const QPointArray &, bool winding=FALSE );
    QRegion( const QRegion & );
    QRegion( const QBitmap & );
   ~QRegion();
    QRegion &operator=( const QRegion & );

    bool    isNull()   const;
    bool    isEmpty()  const;

    bool    contains( const QPoint &p ) const;
    bool    contains( const QRect &r )	const;

    void    translate( int dx, int dy );

    QRegion unite( const QRegion & )	const;
    QRegion intersect( const QRegion &) const;
    QRegion subtract( const QRegion & ) const;
    QRegion eor( const QRegion & )	const;

    QRect   boundingRect() const;
    QMemArray<QRect> rects() const;
    void setRects( const QRect *, int );

    const QRegion operator|( const QRegion & ) const;
    const QRegion operator+( const QRegion & ) const;
    const QRegion operator&( const QRegion & ) const;
    const QRegion operator-( const QRegion & ) const;
    const QRegion operator^( const QRegion & ) const;
    QRegion& operator|=( const QRegion & );
    QRegion& operator+=( const QRegion & );
    QRegion& operator&=( const QRegion & );
    QRegion& operator-=( const QRegion & );
    QRegion& operator^=( const QRegion & );

    bool    operator==( const QRegion & )  const;
    bool    operator!=( const QRegion &r ) const
            { return !(operator==(r)); }

#if defined(Q_WS_WIN)
    HRGN    handle() const { return data->rgn; }
#elif defined(Q_WS_X11)
    Region  handle() const { return data->rgn; }
#elif defined(Q_WS_MAC)
    RgnHandle handle(bool require_rgn=FALSE) const;
#elif defined(Q_WS_QWS)
    // QGfx_QWS needs this for region drawing
    void * handle() const { return data->rgn; }
#endif

#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator<<( QDataStream &, const QRegion & );
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QRegion & );
#endif
private:
    QRegion( bool );
    QRegion copy() const;
    void    detach();
#if defined(Q_WS_WIN)
    QRegion winCombine( const QRegion &, int ) const;
#endif
    void    exec( const QByteArray &, int ver = 0 );
    struct QRegionData : public QShared {
#if defined(Q_WS_WIN)
    HRGN   rgn;
#elif defined(Q_WS_X11)
    QRect rect;
    Region rgn;
#elif defined(Q_WS_MAC)
    uint is_rect:1;
    QRect rect;
    RgnHandle rgn;
#elif defined(Q_WS_QWS)
    void * rgn;
#endif
    bool   is_null;
    } *data;
#if defined(Q_WS_MAC)
    friend struct qt_mac_rgn_data_cache;
    friend QRegionData *qt_mac_get_rgn_data();
    friend void qt_mac_free_rgn_data(QRegionData *);
    void rectifyRegion();
#endif

};

#define QRGN_SETRECT		1		// region stream commands
#define QRGN_SETELLIPSE		2		//  (these are internal)
#define QRGN_SETPTARRAY_ALT	3
#define QRGN_SETPTARRAY_WIND	4
#define QRGN_TRANSLATE		5
#define QRGN_OR			6
#define QRGN_AND		7
#define QRGN_SUB		8
#define QRGN_XOR		9
#define QRGN_RECTS	       10

/*****************************************************************************
  QRegion stream functions
 *****************************************************************************/

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QRegion & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QRegion & );
#endif

#endif // QREGION_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QRegion Member List

Complete Member List for QRegion

This is the complete list of member functions for QRegion, including inherited members.

  • QRegion()
  • ~QRegion()
  • boundingRect()
  • contains()
  • eor()
  • handle()
  • intersect()
  • isEmpty()
  • isNull()
  • operator!=()
  • operator&()
  • operator&=()
  • operator+()
  • operator+=()
  • operator-()
  • operator-=()
  • operator=()
  • operator==()
  • operator^()
  • operator^=()
  • operator|()
  • operator|=()
  • rects()
  • subtract()
  • translate()
  • unite()


QResizeEvent Class

QResizeEvent Class Reference

The QResizeEvent class contains event parameters for resize events. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QResizeEvent ( const QSize & size, const QSize & oldSize )
  • const QSize & size () const
  • const QSize & oldSize () const

Detailed Description

The QResizeEvent class contains event parameters for resize events.

Resize events are sent to widgets that have been resized.

The event handler QWidget::resizeEvent() receives resize events.

See also QWidget::size, QWidget::geometry and Event Classes.

Member Function Documentation

QResizeEvent::QResizeEvent ( const QSize & size, const QSize & oldSize )

Constructs a resize event with the new and old widget sizes, size and oldSize respectively.

const QSize & QResizeEvent::oldSize () const

Returns the old size of the widget.

const QSize & QResizeEvent::size () const

Returns the new size of the widget, which is the same as QWidget::size().

Examples: chart/canvasview.cpp and life/life.cpp.

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


QResizeEvent Member List

Complete Member List for QResizeEvent

This is the complete list of member functions for QResizeEvent, including inherited members.

  • QResizeEvent()
  • oldSize()
  • size()
  • spontaneous()
  • type()


qrtlcodec.h Include File

qrtlcodec.h

This is the verbatim text of the qrtlcodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qrtlcodec.h   3.0.5   edited Oct 12 2001 $
**
** Implementation of QTextCodec class
**
** Created : 981015
**
** Copyright (C)1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QRTLCODEC_H
#define QRTLCODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#endif // QT_H

#ifndef QT_NO_CODEC_HEBREW

class Q_EXPORT QHebrewCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
};

#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QScreen Class

QScreen Class Reference

The QScreen class and its descendants manage the framebuffer and palette. More...

#include <qgfx_qws.h>

List of all member functions.

Public Members

  • QScreen ( int display_id )
  • virtual ~QScreen ()
  • virtual bool initDevice () = 0
  • virtual bool connect ( const QString & displaySpec ) = 0
  • virtual void disconnect () = 0
  • virtual int initCursor ( void * end_of_location, bool init = FALSE )
  • virtual void shutdownDevice ()
  • virtual void setMode ( int, int, int ) = 0
  • virtual bool supportsDepth ( int d ) const
  • virtual QGfx * createGfx ( unsigned char * bytes, int w, int h, int d, int linestep )
  • virtual QGfx * screenGfx ()
  • virtual void save ()
  • virtual void restore ()
  • virtual void blank ( bool on )
  • virtual int pixmapOffsetAlignment ()
  • virtual int pixmapLinestepAlignment ()
  • virtual bool onCard ( unsigned char * p ) const
  • virtual bool onCard ( unsigned char * p, ulong & offset ) const
  • virtual void set ( unsigned int, unsigned int, unsigned int, unsigned int )
  • virtual int alloc ( unsigned int r, unsigned int g, unsigned int b )
  • int width () const
  • int height () const
  • int depth () const
  • virtual int pixmapDepth () const
  • int pixelType () const
  • int linestep () const
  • int deviceWidth () const
  • int deviceHeight () const
  • uchar * base () const
  • virtual uchar * cache ( int, int )
  • virtual void uncache ( uchar * )
  • int screenSize () const
  • int totalSize () const
  • QRgb * clut ()
  • int numCols ()
  • virtual QSize mapToDevice ( const QSize & s ) const
  • virtual QSize mapFromDevice ( const QSize & s ) const
  • virtual QPoint mapToDevice ( const QPoint &, const QSize & ) const
  • virtual QPoint mapFromDevice ( const QPoint &, const QSize & ) const
  • virtual QRect mapToDevice ( const QRect & r, const QSize & ) const
  • virtual QRect mapFromDevice ( const QRect & r, const QSize & ) const
  • virtual QImage mapToDevice ( const QImage & i ) const
  • virtual QImage mapFromDevice ( const QImage & i ) const
  • virtual QRegion mapToDevice ( const QRegion & r, const QSize & ) const
  • virtual QRegion mapFromDevice ( const QRegion & r, const QSize & ) const
  • virtual int transformOrientation () const
  • virtual bool isTransformed () const
  • virtual bool isInterlaced () const
  • virtual void setDirty ( const QRect & )
  • int * opType ()
  • int * lastOp ()

Detailed Description

The QScreen class and its descendants manage the framebuffer and palette.

QScreens act as factories for the screen cursor and QGfx's. QLinuxFbScreen manages a Linux framebuffer; accelerated drivers subclass QLinuxFbScreen. There can only be one screen in a Qt/Embedded application.

See also Qt/Embedded.

Member Function Documentation

QScreen::QScreen ( int display_id )

Create a screen; the display_id is the number of the Qt/Embedded server to connect to.

QScreen::~QScreen () [virtual]

Destroys a QScreen

int QScreen::alloc ( unsigned int r, unsigned int g, unsigned int b ) [virtual]

Given an RGB value r g b, return an index which is the closest match to it in the screen's palette. Used in paletted modes only.

uchar * QScreen::base () const

Returns a pointer to the start of the framebuffer.

void QScreen::blank ( bool on ) [virtual]

If on is true, blank the screen. Otherwise unblank it.

uchar * QScreen::cache ( int, int ) [virtual]

This function is used to store pixmaps in graphics memory for the use of the accelerated drivers. See QLinuxFbScreen (where the cacheing is implemented) for more information.

QRgb * QScreen::clut ()

Returns the screen's color lookup table (color palette). This is only valid in paletted modes (8bpp and lower).

bool QScreen::connect ( const QString & displaySpec ) [pure virtual]

This function is called by every Qt/Embedded application on startup. It maps in the framebuffer and in the accelerated drivers the graphics card control registers. displaySpec has the following syntax:

[gfx driver][:driver specific options][:display number]

for example if you want to use the mach64 driver on fb1 as display 2:

Mach64:/dev/fb1:2

displaySpec is passed in via the QWS_DISPLAY environment variable or the -display command line parameter.

QGfx * QScreen::createGfx ( unsigned char * bytes, int w, int h, int d, int linestep ) [virtual]

Creates a gfx on an arbitrary buffer bytes, width w and height h in pixels, depth d and linestep (length in bytes of each line in the buffer). Accelerated drivers can check to see if bytes points into graphics memory and create an accelerated Gfx.

int QScreen::depth () const

Gives the depth in bits per pixel of the framebuffer. This is the number of bits each pixel takes up rather than the number of significant bits, so 24bpp and 32bpp express the same range of colors (8 bits of red, green and blue)

int QScreen::deviceHeight () const

Gives the full height of the framebuffer device, as opposed to the height which Qt/Embedded will actually use. These can differ if the display is centered within the framebuffer.

int QScreen::deviceWidth () const

Gives the full width of the framebuffer device, as opposed to the width which Qt/Embedded will actually use. These can differ if the display is centered within the framebuffer.

void QScreen::disconnect () [pure virtual]

This function is called by every Qt/Embedded application just before exitting; it's normally used to unmap the framebuffer.

int QScreen::height () const

Gives the height in pixels of the framebuffer.

int QScreen::initCursor ( void * end_of_location, bool init = FALSE ) [virtual]

This is used to initialize the software cursor - end_of_location points to the address after the area where the cursor image can be stored. init is true for the first application this method is called from (the Qt/Embedded server), false otherwise.

bool QScreen::initDevice () [pure virtual]

This function is called by the Qt/Embedded server when initializing the framebuffer. Accelerated drivers use it to set up the graphics card.

bool QScreen::isInterlaced () const [virtual]

Returns TRUE if the display is interlaced (for instance a television screen); otherwise returns FALSE. If TRUE, drawing is altered to look better on such displays.

bool QScreen::isTransformed () const [virtual]

Returns TRUE if the screen is transformed (for instance, rotated 90 degrees); otherwise returns FALSE. QScreen's version always returns FALSE.

int * QScreen::lastOp ()

Returns the screens last operation.

int QScreen::linestep () const

Returns the length in bytes of each scanline of the framebuffer.

QSize QScreen::mapFromDevice ( const QSize & s ) const [virtual]

Map a framebuffer coordinate to the coordinate space used by the application. Used by the rotated driver; the QScreen implementation simply returns s.

QPoint QScreen::mapFromDevice ( const QPoint &, const QSize & ) const [virtual]

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

Map a framebuffer coordinate to the coordinate space used by the application. Used by the rotated driver; the QScreen implementation simply returns the point.

QRect QScreen::mapFromDevice ( const QRect & r, const QSize & ) const [virtual]

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

Map a framebuffer coordinate to the coordinate space used by the application. Used by the rotated driver; the QScreen implementation simply returns r.

QImage QScreen::mapFromDevice ( const QImage & i ) const [virtual]

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

Transforms an image so that it matches the application coordinate space (e.g. rotating it 90 degrees counter-clockwise). The QScreen implementation simply returns i.

QRegion QScreen::mapFromDevice ( const QRegion & r, const QSize & ) const [virtual]

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

Transforms a region so that it matches the application coordinate space (e.g. rotating it 90 degrees counter-clockwise). The QScreen implementation simply returns r.

QSize QScreen::mapToDevice ( const QSize & s ) const [virtual]

Map a user coordinate to the one to actually draw. Used by the rotated driver; the QScreen implementation simply returns s.

QPoint QScreen::mapToDevice ( const QPoint &, const QSize & ) const [virtual]

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

Map a user coordinate to the one to actually draw. Used by the rotated driver; the QScreen implementation simply returns the point passed in.

QRect QScreen::mapToDevice ( const QRect & r, const QSize & ) const [virtual]

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

Map a user coordinate to the one to actually draw. Used by the rotated driver; the QScreen implementation simply returns r.

QImage QScreen::mapToDevice ( const QImage & i ) const [virtual]

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

Transforms an image so that it fits the device coordinate space (e.g. rotating it 90 degrees clockwise). The QScreen implementation simply returns i.

QRegion QScreen::mapToDevice ( const QRegion & r, const QSize & ) const [virtual]

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

Transforms a region so that it fits the device coordinate space (e.g. rotating it 90 degrees clockwise). The QScreen implementation simply returns r.

int QScreen::numCols ()

Returns the number of entries in the color table returned by clut().

bool QScreen::onCard ( unsigned char * p ) const [virtual]

Returns true if the buffer pointed to by p is within graphics card memory, false if it's in main RAM.

bool QScreen::onCard ( unsigned char * p, ulong & offset ) const [virtual]

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

This checks whether the buffer specified by p is on the card (as per the other version of onCard) and returns an offset in bytes from the start of graphics card memory in offset if it is.

int * QScreen::opType ()

Returns the screen's operation type.

int QScreen::pixelType () const

Returns an integer (taking the same values as QGfx::PixelType) that specifies the pixel storage format of the screen.

int QScreen::pixmapDepth () const [virtual]

Gives the preferred depth for pixmaps. By default this is the same as the screen depth, but for the VGA16 driver it's 8bpp.

int QScreen::pixmapLinestepAlignment () [virtual]

Returns the value in bytes to which individual scanlines of pixmaps held in graphics card memory should be aligned. This is only useful for accelerated drivers. By default the value returned is 64 but it can be overridden by individual accelerated drivers.

int QScreen::pixmapOffsetAlignment () [virtual]

Returns the value in bytes to which the start address of pixmaps held in graphics card memory should be aligned. This is only useful for accelerated drivers. By default the value returned is 64 but it can be overridden by individual accelerated drivers.

void QScreen::restore () [virtual]

Restores the state of the graphics card from a previous save()

void QScreen::save () [virtual]

Saves the state of the graphics card - used so that, for instance, the palette can be restored when switching between linux virtual consoles. Hardware QScreen descendants should save register state here if necessary if switching between virtual consoles (for example to/from X) is to be permitted.

QGfx * QScreen::screenGfx () [virtual]

Returns a QGfx (normally a QGfxRaster) initialized to point to the screen, with an origin at 0,0 and a clip region covering the whole screen.

int QScreen::screenSize () const

Returns the size in bytes of the screen. This is always located at the beginning of framebuffer memory (i.e. at base()).

void QScreen::set ( unsigned int, unsigned int, unsigned int, unsigned int ) [virtual]

Sets an entry in the color palette.

void QScreen::setDirty ( const QRect & ) [virtual]

Indicates which section of the screen has been altered. Used by the VNC and VFB displays; the QScreen version does nothing.

void QScreen::setMode ( int, int, int ) [pure virtual]

This function can be used to set the framebuffer width, height and depth. It's currently unused.

void QScreen::shutdownDevice () [virtual]

Called by the Qt/Embedded server on shutdown; never called by a Qt/Embedded client. This is intended to support graphics card specific shutdown; the unaccelerated implementation simply hides the mouse cursor.

bool QScreen::supportsDepth ( int d ) const [virtual]

Returns true if the screen supports a particular color depth d. Possible values are 1,4,8,16 and 32.

int QScreen::totalSize () const

Returns the size in bytes of available graphics card memory, including the screen. Offscreen memory is only used by the accelerated drivers.

int QScreen::transformOrientation () const [virtual]

Used by the rotated server. The QScreeen implementation returns 0.

void QScreen::uncache ( uchar * ) [virtual]

This function is called on pixmap destruction to remove them from graphics card memory.

int QScreen::width () const

Gives the width in pixels of the framebuffer.

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


QScreen Member List

Complete Member List for QScreen

This is the complete list of member functions for QScreen, including inherited members.

  • QScreen()
  • ~QScreen()
  • alloc()
  • base()
  • blank()
  • cache()
  • clut()
  • connect()
  • createGfx()
  • depth()
  • deviceHeight()
  • deviceWidth()
  • disconnect()
  • height()
  • initCursor()
  • initDevice()
  • isInterlaced()
  • isTransformed()
  • lastOp()
  • linestep()
  • mapFromDevice()
  • mapToDevice()
  • numCols()
  • onCard()
  • opType()
  • pixelType()
  • pixmapDepth()
  • pixmapLinestepAlignment()
  • pixmapOffsetAlignment()
  • restore()
  • save()
  • screenGfx()
  • screenSize()
  • set()
  • setDirty()
  • setMode()
  • shutdownDevice()
  • supportsDepth()
  • totalSize()
  • transformOrientation()
  • uncache()
  • width()


QScrollBar类

QScrollBar类参考

QScrollBar窗口部件提供了水平的或垂直的滚动条。 详情请见……

#include <qscrollbar.h>

继承了QWidget和QRangeControl。

所有成员函数的列表。

公有成员

  • QScrollBar ( QWidget * parent, const char * name = 0 )
  • QScrollBar ( Orientation orientation, QWidget * parent, const char * name = 0 )
  • QScrollBar ( int minValue, int maxValue, int lineStep, int pageStep, int value, Orientation orientation, QWidget * parent, const char * name = 0 )
  • virtual void setOrientation ( Orientation )
  • Orientation orientation () const
  • virtual void setTracking ( bool enable )
  • bool tracking () const
  • bool draggingSlider () const
  • virtual void setPalette ( const QPalette & p )
  • int minValue () const
  • int maxValue () const
  • void setMinValue ( int )
  • void setMaxValue ( int )
  • int lineStep () const
  • int pageStep () const
  • void setLineStep ( int )
  • void setPageStep ( int )
  • int value () const
  • int sliderStart () const
  • QRect sliderRect () const

公有槽

  • void setValue ( int )

信号

  • void valueChanged ( int value )
  • void sliderPressed ()
  • void sliderMoved ( int value )
  • void sliderReleased ()
  • void nextLine ()
  • void prevLine ()
  • void nextPage ()
  • void prevPage ()

属性

  • bool draggingSlider - 用户是否已经在滑块上点击鼠标并且正在移动它 （只读）
  • int lineStep - 当前线步
  • int maxValue - 滚动条的当前最大值
  • int minValue - 滚动条的当前最小值
  • Orientation orientation - 滚动条的方位
  • int pageStep - 当前页步
  • bool tracking - 滚动条跟踪是否生效
  • int value - 滚动条的当前值

保护成员

  • virtual void hideEvent ( QHideEvent * )

详细描述

QScrollBar窗口部件提供了水平的或垂直的滚动条。

滚动条允许用户控制一个程序可定义范围内的值并且给用户一个范围控制的当前值得可视化表示。

滚动条包含四个分别的控制：

  • line-up和line-down控制是用户可以用来向上或向下移动线步的小按钮。“线”的意思是可以配置的。在编辑器和列表框中，它是指一行文本，在一个图片查看器中它也许是指20个像素。
  • slider是表示滚动条的当前值的把手，用户可以拖动它来改变值。滚动条的这部分有时被称作“拇指”。
  • page-up/page-down控制是滑块滑行的区域（滚动条的背景）。点击这里让滚动条向点击的方向移动。“页”的意思也是可以配置的：在编辑器和列表框中，它是指和这个窗口部件空间相同的行数。

QScrollBar只有几个自己的函数，它多数依赖于QRangeControl。最有用的函数是setValue()直接设置滚动条的值，addPage()、addLine()、subtractPage()和subtractLine()模拟点击的效果（对于快捷键很有用），setSteps()定义pageStep()和lineStep()的值，并且setRange()设置滚动条的minValue()和maxValue()。QScrollBar有一个方便的可以设置这些属性的构造函数。

一些图形用户界面风格（例如，提供的Windows和Motif风格）也使用pageStep()的值来计算滑块的大小。

除了来自QRangeControl的访问函数之外，QScrollBar还有完整的一套信号：

  • valueChanged() - 当滚动条的值已经发生改变时，被发射。 tracking()决定在用户操作期间，这个信号是否被发射。
  • sliderPressed() - 当用户开始拖动滑块时，被发射。
  • sliderMoved() - 当用户拖动滑块时，被发射。
  • sliderReleased() - 当用户释放滑块时，被发射。
  • nextLine() - 当滚动条已经向下或向右移动了一个线步时，被发射。线步在QRangeControl中被定义。
  • prevLine() - 当滚动条已经向上或向左移动了一个线步时，被发射。
  • nextPage() - 当滚动条已经向下或向右移动了一个页步时，被发射。
  • prevPage() - 当滚动条已经向上或向左移动了一个页步时，被发射。

QScrollBar只提供整数范围。注意尽管QScrollBar可以处理很大的数字，当前屏幕上的滚动条不能有效地控制超过100000像素的范围。除此以外，它使用户使用键盘或者鼠标来控制这个滚动条都很困难。

滚动条可以被键盘控制，但是它的默认focusPolicy()是NoFocus。使用setFocusPolicy()来让键盘焦点生效。对于绑定键的列表，请参考keyPressEvent()。

如果你需要在一个界面上添加滚动条，请考虑使用QScrollView类，它封装了滚动条的常用方法。

也可以参考QSlider、QSpinBox、QScrollView、GUI Design Handbook: Scroll Bar和基本窗口部件。

成员函数文档

QScrollBar::QScrollBar ( QWidget * parent, const char * name = 0 )

构造一个垂直的滚动条。

parent和name参数被发送给QWidget的构造函数。

QScrollBar::QScrollBar ( Orientation orientation, QWidget * parent, const char * name = 0 )

构造一个滚动条。

orientation必须是Qt::Vertical或Qt::Horizontal。

parent和name参数被发送给QWidget的构造函数。

QScrollBar::QScrollBar ( int minValue, int maxValue, int lineStep, int pageStep, int value, Orientation orientation, QWidget * parent, const char * name = 0 )

构造一个滚动条，它的值不能小于minValue或者大于maxValue，线步大小为lineStep并且页步大小为pageStep，它的值被初始化为value（它被使用bound()保证在范围之内）。

如果orientation是Vertical，滚动条是垂直的并且如果它是Horizontal，则滚动条是水平的。

parent和name参数被发送给QWidget的构造函数。

bool QScrollBar::draggingSlider () const

如果用户已经在滑块上点击鼠标并且现在正在拖动它，返回真，否则返回假。详细情况请参考“draggingSlider”属性。

void QScrollBar::hideEvent ( QHideEvent * ) [虚 保护]

当滚动条被隐藏时，这个函数被调用。

从QWidget中重新实现的。

int QScrollBar::lineStep () const

返回当前线步。详细情况请参考“lineStep”属性。

int QScrollBar::maxValue () const

返回滚动条的当前最大值。详细情况请参考“maxValue”属性。

int QScrollBar::minValue () const

返回滚动条的当前最小值。详细情况请参考“minValue”>属性。

void QScrollBar::nextLine () [信号]

当滚动条向下或向右滚动一个线步时，这个信号被发射。

void QScrollBar::nextPage () [信号]

当滚动条向下或向右滚动一个页步时，这个信号被发射。

Orientation QScrollBar::orientation () const

返回滚动条的方向。详细情况请参考“orientation”属性。

int QScrollBar::pageStep () const

返回当前页步。详细情况请参考“pageStep”属性。

void QScrollBar::prevLine () [信号]

当滚动条向上或向左滚动一个线步时，这个信号被发射。

void QScrollBar::prevPage () [信号]

当滚动条向上或向左滚动一个页步时，这个信号被发射。

void QScrollBar::setLineStep ( int )

设置当前线步。详细情况请参考“lineStep”属性。

void QScrollBar::setMaxValue ( int )

设置滚动条的当前最大值。详细情况请参考“maxValue”属性。

void QScrollBar::setMinValue ( int )

设置滚动条的当前最小值。详细情况请参考“minValue”属性。

void QScrollBar::setOrientation ( Orientation ) [虚]

设置滚动条的方位。详细情况请参考“orientation”属性。

void QScrollBar::setPageStep ( int )

设置当前页步。详细情况请参考“pageStep”属性。

void QScrollBar::setPalette ( const QPalette & p ) [虚]

重新实现了虚函数QWidget::setPalette()。

对于使用调色板p的Motif风格的滚动条，设置背景色为中间的颜色。

从QWidget中重新实现的。

void QScrollBar::setTracking ( bool enable ) [虚]

设置滚动条跟踪是否生效为enable。详细情况请参考“tracking”属性。

void QScrollBar::setValue ( int ) [slot]

设置当前滚动条的值。详细情况请参考“value”属性。

void QScrollBar::sliderMoved ( int value ) [信号]

当滑块被用户移动时，这个信号被发射，新滚动条的值value作为参数。

即使当跟踪被关闭，这个信号也被发射。

也可以参考tracking、valueChanged()、nextLine()、prevLine()、nextPage()和prevPage()。

void QScrollBar::sliderPressed () [信号]

当用户使用鼠标按下滑块时，这个信号被发射。

QRect QScrollBar::sliderRect () const

返回滚动条滑块的范围。

也可以参考sliderStart()。

void QScrollBar::sliderReleased () [信号]

当用户使用鼠标释放滑块时，这个信号被发射。

int QScrollBar::sliderStart () const

返回滚动条滑块开始的像素位置。

这对于垂直滚动条相当于sliderRect().y()，对于水平滚动条相当于sliderRect().x()。

bool QScrollBar::tracking () const

如果滚动条跟踪是生效的，返回真，否则返回假。详细情况请参考“tracking”属性。

int QScrollBar::value () const

返回当前滚动条的值。详细情况请参考“value”属性。

void QScrollBar::valueChanged ( int value ) [信号]

当滚动条的值已经改变时，这个信号被发射，新滚动条的值value作为参数。

属性文档

bool draggingSlider

这个属性保存的是用户是否已经在滑块上点击鼠标并且正在移动它。

通过draggingSlider()来获得属性值。

int lineStep

这个属性保存的是当前线步。

当设置线步时，如果新的线步与原来的设置不同，虚函数stepChange()将被调用。

也可以参考setSteps()、QRangeControl::pageStep()和setRange()。

通过setLineStep()设置属性值并且通过lineStep()来获得属性值。

int maxValue

这个属性保存的是滚动条的当前最大值。

当设置这个属性时，如果需要，QScrollBar::minValue被调整，这样使范围仍有效。

也可以参考setRange()。

通过setMaxValue()设置属性值并且通过maxValue()来获得属性值。

int minValue

这个属性保存的是滚动条的当前最小值。

当设置这个属性时，如果需要，QScrollBar::maxValue被调整，这样使范围仍有效。

也可以参考setRange()。

通过setMinValue()设置属性值并且通过minValue()来获得属性值。

Orientation orientation

这个属性保存的是滚动条的方位。

这个方位必须是Qt::Vertical（默认）或Qt::Horizontal。

通过setOrientation()设置属性值并且通过orientation()来获得属性值。

int pageStep

这个属性保存的是当前页步。

当设置页步时，如果新的页步与原来的设置不同，虚函数stepChange()将被调用。

也可以参考QRangeControl::setSteps()、lineStep和setRange()。

通过setPageStep()设置属性值并且通过pageStep()来获得属性值。

bool tracking

这个属性保存的是滚动条跟踪是否生效。

如果跟踪生效（默认），当滑块正在被拖动时，滚动条发射valueChanged()信号。如果失效，只有当用户在移动滑块之后释放鼠标按键时，滚动条发射valueChanged()信号。

通过setTracking()设置属性值并且通过tracking()来获得属性值。

int value

这个属性保存的是滚动条的当前值。

通过setValue()设置属性值并且通过value()来获得属性值。

也可以参考QRangeControl::value()和prevValue()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qscrollbar.h包含文件

qscrollbar.h

这里是qscrollbar.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qscrollbar.h   3.0.5   edited Apr 2 21:19 $
**
** Definition of QScrollBar class
**
** Created : 940427
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSCROLLBAR_H
#define QSCROLLBAR_H

class QTimer;

#ifndef QT_H
#include "qwidget.h"
#include "qrangecontrol.h"
#endif // QT_H

#ifndef QT_NO_SCROLLBAR

class Q_EXPORT QScrollBar : public QWidget, public QRangeControl
{
    Q_OBJECT
    Q_PROPERTY( int minValue READ minValue WRITE setMinValue )
    Q_PROPERTY( int maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( int lineStep READ lineStep WRITE setLineStep )
    Q_PROPERTY( int pageStep READ pageStep WRITE setPageStep )
    Q_PROPERTY( int value READ value WRITE setValue )
    Q_PROPERTY( bool tracking READ tracking WRITE setTracking )
    Q_PROPERTY( bool draggingSlider READ draggingSlider )
    Q_PROPERTY( Orientation orientation READ orientation WRITE setOrientation )

public:
    QScrollBar( QWidget *parent, const char* name=0 );
    QScrollBar( Orientation, QWidget *parent, const char* name=0 );
    QScrollBar( int minValue, int maxValue, int LineStep, int PageStep,
        int value, Orientation,
        QWidget *parent, const char* name=0 );

    virtual void setOrientation( Orientation );
    Orientation orientation() const;
    virtual void setTracking( bool enable );
    bool	tracking() const;
    bool	draggingSlider() const;

    virtual void setPalette( const QPalette & );
    QSize	sizeHint() const;

    int	 minValue() const;
    int	 maxValue() const;
    void setMinValue( int );
    void setMaxValue( int );
    int	 lineStep() const;
    int	 pageStep() const;
    void setLineStep( int );
    void setPageStep( int );
    int  value() const;

    int		sliderStart() const;
    QRect	sliderRect() const;

public slots:
    void setValue( int );

signals:
    void	valueChanged( int value );
    void	sliderPressed();
    void	sliderMoved( int value );
    void	sliderReleased();
    void	nextLine();
    void	prevLine();
    void	nextPage();
    void	prevPage();

protected:
#ifndef QT_NO_WHEELEVENT
    void 	wheelEvent( QWheelEvent * );
#endif
    void	keyPressEvent( QKeyEvent * );
    void	resizeEvent( QResizeEvent * );
    void	paintEvent( QPaintEvent * );

    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	contextMenuEvent( QContextMenuEvent * );
    void	hideEvent( QHideEvent* );

    void	valueChange();
    void	stepChange();
    void	rangeChange();

    void	styleChange( QStyle& );

private slots:
    void doAutoRepeat();

private:
    void init();
    void positionSliderFromValue();
    int calculateValueFromSlider() const;

    void startAutoRepeat();
    void stopAutoRepeat();

    int rangeValueToSliderPos( int val ) const;
    int sliderPosToRangeValue( int  val ) const;

    void action( int control );

    void drawControls( uint controls, uint activeControl ) const;
    void drawControls( uint controls, uint activeControl,
                QPainter *p ) const;

    uint pressedControl;
    bool track;
    bool clickedAt;
    Orientation orient;

    int slidePrevVal;
    QCOORD sliderPos;
    QCOORD clickOffset;

    QTimer * repeater;
    void * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QScrollBar( const QScrollBar & );
    QScrollBar &operator=( const QScrollBar & );
#endif
};

inline void QScrollBar::setTracking( bool t )
{
    track = t;
}

inline bool QScrollBar::tracking() const
{
    return track;
}

inline QScrollBar::Orientation QScrollBar::orientation() const
{
    return orient;
}

inline int QScrollBar::sliderStart() const
{
    return sliderPos;
}

#endif // QT_NO_SCROLLBAR

#endif // QSCROLLBAR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QScrollBar成员列表

完整的QScrollBar成员列表

这里是QScrollBar成员函数的完整列表，包括继承的成员。

  • QScrollBar()
  • acceptDrops()
  • addLine()
  • addPage()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bound()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • directSetValue()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • draggingSlider()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineStep()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maxValue()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minValue()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • nextLine()
  • nextPage()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageStep()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • positionFromValue()
  • prevLine()
  • prevPage()
  • prevValue()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • rangeChange()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineStep()
  • setMask()
  • setMaxValue()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinValue()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPageStep()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRange()
  • setSizeIncrement()
  • setSizePolicy()
  • setSteps()
  • setStyle()
  • setTabOrder()
  • setTracking()
  • setUpdatesEnabled()
  • setValue()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sliderMoved()
  • sliderPressed()
  • sliderRect()
  • sliderReleased()
  • sliderStart()
  • stackUnder()
  • startTimer()
  • stepChange()
  • style()
  • styleChange()
  • subtractLine()
  • subtractPage()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • tracking()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • value()
  • valueChange()
  • valueChanged()
  • valueFromPosition()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QScrollView类

QScrollView类参考

QScrollView窗口部件提供了一块在需要时可以出现滚动条的滚动区域。 详情请见……

#include <qscrollview.h>

继承了QFrame。

被QCanvasView、QTable、QGridView、QIconView、QListBox、QListView和QTextEdit继承。

所有成员函数的列表。

公有成员

  • QScrollView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QScrollView ()
  • enum ResizePolicy { Default, Manual, AutoOne, AutoOneFit }
  • virtual void setResizePolicy ( ResizePolicy )
  • ResizePolicy resizePolicy () const
  • void removeChild ( QWidget * child )
  • virtual void addChild ( QWidget * child, int x = 0, int y = 0 )
  • virtual void moveChild ( QWidget * child, int x, int y )
  • int childX ( QWidget * child )
  • int childY ( QWidget * child )
  • bool childIsVisible ( QWidget * child ) (obsolete)
  • void showChild ( QWidget * child, bool y = TRUE ) (obsolete)
  • enum ScrollBarMode { Auto, AlwaysOff, AlwaysOn }
  • ScrollBarMode vScrollBarMode () const
  • virtual void setVScrollBarMode ( ScrollBarMode )
  • ScrollBarMode hScrollBarMode () const
  • virtual void setHScrollBarMode ( ScrollBarMode )
  • QWidget * cornerWidget () const
  • virtual void setCornerWidget ( QWidget * corner )
  • QScrollBar * horizontalScrollBar () const
  • QScrollBar * verticalScrollBar () const
  • QWidget * viewport () const
  • QWidget * clipper () const
  • int visibleWidth () const
  • int visibleHeight () const
  • int contentsWidth () const
  • int contentsHeight () const
  • int contentsX () const
  • int contentsY () const
  • void updateContents ( int x, int y, int w, int h )
  • void updateContents ( const QRect & r )
  • void updateContents ()
  • void repaintContents ( int x, int y, int w, int h, bool erase = TRUE )
  • void repaintContents ( const QRect & r, bool erase = TRUE )
  • void repaintContents ( bool erase = TRUE )
  • void contentsToViewport ( int x, int y, int & vx, int & vy ) const
  • void viewportToContents ( int vx, int vy, int & x, int & y ) const
  • QPoint contentsToViewport ( const QPoint & p ) const
  • QPoint viewportToContents ( const QPoint & vp ) const
  • void enableClipper ( bool y )
  • void setStaticBackground ( bool y )
  • bool hasStaticBackground () const
  • QSize viewportSize ( int x, int y ) const
  • virtual void setDragAutoScroll ( bool b )
  • bool dragAutoScroll () const

公有槽

  • virtual void resizeContents ( int w, int h )
  • void scrollBy ( int dx, int dy )
  • virtual void setContentsPos ( int x, int y )
  • void ensureVisible ( int x, int y )
  • void ensureVisible ( int x, int y, int xmargin, int ymargin )
  • void center ( int x, int y )
  • void center ( int x, int y, float xmargin, float ymargin )
  • void updateScrollBars ()

信号

  • void contentsMoving ( int x, int y )

属性

  • int contentsHeight - 内容区域的高度 （只读）
  • int contentsWidth - 内容区域的宽度 （只读）
  • int contentsX - 在视口的左边缘的内容的X坐标 （只读）
  • int contentsY - 在视口的左边缘的内容的Y坐标 （只读）
  • bool dragAutoScroll - 在拖动移动事件中自动滚动是否生效
  • ScrollBarMode hScrollBarMode - 水平滚动条模式
  • ResizePolicy resizePolicy - 当前重定义大小策略
  • ScrollBarMode vScrollBarMode - 垂直滚动条模式
  • int visibleHeight - 可视内容的垂直总量 （只读）
  • int visibleWidth - 可视内容的水平总量 （只读）

保护成员

  • virtual void drawContents ( QPainter * p, int clipx, int clipy, int clipw, int cliph )
  • virtual void drawContentsOffset ( QPainter * p, int offsetx, int offsety, int clipx, int clipy, int clipw, int cliph )
  • virtual void contentsMousePressEvent ( QMouseEvent * )
  • virtual void contentsMouseReleaseEvent ( QMouseEvent * )
  • virtual void contentsMouseDoubleClickEvent ( QMouseEvent * )
  • virtual void contentsMouseMoveEvent ( QMouseEvent * )
  • virtual void contentsDragEnterEvent ( QDragEnterEvent * )
  • virtual void contentsDragMoveEvent ( QDragMoveEvent * )
  • virtual void contentsDragLeaveEvent ( QDragLeaveEvent * )
  • virtual void contentsDropEvent ( QDropEvent * )
  • virtual void contentsWheelEvent ( QWheelEvent * e )
  • virtual void contentsContextMenuEvent ( QContextMenuEvent * e )
  • virtual void viewportPaintEvent ( QPaintEvent * pe )
  • virtual void viewportResizeEvent ( QResizeEvent * )
  • virtual void setMargins ( int left, int top, int right, int bottom )
  • int leftMargin () const
  • int topMargin () const
  • int rightMargin () const
  • int bottomMargin () const
  • virtual void setHBarGeometry ( QScrollBar & hbar, int x, int y, int w, int h )
  • virtual void setVBarGeometry ( QScrollBar & vbar, int x, int y, int w, int h )
  • virtual bool eventFilter ( QObject * obj, QEvent * e )

详细描述

QScrollView窗口部件提供了一块在需要时可以出现滚动条的滚动区域。

QScrollView是一个很大的画布——可能比底下窗口系统通常支持的坐标系统大得多。这很重要，因为它很容易超越这些限制（例如，一些网页的高度超过32000像素）。另外，QScrollView可以有一个被放置的QWidget，可以在画出的内容上滚动。这些子窗口部件也可以放在普通坐标范围的外面（但是它们还被限制在大小之内）。

为了提供窗口部件的内容，QScrollView中继承的，重新实现了drawContents()并且使用resizeContents()设置查看区域的大小。使用addChild()和moveChild()在视图中定位窗口部件。

为了有效地使用QScrollView，理解它所使用的三种风格的窗口部件结构是很重要的：一个单一的大的子窗口部件，一个大的放置一些窗口部件的平面区域和一个大的放置很多窗口部件的平面区域。

使用一个大的窗口部件

首先，QScrollView的最简单的用法（就像上面描述的）适合任何一个维度不超过4000像素的滚动区域（这是X11服务器的最大可靠大小）。在这种方法中，你只需要把一个大的子窗口部件放在QScrollView中。这个孩子是滚动视图中的viewport()的孩子并且通过addChild()添加：

    QScrollView* sv = new QScrollView(...);
    QVBox* big_box = new QVBox(sv->viewport());
    sv->addChild(big_box);
你也可以像对任何窗口部件一样，继续在滚动视图中单一孩子中添加任意子窗口部件：
    QLabel* child1 = new QLabel("CHILD", big_box);
    QLabel* child2 = new QLabel("CHILD", big_box);
    QLabel* child3 = new QLabel("CHILD", big_box);
    ...

这里QScrollView有四个孩子：viewport()、verticalScrollBar()、horizontalScrollBar()和一个小的cornerWidget()。viewport()有一个孩子——大的QVBox。这个QVBox有三个QLabel对象作为子窗口部件。当视图被滚动，QVBox被移动，它的孩子就像通常的子窗口部件那样被移动。

使用一个放置一些窗口部件的非常大的视图

QScrollView的第二种用法（就像上面描述的）适合有少量窗口部件的任何一个维度超过4000像素的非常大的滚动区域。在这种情况下，你调用resizeContents()来设置区域的大小并且重新实现drawContents()来绘制内容。你也可以通过让它们成为viewport()的孩子来添加窗口部件并且使用addChild()来添加它们（这和上面的单一大窗口部件的用法相同）：

    QScrollView* sv = new QScrollView(...);
    QLabel* child1 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child1);
    QLabel* child2 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child2);
    QLabel* child3 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child3);
这里，QScrollView有同样的四个孩子：viewport()、verticalScrollBar()、horizontalScrollBar()和一个小的cornerWidget()。viewport()有三个QLabel对象作为子窗口部件。当视图被滚动，滚动视图会分别移动这些子窗口部件。

使用一个放置很多窗口部件的非常大的视图

QScrollView的最后一个用法（就像上面描述的）适合有很多窗口部件的任何一个维度超过4000像素的非常大的滚动区域。在这种用法中，你可以调用resizeContents()来设置区域的大小并且重新实现drawContents()来绘制内容。然后你调用enableClipper(TRUE)并且添加窗口部件，再一次把它们作为viewport()的孩子并且通过addChild()添加它们：

    QScrollView* sv = new QScrollView(...);
    sv->enableClipper(TRUE);
    QLabel* child1 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child1);
    QLabel* child2 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child2);
    QLabel* child3 = new QLabel("CHILD", sv->viewport());
    sv->addChild(child3);

这里，QScrollView有四个孩子：clipper()（这次不是viewport()）、verticalScrollBar()、horizontalScrollBar()和一个小的cornerWidget()。clipper()有一个孩子：viewport()。viewport()有同样的三个标签作为子窗口部件。当视图被滚动时，viewport()被移动，它的孩子就像通常的子窗口部件那样被移动。

有关所有视图的详细资料

如果你想在视图中使用任何子窗口部件，通常你将使用三种方法中的第一种。

注意你在滚动区域中看到的窗口部件是viewport()窗口部件，不是QScrollView本身。所以例如如果要打开鼠标跟踪，请使用viewport()->setMouseTracking(TRUE)。

为了使拖放生效，你应该在QScrollView上使用setAcceptDrops(TRUE)（因为拖放事件被传送给父对象）。但是为了算出在视图中的合理位置，你将需要把拖动坐标从相对于QScrollView映射到相对于内容，为了做到这点使用viewportToContents()函数。

为了在滚动区域中处理鼠标事件，就像继承其它窗口部件那样继承滚动视图，但是不要重新实现mousePressEvent()，请重新实现contentsMousePressEvent()来替代它。内容特定事件处理器提供滚动视图坐标系统中的转换事件。如果你重新实现mousePressEvent()，你将只会当QScrollView的部分被点击时得到调用——并且这个唯一的部分就是那个“角”（如果你没有设置cornerWidget()）和框架，其它的任何事物都被视口、clipper或者滚动条隐藏。

当你构造一个QScrollView，一些窗口部件标记应用于viewport()而不是被发送给QScrollView中QWidget的构造函数。这适用于WResizeNoErase、WStaticContents、WRepaintNoErase和WPaintClever。关于这些标记请参考Qt::WidgetFlags文档。这里有一些实例：

  • 一个操作图像的窗口部件将使用WResizeNoErase|WStaticContents，因为当它的大小增加时，这个窗口部件自己绘制所有的像素，它对于新的部分只需要一个绘制事件，因为旧的部分保持不变。

  • 一个字处理窗口部件也许使用WResizeNoErase并且一行一行地重新绘制自己来得到比较少闪烁的重定义大小。如果这个窗口部件处在没有文本合理化发生的模式中，它也可以使用WStaticContents，这样它对于新的可视部分只得到一个重绘。

  • 一个当任务移动时背景滚动的滚动游戏窗口部件也许使用WRepaintNoErase（除了WStaticContents和WResizeNoErase之外），这样在滚动进入和滚动退出期间窗口系统背景不闪烁。

子窗口部件可以使用addChild()或moveChild()来移动。使用childX()和childY()来得到子窗口部件的位置。

一个窗口部件可以通过setCornerWidget()被放置到垂直滚动条和水平滚动条之间的角里。你可以使用horizontalScrollBar()和verticalScrollBar()获得到滚动条的访问，并且使用viewport()来得到视口。滚动视图可以使用scrollBy()、ensureVisible()、setContentsPos()或center()来被滚动。

可视区域由visibleWidth()和visibleHeight()给定，并且内容区域由contentsWidth()和contentsHeight()给定。内容可以使用repaintContents()或updateContents()之一来重新绘制。

坐标转换由contentsToViewport()和viewportToContents()提供。

contentsMoving()信号正好在内容被移动到新位置之前被发射。

警告： WResizeNoErase是当前的默认设置，也就是说你在滚动视图的子类中一直不得不手工清除背景。这一点将在Qt的未来版本中发生改变并且我们推荐明确地指定这个标记。

也可以参考抽象窗口部件类。

成员类型文档

QScrollView::ResizePolicy

这个枚举类型用来控制QScrollView对重新定义大小事件的反应。这里有四个可能的设置：

  • QScrollView::Default - QScrollView当它不得不选择时，它自动地选择其它设置中的一个。在Qt的这个版本中，如果你使用resizeContents()重新定义内容的大小，QScrollView改变为Manual，如果一个孩子被添加，改变为AutoOne。
  • QScrollView::Manual - 视图保持为resizeContents()设定的大小。
  • QScrollView::AutoOne - 如果只有一个子窗口部件，视图保持为那个窗口部件的大小，否则这个行为是未定义的。
  • QScrollView::AutoOneFit - 如果只有一个子窗口部件，视图保持为那个窗口部件的sizeHint()。如果滚动视图被重新定义为大于孩子的sizeHint()的大小时，孩子将被重新定义大小适合它。如果超过一个孩子，这个行为是未定义的。

QScrollView::ScrollBarMode

这个枚举变量描述QScrollView的滚动条的不同模式。定义的模式有：

  • QScrollView::Auto - 当内容大于所要适合的QScrollView，它显示滚动条，并且否则就不显示。这是默认值。
  • QScrollView::AlwaysOff - QScrollView从不显示滚动条。
  • QScrollView::AlwaysOn - QScrollView一直显示显示滚动条。。

（对于水平和垂直滚动条的模式是互相独立的。）

成员函数文档

QScrollView::QScrollView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个使用parent、name和窗口部件标记f的QScrollView。

这个窗口部件标记WStaticContents、 WRepaintNoErase和WPaintClever被传递给viewport()窗口部件。其它窗口部件标记就像通常一样传递给父对象的构造函数。

QScrollView::~QScrollView ()

销毁这个QScrollView。任何通过addChild()添加的孩子都将被删除。

void QScrollView::addChild ( QWidget * child, int x = 0, int y = 0 ) [虚]

插入窗口部件child到滚动区域的(x, y)位置。位置默认为(0, 0)。如果这个孩子已经在视图中存在，它只被移动。

如果你添加大量的窗口部件，你也许要调用enableClipper(TRUE)。

例如：scrollview/scrollview.cpp。

int QScrollView::bottomMargin () const [保护]

返回下边距。

也可以参考setMargins()。

void QScrollView::center ( int x, int y ) [槽]

滚动内容，这样(x, y)点在可视区域中央。

实例：scrollview/scrollview.cpp。

void QScrollView::center ( int x, int y, float xmargin, float ymargin ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

滚动内容，这样(x, y)点在xmargin和ymargin为边缘（作为可视区域）的范围内可视。

实例：

  • 边缘0.0允许(x, y)在可视区域的边缘。
  • 边缘0.5确保(x, y)在可视区域的中间50％内。
  • 边缘1.0确保(x, y)在可视区域的中央。

bool QScrollView::childIsVisible ( QWidget * child )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

如果child是可视的，返回真。这和child->isVisible()一致。

int QScrollView::childX ( QWidget * child )

返回给定的child窗口部件的X位置。对于已经添加到视图中的窗口部件，请使用这个而不是QWidget::x()。

int QScrollView::childY ( QWidget * child )

返回给定的child窗口部件的Y位置。对于已经添加到视图中的窗口部件，请使用这个而不是QWidget::y()。

QWidget * QScrollView::clipper () const

返回clipper窗口部件。滚动视图中的内容最终被省略来进入clipper窗口部件。

也可以参考visibleWidth和visibleHeight。

void QScrollView::contentsContextMenuEvent ( QContextMenuEvent * e ) [虚 保护]

只要QScrollView收到contextMenuEvent()，这个事件处理器就被调用——鼠标位置被转换为内容中的一个点。

实例：chart/canvasview.cpp。

void QScrollView::contentsDragEnterEvent ( QDragEnterEvent * ) [虚 保护]

只要QScrollView收到dragEnterEvent()，这个事件处理器就被调用——拖动位置被转换为内容中的一个点。

在QTable中被重新实现。

void QScrollView::contentsDragLeaveEvent ( QDragLeaveEvent * ) [虚 保护]

只要QScrollView收到dragLeaveEvent()，这个事件处理器就被调用——拖动位置被转换为内容中的一个点。

在QTable中被重新实现。

void QScrollView::contentsDragMoveEvent ( QDragMoveEvent * ) [虚 保护]

只要QScrollView收到dragMoveEvent()，这个事件处理器就被调用——拖动位置被转换为内容中的一个点。

在QTable中被重新实现。

void QScrollView::contentsDropEvent ( QDropEvent * ) [虚 保护]

只要QScrollView收到dropEvent()，这个事件处理器就被调用——放下位置被转换为内容中的一个点。

在QTable中被重新实现。

int QScrollView::contentsHeight () const

返回内容区域的高度。详细情况请参考“contentsHeight”属性。

void QScrollView::contentsMouseDoubleClickEvent ( QMouseEvent * ) [虚 保护]

只要QScrollView收到mouseDoubleClickEvent()，这个事件处理器就被调用——点击位置被转换为内容中的一个点。

在QListView中被重新实现。

void QScrollView::contentsMouseMoveEvent ( QMouseEvent * ) [虚 保护]

只要QScrollView收到mouseMoveEvent()，这个事件处理器就被调用——鼠标位置被转换为内容中的一个点。

实例：canvas/canvas.cpp和chart/canvasview.cpp。

在QListView中被重新实现。

void QScrollView::contentsMousePressEvent ( QMouseEvent * ) [虚 保护]

只要QScrollView收到mousePressEvent()，这个事件处理器就被调用——按下位置被转换为内容中的一个点。

实例：canvas/canvas.cpp和chart/canvasview.cpp。

在QListView中被重新实现。

void QScrollView::contentsMouseReleaseEvent ( QMouseEvent * ) [虚 保护]

只要QScrollView收到mouseReleaseEvent()，这个事件处理器就被调用——释放位置被转换为内容中的一个点。

在QListView中被重新实现。

void QScrollView::contentsMoving ( int x, int y ) [signal]

这个信号正好在内容被移动到(x, y)位置之前被发射。

也可以参考contentsX和contentsY。

void QScrollView::contentsToViewport ( int x, int y, int & vx, int & vy ) const

把内容中的点(x, y)转换为viewport()窗口部件中的点(vx, vy)。

QPoint QScrollView::contentsToViewport ( const QPoint & p ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回转换为viewport()窗口部件的点的点p。

void QScrollView::contentsWheelEvent ( QWheelEvent * e ) [虚 保护]

只要QScrollView收到wheelEvent()，这个事件处理器就被调用——鼠标位置被转换为内容中的一个点。

int QScrollView::contentsWidth () const

返回内容区域的宽度。详细情况请参考“contentsWidth”属性。

int QScrollView::contentsX () const

返回在视口的左边缘的内容的X坐标。详细情况请参考“contentsX”属性。

int QScrollView::contentsY () const

返回在视口的左边缘的内容的Y坐标。详细情况请参考“contentsY”属性。

QWidget * QScrollView::cornerWidget () const

返回在两个滚动条之间的角落里的窗口部件。

默认情况下，没有角落窗口部件出现。

实例：scrollview/scrollview.cpp。

bool QScrollView::dragAutoScroll () const

如果在拖动移动事件中自动滚动生效，返回真，否则返回假。详细情况请参考“dragAutoScroll”属性。

void QScrollView::drawContents ( QPainter * p, int clipx, int clipy, int clipw, int cliph ) [虚 保护]

如果你正在查看绘制的区域而不是窗口部件，请重新实现这个函数。

这个函数应该使用绘制工具p来绘制内容中的矩形(clipx, clipy, clipw, cliph)。这个裁剪矩形在滚动视图的坐标中。

实例：

  {
    // 在(100000,150000)点填充一个40000*50000的矩形

    // 计算坐标……
    int x1 = 100000, y1 = 150000;
    int x2 = x1+40000-1, y2 = y1+50000-1;

    // 裁剪坐标，这样X/Windows将不会发生问题……
    if (x1 < clipx) x1=clipx;
    if (y1 < clipy) y1=clipy;
    if (x2 > clipx+clipw-1) x2=clipx+clipw-1;
    if (y2 > clipy+cliph-1) y2=clipy+cliph-1;

    // 使用小的坐标来绘制……
    if ( x2 >= x1 && y2 >= y1 )
        p->fillRect(x1, y1, x2-x1+1, y2-y1+1, red);
  }

裁剪矩形和绘制工具p的转化已经被适当地设置了。

实例：qdir/qdir.cpp。

在QCanvasView和QTable中被重新实现。

void QScrollView::drawContentsOffset ( QPainter * p, int offsetx, int offsety, int clipx, int clipy, int clipw, int cliph ) [虚 保护]

仅仅是为了向后兼容。它比使用drawContents(QPainter*,int,int,int,int)更容易。

默认实现是适当地转化绘制工具并且调用drawContents(QPainter*,int,int,int,int)。对于参数p、offsetx、offsety、clipx、clipy、clipw和cliph的解释请参考drawContents。

在QListView中被重新实现。

void QScrollView::enableClipper ( bool y )

当大量的子窗口部件在滚动视图中时，特别是如果它们被一起关闭，滚动的效果可能会损失很多。如果y为真，滚动视图将使用一个额外的窗口部件来把这些子窗口部件组合起来。

注意你只能在添加窗口部件之前调用enableClipper()。

对于一个完全的讨论，请参考这个类的详细描述。

实例：scrollview/scrollview.cpp。

void QScrollView::ensureVisible ( int x, int y ) [槽]

滚动内容，所以点(x, y)在至少50像素的边距内是可视的（如果可能，否则会放在中间）。

void QScrollView::ensureVisible ( int x, int y, int xmargin, int ymargin ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

滚动内容，所以点(x, y)在至少xmargin和ymargin的边距内是可视的（如果可能，否则会放在中间）。

bool QScrollView::eventFilter ( QObject * obj, QEvent * e ) [虚 保护]

这个事件过滤器保证当一个单一内容窗口部件被重新定义大小、显示、隐藏或者销毁时，滚动条会被更新，它把鼠标事件传递给QScrollView。这个事件在e中并且这个对象在obj中。

从QObject中重新实现的。

在QListView中被重新实现。

ScrollBarMode QScrollView::hScrollBarMode () const

返回水平滚动条的模式。详细情况请参考“hScrollBarMode”属性。

bool QScrollView::hasStaticBackground () const

如果QScrollView使用静态背景，返回真，否则返回假。

也可以参考setStaticBackground()。

QScrollBar * QScrollView::horizontalScrollBar () const

返回水平滚动条。它被用来允许快捷键、自动滚动等等和允许改变箭头滚动速度，也就是bar->setSteps( rate, bar->pageStep() )。

它不应该被其他方式操作。

这个函数从来不会返回0。

int QScrollView::leftMargin () const [保护]

返回左边距。

也可以参考setMargins()。

void QScrollView::moveChild ( QWidget * child, int x, int y ) [虚]

重新定义child窗口部件的位置为(x, y)。这个函数和addChild()是一样的。

void QScrollView::removeChild ( QWidget * child )

从滚动区域中移除child窗口部件。注意如果child被删除，这个操作将会自动发生。

void QScrollView::repaintContents ( int x, int y, int w, int h, bool erase = TRUE )

在一个被适当转化的有x、y、w、h定义的矩形上调用repaint()。如果这个矩形不是可视的，那么就什么也没有被重新绘制。如果erase为真，背景会使用背景色来清空。

也可以参考updateContents()。

void QScrollView::repaintContents ( const QRect & r, bool erase = TRUE )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

重新绘制矩形r的内容。如果erase为真，背景会使用背景色来清空。

void QScrollView::repaintContents ( bool erase = TRUE )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

重新绘制内容。如果erase为真，背景会使用背景色来清空。

void QScrollView::resizeContents ( int w, int h ) [virtual slot]

设置内容区域的大小为w像素宽，h像素高并且因此更新视口。

ResizePolicy QScrollView::resizePolicy () const

返回当前重新定义大小的策略。详细情况请参考“resizePolicy”属性。

int QScrollView::rightMargin () const [保护]

返回右边距。

也可以参考setMargins()。

void QScrollView::scrollBy ( int dx, int dy ) [槽]

向左dx、向上dy滚动内容。

void QScrollView::setContentsPos ( int x, int y ) [virtual slot]

滚动内容使点(x, y)在左上角。

实例：process/process.cpp。

void QScrollView::setCornerWidget ( QWidget * corner ) [虚]

设置两个滚动条之间的窗口部件为corner。

你将也需要设置是少一个滚动条的默认为AlwaysOn。

传递0会在角落里不显示窗口部件。

任何以前的corner窗口部件被隐藏。

你可以多次调用使用同一个窗口部件的setCornerWidget()。

你在这里设置的所有窗口部件在QScrollView被销毁的时候都会被它删除，除非在设置完一些其它角落窗口部件（或者0）之后，把这个窗口部件重新定义父对象。

任何最新被放置的窗口部件不应该有当前的父对象。

默认情况下，没有角落窗口部件存在。

也可以参考vScrollBarMode和hScrollBarMode。

实例：scrollview/scrollview.cpp。

void QScrollView::setDragAutoScroll ( bool b ) [虚]

设置在拖动移动事件中自动滚动是否生效为b。详细情况请参考“dragAutoScroll”属性。

void QScrollView::setHBarGeometry ( QScrollBar & hbar, int x, int y, int w, int h ) [虚 保护]

当水平滚动条几何形状发生变化，被调用。它被提供为保护函数这样子类可以做一些有趣的事情，比如在通常由滚动条使用的一些空间上提供额外的按钮。

默认实现简单地把所有的空间给hbar。新的几何形状由x、y、w和h给定。

也可以参考setVBarGeometry()。

void QScrollView::setHScrollBarMode ( ScrollBarMode ) [虚]

设置水平滚动条的模式。详细情况请参考“hScrollBarMode”属性。

void QScrollView::setMargins ( int left, int top, int right, int bottom ) [虚 保护]

设置滚动区域周围的边距为left、top、right和bottom。这对于一些像电子制表软件要“锁定”行或列的应用程序很有用。边距空间在frameRect()之内并且是空白的，重新实现drawContents()或者在没有被使用的区域放上窗口部件。

默认情况下，所有边距为0。

也可以参考frameChanged()。

void QScrollView::setResizePolicy ( ResizePolicy ) [虚]

设置当前重新定义大小的策略。详细情况请参考“resizePolicy”属性。

void QScrollView::setStaticBackground ( bool y )

如果y为真，设置滚动视图有一个静态背景，否则如果y为假，就是一个滚动背景。默认情况，背景是滚动的。

要知道这种方式是非常慢的，比如，每一个内容移动都不得不触发可视区域完全重新绘制。

也可以参考hasStaticBackground()。

void QScrollView::setVBarGeometry ( QScrollBar & vbar, int x, int y, int w, int h ) [虚 保护]

当垂直滚动条几何形状发生变化，被调用。它被提供为保护函数这样子类可以做一些有趣的事情，比如在通常由滚动条使用的一些空间上提供额外的按钮。

默认实现简单地把所有的空间给vbar。新的几何形状由x、y、w和h给定。

也可以参考setHBarGeometry()。

void QScrollView::setVScrollBarMode ( ScrollBarMode ) [虚]

设置垂直滚动条的模式。详细情况请参考“vScrollBarMode”属性。

void QScrollView::showChild ( QWidget * child, bool y = TRUE )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

设置child的可视性。等于QWidget::show()或QWidget::hide()。

int QScrollView::topMargin () const [保护]

返回上边距。

也可以参考setMargins()。

void QScrollView::updateContents ( int x, int y, int w, int h )

在一个被适当转化的有x、y、w、h定义的矩形上调用update()。如果这个矩形不是可视的，那么就什么也没有被重新绘制。

也可以参考repaintContents()。

void QScrollView::updateContents ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

更新矩形r中的内容。

void QScrollView::updateContents ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

void QScrollView::updateScrollBars () [槽]

更新滚动条——所有可能性都被考虑了。你应该永远不需要在你的代码中调用这个函数。

ScrollBarMode QScrollView::vScrollBarMode () const

返回垂直滚动条的模式。详细情况请参考“vScrollBarMode”属性。

QScrollBar * QScrollView::verticalScrollBar () const

返回垂直滚动条。它被用来允许快捷键、自动滚动等等和允许改变箭头滚动速度，也就是bar->setSteps( rate, bar->pageStep() )。

它不应该被其他方式操作。

这个函数从来不会返回0。

QWidget * QScrollView::viewport () const

返回滚动视图中的视口窗口部件。这个窗口部件包含内容窗口部件或者要画的区域。

实例：scrollview/scrollview.cpp。

void QScrollView::viewportPaintEvent ( QPaintEvent * pe ) [虚 保护]

这是一个绘制视口内容的低水平的绘制常规程序。如果drawContents()太高水平的话（例如，如果你不想在视口上打开QPainter），重新实现这个函数。绘制事件被传递进pe。

void QScrollView::viewportResizeEvent ( QResizeEvent * ) [虚 保护]

提供内容上的事件的简单处理，这个函数接收所有发送给视口的重新定义大小事件。

也可以参考QWidget::resizeEvent()。

实例：chart/canvasview.cpp。

QSize QScrollView::viewportSize ( int x, int y ) const

返回视口的大小(x, y)。

视口大小依赖于(x, y)（内容的大小）、这个窗口部件的大小和水平和垂直滚动条的模式。

这个函数允许窗口部件互相交换垂直和水平空间来更好地控制滚动条的外观。例如，一个字处理器或者网页浏览器可以精确地控制右边距的宽度来决定它是否需要一个垂直滚动条。

void QScrollView::viewportToContents ( int vx, int vy, int & x, int & y ) const

把viewport()窗口部件中的点(vx, vy)转换为内容中的点(x, y)。

QPoint QScrollView::viewportToContents ( const QPoint & vp ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回转换为内容中的点的视口的点vp。

int QScrollView::visibleHeight () const

返回可视内容的垂直总量。详细情况请参考“visibleHeight”属性。

int QScrollView::visibleWidth () const

返回可视内容的水平总量。详细情况请参考“visibleWidth”属性。

属性文档

int contentsHeight

这个属性保存的是内容区域的高度。

通过contentsHeight()来获得属性值。

int contentsWidth

这个属性保存的是内容区域的宽度。

通过contentsWidth()来获得属性值。

int contentsX

这个属性保存的是在视口的左边缘的内容的X坐标。

通过contentsX()来获得属性值。

int contentsY

这个属性保存的是在视口的左边缘的内容的Y坐标。

通过contentsY()来获得属性值。

bool dragAutoScroll

这个属性保存的是在拖动移动事件中自动滚动是否生效。

如果这个属性被设置为真（默认），如果用户移动光标接近视图的边框，QScrollView会在拖动移动事件中自动滚动内容。当然这只在视口允许放下的情况才能工作。指定为假将使自动滚动特征失效。

通过setDragAutoScroll()来设置属性值并且通过dragAutoScroll()来获得属性值。

ScrollBarMode hScrollBarMode

这个属性保存的是水平滚动条模式。

默认模式为QScrollView::Auto。

也可以参考vScrollBarMode。

通过setHScrollBarMode()设置属性值并且通过hScrollBarMode()来获得属性值。

ResizePolicy resizePolicy

这个属性保存的是当前重定义大小策略。

默认为Default。

也可以参考ResizePolicy。

通过setResizePolicy()设置属性值并且通过resizePolicy()来获得属性值。

ScrollBarMode vScrollBarMode

这个属性保存的是垂直滚动条模式。

默认模式为QScrollView::Auto。

也可以参考hScrollBarMode。

通过setVScrollBarMode()设置属性值并且通过vScrollBarMode()来获得属性值。

int visibleHeight

这个属性保存的是可视内容的垂直总量。

通过visibleHeight()来获得属性值。

int visibleWidth

这个属性保存的是可视内容的水平总量。

通过visibleWidth()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qscrollview.h包含文件

qscrollview.h

这里是qscrollview.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qscrollview.h   3.0.5   edited Nov 9 2001 $
**
** Definition of QScrollView class
**
** Created : 970523
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QSCROLLVIEW_H
#define QSCROLLVIEW_H

#ifndef QT_H
#include "qframe.h"
#include "qscrollbar.h"
#endif // QT_H

#ifndef QT_NO_SCROLLVIEW

class QScrollViewData;

class Q_EXPORT QScrollView : public QFrame
{
    Q_OBJECT
    Q_ENUMS( ResizePolicy ScrollBarMode )
    Q_PROPERTY( ResizePolicy resizePolicy READ resizePolicy WRITE setResizePolicy )
    Q_PROPERTY( ScrollBarMode vScrollBarMode READ vScrollBarMode WRITE setVScrollBarMode )
    Q_PROPERTY( ScrollBarMode hScrollBarMode READ hScrollBarMode WRITE setHScrollBarMode )
    Q_PROPERTY( int visibleWidth READ visibleWidth )
    Q_PROPERTY( int visibleHeight READ visibleHeight )
    Q_PROPERTY( int contentsWidth READ contentsWidth )
    Q_PROPERTY( int contentsHeight READ contentsHeight )
    Q_PROPERTY( int contentsX READ contentsX )
    Q_PROPERTY( int contentsY READ contentsY )
#ifndef QT_NO_DRAGANDDROP
    Q_PROPERTY( bool dragAutoScroll READ dragAutoScroll WRITE setDragAutoScroll )
#endif

public:
    QScrollView(QWidget* parent=0, const char* name=0, WFlags f=0);
    ~QScrollView();

    enum ResizePolicy { Default, Manual, AutoOne, AutoOneFit };
    virtual void setResizePolicy( ResizePolicy );
    ResizePolicy resizePolicy() const;

    void styleChange(QStyle&);
    void removeChild(QWidget* child);
    virtual void addChild( QWidget* child, int x=0, int y=0 );
    virtual void moveChild( QWidget* child, int x, int y );
    int childX(QWidget* child);
    int childY(QWidget* child);
    bool childIsVisible(QWidget* child) { return child->isVisible(); } // obsolete functions
    void showChild(QWidget* child, bool yes=TRUE) {
    if ( yes )
        child->show();
    else
        child->hide();
    }

    enum ScrollBarMode { Auto, AlwaysOff, AlwaysOn };

    ScrollBarMode vScrollBarMode() const;
    virtual void  setVScrollBarMode( ScrollBarMode );

    ScrollBarMode hScrollBarMode() const;
    virtual void  setHScrollBarMode( ScrollBarMode );

    QWidget*     cornerWidget() const;
    virtual void setCornerWidget(QWidget*);

    QScrollBar*  horizontalScrollBar() const;
    QScrollBar*  verticalScrollBar() const;
    QWidget*	 viewport() const;
    QWidget*	 clipper() const;

    int		visibleWidth() const;
    int		visibleHeight() const;

    int		contentsWidth() const;
    int		contentsHeight() const;
    int		contentsX() const;
    int		contentsY() const;

    void	resize( int w, int h );
    void	resize( const QSize& );
    void	show();

    void	updateContents( int x, int y, int w, int h );
    void	updateContents( const QRect& r );
    void 	updateContents();
    void	repaintContents( int x, int y, int w, int h, bool erase=TRUE );
    void	repaintContents( const QRect& r, bool erase=TRUE );
    void 	repaintContents( bool erase=TRUE );
    void	contentsToViewport( int x, int y, int& vx, int& vy ) const;
    void	viewportToContents( int vx, int vy, int& x, int& y ) const;
    QPoint	contentsToViewport( const QPoint& ) const;
    QPoint	viewportToContents( const QPoint& ) const;
    void	enableClipper( bool y );

    void	setStaticBackground( bool y );
    bool	hasStaticBackground() const;

    QSize	viewportSize( int, int ) const;
    QSize	sizeHint() const;
    QSize	minimumSizeHint() const;

    void	removeChild(QObject* child);

#ifndef QT_NO_DRAGANDDROP
    virtual void setDragAutoScroll( bool b );
    bool	 dragAutoScroll() const;
#endif

signals:
    void	contentsMoving(int x, int y);

public slots:
    virtual void resizeContents( int w, int h );
    void	scrollBy( int dx, int dy );
    virtual void setContentsPos( int x, int y );
    void	ensureVisible(int x, int y);
    void	ensureVisible(int x, int y, int xmargin, int ymargin);
    void	center(int x, int y);
    void	center(int x, int y, float xmargin, float ymargin);

    void	updateScrollBars();
    void	setEnabled( bool enable );

protected:
    virtual void drawContents(QPainter*, int cx, int cy, int cw, int ch);
    virtual void drawContentsOffset(QPainter*, int ox, int oy,
            int cx, int cy, int cw, int ch);

    virtual void contentsMousePressEvent( QMouseEvent* );
    virtual void contentsMouseReleaseEvent( QMouseEvent* );
    virtual void contentsMouseDoubleClickEvent( QMouseEvent* );
    virtual void contentsMouseMoveEvent( QMouseEvent* );
#ifndef QT_NO_DRAGANDDROP
    virtual void contentsDragEnterEvent( QDragEnterEvent * );
    virtual void contentsDragMoveEvent( QDragMoveEvent * );
    virtual void contentsDragLeaveEvent( QDragLeaveEvent * );
    virtual void contentsDropEvent( QDropEvent * );
#endif
#ifndef QT_NO_WHEELEVENT
    virtual void contentsWheelEvent( QWheelEvent * );
#endif
    virtual void contentsContextMenuEvent( QContextMenuEvent * );

    virtual void viewportPaintEvent( QPaintEvent* );
    virtual void viewportResizeEvent( QResizeEvent* );
    virtual void viewportMousePressEvent( QMouseEvent* );
    virtual void viewportMouseReleaseEvent( QMouseEvent* );
    virtual void viewportMouseDoubleClickEvent( QMouseEvent* );
    virtual void viewportMouseMoveEvent( QMouseEvent* );
#ifndef QT_NO_DRAGANDDROP
    virtual void viewportDragEnterEvent( QDragEnterEvent * );
    virtual void viewportDragMoveEvent( QDragMoveEvent * );
    virtual void viewportDragLeaveEvent( QDragLeaveEvent * );
    virtual void viewportDropEvent( QDropEvent * );
#endif
#ifndef QT_NO_WHEELEVENT
    virtual void viewportWheelEvent( QWheelEvent * );
#endif
    virtual void viewportContextMenuEvent( QContextMenuEvent * );

    void	frameChanged();

    virtual void setMargins(int left, int top, int right, int bottom);
    int leftMargin() const;
    int topMargin() const;
    int rightMargin() const;
    int bottomMargin() const;

    bool focusNextPrevChild( bool next );

    virtual void setHBarGeometry(QScrollBar& hbar, int x, int y, int w, int h);
    virtual void setVBarGeometry(QScrollBar& vbar, int x, int y, int w, int h);

    void	resizeEvent(QResizeEvent*);
    void 	mousePressEvent( QMouseEvent * );
    void 	mouseReleaseEvent( QMouseEvent * );
    void 	mouseDoubleClickEvent( QMouseEvent * );
    void 	mouseMoveEvent( QMouseEvent * );
#ifndef QT_NO_WHEELEVENT
    void 	wheelEvent( QWheelEvent * );
#endif
    void	contextMenuEvent( QContextMenuEvent * );
    bool	eventFilter( QObject *, QEvent *e );

private:
    void drawContents( QPainter* );
    void moveContents(int x, int y);

    QScrollViewData* d;

private slots:
    void hslide(int);
    void vslide(int);
#ifndef QT_NO_DRAGANDDROP
    void doDragAutoScroll();
    void startDragAutoScroll();
    void stopDragAutoScroll();
#endif

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QScrollView( const QScrollView & );
    QScrollView &operator=( const QScrollView & );
#endif
    void changeFrameRect(const QRect&);
};

#endif // QT_NO_SCROLLVIEW

#endif // QSCROLLVIEW_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QScrollView成员列表

完整的QScrollView成员列表

这里是QScrollView成员函数的完整列表，包括继承的成员。

  • QScrollView()
  • ~QScrollView()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bottomMargin()
  • caption()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • cornerWidget()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • rightMargin()
  • scroll()
  • scrollBy()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setContentsPos()
  • setCornerWidget()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizePolicy()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSemaphore类

QSemaphore类参考

QSemaphore类提供了强壮的整数信号量。 详情请见……

#include <qsemaphore.h>

所有成员函数的列表。

公有成员

  • QSemaphore ( int maxcount )
  • virtual ~QSemaphore ()
  • int available () const
  • int total () const
  • int operator++ ( int )
  • int operator-- ( int )
  • int operator+= ( int n )
  • int operator-= ( int n )
  • bool tryAccess ( int n )

详细描述

QSemaphore类提供了强壮的整数信号量。

QSemaphore也可以被用来使线程的执行顺序化，和QMutex的方法相似。信号量和互斥量的不同在于，信号量可以在同一时间被多于一个的线程访问。

例如，假设我们有一个应用程序把数据存储到一个大的树型结构中。应用程序创建了10个线程（通常被称作线程池）来执行树中的搜索。当应用程序搜索树中的一小片数据，它在每个基本节点上使用一个线程来执行搜索。一个信号量就可以用来确保两个线程不必在同一时间内试图对树的同一个分支进行搜索。

一个信号量的非计算实例是在餐馆就餐。信号量被初始化为最大值等于餐馆内的椅子数。当人们来了，他们想要一个座位。当座位满了，信号量就被访问，每次一个人。当人们离开了，访问就被释放，允许更多的人进入。如果一个10人的聚会想坐下，但是这里只有9个座位，那么这10个人就必须等，但是一个4人的聚会就可以坐下了（剩下的座位就是5了，那么那10个人就得等更长的时间了）。

当信号量被创建时，它被给定为一个它所允许的同时访问的最大数值。这个数量可以使用operator++()、operator--()、operator+=()和operator-=()来改变。允许访问的数字可以使用available()重新得到，并且总量可以通过total()得到。注意如果没有足够多的可使用的访问，增加函数将会阻塞。如果你需要得到不阻塞的访问，请使用tryAccess()。

也可以参考环境类和线程类。

成员函数文档

QSemaphore::QSemaphore ( int maxcount )

创建一个新的信号量。这个信号量可以同时被最多maxcount次访问。

QSemaphore::~QSemaphore () [虚]

销毁这个信号量。

int QSemaphore::available () const

这个函数返回信号量当前可使用的访问的数量。

int QSemaphore::operator++ ( int )

后置++操作符。

试图得到信号量的访问。如果available() == 0，这个调用将会阻塞，一直到它能够得到访问，比如直到available() > 0。

int QSemaphore::operator+= ( int n )

试图得到信号量的访问。如果available() < n，这个调用将会阻塞，一直到它能够得到访问，比如直到available() >= n。

int QSemaphore::operator-- ( int )

后置--操作符。

释放信号量的访问。这将会唤醒所有等待访问这个信号量的线程。

int QSemaphore::operator-= ( int n )

释放信号量的n个访问。

int QSemaphore::total () const

这个函数返回信号量的最大访问数。

bool QSemaphore::tryAccess ( int n )

试图得到信号量的访问。如果available() < n，这个函数会立即返回假。如果If available() >= n，这个函数会得到n个访问并且返回真。这个函数是不阻塞的。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qsemaphore.h包含文件

qsemaphore.h

这里是qsemaphore.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QSemaphore class
**
** Created : 931107
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSEMAPHORE_H
#define QSEMAPHORE_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

#if defined(QT_THREAD_SUPPORT)

class QSemaphorePrivate;

class Q_EXPORT QSemaphore
{
public:
    QSemaphore( int );
    virtual ~QSemaphore();

    int available() const;
    int total() const;

    // postfix operators
    int operator++(int);
    int operator--(int);

    int operator+=(int);
    int operator-=(int);

    bool tryAccess(int);

private:
    QSemaphorePrivate *d;

#if defined(Q_DISABLE_COPY)
    QSemaphore(const QSemaphore &);
    QSemaphore &operator=(const QSemaphore &);
#endif
};

#endif

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSemaphore成员列表

完整的QSemaphore成员列表

这里是QSemaphore成员函数的完整列表，包括继承的成员。

  • QSemaphore()
  • ~QSemaphore()
  • available()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • total()
  • tryAccess()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QServerSocket Class

QServerSocket Class Reference
[network module]

The QServerSocket class provides a TCP-based server. More...

#include <qserversocket.h>

Inherits QObject.

List of all member functions.

Public Members

  • QServerSocket ( Q_UINT16 port, int backlog = 1, QObject * parent = 0, const char * name = 0 )
  • QServerSocket ( const QHostAddress & address, Q_UINT16 port, int backlog = 1, QObject * parent = 0, const char * name = 0 )
  • QServerSocket ( QObject * parent = 0, const char * name = 0 )
  • virtual ~QServerSocket ()
  • bool ok () const
  • Q_UINT16 port () const
  • int socket () const
  • virtual void setSocket ( int socket )
  • QHostAddress address () const
  • virtual void newConnection ( int socket ) = 0

Protected Members

  • QSocketDevice * socketDevice ()

Detailed Description

The QServerSocket class provides a TCP-based server.

This class is a convenience class for accepting incoming TCP connections. You can specify the port or have QServerSocket pick one, and listen on just one address or on all the machine's addresses.

Using the API is very simple: subclass QServerSocket, call the constructor of your choice, and implement newConnection() to handle new incoming connections. There is nothing more to do.

(Note that due to lack of support in the underlying APIs, QServerSocket cannot accept or reject connections conditionally.)

See also QSocket, QSocketDevice, QHostAddress, QSocketNotifier and Input/Output and Networking.

Member Function Documentation

QServerSocket::QServerSocket ( Q_UINT16 port, int backlog = 1, QObject * parent = 0, const char * name = 0 )

Creates a server socket object, that will serve the given port on all the addresses of this host. If port is 0, QServerSocket will pick a suitable port in a system-dependent manner. Use backlog to specify how many pending connections the server can have.

The parent and name arguments are passed on to the QObject constructor.

Warning: On Tru64 Unix systems a value of 0 for backlog means that you don't accept any connections at all; you should specify a value larger than 0.

QServerSocket::QServerSocket ( const QHostAddress & address, Q_UINT16 port, int backlog = 1, QObject * parent = 0, const char * name = 0 )

Creates a server socket object, that will serve the given port only on the given address. Use backlog to specify how many pending connections the server can have.

The parent and name arguments are passed on to the QObject constructor.

Warning: On Tru64 Unix systems a value of 0 for backlog means that you don't accept any connections at all; you should specify a value larger than 0.

QServerSocket::QServerSocket ( QObject * parent = 0, const char * name = 0 )

Construct an empty server socket.

This constructor, in combination with setSocket(), allows us to use the QServerSocket class as a wrapper for other socket types (e.g. Unix Domain Sockets under Unix).

The parent and name arguments are passed on to the QObject constructor.

See also setSocket().

QServerSocket::~QServerSocket () [virtual]

Destroys the socket.

This causes any backlogged connections (connections that have reached the host, but not yet been completely set up by calling QSocketDevice::accept()) to be severed.

Existing connections continue to exist; this only affects the acceptance of new connections.

QHostAddress QServerSocket::address () const

Returns the address on which this object listens, or 0.0.0.0 if this object listens on more than one address. ok() must be TRUE before calling this function.

See also port() and QSocketDevice::address().

void QServerSocket::newConnection ( int socket ) [pure virtual]

This pure virtual function is responsible for setting up a new incoming connection. socket is the fd (file descripor) for the newly accepted connection.

bool QServerSocket::ok () const

Returns TRUE if the construction succeeded; otherwise returns FALSE.

Q_UINT16 QServerSocket::port () const

Returns the port number on which this server socket listens. This is always non-zero; if you specify 0 in the constructor, QServerSocket will pick a non-zero port itself. ok() must be TRUE before calling this function.

See also address() and QSocketDevice::port().

Example: network/httpd/httpd.cpp.

void QServerSocket::setSocket ( int socket ) [virtual]

Sets the socket to use socket. bind() and listen() should already have been called for socket.

This allows us to use the QServerSocket class as a wrapper for other socket types (e.g. Unix Domain Sockets under Unix).

int QServerSocket::socket () const

Returns the operating system socket.

QSocketDevice * QServerSocket::socketDevice () [protected]

Returns a pointer to the internal socket device. The returned pointer is null if there is no connection or pending connection.

There is normally no need to manipulate the socket device directly since this class does all the necessary setup for most client or server socket applications.

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


qserversocket.h Include File

qserversocket.h

This is the verbatim text of the qserversocket.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qserversocket.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QServerSocketClass.
**
** Created : 970521
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSERVERSOCKET_H
#define QSERVERSOCKET_H

#ifndef QT_H
#include "qobject.h"
#include "qhostaddress.h"
#include "qsocketdevice.h" // ### remove or keep for users' convenience?
#endif // QT_H
#ifndef QT_NO_NETWORK

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_NETWORK
#else
#define QM_EXPORT_NETWORK Q_EXPORT
#endif

class QServerSocketPrivate;

class QM_EXPORT_NETWORK QServerSocket : public QObject
{
    Q_OBJECT
public:
    QServerSocket( Q_UINT16 port, int backlog = 1,
           QObject *parent=0, const char *name=0 );
    QServerSocket( const QHostAddress & address, Q_UINT16 port, int backlog = 1,
           QObject *parent=0, const char *name=0 );
    QServerSocket( QObject *parent=0, const char *name=0 );
    virtual ~QServerSocket();

    bool ok() const;

    Q_UINT16 port() const ;

    int socket() const ;
    virtual void setSocket( int socket );

    QHostAddress address() const ;

    virtual void newConnection( int socket ) = 0;

protected:
    QSocketDevice *socketDevice();

private slots:
    void incomingConnection( int socket );

private:
    QServerSocketPrivate *d;
    void init( const QHostAddress & address, Q_UINT16 port, int backlog );
};

#endif // QT_NO_NETWORK
#endif // QSERVERSOCKET_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QServerSocket Member List

Complete Member List for QServerSocket

This is the complete list of member functions for QServerSocket, including inherited members.

  • QServerSocket()
  • ~QServerSocket()
  • address()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • newConnection()
  • normalizeSignalSlot()
  • objectTrees()
  • ok()
  • parent()
  • port()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • setSocket()
  • signalsBlocked()
  • socket()
  • socketDevice()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QSessionManager Class

QSessionManager Class Reference

The QSessionManager class provides access to the session manager. More...

#include <qsessionmanager.h>

Inherits QObject.

List of all member functions.

Public Members

  • QString sessionId () const
  • void * handle () const
  • bool allowsInteraction ()
  • bool allowsErrorInteraction ()
  • void release ()
  • void cancel ()
  • enum RestartHint { RestartIfRunning, RestartAnyway, RestartImmediately, RestartNever }
  • void setRestartHint ( RestartHint hint )
  • RestartHint restartHint () const
  • void setRestartCommand ( const QStringList & command )
  • QStringList restartCommand () const
  • void setDiscardCommand ( const QStringList & )
  • QStringList discardCommand () const
  • void setManagerProperty ( const QString & name, const QString & value )
  • void setManagerProperty ( const QString & name, const QStringList & value )
  • bool isPhase2 () const
  • void requestPhase2 ()

Detailed Description

The QSessionManager class provides access to the session manager.

The session manager is responsible for session management, most importantly for interruption and resumption. A "session" is a kind of record of the state of the system, e.g. which applications were run at start up and which applications are currently running. The session manager is used to save the session, e.g. when the machine is shut down; and to restore a session, e.g. when the machine is started up. Use QSettings to save and restore an individual application's settings, e.g. window positions, recently used files, etc.

QSessionManager provides an interface between the application and the session manager so that the program can work well with the session manager. In Qt, session management requests for action are handled by the two virtual functions QApplication::commitData() and QApplication::saveState(). Both provide a reference to a session manager object as argument, to allow the application to communicate with the session manager.

During a session management action (i.e. within commitData() and saveState()), no user interaction is possible unless the application got explicit permission from the session manager. You ask for permission by calling allowsInteraction() or, if it's really urgent, allowsErrorInteraction(). Qt does not enforce this, but the session manager may.

You can try to abort the shutdown process by calling cancel(). The default commitData() function does this if some top-level window rejected its closeEvent().

For sophisticated session managers provided on Unix/X11, QSessionManager offers further possibilites to fine-tune an application's session management behavior: setRestartCommand(), setDiscardCommand(), setRestartHint(), setProperty(), requestPhase2(). See the respective function descriptions for further details.

See also Main Window and Related Classes and Environment Classes.

Member Type Documentation

QSessionManager::RestartHint

This enum type defines the circumstances under which this application wants to be restarted by the session manager. The current values are

  • QSessionManager::RestartIfRunning - if the application is still running when the session is shut down, it wants to be restarted at the start of the next session.
  • QSessionManager::RestartAnyway - the application wants to be started at the start of the next session, no matter what. (This is useful for utilities that run just after startup and then quit.)
  • QSessionManager::RestartImmediately - the application wants to be started immediately whenever it is not running.
  • QSessionManager::RestartNever - the application does not want to be restarted automatically.

The default hint is RestartIfRunning.

Member Function Documentation

bool QSessionManager::allowsErrorInteraction ()

This is similar to allowsInteraction(), but also tells the session manager that an error occurred. Session managers may give error interaction request higher priority, which means that it is more likely that an error interaction is permitted. However, you are still not guaranteed that the session manager will allow interaction.

See also allowsInteraction(), release() and cancel().

bool QSessionManager::allowsInteraction ()

Asks the session manager for permission to interact with the user. Returns TRUE if interaction is permitted; otherwise returns FALSE.

The rationale behind this mechanism is to make it possible to synchronize user interaction during a shutdown. Advanced session managers may ask all applications simultaneously to commit their data, resulting in a much faster shutdown.

When the interaction is completed we strongly recommend releasing the user interaction semaphore with a call to release(). This way, other applications may get the chance to interact with the user while your application is still busy saving data. (The semaphore is implicitly released when the application exits.)

If the user decides to cancel the shutdown process during the interaction phase, you must tell the session manager that this has happened by calling cancel().

Here's an example of how an application's QApplication::commitData() might be implemented:

void MyApplication::commitData( QSessionManager& sm ) {
    if ( sm.allowsInteraction() ) {
        switch ( QMessageBox::warning(
                    yourMainWindow,
                    tr("Application Name"),
                    tr("Save changes to document Foo?"),
                    tr("&Yes"),
                    tr("&No"),
                    tr("Cancel"),
                    0, 2) ) {
        case 0: // yes
            sm.release();
            // save document here; if saving fails, call sm.cancel()
            break;
        case 1: // continue without saving
            break;
        default: // cancel
            sm.cancel();
            break;
        }
    } else {
        // we did not get permission to interact, then
        // do something reasonable instead.
    }
}

If an error occurred within the application while saving its data, you may want to try allowsErrorInteraction() instead.

See also QApplication::commitData(), release() and cancel().

void QSessionManager::cancel ()

Tells the session manager to cancel the shutdown process. Applications should not call this function without first asking the user.

See also allowsInteraction() and allowsErrorInteraction().

QStringList QSessionManager::discardCommand () const

Returns the currently set discard command.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = mySession.discardCommand();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also setDiscardCommand(), restartCommand() and setRestartCommand().

void * QSessionManager::handle () const

X11 only: returns a handle to the current SmcConnection.

bool QSessionManager::isPhase2 () const

Returns TRUE if the session manager is currently performing a second session management phase; otherwise returns FALSE.

See also requestPhase2().

void QSessionManager::release ()

Releases the session manager's interaction semaphore after an interaction phase.

See also allowsInteraction() and allowsErrorInteraction().

void QSessionManager::requestPhase2 ()

Requests a second session management phase for the application. The application may then return immediately from the QApplication::commitData() or QApplication::saveState() function, and they will be called again once most or all other applications have finished their session management.

The two phases are useful for applications such as the X11 window manager that need to store information about another application's windows and therefore have to wait until these applications have completed their respective session management tasks.

Note that if another application has requested a second phase it may get called before, simultaneously with, or after your application's second phase.

See also isPhase2().

QStringList QSessionManager::restartCommand () const

Returns the currently set restart command.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = mySession.restartCommand();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also setRestartCommand() and restartHint().

RestartHint QSessionManager::restartHint () const

Returns the application's current restart hint. The default is RestartIfRunning.

See also setRestartHint().

QString QSessionManager::sessionId () const

Returns the identifier of the current session.

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

See also QApplication::sessionId().

void QSessionManager::setDiscardCommand ( const QStringList & )

See also discardCommand() and setRestartCommand().

void QSessionManager::setManagerProperty ( const QString & name, const QStringList & value )

Low-level write access to the application's identification and state record are kept in the session manager.

The property called name has its value set to the string list value.

void QSessionManager::setManagerProperty ( const QString & name, const QString & value )

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

Low-level write access to the application's identification and state records are kept in the session manager.

The property called name has its value set to the string value.

void QSessionManager::setRestartCommand ( const QStringList & command )

If the session manager is capable of restoring sessions it will execute command in order to restore the application. The command defaults to

        appname -session id

The -session option is mandatory; otherwise QApplication cannot tell whether it has been restored or what the current session identifier is. See QApplication::isSessionRestored() and QApplication::sessionId() for details.

If your application is very simple, it may be possible to store the entire application state in additional command line options. This is usually a very bad idea because command lines are often limited to a few hundred bytes. Instead, use QSettings, or temporary files or a database for this purpose. By marking the data with the unique sessionId(), you will be able to restore the application in a future session.

See also restartCommand(), setDiscardCommand() and setRestartHint().

void QSessionManager::setRestartHint ( RestartHint hint )

Sets the application's restart hint to hint. On application startup the hint is set to RestartIfRunning.

Note that these flags are only hints, a session manager may or may not respect them.

We recommend setting the restart hint in QApplication::saveState() because most session managers perform a checkpoint shortly after an application's startup.

See also restartHint().

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


qsessionmanager.h Include File

qsessionmanager.h

This is the verbatim text of the qsessionmanager.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsessionmanager.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSessionManager class
**
** Created : 990510
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSESSIONMANAGER_H
#define QSESSIONMANAGER_H

#ifndef QT_H
#include "qobject.h"
#include "qwindowdefs.h"
#include "qstring.h"
#include "qstringlist.h"
#endif // QT_H
#ifndef QT_NO_SESSIONMANAGER

class QSessionManagerData;

class Q_EXPORT  QSessionManager : public QObject
{
    Q_OBJECT
    QSessionManager( QApplication *app, QString &session );
    ~QSessionManager();
public:
    QString sessionId() const;
#if defined(Q_WS_X11) || defined(Q_WS_MAC)
    void* handle() const;
#endif

    bool allowsInteraction();
    bool allowsErrorInteraction();
    void release();

    void cancel();

    enum RestartHint {
    RestartIfRunning,
    RestartAnyway,
    RestartImmediately,
    RestartNever
    };
    void setRestartHint( RestartHint );
    RestartHint restartHint() const;

    void setRestartCommand( const QStringList& );
    QStringList restartCommand() const;
    void setDiscardCommand( const QStringList& );
    QStringList discardCommand() const;

    void setManagerProperty( const QString& name, const QString& value );
    void setManagerProperty( const QString& name, const QStringList& value );

    bool isPhase2() const;
    void requestPhase2();

private:
    friend class QApplication;
    friend class QBaseApplication;
    QSessionManagerData* d;
};

#endif // QT_NO_SESSIONMANAGER
#endif // QSESSIONMANAGER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSessionManager Member List

Complete Member List for QSessionManager

This is the complete list of member functions for QSessionManager, including inherited members.

  • allowsErrorInteraction()
  • allowsInteraction()
  • blockSignals()
  • cancel()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • discardCommand()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • handle()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isPhase2()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • release()
  • removeChild()
  • removeEventFilter()
  • requestPhase2()
  • restartCommand()
  • restartHint()
  • sender()
  • sessionId()
  • setDiscardCommand()
  • setManagerProperty()
  • setName()
  • setProperty()
  • setRestartCommand()
  • setRestartHint()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QSettings Class

QSettings Class Reference

The QSettings class provides persistent platform-independent application settings. More...

#include <qsettings.h>

List of all member functions.

Public Members

  • QSettings ()
  • ~QSettings ()
  • enum System { Unix = 0, Windows, Mac }
  • bool writeEntry ( const QString & key, bool value )
  • bool writeEntry ( const QString & key, double value )
  • bool writeEntry ( const QString & key, int value )
  • bool writeEntry ( const QString & key, const QString & value )
  • bool writeEntry ( const QString & key, const QStringList & value )
  • bool writeEntry ( const QString & key, const QStringList & value, const QChar & separator )
  • QStringList entryList ( const QString & key ) const
  • QStringList subkeyList ( const QString & key ) const
  • QStringList readListEntry ( const QString & key, bool * ok = 0 )
  • QStringList readListEntry ( const QString & key, const QChar & separator, bool * ok = 0 )
  • QString readEntry ( const QString & key, const QString & def = QString::null, bool * ok = 0 )
  • int readNumEntry ( const QString & key, int def = 0, bool * ok = 0 )
  • double readDoubleEntry ( const QString & key, double def = 0, bool * ok = 0 )
  • bool readBoolEntry ( const QString & key, bool def = 0, bool * ok = 0 )
  • bool removeEntry ( const QString & key )
  • void insertSearchPath ( System s, const QString & path )
  • void removeSearchPath ( System s, const QString & path )

Detailed Description

The QSettings class provides persistent platform-independent application settings.

On Unix systems, QSettings uses text files to store settings. On Windows systems, QSettings uses the system registry. On Mac OS X, QSettings will behave as on Unix, and store to text files.

Each setting comprises an identifying key and the data associated with the key. A key is a unicode string which consists of two or more subkeys. A subkey is a slash, '/', followed by one or more unicode characters (excluding slashes, newlines, carriage returns and equals, '=', signs). The associated data, called the entry or value, may be a boolean, an integer, a double, a string or a list of strings. Entry strings may contain any unicode characters.

If you want to save and restore the entire desktop's settings, i.e. which applications are running, use QSettings to save the settings for each individual application and QSessionManager to save the desktop's session.

Example settings:

    /MyCompany/MyApplication/background color
    /MyCompany/MyApplication/foreground color
    /MyCompany/MyApplication/geometry/x
    /MyCompany/MyApplication/geometry/y
    /MyCompany/MyApplication/geometry/width
    /MyCompany/MyApplication/geometry/height
    /MyCompany/MyApplication/recent files/1
    /MyCompany/MyApplication/recent files/2
    /MyCompany/MyApplication/recent files/3
Each line above is a complete key, made up of subkeys.

A typical usage pattern for application startup:

    QSettings settings;
    settings.insertSearchPath( QSettings::Windows, "/MyCompany" );
    // No search path needed for Unix; see notes further on.
    // Use default values if the keys don't exist
    QString bgColor = settings.readEntry( "/MyApplication/background color", "white" );
    int width = settings.readNumEntry( "/MyApplication/geometry/width", 640 );
    // ...

A typical usage pattern for application exit or 'save preferences':

    QSettings settings;
    settings.insertSearchPath( QSettings::Windows, "/MyCompany" );
    // No search path needed for Unix; see notes further on.
    settings.writeEntry( "/MyApplication/background color", bgColor );
    settings.writeEntry( "/MyApplication/geometry/width", width );
    // ...

You can get a list of entry-holding keys by calling entryList(), and a list of key-holding keys using subkeyList().

    QStringList keys = entryList( "/MyApplication" );
    // keys contains 'background color' and 'foreground color'.

    QStringList keys = entryList( "/MyApplication/recent files" );
    // keys contains '1', '2' and '3'.

    QStringList subkeys = subkeyList( "/MyApplication" );
    // subkeys contains 'geometry' and 'recent files'

    QStringList subkeys = subkeyList( "/MyApplication/recent files" );
    // subkeys is empty.

If you wish to use a different search path call insertSearchPath() as often as necessary to add your preferred paths. Call removeSearchPath() to remove any unwanted paths.

Since settings for Windows are stored in the registry there are size limits as follows:

  • A subkey may not exceed 255 characters.
  • An entry's value may not exceed 16,300 characters.
  • All the values of a key (for example, all the 'recent files' subkeys values), may not exceed 65,535 characters.

These limitations are not enforced on Unix.

Notes for Unix Applications

There is no universally accepted place for storing application settings under Unix. In the examples the settings file will be searched for in the following directories:

  1. $QT_INSTALL_PREFIX/etc/settings
  2. /opt/MyCompany/share/etc
  3. /opt/MyCompany/share/MyApplication/etc
  4. $HOME/.qt
When reading settings the files are searched in the order shown above, with later settings overriding earlier settings. Files for which the user doesn't have read permission are ignored. When saving settings QSettings works in the order shown above, writing to the first settings file for which the user has write permission. ($QT_INSTALL_PREFIX is the directory where Qt was installed. This can be modified by using the configure script's -prefix argument)

If you want to put the settings in a particular place in the filesystem you could do this:

    settings.insertSearchPath( QSettings::Unix, "/opt/MyCompany/share" );

But in practice you may prefer not to use a search path for Unix. For example the following code:

    settings.writeEntry( "/MyApplication/geometry/width", width );
will end up writing the "geometry/width" setting to the file $HOME/.qt/myapplicationrc (assuming that the application is being run by an ordinary user, i.e. not by root).

For multiplatform applications you should ensure that the Windows size limitations are not exceeded.

See also Input/Output and Networking and Miscellaneous Classes.

Member Type Documentation

QSettings::System

  • QSettings::Mac - Macintosh execution environments
  • QSettings::Unix - Mac OS X, Unix, Linux and Unix-like execution environments
  • QSettings::Windows - Windows execution environments

Member Function Documentation

QSettings::QSettings ()

Creates a settings object.

QSettings::~QSettings ()

Destroys the settings object. All modifications made to the settings will automatically be saved.

QStringList QSettings::entryList ( const QString & key ) const

Returns a list of the keys which contain entries under key. Does not return any keys that contain keys.

Example settings:

    /MyCompany/MyApplication/background color
    /MyCompany/MyApplication/foreground color
    /MyCompany/MyApplication/geometry/x
    /MyCompany/MyApplication/geometry/y
    /MyCompany/MyApplication/geometry/width
    /MyCompany/MyApplication/geometry/height

    QStringList keys = entryList( "/MyCompany/MyApplication" );
keys contains 'background color' and 'foreground color'. It does not contain 'geometry' because this key contains keys not entries.

To access the geometry values could either use subkeyList() to read the keys and then read each entry, or simply read each entry directly by specifying its full key, e.g. "/MyCompany/MyApplication/geometry/y".

See also subkeyList().

void QSettings::insertSearchPath ( System s, const QString & path )

Inserts path into the settings search path. The semantics of path depends on the system s.

When s is Windows and the execution environment is not Windows the function does nothing. Similarly when s is Unix and the execution environment is not Unix the function does nothing.

When s is Windows, and the execution environment is Windows, the search path list will be used as the first subfolder of the "Software" folder in the registry.

When reading settings the folders are searched forwards from the first folder (listed below) to the last, with later settings overriding settings found earlier, and ignoring any folders for which the user doesn't have read permission.

  1. HKEY_CURRENT_USER/Software/MyCompany/MyApplication
  2. HKEY_CURRENT_USER/Software/MyApplication
  3. HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication
  4. HKEY_LOCAL_MACHINE/Software/MyApplication

  QSettings settings;
  settings.insertSearchPath( QSettings::Windows, "/MyCompany" );
  settings.writeEntry( "/MyApplication/Tip of the day", TRUE );
The code above will write the subkey "Tip of the day" into the first of the registry folders listed below that is found and for which the user has write permission.
  1. HKEY_LOCAL_MACHINE/Software/MyApplication
  2. HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication
  3. HKEY_CURRENT_USER/Software/MyApplication
  4. HKEY_CURRENT_USER/Software/MyCompany/MyApplication

When s is Unix, and the execution environment is Unix, the search path list will be used when trying to determine a suitable filename for reading and writing settings files. By default, there are two entries in the search path:

  1. $QTDIR/etc - where $QTDIR is the directory where Qt was installed.
  2. $HOME/.qt/ - where $HOME is the user's home directory.

All insertions into the search path will go before $HOME/.qt/. For example:

  QSettings settings;
  settings.insertSearchPath( QSettings::Unix, "/opt/MyCompany/share/etc" );
  settings.insertSearchPath( QSettings::Unix, "/opt/MyCompany/share/MyApplication/etc" );
  // ...
Will result in a search path of:
  1. $QTDIR/etc
  2. /opt/MyCompany/share/etc
  3. /opt/MyCompany/share/MyApplication/etc
  4. $HOME/.qt
When reading settings the files are searched in the order shown above, with later settings overriding earlier settings. Files for which the user doesn't have read permission are ignored. When saving settings QSettings works in the order as shown above, writing to the first settings file for which the user has write permission. ($QTDIR is the directory where Qt was installed.)

Settings under Unix are stored in files whose names are based on the first subkey of the key (not including the search path). The algorithm for creating names is essentially: lowercase the first subkey, replace spaces with underscores and add 'rc', e.g. /MyCompany/MyApplication/background color will be stored in myapplicationrc (assuming that /MyCompany is part of the search path).

See also removeSearchPath().

Example: chart/chartform.cpp.

bool QSettings::readBoolEntry ( const QString & key, bool def = 0, bool * ok = 0 )

Reads the entry specified by key, and returns a bool, or the default value, def, if the entry couldn't be read. If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

See also readEntry(), readNumEntry(), readDoubleEntry(), writeEntry() and removeEntry().

double QSettings::readDoubleEntry ( const QString & key, double def = 0, bool * ok = 0 )

Reads the entry specified by key, and returns a double, or the default value, def, if the entry couldn't be read. If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

See also readEntry(), readNumEntry(), readBoolEntry(), writeEntry() and removeEntry().

QString QSettings::readEntry ( const QString & key, const QString & def = QString::null, bool * ok = 0 )

Reads the entry specified by key, and returns a QString, or the default value, def, if the entry couldn't be read. If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), writeEntry() and removeEntry().

Example: chart/chartform.cpp.

QStringList QSettings::readListEntry ( const QString & key, bool * ok = 0 )

Reads the entry specified by key as a string. If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = mySettings.readListEntry( "recentfiles" );
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() and QStringList::split().

QStringList QSettings::readListEntry ( const QString & key, const QChar & separator, bool * ok = 0 )

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

Reads the entry specified by key as a string. The separator is used to create a QStringList by calling QStringList::split(separator, entry). If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = mySettings.readListEntry( "size", " " );
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() and QStringList::split().

int QSettings::readNumEntry ( const QString & key, int def = 0, bool * ok = 0 )

Reads the entry specified by key, and returns an integer, or the default value, def, if the entry couldn't be read. If ok is non-null, *ok is set to TRUE if the key was read, FALSE otherwise.

See also readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry() and removeEntry().

Example: chart/chartform.cpp.

bool QSettings::removeEntry ( const QString & key )

Removes the entry specified by key.

Returns TRUE if the entry existed and was removed; otherwise returns FALSE.

See also readEntry() and writeEntry().

void QSettings::removeSearchPath ( System s, const QString & path )

Removes all occurrences of path (using exact matching) from the settings search path for system s. Note that the default search paths cannot be removed.

See also insertSearchPath().

QStringList QSettings::subkeyList ( const QString & key ) const

Returns a list of the keys which contain keys under key. Does not return any keys that contain entries.

Example settings:

    /MyCompany/MyApplication/background color
    /MyCompany/MyApplication/foreground color
    /MyCompany/MyApplication/geometry/x
    /MyCompany/MyApplication/geometry/y
    /MyCompany/MyApplication/geometry/width
    /MyCompany/MyApplication/geometry/height
    /MyCompany/MyApplication/recent files/1
    /MyCompany/MyApplication/recent files/2
    /MyCompany/MyApplication/recent files/3

    QStringList keys = subkeyList( "/MyCompany/MyApplication" );
keys contains 'geometry' and 'recent files'. It does not contain 'background color' or 'foreground color' because they are keys which contain entries not keys. To get a list of keys that have values rather than subkeys use entryList().

See also entryList().

bool QSettings::writeEntry ( const QString & key, bool value )

Writes the boolean entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

Example: chart/chartform.cpp.

bool QSettings::writeEntry ( const QString & key, double value )

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

Writes the double entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

bool QSettings::writeEntry ( const QString & key, int value )

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

Writes the integer entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

bool QSettings::writeEntry ( const QString & key, const QString & value )

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

Writes the string entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value. If value is an empty string or a null string the key's value will be an empty string.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

bool QSettings::writeEntry ( const QString & key, const QStringList & value )

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

Writes the string list entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

bool QSettings::writeEntry ( const QString & key, const QStringList & value, const QChar & separator )

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

Writes the string list entry value into key key. The key is created if it doesn't exist. Any previous value is overwritten by value. The list is stored as a sequence of strings separated by separator, so none of the strings in the list should contain the separator. If the list is empty or null the key's value will be an empty string.

If an error occurs the settings are left unchanged and FALSE is returned; otherwise TRUE is returned.

See also readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry() and removeEntry().

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


qsettings.h Include File

qsettings.h

This is the verbatim text of the qsettings.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QSettings class
**
** Created: 2000.06.26
**
** Copyright (C) 2000-2001 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSETTINGS_H
#define QSETTINGS_H

#ifndef QT_H
#include <qdatetime.h>
#include <qstringlist.h>
#endif // QT_H

#ifndef QT_NO_SETTINGS

class QSettingsPrivate;

class Q_EXPORT QSettings
{
public:
    QSettings();
    ~QSettings();

    enum System {
    Unix = 0,
    Windows,
    Mac
    };

#if !defined(Q_NO_BOOL_TYPE)
    bool	writeEntry( const QString &, bool );
#endif
    bool	writeEntry( const QString &, double );
    bool	writeEntry( const QString &, int );
    bool	writeEntry( const QString &, const char * );
    bool	writeEntry( const QString &, const QString & );
    bool	writeEntry( const QString &, const QStringList & );
    bool	writeEntry( const QString &, const QStringList &, const QChar& sep );

    QStringList entryList(const QString &) const;
    QStringList subkeyList(const QString &) const;

    QStringList readListEntry( const QString &, bool * = 0 ); //### const in 4.0
    QStringList readListEntry( const QString &, const QChar& sep, bool * = 0 ); //### const in 4.0
    QString	readEntry( const QString &, const QString &def = QString::null,
               bool * = 0 );//### const in 4.0
    int		readNumEntry( const QString &, int def = 0, bool * = 0 ); //### const in 4.0
    double	readDoubleEntry( const QString &, double def = 0, bool * = 0 ); //### const in 4.0
    bool	readBoolEntry( const QString &, bool def = 0, bool * = 0 ); //### const in 4.0

    bool	removeEntry( const QString & );

    void insertSearchPath( System, const QString & );
    void removeSearchPath( System, const QString & );

private:
    QSettingsPrivate *d;

#if defined(Q_DISABLE_COPY)
    QSettings(const QSettings &);
    QSettings &operator=(const QSettings &);
#endif

    QDateTime lastModficationTime( const QString & );
    bool sync();

    friend class QApplication;
};

#endif // QT_NO_SETTINGS
#endif // QSETTINGS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSettings Member List

Complete Member List for QSettings

This is the complete list of member functions for QSettings, including inherited members.

  • QSettings()
  • ~QSettings()
  • entryList()
  • insertSearchPath()
  • readBoolEntry()
  • readDoubleEntry()
  • readEntry()
  • readListEntry()
  • readNumEntry()
  • removeEntry()
  • removeSearchPath()
  • subkeyList()
  • writeEntry()


QSGIStyle Class

QSGIStyle Class Reference

The QSGIStyle class provides SGI/Irix look and feel. More...

#include <qsgistyle.h>

Inherits QMotifStyle.

List of all member functions.

Public Members

  • QSGIStyle ( bool useHighlightCols = FALSE )
  • virtual ~QSGIStyle ()

Detailed Description

The QSGIStyle class provides SGI/Irix look and feel.

This class implements the SGI look and feel. It resembles the SGI/Irix Motif GUI style as closely as QStyle allows.

See also Widget Appearance and Style.

Member Function Documentation

QSGIStyle::QSGIStyle ( bool useHighlightCols = FALSE )

Constructs a QSGIStyle.

If useHighlightCols is FALSE (default value), the style will polish the application's color palette to emulate the Motif way of highlighting, which is a simple inversion between the base and the text color.

See also QMotifStyle::useHighlightColors().

QSGIStyle::~QSGIStyle () [virtual]

Destroys the style.

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


qsgistyle.h Include File

qsgistyle.h

This is the verbatim text of the qsgistyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsgistyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of SGI-like style class
**
** Created : 981231
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSGISTYLE_H
#define QSGISTYLE_H

#ifndef QT_H
#include "qmotifstyle.h"
#include "qguardedptr.h"
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_STYLE_SGI

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_SGI
#else
#define Q_EXPORT_STYLE_SGI Q_EXPORT
#endif

class QSGIStylePrivate;

class Q_EXPORT_STYLE_SGI QSGIStyle: public QMotifStyle
{
    Q_OBJECT
public:
    QSGIStyle( bool useHighlightCols = FALSE );
    virtual ~QSGIStyle();

    void polish( QWidget* );
    void unPolish( QWidget* );
    void polish( QApplication* );
    void unPolish( QApplication* );

    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags how = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl control,
                 QPainter *p,
                 const QWidget* widget,
                 const QRect& r,
                 const QColorGroup& cg,
                 SFlags how = Style_Default,
                 SCFlags sub = SC_All,
                 SCFlags subActive = SC_None,
                 const QStyleOption& = QStyleOption::Default ) const;

    int pixelMetric( PixelMetric metric, const QWidget *widget = 0 ) const;

    QSize sizeFromContents( ContentsType contents,
                const QWidget *widget,
                const QSize &contentsSize,
                const QStyleOption& = QStyleOption::Default ) const;

    QRect subRect( SubRect r, const QWidget *widget ) const;
    QRect querySubControlMetrics( ComplexControl control,
                  const QWidget *widget,
                  SubControl sc,
                  const QStyleOption& = QStyleOption::Default ) const;

protected:
    bool eventFilter( QObject*, QEvent*);

private:
    QSGIStylePrivate *d;

    uint isApplicationStyle :1;
#if defined(Q_DISABLE_COPY)
    QSGIStyle( const QSGIStyle & );
    QSGIStyle& operator=( const QSGIStyle & );
#endif

};

#endif // QT_NO_STYLE_SGI

#endif // QSGISTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSGIStyle Member List

Complete Member List for QSGIStyle

This is the complete list of member functions for QSGIStyle, including inherited members.

  • QSGIStyle()
  • ~QSGIStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • setUseHighlightColors()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • useHighlightColors()
  • visualRect()


QShowEvent Class

QShowEvent Class Reference

The QShowEvent class provides an event which is sent when a widget is shown. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QShowEvent ()

Detailed Description

The QShowEvent class provides an event which is sent when a widget is shown.

There are two kinds of show events: show events caused by the window system (spontaneous) and internal show events. Spontaneous show events are sent just after the window system shows the window, including after a top-level window has been shown (un-iconified) by the user. Internal show events are delivered just before the widget becomes visible.

See also QHideEvent and Event Classes.

Member Function Documentation

QShowEvent::QShowEvent ()

Constructs a QShowEvent.

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


QShowEvent Member List

Complete Member List for QShowEvent

This is the complete list of member functions for QShowEvent, including inherited members.

  • QShowEvent()
  • spontaneous()
  • type()


QSignal Class

QSignal Class Reference

The QSignal class can be used to send signals for classes that don't inherit QObject. More...

#include <qsignal.h>

Inherits QObject.

List of all member functions.

Public Members

  • QSignal ( QObject * parent = 0, const char * name = 0 )
  • ~QSignal ()
  • bool connect ( const QObject * receiver, const char * member )
  • bool disconnect ( const QObject * receiver, const char * member = 0 )
  • void activate ()
  • bool isBlocked () const (obsolete)
  • void block ( bool b ) (obsolete)
  • void setParameter ( int value ) (obsolete)
  • int parameter () const (obsolete)
  • void setValue ( const QVariant & value )
  • QVariant value () const

Detailed Description

The QSignal class can be used to send signals for classes that don't inherit QObject.

If you want to send signals from a class that does not inherit QObject, you can create an internal QSignal object to emit the signal. You must also provide a function that connects the signal to an outside object slot. This is how we have implemented signals in the QMenuData class, which is not a QObject.

In general, we recommend inheriting QObject instead. QObject provides much more functionality.

You can set a single QVariant parameter for the signal with setValue().

Note that QObject is a private base class of QSignal, i.e. you cannot call any QObject member functions from a QSignal object.

Example:

        #include <qsignal.h>

        class MyClass
        {
        public:
            MyClass();
            ~MyClass();

            void doSomething();

            void connect( QObject *receiver, const char *member );

        private:
            QSignal *sig;
        };

        MyClass::MyClass()
        {
            sig = new QSignal;
        }

        MyClass::~MyClass()
        {
            delete sig;
        }

        void MyClass::doSomething()
        {
            // ... does something
            sig->activate(); // emits the signal
        }

        void MyClass::connect( QObject *receiver, const char *member )
        {
            sig->connect( receiver, member );
        }

See also Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QSignal::QSignal ( QObject * parent = 0, const char * name = 0 )

Constructs a signal object called name, with the parent object parent. These arguments are passed directly to QObject.

QSignal::~QSignal ()

Destroys the signal. All connections are removed, as is the case with all QObjects.

void QSignal::activate ()

Emits the signal. If the platform supports QVariant and a parameter has been set with setValue(), this value is passed in the signal.

void QSignal::block ( bool b )

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

Blocks the signal if b is TRUE, or unblocks the signal if b is FALSE.

An activated signal disappears into hyperspace if it is blocked.

See also isBlocked(), activate() and QObject::blockSignals().

bool QSignal::connect ( const QObject * receiver, const char * member )

Connects the signal to member in object receiver.

See also disconnect() and QObject::connect().

bool QSignal::disconnect ( const QObject * receiver, const char * member = 0 )

Disonnects the signal from member in object receiver.

See also connect() and QObject::disconnect().

bool QSignal::isBlocked () const

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

Returns TRUE if the signal is blocked, or FALSE if it is not blocked.

The signal is not blocked by default.

See also block() and QObject::signalsBlocked().

int QSignal::parameter () const

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

void QSignal::setParameter ( int value )

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

void QSignal::setValue ( const QVariant & value )

Sets the signal's parameter to value

QVariant QSignal::value () const

Returns the signal's parameter

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


qsignal.h Include File

qsignal.h

This is the verbatim text of the qsignal.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsignal.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSignal class
**
** Created : 941201
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIGNAL_H
#define QSIGNAL_H

#ifndef QT_H
#include "qvariant.h"
#include "qobject.h"
#endif // QT_H

class Q_EXPORT QSignal : public QObject
{
    Q_OBJECT

public:
    QSignal( QObject *parent=0, const char *name=0 );
    ~QSignal();

    bool	connect( const QObject *receiver, const char *member );
    bool	disconnect( const QObject *receiver, const char *member=0 );

    void	activate();

#ifndef QT_NO_COMPAT
    bool	isBlocked()	 const		{ return QObject::signalsBlocked(); }
    void	block( bool b )		{ QObject::blockSignals( b ); }
#ifndef QT_NO_VARIANT
    void	setParameter( int value );
    int		parameter() const;
#endif
#endif

#ifndef QT_NO_VARIANT
    void	setValue( const QVariant &value );
    QVariant	value() const;
#endif
signals:
#ifndef QT_NO_VARIANT
    void signal( const QVariant& );
#endif
    void intSignal( int );

private:
#ifndef QT_NO_VARIANT
    QVariant val;
#endif
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSignal( const QSignal & );
    QSignal &operator=( const QSignal & );
#endif
};

#endif // QSIGNAL_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSignal Member List

Complete Member List for QSignal

This is the complete list of member functions for QSignal, including inherited members.

  • QSignal()
  • ~QSignal()
  • activate()
  • block()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isBlocked()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parameter()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setParameter()
  • setProperty()
  • setValue()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • value()


QSignalMapper Class

QSignalMapper Class Reference

The QSignalMapper class bundles signals from identifiable senders. More...

#include <qsignalmapper.h>

Inherits QObject.

List of all member functions.

Public Members

  • QSignalMapper ( QObject * parent, const char * name = 0 )
  • ~QSignalMapper ()
  • virtual void setMapping ( const QObject * sender, int identifier )
  • virtual void setMapping ( const QObject * sender, const QString & identifier )
  • void removeMappings ( const QObject * sender )

Public Slots

  • void map ()

Signals

  • void mapped ( int )
  • void mapped ( const QString & )

Detailed Description

The QSignalMapper class bundles signals from identifiable senders.

This class collects a set of parameterless signals, and re-emits them with integer or string parameters corresponding to the object that sent the signal.

See also Input/Output and Networking.

Member Function Documentation

QSignalMapper::QSignalMapper ( QObject * parent, const char * name = 0 )

Constructs a QSignalMapper called name, with parent parent. Like all QObjects, it will be deleted when the parent is deleted.

QSignalMapper::~QSignalMapper ()

Destroys the QSignalMapper.

void QSignalMapper::map () [slot]

This slot emits signals based on which object sends signals to it.

Examples: i18n/main.cpp and themes/themes.cpp.

void QSignalMapper::mapped ( int ) [signal]

This signal is emitted when map() is signaled from an object that has an integer mapping set.

See also setMapping().

Examples: i18n/main.cpp and themes/themes.cpp.

void QSignalMapper::mapped ( const QString & ) [signal]

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

This signal is emitted when map() is signaled from an object that has a string mapping set.

See also setMapping().

void QSignalMapper::removeMappings ( const QObject * sender )

Removes all mappings for sender. This is done automatically when mapped objects are destroyed.

void QSignalMapper::setMapping ( const QObject * sender, int identifier ) [virtual]

Adds a mapping so that when map() is signaled from the given sender, the signal mapped(identifier) is emitted.

There may be at most one integer identifier for each object.

Examples: i18n/main.cpp and themes/themes.cpp.

void QSignalMapper::setMapping ( const QObject * sender, const QString & identifier ) [virtual]

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

Adds a mapping so that when map() is signaled from the given sender, the signal mapper(identifier) is emitted.

There may be at most one string identifier for each object, and it may not be null.

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


qsignalmapper.h Include File

qsignalmapper.h

This is the verbatim text of the qsignalmapper.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsignalmapper.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSignalMapper class
**
** Created : 980503
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIGNALMAPPER_H
#define QSIGNALMAPPER_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H
#ifndef QT_NO_SIGNALMAPPER
class  QSignalMapperData;
struct QSignalMapperRec;

class Q_EXPORT QSignalMapper : public QObject {
    Q_OBJECT
public:
    QSignalMapper( QObject* parent, const char* name=0 );
    ~QSignalMapper();

    virtual void setMapping( const QObject* sender, int identifier );
    virtual void setMapping( const QObject* sender, const QString &identifier );
    void removeMappings( const QObject* sender );

signals:
    void mapped(int);
    void mapped(const QString &);

public slots:
    void map();

private:
    QSignalMapperData* d;
    QSignalMapperRec* getRec( const QObject* );

private slots:
    void removeMapping();
};

#endif // QT_NO_SIGNALMAPPER
#endif // QSIGNALMAPPER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSignalMapper Member List

Complete Member List for QSignalMapper

This is the complete list of member functions for QSignalMapper, including inherited members.

  • QSignalMapper()
  • ~QSignalMapper()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • map()
  • mapped()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • removeMappings()
  • sender()
  • setMapping()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QSimpleRichText Class

QSimpleRichText Class Reference

The QSimpleRichText class provides a small displayable piece of rich text. More...

#include <qsimplerichtext.h>

List of all member functions.

Public Members

  • QSimpleRichText ( const QString & text, const QFont & fnt, const QString & context = QString::null, const QStyleSheet * sheet = 0 )
  • QSimpleRichText ( const QString & text, const QFont & fnt, const QString & context, const QStyleSheet * sheet, const QMimeSourceFactory * factory, int pageBreak = -1, const QColor & linkColor = Qt::blue, bool linkUnderline = TRUE )
  • ~QSimpleRichText ()
  • void setWidth ( int w )
  • void setWidth ( QPainter * p, int w )
  • void setDefaultFont ( const QFont & f )
  • int width () const
  • int widthUsed () const
  • int height () const
  • void adjustSize ()
  • void draw ( QPainter * p, int x, int y, const QRect & clipRect, const QColorGroup & cg, const QBrush * paper = 0 ) const
  • void draw ( QPainter * p, int x, int y, const QRegion & clipRegion, const QColorGroup & cg, const QBrush * paper = 0 ) const (obsolete)
  • QString context () const
  • QString anchorAt ( const QPoint & pos ) const
  • bool inText ( const QPoint & pos ) const

Detailed Description

The QSimpleRichText class provides a small displayable piece of rich text.

This class encapsulates simple rich text usage in which a string is interpreted as rich text and can be drawn. This is particularly useful if you want to display some rich text in a custom widget. A QStyleSheet is needed to interpret the tags and format the rich text. Qt provides a default HTML-like style sheet, but you may define custom style sheets.

Once created, the rich text object can be queried for its width(), height(), and the actual width used (see widthUsed()). Most importantly, it can be drawn on any given QPainter with draw(). QSimpleRichText can also be used to implement hypertext or active text facilities by using anchorAt(). A hit test through inText() makes it possible to use simple rich text for text objects in editable drawing canvases.

Once constructed from a string the contents cannot be changed, only resized. If the contents change, just throw the rich text object away and make a new one with the new contents.

For large documents use QTextEdit or QTextBrowser. For very small items of rich text you can use a QLabel.

See also Text Related Classes.

Member Function Documentation

QSimpleRichText::QSimpleRichText ( const QString & text, const QFont & fnt, const QString & context = QString::null, const QStyleSheet * sheet = 0 )

Constructs a QSimpleRichText from the rich text string text and the font fnt.

The font is used as a basis for the text rendering. When using rich text rendering on a widget w, you would normally specify the widget's font, for example:

    QSimpleRichText myrichtext( contents, mywidget->font() );

context is the optional context of the rich text object. This becomes important if text contains relative references, for example within image tags. QSimpleRichText always uses the default mime source factory (see QMimeSourceFactory::defaultFactory()) to resolve those references. The context will then be used to calculate the absolute path. See QMimeSourceFactory::makeAbsolute() for details.

The sheet is an optional style sheet. If it is 0, the default style sheet will be used (see QStyleSheet::defaultSheet()).

QSimpleRichText::QSimpleRichText ( const QString & text, const QFont & fnt, const QString & context, const QStyleSheet * sheet, const QMimeSourceFactory * factory, int pageBreak = -1, const QColor & linkColor = Qt::blue, bool linkUnderline = TRUE )

Constructs a QSimpleRichText from the rich text string text and the font fnt.

This is a slightly more complex constructor for QSimpleRichText that takes an additional mime source factory factory, a page break parameter pageBreak and a bool linkUnderline. linkColor is only provided for compatibility, but has no effect, as QColorGroup's QColorGroup::link() color is used now.

context is the optional context of the rich text object. This becomes important if text contains relative references, for example within image tags. QSimpleRichText always uses the default mime source factory (see QMimeSourceFactory::defaultFactory()) to resolve those references. The context will then be used to calculate the absolute path. See QMimeSourceFactory::makeAbsolute() for details.

The sheet is an optional style sheet. If it is 0, the default style sheet will be used (see QStyleSheet::defaultSheet()).

This constructor is useful for creating a QSimpleRichText object suitable for printing. Set pageBreak to be the height of the contents area of the pages.

QSimpleRichText::~QSimpleRichText ()

Destroys the rich text object, freeing memory.

void QSimpleRichText::adjustSize ()

Adjusts the richt text object to a reasonable size.

See also setWidth().

QString QSimpleRichText::anchorAt ( const QPoint & pos ) const

Returns the anchor at the requested position, pos. An empty string is returned if no anchor is specified for this position.

QString QSimpleRichText::context () const

Returns the context of the rich text object. If no context has been specified in the constructor, a null string is returned. The context is the path to use to look up relative links, such as image tags and anchor references.

void QSimpleRichText::draw ( QPainter * p, int x, int y, const QRect & clipRect, const QColorGroup & cg, const QBrush * paper = 0 ) const

Draws the formatted text with painter p, at position (x, y), clipped to clipRect. The clipping rectangle is given in the rich text object's coordinates translated by (x, y). Colors from the color group cg are used as needed, and if not 0, *paper is used as the background brush.

Note that the display code is highly optimized to reduce flicker, so passing a brush for paper is preferable to simply clearing the area to be painted and then calling this without a brush.

Example: helpviewer/helpwindow.cpp.

void QSimpleRichText::draw ( QPainter * p, int x, int y, const QRegion & clipRegion, const QColorGroup & cg, const QBrush * paper = 0 ) const

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

Use the version with clipRect instead. The region version has problems with larger documents on some platforms (on X11 regions internally are represented with 16bit coordinates).

int QSimpleRichText::height () const

Returns the height of the rich text object in pixels.

See also setWidth().

Example: helpviewer/helpwindow.cpp.

bool QSimpleRichText::inText ( const QPoint & pos ) const

Returns TRUE if pos is within a text line of the rich text object; otherwise returns FALSE.

void QSimpleRichText::setDefaultFont ( const QFont & f )

Sets the default font for the rich text object to f

void QSimpleRichText::setWidth ( QPainter * p, int w )

Sets the width of the rich text object to w pixels, recalculating the layout as if it were to be drawn with painter p.

Passing a painter is useful when you intend drawing on devices other than the screen, for example a QPrinter.

See also height() and adjustSize().

Example: helpviewer/helpwindow.cpp.

void QSimpleRichText::setWidth ( int w )

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

Sets the width of the rich text object to w pixels.

See also height() and adjustSize().

int QSimpleRichText::width () const

Returns the set width of the rich text object in pixels.

See also widthUsed().

int QSimpleRichText::widthUsed () const

Returns the width in pixels that is actually used by the rich text object. This can be smaller or wider than the set width.

It may be wider, for example, if the text contains images or non-breakable words that are already wider than the available space. It's smaller when the object only consists of lines that do not fill the width completely.

See also width().

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


qsimplerichtext.h Include File

qsimplerichtext.h

This is the verbatim text of the qsimplerichtext.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsimplerichtext.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the QSimpleRichText class
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIMPLERICHTEXT_H
#define QSIMPLERICHTEXT_H

#ifndef QT_H
#include "qnamespace.h"
#include "qstring.h"
#include "qregion.h"
#endif // QT_H

#ifndef QT_NO_RICHTEXT

class QPainter;
class QWidget;
class QStyleSheet;
class QBrush;
class QMimeSourceFactory;
class QSimpleRichTextData;

class Q_EXPORT QSimpleRichText
{
public:
    QSimpleRichText( const QString& text, const QFont& fnt,
             const QString& context = QString::null, const QStyleSheet* sheet = 0);
    QSimpleRichText( const QString& text, const QFont& fnt,
             const QString& context,  const QStyleSheet* sheet,
             const QMimeSourceFactory* factory, int pageBreak = -1,
             const QColor& linkColor = Qt::blue, bool linkUnderline = TRUE );
    ~QSimpleRichText();

    void setWidth( int );
    void setWidth( QPainter*, int );
    void setDefaultFont( const QFont &f );
    int width() const;
    int widthUsed() const;
    int height() const;
    void adjustSize();

    void draw( QPainter* p,  int x, int y, const QRect& clipRect,
           const QColorGroup& cg, const QBrush* paper = 0) const;

    // obsolete
    void draw( QPainter* p,  int x, int y, const QRegion& clipRegion,
           const QColorGroup& cg, const QBrush* paper = 0) const {
    draw( p, x, y, clipRegion.boundingRect(), cg, paper );
    }

    QString context() const;
    QString anchorAt( const QPoint& pos ) const;

    bool inText( const QPoint& pos ) const;

private:
    QSimpleRichTextData* d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSimpleRichText( const QSimpleRichText & );
    QSimpleRichText &operator=( const QSimpleRichText & );
#endif
};

#endif // QT_NO_RICHTEXT

#endif // QSIMPLERICHTEXT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSimpleRichText Member List

Complete Member List for QSimpleRichText

This is the complete list of member functions for QSimpleRichText, including inherited members.

  • QSimpleRichText()
  • ~QSimpleRichText()
  • adjustSize()
  • anchorAt()
  • context()
  • draw()
  • height()
  • inText()
  • setDefaultFont()
  • setWidth()
  • width()
  • widthUsed()


QSize类

QSize类参考

QSize定义了一个二维对象的大小。 详情请见……

#include <qsize.h>

所有成员函数的列表。

公有成员

  • QSize ()
  • QSize ( int w, int h )
  • bool isNull () const
  • bool isEmpty () const
  • bool isValid () const
  • int width () const
  • int height () const
  • void setWidth ( int w )
  • void setHeight ( int h )
  • void transpose ()
  • QSize expandedTo ( const QSize & otherSize ) const
  • QSize boundedTo ( const QSize & otherSize ) const
  • QCOORD & rwidth ()
  • QCOORD & rheight ()
  • QSize & operator+= ( const QSize & s )
  • QSize & operator-= ( const QSize & s )
  • QSize & operator*= ( int c )
  • QSize & operator*= ( double c )
  • QSize & operator/= ( int c )
  • QSize & operator/= ( double c )

相关函数

  • bool operator== ( const QSize & s1, const QSize & s2 )
  • bool operator!= ( const QSize & s1, const QSize & s2 )
  • const QSize operator+ ( const QSize & s1, const QSize & s2 )
  • const QSize operator- ( const QSize & s1, const QSize & s2 )
  • const QSize operator* ( const QSize & s, int c )
  • const QSize operator* ( int c, const QSize & s )
  • const QSize operator* ( const QSize & s, double c )
  • const QSize operator* ( double c, const QSize & s )
  • const QSize operator/ ( const QSize & s, int c )
  • const QSize operator/ ( const QSize & s, double c )
  • QDataStream & operator<< ( QDataStream & s, const QSize & sz )
  • QDataStream & operator>> ( QDataStream & s, QSize & sz )

详细描述

QSize定义了一个二维对象的大小。

一个大小由一个宽和一个高确定。

坐标类型是QCOORD（和int一样在qwindowdefs.h中定义的）。QCOORD的最小值是QCOORD_MIN（-2147483648），最大值是QCOORD_MAX（2147483647）。

大小可以在构造函数中设置并且可以用setWidth()和setHeight()来修改，或者使用operator+=()、operator-=()、operator*=()和operator/=()等等。你可以使用transpose()来交换宽和高。你可以使用expandedTo()来得到宽和高为两个大小的宽和高的最大值的大小，并且可以使用boundedTo()来得到宽和高为两个大小的宽和高的最小值的大小。

也可以参考QPoint、QRect、图形类和图像处理类。

成员函数文档

QSize::QSize ()

构造一个具有无效的（负的）宽和高的大小。

QSize::QSize ( int w, int h )

构造一个宽为w，高为h的大小。

QSize QSize::boundedTo ( const QSize & otherSize ) const

返回一个宽高分别为这个大小和otherSize两个中宽高最小值的大小。

QSize QSize::expandedTo ( const QSize & otherSize ) const

返回一个宽高分别为这个大小和otherSize两个中宽高最大值的大小。

实例：customlayout/card.cpp和customlayout/flow.cpp。

int QSize::height () const

返回高。

也可以参考width()。

实例：movies/main.cpp、qfd/fontdisplayer.cpp和qfd/qfd.cpp。

bool QSize::isEmpty () const

如果宽<=0或者高<=0，返回真，否则返回假。

bool QSize::isNull () const

如果宽为0并且高也为0，返回真，否则返回假。

bool QSize::isValid () const

如果宽>=0并且高>=0，返回真，否则返回假。

QSize & QSize::operator*= ( int c )

把宽和高都乘以c并且返回这个大小的引用。

QSize & QSize::operator*= ( double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把宽和高都乘以c并且返回这个大小的引用。

注意这个结果被取整了。

QSize & QSize::operator+= ( const QSize & s )

把s加到这个大小上并且返回这个大小的引用。

实例：

    QSize s(  3, 7 );
    QSize r( -1, 4 );
    s += r;                     // s变成了(2,11)

QSize & QSize::operator-= ( const QSize & s )

从这个大小上减去s并且返回这个大小的引用。

实例：

    QSize s(  3, 7 );
    QSize r( -1, 4 );
    s -= r;                     // s变成了(4,3)

QSize & QSize::operator/= ( int c )

把宽和高都除以c并且返回这个大小的引用。

QSize & QSize::operator/= ( double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把宽和高都除以c并且返回这个大小的引用。

注意这个结果被取整了。

QCOORD & QSize::rheight ()

返回高的引用。

使用这个引用你就可以直接操作高了。

实例：

    QSize s( 100, 10 );
    s.rheight() += 5;           // s变成了(100,15)

也可以参考rwidth()。

QCOORD & QSize::rwidth ()

返回宽的引用。

使用这个引用你就可以直接操作宽了。

实例：

    QSize s( 100, 10 );
    s.rwidth() += 20;           // s变成了(120,10)

也可以参考rheight()。

void QSize::setHeight ( int h )

设置高为h。

也可以参考height()和setWidth()。

void QSize::setWidth ( int w )

设置宽为w。

也可以参考width() and setHeight()。

void QSize::transpose ()

交换宽和高的值。

int QSize::width () const

返回宽。

也可以参考height()。

实例：movies/main.cpp、qfd/fontdisplayer.cpp和qfd/qfd.cpp。

相关函数

bool operator!= ( const QSize & s1, const QSize & s2 )

如果s1和s2不同，返回真，否则返回假。

const QSize operator* ( const QSize & s, int c )

把s乘以c并且返回结果。

const QSize operator* ( int c, const QSize & s )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把s乘以c并且返回结果。

const QSize operator* ( const QSize & s, double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把s乘以c并且返回结果。

const QSize operator* ( double c, const QSize & s )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把s乘以c并且返回结果。

const QSize operator+ ( const QSize & s1, const QSize & s2 )

返回s1和s2的和，每个分量分别相加。

const QSize operator- ( const QSize & s1, const QSize & s2 )

从s1中减去s2，每个分量分别相减。

const QSize operator/ ( const QSize & s, int c )

把s除以c并且返回结果。

const QSize operator/ ( const QSize & s, double c )

这是一个重载成员函数，提供了方便。它的行为和上面的函数基本一致。

把s除以c并且返回结果。

注意这个结果被取整了。

QDataStream & operator<< ( QDataStream & s, const QSize & sz )

把大小sz写到流s中并且返回这个流的引用。

也可以参考QDataStream操作符的格式。

bool operator== ( const QSize & s1, const QSize & s2 )

如果s1和s2相等，返回真，否则返回假。

QDataStream & operator>> ( QDataStream & s, QSize & sz )

从流sz中读取大小到s中并且返回这个流的引用。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qsize.h包含文件

qsize.h

这里是qsize.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qsize.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSize class
**
** Created : 931028
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIZE_H
#define QSIZE_H

#ifndef QT_H
#include "qpoint.h" // ### change to windowdefs.h?
#endif // QT_H

class Q_EXPORT QSize
{
public:
    QSize();
    QSize( int w, int h );

    bool   isNull()	const;
    bool   isEmpty()	const;
    bool   isValid()	const;

    int	   width()	const;
    int	   height()	const;
    void   setWidth( int w );
    void   setHeight( int h );
    void   transpose();

    QSize expandedTo( const QSize & ) const;
    QSize boundedTo( const QSize & ) const;

    QCOORD &rwidth();
    QCOORD &rheight();

    QSize &operator+=( const QSize & );
    QSize &operator-=( const QSize & );
    QSize &operator*=( int c );
    QSize &operator*=( double c );
    QSize &operator/=( int c );
    QSize &operator/=( double c );

    friend inline bool	operator==( const QSize &, const QSize & );
    friend inline bool	operator!=( const QSize &, const QSize & );
    friend inline const QSize operator+( const QSize &, const QSize & );
    friend inline const QSize operator-( const QSize &, const QSize & );
    friend inline const QSize operator*( const QSize &, int );
    friend inline const QSize operator*( int, const QSize & );
    friend inline const QSize operator*( const QSize &, double );
    friend inline const QSize operator*( double, const QSize & );
    friend inline const QSize operator/( const QSize &, int );
    friend inline const QSize operator/( const QSize &, double );

private:
    static void warningDivByZero();

    QCOORD wd;
    QCOORD ht;
};

/*****************************************************************************
  QSize stream functions
 *****************************************************************************/

Q_EXPORT QDataStream &operator<<( QDataStream &, const QSize & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QSize & );

/*****************************************************************************
  QSize inline functions
 *****************************************************************************/

inline QSize::QSize()
{ wd = ht = -1; }

inline QSize::QSize( int w, int h )
{ wd=(QCOORD)w; ht=(QCOORD)h; }

inline bool QSize::isNull() const
{ return wd==0 && ht==0; }

inline bool QSize::isEmpty() const
{ return wd<1 || ht<1; }

inline bool QSize::isValid() const
{ return wd>=0 && ht>=0; }

inline int QSize::width() const
{ return wd; }

inline int QSize::height() const
{ return ht; }

inline void QSize::setWidth( int w )
{ wd=(QCOORD)w; }

inline void QSize::setHeight( int h )
{ ht=(QCOORD)h; }

inline QCOORD &QSize::rwidth()
{ return wd; }

inline QCOORD &QSize::rheight()
{ return ht; }

inline QSize &QSize::operator+=( const QSize &s )
{ wd+=s.wd; ht+=s.ht; return *this; }

inline QSize &QSize::operator-=( const QSize &s )
{ wd-=s.wd; ht-=s.ht; return *this; }

inline QSize &QSize::operator*=( int c )
{ wd*=(QCOORD)c; ht*=(QCOORD)c; return *this; }

inline QSize &QSize::operator*=( double c )
{ wd=(QCOORD)(wd*c); ht=(QCOORD)(ht*c); return *this; }

inline bool operator==( const QSize &s1, const QSize &s2 )
{ return s1.wd == s2.wd && s1.ht == s2.ht; }

inline bool operator!=( const QSize &s1, const QSize &s2 )
{ return s1.wd != s2.wd || s1.ht != s2.ht; }

inline const QSize operator+( const QSize & s1, const QSize & s2 )
{ return QSize(s1.wd+s2.wd, s1.ht+s2.ht); }

inline const QSize operator-( const QSize &s1, const QSize &s2 )
{ return QSize(s1.wd-s2.wd, s1.ht-s2.ht); }

inline const QSize operator*( const QSize &s, int c )
{ return QSize(s.wd*c, s.ht*c); }

inline const QSize operator*( int c, const QSize &s )
{  return QSize(s.wd*c, s.ht*c); }

inline const QSize operator*( const QSize &s, double c )
{ return QSize((QCOORD)(s.wd*c), (QCOORD)(s.ht*c)); }

inline const QSize operator*( double c, const QSize &s )
{ return QSize((QCOORD)(s.wd*c), (QCOORD)(s.ht*c)); }

inline QSize &QSize::operator/=( int c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0 )
    warningDivByZero();
#endif
    wd/=(QCOORD)c; ht/=(QCOORD)c;
    return *this;
}

inline QSize &QSize::operator/=( double c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0.0 )
    warningDivByZero();
#endif
    wd=(QCOORD)(wd/c); ht=(QCOORD)(ht/c);
    return *this;
}

inline const QSize operator/( const QSize &s, int c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0 )
    QSize::warningDivByZero();
#endif
    return QSize(s.wd/c, s.ht/c);
}

inline const QSize operator/( const QSize &s, double c )
{
#if defined(QT_CHECK_MATH)
    if ( c == 0.0 )
    QSize::warningDivByZero();
#endif
    return QSize((QCOORD)(s.wd/c), (QCOORD)(s.ht/c));
}

inline QSize QSize::expandedTo( const QSize & otherSize ) const
{
    return QSize( QMAX(wd,otherSize.wd), QMAX(ht,otherSize.ht) );
}

inline QSize QSize::boundedTo( const QSize & otherSize ) const
{
    return QSize( QMIN(wd,otherSize.wd), QMIN(ht,otherSize.ht) );
}

#endif // QSIZE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSize成员列表

完整的QSize成员列表

这里是QSize成员函数的完整列表，包括继承的成员。

  • QSize()
  • boundedTo()
  • expandedTo()
  • height()
  • isEmpty()
  • isNull()
  • isValid()
  • operator*=()
  • operator+=()
  • operator-=()
  • operator/=()
  • rheight()
  • rwidth()
  • setHeight()
  • setWidth()
  • transpose()
  • width()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSizeGrip Class

QSizeGrip Class Reference

The QSizeGrip class provides a corner-grip for resizing a top-level window. More...

#include <qsizegrip.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QSizeGrip ( QWidget * parent, const char * name = 0 )
  • ~QSizeGrip ()
  • virtual QSize sizeHint () const

Protected Members

  • virtual void paintEvent ( QPaintEvent * e )
  • virtual void mousePressEvent ( QMouseEvent * e )
  • virtual void mouseMoveEvent ( QMouseEvent * e )

Detailed Description

The QSizeGrip class provides a corner-grip for resizing a top-level window.

This widget works like the standard Windows resize handle. In the X11 version this resize handle generally works differently from the one provided by the system; we hope to reduce this difference in the future.

Put this widget anywhere in a widget tree and the user can use it to resize the top-level window. Generally, this should be in the lower right-hand corner. Note that QStatusBar already uses this widget, so if you have a status bar (e.g. you are using QMainWindow), then you don't need to use this widget explicitly.

See also QStatusBar, Widget Appearance and Style, Main Window and Related Classes and Basic Widgets.

Member Function Documentation

QSizeGrip::QSizeGrip ( QWidget * parent, const char * name = 0 )

Constructs a resize corner called name, as a child widget of parent.

QSizeGrip::~QSizeGrip ()

Destroys the size grip.

void QSizeGrip::mouseMoveEvent ( QMouseEvent * e ) [virtual protected]

Resizes the top-level widget containing this widget. The event is in e.

Reimplemented from QWidget.

void QSizeGrip::mousePressEvent ( QMouseEvent * e ) [virtual protected]

Primes the resize operation. The event is in e.

Reimplemented from QWidget.

void QSizeGrip::paintEvent ( QPaintEvent * e ) [virtual protected]

Paints the resize grip. Resize grips are usually rendered as small diagonal textured lines in the lower-right corner. The event is in e.

Reimplemented from QWidget.

QSize QSizeGrip::sizeHint () const [virtual]

Returns the size grip's size hint; this is a small size.

Reimplemented from QWidget.

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


qsizegrip.h Include File

qsizegrip.h

This is the verbatim text of the qsizegrip.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsizegrip.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSizeGrip class
**
** Created : 980316
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIZEGRIP_H
#define QSIZEGRIP_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_SIZEGRIP

class Q_EXPORT QSizeGrip: public QWidget
{
    Q_OBJECT
public:
    QSizeGrip( QWidget* parent, const char* name=0 );
    ~QSizeGrip();

    QSize sizeHint() const;

protected:
    void paintEvent( QPaintEvent * );
    void mousePressEvent( QMouseEvent * );
    void mouseMoveEvent( QMouseEvent * );

    bool eventFilter( QObject *, QEvent * );

private:
    QPoint p;
    QSize s;
    int d;
    QWidget *tlw;
};

#endif //QT_NO_SIZEGRIP
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSizeGrip Member List

Complete Member List for QSizeGrip

This is the complete list of member functions for QSizeGrip, including inherited members.

  • QSizeGrip()
  • ~QSizeGrip()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QSizePolicy Class

QSizePolicy Class Reference

The QSizePolicy class is a layout attribute describing horizontal and vertical resizing policy. More...

#include <qsizepolicy.h>

List of all member functions.

Public Members

  • enum SizeType { Fixed = 0, Minimum = MayGrow, Maximum = MayShrink, Preferred = MayGrow | MayShrink, MinimumExpanding = MayGrow | ExpMask, Expanding = MayGrow | MayShrink | ExpMask, Ignored = ExpMask }
  • enum ExpandData { NoDirection = 0, Horizontally = 1, Vertically = 2, BothDirections = Horizontally | Vertically, Horizontal = Horizontally, Vertical = Vertically }
  • QSizePolicy ()
  • QSizePolicy ( SizeType hor, SizeType ver, bool hfw = FALSE )
  • QSizePolicy ( SizeType hor, SizeType ver, uchar horStretch, uchar verStretch, bool hfw = FALSE )
  • SizeType horData () const
  • SizeType verData () const
  • bool mayShrinkHorizontally () const
  • bool mayShrinkVertically () const
  • bool mayGrowHorizontally () const
  • bool mayGrowVertically () const
  • ExpandData expanding () const
  • void setHorData ( SizeType d )
  • void setVerData ( SizeType d )
  • void setHeightForWidth ( bool b )
  • bool hasHeightForWidth () const
  • bool operator== ( const QSizePolicy & s ) const
  • bool operator!= ( const QSizePolicy & s ) const
  • uint horStretch () const
  • uint verStretch () const
  • void setHorStretch ( uchar sf )
  • void setVerStretch ( uchar sf )

Detailed Description

The QSizePolicy class is a layout attribute describing horizontal and vertical resizing policy.

The size policy of a widget is an expression of its willingness to be resized in various ways.

Widgets that reimplement QWidget::sizePolicy() return a QSizePolicy that describes the horizontal and vertical resizing policy they prefer when being laid out. Only one of the constructors is of interest in most applications.

QSizePolicy contains two independent SizeType objects; one describes the widgets's horizontal size policy, and the other describes its vertical size policy. It also contains a flag to indicate whether the height and width of its preferred size are related.

The per-dimension SizeType objects are set in the usual constructor and can be queried using a variety of functions, none of which are really interesting to application programmers.

The hasHeightForWidth() flag indicates whether the widget's sizeHint() is width-dependent (such as a word-wrapping label).

See also QSizePolicy::SizeType, Widget Appearance and Style and Layout Management.

Member Type Documentation

QSizePolicy::ExpandData

This enum type describes in which directions a widget can make use of extra space. There are four possible values:

  • QSizePolicy::NoDirection - the widget cannot make use of extra space in any direction.
  • QSizePolicy::Horizontally - the widget can usefully be wider than the sizeHint().
  • QSizePolicy::Vertically - the widget can usefully be taller than the sizeHint().
  • QSizePolicy::BothDirections - the widget can usefully be both wider and taller than the sizeHint().

QSizePolicy::SizeType

The per-dimension sizing types used when constructing a QSizePolicy are:

  • QSizePolicy::Fixed - the QWidget::sizeHint() is the only acceptable alternative, so the widget can never grow or shrink (e.g. the vertical direction of a push button).
  • QSizePolicy::Minimum - the sizeHint() is minimal, and sufficient. The widget can be expanded, but there is no advantage to it being larger (e.g. the horizontal direction of a push button).
  • QSizePolicy::Maximum - the sizeHint() is a maximum. The widget can be shrunk any amount without detriment if other widgets need the space (e.g. a separator line).
  • QSizePolicy::Preferred - the sizeHint() is best, but the widget can be shrunk and still be useful. The widget can be expanded, but there is no advantage to it being larger than sizeHint() (the default QWidget policy).
  • QSizePolicy::Expanding - the sizeHint() is a sensible size, but the widget can be shrunk and still be useful. The widget can make use of extra space, so it should get as much space as possible (e.g. the horizontal direction of a slider).
  • QSizePolicy::MinimumExpanding - the sizeHint() is minimal, and sufficient. The widget can make use of extra space, so it should get as much space as possible (e.g. the horizontal direction of a slider).
  • QSizePolicy::Ignored - the sizeHint() is ignored. The widget will get as much space as possible.

In any case, QLayout never shrinks a widget below the QWidget::minimumSizeHint().

Member Function Documentation

QSizePolicy::QSizePolicy ()

Default constructor; produces a minimally initialized QSizePolicy.

QSizePolicy::QSizePolicy ( SizeType hor, SizeType ver, bool hfw = FALSE )

This is the constructor normally used to return a value in the overridden QWidget::sizePolicy() function of a QWidget subclass.

It constructs a QSizePolicy with independent horizontal and vertical sizing types, hor and ver respectively. These sizing types affect how the widget is treated by the layout engine.

If hfw is TRUE, the preferred height of the widget is dependent on the width of the widget (for example, a QLabel with line wrapping).

See also horData(), verData() and hasHeightForWidth().

QSizePolicy::QSizePolicy ( SizeType hor, SizeType ver, uchar horStretch, uchar verStretch, bool hfw = FALSE )

Constructs a QSizePolicy with independent horizontal and vertical sizing types hor and ver, and stretch factors horStretch and verStretch.

If hfw is TRUE, the preferred height of the widget is dependent on the width of the widget.

See also horStretch() and verStretch().

ExpandData QSizePolicy::expanding () const

Returns a value indicating whether the widget can make use of extra space (i.e. if it "wants" to grow) horizontally and/or vertically.

See also mayShrinkHorizontally(), mayGrowHorizontally(), mayShrinkVertically() and mayGrowVertically().

bool QSizePolicy::hasHeightForWidth () const

Returns TRUE if the widget's preferred height depends on its width; otherwise returns FALSE.

See also setHeightForWidth().

SizeType QSizePolicy::horData () const

Returns the horizontal component of the size policy.

See also setHorData(), verData() and horStretch().

uint QSizePolicy::horStretch () const

Returns the horizontal stretch factor of the size policy.

See also setHorStretch() and verStretch().

bool QSizePolicy::mayGrowHorizontally () const

Returns TRUE if the widget can sensibly be wider than its sizeHint(); otherwise returns FALSE.

See also mayGrowVertically() and mayShrinkHorizontally().

bool QSizePolicy::mayGrowVertically () const

Returns TRUE if the widget can sensibly be taller than its sizeHint(); otherwise returns FALSE.

See also mayGrowHorizontally() and mayShrinkVertically().

bool QSizePolicy::mayShrinkHorizontally () const

Returns TRUE if the widget can sensibly be narrower than its sizeHint(); otherwise returns FALSE.

See also mayShrinkVertically() and mayGrowHorizontally().

bool QSizePolicy::mayShrinkVertically () const

Returns TRUE if the widget can sensibly be shorter than its sizeHint(); otherwise returns FALSE.

See also mayShrinkHorizontally() and mayGrowVertically().

bool QSizePolicy::operator!= ( const QSizePolicy & s ) const

Returns TRUE if this policy is different from s; otherwise returns FALSE.

See also operator==().

bool QSizePolicy::operator== ( const QSizePolicy & s ) const

Returns TRUE if this policy is equal to s; otherwise returns FALSE.

See also operator!=().

void QSizePolicy::setHeightForWidth ( bool b )

Sets the hasHeightForWidth() flag to b.

See also hasHeightForWidth().

void QSizePolicy::setHorData ( SizeType d )

Sets the horizontal component of the size policy to size type d.

See also horData() and setVerData().

void QSizePolicy::setHorStretch ( uchar sf )

Sets the horizontal stretch factor of the size policy to sf.

See also horStretch() and setVerStretch().

void QSizePolicy::setVerData ( SizeType d )

Sets the vertical component of the size policy to size type d.

See also verData() and setHorData().

void QSizePolicy::setVerStretch ( uchar sf )

Sets the vertical stretch factor of the size policy to sf.

See also verStretch() and setHorStretch().

SizeType QSizePolicy::verData () const

Returns the vertical component of the size policy.

See also setVerData(), horData() and verStretch().

uint QSizePolicy::verStretch () const

Returns the vertical stretch factor of the size policy.

See also setVerStretch() and horStretch().

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


qsizepolicy.h Include File

qsizepolicy.h

This is the verbatim text of the qsizepolicy.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsizepolicy.h   3.0.5   edited Jan 25 16:16 $
**
** Definition of the QSizePolicy class
**
** Created : 980929
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSIZEPOLICY_H
#define QSIZEPOLICY_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

class Q_EXPORT QSizePolicy
{
private:
    enum { HSize = 6, HMask = 0x3f, VMask = HMask << HSize,
       MayGrow = 1, ExpMask = 2, MayShrink = 4 };
public:
    enum SizeType { Fixed = 0,
            Minimum = MayGrow,
            Maximum = MayShrink,
            Preferred = MayGrow|MayShrink ,
            MinimumExpanding = MayGrow|ExpMask,
            Expanding = MayGrow|MayShrink|ExpMask,
            Ignored = ExpMask //magic value
    };

    enum ExpandData { NoDirection = 0,
              Horizontally = 1,
              Vertically = 2,
              BothDirections = Horizontally | Vertically
#ifndef QT_NO_COMPAT
              ,Horizontal = Horizontally,
              Vertical = Vertically
#endif
    };

    QSizePolicy() : data( 0 ) {}

    QSizePolicy( SizeType hor, SizeType ver, bool hfw = FALSE )
    : data( hor | (ver<<HSize) | (hfw ? (Q_UINT16)(1<<2*HSize) : 0) ) {}
    QSizePolicy( SizeType hor, SizeType ver, uchar hors, uchar vers, bool hfw = FALSE );

    SizeType horData() const { return (SizeType)( data & HMask ); }
    SizeType verData() const { return (SizeType)(( data & VMask ) >> HSize); }

    bool mayShrinkHorizontally() const { return horData() & MayShrink || horData() == Ignored; }
    bool mayShrinkVertically() const { return verData() & MayShrink || verData() == Ignored; }
    bool mayGrowHorizontally() const { return horData() & MayGrow || horData() == Ignored; }
    bool mayGrowVertically() const { return verData() & MayGrow || verData() == Ignored; }

    ExpandData expanding() const
    {
    return (ExpandData)( (int)(verData()&ExpMask ? Vertically : 0)+
                 (int)(horData()&ExpMask ? Horizontally : 0) );
    }

    void setHorData( SizeType d ) { data = (Q_UINT16)(data & ~HMask) | d; }
    void setVerData( SizeType d ) { data = (Q_UINT16)(data & ~(HMask<<HSize)) |
                       (d<<HSize); }

    void setHeightForWidth( bool b ) { data = b ? (Q_UINT16)( data | ( 1 << 2*HSize ) )
                          : (Q_UINT16)( data & ~( 1 << 2*HSize ) );  }
    bool hasHeightForWidth() const { return data & ( 1 << 2*HSize ); }

    bool operator==( const QSizePolicy& s ) const { return data == s.data; }
    bool operator!=( const QSizePolicy& s ) const { return data != s.data; }

    uint horStretch() const { return data >> 24; }
    uint verStretch() const { return (data >> 16) & 0xff; }
    void setHorStretch( uchar sf ) { data = (data&0x00ffffff) | (uint(sf)<<24); }
    void setVerStretch( uchar sf ) { data = (data&0xff00ffff) | (uint(sf)<<16); }

private:
    QSizePolicy( int i ): data( (Q_UINT32)i ) {}

    Q_UINT32 data;
};

inline QSizePolicy::QSizePolicy( SizeType hor, SizeType ver, uchar hors, uchar vers, bool hfw )
    : data( hor | (ver<<HSize) | (hfw ? (Q_UINT16)(1<<2*HSize) : 0) ) {
    setHorStretch( hors );
    setVerStretch( vers );
}

#endif // QSIZEPOLICY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSizePolicy Member List

Complete Member List for QSizePolicy

This is the complete list of member functions for QSizePolicy, including inherited members.

  • QSizePolicy()
  • expanding()
  • hasHeightForWidth()
  • horData()
  • horStretch()
  • mayGrowHorizontally()
  • mayGrowVertically()
  • mayShrinkHorizontally()
  • mayShrinkVertically()
  • operator!=()
  • operator==()
  • setHeightForWidth()
  • setHorData()
  • setHorStretch()
  • setVerData()
  • setVerStretch()
  • verData()
  • verStretch()


QSjisCodec Class

QSjisCodec Class Reference

The QSjisCodec class provides conversion to and from Shift-JIS. More...

#include <qsjiscodec.h>

Inherits QTextCodec.

List of all member functions.

Public Members

  • virtual const char * mimeName () const
  • QSjisCodec ()
  • ~QSjisCodec ()

Detailed Description

The QSjisCodec class provides conversion to and from Shift-JIS.

More precisely, the QSjisCodec class subclasses QTextCodec to provide support for Shift-JIS, an encoding of JIS X 0201 Latin, JIS X 0201 Kana or JIS X 0208.

The environment variable UNICODEMAP_JP can be used to fine-tune QJisCodec, QSjisCodec and QEucJpCodec. The QJisCodec documentation describes how to use this variable.

Most of the code here was written by Serika Kurusugawa, a.k.a. Junji Takagi, and is included in Qt with the author's permission and the grateful thanks of the Trolltech team. Here is the copyright statement for that code:

Copyright (c) 1999 Serika Kurusugawa. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS". ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

Member Function Documentation

QSjisCodec::QSjisCodec ()

Creates a Shift-JIS codec. Note that this is done automatically by the QApplication, you do not need construct your own.

QSjisCodec::~QSjisCodec ()

Destroys the Shift-JIS codec.

const char * QSjisCodec::mimeName () const [virtual]

Returns the codec's mime name.

Reimplemented from QTextCodec.

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


qsjiscodec.h Include File

qsjiscodec.h

This is the verbatim text of the qsjiscodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsjiscodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSjisCodec class
**
** Created : 990225
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

// Most of the code here was originally written by Serika Kurusugawa
// a.k.a. Junji Takagi, and is include in Qt with the author's permission,
// and the grateful thanks of the Trolltech team.

/*
 * Copyright (c) 1999 Serika Kurusugawa, All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef QSJISCODEC_H
#define QSJISCODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#include "qjpunicode.h"
#endif // QT_H

#ifndef QT_NO_BIG_CODECS

#if defined(QT_PLUGIN)
#define Q_EXPORT_CODECS_JP
#else
#define Q_EXPORT_CODECS_JP Q_EXPORT
#endif

class Q_EXPORT_CODECS_JP QSjisCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;
    const char* mimeName() const;

    QTextDecoder* makeDecoder() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;

    QSjisCodec();
    ~QSjisCodec();

protected:
    const QJpUnicodeConv *conv;
};

#endif
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSjisCodec Member List

Complete Member List for QSjisCodec

This is the complete list of member functions for QSjisCodec, including inherited members.

  • QSjisCodec()
  • ~QSjisCodec()
  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QSlider Class

QSlider Class Reference

The QSlider widget provides a vertical or horizontal slider. More...

#include <qslider.h>

Inherits QWidget and QRangeControl.

List of all member functions.

Public Members

  • enum TickSetting { NoMarks = 0, Above = 1, Left = Above, Below = 2, Right = Below, Both = 3 }
  • QSlider ( QWidget * parent, const char * name = 0 )
  • QSlider ( Orientation orientation, QWidget * parent, const char * name = 0 )
  • QSlider ( int minValue, int maxValue, int pageStep, int value, Orientation orientation, QWidget * parent, const char * name = 0 )
  • virtual void setOrientation ( Orientation )
  • Orientation orientation () const
  • virtual void setTracking ( bool enable )
  • bool tracking () const
  • virtual void setPalette ( const QPalette & p )
  • int sliderStart () const
  • QRect sliderRect () const
  • virtual void setTickmarks ( TickSetting )
  • TickSetting tickmarks () const
  • virtual void setTickInterval ( int )
  • int tickInterval () const
  • int minValue () const
  • int maxValue () const
  • void setMinValue ( int )
  • void setMaxValue ( int )
  • int lineStep () const
  • int pageStep () const
  • void setLineStep ( int )
  • void setPageStep ( int )
  • int value () const

Public Slots

  • virtual void setValue ( int )
  • void addStep ()
  • void subtractStep ()

Signals

  • void valueChanged ( int value )
  • void sliderPressed ()
  • void sliderMoved ( int value )
  • void sliderReleased ()

Important Inherited Members

  • void setRange ( int minValue, int maxValue )

Properties

  • int lineStep - the current line step
  • int maxValue - the current maximum value of the slider
  • int minValue - the current minimum value of the slider
  • Orientation orientation - the orientation of the slider
  • int pageStep - the current page step
  • int tickInterval - the interval between tickmarks
  • TickSetting tickmarks - the tickmark settings for this slider
  • bool tracking - whether slider tracking is enabled
  • int value - the current slider value

Protected Members

  • virtual void valueChange ()
  • virtual void rangeChange ()

Detailed Description

The QSlider widget provides a vertical or horizontal slider.

The slider is the classic widget for controlling a bounded value. It lets the user move a slider along a horizontal or vertical groove and translates the slider's position into an integer value within the legal range.

QSlider inherits QRangeControl, which provides the "integer" side of the slider. setRange() and value() are likely to be used by practically all slider users; see the QRangeControl documentation for information about the many other functions that class provides.

The main functions offered by the slider itself are tickmark and orientation control; you can use setTickmarks() to indicate where you want the tickmarks to be, setTickInterval() to indicate how many of them you want and setOrientation() to indicate whether the slider is to be horizontal or vertical.

A slider has a default focusPolicy() of WeakWheelFocus, i.e. it accepts focus on Tab and uses the mouse wheel and a suitable keyboard interface.

See also QScrollBar, QSpinBox, GUI Design Handbook: Slider and Basic Widgets.

Member Type Documentation

QSlider::TickSetting

This enum specifies where the tickmarks are to be drawn relative to the slider's groove and the handle the user moves. The possible values are:

  • QSlider::NoMarks - do not draw any tickmarks.
  • QSlider::Both - draw tickmarks on both sides of the groove.
  • QSlider::Above - draw tickmarks above the (horizontal) slider
  • QSlider::Below - draw tickmarks below the (horizontal) slider
  • QSlider::Left - draw tickmarks to the left of the (vertical) slider
  • QSlider::Right - draw tickmarks to the right of the (vertical) slider

Member Function Documentation

QSlider::QSlider ( QWidget * parent, const char * name = 0 )

Constructs a vertical slider.

The parent and name arguments are sent to the QWidget constructor.

QSlider::QSlider ( Orientation orientation, QWidget * parent, const char * name = 0 )

Constructs a slider.

The orientation must be Qt::Vertical or Qt::Horizontal.

The parent and name arguments are sent to the QWidget constructor.

QSlider::QSlider ( int minValue, int maxValue, int pageStep, int value, Orientation orientation, QWidget * parent, const char * name = 0 )

Constructs a slider whose value can never be smaller than minValue or greater than maxValue, whose page step size is pageStep and whose value is initially value (which is guaranteed to be in range using bound()).

If orientation is Qt::Vertical the slider is vertical and if it is Qt::Horizontal the slider is horizontal.

The parent and name arguments are sent to the QWidget constructor.

void QSlider::addStep () [slot]

Moves the slider one pageStep() up or right.

int QSlider::lineStep () const

Returns the current line step. See the "lineStep" property for details.

int QSlider::maxValue () const

Returns the current maximum value of the slider. See the "maxValue" property for details.

int QSlider::minValue () const

Returns the current minimum value of the slider. See the "minValue" property for details.

Orientation QSlider::orientation () const

Returns the orientation of the slider. See the "orientation" property for details.

int QSlider::pageStep () const

Returns the current page step. See the "pageStep" property for details.

void QSlider::rangeChange () [virtual protected]

Implements the virtual QRangeControl function.

Reimplemented from QRangeControl.

void QSlider::setLineStep ( int )

Sets the current line step. See the "lineStep" property for details.

void QSlider::setMaxValue ( int )

Sets the current maximum value of the slider. See the "maxValue" property for details.

void QSlider::setMinValue ( int )

Sets the current minimum value of the slider. See the "minValue" property for details.

void QSlider::setOrientation ( Orientation ) [virtual]

Sets the orientation of the slider. See the "orientation" property for details.

void QSlider::setPageStep ( int )

Sets the current page step. See the "pageStep" property for details.

void QSlider::setPalette ( const QPalette & p ) [virtual]

Reimplements the virtual function QWidget::setPalette().

Sets the background color to the mid color for Motif style sliders using palette p.

Reimplemented from QWidget.

void QRangeControl::setRange ( int minValue, int maxValue )

Sets the range control's min value to minValue and its max value to maxValue.

Calls the virtual rangeChange() function if one or both of the new min and max values are different from the previous setting. Calls the virtual valueChange() function if the current value is adjusted because it was outside the new range.

If maxValue is smaller than minValue, minValue becomes the only legal value.

See also minValue and maxValue.

Examples: listbox/listbox.cpp, t12/lcdrange.cpp, t5/main.cpp, t6/main.cpp, t8/lcdrange.cpp and xform/xform.cpp.

void QSlider::setTickInterval ( int ) [virtual]

Sets the interval between tickmarks. See the "tickInterval" property for details.

void QSlider::setTickmarks ( TickSetting ) [virtual]

Sets the tickmark settings for this slider. See the "tickmarks" property for details.

void QSlider::setTracking ( bool enable ) [virtual]

Sets whether slider tracking is enabled to enable. See the "tracking" property for details.

void QSlider::setValue ( int ) [virtual slot]

Sets the current slider value. See the "value" property for details.

void QSlider::sliderMoved ( int value ) [signal]

This signal is emitted when the slider is dragged, with the new slider value as an argument.

void QSlider::sliderPressed () [signal]

This signal is emitted when the user presses the slider with the mouse.

QRect QSlider::sliderRect () const

Returns the slider handle rectangle. (This is the visual marker that the user can move.)

void QSlider::sliderReleased () [signal]

This signal is emitted when the user releases the slider with the mouse.

int QSlider::sliderStart () const

Returns the start position of the slider.

void QSlider::subtractStep () [slot]

Moves the slider one pageStep() down or left.

int QSlider::tickInterval () const

Returns the interval between tickmarks. See the "tickInterval" property for details.

TickSetting QSlider::tickmarks () const

Returns the tickmark settings for this slider. See the "tickmarks" property for details.

bool QSlider::tracking () const

Returns TRUE if slider tracking is enabled; otherwise returns FALSE. See the "tracking" property for details.

int QSlider::value () const

Returns the current slider value. See the "value" property for details.

void QSlider::valueChange () [virtual protected]

Implements the virtual QRangeControl function.

Reimplemented from QRangeControl.

void QSlider::valueChanged ( int value ) [signal]

This signal is emitted when the slider value is changed, with the new slider value as an argument.

Examples: rangecontrols/rangecontrols.cpp, t12/lcdrange.cpp, t5/main.cpp, t6/main.cpp, t7/lcdrange.cpp and xform/xform.cpp.

Property Documentation

int lineStep

This property holds the current line step.

When setting lineStep, the virtual stepChange() function will be called if the new line step is different from the previous setting.

See also setSteps(), QRangeControl::pageStep() and setRange().

Set this property's value with setLineStep() and get this property's value with lineStep().

int maxValue

This property holds the current maximum value of the slider.

When setting this property, the QSlider::minValue is adjusted, if necessary, to ensure that the range remains valid.

See also setRange().

Set this property's value with setMaxValue() and get this property's value with maxValue().

int minValue

This property holds the current minimum value of the slider.

When setting this property, the QSlider::maxValue is adjusted, if necessary, to ensure that the range remains valid.

See also setRange().

Set this property's value with setMinValue() and get this property's value with minValue().

Orientation orientation

This property holds the orientation of the slider.

The orientation must be Qt::Vertical (the default) or Qt::Horizontal.

Set this property's value with setOrientation() and get this property's value with orientation().

int pageStep

This property holds the current page step.

When setting pageStep, the virtual stepChange() function will be called if the new page step is different from the previous setting.

See also QRangeControl::setSteps(), lineStep and setRange().

Set this property's value with setPageStep() and get this property's value with pageStep().

int tickInterval

This property holds the interval between tickmarks.

This is a value interval, not a pixel interval. If it is 0, the slider will choose between lineStep() and pageStep(). The initial value of tickInterval is 0.

See also QRangeControl::lineStep() and QRangeControl::pageStep().

Set this property's value with setTickInterval() and get this property's value with tickInterval().

TickSetting tickmarks

This property holds the tickmark settings for this slider.

The valid values are in QSlider::TickSetting. The default is NoMarks.

See also tickInterval.

Set this property's value with setTickmarks() and get this property's value with tickmarks().

bool tracking

This property holds whether slider tracking is enabled.

If tracking is enabled (the default), the slider emits the valueChanged() signal whenever the slider is being dragged. If tracking is disabled, the slider emits the valueChanged() signal when the user releases the mouse button (unless the value happens to be the same as before).

Set this property's value with setTracking() and get this property's value with tracking().

int value

This property holds the current slider value.

Set this property's value with setValue() and get this property's value with value().

See also QRangeControl::value() and prevValue().

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


qslider.h Include File

qslider.h

This is the verbatim text of the qslider.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QSlider class
**
** Created : 961019
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSLIDER_H
#define QSLIDER_H

#ifndef QT_H
#include "qwidget.h"
#include "qrangecontrol.h"
#endif // QT_H

#ifndef QT_NO_SLIDER

struct QSliderPrivate;

class QTimer;

class Q_EXPORT QSlider : public QWidget, public QRangeControl
{
    Q_OBJECT
    Q_ENUMS( TickSetting )
    Q_PROPERTY( int minValue READ minValue WRITE setMinValue )
    Q_PROPERTY( int maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( int lineStep READ lineStep WRITE setLineStep )
    Q_PROPERTY( int pageStep READ pageStep WRITE setPageStep )
    Q_PROPERTY( int value READ value WRITE setValue )
    Q_PROPERTY( bool tracking READ tracking WRITE setTracking )
    Q_PROPERTY( Orientation orientation READ orientation WRITE setOrientation )
    Q_PROPERTY( TickSetting tickmarks READ tickmarks WRITE setTickmarks )
    Q_PROPERTY( int tickInterval READ tickInterval WRITE setTickInterval )

public:
    enum TickSetting { NoMarks = 0, Above = 1, Left = Above,
               Below = 2, Right = Below, Both = 3 };

    QSlider( QWidget *parent, const char* name=0 );
    QSlider( Orientation, QWidget *parent, const char* name=0 );
    QSlider( int minValue, int maxValue, int pageStep, int value, Orientation,
         QWidget *parent, const char* name=0 );

    virtual void	setOrientation( Orientation );
    Orientation orientation() const;
    virtual void	setTracking( bool enable );
    bool	tracking() const;
    virtual void 	setPalette( const QPalette & );

    int		sliderStart() const;
    QRect	sliderRect() const;
    QSize	sizeHint() const;
    QSizePolicy sizePolicy() const;
    QSize	minimumSizeHint() const;

    virtual void setTickmarks( TickSetting );
    TickSetting tickmarks() const { return ticks; }

    virtual void setTickInterval( int );
    int 	tickInterval() const { return tickInt; }

    int	 minValue() const;
    int	 maxValue() const;
    void setMinValue( int );
    void setMaxValue( int );
    int	 lineStep() const;
    int	 pageStep() const;
    void setLineStep( int );
    void setPageStep( int );
    int  value() const;

public slots:
    virtual void	setValue( int );
    void	addStep();
    void	subtractStep();

signals:
    void	valueChanged( int value );
    void	sliderPressed();
    void	sliderMoved( int value );
    void	sliderReleased();

protected:
    void	resizeEvent( QResizeEvent * );
    void	paintEvent( QPaintEvent * );

    void	keyPressEvent( QKeyEvent * );
    void	mousePressEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
#ifndef QT_NO_WHEELEVENT
    void	wheelEvent( QWheelEvent * );
#endif
    void	focusInEvent( QFocusEvent *e );
    void	focusOutEvent( QFocusEvent *e );

    void	styleChange( QStyle& );

    void	valueChange();
    void	rangeChange();

private slots:
    void	repeatTimeout();

private:
    enum State { Idle, Dragging, TimingUp, TimingDown };

    void	init();
    int		positionFromValue( int ) const;
    int		valueFromPosition( int ) const;
    void	moveSlider( int );
    void	reallyMoveSlider( int );
    void	resetState();
    int		available() const;
    int		goodPart( const QPoint& ) const;
    void	initTicks();

    QSliderPrivate *extra;
    QTimer	*timer;
    QCOORD	sliderPos;
    int		sliderVal;
    QCOORD	clickOffset;
    State	state;
    bool	track;
    QCOORD	tickOffset;
    TickSetting	ticks;
    int		tickInt;
    Orientation orient;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSlider( const QSlider & );
    QSlider &operator=( const QSlider & );
#endif
};

inline bool QSlider::tracking() const
{
    return track;
}

inline QSlider::Orientation QSlider::orientation() const
{
    return orient;
}

inline int QSlider::sliderStart() const
{
    return sliderPos;
}

#endif // QT_NO_SLIDER

#endif // QSLIDER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSlider Member List

Complete Member List for QSlider

This is the complete list of member functions for QSlider, including inherited members.

  • QSlider()
  • acceptDrops()
  • addLine()
  • addPage()
  • addStep()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bound()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • directSetValue()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineStep()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maxValue()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minValue()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageStep()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • positionFromValue()
  • prevValue()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • rangeChange()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineStep()
  • setMask()
  • setMaxValue()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinValue()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPageStep()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRange()
  • setSizeIncrement()
  • setSizePolicy()
  • setSteps()
  • setStyle()
  • setTabOrder()
  • setTickInterval()
  • setTickmarks()
  • setTracking()
  • setUpdatesEnabled()
  • setValue()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sliderMoved()
  • sliderPressed()
  • sliderRect()
  • sliderReleased()
  • sliderStart()
  • stackUnder()
  • startTimer()
  • stepChange()
  • style()
  • styleChange()
  • subtractLine()
  • subtractPage()
  • subtractStep()
  • tabletEvent()
  • testWFlags()
  • tickInterval()
  • tickmarks()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • tracking()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • value()
  • valueChange()
  • valueChanged()
  • valueFromPosition()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QSocket类

QSocket类参考
[网络模块]

QSocket类提供了一个有缓冲的TCP连接。 详情请见……

#include <qsocket.h>

继承了QObject和QIODevice。

所有成员函数的列表。

公有成员

  • enum Error { ErrConnectionRefused, ErrHostNotFound, ErrSocketRead }
  • QSocket ( QObject * parent = 0, const char * name = 0 )
  • virtual ~QSocket ()
  • enum State { Idle, HostLookup, Connecting, Connected, Closing, Connection = Connected }
  • State state () const
  • int socket () const
  • virtual void setSocket ( int socket )
  • QSocketDevice * socketDevice ()
  • virtual void setSocketDevice ( QSocketDevice * device )
  • virtual void connectToHost ( const QString & host, Q_UINT16 port )
  • QString peerName () const
  • virtual bool open ( int m )
  • virtual void close ()
  • virtual void flush ()
  • virtual Offset size () const
  • virtual Offset at () const
  • virtual bool at ( Offset index )
  • virtual bool atEnd () const
  • Q_ULONG bytesAvailable () const
  • Q_ULONG waitForMore ( int msecs ) const
  • Q_ULONG bytesToWrite () const
  • virtual Q_LONG readBlock ( char * data, Q_ULONG maxlen )
  • virtual Q_LONG writeBlock ( const char * data, Q_ULONG len )
  • virtual int getch ()
  • virtual int putch ( int ch )
  • virtual int ungetch ( int ch )
  • bool canReadLine () const
  • virtual QString readLine ()
  • Q_UINT16 port () const
  • Q_UINT16 peerPort () const
  • QHostAddress address () const
  • QHostAddress peerAddress () const

信号

  • void hostFound ()
  • void connected ()
  • void connectionClosed ()
  • void delayedCloseFinished ()
  • void readyRead ()
  • void bytesWritten ( int nbytes )
  • void error ( int )

保护槽

  • virtual void sn_read ( bool force = FALSE )
  • virtual void sn_write ()

详细描述

QSocket类提供了一个有缓冲的TCP连接。

它提供一个完全非阻塞的QIODevice，使用套接字特征代码来修改和扩展了QIODevice的应用编程接口。

你和可能常常调用的connectToHost()、bytesAvailable()、canReadLine()这些函数并且它们继承了QIODevice。

connectToHost()是一个最常用的函数。就像它的名字那样，它打开一个被命名的主机的连接。

绝大多数网络协议是基于包的或者基于行的。canReadLine()可以识别一个连接中是否包含一个完全不可读的的行，并且bytesAvailable()返回可以被读取的字节数量。

信号error()、connected()、readyRead()和connectionClosed()通知你连接的进展。还有一些不太常用的信号。当connectToHost()已经完成它的DNS查找并且正在开始它的TCP连接时，hostFound()被发射。当close()成功时，delayedCloseFinished()被发射。当QSocket把它的“写”队列中的数据移到TCP运行中。

还有几个套接字的访问函数：state()返回这个对象是否空闲，是否正在做DNS查找，是否正在连接，还是一个正在操作的连接，等等。address()和port()返回连接所使用的IP地址和端口。peerAddress()和peerPort()函数返回自身所用到的IP地址和端口并且peerName()返回自身所用的名称（通常是被传送给connectToHost()的名字）。socket() 返回这个套接字所用到的QSocketDevice的指针。

QSocket继承了QIODevice并且重新实现了一些函数。通常你可以把它作为QIODevice来写，并且绝大多数情况也可以作为QIODevice来读。但匹配的不够完美，因为QIODevice应用编程接口是为同一个机器可以控制的设备而设计的，而异步的端对端网络连接和这个不太一样。例如，没有什么可以和QIODevice::size()确切地匹配。open()、close()、flush()、size()、at()、atEnd()、readBlock()、writeBlock()、getch()、putch()、ungetch()和readLine()的文档详细地描述了不同点。

也可以参考QSocketDevice、QHostAddress、QSocketNotifier和输入/输出和网络。

成员类型文档

QSocket::Error

这个枚举变量指定了可能的错误：

  • QSocket::ErrConnectionRefused - 如果连接被拒绝
  • QSocket::ErrHostNotFound - 如果主机没有被找到
  • QSocket::ErrSocketRead - 如果读取套接字失败

QSocket::State

这个枚举变量定义了连接状态：

  • QSocket::Idle - 如果没有连接
  • QSocket::HostLookup - 在DNS查找期间
  • QSocket::Connecting - 在TCP连接建立期间
  • QSocket::Connected - 当存在一个可操作的连接时
  • QSocket::Closing - 如果这个套接字正在关闭，但是还没有被关闭。

成员函数文档

QSocket::QSocket ( QObject * parent = 0, const char * name = 0 )

创建一个QSocket::Idle状态的QSocket对象。

parent和name参数被传递给QObject的构造函数。

QSocket::~QSocket () [虚]

销毁这个套接字。如果需要关闭连接。

也可以参考close()。

QHostAddress QSocket::address () const

返回这个套接字的主机地址。（这通常就是主机的主IP地址，但是对于到localhost的连接可能是127.0.0.1。）

Offset QSocket::at () const [虚]

返回当前的读索引。因为QSocket是一个顺序设备，当前读索引总是0。

Reimplemented from QIODevice.

bool QSocket::at ( Offset index ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

向前移动读索引到index并且如果操作成功返回真。向前移动读索引意味着忽略进入的数据。

从QIODevice中重新实现的。

bool QSocket::atEnd () const [虚]

如果没有更多的数据可以读取，返回真，否则返回假。

从QIODevice中重新实现的。

Q_ULONG QSocket::bytesAvailable () const

返回可以读取的进入数据的字节数，也就是输入缓存的大小。等于size()。

也可以参考bytesToWrite()。

实例：network/networkprotocol/nntp.cpp。

Q_ULONG QSocket::bytesToWrite () const

返回正在等待被写的数据的字节数，也就是输出缓存的大小。

也可以参考bytesAvailable()。

void QSocket::bytesWritten ( int nbytes ) [信号]

当数据被实际写到网络时，这个信号被发射。nbytes参数指定了多少字节被写了。

bytesToWrite()函数常常会在相同的上下文中被使用，并且它说明了还有多少数量的缓存字节数要写。

也可以参考writeBlock()和bytesToWrite()。

bool QSocket::canReadLine () const

如果这一次可以从这个套接字中读取一个完整行的文本，返回真，否则返回假。

注意如果本地出乎意料地关闭连接，这个函数返回假。这也就是说这样的循环不会工作：

    while( !socket->canReadLine() ) // 错了。
        ...

也可以参考readLine()。

实例：network/clientserver/client/client.cpp、network/httpd/httpd.cpp、network/mail/smtp.cpp和network/networkprotocol/nntp.cpp。

void QSocket::close () [虚]

关闭这个套接字。

读缓存被清空。

如果输出缓存是空的，状态被设置为QSocket::Idle并且连接被立即终止。如果输出缓存中还有数据要写，QSocket进入QSocket::Closing状态并且等待这些数据被写完。当所有的输出数据被写完，状态被设置为QSocket::Idle并且连接被终止。在这时，delayedCloseFinished() 喜好被发射。

也可以参考state()和bytesToWrite()。

实例：network/clientserver/client/client.cpp、network/httpd/httpd.cpp和network/networkprotocol/nntp.cpp。

从QIODevice中重新实现的。

void QSocket::connectToHost ( const QString & host, Q_UINT16 port ) [虚]

试图连接主机host的指定端口port并且立即返回。

任何连接或者正在进行的连接被立即关闭，并且QSocket进入HostLookup 状态。当查找成功，它发射hostFound()，开始一个TCP连接并且进入Connecting状态。最后，当连接成功时，它发射connected()并且进入Connected状态。如果在任何一个地方出现错误，它发射error()。

host可以是一个字符串形式的IP地址，也可以是一个DNS名称。如果需要QSocket将会进行一个普通的DNS查找。注意port是本地字节顺序，不像其它库那样。

也可以参考state()。

实例：network/clientserver/client/client.cpp、network/mail/smtp.cpp和network/networkprotocol/nntp.cpp。

void QSocket::connected () [信号]

在connectToHost()已经被调用并且连接已经被成功建立之后，这个信号被发射。

也可以参考connectToHost()和connectionClosed()。

实例：network/clientserver/client/client.cpp、network/mail/smtp.cpp和network/networkprotocol/nntp.cpp。

void QSocket::connectionClosed () [信号]

当另一端已经关闭这个连接时，这个信号被发射。在连接被关闭之后，读缓存中也许还包含被可读的缓存的输入数据。

也可以参考connectToHost()和close()。

实例：network/clientserver/client/client.cpp和network/networkprotocol/nntp.cpp。

void QSocket::delayedCloseFinished () [信号]

当一个延时的关闭被完成时，这个信号被发射。

如果你调用close()并且输出缓存中还有数据要写，QSocket进入QSocket::Closing状态并且立即返回。然后它将会继续要套接字写知道所有的数据被写完。然后，delayedCloseFinished()信号被发射。

也可以参考close()。

实例：network/clientserver/client/client.cpp和network/httpd/httpd.cpp。

void QSocket::error ( int ) [信号]

在错误发生之后，信号被发射。参数就是Error的值。

实例：network/clientserver/client/client.cpp和network/networkprotocol/nntp.cpp。

void QSocket::flush () [虚]

纯虚函数QIODevice::flush()的实现。

从QIODevice中重新实现的。

int QSocket::getch () [虚]

从内部的读缓存中读取单一的字节/字符。返回读取的字节/字符，或者如果没有什么可以读取的，返回-1。

也可以参考bytesAvailable()和putch()。

从QIODevice中重新实现的。

void QSocket::hostFound () [信号]

在connectToHost()已经被调用并且主机查找已经成功之后，这个信号被发射。

也可以参考connected()。

实例：network/networkprotocol/nntp.cpp。

bool QSocket::open ( int m ) [虚]

使用指定的QIODevice文件模式m打开套接字。当被需要的时候会被自动调用并且你不应该自己调用它。

也可以参考close()。

从QIODevice中重新实现的。

QHostAddress QSocket::peerAddress () const

返回为connectToHost()函数指定名称的主机地址。

QString QSocket::peerName () const

返回为connectToHost()函数指定主机名称。如果没有被设置，返回一个空字符串。

实例：network/mail/smtp.cpp。

Q_UINT16 QSocket::peerPort () const

返回本地的主机端口号，通常是为connectToHost()函数指定的。如果没有被设置，返回0。

注意Qt总是使用本地字节顺序，也就是在Qt中67就是67，不需要调用htons()。

Q_UINT16 QSocket::port () const

返回这个套接字的主机端口号，使用本地字节顺序。

int QSocket::putch ( int ch ) [虚]

写字符ch到输出缓存。

返回ch，或者如果发生错误，返回-1。

也可以参考getch()。

从QIODevice中重新实现的。

Q_LONG QSocket::readBlock ( char * data, Q_ULONG maxlen ) [虚]

从套接字中读取最多maxlen字节到data中并且返回读取的字节数。如果发生错误，返回-1。

实例：network/networkprotocol/nntp.cpp。

从QIODevice中重新实现的。

QString QSocket::readLine () [虚]

返回包含终止新行符（\n）的一行文本。如果canReadLine()返回假，返回“”。

也可以参考canReadLine()。

实例：network/clientserver/client/client.cpp、network/httpd/httpd.cpp、network/mail/smtp.cpp和network/networkprotocol/nntp.cpp。

void QSocket::readyRead () [信号]

当有进入的数据可以被读取时，这个信号被发射。

每一次有新进入的数据时，这个信号都被发射一次。记住新进入的数据只被报告一次，也就是，如果你没有读取全部数据，这个信号不会被再次发射，除非新的数据到达这个套接字。

也可以参考readBlock()、readLine()和bytesAvailable()。

实例：network/clientserver/client/client.cpp、network/httpd/httpd.cpp、network/mail/smtp.cpp和network/networkpotocol/nntp.cpp。

void QSocket::setSocket ( int socket ) [虚]

设置套接字使用socket并且state()为Connected。这个套接字应该已经被连接。

这允许我们使用QSocket类作为一个其它套接字类型（也就是在Unix下的Unix领域套接字）的包装。

实例：network/httpd/httpd.cpp。

void QSocket::setSocketDevice ( QSocketDevice * device ) [虚]

设置内部套接字设备为device。传递一个0的device将导致这个内部套接字设备被使用。在使用新的device之前，任何已经存在的连接将被取消连接。

新的设备在被关联到一个QSocket之前应该没有被连接，在设置套接字调用connectToHost()之后进行连接。

如果你继承QSocketDevice并且想使用QSocket应用编程接口，例如，实现Unix领域套接字，这个函数很有用。

Offset QSocket::size () const [虚]

立即返回可以读取的进入数据的字节数（就像bytesAvailable()一样）。

在QIODevice中重新实现的。

void QSocket::sn_read ( bool force = FALSE ) [虚 保护 槽]

处理套接字读通知的内部槽。

这个函数通常只能被进入一次（也就是，不是递归调用）。如果参数force为真，这个函数被执行，但是没有readyRead()信号被发射。这种方式对于waitForMore()函数很有用，所以在一个连接到readyRead()信号的槽中调用waitForMore()是可能的。

void QSocket::sn_write () [虚 保护 槽]

处理套接字写通知的内部操。

int QSocket::socket () const

返回套接字数，或者如果这个时候没有套接字，返回-1。

QSocketDevice * QSocket::socketDevice ()

返回内部套接字设备的指针。

通常不需要直接操作这个套接字设备，因为这个类对于绝大多数应用程序不需要设置。

State QSocket::state () const

返回这个套接字连接的当前状态。

也可以参考QSocket::State。

实例：network/clientserver/client/client.cpp和network/networkprotocol/nntp.cpp。

int QSocket::ungetch ( int ch ) [虚]

虚函数QIODevice::ungetch()的实现预先考虑写缓存中的字符ch，这样下一次读取把这个字符作为输出的第一个字符。

从QIODevice中重新实现的。

Q_ULONG QSocket::waitForMore ( int msecs ) const

为了得到更多的可用数据，等待msecs毫秒。

如果msecs为-1，这个调用将会不确定地阻塞。

这个一个阻塞调用并且应该在事件驱动的应用程序中避免使用。

返回可以使用的字节数。

也可以参考bytesAvailable()。

Q_LONG QSocket::writeBlock ( const char * data, Q_ULONG len ) [虚]

从data中向套接字中写入len字节并且返回所写的字节数。如果发生错误，返回-1。

实例：network/networkprotocol/nntp.cpp。

从QIODevice中重新实现的。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qsocket.h包含文件

qsocket.h

这里是qsocket.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QSocket class.
**
** Created : 970521
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSOCKET_H
#define QSOCKET_H

#ifndef QT_H
#include "qobject.h"
#include "qiodevice.h"
#include "qhostaddress.h" // int->QHostAddress conversion
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_NETWORK
#else
#define QM_EXPORT_NETWORK Q_EXPORT
#endif

#ifndef QT_NO_NETWORK
class QSocketPrivate;
class QSocketDevice;

class QM_EXPORT_NETWORK QSocket : public QObject, public QIODevice
{
    Q_OBJECT
public:
    enum Error {
    ErrConnectionRefused,
    ErrHostNotFound,
    ErrSocketRead
    };

    QSocket( QObject *parent=0, const char *name=0 );
    virtual ~QSocket();

    enum State { Idle, HostLookup, Connecting,
         Connected, Closing,
         Connection=Connected };
    State	 state() const;

    int		 socket() const;
    virtual void setSocket( int );

    QSocketDevice *socketDevice();
    virtual void setSocketDevice( QSocketDevice * );

#ifndef QT_NO_DNS
    virtual void connectToHost( const QString &host, Q_UINT16 port );
#endif
    QString	 peerName() const;

    // Implementation of QIODevice abstract virtual functions
    bool	 open( int mode );
    void	 close();
    void	 flush();
    Offset	 size() const;
    Offset	 at() const;
    bool	 at( Offset );
    bool	 atEnd() const;

    Q_ULONG	 bytesAvailable() const;
    Q_ULONG	 waitForMore( int msecs ) const;
    Q_ULONG	 bytesToWrite() const;

    Q_LONG	 readBlock( char *data, Q_ULONG maxlen );
    Q_LONG	 writeBlock( const char *data, Q_ULONG len );
    Q_LONG	 readLine( char *data, Q_ULONG maxlen );

    int		 getch();
    int		 putch( int );
    int		 ungetch(int);

    bool	 canReadLine() const;
    virtual	 QString readLine();

    Q_UINT16	 port() const;
    Q_UINT16	 peerPort() const;
    QHostAddress address() const;
    QHostAddress peerAddress() const;

signals:
    void	 hostFound();
    void	 connected();
    void	 connectionClosed();
    void	 delayedCloseFinished();
    void	 readyRead();
    void	 bytesWritten( int nbytes );
    void	 error( int );

protected slots:
    virtual void sn_read( bool force=FALSE );
    virtual void sn_write();

private slots:
    void	tryConnecting();
    void	emitErrorConnectionRefused();

private:
    QSocketPrivate *d;

    bool	 consumeReadBuf( Q_ULONG nbytes, char * );
    bool	 consumeWriteBuf( Q_ULONG nbytes );
    bool	 scanNewline( QByteArray * = 0 );
    void	 tryConnection();
    void         setSocketIntern( int socket );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSocket( const QSocket & );
    QSocket &operator=( const QSocket & );
#endif
};

#endif //QT_NO_NETWORK
#endif // QSOCKET_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSocket成员列表

完整的QSocket成员列表

这里是QSocket成员函数的完整列表，包括继承的成员。

  • QSocket()
  • ~QSocket()
  • address()
  • at()
  • atEnd()
  • blockSignals()
  • bytesAvailable()
  • bytesToWrite()
  • bytesWritten()
  • canReadLine()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • close()
  • connect()
  • connectNotify()
  • connectToHost()
  • connected()
  • connectionClosed()
  • customEvent()
  • delayedCloseFinished()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • error()
  • event()
  • eventFilter()
  • flags()
  • flush()
  • getch()
  • highPriority()
  • hostFound()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isAsynchronous()
  • isBuffered()
  • isCombinedAccess()
  • isDirectAccess()
  • isInactive()
  • isOpen()
  • isRaw()
  • isReadWrite()
  • isReadable()
  • isSequentialAccess()
  • isSynchronous()
  • isTranslated()
  • isWidgetType()
  • isWritable()
  • killTimer()
  • killTimers()
  • metaObject()
  • mode()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • open()
  • parent()
  • peerAddress()
  • peerName()
  • peerPort()
  • port()
  • property()
  • putch()
  • queryList()
  • readAll()
  • readBlock()
  • readLine()
  • readyRead()
  • removeChild()
  • removeEventFilter()
  • reset()
  • resetStatus()
  • sender()
  • setName()
  • setProperty()
  • setSocket()
  • setSocketDevice()
  • signalsBlocked()
  • size()
  • sn_read()
  • sn_write()
  • socket()
  • socketDevice()
  • startTimer()
  • state()
  • status()
  • timerEvent()
  • tr()
  • trUtf8()
  • ungetch()
  • waitForMore()
  • writeBlock()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QSocketDevice Class

QSocketDevice Class Reference
[network module]

The QSocketDevice class provides a platform-independent low-level socket API. More...

#include <qsocketdevice.h>

Inherits QIODevice.

List of all member functions.

Public Members

  • enum Type { Stream, Datagram }
  • QSocketDevice ( Type type = Stream )
  • QSocketDevice ( int socket, Type type )
  • virtual ~QSocketDevice ()
  • bool isValid () const
  • Type type () const
  • int socket () const
  • virtual void setSocket ( int socket, Type type )
  • bool blocking () const
  • virtual void setBlocking ( bool enable )
  • bool addressReusable () const
  • virtual void setAddressReusable ( bool enable )
  • int receiveBufferSize () const
  • virtual void setReceiveBufferSize ( uint size )
  • int sendBufferSize () const
  • virtual void setSendBufferSize ( uint size )
  • virtual bool connect ( const QHostAddress & addr, Q_UINT16 port )
  • virtual bool bind ( const QHostAddress & address, Q_UINT16 port )
  • virtual bool listen ( int backlog )
  • virtual int accept ()
  • Q_LONG bytesAvailable () const
  • Q_LONG waitForMore ( int msecs, bool * timeout = 0 ) const
  • virtual Q_LONG readBlock ( char * data, Q_ULONG maxlen )
  • virtual Q_LONG writeBlock ( const char * data, Q_ULONG len )
  • virtual Q_LONG writeBlock ( const char * data, Q_ULONG len, const QHostAddress & host, Q_UINT16 port )
  • Q_UINT16 port () const
  • Q_UINT16 peerPort () const
  • QHostAddress address () const
  • QHostAddress peerAddress () const
  • enum Error { NoError, AlreadyBound, Inaccessible, NoResources, Bug, Impossible, NoFiles, ConnectionRefused, NetworkFailure, UnknownError }
  • Error error () const

Protected Members

  • void setError ( Error err )

Detailed Description

The QSocketDevice class provides a platform-independent low-level socket API.

This class is not really intended for use outside Qt. It can be used to achieve some things that QSocket does not provide, but it's not particularly easy to understand or use.

The essential purpose of the class is to provide a QIODevice that works on sockets, wrapped in a platform-independent API.

See also QSocket, QSocketNotifier, QHostAddress and Input/Output and Networking.

Member Type Documentation

QSocketDevice::Error

This enum type describes the error states of QSocketDevice. At present these errors are defined:

  • QSocketDevice::NoError - all is fine.
  • QSocketDevice::AlreadyBound - bind() said so.
  • QSocketDevice::Inaccessible - the operating system or firewall prohibits something.
  • QSocketDevice::NoResources - the operating system ran out of something.
  • QSocketDevice::Bug - there seems to be a bug in QSocketDevice.
  • QSocketDevice::Impossible - the impossible happened, usually because you confused QSocketDevice horribly. Simple example:
      ::close( sd->socket() );
  sd->writeBlock( someData, 42 );
    The libc ::close() closes the socket, but QSocketDevice is not aware of this. So when you call writeBlock(), the impossible happens.
  • QSocketDevice::NoFiles - the operating system will not let QSocketDevice open another file.
  • QSocketDevice::ConnectionRefused - a connection attempt was rejected by the peer.
  • QSocketDevice::NetworkFailure - there is a network failure between this host and... and whatever.
  • QSocketDevice::UnknownError - the operating system reacted in a way that the Qt developers did not foresee.

QSocketDevice::Type

This enum type describes the type of the socket:

  • QSocketDevice::Stream - a stream socket (TCP, usually)
  • QSocketDevice::Datagram - a datagram socket (UDP, usually)

Member Function Documentation

QSocketDevice::QSocketDevice ( Type type = Stream )

Creates a QSocketDevice object for a stream or datagram socket.

The type argument must be either QSocketDevice::Stream for a reliable, connection-oriented TCP socket, or QSocketDevice::Datagram for an unreliable UDP socket.

See also blocking().

QSocketDevice::QSocketDevice ( int socket, Type type )

Creates a QSocketDevice object for the existing socket socket.

The type argument must match the actual socket type; use QSocketDevice::Stream for a reliable, connection-oriented TCP socket, or QSocketDevice::Datagram for an unreliable, connectionless UDP socket.

QSocketDevice::~QSocketDevice () [virtual]

Destroys the socket device and closes the socket if it is open.

int QSocketDevice::accept () [virtual]

Extracts the first connection from the queue of pending connections for this socket and returns a new socket identifier. Returns -1 if the operation failed.

See also bind() and listen().

QHostAddress QSocketDevice::address () const

Returns the address of this socket device. This may be 0.0.0.0 for a while, but is set to something sensible when there is a sensible value it can have.

bool QSocketDevice::addressReusable () const

Returns TRUE if the address of this socket can be used by other sockets at the same time, and FALSE if this socket claims exclusive ownership.

See also setAddressReusable().

bool QSocketDevice::bind ( const QHostAddress & address, Q_UINT16 port ) [virtual]

Assigns a name to an unnamed socket. The name is the host address address and the port number port. If the operation succeeds, bind() returns TRUE. Otherwise, it returns FALSE without changing what port() and address() return.

bind() is used by servers for setting up incoming connections. Call bind() before listen().

bool QSocketDevice::blocking () const

Returns TRUE if the socket is in blocking mode, or FALSE if it is in nonblocking mode or if the socket is invalid.

Note that this function does not set error().

Warning: On Windows, this function always returns TRUE since the ioctlsocket() function is broken.

See also setBlocking() and isValid().

Q_LONG QSocketDevice::bytesAvailable () const

Returns the number of bytes available for reading, or -1 if an error occurred.

Warning: On Microsoft Windows, we use the ioctlsocket() function to determine the number of bytes queued on the socket. According to Microsoft (KB Q125486), ioctlsocket() sometimes return an incorrect number. The only safe way to determine the amount of data on the socket is to read it using readBlock(). QSocket has workarounds to deal with this problem.

bool QSocketDevice::connect ( const QHostAddress & addr, Q_UINT16 port ) [virtual]

Connects to the IP address and port specified by addr and port. Returns TRUE if it establishes a connection, and FALSE if not. error() explains why.

Note that error() commonly returns NoError for non-blocking sockets; this just means that you can call connect() again in a little while and it'll probably succeed.

Error QSocketDevice::error () const

Returns the first error seen.

bool QSocketDevice::isValid () const

Returns TRUE if this is a valid socket; otherwise returns FALSE.

See also socket().

bool QSocketDevice::listen ( int backlog ) [virtual]

Specifies how many pending connections a server socket can have. Returns TRUE if the operation was successful, otherwise FALSE.

The listen() call only applies to sockets where type() is Stream, not Datagram sockets. listen() must not be called before bind() or after accept(). It is common to use a backlog value of 50 on most Unix systems.

See also bind() and accept().

QHostAddress QSocketDevice::peerAddress () const

Returns the address of the port this socket device is connected to. This may be 0.0.0.0 for a while, but is set to something sensible when there is a sensible value it can have.

Note that for Datagram sockets, this is the source port of the last packet received, and that it is in native byte order.

Q_UINT16 QSocketDevice::peerPort () const

Returns the port number of the port this socket device is connected to. This may be 0 for a while, but is set to something sensible when there is a sensible value it can have.

Note that for Datagram sockets, this is the source port of the last packet received.

Q_UINT16 QSocketDevice::port () const

Returns the port number of this socket device. This may be 0 for a while, but is set to something sensible when there is a sensible value it can have.

Note that Qt always uses native byte order, i.e. 67 is 67 in Qt, there is no need to call htons().

Q_LONG QSocketDevice::readBlock ( char * data, Q_ULONG maxlen ) [virtual]

Reads max maxlen bytes from the socket into data and returns the number of bytes read. Returns -1 if an error occurred.

Reimplemented from QIODevice.

int QSocketDevice::receiveBufferSize () const

Returns the size of the OS receive buffer.

See also setReceiveBufferSize().

int QSocketDevice::sendBufferSize () const

Returns the size of the OS send buffer.

See also setSendBufferSize().

void QSocketDevice::setAddressReusable ( bool enable ) [virtual]

Sets the address of this socket to be usable by other sockets too if enable is TRUE, and to be used exclusively by this socket if enable is FALSE.

When a socket is reusable, other sockets can use the same port number (and IP address), which is, in general, good. Of course other sockets cannot use the same (address,port,peer-address,peer-port) 4-tuple as this socket, so there is no risk of confusing the two TCP connections.

See also addressReusable().

void QSocketDevice::setBlocking ( bool enable ) [virtual]

Makes the socket blocking if enable is TRUE or nonblocking if enable is FALSE.

Sockets are blocking by default, but we recommend using nonblocking socket operations, especially for GUI programs that need to be responsive.

Warning: On Windows, this function should be used with care since whenever you use a QSocketNotifier on Windows, the socket is immediately made nonblocking.

See also blocking() and isValid().

void QSocketDevice::setError ( Error err ) [protected]

Allows subclasses to set the error state to err.

void QSocketDevice::setReceiveBufferSize ( uint size ) [virtual]

Sets the size of the OS receive buffer to size.

The OS receive buffer size effectively limits two things: how much data can be in transit at any one moment, and how much data can be received in one iteration of the main event loop.

The default is OS-dependent. A socket that receives large amounts of data is probably best off with a buffer size of 49152.

void QSocketDevice::setSendBufferSize ( uint size ) [virtual]

Sets the size of the OS send buffer to size.

The OS send buffer size effectively limits how much data can be in transit at any one moment.

The default is OS-dependent. A socket that sends large amounts of data is probably best off with a buffer size of 49152.

void QSocketDevice::setSocket ( int socket, Type type ) [virtual]

Sets the socket device to operate on the existing socket socket.

The type argument must match the actual socket type; use QSocketDevice::Stream for a reliable, connection-oriented TCP socket, or QSocketDevice::Datagram for an unreliable, connectionless UDP socket.

Any existing socket is closed.

See also isValid() and close().

int QSocketDevice::socket () const

Returns the socket number, or -1 if it is an invalid socket.

See also isValid() and type().

Type QSocketDevice::type () const

Returns the socket type which is either QSocketDevice::Stream or QSocketDevice::Datagram.

See also socket().

Q_LONG QSocketDevice::waitForMore ( int msecs, bool * timeout = 0 ) const

Wait up to msecs milliseconds for more data to be available. If msecs is -1 the call will block indefinitely.

This is a blocking call and should be avoided in event driven applications.

Returns the number of bytes available for reading, or -1 if an error occurred.

If timeout is non-null and no error occurred (i.e. it does not return -1), then this function sets timeout out to TRUE, if the reason for returning was that the timeout was reached, otherwise it sets timeout to FALSE. This is useful to find out if the peer closed the connection.

See also bytesAvailable().

Q_LONG QSocketDevice::writeBlock ( const char * data, Q_ULONG len ) [virtual]

Writes len bytes to the socket from data and returns the number of bytes written. Returns -1 if an error occurred.

This is used for QSocketDevice::Stream sockets.

Reimplemented from QIODevice.

Q_LONG QSocketDevice::writeBlock ( const char * data, Q_ULONG len, const QHostAddress & host, Q_UINT16 port ) [virtual]

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

Writes len bytes to the socket from data and returns the number of bytes written. Returns -1 if an error occurred.

This is used for QSocketDevice::Datagram sockets. You have to specify the host and port of the destination of the data.

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


qsocketdevice.h Include File

qsocketdevice.h

This is the verbatim text of the qsocketdevice.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsocketdevice.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSocketDevice class.
**
** Created : 970521
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the network module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSOCKETDEVICE_H
#define QSOCKETDEVICE_H

#ifndef QT_H
#include "qiodevice.h"
#include "qhostaddress.h" // int->QHostAddress conversion
#endif // QT_H

#if !defined( QT_MODULE_NETWORK ) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_NETWORK )
#define QM_EXPORT_NETWORK
#else
#define QM_EXPORT_NETWORK Q_EXPORT
#endif

#ifndef QT_NO_NETWORK
class QSocketDevicePrivate;

class  QM_EXPORT_NETWORK QSocketDevice: public QIODevice
{
public:
    enum Type { Stream, Datagram };

    QSocketDevice( Type type = Stream );
    QSocketDevice( int socket, Type type );
    virtual ~QSocketDevice();

    bool	 isValid() const;
    Type	 type() const;

    int		 socket() const;
    virtual void setSocket( int socket, Type type );

    bool	 open( int mode );
    void	 close();
    void	 flush();

    // Implementation of QIODevice abstract virtual functions
    Offset	 size() const;
    Offset	 at() const;
    bool	 at( Offset );
    bool	 atEnd() const;

    bool	 blocking() const;
    virtual void setBlocking( bool );

    bool	 addressReusable() const;
    virtual void setAddressReusable( bool );

    int		 receiveBufferSize() const;
    virtual void setReceiveBufferSize( uint );
    int		 sendBufferSize() const;
    virtual void setSendBufferSize( uint );

    virtual bool connect( const QHostAddress &, Q_UINT16 );

    virtual bool bind( const QHostAddress &, Q_UINT16 );
    virtual bool listen( int backlog );
    virtual int	 accept();

    Q_LONG	 bytesAvailable() const;
    Q_LONG	 waitForMore( int msecs, bool *timeout=0 ) const;
    Q_LONG	 readBlock( char *data, Q_ULONG maxlen );
    Q_LONG	 writeBlock( const char *data, Q_ULONG len );
    virtual Q_LONG  writeBlock( const char *data, Q_ULONG len,
                const QHostAddress & host, Q_UINT16 port );

    int		 getch();
    int		 putch( int );
    int		 ungetch(int);

    Q_UINT16	 port() const;
    Q_UINT16	 peerPort() const;
    QHostAddress address() const;
    QHostAddress peerAddress() const;

    enum Error { NoError, AlreadyBound, Inaccessible, NoResources,
         Bug, Impossible, NoFiles, ConnectionRefused,
         NetworkFailure, UnknownError };
    Error 	 error() const;

protected:
    void setError( Error err );

private:
    int fd;
    Type t;
    Q_UINT16 p;
    QHostAddress a;
    Q_UINT16 pp;
    QHostAddress pa;
    QSocketDevice::Error e;
    QSocketDevicePrivate * d;

    enum Option { Broadcast, ReceiveBuffer, ReuseAddress, SendBuffer };

    int		 option( Option ) const;
    virtual void setOption( Option, int );

    void	 fetchConnectionParameters();
#if defined(Q_OS_WIN32)
    void	 fetchPeerConnectionParameters();
#endif

    static void  init();
    int		 createNewSocket();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSocketDevice( const QSocketDevice & );
    QSocketDevice &operator=( const QSocketDevice & );
#endif
};

#endif // QT_NO_NETWORK
#endif // QSOCKETDEVICE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSocketDevice Member List

Complete Member List for QSocketDevice

This is the complete list of member functions for QSocketDevice, including inherited members.

  • QSocketDevice()
  • ~QSocketDevice()
  • accept()
  • address()
  • addressReusable()
  • at()
  • atEnd()
  • bind()
  • blocking()
  • bytesAvailable()
  • close()
  • connect()
  • error()
  • flags()
  • flush()
  • getch()
  • isAsynchronous()
  • isBuffered()
  • isCombinedAccess()
  • isDirectAccess()
  • isInactive()
  • isOpen()
  • isRaw()
  • isReadWrite()
  • isReadable()
  • isSequentialAccess()
  • isSynchronous()
  • isTranslated()
  • isValid()
  • isWritable()
  • listen()
  • mode()
  • open()
  • peerAddress()
  • peerPort()
  • port()
  • putch()
  • readAll()
  • readBlock()
  • readLine()
  • receiveBufferSize()
  • reset()
  • resetStatus()
  • sendBufferSize()
  • setAddressReusable()
  • setBlocking()
  • setError()
  • setReceiveBufferSize()
  • setSendBufferSize()
  • setSocket()
  • size()
  • socket()
  • state()
  • status()
  • type()
  • ungetch()
  • waitForMore()
  • writeBlock()


QSocketNotifier Class

QSocketNotifier Class Reference

The QSocketNotifier class provides support for socket callbacks. More...

#include <qsocketnotifier.h>

Inherits QObject.

List of all member functions.

Public Members

  • enum Type { Read, Write, Exception }
  • QSocketNotifier ( int socket, Type type, QObject * parent = 0, const char * name = 0 )
  • ~QSocketNotifier ()
  • int socket () const
  • Type type () const
  • bool isEnabled () const
  • virtual void setEnabled ( bool enable )

Signals

  • void activated ( int socket )

Detailed Description

The QSocketNotifier class provides support for socket callbacks.

This class makes it possible to write asynchronous socket-based code in Qt. Using synchronous socket operations blocks the program, which is clearly not acceptable for an event-driven GUI program.

Once you have opened a non-blocking socket (whether for TCP, UDP, a UNIX-domain socket, or any other protocol family your operating system supports), you can create a socket notifier to monitor the socket. Then you connect the activated() signal to the slot you want to be called when a socket event occurs.

There are three types of socket notifiers (read, write and exception); you must specify one of these in the constructor.

The type specifies when the activated() signal is to be emitted:

  1. QSocketNotifier::Read - There is data to be read (socket read event).
  2. QSocketNotifier::Write - Data can be written (socket write event).
  3. QSocketNofifier::Exception - An exception has occurred (socket exception event). We recommend against using this.

For example, if you need to monitor both reads and writes for the same socket you must create two socket notifiers.

Example:

        int sockfd;                                 // socket identifier
        struct sockaddr_in sa;                      // should contain host address
        sockfd = socket( AF_INET, SOCK_STREAM, 0 ); // create TCP socket
        // make the socket non-blocking here, usually using fcntl( O_NONBLOCK )
        ::connect( sockfd, (struct sockaddr*)&sa,   // connect to host
                   sizeof(sa) );                    // NOT QObject::connect()!
        QSocketNotifier *sn;
        sn = new QSocketNotifier( sockfd, QSocketNotifier::Read, parent );
        QObject::connect( sn, SIGNAL(activated(int)),
                          myObject, SLOT(dataReceived()) );

The optional parent argument can be set to make the socket notifier a child of any QObject, e.g. a widget. This will ensure that it is automatically destroyed when the widget is destroyed.

For read notifiers it makes little sense to connect the activated() signal to more than one slot because the data can be read from the socket only once.

Also observe that if you do not read all the available data when the read notifier fires, it fires again and again.

If you disable the read notifier your program may deadlock. (The same applies to exception notifiers if you must use them, for instance if you must use TCP urgent data.)

For write notifiers, immediately disable the notifier after the activated() signal has been received and you have sent the data to be written on the socket. When you have more data to be written, enable it again to get a new activated() signal. The exception is if the socket data writing operation (send() or equivalent) fails with a "would block" error, which means that some buffer is full and you must wait before sending more data. In that case you do not need to disable and re-enable the write notifier; it will fire again as soon as the system allows more data to be sent.

The behavior of a write notifier that is left in enabled state after having emitting the first activated() signal (and no "would block" error has occurred) is undefined. Depending on the operating system, it may fire on every pass of the event loop or not at all.

If you need a time-out for your sockets you can use either timer events or the QTimer class.

Socket action is detected in the main event loop of Qt. The X11 version of Qt has a single UNIX select() call that incorporates all socket notifiers and the X socket.

Note that on XFree86 for OS/2, select() works only in the thread in which main() is running; you should therefore use that thread for GUI operations.

See also QSocket, QServerSocket, QSocketDevice and Input/Output and Networking.

Member Type Documentation

QSocketNotifier::Type

  • QSocketNotifier::Read
  • QSocketNotifier::Write
  • QSocketNotifier::Exception

Member Function Documentation

QSocketNotifier::QSocketNotifier ( int socket, Type type, QObject * parent = 0, const char * name = 0 )

Constructs a socket notifier called name, with the parent, parent. It watches socket for type events, and enables it.

It is generally advisable to explicitly enable or disable the socket notifier, especially for write notifiers.

See also setEnabled() and isEnabled().

QSocketNotifier::~QSocketNotifier ()

Destroys the socket notifier.

void QSocketNotifier::activated ( int socket ) [signal]

This signal is emitted under certain conditions specified by the notifier type():

  1. QSocketNotifier::Read - There is data to be read (socket read event).
  2. QSocketNotifier::Write - Data can be written (socket write event).
  3. QSocketNofifier::Exception - An exception has occurred (socket exception event).

The socket argument is the socket identifier.

See also type() and socket().

bool QSocketNotifier::isEnabled () const

Returns TRUE if the notifier is enabled; otherwise returns FALSE.

See also setEnabled().

void QSocketNotifier::setEnabled ( bool enable ) [virtual]

Enables the notifier if enable is TRUE or disables it if enable is FALSE.

The notifier is enabled by default.

If the notifier is enabled, it emits the activated() signal whenever a socket event corresponding to its type occurs. If it is disabled, it ignores socket events (the same effect as not creating the socket notifier).

Write notifiers should normally be disabled immediately after the activated() signal has been emitted; see discussion of write notifiers in the class description above.

See also isEnabled() and activated().

int QSocketNotifier::socket () const

Returns the socket identifier specified to the constructor.

See also type().

Type QSocketNotifier::type () const

Returns the socket event type specified to the constructor: QSocketNotifier::Read, QSocketNotifier::Write, or QSocketNotifier::Exception.

See also socket().

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


qsocketnotifier.h Include File

qsocketnotifier.h

This is the verbatim text of the qsocketnotifier.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QSocketNotifier class
**
** Created : 951114
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSOCKETNOTIFIER_H
#define QSOCKETNOTIFIER_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

class Q_EXPORT QSocketNotifier : public QObject
{
    Q_OBJECT
public:
    enum Type { Read, Write, Exception };

    QSocketNotifier( int socket, Type, QObject *parent=0, const char *name=0 );
   ~QSocketNotifier();

    int		 socket()	const;
    Type	 type()		const;

    bool	 isEnabled()	const;
    virtual void setEnabled( bool );

signals:
    void	 activated( int socket );

protected:
    bool	 event( QEvent * );

private:
    int		 sockfd;
    Type	 sntype;
    bool	 snenabled;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSocketNotifier( const QSocketNotifier & );
    QSocketNotifier &operator=( const QSocketNotifier & );
#endif
};

inline int QSocketNotifier::socket() const
{ return sockfd; }

inline QSocketNotifier::Type QSocketNotifier::type() const
{ return sntype; }

inline bool QSocketNotifier::isEnabled() const
{ return snenabled; }

#endif // QSOCKETNOTIFIER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSocketNotifier Member List

Complete Member List for QSocketNotifier

This is the complete list of member functions for QSocketNotifier, including inherited members.

  • QSocketNotifier()
  • ~QSocketNotifier()
  • activated()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isEnabled()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setEnabled()
  • setName()
  • setProperty()
  • signalsBlocked()
  • socket()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • type()


QSortedList Class

QSortedList Class Reference
[obsolete]

The QSortedList class provides a list sorted by operator< and operator==. More...

#include <qsortedlist.h>

Inherits QPtrList<type>.

List of all member functions.

Public Members

  • QSortedList ()
  • QSortedList ( const QSortedList<type> & list )
  • ~QSortedList ()
  • QSortedList<type> & operator= ( const QSortedList<type> & list )

Detailed Description

The QSortedList class provides a list sorted by operator< and operator==.

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

If you want to sort a QPtrList you have to reimplement the QGList::compareItems() method. If the elements of your list support operator<() and operator==(), you can use QSortedList instead. Its compareItems() calls operator<() and operator==() and returns an appropriate result.

Otherwise, this is as QPtrList.

See also QPtrList.

Member Function Documentation

QSortedList::QSortedList ()

Constructs an empty list.

QSortedList::QSortedList ( const QSortedList<type> & list )

Constructs a copy of list.

Each item in list is copied to this new list.

QSortedList::~QSortedList ()

Removes all items from the list and destroys the list.

All list iterators that access this list will be reset.

QSortedList<type> & QSortedList::operator= ( const QSortedList<type> & list )

Assigns list to this list and returns a reference to this list.

This list is first cleared; each item in list is then appended to this list. Only the pointers are copied (shallow copy) unless newItem() has been reimplemented().

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


qsortedlist.h Include File

qsortedlist.h

This is the verbatim text of the qsortedlist.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsortedlist.h   3.0.5   edited May 29 15:07 $
**
** Definition of QSortedList template/macro class
**
** Created : 920701
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSORTEDLIST_H
#define QSORTEDLIST_H

#ifndef QT_H
#include "qptrlist.h"
#endif // QT_H

template<class type>
class QSortedList
    : public QPtrList<type>
{
public:
    QSortedList() {}
    QSortedList( const QSortedList<type> &l ) : QPtrList<type>(l) {}
    ~QSortedList() { clear(); }
    QSortedList<type> &operator=(const QSortedList<type> &l)
      { return (QSortedList<type>&)QPtrList<type>::operator=(l); }

    virtual int compareItems( QPtrCollection::Item s1, QPtrCollection::Item s2 )
      { if ( *((type*)s1) == *((type*)s2) ) return 0; return ( *((type*)s1) < *((type*)s2) ? -1 : 1 ); }
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSortedList Member List

Complete Member List for QSortedList

This is the complete list of member functions for QSortedList, including inherited members.

  • QSortedList()
  • ~QSortedList()
  • append()
  • at()
  • autoDelete()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • current()
  • currentNode()
  • deleteItem()
  • find()
  • findNext()
  • findNextRef()
  • findRef()
  • first()
  • getFirst()
  • getLast()
  • inSort()
  • insert()
  • isEmpty()
  • last()
  • newItem()
  • next()
  • operator=()
  • operator==()
  • prepend()
  • prev()
  • read()
  • remove()
  • removeFirst()
  • removeLast()
  • removeNode()
  • removeRef()
  • setAutoDelete()
  • sort()
  • take()
  • takeNode()
  • toVector()
  • write()


QSound类

QSound类参考

QSound提供对平台音频设备的访问。 详情请见……

#include <qsound.h>

继承了QObject。

所有成员函数的列表。

公有成员

  • QSound ( const QString & filename, QObject * parent = 0, const char * name = 0 )
  • ~QSound ()
  • int loops () const
  • int loopsRemaining () const
  • void setLoops ( int l )
  • QString fileName () const
  • bool isFinished () const

公有槽

  • void play ()
  • void stop ()

静态公有成员

  • bool isAvailable ()
  • void play ( const QString & filename )
  • bool available ()

详细描述

QSound提供对平台音频设备的访问。

Qt提供了在大多数GUI应用程序中通常都需要的操作：异步播放声音文件。这用一个单呼叫就能简单的完成：

        QSound::play("mysounds/bells.wav");

第二个API是被用来根据一个声音文件创建一个QSound对象并且随后就播放它：

        QSound bells("mysounds/bells.wav");

        bells.play();

用以上第二种方式播放声音虽然也许会消耗更多的内存，但依靠底层平台的音频设备，比起第一种方式播放声音起来更直接。

在微软Windows下使用的底层多媒系统，仅支持WAVE格式的声音文件。

在X11下有效的使用了网络音频系统，另外所有的操作工作都在默默的进行着。NAS支持WAVE和AU文件。

有趣的是，在苹果机上，我们使用QT（QuickTime）来播放声音，这意思就是说所有的QuickTime格式被Qt/Mac所支持。

在Qt/Embedded中,使用了内建混声服务器，可以直接访问/dev/dsp。其仅仅可以支持WAVE格式。

用QSound::isAvailable()可以测试支持的声音。

也可以参考多媒体类。

成员函数文档

QSound::QSound ( const QString & filename, QObject * parent = 0, const char * name = 0 )

构造一个QSound能够快速的通过一个名为filename的文件来播放声音。

这也许会比静态函数play使用更多的内存。

父类parent和名称name的参数（默认为0）被传递给了QObject的构造函数。

QSound::~QSound ()

销毁声音对象。

bool QSound::available () [静态]

如果可以有效的支持就返回真，否则返回假。

QString QSound::fileName () const

返回与声音有关的文件名。

bool QSound::isAvailable () [静态]

如果在该平台上存在声音设备便返回真，否则返回假。应用程序要么当声音是十分重要时选择报告用户要么就默默的操作而不麻烦用户了

如果没有有效的声音，所有的QSound操作工作安静且快速。

bool QSound::isFinished () const

当声音播放完成时返回真，否则返回假。

int QSound::loops () const

返回声音将播放的次数。

int QSound::loopsRemaining () const

返回声音将循环的次数。该值在每次声音循环后会减少。

该函数在窗口下不支持并且总是返回循环的总数。

void QSound::play ( const QString & filename ) [静态]

播放一个叫做filename的文件中的声音。

实例：sound/sound.cpp。

void QSound::play () [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

开启声音播放。该数数立即返回。依靠平台的音频设备，其它的声音也许被停止，也许被新的声音混合。

在任何时候声音可以再次播放，可能混合或者替代先播放的声音。

void QSound::setLoops ( int l )

当它播放时设置声音重复一次。超过-1的值也许会引起声音的死循环。

在Windows中, 不同于1的循环次数的声音将总是死循环。

也可以参考loops()。

void QSound::stop () [槽]

停止声音播放。

也可以参考play()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:hackerjun
Qt 3.0.5版


qsound.h包含文件

qsound.h

这里是qsound.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qsound.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QSound class and QAuServer internal class
**
** Created : 000117
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QSOUND_H
#define QSOUND_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_SOUND

class QSoundData;

class Q_EXPORT QSound : public QObject {
    Q_OBJECT
public:
    static bool isAvailable();
    static void play(const QString& filename);

    QSound(const QString& filename, QObject* parent=0, const char* name=0);
    ~QSound();

    /* Coming soon...
    ?
    QSound(int hertz, Type type=Mono);
    int play(const ushort* data, int samples);
    bool full();
    signal void notFull();
    ?
    */

#ifndef QT_NO_COMPAT
    static bool available() { return isAvailable(); }
#endif

    int loops() const;
    int loopsRemaining() const;
    void setLoops(int);
    QString fileName() const;

    bool isFinished() const;

public slots:
    void play();
    void stop();

private:
    QSoundData* d;
    friend class QAuServer;
};

/*
  QAuServer is an INTERNAL class.  If you wish to provide support for
  additional audio servers, you can make a subclass of QAuServer to do
  so, HOWEVER, your class may need to be re-engineered to some degree
  with each new Qt release, including minor releases.

  QAuBucket is whatever you want.
*/

class QAuBucket {
public:
    virtual ~QAuBucket();
};

class QAuServer : public QObject {
    Q_OBJECT

public:
    QAuServer(QObject* parent, const char* name);
    ~QAuServer();

    virtual void init(QSound*);
    virtual void play(const QString& filename);
    virtual void play(QSound*)=0;
    virtual void stop(QSound*)=0;
    virtual bool okay()=0;

protected:
    void setBucket(QSound*, QAuBucket*);
    QAuBucket* bucket(QSound*);
    int decLoop(QSound*);
};

#endif // QT_NO_SOUND

#endif

Copyright © 2002 Trolltech Trademarks 译者:hackerjun
Qt 3.0.5版


QSound成员列表

完整的QSound成员列表

这里是QSound成员函数的完整列表，包括继承的成员。

  • QSound()
  • ~QSound()
  • available()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fileName()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isAvailable()
  • isFinished()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • loops()
  • loopsRemaining()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • play()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setLoops()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • stop()
  • timerEvent()
  • tr()
  • trUtf8()

Copyright © 2002 Trolltech Trademarks 译者:hackerjun
Qt 3.0.5版


QSpacerItem Class

QSpacerItem Class Reference

The QSpacerItem class provides blank space in a layout. More...

#include <qlayout.h>

Inherits QLayoutItem.

List of all member functions.

Public Members

  • QSpacerItem ( int w, int h, QSizePolicy::SizeType hData = QSizePolicy::Minimum, QSizePolicy::SizeType vData = QSizePolicy::Minimum )
  • void changeSize ( int w, int h, QSizePolicy::SizeType hData = QSizePolicy::Minimum, QSizePolicy::SizeType vData = QSizePolicy::Minimum )
  • virtual QSize sizeHint () const
  • virtual QSize minimumSize () const
  • virtual QSize maximumSize () const
  • virtual QSizePolicy::ExpandData expanding () const
  • virtual bool isEmpty () const
  • virtual void setGeometry ( const QRect & r )

Detailed Description

The QSpacerItem class provides blank space in a layout.

This class is used by custom layouts.

See also QLayout, QLayout::spacerItem(), Widget Appearance and Style and Layout Management.

Member Function Documentation

QSpacerItem::QSpacerItem ( int w, int h, QSizePolicy::SizeType hData = QSizePolicy::Minimum, QSizePolicy::SizeType vData = QSizePolicy::Minimum )

Constructs a spacer item with preferred width w, preferred height h, horizontal size policy hData and vertical size policy vData.

The default values provide a gap that is able to stretch if nothing else wants the space.

void QSpacerItem::changeSize ( int w, int h, QSizePolicy::SizeType hData = QSizePolicy::Minimum, QSizePolicy::SizeType vData = QSizePolicy::Minimum )

Changes this spacer item to have preferred width w, preferred height h, horizontal size policy hData and vertical size policy vData.

The default values provide a gap that is able to stretch if nothing else wants the space.

QSizePolicy::ExpandData QSpacerItem::expanding () const [virtual]

Returns TRUE if this spacer item is expanding; otherwise returns FALSE.

Reimplemented from QLayoutItem.

bool QSpacerItem::isEmpty () const [virtual]

Returns TRUE because a spacer item never contains widgets.

Reimplemented from QLayoutItem.

QSize QSpacerItem::maximumSize () const [virtual]

Returns the maximum size of this spacer item.

Reimplemented from QLayoutItem.

QSize QSpacerItem::minimumSize () const [virtual]

Returns the minimum size of this spacer item.

Reimplemented from QLayoutItem.

void QSpacerItem::setGeometry ( const QRect & r ) [virtual]

Stores the spacer item's rect r so that it can be returned by geometry().

Reimplemented from QLayoutItem.

QSize QSpacerItem::sizeHint () const [virtual]

Returns the preferred size of this spacer item.

Reimplemented from QLayoutItem.

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


QSpacerItem Member List

Complete Member List for QSpacerItem

This is the complete list of member functions for QSpacerItem, including inherited members.

  • QSpacerItem()
  • alignment()
  • changeSize()
  • expanding()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • invalidate()
  • isEmpty()
  • iterator()
  • layout()
  • maximumSize()
  • minimumSize()
  • setAlignment()
  • setGeometry()
  • sizeHint()
  • spacerItem()
  • widget()


QSpinBox Class

QSpinBox Class Reference

The QSpinBox class provides a spin box widget (spin button). More...

#include <qspinbox.h>

Inherits QWidget and QRangeControl.

List of all member functions.

Public Members

  • QSpinBox ( QWidget * parent = 0, const char * name = 0 )
  • QSpinBox ( int minValue, int maxValue, int step = 1, QWidget * parent = 0, const char * name = 0 )
  • ~QSpinBox ()
  • QString text () const
  • virtual QString prefix () const
  • virtual QString suffix () const
  • virtual QString cleanText () const
  • virtual void setSpecialValueText ( const QString & text )
  • QString specialValueText () const
  • virtual void setWrapping ( bool on )
  • bool wrapping () const
  • enum ButtonSymbols { UpDownArrows, PlusMinus }
  • virtual void setButtonSymbols ( ButtonSymbols )
  • ButtonSymbols buttonSymbols () const
  • virtual void setValidator ( const QValidator * v )
  • const QValidator * validator () const
  • int minValue () const
  • int maxValue () const
  • void setMinValue ( int )
  • void setMaxValue ( int )
  • int lineStep () const
  • void setLineStep ( int )
  • int value () const
  • QRect upRect () const
  • QRect downRect () const

Public Slots

  • virtual void setValue ( int value )
  • virtual void setPrefix ( const QString & text )
  • virtual void setSuffix ( const QString & text )
  • virtual void stepUp ()
  • virtual void stepDown ()
  • virtual void selectAll ()

Signals

  • void valueChanged ( int value )
  • void valueChanged ( const QString & valueText )

Properties

  • ButtonSymbols buttonSymbols - the current button symbol mode
  • QString cleanText - the text of the spin box with any prefix() or suffix() and any whitespace at the start and end removed (read only)
  • int lineStep - the line step
  • int maxValue - the maximum value of the spin box
  • int minValue - the minimum value of the spin box
  • QString prefix - the prefix of the spin box
  • QString specialValueText - the special-value text
  • QString suffix - the suffix of the spin box
  • QString text - the text of the spin box, including any prefix() and suffix() (read only)
  • int value - the value of the spin box
  • bool wrapping - whether it is possible to step the value from the highest value to the lowest value and vice versa

Protected Members

  • virtual QString mapValueToText ( int v )
  • virtual int mapTextToValue ( bool * ok )
  • QString currentValueText ()
  • virtual void updateDisplay ()
  • virtual void interpretText ()
  • QLineEdit * editor () const
  • virtual void valueChange ()
  • virtual void rangeChange ()
  • virtual bool eventFilter ( QObject * obj, QEvent * ev )

Protected Slots

  • void textChanged ()

Detailed Description

The QSpinBox class provides a spin box widget (spin button).

QSpinBox allows the user to choose a value either by clicking the up/down buttons to increase/decrease the value currently displayed or by typing the value directly into the spin box. If the value is entered directly into the spin box, \Key Enter must be pressed to apply the new value. The value is usually an integer.

Every time the value changes QSpinBox emits the valueChanged() signal. The current value can be fetched with value() and set with setValue().

The spin box keeps the value within a numeric range, and to multiples of the lineStep() size (see QRangeControl for details). Clicking the up/down buttons or using the keyboard accelerator's up and down arrows will increase or decrease the current value in steps of size lineStep(). The minimum and maximum value and the step size can be set using one of the constructors, and can be changed later with setMinValue(), setMaxValue() and setLineStep().

Most spin boxes are directional, but QSpinBox can also operate as a circular spin box, i.e. if the range is 0-99 and the current value is 99, clicking "up" will give 0. Use setWrapping() if you want circular behavior.

The displayed value can be prepended and appended with arbitrary strings indicating, for example, currency or the unit of measurement. See setPrefix() and setSuffix(). The text in the spin box is retrieved with text() (which includes any prefix() and suffix()), or with cleanText() (which has no prefix(), no suffix() and no leading or trailing whitespace). currentValueText() returns the spin box's current value as text.

Normally the spin box displays up and down arrows in the buttons. You can use setButtonSymbols() to change the display to show + and - symbols if this is clearer for your intended purpose. In either case the up and down arrow keys work as expected.

It is often desirable to give the user a special (often default) choice in addition to the range of numeric values. See setSpecialValueText() for how to do this with QSpinBox.

The default QWidget::focusPolicy() is StrongFocus.

If using prefix(), suffix() and specialValueText() don't provide enough control, you can ignore them and subclass QSpinBox instead.

QSpinBox can easily be subclassed to allow the user to input things other than an integer value as long as the allowed input can be mapped to a range of integers. This can be done by overriding the virtual functions mapValueToText() and mapTextToValue(), and setting another suitable validator using setValidator().

For example, these functions could be changed so that the user provided values from 0.0 to 10.0, or -1 to signify 'Auto', while the range of integers used inside the program would be -1 to 100:

    class MySpinBox : public QSpinBox
    {
        Q_OBJECT
    public:
        ...

        QString mapValueToText( int value )
        {
            if ( value == -1 ) // special case
                return QString( "Auto" );

            return QString( "%1.%2" ) // 0.0 to 10.0
                   .arg( value / 10 ).arg( value % 10 );
        }

        int mapTextToValue( bool *ok )
        {
            if ( text() == "Auto" ) // special case
                return -1;

            return (int) ( 10 * text().toFloat() ); // 0 to 100
        }
    };

See also QScrollBar, QSlider, GUI Design Handbook: Spin Box and Basic Widgets.

Member Type Documentation

QSpinBox::ButtonSymbols

This enum type determines what the buttons in a spin box show. The currently defined values are:
  • QSpinBox::UpDownArrows - the buttons show little arrows in the classic style.
  • QSpinBox::PlusMinus - the buttons show + and - symbols.

See also QSpinBox::buttonSymbols.

Member Function Documentation

QSpinBox::QSpinBox ( QWidget * parent = 0, const char * name = 0 )

Constructs a spin box with the default QRangeControl range and step values. It has the parent parent and the name name.

See also minValue, maxValue, setRange(), lineStep and setSteps().

QSpinBox::QSpinBox ( int minValue, int maxValue, int step = 1, QWidget * parent = 0, const char * name = 0 )

Constructs a spin box that allows values from minValue to maxValue inclusive, with step amount step. The value is initially set to minValue.

The widget's parent is parent and the spin box is called name.

See also minValue, maxValue, setRange(), lineStep and setSteps().

QSpinBox::~QSpinBox ()

Destroys the spin box, freeing all memory and other resources.

ButtonSymbols QSpinBox::buttonSymbols () const

Returns the current button symbol mode. See the "buttonSymbols" property for details.

QString QSpinBox::cleanText () const [virtual]

Returns the text of the spin box with any prefix() or suffix() and any whitespace at the start and end removed. See the "cleanText" property for details.

QString QSpinBox::currentValueText () [protected]

Returns the full text calculated from the current value, including any prefix and suffix. If there is special value text and the value is minValue() the specialValueText() is returned.

QRect QSpinBox::downRect () const

Returns the geometry of the "down" button.

QLineEdit * QSpinBox::editor () const [protected]

Returns a pointer to the embedded QLineEdit.

bool QSpinBox::eventFilter ( QObject * obj, QEvent * ev ) [virtual protected]

Intercepts and handles the events coming to the embedded QLineEdit that have special meaning for the QSpinBox. The object is passed as obj and the event is passed as ev.

Reimplemented from QObject.

void QSpinBox::interpretText () [virtual protected]

QSpinBox calls this after the user has manually edited the contents of the spin box (i.e. by typing in the embedded QLineEdit, rather than using the up/down buttons/keys).

The default implementation of this function interprets the new text using mapTextToValue(). If mapTextToValue() is successful, it changes the spin box's value; if not, the value is left unchanged.

See also editor().

int QSpinBox::lineStep () const

Returns the line step. See the "lineStep" property for details.

int QSpinBox::mapTextToValue ( bool * ok ) [virtual protected]

This virtual function is used by the spin box whenever it needs to interpret text entered by the user as a value. The text is available as text() and as cleanText(), and this function must parse it if possible, and set the bool *ok to TRUE if successful and to FALSE otherwise.

Subclasses that need to display spin box values in a non-numeric way need to reimplement this function.

Note that Qt handles specialValueText() separately; this function is only concerned with the other values.

The default implementation tries to interpret the text() as an integer in the standard way and returns the integer value.

See also interpretText() and mapValueToText().

QString QSpinBox::mapValueToText ( int v ) [virtual protected]

This virtual function is used by the spin box whenever it needs to display value v. The default implementation returns a string containing v printed in the standard way. Reimplementations may return anything. (See the example in the detailed description.)

Note that Qt does not call this function for specialValueText() and that neither prefix() nor suffix() are included in the return value.

If you reimplement this, you may also need to reimplement mapTextToValue().

See also updateDisplay() and mapTextToValue().

int QSpinBox::maxValue () const

Returns the maximum value of the spin box. See the "maxValue" property for details.

int QSpinBox::minValue () const

Returns the minimum value of the spin box. See the "minValue" property for details.

QString QSpinBox::prefix () const [virtual]

Returns the prefix of the spin box. See the "prefix" property for details.

void QSpinBox::rangeChange () [virtual protected]

This virtual function is called by QRangeControl whenever the range has changed. It adjusts the default validator and updates the display; if you need additional processing, you may reimplement this function.

Reimplemented from QRangeControl.

void QSpinBox::selectAll () [virtual slot]

Selects all the text in the editor of the spinbox.

void QSpinBox::setButtonSymbols ( ButtonSymbols ) [virtual]

Sets the current button symbol mode. See the "buttonSymbols" property for details.

void QSpinBox::setLineStep ( int )

Sets the line step. See the "lineStep" property for details.

void QSpinBox::setMaxValue ( int )

Sets the maximum value of the spin box. See the "maxValue" property for details.

void QSpinBox::setMinValue ( int )

Sets the minimum value of the spin box. See the "minValue" property for details.

void QSpinBox::setPrefix ( const QString & text ) [virtual slot]

Sets the prefix of the spin box to text. See the "prefix" property for details.

void QSpinBox::setSpecialValueText ( const QString & text ) [virtual]

Sets the special-value text to text. See the "specialValueText" property for details.

void QSpinBox::setSuffix ( const QString & text ) [virtual slot]

Sets the suffix of the spin box to text. See the "suffix" property for details.

void QSpinBox::setValidator ( const QValidator * v ) [virtual]

Sets the validator to v. The validator controls what keyboard input is accepted when the user is editing in the value field. The default is to use a suitable QIntValidator.

Use setValidator(0) to turn off input validation (entered input will still be clamped to the range of the spinbox).

void QSpinBox::setValue ( int value ) [virtual slot]

Sets the value of the spin box to value. See the "value" property for details.

void QSpinBox::setWrapping ( bool on ) [virtual]

Sets whether it is possible to step the value from the highest value to the lowest value and vice versa to on. See the "wrapping" property for details.

QString QSpinBox::specialValueText () const

Returns the special-value text. See the "specialValueText" property for details.

void QSpinBox::stepDown () [virtual slot]

Decreases the spin box's value one lineStep(), wrapping as necessary. This is the same as clicking on the pointing-down button and can be used for keyboard accelerators, for example.

See also stepUp(), subtractLine(), lineStep, setSteps(), value and value.

void QSpinBox::stepUp () [virtual slot]

Increases the spin box's value by one lineStep(), wrapping as necessary. This is the same as clicking on the pointing-up button and can be used for keyboard accelerators, for example.

See also stepDown(), addLine(), lineStep, setSteps(), value and value.

QString QSpinBox::suffix () const [virtual]

Returns the suffix of the spin box. See the "suffix" property for details.

QString QSpinBox::text () const

Returns the text of the spin box, including any prefix() and suffix(). See the "text" property for details.

void QSpinBox::textChanged () [protected slot]

This slot is called whenever the user edits the text of the spin box.

QRect QSpinBox::upRect () const

Returns the geometry of the "up" button.

void QSpinBox::updateDisplay () [virtual protected]

Updates the contents of the embedded QLineEdit to reflect the current value using mapValueToText(). Also enables/disables the up/down push buttons accordingly.

See also mapValueToText().

const QValidator * QSpinBox::validator () const

Returns the validator that constrains editing for this spin box if there is any; otherwise returns 0.

See also setValidator() and QValidator.

int QSpinBox::value () const

Returns the value of the spin box. See the "value" property for details.

void QSpinBox::valueChange () [virtual protected]

This virtual function is called by QRangeControl whenever the value has changed. The QSpinBox reimplementation updates the display and emits the valueChanged() signals; if you need additional processing, either reimplement this or connect to one of the valueChanged() signals.

Reimplemented from QRangeControl.

void QSpinBox::valueChanged ( int value ) [signal]

This signal is emitted every time the value of the spin box changes; the new value is passed in value. This signal will be emitted as a result of a call to setValue(), or because the user changed the value by using a keyboard accelerator or mouse click, etc.

Note that the valueChanged() signal is emitted every time, not just for the "final" step; i.e. if the user clicks "up" three times, this signal is emitted three times.

See also value.

Examples: listbox/listbox.cpp, qfd/fontdisplayer.cpp and scribble/scribble.cpp.

void QSpinBox::valueChanged ( const QString & valueText ) [signal]

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

This signal is emitted whenever the valueChanged( int ) signal is emitted, i.e. every time the value of the spin box changes (whatever the cause, e.g. by setValue(), by a keyboard accelerator, by mouse clicks, etc.).

The valueText parameter is the same string that is displayed in the edit field of the spin box.

See also value, prefix, suffix and specialValueText.

bool QSpinBox::wrapping () const

Returns TRUE if it is possible to step the value from the highest value to the lowest value and vice versa; otherwise returns FALSE. See the "wrapping" property for details.

Property Documentation

ButtonSymbols buttonSymbols

This property holds the current button symbol mode.

The possible values can be either UpDownArrows or PlusMinus. The default is UpDownArrows.

See also ButtonSymbols.

Set this property's value with setButtonSymbols() and get this property's value with buttonSymbols().

QString cleanText

This property holds the text of the spin box with any prefix() or suffix() and any whitespace at the start and end removed.

Get this property's value with cleanText().

See also text, prefix and suffix.

int lineStep

This property holds the line step.

When the user uses the arrows to change the spin box's value the value will be incremented/decremented by the amount of the line step.

The setLineStep() function calls the virtual stepChange() function if the new line step is different from the previous setting.

See also QRangeControl::setSteps() and setRange().

Set this property's value with setLineStep() and get this property's value with lineStep().

int maxValue

This property holds the maximum value of the spin box.

When setting this property, the QSpinBox::minValue is adjusted so that the range remains valid if necessary.

See also setRange() and specialValueText.

Set this property's value with setMaxValue() and get this property's value with maxValue().

int minValue

This property holds the minimum value of the spin box.

When setting this property, the QSpinBox::maxValue is adjusted so that the range remains valid if necessary.

See also setRange() and specialValueText.

Set this property's value with setMinValue() and get this property's value with minValue().

QString prefix

This property holds the prefix of the spin box.

The prefix is prepended to the start of the displayed value. Typical use is to indicate the unit of measurement to the user. For example:

    sb->setPrefix( "$" );

To turn off the prefix display, set this property to an empty string. The default is no prefix. The prefix is not displayed for the minValue() if specialValueText() is not empty.

If no prefix is set, prefix() returns a null string.

See also suffix.

Set this property's value with setPrefix() and get this property's value with prefix().

QString specialValueText

This property holds the special-value text.

If set, the spin box will display this text instead of a numeric value whenever the current value is equal to minVal(). Typical use is to indicate that this choice has a special (default) meaning.

For example, if your spin box allows the user to choose the margin width in a print dialog and your application is able to automatically choose a good margin width, you can set up the spin box like this:

    QSpinBox marginBox( -1, 20, 1, parent, "marginBox" );
    marginBox->setSuffix( " mm" );
    marginBox->setSpecialValueText( "Auto" );
The user will then be able to choose a margin width from 0-20 millimeters or select "Auto" to leave it to the application to choose. Your code must then interpret the spin box value of -1 as the user requesting automatic margin width.

All values are displayed with the prefix() and suffix() (if set), except for the special value, which only shows the special value text.

To turn off the special-value text display, call this function with an empty string. The default is no special-value text, i.e. the numeric value is shown as usual.

If no special-value text is set, specialValueText() returns a null string.

Set this property's value with setSpecialValueText() and get this property's value with specialValueText().

QString suffix

This property holds the suffix of the spin box.

The suffix is appended to the end of the displayed value. Typical use is to indicate the unit of measurement to the user. For example:

    sb->setSuffix( " km" );

To turn off the suffix display, set this property to an empty string. The default is no suffix. The suffix is not displayed for the minValue() if specialValueText() is not empty.

If no suffix is set, suffix() returns a null string.

See also prefix.

Set this property's value with setSuffix() and get this property's value with suffix().

QString text

This property holds the text of the spin box, including any prefix() and suffix().

There is no default text.

See also value.

Get this property's value with text().

int value

This property holds the value of the spin box.

Set this property's value with setValue() and get this property's value with value().

See also QRangeControl::setValue().

bool wrapping

This property holds whether it is possible to step the value from the highest value to the lowest value and vice versa.

By default, wrapping is turned off.

If you have a range of 0..100 and wrapping is off when the user reaches 100 and presses the Up Arrow nothing will happen; but if wrapping is on the value will change from 100 to 0, then to 1, etc. When wrapping is on, navigating past the highest value takes you to the lowest and vice versa.

See also minValue, maxValue and setRange().

Set this property's value with setWrapping() and get this property's value with wrapping().

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


qspinbox.h Include File

qspinbox.h

This is the verbatim text of the qspinbox.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qspinbox.h   3.0.5   edited Nov 30 2001 $
**
** Definition of QSpinBox widget class
**
** Created : 1997
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSPINBOX_H
#define QSPINBOX_H

#ifndef QT_H
#include "qwidget.h"
#include "qrangecontrol.h"
#endif // QT_H

#ifndef QT_NO_SPINBOX

class QLineEdit;
class QValidator;
class QSpinBoxPrivate;

class Q_EXPORT QSpinBox: public QWidget, public QRangeControl
{
    Q_OBJECT
    Q_ENUMS( ButtonSymbols )
    Q_PROPERTY( QString text READ text )
    Q_PROPERTY( QString prefix READ prefix WRITE setPrefix )
    Q_PROPERTY( QString suffix READ suffix WRITE setSuffix )
    Q_PROPERTY( QString cleanText READ cleanText )
    Q_PROPERTY( QString specialValueText READ specialValueText WRITE setSpecialValueText )
    Q_PROPERTY( bool wrapping READ wrapping WRITE setWrapping )
    Q_PROPERTY( ButtonSymbols buttonSymbols READ buttonSymbols WRITE setButtonSymbols )
    Q_PROPERTY( int maxValue READ maxValue WRITE setMaxValue )
    Q_PROPERTY( int minValue READ minValue WRITE setMinValue )
    Q_PROPERTY( int lineStep READ lineStep WRITE setLineStep )
    Q_PROPERTY( int value READ value WRITE setValue )

public:
    QSpinBox( QWidget* parent=0, const char* name=0 );
    QSpinBox( int minValue, int maxValue, int step = 1,
          QWidget* parent=0, const char* name=0 );
    ~QSpinBox();

    QString		text() const;

    virtual QString	prefix() const;
    virtual QString	suffix() const;
    virtual QString	cleanText() const;

    virtual void	setSpecialValueText( const QString &text );
    QString		specialValueText() const;

    virtual void	setWrapping( bool on );
    bool		wrapping() const;

    enum ButtonSymbols { UpDownArrows, PlusMinus };
    virtual void	setButtonSymbols( ButtonSymbols );
    ButtonSymbols	buttonSymbols() const;

    virtual void	setValidator( const QValidator* v );
    const QValidator * validator() const;

    QSize		sizeHint() const;
    QSize		minimumSizeHint() const;

    int	 minValue() const;
    int	 maxValue() const;
    void setMinValue( int );
    void setMaxValue( int );
    int	 lineStep() const;
    void setLineStep( int );
    int  value() const;

    QRect		upRect() const;
    QRect		downRect() const;

public slots:
    virtual void	setValue( int value );
    virtual void	setPrefix( const QString &text );
    virtual void	setSuffix( const QString &text );
    virtual void	stepUp();
    virtual void	stepDown();
    virtual void 	setEnabled( bool enabled );
    virtual void 	selectAll();

signals:
    void		valueChanged( int value );
    void		valueChanged( const QString &valueText );

protected:
    virtual QString	mapValueToText( int value );
    virtual int		mapTextToValue( bool* ok );
    QString		currentValueText();

    virtual void	updateDisplay();
    virtual void	interpretText();

    QLineEdit*		editor() const;

    virtual void	valueChange();
    virtual void	rangeChange();

    bool		eventFilter( QObject* obj, QEvent* ev );
    void		resizeEvent( QResizeEvent* ev );
#ifndef QT_NO_WHEELEVENT
    void		wheelEvent( QWheelEvent * );
#endif
    void		leaveEvent( QEvent* );

    void		styleChange( QStyle& );

protected slots:
    void		textChanged();

private:
    void initSpinBox();
    QSpinBoxPrivate* d;
    QLineEdit* vi;
    QValidator* validate;
    QString pfix;
    QString sfix;
    QString specText;

    uint wrap		: 1;
    uint edited		: 1;

    void arrangeWidgets();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSpinBox( const QSpinBox& );
    QSpinBox& operator=( const QSpinBox& );
#endif

};

#endif // QT_NO_SPINBOX

#endif // QSPINBOX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSpinBox Member List

Complete Member List for QSpinBox

This is the complete list of member functions for QSpinBox, including inherited members.

  • QSpinBox()
  • ~QSpinBox()
  • acceptDrops()
  • addLine()
  • addPage()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bound()
  • buttonSymbols()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • cleanText()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • currentValueText()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • directSetValue()
  • disconnect()
  • disconnectNotify()
  • downRect()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • editor()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • interpretText()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineStep()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTextToValue()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • mapValueToText()
  • maxValue()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minValue()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageStep()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • positionFromValue()
  • prefix()
  • prevValue()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • rangeChange()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • selectAll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setButtonSymbols()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineStep()
  • setMask()
  • setMaxValue()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinValue()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPrefix()
  • setProperty()
  • setRange()
  • setSizeIncrement()
  • setSizePolicy()
  • setSpecialValueText()
  • setSteps()
  • setStyle()
  • setSuffix()
  • setTabOrder()
  • setUpdatesEnabled()
  • setValidator()
  • setValue()
  • setWFlags()
  • setWrapping()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • specialValueText()
  • stackUnder()
  • startTimer()
  • stepChange()
  • stepDown()
  • stepUp()
  • style()
  • styleChange()
  • subtractLine()
  • subtractPage()
  • suffix()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • upRect()
  • update()
  • updateDisplay()
  • updateGeometry()
  • updateMask()
  • validator()
  • value()
  • valueChange()
  • valueChanged()
  • valueFromPosition()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wrapping()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QSplitter Class

QSplitter Class Reference

The QSplitter class implements a splitter widget. More...

#include <qsplitter.h>

Inherits QFrame.

List of all member functions.

Public Members

  • enum ResizeMode { Stretch, KeepSize, FollowSizeHint }
  • QSplitter ( QWidget * parent = 0, const char * name = 0 )
  • QSplitter ( Orientation o, QWidget * parent = 0, const char * name = 0 )
  • ~QSplitter ()
  • virtual void setOrientation ( Orientation )
  • Orientation orientation () const
  • virtual void setResizeMode ( QWidget * w, ResizeMode mode )
  • virtual void setOpaqueResize ( bool on = TRUE )
  • bool opaqueResize () const
  • void moveToFirst ( QWidget * w )
  • void moveToLast ( QWidget * w )
  • void refresh ()
  • QValueList<int> sizes () const
  • void setSizes ( QValueList<int> list )

Properties

  • Orientation orientation - the orientation of the splitter

Protected Members

  • virtual void childEvent ( QChildEvent * c )
  • int idAfter ( QWidget * w ) const
  • void moveSplitter ( QCOORD p, int id )
  • virtual void drawSplitter ( QPainter * p, QCOORD x, QCOORD y, QCOORD w, QCOORD h ) (obsolete)
  • int adjustPos ( int p, int id )
  • virtual void setRubberband ( int p )
  • void getRange ( int id, int * min, int * max )

Detailed Description

The QSplitter class implements a splitter widget.

A splitter lets the user control the size of child widgets by dragging the boundary between the children. Any number of widgets may be controlled.

To show a QListBox, a QListView and a QTextEdit side by side:

    QSplitter *split = new QSplitter( parent );
    QListBox *lb = new QListBox( split );
    QListView *lv = new QListView( split );
    QTextEdit *ed = new QTextEdit( split );

In QSplitter the boundary can be either horizontal or vertical. The default is horizontal (the children are side by side) but you can use setOrientation( QSplitter::Vertical ) to set it to vertical.

By default, all widgets can be as large or as small as the user wishes, down to minimumSizeHint(). You can also use setMinimumSize() and setMaximumSize() on the children. Use setResizeMode() to specify that a widget should keep its size when the splitter is resized.

Although QSplitter normally resizes the children only at the end of a resize operation, if you call setOpaqueResize( TRUE ) the widgets are resized as often as possible.

The initial distribution of size between the widgets is determined by the initial size of each widget. You can also use setSizes() to set the sizes of all the widgets. The function sizes() returns the sizes set by the user.

If you hide() a child its space will be distributed among the other children. It will be reinstated when you show() it again. It is also possible to reorder the widgets within the splitter using moveToFirst() and moveToLast().

See also QTabBar and Organizers.

Member Type Documentation

QSplitter::ResizeMode

This enum type describes how QSplitter will resize each of its child widgets. The currently defined values are:

  • QSplitter::Stretch - the widget will be resized when the splitter itself is resized.
  • QSplitter::KeepSize - QSplitter will try to keep this widget's size unchanged.
  • QSplitter::FollowSizeHint - QSplitter will resize the widget when the widget's size hint changes.

Member Function Documentation

QSplitter::QSplitter ( QWidget * parent = 0, const char * name = 0 )

Constructs a horizontal splitter with the parent and name arguments being passed on to the QFrame constructor.

QSplitter::QSplitter ( Orientation o, QWidget * parent = 0, const char * name = 0 )

Constructs a splitter with orientation o with the parent and name arguments being passed on to the QFrame constructor.

QSplitter::~QSplitter ()

Destroys the splitter and any children.

int QSplitter::adjustPos ( int p, int id ) [protected]

Returns the closest legal position to p of the splitter with id id.

See also idAfter().

void QSplitter::childEvent ( QChildEvent * c ) [virtual protected]

Tells the splitter that a child widget has been inserted or removed. The event is passed in c.

Reimplemented from QObject.

void QSplitter::drawSplitter ( QPainter * p, QCOORD x, QCOORD y, QCOORD w, QCOORD h ) [virtual protected]

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

Draws the splitter handle in the rectangle described by x, y, w, h using painter p.

See also QStyle::drawPrimitive().

void QSplitter::getRange ( int id, int * min, int * max ) [protected]

Returns the valid range of the splitter with id id in *min and *max.

See also idAfter().

int QSplitter::idAfter ( QWidget * w ) const [protected]

Returns the id of the splitter to the right of or below the widget w, or 0 if there is no such splitter (i.e. it is either not in this QSplitter or it is at the end).

void QSplitter::moveSplitter ( QCOORD p, int id ) [protected]

Moves the left/top edge of the splitter handle with id id as close as possible to position p, which is the distance from the left (or top) edge of the widget.

For Arabic and Hebrew the layout is reversed, and using this function to set the position of the splitter might lead to unexpected results, since in Arabic and Hebrew the position of splitter one is to the left of the position of splitter zero.

See also idAfter().

void QSplitter::moveToFirst ( QWidget * w )

Moves widget w to the leftmost/top position.

Example: splitter/splitter.cpp.

void QSplitter::moveToLast ( QWidget * w )

Moves widget w to the rightmost/bottom position.

bool QSplitter::opaqueResize () const

Returns TRUE if opaque resize is on; otherwise returns FALSE.

See also setOpaqueResize().

Orientation QSplitter::orientation () const

Returns the orientation of the splitter. See the "orientation" property for details.

void QSplitter::refresh ()

Updates the splitter's state. You should not need to call this function.

void QSplitter::setOpaqueResize ( bool on = TRUE ) [virtual]

If on is TRUE then opaque resizing is turned on; otherwise opaque resizing is turned off. Opaque resizing is initially turned off.

See also opaqueResize().

Examples: mainlyQt/editor.cpp and splitter/splitter.cpp.

void QSplitter::setOrientation ( Orientation ) [virtual]

Sets the orientation of the splitter. See the "orientation" property for details.

void QSplitter::setResizeMode ( QWidget * w, ResizeMode mode ) [virtual]

Sets resize mode of w to mode.

See also ResizeMode.

Examples: fileiconview/mainwindow.cpp, listviews/listviews.cpp, network/ftpclient/ftpmainwindow.cpp and splitter/splitter.cpp.

void QSplitter::setRubberband ( int p ) [virtual protected]

Shows a rubber band at position p. If p is negative, the rubber band is removed.

void QSplitter::setSizes ( QValueList<int> list )

Sets the size parameters to the values given in list. If the splitter is horizontal, the values set the sizes from left to right. If it is vertical, the sizes are applied from top to bottom. Extra values in list are ignored.

If list contains too few values, the result is undefined but the program will still be well-behaved.

See also sizes().

QValueList<int> QSplitter::sizes () const

Returns a list of the size parameters of all the widgets in this splitter.

Giving the values to another splitter's setSizes() function will produce a splitter with the same layout as this one.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<int> list = mySplitter.sizes();
    QValueList<int>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also setSizes().

Property Documentation

Orientation orientation

This property holds the orientation of the splitter.

By default the orientation is horizontal (the widgets are side by side). The possible orientations are Qt:Vertical and Qt::Horizontal (the default).

Set this property's value with setOrientation() and get this property's value with orientation().

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


qsplitter.h Include File

qsplitter.h

This is the verbatim text of the qsplitter.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qsplitter.h   3.0.5   edited Oct 12 2001 $
**
** Defintion of  QSplitter class
**
**  Created:  980105
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QSPLITTER_H
#define QSPLITTER_H

#ifndef QT_H
#include "qframe.h"
#include "qvaluelist.h"
#endif // QT_H

#ifndef QT_NO_SPLITTER

class QSplitterHandle;
class QSplitterData;
class QSplitterLayoutStruct;

class Q_EXPORT QSplitter : public QFrame
{
    Q_OBJECT
    Q_PROPERTY( Orientation orientation READ orientation WRITE setOrientation )

public:
    enum ResizeMode { Stretch, KeepSize, FollowSizeHint };

    QSplitter( QWidget* parent=0, const char* name=0 );
    QSplitter( Orientation, QWidget* parent=0, const char* name=0 );
    ~QSplitter();

    virtual void setOrientation( Orientation );
    Orientation orientation() const { return orient; }

    virtual void setResizeMode( QWidget *w, ResizeMode );
    virtual void setOpaqueResize( bool = TRUE );
    bool opaqueResize() const;

    void moveToFirst( QWidget * );
    void moveToLast( QWidget * );

    void refresh() { recalc( TRUE ); }
    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    QValueList<int> sizes() const;
    void setSizes( QValueList<int> );

protected:
    void childEvent( QChildEvent * );

    bool event( QEvent * );
    void resizeEvent( QResizeEvent * );

    int idAfter( QWidget* ) const;

    void moveSplitter( QCOORD pos, int id );
    virtual void drawSplitter( QPainter*, QCOORD x, QCOORD y,
                   QCOORD w, QCOORD h );
    void styleChange( QStyle& );
    int adjustPos( int , int );
    virtual void setRubberband( int );
    void getRange( int id, int*, int* );

private:
    void init();
    void recalc( bool update = FALSE );
    void doResize();
    void storeSizes();
    void processChildEvents();
    QSplitterLayoutStruct *addWidget( QWidget*, bool first = FALSE );
    void recalcId();
    void moveBefore( int pos, int id, bool upLeft );
    void moveAfter( int pos, int id, bool upLeft );
    void setG( QWidget *w, int p, int s, bool isSplitter = FALSE );

    QCOORD pick( const QPoint &p ) const
    { return orient == Horizontal ? p.x() : p.y(); }
    QCOORD pick( const QSize &s ) const
    { return orient == Horizontal ? s.width() : s.height(); }

    QCOORD trans( const QPoint &p ) const
    { return orient == Vertical ? p.x() : p.y(); }
    QCOORD trans( const QSize &s ) const
    { return orient == Vertical ? s.width() : s.height(); }

    QSplitterData *data;

    Orientation orient;
    friend class QSplitterHandle;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSplitter( const QSplitter & );
    QSplitter& operator=( const QSplitter & );
#endif
};

#endif // QT_NO_SPLITTER

#endif // QSPLITTER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSplitter Member List

Complete Member List for QSplitter

This is the complete list of member functions for QSplitter, including inherited members.

  • QSplitter()
  • ~QSplitter()
  • acceptDrops()
  • adjustPos()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawSplitter()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getRange()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • idAfter()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • moveSplitter()
  • moveToFirst()
  • moveToLast()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • opaqueResize()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • refresh()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOpaqueResize()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeMode()
  • setRubberband()
  • setSizeIncrement()
  • setSizePolicy()
  • setSizes()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sizes()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QSql类

QSql类参考
[sql模块]

QSql类是一个Qt SQL的全局标示符命名空间。 详情请见……

#include <qsql.h>

所有成员函数列表。

公有成员

  • QSql ()
  • enum Op { None = -1, Insert = 0, Update = 1, Delete = 2 }
  • enum Location { BeforeFirst = -1, AfterLast = -2 }
  • enum Confirm { Cancel = -1, No = 0, Yes = 1 }

详细描述

QSql类是一个Qt SQL的全局标示符命名空间。

通常情况下，你可以忽视它。许多Qt SQL类继承它，所以Qt SQL命名空间中的所有标示符都是可见的，而没有受到任何限制。

也可以参考数据库类。

成员类型文档

QSql::Confirm

此枚举类型描述编辑标准。

目前定义的值有：

  • QSql::Yes
  • QSql::No
  • QSql::Cancel

QSql::Location

此枚举类型描述SQL导航位置。

目前定义的值有：

  • QSql::BeforeFirst
  • QSql::AfterLast

QSql::Op

此枚举类型描述编辑操作。

目前定义的值有：

  • QSql::None
  • QSql::Insert
  • QSql::Update
  • QSql::Delete

成员函数文档

QSql::QSql ()

构建一个Qt SQL命名空间类。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


qsql.h包含文件

qsql.h

这里是qsql.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
**
** Definition of QSql class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQL_H
#define QSQL_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QM_EXPORT_SQL QSql
{
public:
    QSql() {}
    enum Op {
    None = -1,
    Insert = 0,
    Update = 1,
    Delete = 2
    };

    enum Location {
    BeforeFirst = -1,
    AfterLast = -2
    };

    enum Confirm {
    Cancel = -1,
    No = 0,
    Yes = 1
    };

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSql( const QSql & );
    QSql &operator=( const QSql & );
#endif

};

#endif
#endif

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


QSql成员列表

完整的QSql成员列表

这里是QSql成员函数的完整列表，包括继承的成员。

  • QSql()

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


QSqlCursor Class

QSqlCursor Class Reference
[sql module]

The QSqlCursor class provides browsing and editing of SQL tables and views. More...

#include <qsqlcursor.h>

Inherits QSqlRecord and QSqlQuery.

List of all member functions.

Public Members

  • QSqlCursor ( const QString & name = QString::null, bool autopopulate = TRUE, QSqlDatabase * db = 0 )
  • QSqlCursor ( const QSqlCursor & other )
  • QSqlCursor & operator= ( const QSqlCursor & other )
  • ~QSqlCursor ()
  • enum Mode { ReadOnly = 0, Insert = 1, Update = 2, Delete = 4, Writable = 7 }
  • virtual QSqlIndex primaryIndex ( bool setFromCursor = TRUE ) const
  • virtual QSqlIndex index ( const QStringList & fieldNames ) const
  • QSqlIndex index ( const QString & fieldName ) const
  • QSqlIndex index ( const char * fieldName ) const
  • virtual void setPrimaryIndex ( const QSqlIndex & idx )
  • virtual void append ( const QSqlFieldInfo & fieldInfo )
  • virtual void insert ( int pos, const QSqlFieldInfo & fieldInfo )
  • virtual void remove ( int pos )
  • virtual void clear ()
  • virtual void setGenerated ( const QString & name, bool generated )
  • virtual void setGenerated ( int i, bool generated )
  • virtual QSqlRecord * editBuffer ( bool copy = FALSE )
  • virtual QSqlRecord * primeInsert ()
  • virtual QSqlRecord * primeUpdate ()
  • virtual QSqlRecord * primeDelete ()
  • virtual int insert ( bool invalidate = TRUE )
  • virtual int update ( bool invalidate = TRUE )
  • virtual int del ( bool invalidate = TRUE )
  • virtual void setMode ( int mode )
  • int mode () const
  • virtual void setCalculated ( const QString & name, bool calculated )
  • bool isCalculated ( const QString & name ) const
  • virtual void setTrimmed ( const QString & name, bool trim )
  • bool isTrimmed ( const QString & name ) const
  • bool isReadOnly () const
  • bool canInsert () const
  • bool canUpdate () const
  • bool canDelete () const
  • bool select ()
  • bool select ( const QSqlIndex & sort )
  • bool select ( const QSqlIndex & filter, const QSqlIndex & sort )
  • virtual bool select ( const QString & filter, const QSqlIndex & sort = QSqlIndex ( ) )
  • virtual void setSort ( const QSqlIndex & sort )
  • QSqlIndex sort () const
  • virtual void setFilter ( const QString & filter )
  • QString filter () const
  • virtual void setName ( const QString & name, bool autopopulate = TRUE )
  • QString name () const

Protected Members

  • virtual QVariant calculateField ( const QString & name )
  • virtual int update ( const QString & filter, bool invalidate = TRUE )
  • virtual int del ( const QString & filter, bool invalidate = TRUE )
  • virtual QString toString ( const QString & prefix, QSqlField * field, const QString & fieldSep ) const
  • virtual QString toString ( QSqlRecord * rec, const QString & prefix, const QString & fieldSep, const QString & sep ) const
  • virtual QString toString ( const QSqlIndex & i, QSqlRecord * rec, const QString & prefix, const QString & fieldSep, const QString & sep ) const

Detailed Description

The QSqlCursor class provides browsing and editing of SQL tables and views.

A QSqlCursor is a database record (see QSqlRecord) that corresponds to a table or view within an SQL database (see QSqlDatabase). There are two buffers in a cursor, one used for browsing and one used for editing records. Each buffer contains a list of fields which correspond to the fields in the table or view.

When positioned on a valid record, the browse buffer contains the values of the current record's fields from the database. The edit buffer is separate, and is used for editing existing records and inserting new records.

For browsing data, a cursor must first select() data from the database. After a successful select() the cursor is active (isActive() returns TRUE), but is initially not positioned on a valid record (isValid() returns FALSE). To position the cursor on a valid record, use one of the navigation functions, next(), prev(), first(), last(), or seek(). Once positioned on a valid record, data can be retrieved from the browse buffer using value(). If a navigation function is not successful, it returns FALSE, the cursor will no longer be positioned on a valid record and the values returned by value() are undefined.

For example:

            QSqlCursor cur( "staff" ); // Specify the table/view name
            cur.select(); // We'll retrieve every record
            while ( cur.next() ) {
                qDebug( cur.value( "id" ).toString() + ": " +
                        cur.value( "surname" ).toString() + " " +
                        cur.value( "salary" ).toString() );
            }

In the above example, a cursor is created specifying a table or view name in the database. Then, select() is called, which can be optionally parameterised to filter and order the records retrieved. Each record in the cursor is retrieved using next(). When next() returns FALSE, there are no more records to process, and the loop terminates.

For editing records (rows of data), a cursor contains a separate edit buffer which is independent of the fields used when browsing. The functions insert(), update() and del() operate on the edit buffer. This allows the cursor to be repositioned to other records while simultaneously maintaining a separate buffer for edits. You can get a pointer to the edit buffer using editBuffer(). The primeInsert(), primeUpdate() and primeDelete() functions also return a pointer to the edit buffer and prepare it for insert, update and delete respectively. Edit operations only affect a single row at a time. Note that update() and del() require that the table or view contain a primaryIndex() to ensure that edit operations affect a unique record within the database.

For example:

            QSqlCursor cur( "prices" );
            cur.select( "id=202" );
            if ( cur.next() ) {
                QSqlRecord *buffer = cur.primeUpdate();
                double price = buffer->value( "price" ).toDouble();
                double newprice = price * 1.05;
                buffer->setValue( "price", newprice );
                cur.update();
            }

To edit an existing database record, first move to the record you wish to update. Call primeUpdate() to get the pointer to the cursor's edit buffer. Then use this pointer to modify the values in the edit buffer. Finally, call update() to save the changes to the database. The values in the edit buffer will be used to locate the appropriate record when updating the database (see primaryIndex()).

Similarly, when deleting an existing database record, first move to the record you wish to delete. Then, call primeDelete() to get the pointer to the edit buffer. Finally, call del() to delete the record from the database. Again, the values in the edit buffer will be used to locate and delete the appropriate record.

To insert a new record, call primeInsert() to get the pointer to the edit buffer. Use this pointer to populate the edit buffer with new values and then insert() the record into the database.

After calling insert(), update() or del(), the cursor is no longer positioned on a valid record and can no longer be navigated (isValid() return FALSE). The reason for this is that any changes made to the database will not be visible until select() is called to refresh the cursor. You can change this behavior by passing FALSE to insert(), update() or del() which will prevent the cursor from becoming invalid. These edits will then not be visible when navigating the cursor until select() is called.

QSqlCursor contains virtual methods which allow editing behavior to be customized by subclasses. This allows custom cursors to be created which encapsulate the editing behavior of a database table for an entire application. For example, a cursor can be customized to always auto-number primary index fields, or provide fields with suitable default values, when inserting new records.

Note that QSqlCursor does not inherit from QObject. This means that you are responsible for destroying instances of this class yourself. However if you create a QSqlCursor and use it in a QDataTable, QDataBrowser or a QDataView these classes will usually take ownership of the cursor and destroy it when they don't need it anymore. The documentation for QDataTable, QDataBrowser and QDataView explicitly states which calls take ownership of the cursor.

See also Database Classes.

Member Type Documentation

QSqlCursor::Mode

This enum type describes how QSqlCursor operates on records in the database.

The currently defined values are:

  • QSqlCursor::ReadOnly - the cursor can only SELECT records from the database.
  • QSqlCursor::Insert - the cursor can INSERT records into the database.
  • QSqlCursor::Update - the cursor can UPDATE records in the database.
  • QSqlCursor::Delete - the cursor can DELETE records from the database.
  • QSqlCursor::Writable - the cursor can INSERT, UPDATE and DELETE records in the database.

Member Function Documentation

QSqlCursor::QSqlCursor ( const QString & name = QString::null, bool autopopulate = TRUE, QSqlDatabase * db = 0 )

Constructs a cursor on database db using table or view name.

If autopopulate is TRUE (the default), the name of the cursor must correspond to an existing table or view name in the database so that field information can be automatically created. If the table or view does not exist, the cursor will not be functional.

The cursor is created with an initial mode of QSqlCursor::Writable (meaning that records can be inserted, updated or deleted using the cursor). If the cursor does not have a unique primary index, update and deletes cannot be performed.

Note that autopopulate refers to populating the cursor with meta-data, e.g. the names of the table's fields, not with retrieving data. The select() function is used to populate the cursor with data.

See also setName() and setMode().

QSqlCursor::QSqlCursor ( const QSqlCursor & other )

Constructs a copy of other.

QSqlCursor::~QSqlCursor ()

Destroys the object and frees any allocated resources.

void QSqlCursor::append ( const QSqlFieldInfo & fieldInfo ) [virtual]

Append a copy of field fieldInfo to the end of the cursor. Note that all references to the cursor edit buffer become invalidated.

QVariant QSqlCursor::calculateField ( const QString & name ) [virtual protected]

Protected virtual function which is called whenever a field needs to be calculated. If calculated fields are being used, derived classes must reimplement this function and return the appropriate value for field name. The default implementation returns an invalid QVariant.

See also setCalculated().

Examples: sql/overview/subclass3/main.cpp and sql/overview/subclass4/main.cpp.

bool QSqlCursor::canDelete () const

Returns TRUE if the cursor will perform deletes, FALSE otherwise.

See also setMode().

bool QSqlCursor::canInsert () const

Returns TRUE if the cursor will perform inserts, FALSE otherwise.

See also setMode().

bool QSqlCursor::canUpdate () const

Returns TRUE if the cursor will perform updates, FALSE otherwise.

See also setMode().

void QSqlCursor::clear () [virtual]

Removes all fields from the cursor. Note that all references to the cursor edit buffer become invalidated.

Reimplemented from QSqlRecord.

int QSqlCursor::del ( bool invalidate = TRUE ) [virtual]

Deletes a record from the database using the cursor's primary index and the contents of the cursor edit buffer. Returns the number of records which were deleted, or 0 if there was an error. For error information, use lastError().

Only records which meet the filter criteria specified by the cursor's primary index are deleted. If the cursor does not contain a primary index, no delete is performed and 0 is returned. If invalidate is TRUE (the default), the current cursor can no longer be navigated. A new select() call must be made before you can move to a valid record. For example:

            QSqlCursor cur( "prices" );
            cur.select( "id=999" );
            if ( cur.next() ) {
                cur.primeDelete();
                cur.del();
            }

In the above example, a cursor is created on the 'prices' table and positioned to the record to be deleted. First primeDelete() is called to populate the edit buffer with the current cursor values, e.g. with an id of 999, and then del() is called to actually delete the record from the database. Remember: all edit operations (insert(), update() and delete()) operate on the contents of the cursor edit buffer and not on the contents of the cursor itself.

See also primeDelete(), setMode() and lastError().

Example: sql/overview/del/main.cpp.

int QSqlCursor::del ( const QString & filter, bool invalidate = TRUE ) [virtual protected]

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

Deletes the current cursor record from the database using the filter filter. Only records which meet the filter criteria are deleted. Returns the number of records which were deleted. If invalidate is TRUE (the default), the current cursor can no longer be navigated. A new select() call must be made before you can move to a valid record. For error information, use lastError().

The filter is an SQL WHERE clause, e.g. id=500.

See also setMode() and lastError().

QSqlRecord * QSqlCursor::editBuffer ( bool copy = FALSE ) [virtual]

Returns a pointer to the current internal edit buffer. If copy is TRUE (the default is FALSE), the current cursor field values are first copied into the edit buffer. The edit buffer is valid as long as the cursor remains valid. The cursor retains ownership of the returned pointer, so it must not be deleted or modified.

See also primeInsert(), primeUpdate() and primeDelete().

QString QSqlCursor::filter () const

Returns the current filter, or an empty string if there is no current filter.

QSqlIndex QSqlCursor::index ( const QStringList & fieldNames ) const [virtual]

Returns an index composed of fieldNames, all in ASCending order. Note that all field names must exist in the cursor, otherwise an empty index is returned.

See also QSqlIndex.

Examples: sql/overview/extract/main.cpp, sql/overview/order1/main.cpp, sql/overview/order2/main.cpp and sql/overview/table3/main.cpp.

QSqlIndex QSqlCursor::index ( const QString & fieldName ) const

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

Returns an index based on fieldName.

QSqlIndex QSqlCursor::index ( const char * fieldName ) const

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

Returns an index based on fieldName.

void QSqlCursor::insert ( int pos, const QSqlFieldInfo & fieldInfo ) [virtual]

Insert a copy of fieldInfo at position pos. If a field already exists at pos, it is removed. Note that all references to the cursor edit buffer become invalidated.

Examples: sql/overview/insert/main.cpp and sql/overview/insert2/main.cpp.

int QSqlCursor::insert ( bool invalidate = TRUE ) [virtual]

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

Inserts the current contents of the cursor's edit record buffer into the database, if the cursor allows inserts. Returns the number of rows affected by the insert. For error information, use lastError().

If invalidate is TRUE (the default), the cursor will no longer be positioned on a valid record and can no longer be navigated. A new select() call must be made before navigating to a valid record.

            QSqlCursor cur( "prices" );
            QSqlRecord *buffer = cur.primeInsert();
            buffer->setValue( "id",    53981 );
            buffer->setValue( "name",  "Thingy" );
            buffer->setValue( "price", 105.75 );
            cur.insert();

In the above example, a cursor is created on the 'prices' table and a pointer to the insert buffer is aquired using primeInsert(). Each field's value is set to the desired value and then insert() is called to insert the data into the database. Remember: all edit operations (insert(), update() and delete()) operate on the contents of the cursor edit buffer and not on the contents of the cursor itself.

See also setMode() and lastError().

bool QSqlCursor::isCalculated ( const QString & name ) const

Returns TRUE if the field name is calculated, otherwise FALSE is returned. If the field name does not exist, FALSE is returned.

See also setCalculated().

bool QSqlCursor::isReadOnly () const

Returns TRUE if the cursor is read-only, FALSE otherwise. The default is FALSE. Read-only cursors cannot be edited using insert(), update() or del().

See also setMode().

bool QSqlCursor::isTrimmed ( const QString & name ) const

Returns TRUE if the field name is trimmed, otherwise FALSE is returned. If the field name does not exist, FALSE is returned.

When a trimmed field of type string or cstring is read from the database any trailing (right-most) spaces are removed.

See also setTrimmed().

int QSqlCursor::mode () const

Returns the current cursor mode.

See also setMode().

QString QSqlCursor::name () const

Returns the name of the cursor.

QSqlCursor & QSqlCursor::operator= ( const QSqlCursor & other )

Sets the cursor equal to other.

QSqlIndex QSqlCursor::primaryIndex ( bool setFromCursor = TRUE ) const [virtual]

Returns the primary index associated with the cursor as defined in the database, or an empty index if there is no primary index. If setFromCursor is TRUE (the default), the index fields are populated with the corresponding values in the cursor's current record.

QSqlRecord * QSqlCursor::primeDelete () [virtual]

'Primes' the field values of the edit buffer for delete and returns a pointer to the edit buffer. The default implementation copies the field values from the current cursor record into the edit buffer (therefore, this function is equivalent to calling editBuffer( TRUE ) ). The cursor retains ownership of the returned pointer, so it must not be deleted or modified.

See also editBuffer() and del().

Example: sql/overview/del/main.cpp.

QSqlRecord * QSqlCursor::primeInsert () [virtual]

'Primes' the field values of the edit buffer for insert and returns a pointer to the edit buffer. The default implementation clears all field values in the edit buffer. The cursor retains ownership of the returned pointer, so it must not be deleted or modified.

See also editBuffer() and insert().

Examples: sql/overview/insert/main.cpp, sql/overview/insert2/main.cpp, sql/overview/subclass5/main.cpp and sql/sqltable/main.cpp.

QSqlRecord * QSqlCursor::primeUpdate () [virtual]

'Primes' the field values of the edit buffer for update and returns a pointer to the edit buffer. The default implementation copies the field values from the current cursor record into the edit buffer (therefore, this function is equivalent to calling editBuffer( TRUE ) ). The cursor retains ownership of the returned pointer, so it must not be deleted or modified.

See also editBuffer() and update().

Examples: sql/overview/custom1/main.cpp, sql/overview/form1/main.cpp and sql/overview/update/main.cpp.

void QSqlCursor::remove ( int pos ) [virtual]

Removes the field at pos. If pos does not exist, nothing happens. Note that all references to the cursor edit buffer become invalidated.

Reimplemented from QSqlRecord.

bool QSqlCursor::select ( const QString & filter, const QSqlIndex & sort = QSqlIndex ( ) ) [virtual]

Selects all fields in the cursor from the database matching the filter criteria filter. The data is returned in the order specified by the index sort. Returns TRUE if the data was successfully selected, otherwise FALSE is returned.

The filter is a string containing an SQL WHERE clause but without the 'WHERE' keyword. The cursor is initially positioned at an invalid row after this function is called. To move to a valid row, use seek(), first(), last(), prev() or next().

Example:

  QSqlCursor cur( "Employee" ); // Use the Employee table or view
  cur.select( "deptno=10" ); // select all records in department 10
  while( cur.next() ) {
      ... // process data
  }
  ...
  // select records in other departments, ordered by department number
  cur.select( "deptno>10", cur.index( "deptno" ) );
  ...

The filter will apply to any subsequent select() calls that do not explicitly specify another filter. Similarly the sort will apply to any subsequent select() calls that do not explicitly specify another sort.

  QSqlCursor cur( "Employee" );
  cur.select( "deptno=10" ); // select all records in department 10
  while( cur.next() ) {
      ... // process data
  }
  ...
  cur.select(); // re-selects all records in department 10
  ...

Examples: sql/overview/del/main.cpp, sql/overview/extract/main.cpp, sql/overview/order1/main.cpp, sql/overview/order2/main.cpp, sql/overview/retrieve2/main.cpp, sql/overview/table3/main.cpp and sql/overview/update/main.cpp.

bool QSqlCursor::select ()

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

Selects all fields in the cursor from the database. The rows are returned in the order specified by the last call to setSort() or the last call to select() that specified a sort, whichever is the most recent. If there is no current sort, the order in which the rows are returned is undefined. The records are filtered according to the filter specified by the last call to setFilter() or the last call to select() that specified a filter, whichever is the most recent. If there is no current filter, all records are returned. The cursor is initially positioned at an invalid row. To move to a valid row, use seek(), first(), last(), prev() or next().

See also setSort() and setFilter().

bool QSqlCursor::select ( const QSqlIndex & sort )

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

Selects all fields in the cursor from the database. The data is returned in the order specified by the index sort. The records are filtered according to the filter specified by the last call to setFilter() or the last call to select() that specified a filter, whichever is the most recent. The cursor is initially positioned at an invalid row. To move to a valid row, use seek(), first(), last(), prev() or next().

bool QSqlCursor::select ( const QSqlIndex & filter, const QSqlIndex & sort )

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

Selects all fields in the cursor matching the filter index filter. The data is returned in the order specified by the index sort. The filter index works by constructing a WHERE clause using the names of the fields from the filter and their values from the current cursor record. The cursor is initially positioned at an invalid row. To move to a valid row, use seek(), first(), last(), prev() or next(). This function is useful, for example, for retrieving data based upon a table's primary index:

  QSqlCursor cur( "Employee" );
  QSqlIndex pk = cur.primaryIndex();
  cur.setValue( "id", 10 );
  cur.select( pk, pk ); // generates "SELECT ... FROM Employee WHERE id=10 ORDER BY id"
  ...

In this example the QSqlIndex, pk, is used for two different purposes. When used as the filter (first) argument, the field names it contains are used to construct the WHERE clause, each set to the current cursor value, WHERE id=10, in this case. When used as the sort (second) argument the field names it contains are used for the ORDER BY clause, ORDER BY id in this example.

void QSqlCursor::setCalculated ( const QString & name, bool calculated ) [virtual]

Sets field name to calculated. If the field name does not exist, nothing happens. The value of a calculated field is set by the calculateField() virtual function which you must reimplement otherwise the field value will become an invalid QVariant. Calculated fields do not appear in generated SQL statements sent to the database.

See also calculateField() and QSqlRecord::setGenerated().

void QSqlCursor::setFilter ( const QString & filter ) [virtual]

Sets the current filter to filter. Note that no new records are selected. To select new records, use select(). The filter will apply to any subsequent select() calls that do not explicitly specify a filter.

The filter is an SQL WHERE clause without the keyword 'WHERE', e.g. name='Dave'.

void QSqlCursor::setGenerated ( const QString & name, bool generated ) [virtual]

Sets the generated flag for the field name to generated. If the field does not exist, nothing happens. Only fields that have generated set to TRUE are included in the SQL that is generated.

See also isGenerated().

Reimplemented from QSqlRecord.

void QSqlCursor::setGenerated ( int i, bool generated ) [virtual]

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

Sets the generated flag for the field i to generated.

See also isGenerated().

Reimplemented from QSqlRecord.

void QSqlCursor::setMode ( int mode ) [virtual]

Sets the cursor mode to mode. This value can be an OR'ed combination of QSqlCursor::Mode values. The default mode for a cursor is QSqlCursor::Writable.

  QSqlCursor cur( "Employee" );
  cur.setMode( QSqlCursor::Writable ); // allow insert/update/delete
  ...
  cur.setMode( QSqlCursor::Insert | QSqlCursor::Update ); // allow inserts and updates only
  ...
  cur.setMode( QSqlCursor::ReadOnly ); // no inserts/updates/deletes allowed

void QSqlCursor::setName ( const QString & name, bool autopopulate = TRUE ) [virtual]

Sets the name of the cursor to name. If autopopulate is TRUE (the default), the name must correspond to a valid table or view name in the database. Also, note that all references to the cursor edit buffer become invalidated when fields are auto-populated. See the QSqlCursor constructor documentation for more information.

void QSqlCursor::setPrimaryIndex ( const QSqlIndex & idx ) [virtual]

Sets the primary index associated with the cursor to the index idx. Note that this index must contain a field or set of fields which identify a unique record within the underlying database table or view so that update() and del() will execute as expected.

See also update() and del().

void QSqlCursor::setSort ( const QSqlIndex & sort ) [virtual]

Sets the current sort to sort. Note that no new records are selected. To select new records, use select(). The sort will apply to any subsequent select() calls that do not explicitly specify a sort.

void QSqlCursor::setTrimmed ( const QString & name, bool trim ) [virtual]

Sets field name to trim. If the field name does not exist, nothing happens.

When a trimmed field of type string or cstring is read from the database any trailing (right-most) spaces are removed.

See QVariant.

See also isTrimmed().

QSqlIndex QSqlCursor::sort () const

Returns the current sort, or an empty index if there is no current sort.

QString QSqlCursor::toString ( QSqlRecord * rec, const QString & prefix, const QString & fieldSep, const QString & sep ) const [virtual protected]

Returns a formatted string composed of all the fields in rec. Each field is composed of the prefix (e.g. table or view name), ".", the field name, the fieldSep and the field value. If the prefix is empty then the field will begin with the field name. The fields are then joined together separated by sep. Fields where isGenerated() returns FALSE are not included. This function is useful for generating SQL statements.

QString QSqlCursor::toString ( const QString & prefix, QSqlField * field, const QString & fieldSep ) const [virtual protected]

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

Returns a formatted string composed of the prefix (e.g. table or view name), ".", the field name, the fieldSep and the field value. If the prefix is empty then the string will begin with the field name. This function is useful for generating SQL statements.

QString QSqlCursor::toString ( const QSqlIndex & i, QSqlRecord * rec, const QString & prefix, const QString & fieldSep, const QString & sep ) const [virtual protected]

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

Returns a formatted string composed of all the fields in the index i. Each field is composed of the prefix (e.g. table or view name), ".", the field name, the fieldSep and the field value. If the prefix is empty then the field will begin with the field name. The field values are taken from rec. The fields are then joined together separated by sep. Fields where isGenerated() returns FALSE are ignored. This function is useful for generating SQL statements.

int QSqlCursor::update ( bool invalidate = TRUE ) [virtual]

Updates the database with the current contents of the edit buffer. Returns the number of records which were updated, or 0 if there was an error. For error information, use lastError().

Only records which meet the filter criteria specified by the cursor's primary index are updated. If the cursor does not contain a primary index, no update is performed and 0 is returned.

If invalidate is TRUE (the default), the current cursor can no longer be navigated. A new select() call must be made before you can move to a valid record. For example:

            QSqlCursor cur( "prices" );
            cur.select( "id=202" );
            if ( cur.next() ) {
                QSqlRecord *buffer = cur.primeUpdate();
                double price = buffer->value( "price" ).toDouble();
                double newprice = price * 1.05;
                buffer->setValue( "price", newprice );
                cur.update();
            }

In the above example, a cursor is created on the 'prices' table and is positioned on the record to be update updated. A pointer is then aquired to the cursor's edit buffer using primeUpdate(). A new value is calculated and placed into the edit buffer with the setValue() call. Finally, an update() call is made on the cursor which uses the tables's primary index to update the record in the database with the contents of the cursor's edit buffer. Remember: all edit operations (insert(), update() and delete()) operate on the contents of the cursor edit buffer and not on the contents of the cursor itself.

Note that if the primary index does not uniquely distinguish records the database may be changed into an inconsistent state.

See also setMode() and lastError().

Example: sql/overview/update/main.cpp.

int QSqlCursor::update ( const QString & filter, bool invalidate = TRUE ) [virtual protected]

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

Updates the database with the current contents of the cursor edit buffer using the specified filter. Returns the number of records which were updated, or 0 if there was an error. For error information, use lastError().

Only records which meet the filter criteria are updated, otherwise all records in the table are updated.

If invalidate is TRUE (the default), the cursor can no longer be navigated. A new select() call must be made before you can move to a valid record.

See also primeUpdate(), setMode() and lastError().

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


qsqlcursor.h Include File

qsqlcursor.h

This is the verbatim text of the qsqlcursor.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlCursor class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLCURSOR_H
#define QSQLCURSOR_H

#ifndef QT_H
#include "qsqlrecord.h"
#include "qstringlist.h"
#include "qsqlquery.h"
#include "qsqlindex.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlDatabase;
class QSqlCursorPrivate;

class QM_EXPORT_SQL QSqlCursor : public QSqlRecord, public QSqlQuery
{
public:
    QSqlCursor( const QString & name = QString::null, bool autopopulate = TRUE, QSqlDatabase* db = 0 );
    QSqlCursor( const QSqlCursor & other );
    QSqlCursor& operator=( const QSqlCursor& other );
    ~QSqlCursor();

    enum Mode {
    ReadOnly = 0,
    Insert = 1,
    Update = 2,
    Delete = 4,
    Writable = 7
    };

    QVariant		value( int i ) const;
    QVariant		value( const QString& name ) const;
    virtual QSqlIndex	primaryIndex( bool prime = TRUE ) const;
    virtual QSqlIndex	index( const QStringList& fieldNames ) const;
    QSqlIndex		index( const QString& fieldName ) const;
    QSqlIndex		index( const char* fieldName ) const;
    virtual void	setPrimaryIndex( const QSqlIndex& idx );

    virtual void	append( const QSqlFieldInfo& fieldInfo );
    virtual void	insert( int pos, const QSqlFieldInfo& fieldInfo );
    void		remove( int pos );
    void		clear();
    void		setGenerated( const QString& name, bool generated );
    void		setGenerated( int i, bool generated );

    virtual QSqlRecord*	editBuffer( bool copy = FALSE );
    virtual QSqlRecord*	primeInsert();
    virtual QSqlRecord*	primeUpdate();
    virtual QSqlRecord*	primeDelete();
    virtual int		insert( bool invalidate = TRUE );
    virtual int		update( bool invalidate = TRUE );
    virtual int		del( bool invalidate = TRUE );

    virtual void	setMode( int flags );
    int			mode() const;
    virtual void	setCalculated( const QString& name, bool calculated );
    bool		isCalculated( const QString& name ) const;
    virtual void	setTrimmed( const QString& name, bool trim );
    bool		isTrimmed( const QString& name ) const;

    bool		isReadOnly() const;
    bool		canInsert() const;
    bool		canUpdate() const;
    bool		canDelete() const;

    bool		select();
    bool		select( const QSqlIndex& sort );
    bool		select( const QSqlIndex & filter, const QSqlIndex & sort );
    virtual bool	select( const QString & filter, const QSqlIndex & sort = QSqlIndex() );

    virtual void	setSort( const QSqlIndex& sort );
    QSqlIndex		sort() const;
    virtual void	setFilter( const QString& filter );
    QString		filter() const;
    virtual void	setName( const QString& name, bool autopopulate = TRUE );
    QString		name() const;
    QString		toString( const QString& prefix = QString::null,
                const QString& sep = "," ) const;

protected:
    void		afterSeek();
    bool		exec( const QString & sql );

    virtual QVariant	calculateField( const QString& name );
    virtual int		update( const QString & filter, bool invalidate = TRUE );
    virtual int		del( const QString & filter, bool invalidate = TRUE );

    virtual QString	toString( const QString& prefix, QSqlField* field, const QString& fieldSep ) const;
    virtual QString	toString( QSqlRecord* rec, const QString& prefix, const QString& fieldSep,
                const QString& sep ) const;
    virtual QString	toString( const QSqlIndex& i, QSqlRecord* rec, const QString& prefix,
                const QString& fieldSep, const QString& sep ) const;

private:
    void		sync();
    int			apply( const QString& q, bool invalidate );
    QSqlRecord&		operator=( const QSqlRecord & list );
    void 		append( const QSqlField& field );
    void 		insert( int pos, const QSqlField& field );

    QSqlCursorPrivate*	d;
};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlCursor Member List

Complete Member List for QSqlCursor

This is the complete list of member functions for QSqlCursor, including inherited members.

  • QSqlCursor()
  • ~QSqlCursor()
  • afterSeek()
  • append()
  • at()
  • beforeSeek()
  • calculateField()
  • canDelete()
  • canInsert()
  • canUpdate()
  • clear()
  • clearValues()
  • contains()
  • count()
  • del()
  • driver()
  • editBuffer()
  • exec()
  • field()
  • fieldName()
  • filter()
  • first()
  • index()
  • insert()
  • isActive()
  • isCalculated()
  • isEmpty()
  • isGenerated()
  • isNull()
  • isReadOnly()
  • isSelect()
  • isTrimmed()
  • isValid()
  • last()
  • lastError()
  • lastQuery()
  • mode()
  • name()
  • next()
  • numRowsAffected()
  • operator=()
  • position()
  • prev()
  • primaryIndex()
  • primeDelete()
  • primeInsert()
  • primeUpdate()
  • remove()
  • result()
  • seek()
  • select()
  • setCalculated()
  • setFilter()
  • setGenerated()
  • setMode()
  • setName()
  • setNull()
  • setPrimaryIndex()
  • setSort()
  • setTrimmed()
  • setValue()
  • size()
  • sort()
  • toString()
  • toStringList()
  • update()
  • value()


QSqlDatabase Class

QSqlDatabase Class Reference
[sql module]

The QSqlDatabase class is used to create SQL database connections and provide transaction handling. More...

#include <qsqldatabase.h>

Inherits QObject.

List of all member functions.

Public Members

  • ~QSqlDatabase ()
  • bool open ()
  • bool open ( const QString & user, const QString & password )
  • void close ()
  • bool isOpen () const
  • bool isOpenError () const
  • QStringList tables () const
  • QSqlIndex primaryIndex ( const QString & tablename ) const
  • QSqlRecord record ( const QString & tablename ) const
  • QSqlRecord record ( const QSqlQuery & query ) const
  • QSqlRecordInfo recordInfo ( const QString & tablename ) const
  • QSqlRecordInfo recordInfo ( const QSqlQuery & query ) const
  • QSqlQuery exec ( const QString & query = QString::null ) const
  • QSqlError lastError () const
  • bool transaction ()
  • bool commit ()
  • bool rollback ()
  • virtual void setDatabaseName ( const QString & name )
  • virtual void setUserName ( const QString & name )
  • virtual void setPassword ( const QString & password )
  • virtual void setHostName ( const QString & host )
  • virtual void setPort ( int p )
  • QString databaseName () const
  • QString userName () const
  • QString password () const
  • QString hostName () const
  • QString driverName () const
  • int port () const
  • QSqlDriver * driver () const

Static Public Members

  • QSqlDatabase * addDatabase ( const QString & type, const QString & connectionName = defaultConnection )
  • QSqlDatabase * database ( const QString & connectionName = defaultConnection, bool open = TRUE )
  • void removeDatabase ( const QString & connectionName )
  • bool contains ( const QString & connectionName = defaultConnection )
  • QStringList drivers ()

Properties

  • QString databaseName - the name of the database. Note that the database name is the TNS Service Name for the QOCI8 (Oracle) driver, and the Data Source Name for the QODBC3 driver
  • QString hostName - the host name where the database resides
  • QString password - the password used to connect to the database
  • int port - the port used to connect to the database
  • QString userName - the user name connected to the database

Protected Members

  • QSqlDatabase ( const QString & driver, const QString & name, QObject * parent = 0, const char * objname = 0 )

Detailed Description

The QSqlDatabase class is used to create SQL database connections and provide transaction handling.

This class is used to create connections to SQL databases. It also provides transaction handling functions for those database drivers that support transactions.

The QSqlDatabase class itself provides an abstract interface for accessing many types of database backend. Database-specific drivers are used internally to actually access and manipulate data, (see QSqlDriver). Result set objects provide the interface for executing and manipulating SQL queries (see QSqlQuery).

See also Database Classes.

Member Function Documentation

QSqlDatabase::QSqlDatabase ( const QString & driver, const QString & name, QObject * parent = 0, const char * objname = 0 ) [protected]

Creates a QSqlDatabase connection named name that uses the driver referred to by driver, with the parent parent and the object name objname. If the driver is not recognized, the database connection will have no functionality.

The currently available drivers are:

  • QODBC3 - ODBC (Open Database Connectivity) Driver
  • QOCI8 - Oracle Call Interface Driver
  • QPSQL7 - PostgreSQL v6.x and v7.x Driver
  • QTDS7 - Sybase Adaptive Server and Microsoft SQL Server Driver
  • QMYSQL3 - MySQL Driver

Note that additional 3rd party drivers can be loaded dynamically.

QSqlDatabase::~QSqlDatabase ()

Destroys the object and frees any allocated resources.

QSqlDatabase * QSqlDatabase::addDatabase ( const QString & type, const QString & connectionName = defaultConnection ) [static]

Adds a database to the list of database connections using the driver type and the connection name connectionName.

The database connection is referred to by connectionName. A pointer to the newly added database connection is returned. This pointer is owned by QSqlDatabase and will be deleted on program exit or when removeDatabase() is called. If connectionName is not specified, the newly added database connection becomes the default database connection for the application, and subsequent calls to database() (without a database name parameter) will return a pointer to it.

See also database() and removeDatabase().

Examples: sql/overview/connect1/main.cpp, sql/overview/create_connections/main.cpp and sql/sqltable/main.cpp.

void QSqlDatabase::close ()

Closes the database connection, freeing any resources acquired.

bool QSqlDatabase::commit ()

Commits a transaction to the database if the driver supports transactions. Returns TRUE if the operation succeeded, FALSE otherwise.

See also QSqlDriver::hasFeature() and rollback().

bool QSqlDatabase::contains ( const QString & connectionName = defaultConnection ) [static]

Returns TRUE if the list of database connections contains connectionName, otherwise returns FALSE.

QSqlDatabase * QSqlDatabase::database ( const QString & connectionName = defaultConnection, bool open = TRUE ) [static]

Returns a pointer to the database connection named connectionName. The database connection must have been previously added with database(). If open is TRUE (the default) and the database connection is not already open it is opened now. If no connectionName is specified the default connection is used. If connectionName does not exist in the list of databases, 0 is returned. The pointer returned is owned by QSqlDatabase and should not be deleted.

Examples: sql/overview/basicbrowsing/main.cpp and sql/overview/create_connections/main.cpp.

QString QSqlDatabase::databaseName () const

Returns the name of the database. Note that the database name is the TNS Service Name for the QOCI8 (Oracle) driver, and the Data Source Name for the QODBC3 driver. See the "databaseName" property for details.

QSqlDriver * QSqlDatabase::driver () const

Returns a pointer to the database driver used to access the database connection.

QString QSqlDatabase::driverName () const

Returns the name of the driver used by the database connection.

QStringList QSqlDatabase::drivers () [static]

Returns a list of all available database drivers.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDatabase.drivers();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

QSqlQuery QSqlDatabase::exec ( const QString & query = QString::null ) const

Executes an SQL statement (e.g. an INSERT, UPDATE or DELETE statement) on the database, and returns a QSqlQuery object. Use lastError() to retrieve error information. If query is QString::null, an empty, invalid query is returned and lastError() is not affected.

See also QSqlQuery and lastError().

QString QSqlDatabase::hostName () const

Returns the host name where the database resides. See the "hostName" property for details.

bool QSqlDatabase::isOpen () const

Returns TRUE if the database connection is currently open, otherwise returns FALSE.

bool QSqlDatabase::isOpenError () const

Returns TRUE if there was an error opening the database connection, otherwise returns FALSE. Error information can be retrieved using the lastError() function.

QSqlError QSqlDatabase::lastError () const

Returns information about the last error that occurred on the database. See QSqlError for more information.

Examples: sql/overview/create_connections/main.cpp and sql/sqltable/main.cpp.

bool QSqlDatabase::open ()

Opens the database connection using the current connection values. Returns TRUE on success, and FALSE if there was an error. Error information can be retrieved using the lastError() function.

See also lastError().

Examples: sql/overview/connect1/main.cpp, sql/overview/create_connections/main.cpp and sql/sqltable/main.cpp.

bool QSqlDatabase::open ( const QString & user, const QString & password )

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

Opens the database connection using user name and password. Returns TRUE on success, and FALSE if there was an error. Error information can be retrieved using the lastError() function.

See also lastError().

QString QSqlDatabase::password () const

Returns the password used to connect to the database. See the "password" property for details.

int QSqlDatabase::port () const

Returns the port used to connect to the database. See the "port" property for details.

QSqlIndex QSqlDatabase::primaryIndex ( const QString & tablename ) const

Returns the primary index for table tablename. If no primary index exists an empty QSqlIndex will be returned.

QSqlRecord QSqlDatabase::record ( const QString & tablename ) const

Returns a QSqlRecord populated with the names of all the fields in the table (or view) named tablename. The order in which the fields are returned is undefined. If no such table (or view) exists, an empty record is returned.

See also recordInfo().

QSqlRecord QSqlDatabase::record ( const QSqlQuery & query ) const

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

Returns a QSqlRecord populated with the names of all the fields used in the SQL query. If the query is a "SELECT *" the order in which fields are returned is undefined.

See also recordInfo().

QSqlRecordInfo QSqlDatabase::recordInfo ( const QString & tablename ) const

Returns a QSqlRecordInfo populated with meta-data about the table (or view) tablename. If no such table (or view) exists, an empty record is returned.

See also QSqlRecordInfo, QSqlFieldInfo and record().

QSqlRecordInfo QSqlDatabase::recordInfo ( const QSqlQuery & query ) const

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

Returns a QSqlRecordInfo object with meta data for the QSqlQuery query. Note that this overloaded function may return not as much information as the recordInfo function which takes the name of a table as parameter.

See also QSqlRecordInfo, QSqlFieldInfo and record().

void QSqlDatabase::removeDatabase ( const QString & connectionName ) [static]

Removes the database connection connectionName from the list of database connections. Note that there should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.

bool QSqlDatabase::rollback ()

Rolls a transaction back on the database if the driver supports transactions. Returns TRUE if the operation succeeded, FALSE otherwise.

See also QSqlDriver::hasFeature(), commit() and transaction().

void QSqlDatabase::setDatabaseName ( const QString & name ) [virtual]

Sets the name of the database. Note that the database name is the TNS Service Name for the QOCI8 (Oracle) driver, and the Data Source Name for the QODBC3 driver to name. See the "databaseName" property for details.

void QSqlDatabase::setHostName ( const QString & host ) [virtual]

Sets the host name where the database resides to host. See the "hostName" property for details.

void QSqlDatabase::setPassword ( const QString & password ) [virtual]

Sets the password used to connect to the database to password. See the "password" property for details.

void QSqlDatabase::setPort ( int p ) [virtual]

Sets the port used to connect to the database to p. See the "port" property for details.

void QSqlDatabase::setUserName ( const QString & name ) [virtual]

Sets the user name connected to the database to name. See the "userName" property for details.

QStringList QSqlDatabase::tables () const

Returns a list of tables in the database.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myDatabase.tables();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

bool QSqlDatabase::transaction ()

Begins a transaction on the database if the driver supports transactions. Returns TRUE if the operation succeeded, FALSE otherwise.

See also QSqlDriver::hasFeature(), commit() and rollback().

QString QSqlDatabase::userName () const

Returns the user name connected to the database. See the "userName" property for details.

Property Documentation

QString databaseName

This property holds the name of the database. Note that the database name is the TNS Service Name for the QOCI8 (Oracle) driver, and the Data Source Name for the QODBC3 driver.

There is no default value.

Set this property's value with setDatabaseName() and get this property's value with databaseName().

QString hostName

This property holds the host name where the database resides.

There is no default value.

Set this property's value with setHostName() and get this property's value with hostName().

QString password

This property holds the password used to connect to the database.

There is no default value.

Set this property's value with setPassword() and get this property's value with password().

int port

This property holds the port used to connect to the database.

There is no default value.

Set this property's value with setPort() and get this property's value with port().

QString userName

This property holds the user name connected to the database.

There is no default value.

Set this property's value with setUserName() and get this property's value with userName().

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


qsqldatabase.h Include File

qsqldatabase.h

This is the verbatim text of the qsqldatabase.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlDatabase class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLDATABASE_H
#define QSQLDATABASE_H

#ifndef QT_H
#include "qobject.h"
#include "qstring.h"
#include "qsqlquery.h"
#include "qstringlist.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlError;
class QSqlDriver;
class QSqlIndex;
class QSqlRecord;
class QSqlRecordInfo;
class QSqlDatabasePrivate;

class QM_EXPORT_SQL QSqlDriverCreatorBase
{
public:
    virtual QSqlDriver* createObject() = 0;
};

template <class type>
class QM_EXPORT_SQL QSqlDriverCreator: public QSqlDriverCreatorBase
{
public:
    QSqlDriver* createObject() { return new type; }
};

class QM_EXPORT_SQL QSqlDatabase : public QObject
{
    Q_OBJECT
    Q_PROPERTY( QString databaseName  READ databaseName WRITE setDatabaseName )
    Q_PROPERTY( QString userName  READ userName WRITE setUserName )
    Q_PROPERTY( QString password  READ password WRITE setPassword )
    Q_PROPERTY( QString hostName  READ hostName WRITE setHostName )
    Q_PROPERTY( int port READ port WRITE setPort )

public:
    ~QSqlDatabase();

    bool		open();
    bool		open( const QString& user, const QString& password );
    void		close();
    bool		isOpen() const;
    bool		isOpenError() const;
    QStringList		tables() const;
    QSqlIndex		primaryIndex( const QString& tablename ) const;
    QSqlRecord		record( const QString& tablename ) const;
    QSqlRecord		record( const QSqlQuery& query ) const;
    QSqlRecordInfo	recordInfo( const QString& tablename ) const;
    QSqlRecordInfo	recordInfo( const QSqlQuery& query ) const;
    QSqlQuery		exec( const QString& query = QString::null ) const;
    QSqlError		lastError() const;

    bool		transaction();
    bool		commit();
    bool		rollback();

    virtual void	setDatabaseName( const QString& name );
    virtual void	setUserName( const QString& name );
    virtual void	setPassword( const QString& password );
    virtual void	setHostName( const QString& host );
    virtual void	setPort( int p );
    QString		databaseName() const;
    QString		userName() const;
    QString		password() const;
    QString		hostName() const;
    QString		driverName() const;
    int         	port() const;

    QSqlDriver*		driver() const;

    // MOC_SKIP_BEGIN
    QT_STATIC_CONST char * const defaultConnection;
    // MOC_SKIP_END

    static QSqlDatabase* addDatabase( const QString& type, const QString& connectionName = defaultConnection );
    static QSqlDatabase* database( const QString& connectionName = defaultConnection, bool open = TRUE );
    static void          removeDatabase( const QString& connectionName );
    static bool          contains( const QString& connectionName = defaultConnection );
    static QStringList   drivers();
    static void          registerSqlDriver( const QString& name, const QSqlDriverCreatorBase* dcb );

protected:
    QSqlDatabase( const QString& type, const QString& name, QObject * parent=0, const char * objname=0 );
private:
    void	init( const QString& type, const QString& name );
    QSqlDatabasePrivate* d;
};

#endif // QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlDatabase Member List

Complete Member List for QSqlDatabase

This is the complete list of member functions for QSqlDatabase, including inherited members.

  • QSqlDatabase()
  • ~QSqlDatabase()
  • addDatabase()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • close()
  • commit()
  • connect()
  • connectNotify()
  • contains()
  • customEvent()
  • database()
  • databaseName()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • driver()
  • driverName()
  • drivers()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • exec()
  • highPriority()
  • hostName()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isOpen()
  • isOpenError()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • lastError()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • open()
  • parent()
  • password()
  • port()
  • primaryIndex()
  • property()
  • queryList()
  • record()
  • recordInfo()
  • removeChild()
  • removeDatabase()
  • removeEventFilter()
  • rollback()
  • sender()
  • setDatabaseName()
  • setHostName()
  • setName()
  • setPassword()
  • setPort()
  • setProperty()
  • setUserName()
  • signalsBlocked()
  • startTimer()
  • tables()
  • timerEvent()
  • tr()
  • trUtf8()
  • transaction()
  • userName()


QSqlDriver Class

QSqlDriver Class Reference
[sql module]

The QSqlDriver class is an abstract base class for accessing SQL databases. More...

#include <qsqldriver.h>

Inherits QObject.

List of all member functions.

Public Members

  • enum DriverFeature { Transactions, QuerySize, BLOB }
  • QSqlDriver ( QObject * parent = 0, const char * name = 0 )
  • ~QSqlDriver ()
  • bool isOpen () const
  • bool isOpenError () const
  • virtual bool beginTransaction ()
  • virtual bool commitTransaction ()
  • virtual bool rollbackTransaction ()
  • virtual QStringList tables ( const QString & user ) const
  • virtual QSqlIndex primaryIndex ( const QString & tableName ) const
  • virtual QSqlRecord record ( const QString & tableName ) const
  • virtual QSqlRecord record ( const QSqlQuery & query ) const
  • virtual QSqlRecordInfo recordInfo ( const QString & tablename ) const
  • virtual QSqlRecordInfo recordInfo ( const QSqlQuery & query ) const
  • virtual QString nullText () const
  • virtual QString formatValue ( const QSqlField * field, bool trimStrings = FALSE ) const
  • QSqlError lastError () const
  • virtual bool hasFeature ( DriverFeature f ) const = 0
  • virtual bool open ( const QString & db, const QString & user = QString::null, const QString & password = QString::null, const QString & host = QString::null, int port = -1 ) = 0
  • virtual void close () = 0
  • virtual QSqlQuery createQuery () const = 0

Protected Members

  • virtual void setOpen ( bool o )
  • virtual void setOpenError ( bool e )
  • virtual void setLastError ( const QSqlError & e )

Detailed Description

The QSqlDriver class is an abstract base class for accessing SQL databases.

This class should not be used directly. Use QSqlDatabase instead.

See also Database Classes.

Member Type Documentation

QSqlDriver::DriverFeature

This enum contains a list of features a driver may support. Use hasFeature() to query whether a feature is supported or not.

The currently defined values are:

  • QSqlDriver::Transactions - whether the driver supports SQL transactions
  • QSqlDriver::QuerySize - whether the database is capable of reporting the size of a query. Note that some databases do not support returning the size (i.e. number of rows returned) of a query, in which case QSqlQuery::size() will return -1
  • QSqlDriver::BLOB - whether the driver supports Binary Large Object fields

See also hasFeature().

Member Function Documentation

QSqlDriver::QSqlDriver ( QObject * parent = 0, const char * name = 0 )

Default constructor. Creates a new driver with parent parent and name name.

QSqlDriver::~QSqlDriver ()

Destroys the object and frees any allocated resources.

bool QSqlDriver::beginTransaction () [virtual]

Protected function which derived classes can reimplement to begin a transaction. If successful, return TRUE, otherwise return FALSE. The default implementation returns FALSE.

See also commitTransaction() and rollbackTransaction().

void QSqlDriver::close () [pure virtual]

Derived classes must reimplement this abstract virtual function in order to close the database connection. Return TRUE on success, FALSE on failure.

See also setOpen().

bool QSqlDriver::commitTransaction () [virtual]

Protected function which derived classes can reimplement to commit a transaction. If successful, return TRUE, otherwise return FALSE. The default implementation returns FALSE.

See also beginTransaction() and rollbackTransaction().

QSqlQuery QSqlDriver::createQuery () const [pure virtual]

Creates an empty SQL result on the database. Derived classes must reimplement this function and return a QSqlQuery object appropriate for their database to the caller.

QString QSqlDriver::formatValue ( const QSqlField * field, bool trimStrings = FALSE ) const [virtual]

Returns a string representation of the field value for the database. This is used, for example, when constructing INSERT and UPDATE statements.

The default implementation returns the value formatted as a string according to the following rules:

  • If field is null, nullText() is returned.
  • If field is character data, the value is returned enclosed in single quotation marks, which is appropriate for many SQL databases. Any embedded single-quote characters are escaped (replaced with two single-quote characters). If trimStrings is TRUE (the default is FALSE), all trailing whitespace is trimmed from the field.
  • If field is date/time data, the value is formatted in ISO format and enclosed in single quotation marks. If the date/time data is invalid, nullText() is returned.
  • If field is bytearray data, and the driver can edit binary fields, the value is formatted as a hexadecimal string.
  • For any other field type toString() will be called on its value and the result returned.

See also QVariant::toString().

bool QSqlDriver::hasFeature ( DriverFeature f ) const [pure virtual]

Returns TRUE if the driver supports feature f; otherwise returns FALSE.

Note that some databases need to be open() before this can be determined.

See also DriverFeature.

bool QSqlDriver::isOpen () const

Returns TRUE if the database connection is open, FALSE otherwise.

bool QSqlDriver::isOpenError () const

Returns TRUE if the there was an error opening the database connection, FALSE otherwise.

QSqlError QSqlDriver::lastError () const

Returns a QSqlError object which contains information about the last error that occurred on the database.

QString QSqlDriver::nullText () const [virtual]

Returns a string representation of the 'NULL' value for the database. This is used, for example, when constructing INSERT and UPDATE statements. The default implementation returns the string 'NULL'.

bool QSqlDriver::open ( const QString & db, const QString & user = QString::null, const QString & password = QString::null, const QString & host = QString::null, int port = -1 ) [pure virtual]

Derived classes must reimplement this abstract virtual function in order to open a database connection on database db, using user name user, password password, host host and port port.

The function must return TRUE on success and FALSE on failure.

See also setOpen().

QSqlIndex QSqlDriver::primaryIndex ( const QString & tableName ) const [virtual]

Returns the primary index for table tableName. Returns an empty QSqlIndex if the table doesn't have a primary index. The default implementation returns an empty index.

QSqlRecord QSqlDriver::record ( const QString & tableName ) const [virtual]

Returns a QSqlRecord populated with the names of the fields in table tableName. If no such table exists, an empty list is returned. The default implementation returns an empty record.

QSqlRecord QSqlDriver::record ( const QSqlQuery & query ) const [virtual]

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

Returns a QSqlRecord populated with the names of the fields in the SQL query. The default implementation returns an empty record.

QSqlRecordInfo QSqlDriver::recordInfo ( const QString & tablename ) const [virtual]

Returns a QSqlRecordInfo object with meta data on the table tablename.

QSqlRecordInfo QSqlDriver::recordInfo ( const QSqlQuery & query ) const [virtual]

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

Returns a QSqlRecordInfo object with meta data for the QSqlQuery query. Note that this overloaded function may return not as much information as the recordInfo function which takes the name of a table as parameter.

bool QSqlDriver::rollbackTransaction () [virtual]

Protected function which derived classes can reimplement to rollback a transaction. If successful, return TRUE, otherwise return FALSE. The default implementation returns FALSE.

See also beginTransaction() and commitTransaction().

void QSqlDriver::setLastError ( const QSqlError & e ) [virtual protected]

Protected function which allows derived classes to set the value of the last error, e, that occurred on the database.

See also lastError().

void QSqlDriver::setOpen ( bool o ) [virtual protected]

Protected function which sets the open state of the database to o. Derived classes can use this function to report the status of open().

See also open() and setOpenError().

void QSqlDriver::setOpenError ( bool e ) [virtual protected]

Protected function which sets the open error state of the database to e. Derived classes can use this function to report the status of open(). Note that if e is TRUE the open state of the database is set to closed (i.e., isOpen() returns FALSE).

See also open().

QStringList QSqlDriver::tables ( const QString & user ) const [virtual]

Returns a list of tables in the database. The default implementation returns an empty list.

Currently the user argument is unused.

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


qsqldriver.h Include File

qsqldriver.h

This is the verbatim text of the qsqldriver.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlDriver class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLDRIVER_H
#define QSQLDRIVER_H

#ifndef QT_H
#include "qobject.h"
#include "qstring.h"
#include "qsqlerror.h"
#include "qsqlquery.h"
#include "qsqlfield.h"
#include "qsqlindex.h"
#include "qstringlist.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlDatabase;

class QM_EXPORT_SQL QSqlDriver : public QObject
{
    friend class QSqlDatabase;
    Q_OBJECT
public:
    enum DriverFeature { Transactions, QuerySize, BLOB };

    QSqlDriver( QObject * parent=0, const char * name=0 );
    ~QSqlDriver();

    bool			isOpen() const;
    bool			isOpenError() const;

    virtual bool		beginTransaction();
    virtual bool		commitTransaction();
    virtual bool		rollbackTransaction();
    virtual QStringList		tables( const QString& user ) const;
    virtual QSqlIndex		primaryIndex( const QString& tableName ) const;
    virtual QSqlRecord		record( const QString& tableName ) const;
    virtual QSqlRecord		record( const QSqlQuery& query ) const;
    virtual QSqlRecordInfo	recordInfo( const QString& tablename ) const;
    virtual QSqlRecordInfo	recordInfo( const QSqlQuery& query ) const;
    virtual QString		nullText() const;
    virtual QString		formatValue( const QSqlField* field, bool trimStrings = FALSE ) const;
    QSqlError			lastError() const;

    virtual bool		hasFeature( DriverFeature f ) const = 0;
    virtual bool		open( const QString & db,
                    const QString & user = QString::null,
                    const QString & password = QString::null,
                    const QString & host = QString::null,
                int port = -1 ) = 0;
    virtual void		close() = 0;
    virtual QSqlQuery		createQuery() const = 0;

protected:
    virtual void		setOpen( bool o );
    virtual void		setOpenError( bool e );
    virtual void		setLastError( const QSqlError& e );
private:
    int		          dbState;
    QSqlError	          error;
#if defined(Q_DISABLE_COPY)
    QSqlDriver( const QSqlDriver & );
    QSqlDriver &operator=( const QSqlDriver & );
#endif
};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlDriver Member List

Complete Member List for QSqlDriver

This is the complete list of member functions for QSqlDriver, including inherited members.

  • QSqlDriver()
  • ~QSqlDriver()
  • beginTransaction()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • close()
  • commitTransaction()
  • connect()
  • connectNotify()
  • createQuery()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • formatValue()
  • hasFeature()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isOpen()
  • isOpenError()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • lastError()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • nullText()
  • objectTrees()
  • open()
  • parent()
  • primaryIndex()
  • property()
  • queryList()
  • record()
  • recordInfo()
  • removeChild()
  • removeEventFilter()
  • rollbackTransaction()
  • sender()
  • setLastError()
  • setName()
  • setOpen()
  • setOpenError()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • tables()
  • timerEvent()
  • tr()
  • trUtf8()


QSqlDriverPlugin Class

QSqlDriverPlugin Class Reference

The QSqlDriverPlugin class provides an abstract base for custom QSqlDriver plugins. More...

#include <qsqldriverplugin.h>

List of all member functions.

Public Members

  • QSqlDriverPlugin ()
  • ~QSqlDriverPlugin ()
  • virtual QStringList keys () const = 0
  • virtual QSqlDriver * create ( const QString & key ) = 0

Detailed Description

The QSqlDriverPlugin class provides an abstract base for custom QSqlDriver plugins.

The SQL driver plugin is a simple plugin interface that makes it easy to create your own SQL driver plugins that can be loaded dynamically by Qt.

Writing a SQL plugin is achieved by subclassing this base class, reimplementing the pure virtual functions keys() and create(), and exporting the class with the Q_EXPORT_PLUGIN macro. See the SQL plugins that come with Qt for example implementations (in the plugins/src/sqldrivers subdirectory of the source distribution). Read the plugins documentation for more information on plugins.

See also Plugins.

Member Function Documentation

QSqlDriverPlugin::QSqlDriverPlugin ()

Constructs a SQL driver plugin. This is invoked automatically by the Q_EXPORT_PLUGIN macro.

QSqlDriverPlugin::~QSqlDriverPlugin ()

Destroys the SQL driver plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

QSqlDriver * QSqlDriverPlugin::create ( const QString & key ) [pure virtual]

Creates and returns a QSqlDriver object for the driver key key. The driver key is usually the class name of the required driver.

See also keys().

QStringList QSqlDriverPlugin::keys () const [pure virtual]

Returns the list of driver keys this plugin supports.

These keys are usually the class names of the custom drivers that are implemented in the plugin.

See also create().

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


qsqldriverplugin.h Include File

qsqldriverplugin.h

This is the verbatim text of the qsqldriverplugin.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QSqlDriverPlugin class
**
** Created : 010920
**
** Copyright (C) 2001-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLDRIVERPLUGIN_H
#define QSQLDRIVERPLUGIN_H

#ifndef QT_H
#include "qgplugin.h"
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_SQL
#ifndef QT_NO_COMPONENT

class QSqlDriver;
class QSqlDriverPluginPrivate;

class Q_EXPORT QSqlDriverPlugin : public QGPlugin
{
    Q_OBJECT
public:
    QSqlDriverPlugin();
    ~QSqlDriverPlugin();

    virtual QStringList keys() const = 0;
    virtual QSqlDriver *create( const QString &key ) = 0;

private:
    QSqlDriverPluginPrivate *d;
};

#endif // QT_NO_COMPONENT
#endif // QT_NO_SQL

#endif // QSQLDRIVERPLUGIN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlDriverPlugin Member List

Complete Member List for QSqlDriverPlugin

This is the complete list of member functions for QSqlDriverPlugin, including inherited members.

  • QSqlDriverPlugin()
  • ~QSqlDriverPlugin()
  • create()
  • keys()


QSqlEditorFactory Class

QSqlEditorFactory Class Reference
[sql module]

The QSqlEditorFactory class is used to create the editors used by QDataTable and QSqlForm. More...

#include <qsqleditorfactory.h>

Inherits QEditorFactory.

List of all member functions.

Public Members

  • QSqlEditorFactory ( QObject * parent = 0, const char * name = 0 )
  • ~QSqlEditorFactory ()
  • virtual QWidget * createEditor ( QWidget * parent, const QVariant & variant )
  • virtual QWidget * createEditor ( QWidget * parent, const QSqlField * field )

Static Public Members

  • QSqlEditorFactory * defaultFactory ()
  • void installDefaultFactory ( QSqlEditorFactory * factory )

Detailed Description

The QSqlEditorFactory class is used to create the editors used by QDataTable and QSqlForm.

QSqlEditorFactory is used by QDataTable and QSqlForm to automatically create appropriate editors for a given QSqlField. For example if the field is a QVariant::String a QLineEdit would be the default editor, whereas a QVariant::Int's default editor would be a QSpinBox.

If you want to create different editors for fields with the same data type, subclass QSqlEditorFactory and reimplement the createEditor() function.

See also QDataTable, QSqlForm and Database Classes.

Member Function Documentation

QSqlEditorFactory::QSqlEditorFactory ( QObject * parent = 0, const char * name = 0 )

Constructs a SQL editor factory with parent parent and name name.

QSqlEditorFactory::~QSqlEditorFactory ()

Destroys the object and frees any allocated resources.

QWidget * QSqlEditorFactory::createEditor ( QWidget * parent, const QVariant & variant ) [virtual]

Creates and returns the appropriate editor widget for the QVariant variant.

The widget that is returned has the parent parent (which may be zero). If variant is invalid, 0 is returned.

Reimplemented from QEditorFactory.

QWidget * QSqlEditorFactory::createEditor ( QWidget * parent, const QSqlField * field ) [virtual]

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

Creates and returns the appropriate editor for the QSqlField field.

QSqlEditorFactory * QSqlEditorFactory::defaultFactory () [static]

Returns an instance of a default editor factory.

void QSqlEditorFactory::installDefaultFactory ( QSqlEditorFactory * factory ) [static]

Replaces the default editor factory with factory. All QDataTable and QSqlForm instantiations will use this new factory for creating field editors. QSqlEditorFactory takes ownership of factory, and destroys it when it is no longer needed.

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


qsqleditorfactory.h Include File

qsqleditorfactory.h

This is the verbatim text of the qsqleditorfactory.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlEditorFactory class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLEDITORFACTORY_H
#define QSQLEDITORFACTORY_H

#ifndef QT_H
#include "qeditorfactory.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlField;

class QM_EXPORT_SQL QSqlEditorFactory : public QEditorFactory
{
public:
    QSqlEditorFactory ( QObject * parent = 0, const char * name = 0 );
    ~QSqlEditorFactory();
    virtual QWidget * createEditor( QWidget * parent, const QVariant & variant );
    virtual QWidget * createEditor( QWidget * parent, const QSqlField * field );

    static QSqlEditorFactory * defaultFactory();
    static void installDefaultFactory( QSqlEditorFactory * factory );
};

#endif // QT_NO_SQL
#endif // QSQLEDITORFACTORY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlEditorFactory Member List

Complete Member List for QSqlEditorFactory

This is the complete list of member functions for QSqlEditorFactory, including inherited members.

  • QSqlEditorFactory()
  • ~QSqlEditorFactory()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • createEditor()
  • customEvent()
  • defaultFactory()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installDefaultFactory()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QSqlError Class

QSqlError Class Reference
[sql module]

The QSqlError class provides SQL database error information. More...

#include <qsqlerror.h>

List of all member functions.

Public Members

  • enum Type { None, Connection, Statement, Transaction, Unknown }
  • QSqlError ( const QString & driverText = QString::null, const QString & databaseText = QString::null, int type = QSqlError::None, int number = -1 )
  • QSqlError ( const QSqlError & other )
  • QSqlError & operator= ( const QSqlError & other )
  • virtual ~QSqlError ()
  • QString driverText () const
  • virtual void setDriverText ( const QString & driverText )
  • QString databaseText () const
  • virtual void setDatabaseText ( const QString & databaseText )
  • int type () const
  • virtual void setType ( int type )
  • int number () const
  • virtual void setNumber ( int number )

Detailed Description

The QSqlError class provides SQL database error information.

This class is used to report database-specific errors. An error description and (if appropriate) a database-specific error number can be recovered using this class.

See also Database Classes.

Member Type Documentation

QSqlError::Type

This enum type describes the type of SQL error that occurred.

The currently defined values are:

  • QSqlError::None - no error occurred
  • QSqlError::Connection - connection error
  • QSqlError::Statement - statement syntax error
  • QSqlError::Transaction - transaction failed error
  • QSqlError::Unknown - unknown error

Member Function Documentation

QSqlError::QSqlError ( const QString & driverText = QString::null, const QString & databaseText = QString::null, int type = QSqlError::None, int number = -1 )

Constructs an error containing the driver error text driverText, the database-specific error text databaseText, the type type and the optional error number number.

QSqlError::QSqlError ( const QSqlError & other )

Creates a copy of other.

QSqlError::~QSqlError () [virtual]

Destroys the object and frees any allocated resources.

QString QSqlError::databaseText () const

Returns the text of the error as reported by the database. This may contain database-specific descriptions.

QString QSqlError::driverText () const

Returns the text of the error as reported by the driver. This may contain database-specific descriptions.

int QSqlError::number () const

Returns the database-specific error number, or -1 if it cannot be determined.

QSqlError & QSqlError::operator= ( const QSqlError & other )

Sets the error equal to other.

void QSqlError::setDatabaseText ( const QString & databaseText ) [virtual]

Sets the database error text to the value of databaseText.

void QSqlError::setDriverText ( const QString & driverText ) [virtual]

Sets the driver error text to the value of driverText.

void QSqlError::setNumber ( int number ) [virtual]

Sets the database-specific error number to the value of number.

void QSqlError::setType ( int type ) [virtual]

Sets the error type to the value of type.

int QSqlError::type () const

Returns the error type, or -1 if the type cannot be determined.

See also QSqlError::Type.

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


qsqlerror.h Include File

qsqlerror.h

This is the verbatim text of the qsqlerror.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlError class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLERROR_H
#define QSQLERROR_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QM_EXPORT_SQL QSqlError
{
public:
    enum Type {
    None,
    Connection,
    Statement,
    Transaction,
    Unknown
    };
    QSqlError(  const QString& driverText = QString::null,
        const QString& databaseText = QString::null,
        int type = QSqlError::None,
        int number = -1 );
    QSqlError( const QSqlError& other );
    QSqlError& operator=( const QSqlError& other );
    virtual ~QSqlError();

    QString	driverText() const;
    virtual void setDriverText( const QString& driverText );
    QString	databaseText() const;
    virtual void setDatabaseText( const QString& databaseText );
    int		type() const;
    virtual void setType( int type );
    int		number() const;
    virtual void setNumber( int number );
private:
    QString	driverError;
    QString	databaseError;
    int		errorType;
    int	errorNumber;
};

#endif // QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlError Member List

Complete Member List for QSqlError

This is the complete list of member functions for QSqlError, including inherited members.

  • QSqlError()
  • ~QSqlError()
  • databaseText()
  • driverText()
  • number()
  • operator=()
  • setDatabaseText()
  • setDriverText()
  • setNumber()
  • setType()
  • type()


QSqlField Class

QSqlField Class Reference
[sql module]

The QSqlField class manipulates the fields in SQL database tables and views. More...

#include <qsqlfield.h>

List of all member functions.

Public Members

  • QSqlField ( const QString & fieldName = QString::null, QVariant::Type type = QVariant::Invalid )
  • QSqlField ( const QSqlField & other )
  • QSqlField & operator= ( const QSqlField & other )
  • bool operator== ( const QSqlField & other ) const
  • virtual ~QSqlField ()
  • virtual void setValue ( const QVariant & value )
  • virtual QVariant value () const
  • virtual void setName ( const QString & name )
  • QString name () const
  • virtual void setNull ()
  • bool isNull () const
  • virtual void setReadOnly ( bool readOnly )
  • bool isReadOnly () const
  • void clear ( bool nullify = TRUE )
  • QVariant::Type type () const

Detailed Description

The QSqlField class manipulates the fields in SQL database tables and views.

QSqlField represents the characteristics of a single column in a database table or view, such as the data type and column name. A field also contains the value of the database column, which can be viewed or changed.

Field data values are stored as QVariants. Using an incompatible type is not permitted. For example:

    QSqlField f( "myfield", QVariant::Int );
    f.setValue( QPixmap() );  // will not work

However, the field will attempt to cast certain data types to the field data type where possible:

    QSqlField f( "myfield", QVariant::Int );
    f.setValue( QString("123") ); // casts QString to int

QSqlField objects are rarely created explicitly in application code. They are usually accessed indirectly through QSqlRecord or QSqlCursor which already contain a list of fields. For example:

    QSqlCursor cur( "Employee" );        // create cursor using the 'Employee' table
    QSqlField* f = cur.field( "name" );  // use the 'name' field
    f->setValue( "Dave" );               // set field value
    ...

In practice we rarely need to extract a pointer to a field at all. The previous example would normally be written:

    QSqlCursor cur( "Employee" );
    cur.setValue( "name", "Dave" );
    ...

See also Database Classes.

Member Function Documentation

QSqlField::QSqlField ( const QString & fieldName = QString::null, QVariant::Type type = QVariant::Invalid )

Constructs an empty field called fieldName of type type.

QSqlField::QSqlField ( const QSqlField & other )

Constructs a copy of other.

QSqlField::~QSqlField () [virtual]

Destroys the object and frees any allocated resources.

void QSqlField::clear ( bool nullify = TRUE )

Clears the value of the field. If the field is read-only, nothing happens. If nullify is TRUE (the default), the field is set to NULL.

bool QSqlField::isNull () const

Returns TRUE if the field is currently null, otherwise returns FALSE.

bool QSqlField::isReadOnly () const

Returns TRUE if the field's value is read only, otherwise FALSE.

QString QSqlField::name () const

Returns the name of the field.

Example: sql/overview/table4/main.cpp.

QSqlField & QSqlField::operator= ( const QSqlField & other )

Sets the field equal to other.

bool QSqlField::operator== ( const QSqlField & other ) const

Returns TRUE if the field is equal to other, otherwise returns FALSE. Fields are considered equal when the following field properties are the same:

  • name()
  • isNull()
  • value()
  • isReadOnly()

void QSqlField::setName ( const QString & name ) [virtual]

Sets the name of the field to name.

void QSqlField::setNull () [virtual]

Sets the field to NULL and clears the value using clear(). If the field is read-only, nothing happens.

See also isReadOnly() and clear().

void QSqlField::setReadOnly ( bool readOnly ) [virtual]

Sets the read only flag of the field's value to readOnly.

See also setValue().

void QSqlField::setValue ( const QVariant & value ) [virtual]

Sets the value of the field to value. If the field is read-only (isReadOnly() returns TRUE), nothing happens. If the data type of value differs from the field's current data type, an attempt is made to cast it to the proper type. This preserves the data type of the field in the case of assignment, e.g. a QString to an integer data type. For example:

  QSqlCursor cur( "Employee" );                 // 'Employee' table
  QSqlField* f = cur.field( "student_count" );  // an integer field
  ...
  f->setValue( myLineEdit->text() );            // cast the line edit text to an integer

See also isReadOnly().

QVariant::Type QSqlField::type () const

Returns the field's type.

QVariant QSqlField::value () const [virtual]

Returns the internal value of the field as a QVariant.

Example: sql/overview/table4/main.cpp.

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


qsqlfield.h Include File

qsqlfield.h

This is the verbatim text of the qsqlfield.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlField class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLFIELD_H
#define QSQLFIELD_H

#ifndef QT_H
#include "qstring.h"
#include "qvariant.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlFieldPrivate;

class QM_EXPORT_SQL QSqlField
{
public:
    QSqlField( const QString& fieldName = QString::null, QVariant::Type type = QVariant::Invalid );
    QSqlField( const QSqlField& other );
    QSqlField& operator=( const QSqlField& other );
    bool operator==(const QSqlField& other) const;
    virtual ~QSqlField();

    virtual void	setValue( const QVariant& value );
    virtual QVariant	value() const;
    virtual void	setName( const QString& name );
    QString		name() const;
    virtual void	setNull();
    bool		isNull() const;
    virtual void	setReadOnly( bool readOnly );
    bool		isReadOnly() const;
    void		clear( bool nullify = TRUE );
    QVariant::Type	type() const;

private:
    QString       nm;
    QVariant      val;
    uint          ro: 1;
    uint          nul: 1;
    QSqlFieldPrivate* d;
};

inline QVariant QSqlField::value() const
{ return val; }

inline QString QSqlField::name() const
{ return nm; }

inline bool QSqlField::isNull() const
{ return nul; }

inline bool QSqlField::isReadOnly() const
{ return ro; }

inline QVariant::Type QSqlField::type() const
{ return val.type(); }

/******************************************/
/*******     QSqlFieldInfo Class     ******/
/******************************************/

struct QSqlFieldInfoPrivate;

class QM_EXPORT_SQL QSqlFieldInfo
{
public:
    QSqlFieldInfo( const QString& name = QString::null,
           QVariant::Type typ = QVariant::Invalid,
           int required = -1,
           int len = -1,
           int prec = -1,
           const QVariant& defValue = QVariant(),
           int sqlType = 0,
           bool generated = TRUE,
           bool trim = FALSE,
           bool calculated = FALSE );
    QSqlFieldInfo( const QSqlFieldInfo & other );
    QSqlFieldInfo( const QSqlField & other, bool generated = TRUE );
    virtual ~QSqlFieldInfo();
    QSqlFieldInfo& operator=( const QSqlFieldInfo& other );
    bool operator==( const QSqlFieldInfo& f ) const;

    QSqlField		toField() const;
    int			isRequired() const;
    QVariant::Type	type() const;
    int			length() const;
    int			precision() const;
    QVariant		defaultValue() const;
    QString		name() const;
    int			typeID() const;
    bool		isGenerated() const;
    bool		isTrim() const;
    bool		isCalculated() const;

    virtual void	setTrim( bool trim );
    virtual void	setGenerated( bool gen );
    virtual void	setCalculated( bool calc );

private:
    QSqlFieldInfoPrivate* d;
};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlField Member List

Complete Member List for QSqlField

This is the complete list of member functions for QSqlField, including inherited members.

  • QSqlField()
  • ~QSqlField()
  • clear()
  • isNull()
  • isReadOnly()
  • name()
  • operator=()
  • operator==()
  • setName()
  • setNull()
  • setReadOnly()
  • setValue()
  • type()
  • value()


QSqlFieldInfo Class

QSqlFieldInfo Class Reference
[sql module]

The QSqlFieldInfo class stores meta data associated with a SQL field. More...

#include <qsqlfield.h>

List of all member functions.

Public Members

  • QSqlFieldInfo ( const QString & name = QString::null, QVariant::Type typ = QVariant::Invalid, int required = -1, int len = -1, int prec = -1, const QVariant & defValue = QVariant ( ), int typeID = 0, bool generated = TRUE, bool trim = FALSE, bool calculated = FALSE )
  • QSqlFieldInfo ( const QSqlFieldInfo & other )
  • QSqlFieldInfo ( const QSqlField & other, bool generated = TRUE )
  • virtual ~QSqlFieldInfo ()
  • QSqlFieldInfo & operator= ( const QSqlFieldInfo & other )
  • bool operator== ( const QSqlFieldInfo & f ) const
  • QSqlField toField () const
  • int isRequired () const
  • QVariant::Type type () const
  • int length () const
  • int precision () const
  • QVariant defaultValue () const
  • QString name () const
  • int typeID () const
  • bool isGenerated () const
  • bool isTrim () const
  • bool isCalculated () const
  • virtual void setTrim ( bool trim )
  • virtual void setGenerated ( bool gen )
  • virtual void setCalculated ( bool calc )

Detailed Description

The QSqlFieldInfo class stores meta data associated with a SQL field.

QSqlFieldInfo objects only store meta data; field values are stored in QSqlField objects.

All values must be set in the constructor, and may be retrieved using isRequired(), type(), length(), precision(), defaultValue(), name(), isGenerated() and typeID().

See also Database Classes.

Member Function Documentation

QSqlFieldInfo::QSqlFieldInfo ( const QString & name = QString::null, QVariant::Type typ = QVariant::Invalid, int required = -1, int len = -1, int prec = -1, const QVariant & defValue = QVariant ( ), int typeID = 0, bool generated = TRUE, bool trim = FALSE, bool calculated = FALSE )

Constructs a QSqlFieldInfo with the following parameters:
  • name the name of the field.
  • typ the field's type in a QVariant.
  • required greater than 0 if the field is required, 0 if its value can be NULL and less than 0 if it cannot be determined whether the field is required or not.
  • len the length of the field. Note that for non-character types some databases return either the length in bytes or the number of digits. -1 signifies that the length cannot be determined.
  • prec the precision of the field, or -1 if the field has no precision or it cannot be determined.
  • defValue the default value that is inserted into the table if none is specified by the user. QVariant() if there is no default value or it cannot be determined.
  • typeID the internal typeID of the database system (only useful for low-level programming). 0 if unknown.
  • generated TRUE indicates that this field should be included in auto-generated SQL statments, e.g. in QSqlCursor.
  • trim TRUE indicates that widgets should remove trailing whitespace from character fields. This does not affect the field value but only its representation inside widgets.
  • calculated TRUE indicates that the value of this field is calculated. The value of calculated fields can by modified by subclassing QSqlCursor and overriding QSqlCursor::calculateField().

QSqlFieldInfo::QSqlFieldInfo ( const QSqlFieldInfo & other )

Constructs a copy of other.

QSqlFieldInfo::QSqlFieldInfo ( const QSqlField & other, bool generated = TRUE )

Creates a QSqlFieldInfo object with the type and the name of the QSqlField other. If generated is TRUE this field will be included in auto-generated SQL statments, e.g. in QSqlCursor.

QSqlFieldInfo::~QSqlFieldInfo () [virtual]

Destroys the object and frees any allocated resources.

QVariant QSqlFieldInfo::defaultValue () const

Returns the default value of this field or an empty QVariant if the field has no default value or the value couldn't be determined. The default value is the value inserted in the database when it was not explicitly specified by the user.

bool QSqlFieldInfo::isCalculated () const

Returns TRUE if the field is calculated.

See also setCalculated().

bool QSqlFieldInfo::isGenerated () const

Returns TRUE if this field should be included in auto-generated SQL statments, e.g. in QSqlCursor; otherwise returns FALSE.

See also setGenerated().

int QSqlFieldInfo::isRequired () const

Returns a value greater than 0 if the field is required (NULL values are not allowed), 0 if it isn't required (NULL values are allowed) or less than 0 if it cannot be determined whether the field is required or not.

bool QSqlFieldInfo::isTrim () const

Returns TRUE if trailing whitespace should be removed from character fields.

See also setTrim().

int QSqlFieldInfo::length () const

Returns the length of this field. For fields storing text the return value is the maximum number of characters the field can hold. For non-character fields some database systems return the number of bytes needed or the number of digits allowed. If the length cannot be determined -1 is returned.

QString QSqlFieldInfo::name () const

Returns the name of the field in the SQL table.

Examples: sql/overview/subclass3/main.cpp and sql/overview/subclass4/main.cpp.

QSqlFieldInfo & QSqlFieldInfo::operator= ( const QSqlFieldInfo & other )

Assigns other to this field info and returns a reference to it.

bool QSqlFieldInfo::operator== ( const QSqlFieldInfo & f ) const

Returns TRUE if this fieldinfo is equal to f; otherwise returns FALSE.

Two field infos are considered equal when all their attributes match.

int QSqlFieldInfo::precision () const

Returns the precision of this field or -1 if the field has no precision or it cannot be determined.

void QSqlFieldInfo::setCalculated ( bool calc ) [virtual]

calc set to TRUE indicates that this field is a calculated field. The value of calculated fields can by modified by subclassing QSqlCursor and overriding QSqlCursor::calculateField().

See also isCalculated().

void QSqlFieldInfo::setGenerated ( bool gen ) [virtual]

gen set to FALSE indicates that this field should not appear in auto-generated SQL statements (for example in QSqlCursor).

See also isGenerated().

void QSqlFieldInfo::setTrim ( bool trim ) [virtual]

If trim is TRUE widgets should remove trailing whitespace from character fields. This does not affect the field value but only its representation inside widgets.

See also isTrim().

QSqlField QSqlFieldInfo::toField () const

Returns an empty QSqlField based on the information in this QSqlFieldInfo.

QVariant::Type QSqlFieldInfo::type () const

Returns the type of this field or QVariant::Invalid if the type is unknown.

int QSqlFieldInfo::typeID () const

Returns the internal type identifier as returned from the database system. The return value is 0 if the type is unknown.

Warning: This information is only useful for low-level database programming and is not database independent.

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


QSqlFieldInfo Member List

Complete Member List for QSqlFieldInfo

This is the complete list of member functions for QSqlFieldInfo, including inherited members.

  • QSqlFieldInfo()
  • ~QSqlFieldInfo()
  • defaultValue()
  • isCalculated()
  • isGenerated()
  • isRequired()
  • isTrim()
  • length()
  • name()
  • operator=()
  • operator==()
  • precision()
  • setCalculated()
  • setGenerated()
  • setTrim()
  • toField()
  • type()
  • typeID()


QSqlForm Class

QSqlForm Class Reference
[sql module]

The QSqlForm class creates and manages data entry forms tied to SQL databases. More...

#include <qsqlform.h>

Inherits QObject.

List of all member functions.

Public Members

  • QSqlForm ( QObject * parent = 0, const char * name = 0 )
  • ~QSqlForm ()
  • virtual void insert ( QWidget * widget, const QString & field )
  • virtual void remove ( const QString & field )
  • uint count () const
  • QWidget * widget ( uint i ) const
  • QSqlField * widgetToField ( QWidget * widget ) const
  • QWidget * fieldToWidget ( QSqlField * field ) const
  • void installPropertyMap ( QSqlPropertyMap * pmap )
  • virtual void setRecord ( QSqlRecord * buf )

Public Slots

  • virtual void readField ( QWidget * widget )
  • virtual void writeField ( QWidget * widget )
  • virtual void readFields ()
  • virtual void writeFields ()
  • virtual void clear ()
  • virtual void clearValues ( bool nullify = FALSE )

Protected Members

  • virtual void insert ( QWidget * widget, QSqlField * field )
  • virtual void remove ( QWidget * widget )

Detailed Description

The QSqlForm class creates and manages data entry forms tied to SQL databases.

Typical use of a QSqlForm consists of the following steps:

  1. Create the widgets you want to appear in the form.
  2. Create a cursor and navigate to the record to be edited.
  3. Create the QSqlForm.
  4. Set the form's record buffer to the cursor's update buffer.
  5. Insert each widget and the field it is to edit into the form.
  6. Use readFields() to update the editor widgets with values from the database's fields.
  7. Display the form and let the user edit values etc.
  8. Use writeFields() to update the database's field values with the values in the editor widgets.

Note that a QSqlForm does not access the database directly, but most often via QSqlFields which are part of a QSqlCursor. A QSqlCursor::insert(), QSqlCursor::update() or QSqlCursor::del() call is needed to actually write values to the database.

Some sample code to initialize a form successfully:

  QLineEdit  myEditor( this );
  QSqlForm   myForm( this );
  QSqlCursor myCursor( "mytable" );

  // Execute a query to make the cursor valid
  myCursor.select();
  // Move the cursor to a valid record (the first record)
  myCursor.next();
  // Set the form's record pointer to the cursor's edit buffer (which
  // contains the current record's values)
  myForm.setRecord( myCursor.primeUpdate() );

  // Insert a field into the form that uses myEditor to edit the
  // field 'somefield' in 'mytable'
  myForm.insert( &myEditor, "somefield" );

  // Update myEditor with the value from the mapped database field
  myForm.readFields();
  ...
  // Let the user edit the form
  ...
  // Update the database
  myForm.writeFields(); // Update the cursor's edit buffer from the form
  myCursor.update();    // Update the database from the cursor's buffer

If you want to use custom editors for displaying/editing data fields, you need to install a custom QSqlPropertyMap. The form uses this object to get or set the value of a widget.

Note that Qt Designer provides a visual means of creating data-aware forms.

See also installPropertyMap(), QSqlPropertyMap and Database Classes.

Member Function Documentation

QSqlForm::QSqlForm ( QObject * parent = 0, const char * name = 0 )

Constructs a QSqlForm with parent parent and name name.

QSqlForm::~QSqlForm ()

Destroys the object and frees any allocated resources.

void QSqlForm::clear () [virtual slot]

Removes every widget, and the fields they're mapped to, from the form.

void QSqlForm::clearValues ( bool nullify = FALSE ) [virtual slot]

Clears the values in all the widgets, and the fields they are mapped to, in the form. If nullify is TRUE (the default is FALSE), each field is also set to null.

uint QSqlForm::count () const

Returns the number of widgets in the form.

QWidget * QSqlForm::fieldToWidget ( QSqlField * field ) const

Returns the widget that field field is mapped to.

void QSqlForm::insert ( QWidget * widget, const QString & field ) [virtual]

Inserts a widget, and the name of the field it is to be mapped to, into the form. To actually associate inserted widgets with an edit buffer, use setRecord().

See also setRecord().

Examples: sql/overview/form1/main.cpp and sql/overview/form2/main.cpp.

void QSqlForm::insert ( QWidget * widget, QSqlField * field ) [virtual protected]

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

Inserts a widget, and the field it is to be mapped to, into the form.

void QSqlForm::installPropertyMap ( QSqlPropertyMap * pmap )

Installs a custom QSqlPropertyMap. This is useful if you plan to create your own custom editor widgets.

QSqlForm takes ownership of pmap, and pmap is therefore deleted when QSqlForm goes out of scope.

See also QDataTable::installEditorFactory().

Example: sql/overview/custom1/main.cpp.

void QSqlForm::readField ( QWidget * widget ) [virtual slot]

Updates the widget widget with the value from the SQL field it is mapped to. Nothing happens if no SQL field is mapped to the widget.

void QSqlForm::readFields () [virtual slot]

Updates the widgets in the form with current values from the SQL fields they are mapped to.

Examples: sql/overview/form1/main.cpp and sql/overview/form2/main.cpp.

void QSqlForm::remove ( QWidget * widget ) [virtual protected]

Removes a widget, and hence the field it's mapped to, from the form.

void QSqlForm::remove ( const QString & field ) [virtual]

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

Removes field from the form.

void QSqlForm::setRecord ( QSqlRecord * buf ) [virtual]

Sets buf as the record buffer for the form. To force the display of the data from buf, use readFields().

See also readFields() and writeFields().

Examples: sql/overview/custom1/main.cpp, sql/overview/form1/main.cpp and sql/overview/form2/main.cpp.

QWidget * QSqlForm::widget ( uint i ) const

Returns the i-th widget in the form. Useful for traversing the widgets in the form.

QSqlField * QSqlForm::widgetToField ( QWidget * widget ) const

Returns the SQL field that widget widget is mapped to.

void QSqlForm::writeField ( QWidget * widget ) [virtual slot]

Updates the SQL field with the value from the widget it is mapped to. Nothing happens if no SQL field is mapped to the widget.

void QSqlForm::writeFields () [virtual slot]

Updates the SQL fields with values from the widgets they are mapped to. To actually update the database with the contents of the record buffer, use QSqlCursor::insert(), QSqlCursor::update() or QSqlCursor::del() as appropriate.

Example: sql/overview/form2/main.cpp.

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


qsqlform.h Include File

qsqlform.h

This is the verbatim text of the qsqlform.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlForm class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLFORM_H
#define QSQLFORM_H

#ifndef QT_H
#include "qobject.h"
#include "qmap.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlField;
class QSqlRecord;
class QSqlEditorFactory;
class QSqlPropertyMap;
class QWidget;
class QSqlFormPrivate;

class QM_EXPORT_SQL QSqlForm : public QObject
{
    Q_OBJECT
public:
    QSqlForm( QObject * parent = 0, const char * name = 0 );
    ~QSqlForm();

    virtual void insert( QWidget * widget, const QString& field );
    virtual void remove( const QString& field );
    uint         count() const;

    QWidget *   widget( uint i ) const;
    QSqlField * widgetToField( QWidget * widget ) const;
    QWidget *   fieldToWidget( QSqlField * field ) const;

    void        installPropertyMap( QSqlPropertyMap * map );

    virtual void setRecord( QSqlRecord* buf );

public slots:
    virtual void readField( QWidget * widget );
    virtual void writeField( QWidget * widget );
    virtual void readFields();
    virtual void writeFields();

    virtual void clear();
    virtual void clearValues( bool nullify = FALSE );

protected:
    virtual void insert( QWidget * widget, QSqlField * field );
    virtual void remove( QWidget * widget );
    void clearMap();

private:
    virtual void sync();
    QSqlFormPrivate* d;
};

#endif // QT_NO_SQL
#endif // QSQLFORM_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlForm Member List

Complete Member List for QSqlForm

This is the complete list of member functions for QSqlForm, including inherited members.

  • QSqlForm()
  • ~QSqlForm()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clear()
  • clearValues()
  • connect()
  • connectNotify()
  • count()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fieldToWidget()
  • highPriority()
  • inherits()
  • insert()
  • insertChild()
  • installEventFilter()
  • installPropertyMap()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • readField()
  • readFields()
  • remove()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • setRecord()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()
  • widgetToField()
  • writeField()
  • writeFields()


QSqlIndex Class

QSqlIndex Class Reference
[sql module]

The QSqlIndex class provides functions to manipulate and describe QSqlCursor and QSqlDatabase indexes. More...

#include <qsqlindex.h>

Inherits QSqlRecord.

List of all member functions.

Public Members

  • QSqlIndex ( const QString & cursorname = QString::null, const QString & name = QString::null )
  • QSqlIndex ( const QSqlIndex & other )
  • ~QSqlIndex ()
  • QSqlIndex & operator= ( const QSqlIndex & other )
  • virtual void setCursorName ( const QString & cursorName )
  • QString cursorName () const
  • virtual void setName ( const QString & name )
  • QString name () const
  • virtual void append ( const QSqlField & field )
  • virtual void append ( const QSqlField & field, bool desc )
  • bool isDescending ( int i ) const
  • virtual void setDescending ( int i, bool desc )

Static Public Members

  • QSqlIndex fromStringList ( const QStringList & l, const QSqlCursor * cursor )

Detailed Description

The QSqlIndex class provides functions to manipulate and describe QSqlCursor and QSqlDatabase indexes.

This class is used to describe and manipulate QSqlCursor and QSqlDatabase indexes. An index refers to a single table or view in a database. Information about the fields that comprise the index can be used to generate SQL statements, or to affect the behavior of a QSqlCursor object.

Normally, QSqlIndex objects are created by QSqlDatabase or QSqlCursor.

See also Database Classes.

Member Function Documentation

QSqlIndex::QSqlIndex ( const QString & cursorname = QString::null, const QString & name = QString::null )

Constructs an empty index using the cursor name cursorname and index name name.

QSqlIndex::QSqlIndex ( const QSqlIndex & other )

Constructs a copy of other.

QSqlIndex::~QSqlIndex ()

Destroys the object and frees any allocated resources.

void QSqlIndex::append ( const QSqlField & field ) [virtual]

Appends the field field to the list of indexed fields. The field is appended with an ascending sort order.

Reimplemented from QSqlRecord.

void QSqlIndex::append ( const QSqlField & field, bool desc ) [virtual]

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

Appends the field field to the list of indexed fields. The field is appended with an ascending sort order, unless desc is TRUE.

QString QSqlIndex::cursorName () const

Returns the name of the cursor which the index is associated with.

QSqlIndex QSqlIndex::fromStringList ( const QStringList & l, const QSqlCursor * cursor ) [static]

Returns an index based on the field descriptions in l and the cursor cursor. The field descriptions should be in the same format that toStringList() produces, for example, a surname field in the people table might be in one of these forms: "surname", "surname DESC" or "people.surname ASC".

See also toStringList().

bool QSqlIndex::isDescending ( int i ) const

Returns true if field i in the index is sorted in descending order, otherwise returns FALSE.

QString QSqlIndex::name () const

Returns the name of the index.

QSqlIndex & QSqlIndex::operator= ( const QSqlIndex & other )

Sets the index equal to other.

void QSqlIndex::setCursorName ( const QString & cursorName ) [virtual]

Sets the name of the cursor that the index is associated with to cursorName.

void QSqlIndex::setDescending ( int i, bool desc ) [virtual]

If desc is TRUE, field i is sorted in descending order. Otherwise, field i is sorted in ascending order (the default). If the field does not exist, nothing happens.

void QSqlIndex::setName ( const QString & name ) [virtual]

Sets the name of the index to name.

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


qsqlindex.h Include File

qsqlindex.h

This is the verbatim text of the qsqlindex.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlIndex class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLINDEX_H
#define QSQLINDEX_H

#ifndef QT_H
#include "qstring.h"
#include "qstringlist.h"
#include "qsqlfield.h"
#include "qsqlrecord.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QValueList<bool>;
// MOC_SKIP_END
#endif

class QSqlCursor;

class QM_EXPORT_SQL QSqlIndex : public QSqlRecord
{
public:
    QSqlIndex( const QString& cursorName = QString::null, const QString& name = QString::null );
    QSqlIndex( const QSqlIndex& other );
    ~QSqlIndex();
    QSqlIndex&       operator=( const QSqlIndex& other );
    virtual void     setCursorName( const QString& cursorName );
    QString          cursorName() const { return cursor; }
    virtual void     setName( const QString& name );
    QString          name() const { return nm; }

    void             append( const QSqlField& field );
    virtual void     append( const QSqlField& field, bool desc );

    bool             isDescending( int i ) const;
    virtual void     setDescending( int i, bool desc );

    QString          toString( const QString& prefix = QString::null,
                   const QString& sep = ",",
                   bool verbose = TRUE ) const;
    QStringList      toStringList( const QString& prefix = QString::null,
                   bool verbose = TRUE ) const;

    static QSqlIndex fromStringList( const QStringList& l, const QSqlCursor* cursor );

private:
    QString          createField( int i, const QString& prefix, bool verbose ) const;
    QString          cursor;
    QString          nm;
    QValueList<bool> sorts;
};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlIndex Member List

Complete Member List for QSqlIndex

This is the complete list of member functions for QSqlIndex, including inherited members.

  • QSqlIndex()
  • ~QSqlIndex()
  • append()
  • clear()
  • clearValues()
  • contains()
  • count()
  • cursorName()
  • field()
  • fieldName()
  • fromStringList()
  • insert()
  • isDescending()
  • isEmpty()
  • isGenerated()
  • isNull()
  • name()
  • operator=()
  • position()
  • remove()
  • setCursorName()
  • setDescending()
  • setGenerated()
  • setName()
  • setNull()
  • setValue()
  • toString()
  • toStringList()
  • value()


QSqlPropertyMap Class

QSqlPropertyMap Class Reference
[sql module]

The QSqlPropertyMap class is used to map widgets to SQL fields. More...

#include <qsqlpropertymap.h>

List of all member functions.

Public Members

  • QSqlPropertyMap ()
  • virtual ~QSqlPropertyMap ()
  • QVariant property ( QWidget * widget )
  • virtual void setProperty ( QWidget * widget, const QVariant & value )
  • void insert ( const QString & classname, const QString & property )
  • void remove ( const QString & classname )

Static Public Members

  • QSqlPropertyMap * defaultMap ()
  • void installDefaultMap ( QSqlPropertyMap * map )

Detailed Description

The QSqlPropertyMap class is used to map widgets to SQL fields.

The SQL module uses Qt object properties to insert and extract values from editor widgets.

This class is used to map editors to SQL fields. This works by associating SQL editor class names to the properties used to insert and extract values to/from the editor.

For example, a QLineEdit can be used to edit text strings and other data types in QDataTables or QSqlForms. Several properties are defined in QLineEdit, but only the text property is used to insert and extract text from a QLineEdit. Both QDataTable and QSqlForm use the global QSqlPropertyMap for inserting and extracting values to and from an editor widget. The global property map defines several common widgets and properties that are suitable for many applications. You can add and remove widget properties to suit your specific needs.

If you want to use custom editors with your QDataTable or QSqlForm, you have to install your own QSqlPropertyMap for that table or form. Example:

  QSqlPropertyMap *myMap  = new QSqlPropertyMap();
  QSqlForm        *myForm = new QSqlForm( this );
  MyEditor         myEditor( this );

  // Set the QSqlForm's record buffer to the update buffer of
  // a pre-existing QSqlCursor called 'cur'.
  myForm->setRecord( cur->primeUpdate() );

  // Install the customized map
  myMap->insert( "MyEditor", "content" );
  myForm->installPropertyMap( myMap ); // myForm now owns myMap
  ...
  // Insert a field into the form that uses a myEditor to edit the
  // field 'somefield'
  myForm->insert( &myEditor, "somefield" );

  // Update myEditor with the value from the mapped database field
  myForm->readFields();
  ...
  // Let the user edit the form
  ...
  // Update the database fields with the values in the form
  myForm->writeFields();
  ...

You can also replace the global QSqlPropertyMap that is used by default. (Bear in mind that QSqlPropertyMap takes ownership of the new default map.)

  QSqlPropertyMap *myMap = new QSqlPropertyMap;

  myMap->insert( "MyEditor", "content" );
  QSqlPropertyMap::installDefaultMap( myMap );
  ...

See also QDataTable, QSqlForm, QSqlEditorFactory and Database Classes.

Member Function Documentation

QSqlPropertyMap::QSqlPropertyMap ()

Constructs a QSqlPropertyMap.

The default property mappings used by Qt widgets are:

  • QButton -- text
  • QCheckBox -- checked
  • QComboBox -- currentItem
  • QDateEdit -- date
  • QDateTimeEdit -- dateTime
  • QDial -- value
  • QLabel -- text
  • QLCDNumber -- value
  • QLineEdit -- text
  • QListBox -- currentItem
  • QMultiLineEdit -- text
  • QPushButton -- text
  • QRadioButton -- text
  • QScrollBar -- value
  • QSlider -- value
  • QSpinBox -- value
  • QTextBrowser -- source
  • QTextEdit -- text
  • QTextView -- text
  • QTimeEdit -- time

QSqlPropertyMap::~QSqlPropertyMap () [virtual]

Destroys the QSqlPropertyMap.

Note that if the QSqlPropertyMap is installed with installPropertyMap() the object it was installed into, e.g. the QSqlForm, takes ownership and will delete the QSqlPropertyMap when necessary.

QSqlPropertyMap * QSqlPropertyMap::defaultMap () [static]

Returns the application global QSqlPropertyMap.

void QSqlPropertyMap::insert ( const QString & classname, const QString & property )

Insert a new classname/property pair, which is used for custom SQL field editors. There must be a Q_PROPERTY clause in the classname class declaration for the property.

Example: sql/overview/custom1/main.cpp.

void QSqlPropertyMap::installDefaultMap ( QSqlPropertyMap * map ) [static]

Replaces the global default property map with map. All QDataTable and QSqlForm instantiations will use this new map for inserting and extracting values to and from editors. QSqlPropertyMap takes ownership of map, and destroys it when it is no longer needed.

QVariant QSqlPropertyMap::property ( QWidget * widget )

Returns the mapped property of widget as a QVariant.

void QSqlPropertyMap::remove ( const QString & classname )

Removes classname from the map.

void QSqlPropertyMap::setProperty ( QWidget * widget, const QVariant & value ) [virtual]

Sets the property of widget to value.

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


qsqlpropertymap.h Include File

qsqlpropertymap.h

This is the verbatim text of the qsqlpropertymap.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlPropertyMap class
**
** Created : 2000-11-20
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLPROPERTYMAP_H
#define QSQLPROPERTYMAP_H

#ifndef QT_H
#include "qvariant.h"
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_SQL

class QWidget;
class QSqlPropertyMapPrivate;

class Q_EXPORT QSqlPropertyMap {
public:
    QSqlPropertyMap();
    virtual ~QSqlPropertyMap();

    QVariant      property( QWidget * widget );
    virtual void  setProperty( QWidget * widget, const QVariant & value );

    void insert( const QString & classname, const QString & property );
    void remove( const QString & classname );

    static QSqlPropertyMap * defaultMap();
    static void installDefaultMap( QSqlPropertyMap * map );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSqlPropertyMap( const QSqlPropertyMap & );
    QSqlPropertyMap &operator=( const QSqlPropertyMap & );
#endif
    QSqlPropertyMapPrivate* d;

};

#endif // QT_NO_SQL
#endif // QSQLPROPERTYMAP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlPropertyMap Member List

Complete Member List for QSqlPropertyMap

This is the complete list of member functions for QSqlPropertyMap, including inherited members.

  • QSqlPropertyMap()
  • ~QSqlPropertyMap()
  • defaultMap()
  • insert()
  • installDefaultMap()
  • property()
  • remove()
  • setProperty()


QSqlQuery类

QSqlQuery类参考
[sql模块]

QSqlQuery类提供了一种执行和操纵SQL语句的方式。 详情请见……

#include <qsqlquery.h>

被QSqlCursor继承。

所有成员函数的列表。

公有成员

  • QSqlQuery ( QSqlResult * r )
  • QSqlQuery ( const QString & query = QString::null, QSqlDatabase * db = 0 )
  • QSqlQuery ( const QSqlQuery & other )
  • QSqlQuery & operator= ( const QSqlQuery & other )
  • virtual ~QSqlQuery ()
  • bool isValid () const
  • bool isActive () const
  • bool isNull ( int field ) const
  • int at () const
  • QString lastQuery () const
  • int numRowsAffected () const
  • QSqlError lastError () const
  • bool isSelect () const
  • int size () const
  • const QSqlDriver * driver () const
  • const QSqlResult * result () const
  • virtual bool exec ( const QString & query )
  • virtual QVariant value ( int i ) const
  • virtual bool seek ( int i, bool relative = FALSE )
  • virtual bool next ()
  • virtual bool prev ()
  • virtual bool first ()
  • virtual bool last ()

保护成员

  • virtual void beforeSeek ()
  • virtual void afterSeek ()

详细描述

QSqlQuery类提供了一种执行和操纵SQL语句的方式。

QSqlQuery包括了所有的功能，像在一个QSqlDatabase上执行SQL查询创建、导航和索取数据等等。 它可以执行DML（数据操作语言）语句，比如 SELECT, INSERT, UPDATE 和 DELETE, 还可以执行DDL（数据定义语言）语句，比如：CREATE TABLE。 不仅如此，它还可以用于执行特定数据库而不是标准SQL语句的指令(比如 SET DATESTYLE=ISO 用于 PostgreSQL).

成功执行一SQL语句设置query为活动状态（ isActive() 返回TRUE）否则查询置为非活动状态。无论那种情况，执行一条新的 SQL 语句之后，查询都被定位在一个无效的记录上；所以在数据被获取之前，查询都必须被导航到一个有效的记录上 （isValid()可以确定查询是否处在一个有效的记录上）。

在记录之间进行导航用以下一条函数:

  • next()
  • prev()
  • first()
  • last()
  • seek(int)

这些函数允许程序员向前、向后或随心所欲地在查询返回的记录之间移动。一旦一个处于活动状态的查询 被定位在一个有效的记录上时，就可以通过value()获取数据。所有的数据都被用QVariants从SQL后端转换过来。

比如：

    QSqlQuery query( "select name from customer" );
    while ( query.next() ) {
        QString name = query.value(0).toString();
        doSomething( name );
    }

要获得从一个查询中返回的数据，用value()方法。由SELECT语句返回的数据中的每个域可以通过指定一个索引来访问，索引从0开始。没有一个方法可以通过指定名字来定位域的，因为这不能得到可能确认。（请看QSqlCursor，它提供一个更加有弹性的接口用于从一个表单中选择数据或在一个数据库中查看数据）。

也可以参考QSqlDatabase、QSqlCursor、QVariant和数据库类。

成员函数文档

QSqlQuery::QSqlQuery ( QSqlResult * r )

创建一个QSqlQuery对象，用QSqlResult r 用于和一个数据库进行通信。

QSqlQuery::QSqlQuery ( const QString & query = QString::null, QSqlDatabase * db = 0 )

用 SQL query 和数据库db创建一个QSqlQuery对象。如果db为0（默认），则使用程序的默认数据库。

也可以参考QSqlDatabase。

QSqlQuery::QSqlQuery ( const QSqlQuery & other )

构建一个other的副本。

QSqlQuery::~QSqlQuery () [virtual]

清空此对象并释放所有的资源。

void QSqlQuery::afterSeek () [virtual protected]

保护虚函数，当内部记录指针被移动到一个新的记录时被调用。默认的操作什么都不做。

int QSqlQuery::at () const

返回查询的当前的内部位置。第一个记录的位置是0。如果位置是无效的，一个描述无效位置的QSql::Location将返回。

S也可以参考 isValid()。

例子： sql/overview/navigating/main.cpp。

void QSqlQuery::beforeSeek () [virtual protected]

保护虚函数，内部记录指针被移动到一个新的记录之前被调用。默认的操作什么都不做。

const QSqlDriver * QSqlQuery::driver () const

返回一个指向与查询对应的数据库驱动的指针。

bool QSqlQuery::exec ( const QString & query ) [virtual]

执行 SQL query。如果查询成功了便设置查询的状态为活动，并且返回TRUE。否则返回false并且查询变为非活动状态。 query 语句必须必须符合数据数据库的语法要求，比如说，标准的SQL。

执行之后，查询被定位在一个无效的记录上，所以在获得数据之前，必须先导航到一个有效的记录上。

注意：执行exec()之后，查询的最后错误会被得新设置。

也可以参考 isActive()、isValid()、next()、prev()、first()、last() 和 seek()。

例子： sql/overview/basicbrowsing/main.cpp、sql/overview/basicbrowsing2/main.cpp 和 sql/overview/basicdatamanip/main.cpp。

bool QSqlQuery::first () [virtual]

检索结果集中的第一个记录，如果有效的话，还将定位查询在检索的记录上。注意，在调用这个函数之前，结果集必须处于一个有效的状态，并且 isSelect() 必须返回TRUE，否则它将什么都不做，返回FALSE。成功执行返回TRUE。如果不成功，查询被设置到一个无效的位置上，并返回FALSE。

例子： sql/overview/navigating/main.cpp。

bool QSqlQuery::isActive () const

如果查询当前是处于一个活动的状态返回 TRUE，否则返回 FALSE。

例子：sql/overview/basicbrowsing/main.cpp、sql/overview/basicbrowsing2/main.cpp、sql/overview/basicdatamanip/main.cpp、sql/overview/navigating/main.cpp 和 sql/overview/retrieve1/main.cpp。

bool QSqlQuery::isNull ( int field ) const

如果field 当前为 NULL 返回，否则返回 FALSE 。在调用这个函数之前，查询必须是活动的并且被定位在一个有效的记录上，否则将返回 FALSE 。注意，对于一些驱动来说，isNull() 不会返回准确的信息，直到尝试去检索数据。

也可以参考 isActive()、isValid() 和 value()。

bool QSqlQuery::isSelect () const

如果当前的查询是 SELECT 语句返回TRUE，否则返回 FALSE。

bool QSqlQuery::isValid () const

如果查询当前处在一个有效的记录上返回TRUE，否则返回FALSE。

bool QSqlQuery::last () [virtual]

R检索结果集中的最后一个记录，如果有效的话，将定位查询在检索的记录上。注意，在调用这个函数之前，结果集必须处于有效的状态，而且 isSelect() 必须返回 TRUE。否则它将什么都不做还返回 FALSE。如果成功将返回 TRUE。如果失败查询被定位到一个无效的位置上并且返回FALSE。

例子：sql/overview/navigating/main.cpp。

QSqlError QSqlQuery::lastError () const

返回最后产生的错误信息。

也可以参考 QSqlError。

QString QSqlQuery::lastQuery () const

返回当前正被使用的查询的文本，如果没有查询文本则返回 QString::null。

bool QSqlQuery::next () [virtual]

在结果集中检索下一个记录，如果有效，定位查询在被检索的记录上。注意，在调用这个函数之前，结果集必须处于有效的状态，而且 isSelect() 必须返回 TRUE。否则它将什么都不做返回 FALSE。

应用以下一些规则：

  • 如果如果集被定位在第一个记录之前，刚刚执行完一个查询就处于这种状态，那么可以用此函数来检索第一个记录。
  • 如果如果集被定位在最后一个记录之后，那么什么都不会改变，返回FALSE。
  • 如果结果集被定位在中间，此函数可以检索下一个记录。

如果记录不能被检索，结果集将被定位在最后一个记录之后，并返回 FALSE 。如果记录成功检索，那么返回 TRUE 。

也可以参考 at()和isValid()。

例子： sql/overview/basicbrowsing/main.cpp、sql/overview/basicbrowsing2/main.cpp、sql/overview/retrieve1/main.cpp、sql/overview/subclass3/main.cpp、sql/overview/subclass4/main.cpp、sql/overview/subclass5/main.cpp和sql/sqltable/main.cpp。

int QSqlQuery::numRowsAffected () const

返回有多少行记录被结果集的 SQL 语句影响了，如果不能确定将返回 -1 。注意，对于 SELECT语句，此值等同于 size()如果查询处于非活动状态（isActive()返回FALSE），将反回 -1。

也可以参考 size() 和 QSqlDriver::hasFeature()。

例子： sql/overview/basicbrowsing2/main.cpp 和 sql/overview/basicdatamanip/main.cpp。

QSqlQuery & QSqlQuery::operator= ( const QSqlQuery & other )

分配other 给查询。

bool QSqlQuery::prev () [virtual]

在结果集中检索前一个记录，如果有效，查询被这位在检索的记录上。注意，在调用这个函数之前，结果集必须处于有效的状态，而且 isSelect() 必须返回 TRUE。否则它将什么都不做返回 FALSE。

应用以下一些规则：

  • 如果结果集被定位在第一个记录之前，什么都不会改变，返回 FALSE。
  • 如果结果集被定位在最后一个记录之后，调用此函数可以检索到最后一个记录。
  • 如果结果集被定位在中间位置，调用此函数可以检索前一个记录。

如果记录不能被检索，结果集将被定位在第一个记录之前，并返回 FALSE 。如果记录成功检索，那么返回 TRUE 。

也可以参考 at()。

const QSqlResult * QSqlQuery::result () const

返回查询对应的指针。

bool QSqlQuery::seek ( int i, bool relative = FALSE ) [virtual]

检索位置为 i（偏移） 的记录，如果有效，查询被定位在检索的记录上。第一个记录在位置0上。注意，在调用这个函数之前，查询必须处于活动状态，而且 isSelect() 必须返回TRUE。

应用以下一些规则：

如果 relative 为FALSE（默认）, 应用以下规则：

  • 如果i 是负的，结果集被定位在第一个记录之前，并返回 FALSE。
  • 否则，将定位查询到位置 i 。如果位置 i 上的记录不能被检索，结果集被定位到最后一个记录之后返回FALSE。如果记录被成功检索，返回TRUE。

如果 relative为TRUE，应用以下规则：

  • 如果结果集当前处于第一个记录之前，或者就在第一个记录之上，而且 i 是负的，那么什么都不会改变，FALSE 将被返回。
  • 如果结果集处于在最后一个记录之后，而且 i 是负的，那么什么都不改变，返回 FALSE。
  • 如果结果集处于中间的某个位置，相对偏移量 i 移动结果集在0 之下，那么结果集将定位在第一个记录之前，返回FALSE。
  • 否则，调用此函数将向前移动结果集到记录 i （或者向后移动到记录i如果i 是负的）。如果记录偏移量 i不能被检索，当那么i >=0时，结果集将被定位在最后一个记录之后（或者当i是负时，在第一个记录之前），返回 FALSE。如果记录成功检索，返回TRUE。

例子： sql/overview/navigating/main.cpp。

int QSqlQuery::size () const

返回结果集的大小，（多少行被返回），如果大小不能确定或者数据库不支持报告查询大小的信息时返回-1。注意，对于那些非 SELECT 语句（isSelect()返回FALSE）， size() 将返回 -1，如果查询处于非活动状态（isActive()返回FALSE），将返回-1。

想得一个非 SELECT 语句影响的行数，用 numRowsAffected()。

也可以参考 isActive()、numRowsAffected() 和 QSqlDriver::hasFeature()。

例子 sql/overview/navigating/main.cpp。

QVariant QSqlQuery::value ( int i ) const [virtual]

返回域 i 的值（基于0）。

用SELECT 语句的文本，域被从左到右编号，比如：在"select forename, surname from people"，域0是forename 而域1 是surname。推荐使用 SELECT * * 语句，因为这样的话查询中的域没有定义。

如果域 i 不存在的话，如果查询处于非活动状态，或查询被定位在一个无效的记录上，一个无效的QVariant被返回。

也可以参考 prev()、next()、first()、last()、seek()、isActive()和isValid()。

例子： sql/overview/basicbrowsing/main.cpp、sql/overview/basicbrowsing2/main.cpp、sql/overview/retrieve1/main.cpp、sql/overview/subclass3/main.cpp、sql/overview/subclass4/main.cpp、sql/overview/subclass5/main.cpp和sql/sqltable/main.cpp。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


qsqlquery.h 包含文件

qsqlquery.h

这里是qsqlquery.h 包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
**
** Definition of QSqlQuery class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLQUERY_H
#define QSQLQUERY_H

#ifndef QT_H
#include "qobject.h"
#include "qstring.h"
#include "qvariant.h"
#include "qvaluelist.h"
#include "qsqlerror.h"
#include "qsqlfield.h"
#endif // QT_H

#ifndef QT_NO_SQL

class QSqlDriver;
class QSqlResult;
class QSqlResultInfo;
class QSqlDatabase;

class Q_EXPORT QSqlResultShared : public QObject, public QShared
{
    Q_OBJECT
public:
    QSqlResultShared( QSqlResult* result );
    virtual ~QSqlResultShared();
    QSqlResult* sqlResult;
private slots:
    void slotResultDestroyed();
};

class Q_EXPORT QSqlQuery
{
public:
    QSqlQuery( QSqlResult * r );
    QSqlQuery( const QString& query = QString::null, QSqlDatabase* db = 0 );
    QSqlQuery( const QSqlQuery& other );
    QSqlQuery&          operator=( const QSqlQuery& other );
    virtual ~QSqlQuery();

    bool                isValid() const;
    bool                isActive() const;
    bool	        isNull( int field ) const;
    int                 at() const;
    QString             lastQuery() const;
    int                 numRowsAffected() const;
    QSqlError	        lastError() const;
    bool                isSelect() const;
    int                 size() const;
    const QSqlDriver*   driver() const;
    const QSqlResult*   result() const;

    virtual bool	exec ( const QString& query );
    virtual QVariant    value( int i ) const;

    virtual bool	seek( int i, bool relative = FALSE );
    virtual bool        next();
    virtual bool        prev();
    virtual bool        first();
    virtual bool        last();

protected:
    virtual void        beforeSeek();
    virtual void        afterSeek();

private:
    void                deref();
    bool                checkDetach();
    QSqlResultShared*   d;
};

#endif // QT_NO_SQL
#endif

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


QSqlQuery成员列表

完整的QSqlQuery成员列表

这里是QSqlQuery成员函数的完整列表，包括继承的成员。

  • QSqlQuery()
  • ~QSqlQuery()
  • afterSeek()
  • at()
  • beforeSeek()
  • driver()
  • exec()
  • first()
  • isActive()
  • isNull()
  • isSelect()
  • isValid()
  • last()
  • lastError()
  • lastQuery()
  • next()
  • numRowsAffected()
  • operator=()
  • prev()
  • result()
  • seek()
  • size()
  • value()

Copyright © 2002 Trolltech Trademarks 译者:tipy
Qt 3.0.5版


QSqlRecord Class

QSqlRecord Class Reference
[sql module]

The QSqlRecord class encapsulates a database record, i.e. a set of database fields. More...

#include <qsqlrecord.h>

Inherited by QSqlCursor and QSqlIndex.

List of all member functions.

Public Members

  • QSqlRecord ()
  • QSqlRecord ( const QSqlRecord & other )
  • QSqlRecord & operator= ( const QSqlRecord & other )
  • virtual ~QSqlRecord ()
  • virtual QVariant value ( int i ) const
  • virtual QVariant value ( const QString & name ) const
  • virtual void setValue ( int i, const QVariant & val )
  • virtual void setValue ( const QString & name, const QVariant & val )
  • bool isGenerated ( int i ) const
  • bool isGenerated ( const QString & name ) const
  • virtual void setGenerated ( const QString & name, bool generated )
  • virtual void setGenerated ( int i, bool generated )
  • virtual void setNull ( int i )
  • virtual void setNull ( const QString & name )
  • bool isNull ( int i )
  • bool isNull ( const QString & name )
  • int position ( const QString & name ) const
  • QString fieldName ( int i ) const
  • QSqlField * field ( int i )
  • QSqlField * field ( const QString & name )
  • const QSqlField * field ( int i ) const
  • const QSqlField * field ( const QString & name ) const
  • virtual void append ( const QSqlField & field )
  • virtual void insert ( int pos, const QSqlField & field )
  • virtual void remove ( int pos )
  • bool isEmpty () const
  • bool contains ( const QString & name ) const
  • virtual void clear ()
  • virtual void clearValues ( bool nullify = FALSE )
  • uint count () const
  • virtual QString toString ( const QString & prefix = QString::null, const QString & sep = "," ) const
  • virtual QStringList toStringList ( const QString & prefix = QString::null ) const

Detailed Description

The QSqlRecord class encapsulates a database record, i.e. a set of database fields.

The QSqlRecord class encapsulates the functionality and characteristics of a database record (usually a table or view within the database). QSqlRecords support adding and removing fields as well as setting and retrieving field values.

QSqlRecord is implicitly shared. This means you can make copies of the record in time O(1). If multiple QSqlRecord instances share the same data and one is modifying the record's data then this modifying instance makes a copy and modifies its private copy - thus it does not affect other instances.

See also Database Classes.

Member Function Documentation

QSqlRecord::QSqlRecord ()

Constructs an empty record.

QSqlRecord::QSqlRecord ( const QSqlRecord & other )

Constructs a copy of other.

QSqlRecord::~QSqlRecord () [virtual]

Destroys the object and frees any allocated resources.

void QSqlRecord::append ( const QSqlField & field ) [virtual]

Append a copy of field field to the end of the record.

Reimplemented in QSqlIndex.

void QSqlRecord::clear () [virtual]

Removes all fields from the record.

See also clearValues().

Reimplemented in QSqlCursor.

void QSqlRecord::clearValues ( bool nullify = FALSE ) [virtual]

Clears the value of all fields in the record. If nullify is TRUE, (it's default is FALSE), each field is set to null.

bool QSqlRecord::contains ( const QString & name ) const

Returns TRUE if there is a field in the record called name, otherwise returns FALSE.

uint QSqlRecord::count () const

Returns the number of fields in the record.

QSqlField * QSqlRecord::field ( int i )

Returns a pointer to the field at position i within the record, or 0 if it cannot be found.

QSqlField * QSqlRecord::field ( const QString & name )

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

Returns a pointer to the field with name name within the record, or 0 if it cannot be found. Field names are not case-sensitive.

const QSqlField * QSqlRecord::field ( int i ) const

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

const QSqlField * QSqlRecord::field ( const QString & name ) const

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

Returns a pointer to the field with name name within the record, or 0 if it cannot be found. Field names are not case-sensitive.

QString QSqlRecord::fieldName ( int i ) const

Returns the name of the field at position i. If the field does not exist, QString::null is returned.

void QSqlRecord::insert ( int pos, const QSqlField & field ) [virtual]

Insert a copy of field at position pos. If a field already exists at pos, it is removed.

bool QSqlRecord::isEmpty () const

Returns TRUE if there are no fields in the record, otherwise returns FALSE.

bool QSqlRecord::isGenerated ( const QString & name ) const

Returns TRUE if the field name is to be generated (the default), otherwise returns FALSE. If the field does not exist, FALSE is returned.

See also setGenerated().

bool QSqlRecord::isGenerated ( int i ) const

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

Returns TRUE if the field with the index i is to be generated (the default), otherwise returns FALSE. If the field does not exist, FALSE is returned.

See also setGenerated().

bool QSqlRecord::isNull ( const QString & name )

Returns TRUE if the field name is currently null, otherwise returns FALSE. If the field name doesn't exist the return value is TRUE.

See also position().

bool QSqlRecord::isNull ( int i )

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

Returns TRUE if the field i is currently null, otherwise returns FALSE. If the index i doesn't exist the return value is TRUE.

See also fieldName().

QSqlRecord & QSqlRecord::operator= ( const QSqlRecord & other )

Sets the record equal to other.

int QSqlRecord::position ( const QString & name ) const

Returns the position of the field named name within the record, or -1 if it cannot be found. Field names are not case-sensitive. If more than one field matches, the first one is returned.

void QSqlRecord::remove ( int pos ) [virtual]

Removes the field at pos. If pos does not exist, nothing happens.

Reimplemented in QSqlCursor.

void QSqlRecord::setGenerated ( const QString & name, bool generated ) [virtual]

Sets the generated flag for the field name to generated. If the field does not exist, nothing happens. Only fields that have generated set to TRUE are included in the SQL that is generated, e.g. by QSqlCursor.

See also isGenerated().

Reimplemented in QSqlCursor.

void QSqlRecord::setGenerated ( int i, bool generated ) [virtual]

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

Sets the generated flag for the field i to generated.

See also isGenerated().

Reimplemented in QSqlCursor.

void QSqlRecord::setNull ( int i ) [virtual]

Sets the value of field i to NULL. If the field does not exist, nothing happens.

void QSqlRecord::setNull ( const QString & name ) [virtual]

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

Sets the value of field name to NULL. If the field does not exist, nothing happens.

void QSqlRecord::setValue ( int i, const QVariant & val ) [virtual]

Sets the value of the field at position i to val. If the field does not exist, nothing happens.

Examples: sql/overview/extract/main.cpp, sql/overview/insert/main.cpp, sql/overview/insert2/main.cpp, sql/overview/order2/main.cpp, sql/overview/subclass5/main.cpp, sql/overview/update/main.cpp and sql/sqltable/main.cpp.

void QSqlRecord::setValue ( const QString & name, const QVariant & val ) [virtual]

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

Sets the value of field name to val. If the field does not exist, nothing happens.

QString QSqlRecord::toString ( const QString & prefix = QString::null, const QString & sep = "," ) const [virtual]

Returns a list of all the record's field names as a string separated by sep.

Note that fields which are not generated are not included (see isGenerated() ). The returned string is suitable, for example, for generating SQL SELECT statements. If a prefix is specified, e.g. a table name, all fields are prefixed in the form:

"prefix. <fieldname>"

QStringList QSqlRecord::toStringList ( const QString & prefix = QString::null ) const [virtual]

Returns a list of all the record's field names, each having the prefix prefix.

Note that fields which have generated set to FALSE are not included. (See isGenerated() ). If prefix is supplied, e.g. a table name, all fields are prefixed in the form:

"prefix. <fieldname>"

QVariant QSqlRecord::value ( int i ) const [virtual]

Returns the value of the field located at position i in the record. If field i does not exist the resultant behaviour is undefined.

This function should be used with QSqlQuerys. When working with a QSqlCursor the value(const QString&) overload which uses field names is more appropriate.

Example: sql/overview/update/main.cpp.

QVariant QSqlRecord::value ( const QString & name ) const [virtual]

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

Returns the value of the field named name in the record. If field name does not exist the resultant behaviour is undefined.

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


qsqlrecord.h Include File

qsqlrecord.h

This is the verbatim text of the qsqlrecord.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlRecord class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLRECORD_H
#define QSQLRECORD_H

#ifndef QT_H
#include "qstring.h"
#include "qstringlist.h"
#include "qvariant.h"
#include "qsqlfield.h"
#endif // QT_H

#ifndef QT_NO_SQL

class QSqlRecordPrivate;

class QSqlRecordShared : public QShared
{
public:
    QSqlRecordShared( QSqlRecordPrivate* sqlRecordPrivate )
    : d( sqlRecordPrivate )
    {}
    virtual ~QSqlRecordShared();
    QSqlRecordPrivate* d;
};

class Q_EXPORT QSqlRecord
{
public:
    QSqlRecord();
    QSqlRecord( const QSqlRecord& other );
    QSqlRecord& operator=( const QSqlRecord& other );
    virtual ~QSqlRecord();
    virtual QVariant     value( int i ) const;
    virtual QVariant     value( const QString& name ) const;
    virtual void         setValue( int i, const QVariant& val );
    virtual void         setValue( const QString& name, const QVariant& val );
    bool                 isGenerated( int i ) const;
    bool                 isGenerated( const QString& name ) const;
    virtual void         setGenerated( const QString& name, bool generated );
    virtual void         setGenerated( int i, bool generated );
    virtual void         setNull( int i );
    virtual void         setNull( const QString& name );
    bool                 isNull( int i );
    bool                 isNull( const QString& name );

    int                  position( const QString& name ) const;
    QString              fieldName( int i ) const;
    QSqlField*           field( int i );
    QSqlField*           field( const QString& name );
    const QSqlField*     field( int i ) const;
    const QSqlField*     field( const QString& name ) const;

    virtual void         append( const QSqlField& field );
    virtual void         insert( int pos, const QSqlField& field );
    virtual void         remove( int pos );

    bool                 isEmpty() const;
    bool                 contains( const QString& name ) const;
    virtual void         clear();
    virtual void         clearValues( bool nullify = FALSE );
    uint                 count() const;
    virtual QString      toString( const QString& prefix = QString::null,
                   const QString& sep = "," ) const;
    virtual QStringList  toStringList( const QString& prefix = QString::null ) const;

private:
    QString              createField( int i, const QString& prefix ) const;
    void                 deref();
    bool                 checkDetach();
    QSqlRecordShared*    sh;
};

/******************************************/
/*******     QSqlRecordInfo Class    ******/
/******************************************/

typedef QValueList<QSqlFieldInfo> QSqlFieldInfoList;

class Q_EXPORT QSqlRecordInfo: public QSqlFieldInfoList
{
public:
    QSqlRecordInfo(): QSqlFieldInfoList() {}
    QSqlRecordInfo( const QSqlFieldInfoList& other ): QSqlFieldInfoList( other ) {}
    QSqlRecordInfo( const QSqlRecord& other );

    size_type contains( const QString& fieldName ) const;
    QSqlFieldInfo find( const QString& fieldName ) const;
    QSqlRecord toRecord() const;

};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlRecord Member List

Complete Member List for QSqlRecord

This is the complete list of member functions for QSqlRecord, including inherited members.

  • QSqlRecord()
  • ~QSqlRecord()
  • append()
  • clear()
  • clearValues()
  • contains()
  • count()
  • field()
  • fieldName()
  • insert()
  • isEmpty()
  • isGenerated()
  • isNull()
  • operator=()
  • position()
  • remove()
  • setGenerated()
  • setNull()
  • setValue()
  • toString()
  • toStringList()
  • value()


QSqlRecordInfo Class

QSqlRecordInfo Class Reference
[sql module]

The QSqlRecordInfo class encapsulates a set of database field meta data. More...

#include <qsqlrecord.h>

List of all member functions.

Public Members

  • QSqlRecordInfo ()
  • QSqlRecordInfo ( const QSqlFieldInfoList & other )
  • QSqlRecordInfo ( const QSqlRecord & other )
  • size_type contains ( const QString & fieldName ) const
  • QSqlFieldInfo find ( const QString & fieldName ) const
  • QSqlRecord toRecord () const

Detailed Description

The QSqlRecordInfo class encapsulates a set of database field meta data.

This class is a QValueList that holds a set of database field meta data. Use contains() to see if a given field name exists in the record, and use find() to get a QSqlFieldInfo record for a named field.

See also QValueList, QSqlFieldInfo and Database Classes.

Member Function Documentation

QSqlRecordInfo::QSqlRecordInfo ()

Constructs an empty recordinfo object

QSqlRecordInfo::QSqlRecordInfo ( const QSqlFieldInfoList & other )

Constructs a copy of other.

QSqlRecordInfo::QSqlRecordInfo ( const QSqlRecord & other )

Constructs a QSqlRecordInfo object based on the fields in the QSqlRecord other.

size_type QSqlRecordInfo::contains ( const QString & fieldName ) const

Returns the number of times a field named fieldName occurs in the record. Returns 0 if no field by that name could be found.

QSqlFieldInfo QSqlRecordInfo::find ( const QString & fieldName ) const

Returns a QSqlFieldInfo object for the first field in the record which has the field name fieldName. If no matching field is found then an empty QSqlFieldInfo object is returned.

QSqlRecord QSqlRecordInfo::toRecord () const

Returns an empty QSqlRecord based on the field information in this QSqlRecordInfo.

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


QSqlRecordInfo Member List

Complete Member List for QSqlRecordInfo

This is the complete list of member functions for QSqlRecordInfo, including inherited members.

  • QSqlRecordInfo()
  • contains()
  • find()
  • toRecord()


QSqlResult Class

QSqlResult Class Reference
[sql module]

The QSqlResult class provides an abstract interface for accessing data from SQL databases. More...

#include <qsqlresult.h>

List of all member functions.

Public Members

  • virtual ~QSqlResult ()

Protected Members

  • QSqlResult ( const QSqlDriver * db )
  • int at () const
  • QString lastQuery () const
  • QSqlError lastError () const
  • bool isValid () const
  • bool isActive () const
  • bool isSelect () const
  • bool isForwardOnly () const
  • const QSqlDriver * driver () const
  • virtual void setAt ( int at )
  • virtual void setActive ( bool a )
  • virtual void setLastError ( const QSqlError & e )
  • virtual void setQuery ( const QString & query )
  • virtual void setSelect ( bool s )
  • virtual void setForwardOnly ( bool forward )
  • virtual QVariant data ( int i ) = 0
  • virtual bool isNull ( int i ) = 0
  • virtual bool reset ( const QString & query ) = 0
  • virtual bool fetch ( int i ) = 0
  • virtual bool fetchNext ()
  • virtual bool fetchPrev ()
  • virtual bool fetchFirst () = 0
  • virtual bool fetchLast () = 0
  • virtual int size () = 0
  • virtual int numRowsAffected () = 0

Detailed Description

The QSqlResult class provides an abstract interface for accessing data from SQL databases.

Normally you would use QSqlQuery instead of QSqlResult since QSqlQuery provides a generic wrapper for database-specific implementations of QSqlResult.

See also QSql and Database Classes.

Member Function Documentation

QSqlResult::QSqlResult ( const QSqlDriver * db ) [protected]

Protected constructor which creates a QSqlResult using database db. The object is initialized to an inactive state.

QSqlResult::~QSqlResult () [virtual]

Destroys the object and frees any allocated resources.

int QSqlResult::at () const [protected]

Returns the current (zero-based) position of the result.

QVariant QSqlResult::data ( int i ) [pure virtual protected]

Returns the data for field i (zero-based) as a QVariant. This function is only called if the result is in an active state and is positioned on a valid record and i is non-negative. Derived classes must reimplement this function and return the value of field i, or QVariant() if it cannot be determined.

const QSqlDriver * QSqlResult::driver () const [protected]

Returns the driver associated with the result.

bool QSqlResult::fetch ( int i ) [pure virtual protected]

Positions the result to an arbitrary (zero-based) index i. This function is only called if the result is in an active state. Derived classes must reimplement this function and position the result to the index i, and call setAt() with an appropriate value. Return TRUE to indicate success, FALSE for failure.

bool QSqlResult::fetchFirst () [pure virtual protected]

Positions the result to the first record in the result. This function is only called if the result is in an active state. Derived classes must reimplement this function and position the result to the first record, and call setAt() with an appropriate value. Return TRUE to indicate success, FALSE for failure.

bool QSqlResult::fetchLast () [pure virtual protected]

Positions the result to the last record in the result. This function is only called if the result is in an active state. Derived classes must reimplement this function and position the result to the last record, and call setAt() with an appropriate value. Return TRUE to indicate success, FALSE for failure.

bool QSqlResult::fetchNext () [virtual protected]

Positions the result to the next available record in the result. This function is only called if the result is in an active state. The default implementation calls fetch() with the next index. Derived classes can reimplement this function and position the result to the next record in some other way, and call setAt() with an appropriate value. Return TRUE to indicate success, FALSE for failure.

bool QSqlResult::fetchPrev () [virtual protected]

Positions the result to the previous available record in the result. This function is only called if the result is in an active state. The default implementation calls fetch() with the previous index. Derived classes can reimplement this function and position the result to the next record in some other way, and call setAt() with an appropriate value. Return TRUE to indicate success, FALSE for failure.

bool QSqlResult::isActive () const [protected]

Returns TRUE if the result has records to be retrieved, otherwise returns FALSE.

bool QSqlResult::isForwardOnly () const [protected]

Returns TRUE when you can only scroll forward through a result set otherwise FALSE

bool QSqlResult::isNull ( int i ) [pure virtual protected]

Returns TRUE if the field at position i is NULL, otherwise returns FALSE.

bool QSqlResult::isSelect () const [protected]

Returns TRUE if the current result is from a SELECT statement, otherwise returns FALSE.

bool QSqlResult::isValid () const [protected]

Returns TRUE if the result is positioned on a valid record (that is, the result is not positioned before the first or after the last record); otherwise returns FALSE.

QSqlError QSqlResult::lastError () const [protected]

Returns the last error associated with the result.

QString QSqlResult::lastQuery () const [protected]

Returns the current SQL query text, or QString::null if there is none.

int QSqlResult::numRowsAffected () [pure virtual protected]

Returns the number of rows affected by the last query executed.

bool QSqlResult::reset ( const QString & query ) [pure virtual protected]

Sets the result to use the SQL statement query for subsequent data retrieval. Derived classes must reimplement this function and apply the query to the database. This function is called only after the result is set to an inactive state and is positioned before the first record of the new result. Derived classes should return TRUE if the query was successful and ready to be used, FALSE otherwise.

void QSqlResult::setActive ( bool a ) [virtual protected]

Protected function provided for derived classes to set the internal active state to the value of a.

See also isActive().

void QSqlResult::setAt ( int at ) [virtual protected]

Protected function provided for derived classes to set the internal (zero-based) result index to at.

See also at().

void QSqlResult::setForwardOnly ( bool forward ) [virtual protected]

Sets forward only mode to forward. If forward is TRUE only fetchNext() is allowed for navigating the results. Forward only mode needs far less memory since results do not have to be cached. forward only mode is off by default.

See also fetchNext().

void QSqlResult::setLastError ( const QSqlError & e ) [virtual protected]

Protected function provided for derived classes to set the last error to the value of e.

See also lastError().

void QSqlResult::setQuery ( const QString & query ) [virtual protected]

Sets the current query for the result to query. The result must be reset() in order to execute the query on the database.

void QSqlResult::setSelect ( bool s ) [virtual protected]

Protected function provided for derived classes to indicate whether or not the current statement is an SQL SELECT statement. The s parameter should indicate TRUE if the statement is a SELECT statement, otherwise FALSE.

int QSqlResult::size () [pure virtual protected]

Returns the size of the result or -1 if it cannot be determined.

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


qsqlresult.h Include File

qsqlresult.h

This is the verbatim text of the qsqlresult.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QSqlResult class
**
** Created : 2000-11-03
**
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of the sql module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSQLRESULT_H
#define QSQLRESULT_H

#ifndef QT_H
#include "qstring.h"
#include "qvariant.h"
#include "qsqlerror.h"
#include "qsqlfield.h"
#include "qsql.h"
#endif // QT_H

#if !defined( QT_MODULE_SQL ) || defined( QT_LICENSE_PROFESSIONAL )
#define QM_EXPORT_SQL
#else
#define QM_EXPORT_SQL Q_EXPORT
#endif

#ifndef QT_NO_SQL

class QSqlDriver;
class QSql;
class QSqlResultInfo;
class QSqlResultPrivate;

class QM_EXPORT_SQL QSqlResult
{
friend class QSqlQuery;
friend class QSqlResultShared;
public:
    virtual ~QSqlResult();
protected:
    QSqlResult(const QSqlDriver * db );
    int		    at() const;
    QString         lastQuery() const;
    QSqlError       lastError() const;
    bool            isValid() const;
    bool            isActive() const;
    bool            isSelect() const;
    bool            isForwardOnly() const;
    const QSqlDriver* driver() const;
    virtual void    setAt( int at );
    virtual void    setActive( bool a );
    virtual void    setLastError( const QSqlError& e );
    virtual void    setQuery( const QString& query );
    virtual void    setSelect( bool s );
    virtual void    setForwardOnly( bool forward );

    virtual QVariant data( int i ) = 0;
    virtual bool    isNull( int i ) = 0;
    virtual bool    reset ( const QString& sqlquery ) = 0;
    virtual bool    fetch( int i ) = 0;
    virtual bool    fetchNext();
    virtual bool    fetchPrev();
    virtual bool    fetchFirst() = 0;
    virtual bool    fetchLast() = 0;
    virtual int     size() = 0;
    virtual int     numRowsAffected() = 0;
private:
    QSqlResultPrivate* d;
    bool forwardOnly;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QSqlResult( const QSqlResult & );
    QSqlResult &operator=( const QSqlResult & );
#endif

};

#endif	// QT_NO_SQL
#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QSqlResult Member List

Complete Member List for QSqlResult

This is the complete list of member functions for QSqlResult, including inherited members.

  • QSqlResult()
  • ~QSqlResult()
  • at()
  • data()
  • driver()
  • fetch()
  • fetchFirst()
  • fetchLast()
  • fetchNext()
  • fetchPrev()
  • isActive()
  • isForwardOnly()
  • isNull()
  • isSelect()
  • isValid()
  • lastError()
  • lastQuery()
  • numRowsAffected()
  • reset()
  • setActive()
  • setAt()
  • setForwardOnly()
  • setLastError()
  • setQuery()
  • setSelect()
  • size()


QStatusBar类

QStatusBar类参考

QStatusBar类提供了一个适合呈现状态信息的水平条。 详情请见……

#include <qstatusbar.h>

Inherits QWidget。

所有成员函数的列表。

公有成员

  • QStatusBar ( QWidget * parent = 0, const char * name = 0 )
  • virtual ~QStatusBar ()
  • virtual void addWidget ( QWidget * widget, int stretch = 0, bool permanent = FALSE )
  • virtual void removeWidget ( QWidget * widget )
  • void setSizeGripEnabled ( bool )
  • bool isSizeGripEnabled () const

公有槽

  • void message ( const QString & message )
  • void message ( const QString & message, int ms )
  • void clear ()

属性

  • bool sizeGripEnabled - 在状态条右下方的QSizeGrip是否有效

保护成员

  • virtual void paintEvent ( QPaintEvent * )
  • void reformat ()
  • void hideOrShow ()

详细描述

QStatusBar类提供了一个适合呈现状态信息的水平条。

每一个状态指示器都会落在下面这三种类别之内：

  • 临时的 - 暂时地占用状态条的大部分。例如，用于解释工具提示文本或者菜单条目。
  • 正常的 - 占用状态条的一部分并且也可能被临时的信息隐藏。例如，用于在字处理器中显示页数和行数。
  • 永久的 - 从不被隐藏。用于重要的模式指示，例如，一些程序把大小写指示器放在状态条中。

QStatusBar让你能够显示上述所有类型的指示信息。

为了显示临时的消息，请调用message()（可以把一个合适的信号和它连接起来）。如果要移除一个临时的消息，调用clear()。这里有两类消息：一类消息一直显示到下一个clear()或mesage()被调用才消失，并且另一种是有时间限制的：

     connect( loader, SIGNAL(progressMessage(const QString&)),
              statusBar(), SLOT(message(const QString&)) );

     statusBar()->message("Loading...");  // 初始消息
     loader.loadStuff();                  // 发射进程消息
     statusBar()->message("Done.", 2000); // 显示2秒的最后消息

正常的和永久的消息通过创建一个小窗口部件并且然后通过addWidget()把它添加到状态条中来被显示。QLabel、QProgressBar或者甚至QToolButton这些窗口部件对于添加到状态条都是很有用的。removeWidget()用于移除窗口部件。

     statusBar()->addWidget(new MyReadWriteIndication(statusBar()));

默认情况下，QStatusBar在右下角提供了一个QSizeGrip。你可以使用setSizeGripEnabled(FALSE)来使它失效。

也可以参考QToolBar、QMainWindow、QLabel、图形用户界面设计手册：状态条、主窗口和相关类和帮助系统。

成员函数文档

QStatusBar::QStatusBar ( QWidget * parent = 0, const char * name = 0 )

构造一个父对象为parent、名称为name并且有一个大小控制的状态条。

也可以参考sizeGripEnabled。

QStatusBar::~QStatusBar () [虚]

销毁这个状态条并且释放任何已经分配的资源和子窗口部件。

void QStatusBar::addWidget ( QWidget * widget, int stretch = 0, bool permanent = FALSE ) [虚]

把widget添加到这个状态条。

如果permanent为真，widget就是永久可视的并且如果permanent为假，它也可以被临时的消息遮挡。默认为假。

如果permanent为真，widget被定位在状态条的最右面。如果permanent为假（默认），widget被调节到第一个永久窗口部件的左面。

stretch用于在状态条变大或者变小时为widget计算一个合适的大小。默认为0是指使用最小的空间。

这个函数可以导致一些闪烁。

也可以参考removeWidget()。

void QStatusBar::clear () [槽]

移除正在被显示的任何临时的消息。

也可以参考message()。

void QStatusBar::hideOrShow () [保护]

确保右面的窗口部件是可视的。被message()和clear()使用。

bool QStatusBar::isSizeGripEnabled () const

如果在状态条右下方的QSizeGrip是生效的，返回真，否则返回假。详细情况请参考“sizeGripEnabled”属性。

void QStatusBar::message ( const QString & message ) [槽]

隐藏正常状态指示器并且显示message，直到clear()或者另一个message()被调用。

也可以参考clear()。

void QStatusBar::message ( const QString & message, int ms ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

隐藏正常状态指示器并且显示messagems毫秒，或者直到clear()或者另一个message()被调用，看哪一个先发生了。

void QStatusBar::paintEvent ( QPaintEvent * ) [虚 保护]

如果适当，显示临时的消息。

从QWidget中重新实现。

void QStatusBar::reformat () [保护]

改变状态条的外观来说明项的变化。特殊的子类可能需要这个，但是几何形状管理将通常要注意任何需要的重新整理。

void QStatusBar::removeWidget ( QWidget * widget ) [虚]

从状态条中移除widget。

这个函数可能导致一些闪烁。

注意widget没有被删除。

也可以参考addWidget()。

void QStatusBar::setSizeGripEnabled ( bool )

设置在状态条右下方的QSizeGrip是否生效。详细情况请参考“sizeGripEnabled”属性。

属性文档

bool sizeGripEnabled

这个属性保存的是在状态条右下方的QSizeGrip是否有效。

可以让状态条右下方的QSizeGrip生效或者失效。默认它是生效的。

通过setSizeGripEnabled()设置属性值并且通过isSizeGripEnabled()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qstatusbar.h包含文件

qstatusbar.h

这里是qstatusbar.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qstatusbar.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QStatusBar class
**
** Created : 980316
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTATUSBAR_H
#define QSTATUSBAR_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_STATUSBAR

class QStatusBarPrivate;

class Q_EXPORT QStatusBar: public QWidget
{
    Q_OBJECT
    Q_PROPERTY( bool sizeGripEnabled READ isSizeGripEnabled WRITE setSizeGripEnabled )

public:
    QStatusBar( QWidget* parent=0, const char* name=0 );
    virtual ~QStatusBar();

    virtual void addWidget( QWidget *, int stretch = 0, bool = FALSE );
    virtual void removeWidget( QWidget * );

    void setSizeGripEnabled(bool);
    bool isSizeGripEnabled() const;

public slots:
    void message( const QString &);
    void message( const QString &, int );
    void clear();

protected:
    void paintEvent( QPaintEvent * );
    void resizeEvent( QResizeEvent * );

    void reformat();
    void hideOrShow();
    bool event( QEvent *);

private:
    QStatusBarPrivate * d;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QStatusBar( const QStatusBar & );
    QStatusBar& operator=( const QStatusBar & );
#endif
};

#endif // QT_NO_STATUSBAR

#endif // QSTATUSBAR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QStatusBar成员列表

完整的QStatusBar成员列表

这里是QStatusBar成员函数的完整列表，包括继承的成员。

  • QStatusBar()
  • ~QStatusBar()
  • acceptDrops()
  • addWidget()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • hideOrShow()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • message()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reformat()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeWidget()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QStoredDrag Class

QStoredDrag Class Reference

The QStoredDrag class provides a simple stored-value drag object for arbitrary MIME data. More...

#include <qdragobject.h>

Inherits QDragObject.

Inherited by QUriDrag and QColorDrag.

List of all member functions.

Public Members

  • QStoredDrag ( const char * mimeType, QWidget * dragSource = 0, const char * name = 0 )
  • ~QStoredDrag ()
  • virtual void setEncodedData ( const QByteArray & encodedData )
  • virtual QByteArray encodedData ( const char * m ) const

Detailed Description

The QStoredDrag class provides a simple stored-value drag object for arbitrary MIME data.

When a block of data has only one representation, you can use a QStoredDrag to hold it.

For more information about drag and drop, see the QDragObject class and the drag and drop documentation.

See also Drag And Drop Classes.

Member Function Documentation

QStoredDrag::QStoredDrag ( const char * mimeType, QWidget * dragSource = 0, const char * name = 0 )

Constructs a QStoredDrag. The dragSource and name are passed to the QDragObject constructor, and the format is set to mimeType.

The data will be unset. Use setEncodedData() to set it.

QStoredDrag::~QStoredDrag ()

Destroys the drag object and frees up all allocated resources.

QByteArray QStoredDrag::encodedData ( const char * m ) const [virtual]

Returns the stored data. m contains the data's format.

See also setEncodedData().

Reimplemented from QMimeSource.

void QStoredDrag::setEncodedData ( const QByteArray & encodedData ) [virtual]

Sets the encoded data of this drag object to encodedData. The encoded data is what's delivered to the drop sites. It must be in a strictly defined and portable format.

The drag object can't be dropped (by the user) until this function has been called.

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


QStoredDrag Member List

Complete Member List for QStoredDrag

This is the complete list of member functions for QStoredDrag, including inherited members.

  • QStoredDrag()
  • ~QStoredDrag()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setEncodedData()
  • setName()
  • setPixmap()
  • setProperty()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


QStrIList Class

QStrIList Class Reference

The QStrIList class provides a doubly-linked list of char* with case-insensitive comparison. More...

#include <qstrlist.h>

Inherits QStrList.

List of all member functions.

Public Members

  • QStrIList ( bool deepCopies = TRUE )
  • ~QStrIList ()

Detailed Description

The QStrIList class provides a doubly-linked list of char* with case-insensitive comparison.

This class is a QPtrList<char> instance (a list of char*).

QStrIList is identical to QStrList except that the virtual compareItems() function is reimplemented to compare strings case-insensitively. The inSort() function inserts strings in a sorted order. In general it is fastest to insert the strings as they come and sort() at the end; inSort() is useful when you just have to add a few extra strings to an already sorted list.

The QStrListIterator class works for QStrIList.

See also Collection Classes and Non-GUI Classes.

Member Function Documentation

QStrIList::QStrIList ( bool deepCopies = TRUE )

Constructs a list of strings. Will make deep copies of all inserted strings if deepCopies is TRUE, or use shallow copies if deepCopies is FALSE.

QStrIList::~QStrIList ()

Destroys the list. All strings are removed.

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


QStrIList Member List

Complete Member List for QStrIList

This is the complete list of member functions for QStrIList, including inherited members.

  • QStrIList()
  • ~QStrIList()
  • append()
  • at()
  • autoDelete()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • current()
  • currentNode()
  • deleteItem()
  • find()
  • findNext()
  • findNextRef()
  • findRef()
  • first()
  • getFirst()
  • getLast()
  • inSort()
  • insert()
  • isEmpty()
  • last()
  • newItem()
  • next()
  • operator=()
  • operator==()
  • prepend()
  • prev()
  • read()
  • remove()
  • removeFirst()
  • removeLast()
  • removeNode()
  • removeRef()
  • setAutoDelete()
  • sort()
  • take()
  • takeNode()
  • toVector()
  • write()


QString类

QString类参考

QString类提供了一个Unicode文本和经典的C以零结尾的字符数组的抽象。 详情请见……

#include <qstring.h>

所有成员函数的列表。

公有成员

  • QString ()
  • QString ( QChar ch )
  • QString ( const QString & s )
  • QString ( const QByteArray & ba )
  • QString ( const QChar * unicode, uint length )
  • QString ( const char * str )
  • ~QString ()
  • QString & operator= ( const QString & s )
  • QString & operator= ( const char * str )
  • QString & operator= ( const QCString & cs )
  • QString & operator= ( QChar c )
  • QString & operator= ( char c )
  • bool isNull () const
  • bool isEmpty () const
  • uint length () const
  • void truncate ( uint newLen )
  • QString & fill ( QChar c, int len = -1 )
  • QString copy () const (obsolete)
  • QString arg ( long a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( ulong a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( int a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( uint a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( short a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( ushort a, int fieldwidth = 0, int base = 10 ) const
  • QString arg ( char a, int fieldwidth = 0 ) const
  • QString arg ( QChar a, int fieldwidth = 0 ) const
  • QString arg ( const QString & a, int fieldwidth = 0 ) const
  • QString arg ( double a, int fieldwidth = 0, char fmt = 'g', int prec = -1 ) const
  • QString & sprintf ( const char * cformat, ... )
  • int find ( QChar c, int index = 0, bool cs = TRUE ) const
  • int find ( char c, int index = 0, bool cs = TRUE ) const
  • int find ( const QString & str, int index = 0, bool cs = TRUE ) const
  • int find ( const QRegExp & rx, int index = 0 ) const
  • int find ( const char * str, int index = 0 ) const
  • int findRev ( QChar c, int index = -1, bool cs = TRUE ) const
  • int findRev ( char c, int index = -1, bool cs = TRUE ) const
  • int findRev ( const QString & str, int index = -1, bool cs = TRUE ) const
  • int findRev ( const QRegExp & rx, int index = -1 ) const
  • int findRev ( const char * str, int index = -1 ) const
  • int contains ( QChar c, bool cs = TRUE ) const
  • int contains ( char c, bool cs = TRUE ) const
  • int contains ( const char * str, bool cs = TRUE ) const
  • int contains ( const QString & str, bool cs = TRUE ) const
  • int contains ( const QRegExp & rx ) const
  • enum SectionFlags { SectionDefault = 0x00, SectionSkipEmpty = 0x01, SectionIncludeLeadingSep = 0x02, SectionIncludeTrailingSep = 0x04, SectionCaseInsensitiveSeps = 0x08 }
  • QString section ( QChar sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const
  • QString section ( char sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const
  • QString section ( const char * sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const
  • QString section ( const QString & sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const
  • QString section ( const QRegExp & reg, int start, int end = 0xffffffff, int flags = SectionDefault ) const
  • QString left ( uint len ) const
  • QString right ( uint len ) const
  • QString mid ( uint index, uint len = 0xffffffff ) const
  • QString leftJustify ( uint width, QChar fill = ' ', bool truncate = FALSE ) const
  • QString rightJustify ( uint width, QChar fill = ' ', bool truncate = FALSE ) const
  • QString lower () const
  • QString upper () const
  • QString stripWhiteSpace () const
  • QString simplifyWhiteSpace () const
  • QString & insert ( uint index, const QString & s )
  • QString & insert ( uint index, const QChar * s, uint len )
  • QString & insert ( uint index, QChar c )
  • QString & insert ( uint index, char c )
  • QString & append ( char ch )
  • QString & append ( QChar ch )
  • QString & append ( const QString & str )
  • QString & prepend ( char ch )
  • QString & prepend ( QChar ch )
  • QString & prepend ( const QString & s )
  • QString & remove ( uint index, uint len )
  • QString & replace ( uint index, uint len, const QString & s )
  • QString & replace ( uint index, uint len, const QChar * s, uint slen )
  • QString & replace ( const QRegExp & rx, const QString & str )
  • short toShort ( bool * ok = 0, int base = 10 ) const
  • ushort toUShort ( bool * ok = 0, int base = 10 ) const
  • int toInt ( bool * ok = 0, int base = 10 ) const
  • uint toUInt ( bool * ok = 0, int base = 10 ) const
  • long toLong ( bool * ok = 0, int base = 10 ) const
  • ulong toULong ( bool * ok = 0, int base = 10 ) const
  • float toFloat ( bool * ok = 0 ) const
  • double toDouble ( bool * ok = 0 ) const
  • QString & setNum ( short n, int base = 10 )
  • QString & setNum ( ushort n, int base = 10 )
  • QString & setNum ( int n, int base = 10 )
  • QString & setNum ( uint n, int base = 10 )
  • QString & setNum ( long n, int base = 10 )
  • QString & setNum ( ulong n, int base = 10 )
  • QString & setNum ( float n, char f = 'g', int prec = 6 )
  • QString & setNum ( double n, char f = 'g', int prec = 6 )
  • void setExpand ( uint index, QChar c ) (obsolete)
  • QString & operator+= ( const QString & str )
  • QString & operator+= ( QChar c )
  • QString & operator+= ( char c )
  • QChar at ( uint i ) const
  • QChar operator[] ( int i ) const
  • QCharRef at ( uint i )
  • QCharRef operator[] ( int i )
  • QChar constref ( uint i ) const
  • QChar & ref ( uint i )
  • const QChar * unicode () const
  • const char * ascii () const (obsolete)
  • const char * latin1 () const
  • QCString utf8 () const
  • QCString local8Bit () const
  • bool operator! () const
  • operator const char * () const
  • QString & setUnicode ( const QChar * unicode, uint len )
  • QString & setUnicodeCodes ( const ushort * unicode_as_ushorts, uint len )
  • QString & setLatin1 ( const char * str, int len = -1 )
  • int compare ( const QString & s ) const
  • int localeAwareCompare ( const QString & s ) const
  • void compose ()
  • const char * data () const (obsolete)
  • bool startsWith ( const QString & s ) const
  • bool endsWith ( const QString & s ) const
  • void setLength ( uint newLen )

静态公有成员

  • QString number ( long n, int base = 10 )
  • QString number ( ulong n, int base = 10 )
  • QString number ( int n, int base = 10 )
  • QString number ( uint n, int base = 10 )
  • QString number ( double n, char f = 'g', int prec = 6 )
  • QString fromLatin1 ( const char * chars, int len = -1 )
  • QString fromUtf8 ( const char * utf8, int len = -1 )
  • QString fromLocal8Bit ( const char * local8Bit, int len = -1 )
  • int compare ( const QString & s1, const QString & s2 )
  • int localeAwareCompare ( const QString & s1, const QString & s2 )

相关函数

  • bool operator== ( const QString & s1, const QString & s2 )
  • bool operator== ( const QString & s1, const char * s2 )
  • bool operator== ( const char * s1, const QString & s2 )
  • bool operator!= ( const QString & s1, const QString & s2 )
  • bool operator!= ( const QString & s1, const char * s2 )
  • bool operator!= ( const char * s1, const QString & s2 )
  • bool operator< ( const QString & s1, const char * s2 )
  • bool operator< ( const char * s1, const QString & s2 )
  • bool operator<= ( const QString & s1, const char * s2 )
  • bool operator<= ( const char * s1, const QString & s2 )
  • bool operator> ( const QString & s1, const char * s2 )
  • bool operator> ( const char * s1, const QString & s2 )
  • bool operator>= ( const QString & s1, const char * s2 )
  • bool operator>= ( const char * s1, const QString & s2 )
  • const QString operator+ ( const QString & s1, const QString & s2 )
  • const QString operator+ ( const QString & s1, const char * s2 )
  • const QString operator+ ( const char * s1, const QString & s2 )
  • const QString operator+ ( const QString & s, char c )
  • const QString operator+ ( char c, const QString & s )
  • QDataStream & operator<< ( QDataStream & s, const QString & str )
  • QDataStream & operator>> ( QDataStream & s, QString & str )

详细描述

QString类提供了一个Unicode文本和经典的C以零结尾的字符数组的抽象。

QString使用隐含共享，这使它非常有效率并且很容易使用。

所有的QString的方法都使用const char *参数，const char *被解释为经典的C风格的以零结尾的ASCII字符串。所以const char *参数为0是合法的。如果const char *不是以零结尾的，结果是不确定的。把经典的C字符串复制到QString的函数将不会复制结尾的0字符。QString的QChar数组（可以通过unicode()返回）通常不以零结尾。如果你需要把QString传递到一个需要C的以零结尾的字符串，请使用latin1()。

没有分配任何东西的QString是零，也就是长度和数据指针都为0。引用空字符串（“”，一个单一的'\0'字符）的QString是空。零和空这两个QString在方法中都是合法的。把(const char *) 0赋值给QString给定了一个零QString。为了方便，QString::null是一个零QString。当排序的时候，空字符串在最前面，然后是非空字符串，然后才是零字符串。我们建议使用if ( !str.isNull() )，而不是if ( !str )来检测非零字符串，关于解释说明也可以参考operator!()。

注意如果你发现你正在混合使用QCString、QString和QByteArray，这将会导致很多不必要的复制并且也许会预示着你正在处理的真实自然数据是不确定的。如果数据是以零结尾的八位数据，请使用QCString；如果它是没有结尾的（也就是包含0）八位数据，请使用QByteArray；如果它是文本，请使用QString。

字符串列表可以使用QStringList类来处理。你可以使用QStringList::split()来把一个字符串分割为一个字符串列表，并且可以使用QStringList::join()把一个字符串列表连接成一个使用随意间隔符的字符串。你也可以使用QStringList::grep()从一个字符串列表中获得包含特定子字符串或者包含匹配特定的regex的字符串列表。

C程序员的注意事项

由于C++的类型系统和QString是隐含共享的事实，QString也许会被看做整型或者其它简单基本类型。例如：

    QString boolToString( bool b )
    {
        QString result;
        if ( b )
            result = "True";
        else
            result = "False";
        return result;
    }

变量result是一个分配在栈中的自动变量。当return被调用时，因为我们正在返回值，复制构造函数被调用并且这个字符串的一个复制被返回。（我们要感谢隐含共享，没有实际的复制发生，请看下面。）

在Qt的源代码中，你将会遇到想这样的QString的用法：

    QString func( const QString& input )
    {
        QString output = input;
        // 处理输出
        return output;
    }

从input到output的“复制”几乎和复制指针一样快，因为后面的场景复制是通过增加引用计数器来实现的。QString操作是基于写时复制的，只有在实例发生实际改变时，才会被复制。

如果你想不丢失任何Unicode信息的情况下创建一个QString的深度复制，那么你应该使用QString中用QChar*作为参数的构造函数。例如：

    QString a("abcd");
    QString b( a.unicode(), b.length() );

另外，使用QString中用const char*参数的构造函数就足够了。例如：

    QString a("abcd");
    QString b( a.latin1() );

也可以参考QChar、QCString、QByteArray、QConstString、隐含和明显共享类、文本相关类和非图形用户界面类。

成员类型文档

QString::SectionFlags

  • QString::SectionDefault - 空的部分被考虑，开始的和结尾的分隔符不被包含并且区分大小写来比较分隔符。
  • QString::SectionSkipEmpty - 把空的部分看做就像它们不存在一样，也就是说它们不被考虑为有关的start和end。
  • QString::SectionIncludeLeadingSep - 在结果字符串中包含开始的分隔符（如果有的话）。
  • QString::SectionIncludeTrailingSep - 在结果字符串中包含末尾的分隔符（如果有的话）。
  • QString::SectionCaseInsensitiveSeps - 不区分大小写来比较分隔符。

最后的四个值可以被或运算在一起来形成一个标记。

也可以参考section()。

成员函数文档

QString::QString ()

构造一个零字符串。这是一个不被分配任何东西的字符串，也就是说长度和数据指针都为0。

也可以参考isNull()。

QString::QString ( QChar ch )

构造一个长度为一个字符，内容为给定字符ch的字符串。

QString::QString ( const QString & s )

构造一个s的隐含共享的复制。这是短时间的，因为引用计数被使用。

QString::QString ( const QByteArray & ba )

构造一个被解释为经典C字符串的ba的深度复制的字符串。

QString::QString ( const QChar * unicode, uint length )

构造一个QChar数组中开始length个字符的深度复制的字符串。

如果unicode和length为0，那么一个零字符串被创建。

如果只是unicode为0，字符串为空，但是被分配为length个字符空间——无论如何QString可以自动扩展，但是这也许会在一些情况下提高速度。我们建议根据这个目的使用简单的构造函数和setLength()，因为它的结果是有更多的可读代码。

也可以参考isNull()和setLength()。

QString::QString ( const char * str )

构造一个被解释为经典C字符串的str的深度复制的字符串。

如果str，那么一个零字符串被创建。

这是一个抛出构造函数，但是它是完全安全的：把一个Latin1的const char*转化到QString保存了所有的信息。当你编译你的应用程序时，你可以通过定义QT_NO_CAST_ASCII来关闭这个构造函数。你可以使用setLatin1()、fromLatin1()、fromLocal8Bit()和fromUtf8()来生成QString。或者无论什么适合你的八位数据的编码方式。

也可以参考isNull()。

QString::~QString ()

销毁这个字符串并且如果这是这个字符串的最后一个复制，就释放“真实的”字符串。

QString & QString::append ( const QString & str )

把str添加到字符串中并且返回结果的引用。

    string = "Test";
    string.append( "ing" );        // string == "Testing"

等于operator+=()。

实例：dirview/dirview.cpp。

QString & QString::append ( char ch )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把字符ch添加到字符串中并且返回结果的引用。

等于operator+=()。

QString & QString::append ( QChar ch )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把字符ch添加到字符串中并且返回结果的引用。

等于operator+=()。

QString QString::arg ( const QString & a, int fieldwidth = 0 ) const

这个函数将返回使用a来替换最低层出现的%i（i为'1'或'2'或……'9'）的字符串。

fieldwidth值指定了填充到a中的最小空间。正值将产生右对齐文本，负值将产生左对齐文本。

    QString firstName( "Joe" );
    QString lastName( "Bloggs" );
    QString fullName;
    fullName = QString( "First name is '%1', last name is '%2'" )
               .arg( firstName )
               .arg( lastName );

    // fullName == First name is 'Joe', last name is 'Bloggs'

警告：如果你是用arg()来构造一个想上面实例中的“真正”的句子，那么这可能导致一些翻译的问题（当你使用tr()函数时）。

如果没有%i模式，一个警告信息（qWarning()）被输出并且这个文本被添加到字符串的末尾。这被做为错误恢复的功能并且不应该在正确的代码中出现。

也可以参考QObject::tr()。

QString QString::arg ( long a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

fieldwidth值指定了填充到a中的最小空间。正值将产生右对齐文本，负值将产生左对齐文本。

a被基于base表示，默认为10，并且必须在2到36之间。

    QString str;
    str = QString( "Decimal 63 is %1 in hexadecimal" )
          .arg( 63, 0, 16 );
    // str == "Decimal 63 is 3f in hexadecimal"

QString QString::arg ( ulong a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被基于base表示，默认为10，并且必须在2到36之间。

QString QString::arg ( int a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被基于base表示，默认为10，并且必须在2到36之间。

QString QString::arg ( uint a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被基于base表示，默认为10，并且必须在2到36之间。

QString QString::arg ( short a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被基于base表示，默认为10，并且必须在2到36之间。

QString QString::arg ( ushort a, int fieldwidth = 0, int base = 10 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被基于base表示，默认为10，并且必须在2到36之间。

QString QString::arg ( char a, int fieldwidth = 0 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

a被假设在Latin1字符集中。

QString QString::arg ( QChar a, int fieldwidth = 0 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

QString QString::arg ( double a, int fieldwidth = 0, char fmt = 'g', int prec = -1 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

根据fmt指定的格式，参数a被格式化，g为默认情况并且可以为下列之一：

  • e - 格式化为[-]9.9e[+|-]999
  • E - 格式化为[-]9.9E[+|-]999
  • f - 格式化为[-]9.9
  • g - 使用e或f格式，看哪一个更简练
  • G - 使用E或f格式，看哪一个更简练

在所有的情况下，小数点之后数字的个数等于prec指定的精度。

    double d = 12.34;
    QString ds = QString( "'E' format, precision 3, gives %1" )
                 .arg( d, 0, 'E', 3 );
    // ds == "1.234E+001"

const char * QString::ascii () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数简单的调用latin1()并且返回结果。

实例：network/networkprotocol/nntp.cpp。

QChar QString::at ( uint i ) const

返回在索引i处的字符，或者如果i超过字符串的长度返回0。

    const QString string( "abcdefgh" );
    QChar ch = string.at( 4 );
    // ch == 'e'

如果QString不是常量（也就是const QString）或者const&（也就是const QString&），那么at()的非常量重载将被用来替代。

QCharRef QString::at ( uint i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数返回在索引i处的字符的引用。这个结果引用在这之后可以被分配，或者立即使用，但是一旦超过原字符串进行根多的修改，它将会变为无效。

如果i超过了字符串的长度，那么这个字符串将会被使用QChar::null扩大。

int QString::compare ( const QString & s1, const QString & s2 ) [静态]

对s1和s2进行词典比较，如果s1小于、等于或者大于s2，就返回小于、等于或者大于0的整数。

这个比较是专有的基于字符的数字Unicode值并且非常快，但是不是人们所期待的。排序用户界面字符串请考虑使用QString::localeAwareCompare()。

    int a = QString::compare( "def", "abc" );   // a > 0
    int b = QString::compare( "abc", "def" );   // b < 0
    int c = QString::compare(" abc", "abc" );   // c == 0

int QString::compare ( const QString & s ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

对这个字符串和s进行词典比较，如果它小于、等于或者大于s，就返回小于、等于或者大于0的整数。

void QString::compose ()

注意这个函数在Qt 3.0中不被支持并且仅仅用于实验和说明目的。它主要是关注于阿拉伯的和其它多成分文本的实验。

适用于可能带连字的QString。当多成分文本需要表现缺乏象形字的字体时非常有用，但是它也可以制造像QChar(0x0041)（'A'）和QChar(0x0308)（Unicode accent diaresis），给定的QChar(0x00c4)（德语的A元音变音）。

QChar QString::constref ( uint i ) const

返回在索引i处的QChar的值。

等于at(i)。

也可以参考ref()。

int QString::contains ( QChar c, bool cs = TRUE ) const

返回在这个字符串中字符c出现的次数。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

    QString string( "Trolltech and Qt" );
    int i = string.contains( 't', FALSE );  // i == 3

实例：fileiconview/qfileiconview.cpp和mdi/application.cpp。

int QString::contains ( char c, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

int QString::contains ( const char * str, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回在这个字符串中字符串str出现的次数。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

int QString::contains ( const QString & str, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回在这个字符串中str出现的次数。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

这个函数计算重叠的字符串，所以在下面的实例中，“bananas”中有两个“ana”的实例。

    QString str( "bananas" );
    int i = str.contains( "ana" );  // i == 2

也可以参考findRev()。

int QString::contains ( const QRegExp & rx ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回在字符串中正则表达式rx出现的次数。

这个函数计算重叠的字符串，所以在下面的实例中，有四个“ana”或者“ama”的实例。

    QString str = "banana and panama";
    QRegExp rxp = QRegExp( "a[nm]a", TRUE, FALSE );
    int i = str.contains( rxp );    // i == 4

也可以参考find()和findRev()。

QString QString::copy () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

在Qt 2.0和以后的版本中，对这个函数的所有调用都是不需要的。只要移除它们就可以了。

const char * QString::data () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

返回以零结尾的经典的C字符串的指针。

在Qt 1.x中，这将返回按自己顺序允许直接维护的字符串的char*。在Qt 2.x中，QString是一个Unicode字符串，char*变换构造了一个临时字符串，并且因此直接字符处理是没有意义的了。

bool QString::endsWith ( const QString & s ) const

如果字符串以s结尾，返回真，否则返回假。

也可以参考startsWith()。

实例：chart/main.cpp。

QString & QString::fill ( QChar c, int len = -1 )

填充字符串为len个字符的值c，并且返回字符串的引用。

如果len为负数（默认），当前字符串长度被使用。

    QString str;
    str.fill( 'g', 5 );      // string == "ggggg"

int QString::find ( const QRegExp & rx, int index = 0 ) const

从位置index开始，找到常量正则表达式 rx第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。（对于反向搜索也可以参考findRev()。）

返回rx第一次出现的位置，如果rx没有被找到，返回-1。

    QString string( "bananas" );
    int i = string.find( QRegExp("an"), 0 );    // i == 1

也可以参考findRev()、replace()和contains()。

实例：network/mail/smtp.cpp。

int QString::find ( QChar c, int index = 0, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始，找到字符c第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。（对于反向搜索也可以参考findRev()。）

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

返回c第一次出现的位置，如果c没有被找到，返回-1。

int QString::find ( char c, int index = 0, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始，找到字符c第一次出现的位置。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

int QString::find ( const QString & str, int index = 0, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始，找到字符串str第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。（对于反向搜索也可以参考findRev()。）

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

返回str第一次出现的位置，如果str没有被找到，返回-1。

int QString::find ( const char * str, int index = 0 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

等于find(QString(str), index)。

int QString::findRev ( const char * str, int index = -1 ) const

等于findRev(QString(str), index)。

int QString::findRev ( QChar c, int index = -1, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始并且反向搜索，找到字符c第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。

返回c第一次出现的位置，如果c没有被找到，返回-1。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

    QString string( "bananas" );
    int i = string.findRev( 'a' );      // i == 5

int QString::findRev ( char c, int index = -1, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始并且反向搜索，找到字符c第一次出现的位置。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

int QString::findRev ( const QString & str, int index = -1, bool cs = TRUE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始并且反向搜索，找到字符串str第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。

返回str第一次出现的位置，如果str没有被找到，返回-1。

如果cs为真，那么匹配是区分大小写的。如果cs为假，那么匹配是不区分大小写的。

    QString string("bananas");
    int i = string.findRev( "ana" );      // i == 3

int QString::findRev ( const QRegExp & rx, int index = -1 ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从位置index开始并且反向搜索，找到正则表达式rx第一次出现的位置。如果index为-1，搜索从最后一个字符开始，如果是-1，从紧挨着最后一个字符的字符开始，依此类推。

返回rx第一次出现的位置，如果rx没有被找到，返回-1。

    QString string( "bananas" );
    int i = string.findRev( QRegExp("an") );      // i == 3

也可以参考find()。

QString QString::fromLatin1 ( const char * chars, int len = -1 ) [静态]

返回从chars的前len个字符解码得到的Unicode字符串，忽略chars的其余字符。如果len为-1，那么chars的长度将被使用。如果len大于chars的长度，那么chars的长度将被使用。

这个和QString(const char*)构造函数一样，但是如果你在编译的时候定义了QT_NO_CAST_ASCII，你可以使那个构造函数不可见，在这种情况下你可以使用这个函数来从Latin-1文本中明显地创建一个QString。

    QString str = QString::fromLatin1( "123456789", 5 );
    // str == "12345"

实例：listbox/listbox.cpp和network/mail/smtp.cpp。

QString QString::fromLocal8Bit ( const char * local8Bit, int len = -1 ) [静态]

返回从local8Bit的前len个字符解码得到的Unicode字符串，忽略local8Bit的其余字符。如果len为-1，那么local8Bit的长度将被使用。如果len大于chars的长度，那么local8Bit的长度将被使用。

    QString str = QString::fromLocal8Bit( "123456789", 5 );
    // str == "12345"

local8Bit被假设使用本地指定的格式编码的。

关于Unicode字符串的编码/解码更多变化请参考QTextCodec。

QString QString::fromUtf8 ( const char * utf8, int len = -1 ) [静态]

返回从utf8的前len个字符解码得到的Unicode字符串，忽略utf8的其余字符。如果len为-1，那么utf8的长度将被使用。如果len大于chars的长度，那么utf8的长度将被使用。

    QString str = QString::fromUtf8( "123456789", 5 );
    // str == "12345"

关于Unicode字符串的编码/解码更多变化请参考QTextCodec。

实例：fonts/simple-qfont-demo/viewer.cpp。

QString & QString::insert ( uint index, const QString & s )

把s插入到字符串的index位置之前。

如果index超过字符串的结尾，字符串被填充空格扩展到index长度并且然后s被添加，返回这个字符串的引用。

    QString string( "I like fish" );
    str = string.insert( 2, "don't " );
    // str == "I don't like fish"

也可以参考remove()和replace()。

实例：themes/themes.cpp和xform/xform.cpp。

QString & QString::insert ( uint index, const QChar * s, uint len )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把s中的字符插入到字符串的index位置之前len次并且返回这个字符串的引用。

QString & QString::insert ( uint index, QChar c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把c插入到字符串的index位置之前并且返回这个字符串的引用。

如果index超过字符串的结尾，字符串被填充空格（ASCII码为32）扩展到index长度并且然后s被添加，返回这个字符串的引用。

QString & QString::insert ( uint index, char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在index位置插入字符c。

bool QString::isEmpty () const

如果字符串为空，也就是如果length() == 0，返回真。因此，零字符串也是空字符串。

    QString a( "" );
    a.isEmpty();        // 真
    a.isNull();         // 假

    QString b;
    b.isEmpty();        // 真
    b.isNull();         // 真

也可以参考isNull()和length()。

实例：addressbook/mainwindow.cpp、chart/chartform.cpp、chart/chartform_canvas.cpp、network/networkprotocol/nntp.cpp、qmag/qmag.cpp和qwerty/qwerty.cpp。

bool QString::isNull () const

如果字符串为零，返回真。零字符串总是空的。

    QString a;          // a.unicode() == 0，a.length() == 0
    a.isNull();         // 真，因为a.unicode() == 0
    a.isEmpty();        // 真

也可以参考isEmpty()和length()。

实例：i18n/main.cpp和qdir/qdir.cpp。

const char * QString::latin1 () const

返回字符串的Latin-1表述。注意如果字符串包含非Latin-1字符，返回值是不确定的。如果你想把字符串转化为Unicode以为的格式，请参考QTextCodec类。

这个函数主要对于使用Unicode的开机时的老程序有用处。

只要源字符串的一个未修改复制存在，这个结果就保持有效。

也可以参考utf8()和local8Bit()。

实例：fileiconview/qfileiconview.cpp和network/networkprotocol/nntp.cpp。

QString QString::left ( uint len ) const

返回包含字符串最左面的len个字符的子字符串。

如果len超过字符串的长度，则整个字符串被返回。

    QString s = "Pineapple";
    QString t = s.left( 4 );    // t == "Pine"

也可以参考right()、mid()和isEmpty()。

实例：themes/themes.cpp。

QString QString::leftJustify ( uint width, QChar fill = ' ', bool truncate = FALSE ) const

返回一个长度为width的，包含这个字符串，并且用fill填补的字符串。

如果truncate为假并且字符串的长度超过width，那么返回的字符串是这个字符串的复制。

如果truncate为真并且字符串的长度超过width，那么这个字符串的复制中超过width长度的任何字符都被移除并且这个复制被返回。

    QString s( "apple" );
    QString t = s.leftJustify( 8, '.' );        // t == "apple..."

也可以参考rightJustify()。

uint QString::length () const

返回字符串的长度。

零字符串和空字符串的长度都为0。

也可以参考isNull()和isEmpty()。

实例：fileiconview/qfileiconview.cpp、network/networkprotocol/nntp.cpp、rot13/rot13.cpp和themes/themes.cpp。

QCString QString::local8Bit () const

返回被编码为本地指定格式的字符串。在X11上，这是QTextCodec::codecForLocale()。在Windows上，它是系统定义的编码方式。在Mac OS X上，总是使用utf8作为编码方式。

关于Unicode字符串的编码/解码更多变化请参考QTextCodec。

也可以参考QString::fromLocal8Bit()、latin1()和utf8()。

int QString::localeAwareCompare ( const QString & s1, const QString & s2 ) [静态]

对s1和s2进行比较，如果s1小于、等于或者大于s2，就返回小于、等于或者大于0的整数。

这个比较是基于本地的并且也是基于平台的方式。使用这个函数可以把排好序的字符串列表呈现给用户。

也可以参考QString::compare()和QTextCodec::locale()。

int QString::localeAwareCompare ( const QString & s ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

对这个字符串和s进行比较。

QString QString::lower () const

返回由这个字符串转换的小写字符串。

    QString string( "TROlltECH" );
    str = string.lower();   // str == "trolltech"

也可以参考upper()。

实例：scribble/scribble.cpp。

QString QString::mid ( uint index, uint len = 0xffffffff ) const

返回包含这个字符串从index位置开始len个字符的字符串。

如果这个字符串为空或者index超出范围，返回零。如果index+len超过这个字符串的长度，返回从index开始的整个字符串。

    QString s( "Five pineapples" );
    QString t = s.mid( 5, 4 );                  // t == "pine"

也可以参考left()和right()。

实例：network/mail/smtp.cpp、qmag/qmag.cpp和themes/themes.cpp。

QString QString::number ( long n, int base = 10 ) [静态]

一个把数字n转换为字符串的方便函数，n被基于base表示，默认为10，并且必须在2到36之间。

    long a = 63;
    QString str = QString::number( a, 16 );             // str == "3f"
    QString str = QString::number( a, 16 ).upper();     // str == "3F"

也可以参考setNum()。

实例：action/application.cpp、application/application.cpp、chart/chartform.cpp、fonts/simple-qfont-demo/viewer.cpp、mdi/application.cpp和sql/overview/extract/main.cpp。

QString QString::number ( ulong n, int base = 10 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

也可以参考setNum()。

QString QString::number ( int n, int base = 10 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

也可以参考setNum()。

QString QString::number ( uint n, int base = 10 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

一个把数字n转换为字符串表示的方便制造函数，n被基于base表示，默认为10，并且必须在2到36之间。

也可以参考setNum()。

QString QString::number ( double n, char f = 'g', int prec = 6 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

根据fmt指定的格式，参数n被格式化，g为默认情况并且可以为下列之一：

  • e - 格式化为[-]9.9e[+|-]999
  • E - 格式化为[-]9.9E[+|-]999
  • f - 格式化为[-]9.9
  • g - 使用e或f格式，看哪一个更简练
  • G - 使用E或f格式，看哪一个更简练

在所有的情况下，小数点之后数字的个数等于prec指定的精度。

    double d = 12.34;
    QString ds = QString( "'E' format, precision 3, gives %1" )
                 .arg( d, 0, 'E', 3 );
    // ds == "1.234E+001"

也可以参考setNum()。

QString::operator const char * () const

返回latin1()。请确定已经看到这里的警告文档。注意对于你希望严格遵守Unicode的新代码，当你编译你的代码时，你可以定义QT_NO_ASCII_CAST宏来隐藏这个函数，这样自动抛出就不会被完成。这样可以添加你可以抓住在operator!()下描述的编程错误的优点。

bool QString::operator! () const

如果它不是零字符串，返回真，否则返回假。

    QString name = getName();
    if ( !name )
        name = "Rodney";

注意如果你这样做

    QString name = getName();
    if ( name )
        doSomethingWith(name);

它将调用“operator const char*()”，这是没有效率的，当你希望写遵守Unicode的代码时，你可以定义QT_NO_ASCII_CAST宏。

当你想使用上述的语义时，请使用：

    QString name = getName();
    if ( !name.isNull() )
        doSomethingWith(name);

QString & QString::operator+= ( const QString & str )

把str添加到字符串中并且返回结果的引用。

QString & QString::operator+= ( QChar c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把字符c添加到字符串中并且返回结果的引用。

QString & QString::operator+= ( char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把字符c添加到字符串中并且返回结果的引用。

QString & QString::operator= ( QChar c )

设置字符串只包含单个字符c。

QString & QString::operator= ( const QString & s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把s的一个浅度复制赋值给这个字符串并且返回这个字符串的引用。这是非常快的，因为字符串没有被实际复制。

QString & QString::operator= ( const char * str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把解释为经典C字符串的str的一个深度复制赋值给这个字符串并且返回这个字符串的引用。

如果str为0，那么零字符串被创建。

也可以参考isNull()。

QString & QString::operator= ( const QCString & cs )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把解释为经典C字符串的cs的一个深度复制赋值给这个字符串并且返回这个字符串的引用。

QString & QString::operator= ( char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串只包含单个字符c。

QChar QString::operator[] ( int i ) const

返回在索引i处的字符，或者如果i超过字符串的长度返回QChar::null。

如果QString不是常量（也就是const QString）或者const&（也就是const QString&），那么operator[]的非常量重载将被使用来替代它。

QCharRef QString::operator[] ( int i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数返回在索引i处的字符的引用。这个结果引用可以立即被赋值或者使用，但是一旦初始字符串发生了改变，它将会变为无效。

如果i超过了字符串的长度，那么字符串将会被使用QChar::null来扩展，这样QCharRef就可以引用字符串中的有效（零）字符。

QCharRef内部类可以被常量QChar使用，但是如果你对它赋值，你就会改变初始字符串（它将会自动分离，因为QString是写时复制）。如果你试图把结果作为QChar以外的东西使用，你将得到编译错误。

QString & QString::prepend ( const QString & s )

在字符串开始处插入s并且返回这个字符串的引用。

等于insert(0, s)。

    QString string = "42";
    string.prepend( "The answer is " );
    // string == "The answer is 42"

也可以参考insert()。

QString & QString::prepend ( char ch )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串开始处插入ch并且返回这个字符串的引用。

等于insert(0, ch)。

也可以参考insert()。

QString & QString::prepend ( QChar ch )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在字符串开始处插入ch并且返回这个字符串的引用。

等于insert(0, ch)。

也可以参考insert()。

QChar & QString::ref ( uint i )

返回在索引i的QChar的引用，如果需要就是用QChar::null扩展字符串。这个结果引用可以立即被赋值或者使用，但是一旦初始字符串发生了改变，它将会变为无效。

    QString string("ABCDEF");
    QChar ch = string.ref( 3 );         // ch == 'D'

也可以参考constref()。

QString & QString::remove ( uint index, uint len )

从字符串中的index位置开始移除len个字符并且返回这个字符串的引用。

如果index超出字符串的长度，就什么也不发生。如果index在字符串中间，但是index加上len超过字符串的结尾，这个字符串将从index开始被截短。

    QString string( "Montreal" );
    string.remove( 1, 4 );      // string == "Meal"

也可以参考insert()和replace()。

QString & QString::replace ( uint index, uint len, const QString & s )

从字符串中的index位置开始使用s替换len个字符，并且返回这个字符串的引用。

如果index超出字符串的长度，就什么也不被删除并且s被添加到字符串结尾。如果 index有效并且index加上len超过字符串的结尾，那么这个字符串将从index开始被截短，并且s被添加到字符串结尾。

    QString string( "Say yes!" );
    string = string.replace( 4, 3, "NO" );
    // string == "Say NO!"

也可以参考insert()和remove()。

实例：listviews/listviews.cpp、network/networkprotocol/nntp.cpp和qmag/qmag.cpp。

QString & QString::replace ( uint index, uint len, const QChar * s, uint slen )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从字符串中的index位置开始使用s中的slen个字符的QChar数据替换len个字符，并且返回这个字符串的引用。

也可以参考insert()和remove()。

QString & QString::replace ( const QRegExp & rx, const QString & str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

用str替换字符串中出现的每一个正则表达式rx。返回这个字符串的引用。

    QString string = "banana";
    string = string.replace( QRegExp("an"), "" ); // string == "ba"

也可以参考find()和findRev()。

QString QString::right ( uint len ) const

返回包含字符串最右面的len个字符的子字符串。

如果len超过字符串的长度，则整个字符串被返回。

    QString string( "Pineapple" );
    QString t = string.right( 5 );   // t == "apple"

也可以参考left()、mid()和isEmpty()。

实例：fileiconview/qfileiconview.cpp。

QString QString::rightJustify ( uint width, QChar fill = ' ', bool truncate = FALSE ) const

返回一个长度为width的，包含fill填补的字符串，后面跟着这个字符串。

如果truncate为假并且字符串的长度超过width，那么返回的字符串是这个字符串的复制。

如果truncate为真并且字符串的长度超过width，那么这个字符串的复制中超过width长度的任何字符都被移除并且这个复制被返回。

    QString string( "apple" );
    QString t = string.rightJustify( 8, '.' );  // t == "...apple"

也可以参考leftJustify()。

QString QString::section ( QChar sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const

这个函数用来返回字符串的一部分。

这个字符串被看作由字符sep分隔开的顺序的区段。返回的从位置start到位置end（两个都包含）的区段组成的字符串。如果end没有被指定，那么从位置start开始到字符串的结尾的所有区段都被返回。区段是从左面是0、1、2等等计数，或者从右面-1、-2等等计数的。

flags参数可以用来影响这个函数行为的特征，例如是否区分大小写，是否忽略空区段并且如何处理开始和结尾的分隔符，请参考SectionFlags。

    QString csv( "forename,middlename,surname,phone" );
    QString s = csv.section( ',', 2, 2 );   // s == "surname"

    QString path( "/usr/local/bin/myapp" ); // First field is empty
    QString s = path.section( '/', 3, 4 );  // s == "bin/myapp"
    QString s = path.section( '/', 3, 3, SectionSkipEmpty ); // s == "myapp"

如果start或者end为负数，我们就从字符串的右面开始计数，最右面的是-1，接着是-2，依此类推。

    QString csv( "forename,middlename,surname,phone" );
    QString s = csv.section( ',', -3, -2 );  // s == "middlename,surname"

    QString path( "/usr/local/bin/myapp" ); // First field is empty
    QString s = path.section( '/', -1 ); // s == "myapp"

也可以参考QStringList::split()。

实例：chart/element.cpp。

QString QString::section ( char sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

QString QString::section ( const char * sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

QString QString::section ( const QString & sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数用来返回字符串的一部分。

这个字符串被看作由字符串sep分隔开的顺序的区段。返回的从位置start到位置end（两个都包含）的区段组成的字符串。如果end没有被指定，那么从位置start开始到字符串的结尾的所有区段都被返回。区段是从左面是0、1、2等等计数，或者从右面-1、-2等等计数的。

flags参数可以用来影响这个函数行为的特征，例如是否区分大小写，是否忽略空区段并且如何处理开始和结尾的分隔符，请参考SectionFlags。

    QString data( "forename**middlename**surname**phone" );
    QString s = data.section( "**", 2, 2 ); // s == "surname"

如果start或者end为负数，我们就从字符串的右面开始计数，最右面的是-1，接着是-2，依此类推。

    QString data( "forename**middlename**surname**phone" );
    QString s = data.section( "**", -3, -2 ); // s == "middlename**surname"

也可以参考QStringList::split()。

QString QString::section ( const QRegExp & reg, int start, int end = 0xffffffff, int flags = SectionDefault ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数用来返回字符串的一部分。

这个字符串被看作由正则表达式 reg分隔开的顺序的区段。返回的从位置start到位置end（两个都包含）的区段组成的字符串。如果end没有被指定，那么从位置start开始到字符串的结尾的所有区段都被返回。区段是从左面是0、1、2等等计数，或者从右面-1、-2等等计数的。

flags参数可以用来影响这个函数行为的特征，例如是否区分大小写，是否忽略空区段并且如何处理开始和结尾的分隔符，请参考SectionFlags。

    QString line( "forename\tmiddlename  surname \t \t phone" );
    QRegExp sep( "\s+" );
    QString s = line.section( sep, 2, 2 ); // s == "surname"

如果start或者end为负数，我们就从字符串的右面开始计数，最右面的是-1，接着是-2，依此类推。

    QString line( "forename\tmiddlename  surname \t \t phone" );
    QRegExp sep( "\\s+" );
    QString s = line.section( sep, -3, -2 ); // s == "middlename  surname"

警告： QRegExp这一部分比其它字符串和字符的重载版本要花费更多。

也可以参考QStringList::split()和simplifyWhiteSpace()。

void QString::setExpand ( uint index, QChar c )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

设置在index位置的字符为c并且如果需要使用空格来扩展这个字符串。

这个方法在Qt 3.x中是多余的，因为operator[]可以在需要的时候扩展字符串。

QString & QString::setLatin1 ( const char * str, int len = -1 )

设置这个字符串为解释为经典的Latin1的C字符串的str。如果len为-1（默认），那么它将被设置为strlen(str)。

如果str为0，那么零字符串被创建。如果str为“”，那么空字符串被创建。

也可以参考isNull()和isEmpty()。

void QString::setLength ( uint newLen )

确保至少newLen个字符被分配给这个字符串，并且设置这个字符串的长度为newLen。任何分配的新空间保留任意的数据。

如果newLen为0，那么这个字符串将变为空，除非这个字符串是零，这种情况下它仍保持为零。

如果不能分配足够的内存，字符串保持不变。

这个函数总是把这个字符串和有同样数据的其它引用分离。

这个函数对于需要构建一个长字符创并且想避免重复重新分配空间的代码很有用。在这个实例中，我们想添加字符串，直到条件为真，并且我们十分确信分配给它的大小是足够大的：

    QString result;
    int resultLength = 0;
    result.setLength( newLen ) // 分配一些空间
    while ( ... ) {
        result[resultLength++] = ... // 填充（部分的）空格作为数据
    }
    result.truncate[resultLength]; // 并且去掉不确定的垃圾

如果newLen是不足的话，最坏的情况就是将会循环将会变慢。

也可以参考truncate()、isNull()、isEmpty()和length()。

QString & QString::setNum ( long n, int base = 10 )

设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

    QString string;
    string = string.setNum( 1234 );     // string == "1234"

QString & QString::setNum ( short n, int base = 10 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

QString & QString::setNum ( ushort n, int base = 10 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

QString & QString::setNum ( int n, int base = 10 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

QString & QString::setNum ( uint n, int base = 10 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

QString & QString::setNum ( ulong n, int base = 10 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置字符串为打印的数据n，n是基于base并且返回这个字符串的引用。

base默认为10并且必须在2到36之间。

QString & QString::setNum ( float n, char f = 'g', int prec = 6 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为打印的由格式f和精度prec格式化的数据n并且返回这个字符串的引用。

格式f可以为“f”、“F”、“e”、“E”、“g”或者“G”。关于这些格式的解释请参考arg()。

QString & QString::setNum ( double n, char f = 'g', int prec = 6 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字符串为打印的由格式f和精度prec格式化的数据n并且返回这个字符串的引用。

格式f可以为“f”、“F”、“e”、“E”、“g”或者“G”。关于这些格式的解释请参考arg()。

QString & QString::setUnicode ( const QChar * unicode, uint len )

重新定义字符串的大小为len并且把unicode复制到字符串中。如果unicode为零，什么都不被复制，但是字符串还是被重新定义为len。如果len为0，那么字符串变为零字符串。

也可以参考setLatin1()和isNull()。

QString & QString::setUnicodeCodes ( const ushort * unicode_as_ushorts, uint len )

重新定义字符串的大小为len并且把unicode_as_ushorts复制到字符串中（在一些X11客户端平台上这将进入到二进制缓存通道中）。

如果unicode_as_ushorts为零，什么都不被复制，但是字符串还是被重新定义为len。如果len为0，那么字符串变为零字符串。

也可以参考setLatin1()和isNull()。

QString QString::simplifyWhiteSpace () const

返回一个移除了这个字符串的开始和结尾的空白符号的字符串，并且内部的空白符号都被替代为单一的空格。

空白符号是指任何QChar::isSpace()返回真的字符。这里面包括十进制为9（TAB）、10（LF）、11（VT）、12（FF）、13（CR）和32（Space）的UNICODE字符。

    QString string = "  lots\t of\nwhite    space ";
    QString t = string.simplifyWhiteSpace();
    // t == "lots of white space"

也可以参考stripWhiteSpace()。

QString & QString::sprintf ( const char * cformat, ... )

从一个格式化字符串cformat和一个任意的参数列表安全地构建一个格式化的字符串。

%s转义序列希望一个utf8()编码字符串。格式化字符串cformat希望是一个Latin1的。如果你需要一个Unicode格式字符串，使用arg()来替代。为了完全支持Unicode的类型安全的字符串构建，你可以像这样使用QTextOStream：

    QString str;
    QString s = ...;
    int x = ...;
    QTextOStream( &str ) << s << " : " << x;

对于翻译，特别是如果字符串包含超过一个的转义序列，你应该考虑使用arg()来替代它。这将允许翻译者来控制替换的顺序并且支持Unicode。

也可以参考arg()。

实例：dclock/dclock.cpp、forever/forever.cpp、layout/layout.cpp、qmag/qmag.cpp、scrollview/scrollview.cpp、tooltip/tooltip.cpp和xform/xform.cpp。

bool QString::startsWith ( const QString & s ) const

如果字符串以s开始，返回真，否则返回假。

    QString string("Bananas");
    bool a = string.startsWith("Ban");      //  a == TRUE

也可以参考endsWith()。

QString QString::stripWhiteSpace () const

返回一个移除了这个字符串的开始和结尾的空白符号的字符串，并且内部的空白符号都被替代为单一的空格。

空白符号是指任何QChar::isSpace()返回真的字符。这里面包括十进制为9（TAB）、10（LF）、11（VT）、12（FF）、13（CR）和32（Space）的UNICODE字符。

    QString string = "   white space   ";
    QString s = string.stripWhiteSpace();       // s == "white space"

也可以参考simplifyWhiteSpace()。

double QString::toDouble ( bool * ok = 0 ) const

返回由这个字符串转化的double值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

    QString string( "1234.56" );
    double a = string.toDouble();   // a == 1234.56

也可以参考number()。

float QString::toFloat ( bool * ok = 0 ) const

返回由这个字符串转化的float值。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

也可以参考number()。

int QString::toInt ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的int值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

    QString str( "FF" );
    bool ok;
    int hex = str.toInt( &ok, 16 );     // hex == 255, ok == TRUE
    int dec = str.toInt( &ok, 10 );     // dec == 0, ok == FALSE

也可以参考number()。

long QString::toLong ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的long值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

也可以参考number()。

short QString::toShort ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的short值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

uint QString::toUInt ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的unsigned int值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

也可以参考number()。

ulong QString::toULong ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的unsigned long值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

也可以参考number()。

ushort QString::toUShort ( bool * ok = 0, int base = 10 ) const

返回由这个字符串转化的unsigned short值，是基于base的，默认为10并且必须在2到36之间。

如果转化发生错误，*ok被设置为假（除非ok为0，这是默认的）并且0被返回。否则*ok被设置为真。

void QString::truncate ( uint newLen )

如果newLen小于字符串的长度，那么字符串将从newLen位置被截短。否则就什么也不发生。

    QString s = "truncate me";
    s.truncate( 5 );            // s == "trunc"

也可以参考setLength()。

实例：network/mail/smtp.cpp。

const QChar * QString::unicode () const

返回这个字符串的Unicode表述。直到这个字符串被修改，这个结果保持有效。

QString QString::upper () const

返回由这个字符串转换的大写字符串。

    QString string( "TeXt" );
    str = string.upper();     // t == "TEXT"

也可以参考lower()。

实例：scribble/scribble.cpp和sql/overview/custom1/main.cpp。

QCString QString::utf8 () const

返回按UTF8格式编码的字符串。

关于Unicode字符串的编码/解码更多变化请参考QTextCodec。

也可以参考QString::fromUtf8()、local8Bit()和latin1()。

相关函数

bool operator!= ( const QString & s1, const QString & s2 )

如果s1在词典中不等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

bool operator!= ( const QString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中不等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

bool operator!= ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中不等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

const QString operator+ ( const QString & s1, const QString & s2 )

返回字符串s1和字符串s2连接的结果的字符串。

等于s1.append(s2)。

const QString operator+ ( const QString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回字符串s1和字符串s2连接的结果的字符串。

等于s1.append(s2)。

const QString operator+ ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回字符串s1和字符串s2连接的结果的字符串。

const QString operator+ ( const QString & s, char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回字符串s和字符c连接的结果的字符串。

等于s.append(c)。

const QString operator+ ( char c, const QString & s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回字符c和字符串s连接的结果的字符串。

等于s.prepend(c)。

bool operator< ( const QString & s1, const char * s2 )

如果s1在词典中小于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) < 0。

bool operator< ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中小于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) < 0。

QDataStream & operator<< ( QDataStream & s, const QString & str )

把字符串str写到流s中。

也可以参考QDataStream操作符的格式。

bool operator<= ( const QString & s1, const char * s2 )

如果s1在词典中小于或等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1,s2) <= 0。

bool operator<= ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中小于或等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1,s2) <= 0。

bool operator== ( const QString & s1, const QString & s2 )

如果s1在词典中等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

bool operator== ( const QString & s1, const char * s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

bool operator== ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) != 0。

bool operator> ( const QString & s1, const char * s2 )

如果s1在词典中大于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) > 0。

bool operator> ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中大于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) > 0。

bool operator>= ( const QString & s1, const char * s2 )

如果s1在词典中大于或等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) >= 0。

bool operator>= ( const char * s1, const QString & s2 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果s1在词典中大于或等于s2，返回真，否则如果不是，返回假。这个比较是区分大小写的。注意一个零字符串不等于一个非零的空字符串。

等于compare(s1, s2) >= 0。

QDataStream & operator>> ( QDataStream & s, QString & str )

从流s中读取一个字符串到字符串str中。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qstring.h包含文件

qstring.h

这里是qstring.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of the QString class, and related Unicode
** functions.
**
** Created : 920609
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTRING_H
#define QSTRING_H

#ifndef QT_H
#include "qcstring.h"
#endif // QT_H

/*****************************************************************************
  QString class
 *****************************************************************************/

class QRegExp;
class QString;
class QCharRef;

class Q_EXPORT QChar {
public:
    QChar();
    QChar( char c );
    QChar( uchar c );
    QChar( uchar c, uchar r );
    QChar( const QChar& c );
    QChar( ushort rc );
    QChar( short rc );
    QChar( uint rc );
    QChar( int rc );

    QT_STATIC_CONST QChar null;            // 0000
    QT_STATIC_CONST QChar replacement;     // FFFD
    QT_STATIC_CONST QChar byteOrderMark;     // FEFF
    QT_STATIC_CONST QChar byteOrderSwapped;     // FFFE
    QT_STATIC_CONST QChar nbsp;            // 00A0

    // Unicode information

    enum Category
    {
        NoCategory,

        Mark_NonSpacing,          //   Mn
        Mark_SpacingCombining,    //   Mc
        Mark_Enclosing,           //   Me

        Number_DecimalDigit,      //   Nd
        Number_Letter,            //   Nl
        Number_Other,             //   No

        Separator_Space,          //   Zs
        Separator_Line,           //   Zl
        Separator_Paragraph,      //   Zp

        Other_Control,            //   Cc
        Other_Format,             //   Cf
        Other_Surrogate,          //   Cs
        Other_PrivateUse,         //   Co
        Other_NotAssigned,        //   Cn

        Letter_Uppercase,         //   Lu
        Letter_Lowercase,         //   Ll
        Letter_Titlecase,         //   Lt
        Letter_Modifier,          //   Lm
        Letter_Other,             //   Lo

        Punctuation_Connector,    //   Pc
        Punctuation_Dash,         //   Pd
        Punctuation_Dask = Punctuation_Dash, // oops
        Punctuation_Open,         //   Ps
        Punctuation_Close,        //   Pe
        Punctuation_InitialQuote, //   Pi
        Punctuation_FinalQuote,   //   Pf
        Punctuation_Other,        //   Po

        Symbol_Math,              //   Sm
        Symbol_Currency,          //   Sc
        Symbol_Modifier,          //   Sk
        Symbol_Other              //   So
    };

    enum Direction
    {
        DirL, DirR, DirEN, DirES, DirET, DirAN, DirCS, DirB, DirS, DirWS, DirON,
        DirLRE, DirLRO, DirAL, DirRLE, DirRLO, DirPDF, DirNSM, DirBN
    };

    enum Decomposition
    {
        Single, Canonical, Font, NoBreak, Initial, Medial,
        Final, Isolated, Circle, Super, Sub, Vertical,
        Wide, Narrow, Small, Square, Compat, Fraction
    };

    enum Joining
    {
        OtherJoining, Dual, Right, Center
    };

    enum CombiningClass
    {
        Combining_BelowLeftAttached       = 200,
        Combining_BelowAttached           = 202,
        Combining_BelowRightAttached      = 204,
        Combining_LeftAttached            = 208,
        Combining_RightAttached           = 210,
        Combining_AboveLeftAttached       = 212,
        Combining_AboveAttached           = 214,
        Combining_AboveRightAttached      = 216,

        Combining_BelowLeft               = 218,
        Combining_Below                   = 220,
        Combining_BelowRight              = 222,
        Combining_Left                    = 224,
        Combining_Right                   = 226,
        Combining_AboveLeft               = 228,
        Combining_Above                   = 230,
        Combining_AboveRight              = 232,

        Combining_DoubleBelow             = 233,
        Combining_DoubleAbove             = 234,
        Combining_IotaSubscript           = 240
    };

    // ****** WHEN ADDING FUNCTIONS, CONSIDER ADDING TO QCharRef TOO

    int digitValue() const;
    QChar lower() const;
    QChar upper() const;

    Category category() const;
    Direction direction() const;
    Joining joining() const;
    bool mirrored() const;
    QChar mirroredChar() const;
    const QString &decomposition() const;
    Decomposition decompositionTag() const;
    unsigned char combiningClass() const;

    char latin1() const { return ucs > 0xff ? 0 : (char) ucs; }
    ushort unicode() const { return ucs; }
    ushort &unicode() { return ucs; }
#ifndef QT_NO_CAST_ASCII
    // like all ifdef'd code this is undocumented
    operator char() const { return latin1(); }
#endif

    bool isNull() const { return unicode()==0; }
    bool isPrint() const;
    bool isPunct() const;
    bool isSpace() const;
    bool isMark() const;
    bool isLetter() const;
    bool isNumber() const;
    bool isLetterOrNumber() const;
    bool isDigit() const;
    bool isSymbol() const;

    uchar cell() const { return ((uchar) ucs & 0xff); }
    uchar row() const { return ((uchar) (ucs>>8)&0xff); }
    void setCell( uchar cell ) { ucs = (ucs & 0xff00) + cell; }
    void setRow( uchar row ) { ucs = (((ushort) row)<<8) + (ucs&0xff); }

    static bool networkOrdered() {
    int wordSize;
    bool bigEndian = FALSE;
    qSysInfo( &wordSize, &bigEndian );
    return bigEndian;
    }

    friend inline bool operator==( char ch, QChar c );
    friend inline bool operator==( QChar c, char ch );
    friend inline bool operator==( QChar c1, QChar c2 );
    friend inline bool operator!=( QChar c1, QChar c2 );
    friend inline bool operator!=( char ch, QChar c );
    friend inline bool operator!=( QChar c, char ch );
    friend inline bool operator<=( QChar c, char ch );
    friend inline bool operator<=( char ch, QChar c );
    friend inline bool operator<=( QChar c1, QChar c2 );

private:
    ushort ucs;
#if defined(QT_QSTRING_UCS_4)
    ushort grp;
#endif
} Q_PACKED;

inline QChar::QChar()
{
    ucs = 0;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( char c )
{
    ucs = (uchar)c;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( uchar c )
{
    ucs = c;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( uchar c, uchar r )
{
    ucs = (r << 8) | c;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( const QChar& c )
{
    ucs = c.ucs;
#ifdef QT_QSTRING_UCS_4
    grp = c.grp;
#endif
}

inline QChar::QChar( ushort rc )
{
    ucs = rc;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( short rc )
{
    ucs = (ushort) rc;
#ifdef QT_QSTRING_UCS_4
    grp = 0;
#endif
}
inline QChar::QChar( uint rc )
{
    ucs = (ushort ) (rc & 0xffff);
#ifdef QT_QSTRING_UCS_4
    grp = (ushort) ((rc >> 16) & 0xffff);
#endif
}
inline QChar::QChar( int rc )
{
    ucs = (ushort) (rc & 0xffff);
#ifdef QT_QSTRING_UCS_4
    grp = (ushort) ((rc >> 16) & 0xffff);
#endif
}

inline bool operator==( char ch, QChar c )
{
    return ((uchar) ch) == c.ucs;
}

inline bool operator==( QChar c, char ch )
{
    return ((uchar) ch) == c.ucs;
}

inline bool operator==( QChar c1, QChar c2 )
{
    return c1.ucs == c2.ucs;
}

inline bool operator!=( QChar c1, QChar c2 )
{
    return c1.ucs != c2.ucs;
}

inline bool operator!=( char ch, QChar c )
{
    return ((uchar)ch) != c.ucs;
}

inline bool operator!=( QChar c, char ch )
{
    return ((uchar) ch) != c.ucs;
}

inline bool operator<=( QChar c, char ch )
{
    return c.ucs <= ((uchar) ch);
}

inline bool operator<=( char ch, QChar c )
{
    return ((uchar) ch) <= c.ucs;
}

inline bool operator<=( QChar c1, QChar c2 )
{
    return c1.ucs <= c2.ucs;
}

inline bool operator>=( QChar c, char ch ) { return ch <= c; }
inline bool operator>=( char ch, QChar c ) { return c <= ch; }
inline bool operator>=( QChar c1, QChar c2 ) { return c2 <= c1; }
inline bool operator<( QChar c, char ch ) { return !(ch<=c); }
inline bool operator<( char ch, QChar c ) { return !(c<=ch); }
inline bool operator<( QChar c1, QChar c2 ) { return !(c2<=c1); }
inline bool operator>( QChar c, char ch ) { return !(ch>=c); }
inline bool operator>( char ch, QChar c ) { return !(c>=ch); }
inline bool operator>( QChar c1, QChar c2 ) { return !(c2>=c1); }

// internal
struct Q_EXPORT QStringData : public QShared {
    QStringData() :
        unicode(0), ascii(0), len(0), simpletext(1), maxl(0), dirty(0) { ref(); }
    QStringData(QChar *u, uint l, uint m) :
        unicode(u), ascii(0), len(l), simpletext(1), maxl(m), dirty(1) { }

    ~QStringData() { if ( unicode ) delete[] ((char*)unicode);
                     if ( ascii ) delete[] ascii; }

    void deleteSelf();
    QChar *unicode;
    char *ascii;
    void setDirty() {
    if ( ascii ) {
        delete [] ascii;
        ascii = 0;
    }
    dirty = 1;
    }
#ifdef Q_OS_MAC9
    uint len;
#else
    uint len : 30;
#endif
    uint simpletext : 1;
#ifdef Q_OS_MAC9
    uint maxl;
#else
    uint maxl : 30;
#endif
    uint dirty : 1;
};

class Q_EXPORT QString
{
public:
    QString();                                  // make null string
    QString( QChar );                           // one-char string
    QString( const QString & );                 // impl-shared copy
    QString( const QByteArray& );               // deep copy
    QString( const QChar* unicode, uint length ); // deep copy
#ifndef QT_NO_CAST_ASCII
    QString( const char *str );                 // deep copy
#endif
    ~QString();

    QString    &operator=( const QString & );   // impl-shared copy
#ifndef QT_NO_CAST_ASCII
    QString    &operator=( const char * );      // deep copy
#endif
    QString    &operator=( const QCString& );   // deep copy
    QString    &operator=( QChar c );
    QString    &operator=( char c );

    QT_STATIC_CONST QString null;

    bool        isNull()        const;
    bool        isEmpty()       const;
    uint        length()        const;
    void        truncate( uint pos );

    QString &   fill( QChar c, int len = -1 );

    QString     copy()  const;

    QString arg( long a, int fieldwidth=0, int base=10 ) const;
    QString arg( ulong a, int fieldwidth=0, int base=10 ) const;
    QString arg( int a, int fieldwidth=0, int base=10 ) const;
    QString arg( uint a, int fieldwidth=0, int base=10 ) const;
    QString arg( short a, int fieldwidth=0, int base=10 ) const;
    QString arg( ushort a, int fieldwidth=0, int base=10 ) const;
    QString arg( char a, int fieldwidth=0 ) const;
    QString arg( QChar a, int fieldwidth=0 ) const;
    QString arg( const QString& a, int fieldwidth=0 ) const;
    QString arg( double a, int fieldwidth=0, char fmt='g', int prec=-1 ) const;

#ifndef QT_NO_SPRINTF
    QString    &sprintf( const char* format, ... )
#if defined(Q_CC_GNU) && !defined(__INSURE__)
        __attribute__ ((format (printf, 2, 3)))
#endif
        ;
#endif

    int         find( QChar c, int index=0, bool cs=TRUE ) const;
    int         find( char c, int index=0, bool cs=TRUE ) const;
    int         find( const QString &str, int index=0, bool cs=TRUE ) const;
#ifndef QT_NO_REGEXP
    int         find( const QRegExp &, int index=0 ) const;
#endif
#ifndef QT_NO_CAST_ASCII
    int         find( const char* str, int index=0 ) const;
#endif
    int         findRev( QChar c, int index=-1, bool cs=TRUE) const;
    int         findRev( char c, int index=-1, bool cs=TRUE) const;
    int         findRev( const QString &str, int index=-1, bool cs=TRUE) const;
#ifndef QT_NO_REGEXP
    int         findRev( const QRegExp &, int index=-1 ) const;
#endif
#ifndef QT_NO_CAST_ASCII
    int         findRev( const char* str, int index=-1 ) const;
#endif
    int         contains( QChar c, bool cs=TRUE ) const;
    int         contains( char c, bool cs=TRUE ) const
                    { return contains(QChar(c), cs); }
#ifndef QT_NO_CAST_ASCII
    int         contains( const char* str, bool cs=TRUE ) const;
#endif
    int         contains( const QString &str, bool cs=TRUE ) const;
#ifndef QT_NO_REGEXP
    int         contains( const QRegExp & ) const;
#endif

    enum SectionFlags {
    SectionDefault             = 0x00,
    SectionSkipEmpty           = 0x01,
    SectionIncludeLeadingSep   = 0x02,
    SectionIncludeTrailingSep  = 0x04,
    SectionCaseInsensitiveSeps = 0x08
    };
    QString     section( QChar sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const;
    QString     section( char sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const;
#ifndef QT_NO_CAST_ASCII
    QString      section( const char *in_sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const;
#endif
    QString     section( const QString &in_sep, int start, int end = 0xffffffff, int flags = SectionDefault ) const;
#ifndef QT_NO_REGEXP
    QString     section( const QRegExp &reg, int start, int end = 0xffffffff, int flags = SectionDefault ) const;
#endif

    QString     left( uint len )  const;
    QString     right( uint len ) const;
    QString     mid( uint index, uint len=0xffffffff) const;

    QString     leftJustify( uint width, QChar fill=' ', bool trunc=FALSE)const;
    QString     rightJustify( uint width, QChar fill=' ',bool trunc=FALSE)const;

    QString     lower() const;
    QString     upper() const;

    QString     stripWhiteSpace()       const;
    QString     simplifyWhiteSpace()    const;

    QString    &insert( uint index, const QString & );
    QString    &insert( uint index, const QChar*, uint len );
    QString    &insert( uint index, QChar );
    QString    &insert( uint index, char c ) { return insert(index,QChar(c)); }
    QString    &append( char );
    QString    &append( QChar );
    QString    &append( const QString & );
    QString    &prepend( char );
    QString    &prepend( QChar );
    QString    &prepend( const QString & );
    QString    &remove( uint index, uint len );
    QString    &replace( uint index, uint len, const QString & );
    QString    &replace( uint index, uint len, const QChar*, uint clen );
#ifndef QT_NO_REGEXP
    QString    &replace( const QRegExp &, const QString & );
#endif
    short       toShort( bool *ok=0, int base=10 )      const;
    ushort      toUShort( bool *ok=0, int base=10 )     const;
    int         toInt( bool *ok=0, int base=10 )        const;
    uint        toUInt( bool *ok=0, int base=10 )       const;
    long        toLong( bool *ok=0, int base=10 )       const;
    ulong       toULong( bool *ok=0, int base=10 )      const;
    float       toFloat( bool *ok=0 )   const;
    double      toDouble( bool *ok=0 )  const;

    QString    &setNum( short, int base=10 );
    QString    &setNum( ushort, int base=10 );
    QString    &setNum( int, int base=10 );
    QString    &setNum( uint, int base=10 );
    QString    &setNum( long, int base=10 );
    QString    &setNum( ulong, int base=10 );
    QString    &setNum( float, char f='g', int prec=6 );
    QString    &setNum( double, char f='g', int prec=6 );

    static QString number( long, int base=10 );
    static QString number( ulong, int base=10);
    static QString number( int, int base=10 );
    static QString number( uint, int base=10);
    static QString number( double, char f='g', int prec=6 );

    void        setExpand( uint index, QChar c );

    QString    &operator+=( const QString &str );
    QString    &operator+=( QChar c );
    QString    &operator+=( char c );

    QChar at( uint i ) const
        { return i < d->len ? d->unicode[i] : QChar::null; }
    QChar operator[]( int i ) const { return at((uint)i); }
    QCharRef at( uint i );
    QCharRef operator[]( int i );

    QChar constref(uint i) const
        { return at(i); }
    QChar& ref(uint i)
        { // Optimized for easy-inlining by simple compilers.
            if ( d->count != 1 || i >= d->len )
                subat( i );
            d->setDirty();
            return d->unicode[i];
        }

    const QChar* unicode() const { return d->unicode; }
    const char* ascii() const { return latin1(); }
    const char* latin1() const;
    static QString fromLatin1(const char*, int len=-1);
#ifndef QT_NO_TEXTCODEC
    QCString utf8() const;
    static QString fromUtf8(const char*, int len=-1);
#endif
    QCString local8Bit() const;
    static QString fromLocal8Bit(const char*, int len=-1);
    bool operator!() const;
#ifndef QT_NO_ASCII_CAST
    operator const char *() const { return latin1(); }
#endif

    QString &setUnicode( const QChar* unicode, uint len );
    QString &setUnicodeCodes( const ushort* unicode_as_ushorts, uint len );
    QString &setLatin1( const char*, int len=-1 );

    int compare( const QString& s ) const;
    static int compare( const QString& s1, const QString& s2 )
    { return s1.compare( s2 ); }

    int localeAwareCompare( const QString& s ) const;
    static int localeAwareCompare( const QString& s1, const QString& s2 )
    { return s1.localeAwareCompare( s2 ); }

#ifndef QT_NO_DATASTREAM
    friend Q_EXPORT QDataStream &operator>>( QDataStream &, QString & );
#endif

    void compose();

#ifndef QT_NO_COMPAT
    const char* data() const { return latin1(); }
#endif

    bool startsWith( const QString& ) const;
    bool endsWith( const QString& ) const;

    void setLength( uint newLength );

    bool simpleText() const { if ( d->dirty ) checkSimpleText(); return (bool)d->simpletext; }
    bool isRightToLeft() const;

private:
    /*
      In Qt 1.0 and 2.0, users could write
      str.replace(QString("foo"), QString("bar")) and "foo" was
      automatically converted into a regexp.

      In Qt 3.0, this gives a compiler error. Users have to write
      QRegExp("foo"). In Qt 3.1 or 4.0, we will move replace() to the
      public API.
    */
    QString& replace( const QString &, const QString & ) { return *this; }

    QString( int size, bool /* dummy */ );	// allocate size incl. \0

    void deref();
    void real_detach();
    void subat( uint );
    bool findArg(int& pos, int& len) const;

    void checkSimpleText() const;

    static QChar* asciiToUnicode( const char*, uint * len, uint maxlen=(uint)-1 );
    static QChar* asciiToUnicode( const QByteArray&, uint * len );
    static char* unicodeToAscii( const QChar*, uint len );

    QStringData *d;
    static QStringData* shared_null;
    static QStringData* makeSharedNull();

    friend class QConstString;
    friend class QTextStream;
    QString( QStringData* dd, bool /* dummy */ ) : d(dd) { }
};

class Q_EXPORT QCharRef {
    friend class QString;
    QString& s;
    uint p;
    QCharRef(QString* str, uint pos) : s(*str), p(pos) { }

public:
    // most QChar operations repeated here...

    // all this is not documented: We just say "like QChar" and let it be.
#ifndef Q_QDOC
    ushort unicode() const { return s.constref(p).unicode(); }
    char latin1() const { return s.constref(p).latin1(); }

    // An operator= for each QChar cast constructor...
    QCharRef operator=(char c ) { s.ref(p)=c; return *this; }
    QCharRef operator=(uchar c ) { s.ref(p)=c; return *this; }
    QCharRef operator=(QChar c ) { s.ref(p)=c; return *this; }
    QCharRef operator=(const QCharRef& c ) { s.ref(p)=c.unicode(); return *this; }
    QCharRef operator=(ushort rc ) { s.ref(p)=rc; return *this; }
    QCharRef operator=(short rc ) { s.ref(p)=rc; return *this; }
    QCharRef operator=(uint rc ) { s.ref(p)=rc; return *this; }
    QCharRef operator=(int rc ) { s.ref(p)=rc; return *this; }

    operator QChar () const { return s.constref(p); }

    // each function...
    bool isNull() const { return unicode()==0; }
    bool isPrint() const { return s.constref(p).isPrint(); }
    bool isPunct() const { return s.constref(p).isPunct(); }
    bool isSpace() const { return s.constref(p).isSpace(); }
    bool isMark() const { return s.constref(p).isMark(); }
    bool isLetter() const { return s.constref(p).isLetter(); }
    bool isNumber() const { return s.constref(p).isNumber(); }
    bool isLetterOrNumber() { return s.constref(p).isLetterOrNumber(); }
    bool isDigit() const { return s.constref(p).isDigit(); }

    int digitValue() const { return s.constref(p).digitValue(); }
    QChar lower() const { return s.constref(p).lower(); }
    QChar upper() const { return s.constref(p).upper(); }

    QChar::Category category() const { return s.constref(p).category(); }
    QChar::Direction direction() const { return s.constref(p).direction(); }
    QChar::Joining joining() const { return s.constref(p).joining(); }
    bool mirrored() const { return s.constref(p).mirrored(); }
    QChar mirroredChar() const { return s.constref(p).mirroredChar(); }
    const QString &decomposition() const { return s.constref(p).decomposition(); }
    QChar::Decomposition decompositionTag() const { return s.constref(p).decompositionTag(); }
    unsigned char combiningClass() const { return s.constref(p).combiningClass(); }

    // Not the non-const ones of these.
    uchar cell() const { return s.constref(p).cell(); }
    uchar row() const { return s.constref(p).row(); }
#endif
};

inline QCharRef QString::at( uint i ) { return QCharRef(this,i); }
inline QCharRef QString::operator[]( int i ) { return at((uint)i); }

class Q_EXPORT QConstString : private QString {
public:
    QConstString( const QChar* unicode, uint length );
    ~QConstString();
    const QString& string() const { return *this; }
};

/*****************************************************************************
  QString stream functions
 *****************************************************************************/
#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream &operator<<( QDataStream &, const QString & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QString & );
#endif

/*****************************************************************************
  QString inline functions
 *****************************************************************************/

// These two move code into makeSharedNull() and deletesData()
// to improve cache-coherence (and reduce code bloat), while
// keeping the common cases fast.
//
// No safe way to pre-init shared_null on ALL compilers/linkers.
inline QString::QString() :
    d(shared_null ? shared_null : makeSharedNull())
{
    d->ref();
}
//
inline QString::~QString()
{
    if ( d->deref() ) {
        if ( d == shared_null )
            shared_null = 0;
        d->deleteSelf();
    }
}

inline QString QString::section( QChar sep, int start, int end, int flags ) const
{ return section(QString(sep), start, end, flags); }

inline QString QString::section( char sep, int start, int end, int flags ) const
{ return section(QChar(sep), start, end, flags); }

#ifndef QT_NO_CAST_ASCII
inline QString QString::section( const char *in_sep, int start, int end, int flags ) const
{ return section(QString(in_sep), start, end, flags); }
#endif

inline QString &QString::operator=( QChar c )
{ return *this = QString(c); }

inline QString &QString::operator=( char c )
{ return *this = QString(QChar(c)); }

inline bool QString::isNull() const
{ return unicode() == 0; }

inline bool QString::operator!() const
{ return isNull(); }

inline uint QString::length() const
{ return d->len; }

inline bool QString::isEmpty() const
{ return length() == 0; }

inline QString QString::copy() const
{ return QString( *this ); }

inline QString &QString::prepend( const QString & s )
{ return insert(0,s); }

inline QString &QString::prepend( QChar c )
{ return insert(0,c); }

inline QString &QString::prepend( char c )
{ return insert(0,c); }

inline QString &QString::append( const QString & s )
{ return operator+=(s); }

inline QString &QString::append( QChar c )
{ return operator+=(c); }

inline QString &QString::append( char c )
{ return operator+=(c); }

inline QString &QString::setNum( short n, int base )
{ return setNum((long)n, base); }

inline QString &QString::setNum( ushort n, int base )
{ return setNum((ulong)n, base); }

inline QString &QString::setNum( int n, int base )
{ return setNum((long)n, base); }

inline QString &QString::setNum( uint n, int base )
{ return setNum((ulong)n, base); }

inline QString &QString::setNum( float n, char f, int prec )
{ return setNum((double)n,f,prec); }

inline QString QString::arg(int a, int fieldwidth, int base) const
{ return arg((long)a, fieldwidth, base); }

inline QString QString::arg(uint a, int fieldwidth, int base) const
{ return arg((ulong)a, fieldwidth, base); }

inline QString QString::arg(short a, int fieldwidth, int base) const
{ return arg((long)a, fieldwidth, base); }

inline QString QString::arg(ushort a, int fieldwidth, int base) const
{ return arg((ulong)a, fieldwidth, base); }

inline int QString::find( char c, int index, bool cs ) const
{ return find(QChar(c), index, cs); }

inline int QString::findRev( char c, int index, bool cs) const
{ return findRev( QChar(c), index, cs ); }

#ifndef QT_NO_CAST_ASCII
inline int QString::find( const char* str, int index ) const
{ return find(QString::fromLatin1(str), index); }

inline int QString::findRev( const char* str, int index ) const
{ return findRev(QString::fromLatin1(str), index); }
#endif

/*****************************************************************************
  QString non-member operators
 *****************************************************************************/

Q_EXPORT bool operator!=( const QString &s1, const QString &s2 );
Q_EXPORT bool operator<( const QString &s1, const QString &s2 );
Q_EXPORT bool operator<=( const QString &s1, const QString &s2 );
Q_EXPORT bool operator==( const QString &s1, const QString &s2 );
Q_EXPORT bool operator>( const QString &s1, const QString &s2 );
Q_EXPORT bool operator>=( const QString &s1, const QString &s2 );
#ifndef QT_NO_CAST_ASCII
Q_EXPORT bool operator!=( const QString &s1, const char *s2 );
Q_EXPORT bool operator<( const QString &s1, const char *s2 );
Q_EXPORT bool operator<=( const QString &s1, const char *s2 );
Q_EXPORT bool operator==( const QString &s1, const char *s2 );
Q_EXPORT bool operator>( const QString &s1, const char *s2 );
Q_EXPORT bool operator>=( const QString &s1, const char *s2 );
Q_EXPORT bool operator!=( const char *s1, const QString &s2 );
Q_EXPORT bool operator<( const char *s1, const QString &s2 );
Q_EXPORT bool operator<=( const char *s1, const QString &s2 );
Q_EXPORT bool operator==( const char *s1, const QString &s2 );
//Q_EXPORT bool operator>( const char *s1, const QString &s2 ); // MSVC++
Q_EXPORT bool operator>=( const char *s1, const QString &s2 );
#endif

Q_EXPORT inline const QString operator+( const QString &s1, const QString &s2 )
{
    QString tmp( s1 );
    tmp += s2;
    return tmp;
}

#ifndef QT_NO_CAST_ASCII
Q_EXPORT inline const QString operator+( const QString &s1, const char *s2 )
{
    QString tmp( s1 );
    tmp += QString::fromLatin1(s2);
    return tmp;
}

Q_EXPORT inline const QString operator+( const char *s1, const QString &s2 )
{
    QString tmp = QString::fromLatin1( s1 );
    tmp += s2;
    return tmp;
}
#endif

Q_EXPORT inline const QString operator+( const QString &s1, QChar c2 )
{
    QString tmp( s1 );
    tmp += c2;
    return tmp;
}

Q_EXPORT inline const QString operator+( const QString &s1, char c2 )
{
    QString tmp( s1 );
    tmp += c2;
    return tmp;
}

Q_EXPORT inline const QString operator+( QChar c1, const QString &s2 )
{
    QString tmp;
    tmp += c1;
    tmp += s2;
    return tmp;
}

Q_EXPORT inline const QString operator+( char c1, const QString &s2 )
{
    QString tmp;
    tmp += c1;
    tmp += s2;
    return tmp;
}

#if defined(Q_OS_WIN32)
extern Q_EXPORT QString qt_winQString(void*);
extern Q_EXPORT const void* qt_winTchar(const QString& str, bool addnul);
extern Q_EXPORT void* qt_winTchar_new(const QString& str);
extern Q_EXPORT QCString qt_winQString2MB( const QString& s, int len=-1 );
extern Q_EXPORT QString qt_winMB2QString( const char* mb, int len=-1 );
#endif

#endif // QSTRING_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QString成员列表

完整的QString成员列表

这里是QString成员函数的完整列表，包括继承的成员。

  • QString()
  • ~QString()
  • append()
  • arg()
  • ascii()
  • at()
  • compare()
  • compose()
  • constref()
  • contains()
  • copy()
  • data()
  • endsWith()
  • fill()
  • find()
  • findRev()
  • fromLatin1()
  • fromLocal8Bit()
  • fromUtf8()
  • insert()
  • isEmpty()
  • isNull()
  • latin1()
  • left()
  • leftJustify()
  • length()
  • local8Bit()
  • localeAwareCompare()
  • lower()
  • mid()
  • number()
  • operator const char *()
  • operator!()
  • operator+=()
  • operator=()
  • operator[]()
  • prepend()
  • ref()
  • remove()
  • replace()
  • right()
  • rightJustify()
  • section()
  • setExpand()
  • setLatin1()
  • setLength()
  • setNum()
  • setUnicode()
  • setUnicodeCodes()
  • simplifyWhiteSpace()
  • sprintf()
  • startsWith()
  • stripWhiteSpace()
  • toDouble()
  • toFloat()
  • toInt()
  • toLong()
  • toShort()
  • toUInt()
  • toULong()
  • toUShort()
  • truncate()
  • unicode()
  • upper()
  • utf8()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QStringList Class

QStringList Class Reference

The QStringList class provides a list of strings. More...

#include <qstringlist.h>

Inherits QValueList<QString>.

List of all member functions.

Public Members

  • QStringList ()
  • QStringList ( const QStringList & l )
  • QStringList ( const QValueList<QString> & l )
  • QStringList ( const QString & i )
  • QStringList ( const char * i )
  • void sort ()
  • QString join ( const QString & sep ) const
  • QStringList grep ( const QString & str, bool cs = TRUE ) const
  • QStringList grep ( const QRegExp & expr ) const

Static Public Members

  • QStringList fromStrList ( const QStrList & ascii )
  • QStringList split ( const QString & sep, const QString & str, bool allowEmptyEntries = FALSE )
  • QStringList split ( const QChar & sep, const QString & str, bool allowEmptyEntries = FALSE )
  • QStringList split ( const QRegExp & sep, const QString & str, bool allowEmptyEntries = FALSE )

Detailed Description

The QStringList class provides a list of strings.

It is used to store and manipulate strings that logically belong together. Basically QStringList is a QValueList of QString objects. As opposed to QStrList, which stores pointers to characters, QStringList deals with real QString objects. It is the class of choice whenever you work with Unicode strings. QStringList is part of the Qt Template Library.

Like QString itself, QStringList objects are implicitly shared. Passing them around as value-parameters is both fast and safe.

Strings can be added to a list using append(), operator+=() or operator<<(), e.g.

    QStringList fonts;
    fonts.append( "Times" );
    fonts += "Courier";
    fonts += "Courier New";
    fonts << "Helvetica [Cronyx]" << "Helvetica [Adobe]";

String lists have an iterator, QStringList::Iterator(), e.g.

    for ( QStringList::Iterator it = fonts.begin(); it != fonts.end(); ++it ) {
        cout << *it << ":";
    }
    cout << endl;
    // Output:
    //  Times:Courier:Courier New:Helvetica [Cronyx]:Helvetica [Adobe]:

Many Qt functions return const string lists; to iterate over these you should make a copy and iterate over the copy.

You can concatenate all the strings in a string list into a single string (with an optional separator) using join(), e.g.

    QString allFonts = fonts.join( ", " );
    cout << allFonts << endl;
    // Output:
    //  Times, Courier, Courier New, Helvetica [Cronyx], Helvetica [Adobe]

You can sort the list with sort(), and extract a new list which contains only those strings which contain a particular substring (or match a particular regular expression) using the grep() functions, e.g.

    fonts.sort();
    cout << fonts.join( ", " ) << endl;
    // Output:
    //  Courier, Courier New, Helvetica [Adobe], Helvetica [Cronyx], Times

    QStringList helveticas = fonts.grep( "Helvetica" );
    cout << helveticas.join( ", " ) << endl;
    // Output:
    //  Helvetica [Adobe], Helvetica [Cronyx]

Existing strings can be split into string lists with character, string or regular expression separators, e.g.

    QString s = "Red\tGreen\tBlue";
    QStringList colors = QStringList::split( "\t", s );
    cout << colors.join( ", " ) << endl;
    // Output:
    //  Red, Green, Blue

See also Implicitly and Explicitly Shared Classes, Text Related Classes and Non-GUI Classes.

Member Function Documentation

QStringList::QStringList ()

Creates an empty string list.

QStringList::QStringList ( const QStringList & l )

Creates a copy of the list l. This function is very fast because QStringList is implicitly shared. However, for the programmer this is the same as a deep copy. If this list or the original one or some other list referencing the same shared data is modified, the modifying list first makes a copy, i.e. copy-on-write.

QStringList::QStringList ( const QValueList<QString> & l )

Constructs a new string list that is a copy of l.

QStringList::QStringList ( const QString & i )

Constructs a string list consisting of the single string i. Longer lists are easily created as follows:

    QStringList items;
    items << "Buy" << "Sell" << "Update" << "Value";

QStringList::QStringList ( const char * i )

Constructs a string list consisting of the single latin-1 string i.

QStringList QStringList::fromStrList ( const QStrList & ascii ) [static]

Converts from an ASCII-QStrList ascii to a QStringList (Unicode).

QStringList QStringList::grep ( const QString & str, bool cs = TRUE ) const

Returns a list of all strings containing the substring str.

If cs is TRUE, the grep is done case-sensitively; otherwise case is ignored.

QStringList QStringList::grep ( const QRegExp & expr ) const

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

Returns a list of all the strings that contain a substring that matches the regular expression expr.

QString QStringList::join ( const QString & sep ) const

Joins the string list into a single string with each element separated by the string sep.

See also split().

void QStringList::sort ()

Sorts the list of strings in ascending case-sensitive order.

Sorting is very fast. It uses the Qt Template Library's efficient HeapSort implementation that has a time complexity of O(n*log n).

If you want to sort your strings in an arbitrary order consider using a QMap. For example you could use a QMap<QString,QString> to create a case-insensitive ordering (e.g. mapping the lowercase text to the text), or a QMap<int,QString> to sort the strings by some integer index, etc.

Example: themes/themes.cpp.

QStringList QStringList::split ( const QRegExp & sep, const QString & str, bool allowEmptyEntries = FALSE ) [static]

Splits the string str into strings wherever the regular expression sep occurs, and returns the list of those strings.

If allowEmptyEntries is TRUE, an empty string is inserted in the list wherever the separator matches twice without intervening text.

For example, if you split the string "a,,b,c" on commas, split() returns the three-item list "a", "b", "c" if allowEmptyEntries is FALSE (the default), and the four-item list "a", "", "b", "c" if allowEmptyEntries is TRUE.

If sep does not match anywhere in str, split() returns a list consisting of the single string str.

See also join() and QString::section().

Examples: chart/element.cpp, dirview/dirview.cpp and network/httpd/httpd.cpp.

QStringList QStringList::split ( const QString & sep, const QString & str, bool allowEmptyEntries = FALSE ) [static]

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

This version of the function uses a QString as separator, rather than a regular expression.

If sep is an empty string, the return value is a list of one-character strings: split( QString( "" ), "mfc" ) returns the three-item list, "m", "f", "c".

If allowEmptyEntries is TRUE, an empty string is inserted in the list wherever the separator matches twice without intervening text.

See also join() and QString::section().

QStringList QStringList::split ( const QChar & sep, const QString & str, bool allowEmptyEntries = FALSE ) [static]

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

This version of the function uses a QChar as separator, rather than a regular expression.

See also join() and QString::section().

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


qstringlist.h Include File

qstringlist.h

This is the verbatim text of the qstringlist.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qstringlist.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QStringList class
**
** Created : 990406
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTRINGLIST_H
#define QSTRINGLIST_H

#ifndef QT_H
#include "qvaluelist.h"
#include "qstring.h"
#include "qstrlist.h"
#endif // QT_H

#ifndef QT_NO_STRINGLIST

class QRegExp;

class Q_EXPORT QStringList : public QValueList<QString>
{
public:
    QStringList() { }
    QStringList( const QStringList& l ) : QValueList<QString>(l) { }
    QStringList( const QValueList<QString>& l ) : QValueList<QString>(l) { }
    QStringList( const QString& i ) { append(i); }
#ifndef QT_NO_CAST_ASCII
    QStringList( const char* i ) { append(i); }
#endif

    static QStringList fromStrList(const QStrList&);

    void sort();

    static QStringList split( const QString &sep, const QString &str, bool allowEmptyEntries = FALSE );
    static QStringList split( const QChar &sep, const QString &str, bool allowEmptyEntries = FALSE );
    static QStringList split( const QRegExp &sep, const QString &str, bool allowEmptyEntries = FALSE );
    QString join( const QString &sep ) const;

    QStringList grep( const QString &str, bool cs = TRUE ) const;
    QStringList grep( const QRegExp &expr ) const;
};

#ifndef QT_NO_DATASTREAM
class QDataStream;
extern Q_EXPORT QDataStream &operator>>( QDataStream &, QStringList& );
extern Q_EXPORT QDataStream &operator<<( QDataStream &, const QStringList& );
#endif

#endif // QT_NO_STRINGLIST
#endif // QSTRINGLIST_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStringList Member List

Complete Member List for QStringList

This is the complete list of member functions for QStringList, including inherited members.

  • QStringList()
  • append()
  • at()
  • back()
  • begin()
  • clear()
  • contains()
  • count()
  • empty()
  • end()
  • erase()
  • find()
  • findIndex()
  • first()
  • fromLast()
  • fromStrList()
  • front()
  • grep()
  • insert()
  • isEmpty()
  • join()
  • last()
  • operator!=()
  • operator+()
  • operator+=()
  • operator<<()
  • operator=()
  • operator==()
  • operator[]()
  • pop_back()
  • pop_front()
  • prepend()
  • push_back()
  • push_front()
  • remove()
  • size()
  • sort()
  • split()


QStrList Class

QStrList Class Reference

The QStrList class provides a doubly-linked list of char*. More...

#include <qstrlist.h>

Inherits QPtrList<char>.

Inherited by QStrIList.

List of all member functions.

Public Members

  • QStrList ( bool deepCopies = TRUE )
  • QStrList ( const QStrList & list )
  • ~QStrList ()
  • QStrList & operator= ( const QStrList & list )

Detailed Description

The QStrList class provides a doubly-linked list of char*.

If you want a string list of QStrings use QStringList.

This class is a QPtrList<char> instance (a list of char*).

QStrList can make deep or shallow copies of the strings that are inserted.

A deep copy means that memory is allocated for the string and then the string data is copied into this memory. A shallow copy is just a copy of the pointer value and not of the string data itself.

The disadvantage of shallow copies is that because a pointer can be deleted only once, the program must put all strings in a central place and know when it is safe to delete them (i.e. when the strings are no longer referenced by other parts of the program). This can make the program more complex. The advantage of shallow copies is that shallow copies consume far less memory than deep copies. It is also much faster to copy a pointer (typically 4 or 8 bytes) than to copy string data.

A QStrList that operates on deep copies will, by default, turn on auto-deletion (see setAutoDelete()). Thus, by default QStrList will deallocate any string copies it allocates.

The virtual compareItems() function is reimplemented and does a case-sensitive string comparison. The inSort() function will insert strings in a sorted order. In general it is fastest to insert the strings as they come and sort() at the end; inSort() is useful when you just have to add a few extra strings to an already sorted list.

The QStrListIterator class is an iterator for QStrList.

See also Collection Classes, Text Related Classes and Non-GUI Classes.

Member Function Documentation

QStrList::QStrList ( bool deepCopies = TRUE )

Constructs an empty list of strings. Will make deep copies of all inserted strings if deepCopies is TRUE, or use shallow copies if deepCopies is FALSE.

QStrList::QStrList ( const QStrList & list )

Constructs a copy of list.

If list has deep copies, this list will also get deep copies. Only the pointers are copied (shallow copy) if the other list does not use deep copies.

QStrList::~QStrList ()

Destroys the list. All strings are removed.

QStrList & QStrList::operator= ( const QStrList & list )

Assigns list to this list and returns a reference to this list.

If list has deep copies, this list will also get deep copies. Only the pointers are copied (shallow copy) if the other list does not use deep copies.

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


qstrlist.h Include File

qstrlist.h

This is the verbatim text of the qstrlist.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QStrList, QStrIList and QStrListIterator classes
**
** Created : 920730
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTRLIST_H
#define QSTRLIST_H

#ifndef QT_H
#include "qstring.h"
#include "qptrlist.h"
#include "qdatastream.h"
#endif // QT_H

#if defined(Q_TEMPLATEDLL)
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrList<char>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrListIterator<char>;
#endif

#if defined(Q_QDOC)
class QStrListIterator : public QPtrListIterator<char>
{
};
#else
typedef QPtrListIterator<char> QStrListIterator;
#endif

class Q_EXPORT QStrList : public QPtrList<char>
{
public:
    QStrList( bool deepCopies=TRUE ) { dc = deepCopies; del_item = deepCopies; }
    QStrList( const QStrList & );
    ~QStrList()			{ clear(); }
    QStrList& operator=( const QStrList & );

private:
    QPtrCollection::Item newItem( QPtrCollection::Item d ) { return dc ? qstrdup( (const char*)d ) : d; }
    void deleteItem( QPtrCollection::Item d ) { if ( del_item ) delete[] (char*)d; }
    int compareItems( QPtrCollection::Item s1, QPtrCollection::Item s2 ) { return qstrcmp((const char*)s1,
                             (const char*)s2); }
#ifndef QT_NO_DATASTREAM
    QDataStream &read( QDataStream &s, QPtrCollection::Item &d )
                { s >> (char *&)d; return s; }
    QDataStream &write( QDataStream &s, QPtrCollection::Item d ) const
                { return s << (const char *)d; }
#endif
    bool  dc;
};

class Q_EXPORT QStrIList : public QStrList	// case insensitive string list
{
public:
    QStrIList( bool deepCopies=TRUE ) : QStrList( deepCopies ) {}
    ~QStrIList()			{ clear(); }
private:
    int	  compareItems( QPtrCollection::Item s1, QPtrCollection::Item s2 )
                { return qstricmp((const char*)s1,
                            (const char*)s2); }
};

inline QStrList & QStrList::operator=( const QStrList &strList )
{
    clear();
    dc = strList.dc;
    del_item = dc;
    QPtrList<char>::operator=( strList );
    return *this;
}

inline QStrList::QStrList( const QStrList &strList )
    : QPtrList<char>( strList )
{
    dc = FALSE;
    operator=( strList );
}

#endif // QSTRLIST_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStrList Member List

Complete Member List for QStrList

This is the complete list of member functions for QStrList, including inherited members.

  • QStrList()
  • ~QStrList()
  • append()
  • at()
  • autoDelete()
  • clear()
  • compareItems()
  • contains()
  • containsRef()
  • count()
  • current()
  • currentNode()
  • deleteItem()
  • find()
  • findNext()
  • findNextRef()
  • findRef()
  • first()
  • getFirst()
  • getLast()
  • inSort()
  • insert()
  • isEmpty()
  • last()
  • newItem()
  • next()
  • operator=()
  • operator==()
  • prepend()
  • prev()
  • read()
  • remove()
  • removeFirst()
  • removeLast()
  • removeNode()
  • removeRef()
  • setAutoDelete()
  • sort()
  • take()
  • takeNode()
  • toVector()
  • write()


QStrListIterator Class

QStrListIterator Class Reference

The QStrListIterator class is an iterator for the QStrList and QStrIList classes. More...

#include <qstrlist.h>

Inherits QPtrListIterator<char>.

List of all member functions.

Detailed Description

The QStrListIterator class is an iterator for the QStrList and QStrIList classes.

This class is a QPtrListIterator<char> instance. It can traverse the strings in the QStrList and QStrIList classes.

See also Non-GUI Classes.

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


QStrListIterator Member List

Complete Member List for QStrListIterator

This is the complete list of member functions for QStrListIterator, including inherited members.

  • atFirst()
  • atLast()
  • count()
  • current()
  • isEmpty()
  • operator type *()
  • operator()()
  • operator*()
  • operator++()
  • operator+=()
  • operator--()
  • operator-=()
  • operator=()
  • toFirst()
  • toLast()


QStyle Class

QStyle Class Reference

The QStyle class specifies the look and feel of a GUI. More...

#include <qstyle.h>

Inherits QObject.

Inherited by QCommonStyle.

List of all member functions.

Public Members

  • QStyle ()
  • virtual ~QStyle ()
  • virtual void polish ( QWidget * )
  • virtual void unPolish ( QWidget * )
  • virtual void polish ( QApplication * )
  • virtual void unPolish ( QApplication * )
  • virtual void polish ( QPalette & )
  • virtual void polishPopupMenu ( QPopupMenu * ) = 0
  • virtual QRect itemRect ( QPainter * p, const QRect & r, int flags, bool enabled, const QPixmap * pixmap, const QString & text, int len = -1 ) const
  • virtual void drawItem ( QPainter * p, const QRect & r, int flags, const QColorGroup & g, bool enabled, const QPixmap * pixmap, const QString & text, int len = -1, const QColor * penColor = 0 ) const
  • enum PrimitiveElement { PE_ButtonCommand, PE_ButtonDefault, PE_ButtonBevel, PE_ButtonTool, PE_ButtonDropDown, PE_FocusRect, PE_ArrowUp, PE_ArrowDown, PE_ArrowRight, PE_ArrowLeft, PE_SpinWidgetUp, PE_SpinWidgetDown, PE_SpinWidgetPlus, PE_SpinWidgetMinus, PE_Indicator, PE_IndicatorMask, PE_ExclusiveIndicator, PE_ExclusiveIndicatorMask, PE_DockWindowHandle, PE_DockWindowSeparator, PE_DockWindowResizeHandle, PE_Splitter, PE_Panel, PE_PanelPopup, PE_PanelMenuBar, PE_PanelDockWindow, PE_TabBarBase, PE_HeaderSection, PE_HeaderArrow, PE_StatusBarSection, PE_GroupBoxFrame, PE_Separator, PE_SizeGrip, PE_CheckMark, PE_ScrollBarAddLine, PE_ScrollBarSubLine, PE_ScrollBarAddPage, PE_ScrollBarSubPage, PE_ScrollBarSlider, PE_ScrollBarFirst, PE_ScrollBarLast, PE_ProgressBarChunk, PE_PanelLineEdit, PE_PanelTabWidget, PE_WindowFrame, PE_CustomBase = 0xf000000 }
  • enum StyleFlags { Style_Default = 0x00000000, Style_Enabled = 0x00000001, Style_Raised = 0x00000002, Style_Sunken = 0x00000004, Style_Off = 0x00000008, Style_NoChange = 0x00000010, Style_On = 0x00000020, Style_Down = 0x00000040, Style_Horizontal = 0x00000080, Style_HasFocus = 0x00000100, Style_Top = 0x00000200, Style_Bottom = 0x00000400, Style_FocusAtBorder = 0x00000800, Style_AutoRaise = 0x00001000, Style_MouseOver = 0x00002000, Style_Up = 0x00004000, Style_Selected = 0x00008000, Style_Active = 0x00010000, Style_ButtonDefault = 0x00020000 }
  • virtual void drawPrimitive ( PrimitiveElement pe, QPainter * p, const QRect & r, const QColorGroup & cg, SFlags flags = Style_Default, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • enum ControlElement { CE_PushButton, CE_PushButtonLabel, CE_CheckBox, CE_CheckBoxLabel, CE_RadioButton, CE_RadioButtonLabel, CE_TabBarTab, CE_TabBarLabel, CE_ProgressBarGroove, CE_ProgressBarContents, CE_ProgressBarLabel, CE_PopupMenuItem, CE_MenuBarItem, CE_ToolButtonLabel, CE_PopupMenuScroller, CE_CustomBase = 0xf0000000 }
  • virtual void drawControl ( ControlElement element, QPainter * p, const QWidget * widget, const QRect & r, const QColorGroup & cg, SFlags how = Style_Default, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • virtual void drawControlMask ( ControlElement element, QPainter * p, const QWidget * widget, const QRect & r, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • enum SubRect { SR_PushButtonContents, SR_PushButtonFocusRect, SR_CheckBoxIndicator, SR_CheckBoxContents, SR_CheckBoxFocusRect, SR_RadioButtonIndicator, SR_RadioButtonContents, SR_RadioButtonFocusRect, SR_ComboBoxFocusRect, SR_SliderFocusRect, SR_DockWindowHandleRect, SR_ProgressBarGroove, SR_ProgressBarContents, SR_ProgressBarLabel, SR_ToolButtonContents, SR_CustomBase = 0xf0000000 }
  • virtual QRect subRect ( SubRect subrect, const QWidget * widget ) const = 0
  • enum ComplexControl { CC_SpinWidget, CC_ComboBox, CC_ScrollBar, CC_Slider, CC_ToolButton, CC_TitleBar, CC_ListView, CC_CustomBase = 0xf0000000 }
  • enum SubControl { SC_None = 0x00000000, SC_ScrollBarAddLine = 0x00000001, SC_ScrollBarSubLine = 0x00000002, SC_ScrollBarAddPage = 0x00000004, SC_ScrollBarSubPage = 0x00000008, SC_ScrollBarFirst = 0x00000010, SC_ScrollBarLast = 0x00000020, SC_ScrollBarSlider = 0x00000040, SC_ScrollBarGroove = 0x00000080, SC_SpinWidgetUp = 0x00000001, SC_SpinWidgetDown = 0x00000002, SC_SpinWidgetFrame = 0x00000004, SC_SpinWidgetEditField = 0x00000008, SC_SpinWidgetButtonField = 0x00000010, SC_ComboBoxFrame = 0x00000001, SC_ComboBoxEditField = 0x00000002, SC_ComboBoxArrow = 0x00000004, SC_SliderGroove = 0x00000001, SC_SliderHandle = 0x00000002, SC_SliderTickmarks = 0x00000004, SC_ToolButton = 0x00000001, SC_ToolButtonMenu = 0x00000002, SC_TitleBarLabel = 0x00000001, SC_TitleBarSysMenu = 0x00000002, SC_TitleBarMinButton = 0x00000004, SC_TitleBarMaxButton = 0x00000008, SC_TitleBarCloseButton = 0x00000010, SC_TitleBarNormalButton = 0x00000020, SC_TitleBarShadeButton = 0x00000040, SC_TitleBarUnshadeButton = 0x00000080, SC_ListView = 0x00000001, SC_ListViewBranch = 0x00000002, SC_ListViewExpand = 0x00000004, SC_All = 0xffffffff }
  • virtual void drawComplexControl ( ComplexControl control, QPainter * p, const QWidget * widget, const QRect & r, const QColorGroup & cg, SFlags how = Style_Default, SCFlags sub = SC_All, SCFlags subActive = SC_None, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • virtual void drawComplexControlMask ( ComplexControl control, QPainter * p, const QWidget * widget, const QRect & r, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • virtual QRect querySubControlMetrics ( ComplexControl control, const QWidget * widget, SubControl subcontrol, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • virtual SubControl querySubControl ( ComplexControl control, const QWidget * widget, const QPoint & pos, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • enum PixelMetric { PM_ButtonMargin, PM_ButtonDefaultIndicator, PM_MenuButtonIndicator, PM_ButtonShiftHorizontal, PM_ButtonShiftVertical, PM_DefaultFrameWidth, PM_SpinBoxFrameWidth, PM_MaximumDragDistance, PM_ScrollBarExtent, PM_ScrollBarSliderMin, PM_SliderThickness, PM_SliderControlThickness, PM_SliderLength, PM_SliderTickmarkOffset, PM_SliderSpaceAvailable, PM_DockWindowSeparatorExtent, PM_DockWindowHandleExtent, PM_DockWindowFrameWidth, PM_MenuBarFrameWidth, PM_TabBarTabOverlap, PM_TabBarTabHSpace, PM_TabBarTabVSpace, PM_TabBarBaseHeight, PM_TabBarBaseOverlap, PM_ProgressBarChunkWidth, PM_SplitterWidth, PM_TitleBarHeight, PM_IndicatorWidth, PM_IndicatorHeight, PM_ExclusiveIndicatorWidth, PM_ExclusiveIndicatorHeight, PM_PopupMenuScrollerHeight, PM_CustomBase = 0xf0000000 }
  • virtual int pixelMetric ( PixelMetric metric, const QWidget * widget = 0 ) const = 0
  • enum ContentsType { CT_PushButton, CT_CheckBox, CT_RadioButton, CT_ToolButton, CT_ComboBox, CT_Splitter, CT_DockWindow, CT_ProgressBar, CT_PopupMenuItem, CT_CustomBase = 0xf0000000 }
  • virtual QSize sizeFromContents ( ContentsType contents, const QWidget * widget, const QSize & contentsSize, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • enum StyleHint { SH_EtchDisabledText, SH_GUIStyle, SH_ScrollBar_BackgroundMode, SH_ScrollBar_MiddleClickAbsolutePosition, SH_ScrollBar_ScrollWhenPointerLeavesControl, SH_TabBar_SelectMouseType, SH_TabBar_Alignment, SH_Header_ArrowAlignment, SH_Slider_SnapToValue, SH_Slider_SloppyKeyEvents, SH_ProgressDialog_CenterCancelButton, SH_ProgressDialog_TextLabelAlignment, SH_PrintDialog_RightAlignButtons, SH_MainWindow_SpaceBelowMenuBar, SH_FontDialog_SelectAssociatedText, SH_PopupMenu_AllowActiveAndDisabled, SH_PopupMenu_SpaceActivatesItem, SH_PopupMenu_SubMenuPopupDelay, SH_ScrollView_FrameOnlyAroundContents, SH_MenuBar_AltKeyNavigation, SH_ComboBox_ListMouseTracking, SH_PopupMenu_MouseTracking, SH_MenuBar_MouseTracking, SH_ItemView_ChangeHighlightOnFocus, SH_Widget_ShareActivation, SH_Workspace_FillSpaceOnMaximize, SH_ComboBox_Popup, SH_TitleBar_NoBorder, SH_ScrollBar_StopMouseOverSlider, SH_BlinkCursorWhenTextSelected, SH_RichText_FullWidthSelection, SH_PopupMenu_Scrollable, SH_CustomBase = 0xf0000000 }
  • virtual int styleHint ( StyleHint stylehint, const QWidget * widget = 0, const QStyleOption & opt = QStyleOption::Default, QStyleHintReturn * returnData = 0 ) const = 0
  • enum StylePixmap { SP_TitleBarMinButton, SP_TitleBarMaxButton, SP_TitleBarCloseButton, SP_TitleBarNormalButton, SP_TitleBarShadeButton, SP_TitleBarUnshadeButton, SP_DockWindowCloseButton, SP_MessageBoxInformation, SP_MessageBoxWarning, SP_MessageBoxCritical, SP_CustomBase = 0xf0000000 }
  • virtual QPixmap stylePixmap ( StylePixmap stylepixmap, const QWidget * widget = 0, const QStyleOption & opt = QStyleOption::Default ) const = 0
  • int defaultFrameWidth () const (obsolete)
  • void tabbarMetrics ( const QWidget * t, int & hf, int & vf, int & ov ) const (obsolete)
  • QSize scrollBarExtent () const (obsolete)

Static Public Members

  • QRect visualRect ( const QRect & logical, const QWidget * w )
  • QRect visualRect ( const QRect & logical, const QRect & bounding )

Detailed Description

The QStyle class specifies the look and feel of a GUI.

A large number of GUI elements are common to many widgets. The QStyle class allows the look of these elements to be modified across all widgets that use the QStyle functions. It also provides two feel options: Motif and Windows.

Although it is not possible to fully enumerate the look of graphical elements and the feel of widgets in a GUI, QStyle provides a considerable amount of control and customisability.

In Qt 1.x the look and feel option for widgets was specified by a single value: the GUIStyle. Starting with Qt 2.0, this notion was expanded to allow the look to be specified by virtual drawing functions.

Derived classes may reimplement some or all of the drawing functions to modify the look of all widgets that use those functions.

Languages written from right to left (such as Arabic and Hebrew) usually also mirror the whole layout of widgets. If you design a style, you should take special care when drawing asymmetric elements to make sure that they also look correct in a mirrored layout. You can start your application with -reverse to check the mirrored layout. Also notice, that for a reversed layout, the light usually comes from top right instead of top left.

The actual reverse layout is performed automatically when possible. However, for the sake of flexibility, the translation cannot be performed everywhere. The documentation for each function in the QStyle API states whether the function expects/returns logical or screen coordinates. Using logical coordinates (in ComplexControls, for example) provides great flexibility in controlling the look of a widget. Use visualRect() when necessary to translate logical coordinates into screen coordinates for drawing.

In Qt versions prior to 3.0, if you wanted a low level route into changing the appearance of a widget, you would reimplement polish(). With the new 3.0 style engine the recommended approach is to reimplement the draw functions, for example drawItem(), drawPrimitive(), drawControl(), drawControlMask(), drawComplexControl() and drawComplexControlMask(). Each of these functions is called with a range of parameters that provide information that you can use to determine how to draw them, e.g. style flags, rectangle, color group, etc.

For information on changing elements of an existing style or creating your own style see the Style overview.

Styles can also be created as plugins.

See also Widget Appearance and Style.

Member Type Documentation

QStyle::ComplexControl

This enum represents a ComplexControl. ComplexControls have different behaviour depending upon where the user clicks on them or which keys are pressed.

  • QStyle::CC_SpinWidget
  • QStyle::CC_ComboBox
  • QStyle::CC_ScrollBar
  • QStyle::CC_Slider
  • QStyle::CC_ToolButton
  • QStyle::CC_TitleBar
  • QStyle::CC_ListView

  • QStyle::CC_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also SubControl and drawComplexControl().

QStyle::ContentsType

This enum represents a ContentsType. It is used to calculate sizes for the contents of various widgets.

  • QStyle::CT_PushButton
  • QStyle::CT_CheckBox
  • QStyle::CT_RadioButton
  • QStyle::CT_ToolButton
  • QStyle::CT_ComboBox
  • QStyle::CT_Splitter
  • QStyle::CT_DockWindow
  • QStyle::CT_ProgressBar
  • QStyle::CT_PopupMenuItem

  • QStyle::CT_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also sizeFromContents().

QStyle::ControlElement

This enum represents a ControlElement. A ControlElement is part of a widget that performs some action or displays information to the user.

  • QStyle::CE_PushButton - the bevel and default indicator of a QPushButton.
  • QStyle::CE_PushButtonLabel - the label (iconset with text or pixmap) of a QPushButton.

  • QStyle::CE_CheckBox - the indicator of a QCheckBox.
  • QStyle::CE_CheckBoxLabel - the label (text or pixmap) of a QCheckBox.

  • QStyle::CE_RadioButton - the indicator of a QRadioButton.
  • QStyle::CE_RadioButtonLabel - the label (text or pixmap) of a QRadioButton.

  • QStyle::CE_TabBarTab - the tab within a QTabBar (a QTab).
  • QStyle::CE_TabBarLabel - the label within a QTab.

  • QStyle::CE_ProgressBarGroove - the groove where the progress indicator is drawn in a QProgressBar.
  • QStyle::CE_ProgressBarContents - the progress indicator of a QProgressBar.
  • QStyle::CE_ProgressBarLabel - the text label of a QProgressBar.

  • QStyle::CE_PopupMenuItem - a menu item in a QPopupMenu.
  • QStyle::CE_PopupMenuScroller - scrolling areas in a popumenu when the style supports scrolling.
  • QStyle::CE_MenuBarItem - a menu item in a QMenuBar.
  • QStyle::CE_ToolButtonLabel - a tool button's label.

  • QStyle::CE_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also drawControl().

QStyle::PixelMetric

This enum represents a PixelMetric. A PixelMetric is a style dependent size represented as a single pixel value.

  • QStyle::PM_ButtonMargin - amount of whitespace between pushbutton labels and the frame.
  • QStyle::PM_ButtonDefaultIndicator - width of the default-button indicator frame.
  • QStyle::PM_MenuButtonIndicator - width of the menu button indicator proportional to the widget height.
  • QStyle::PM_ButtonShiftHorizontal - horizontal contents shift of a button when the button is down.
  • QStyle::PM_ButtonShiftVertical - vertical contents shift of a button when the button is down.

  • QStyle::PM_DefaultFrameWidth - default frame width, usually 2.
  • QStyle::PM_SpinBoxFrameWidth - frame width of a spin box.

  • QStyle::PM_MaximumDragDistance - Some feels require the scrollbar or other sliders to jump back to the original position when the mouse pointer is too far away while dragging. A value of -1 disables this behavior.

  • QStyle::PM_ScrollBarExtent - width of a vertical scrollbar and the height of a horizontal scrollbar.
  • QStyle::PM_ScrollBarSliderMin - the minimum height of a vertical scrollbar's slider and the minimum width of a horiztonal scrollbar slider.

  • QStyle::PM_SliderThickness - total slider thickness.
  • QStyle::PM_SliderControlThickness - thickness of the slider handle.
  • QStyle::PM_SliderLength - length of the slider.
  • QStyle::PM_SliderTickmarkOffset - the offset between the tickmarks and the slider.
  • QStyle::PM_SliderSpaceAvailable - the available space for the slider to move.

  • QStyle::PM_DockWindowSeparatorExtent - width of a separator in a horiztonal dock window and the height of a separator in a vertical dock window.
  • QStyle::PM_DockWindowHandleExtent - width of the handle in a horizontal dock window and the height of the handle in a vertical dock window.
  • QStyle::PM_DockWindowFrameWidth - frame width of a dock window.

  • QStyle::PM_MenuBarFrameWidth - frame width of a menubar.

  • QStyle::PM_TabBarTabOverlap - number of pixels the tabs should overlap.
  • QStyle::PM_TabBarTabHSpace - extra space added to the tab width.
  • QStyle::PM_TabBarTabVSpace - extra space added to the tab height.
  • QStyle::PM_TabBarBaseHeight - height of the area between the tab bar and the tab pages.
  • QStyle::PM_TabBarBaseOverlap - number of pixels the tab bar overlaps the tab bar base.

  • QStyle::PM_ProgressBarChunkWidth - width of a chunk in a progress bar indicator.

  • QStyle::PM_SplitterWidth - width of a splitter.
  • QStyle::PM_TitleBarHeight - height of the title bar.
  • QStyle::PM_IndicatorWidth - width of a check box indicator.
  • QStyle::PM_IndicatorHeight - height of a checkbox indicator.
  • QStyle::PM_ExclusiveIndicatorWidth - width of a radio button indicator.
  • QStyle::PM_ExclusiveIndicatorHeight - height of a radio button indicator.
  • QStyle::PM_PopupMenuScrollerHeight - height of the scroller area in a popupmenu.
  • QStyle::PM_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also pixelMetric().

QStyle::PrimitiveElement

This enum represents the PrimitiveElements of a style. A PrimitiveElement is a common GUI element, such as a checkbox indicator or pushbutton bevel.

  • QStyle::PE_ButtonCommand - button used to initiate an action, for example, a QPushButton.
  • QStyle::PE_ButtonDefault - this button is the default button, e.g. in a dialog.
  • QStyle::PE_ButtonBevel - generic button bevel.
  • QStyle::PE_ButtonTool - tool button, for example, a QToolButton.
  • QStyle::PE_ButtonDropDown - drop down button, for example, a tool button that displays a popup menu, for example, QPopupMenu.

  • QStyle::PE_FocusRect - generic focus indicator.

  • QStyle::PE_ArrowUp - up arrow.
  • QStyle::PE_ArrowDown - down arrow.
  • QStyle::PE_ArrowRight - right arrow.
  • QStyle::PE_ArrowLeft - left arrow.

  • QStyle::PE_SpinWidgetUp - up symbol for a spin widget, for example a QSpinBox.
  • QStyle::PE_SpinWidgetDown - down symbol for a spin widget.
  • QStyle::PE_SpinWidgetPlus - increase symbol for a spin widget.
  • QStyle::PE_SpinWidgetMinus - decrease symbol for a spin widget.

  • QStyle::PE_Indicator - on/off indicator, for example, a QCheckBox.
  • QStyle::PE_IndicatorMask - bitmap mask for an indicator.
  • QStyle::PE_ExclusiveIndicator - exclusive on/off indicator, for example, a QRadioButton.
  • QStyle::PE_ExclusiveIndicatorMask - bitmap mask for an exclusive indicator.

  • QStyle::PE_DockWindowHandle - tear off handle for dock windows and toolbars, for example QDockWindows and QToolBars.
  • QStyle::PE_DockWindowSeparator - item separator for dock window and toolbar contents.
  • QStyle::PE_DockWindowResizeHandle - resize handle for dock windows.
  • QStyle::PE_Splitter - splitter handle; see also QSplitter.

  • QStyle::PE_Panel - generic panel frame; see also QFrame.
  • QStyle::PE_PanelPopup - panel frame for popup windows/menus; see also QPopupMenu.
  • QStyle::PE_PanelMenuBar - panel frame for menu bars.
  • QStyle::PE_PanelDockWindow - panel frame for dock windows and toolbars.
  • QStyle::PE_PanelTabWidget - panel frame for tab widgets.
  • QStyle::PE_PanelLineEdit - panel frame for line edits.
  • QStyle::PE_TabBarBase - area below tabs in a tab widget, for example, QTab.

  • QStyle::PE_HeaderSection - section of a list or table header; see also QHeader.
  • QStyle::PE_HeaderArrow - arrow used to indicate sorting on a list or table header
  • QStyle::PE_StatusBarSection - section of a status bar; see also QStatusBar.

  • QStyle::PE_GroupBoxFrame - frame around a group box; see also QGroupBox.
  • QStyle::PE_WindowFrame - frame around a MDI or docking window

  • QStyle::PE_Separator - generic separator.

  • QStyle::PE_SizeGrip - window resize handle; see also QSizeGrip.

  • QStyle::PE_CheckMark - generic check mark; see also QCheckBox.

  • QStyle::PE_ScrollBarAddLine - scrollbar line increase indicator (i.e. scroll down); see also QScrollBar.
  • QStyle::PE_ScrollBarSubLine - scrollbar line decrease indicator (i.e. scroll up).
  • QStyle::PE_ScrollBarAddPage - scolllbar page increase indicator (i.e. page down).
  • QStyle::PE_ScrollBarSubPage - scrollbar page decrease indicator (i.e. page up).
  • QStyle::PE_ScrollBarSlider - scrollbar slider
  • QStyle::PE_ScrollBarFirst - scrollbar first line indicator (i.e. home).
  • QStyle::PE_ScrollBarLast - scrollbar last line indicator (i.e. end).

  • QStyle::PE_ProgressBarChunk - section of a progress bar indicator; see also QProgressBar.
  • QStyle::PE_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also drawPrimitive().

QStyle::StyleFlags

This enum represents flags for drawing PrimitiveElements. Not all primitives use all of these flags. Note that these flags may mean different things to different primitives. For an explanation of the relationship between primitives and their flags, as well as the different meanings of the flags, see the Style overview.

  • QStyle::Style_Default
  • QStyle::Style_Enabled
  • QStyle::Style_Raised
  • QStyle::Style_Sunken
  • QStyle::Style_Off
  • QStyle::Style_NoChange
  • QStyle::Style_On
  • QStyle::Style_Down
  • QStyle::Style_Horizontal
  • QStyle::Style_HasFocus
  • QStyle::Style_Top
  • QStyle::Style_Bottom
  • QStyle::Style_FocusAtBorder
  • QStyle::Style_AutoRaise
  • QStyle::Style_MouseOver
  • QStyle::Style_Up
  • QStyle::Style_Selected
  • QStyle::Style_HasFocus
  • QStyle::Style_Active
  • QStyle::Style_ButtonDefault

See also drawPrimitive().

QStyle::StyleHint

This enum represents a StyleHint. A StyleHint is a general look and/or feel hint.

  • QStyle::SH_EtchDisabledText - disabled text is "etched" like Windows.
  • QStyle::SH_GUIStyle - the GUI style to use.
  • QStyle::SH_ScrollBar_BackgroundMode - the background mode for a QScrollBar. Possible values are any of those in the BackgroundMode enum.
  • QStyle::SH_ScrollBar_MiddleClickAbsolutePosition - a boolean value. If TRUE, middle clicking on a scrollbar causes the slider to jump to that position. If FALSE, the middle clicking is ignored.
  • QStyle::SH_ScrollBar_ScrollWhenPointerLeavesControl - a boolean value. If TRUE, when clicking a scrollbar SubControl, holding the mouse button down and moving the pointer outside the SubControl, the scrollbar continues to scroll. If FALSE, the scollbar stops scrolling when the pointer leaves the SubControl.

  • QStyle::SH_TabBar_Alignment - the alignment for tabs in a QTabWidget. Possible values are Qt::AlignLeft, Qt::AlignCenter and Qt::AlignRight.
  • QStyle::SH_Header_ArrowAlignment - the placement of the sorting indicator may appear in list or table headers. Possible values are Qt::Left or Qt::Right.
  • QStyle::SH_Slider_SnapToValue - sliders snap to values while moving, like Windows
  • QStyle::SH_Slider_SloppyKeyEvents - key presses handled in a sloppy manner, i.e. left on a vertical slider subtracts a line.
  • QStyle::SH_ProgressDialog_CenterCancelButton - center button on progress dialogs, like Motif, otherwise right aligned.
  • QStyle::SH_ProgressDialog_TextLabelAlignment - Qt::AlignmentFlags -- text label alignment in progress dialogs; Center on windows, Auto|VCenter otherwise.
  • QStyle::SH_PrintDialog_RightAlignButtons - right align buttons in the print dialog, like Windows.
  • QStyle::SH_MainWindow_SpaceBelowMenuBar - 1 or 2 pixel space between the menubar and the dockarea, like Windows.
  • QStyle::SH_FontDialog_SelectAssociatedText - select the text in the line edit, or when selecting an item from the listbox, or when the line edit receives focus, like Windows.
  • QStyle::SH_PopupMenu_AllowActiveAndDisabled - allows disabled menu items to be active.
  • QStyle::SH_PopupMenu_SpaceActivatesItem - pressing Space activates the item, like Motif.
  • QStyle::SH_PopupMenu_SubMenuPopupDelay - the number of milliseconds to wait before opening a submenu; 256 on windows, 96 on Motif.
  • QStyle::SH_ScrollView_FrameOnlyAroundContents - whether scrollviews draw their frame only around contents (like Motif), or around contents, scrollbars and corner widgets (like Windows).
  • QStyle::SH_MenuBar_AltKeyNavigation - menubars items are navigable by pressing Alt, followed by using the arrow keys to select the desired item.
  • QStyle::SH_ComboBox_ListMouseTracking - mouse tracking in combobox dropdown lists.
  • QStyle::SH_PopupMenu_MouseTracking - mouse tracking in popup menus.
  • QStyle::SH_MenuBar_MouseTracking - mouse tracking in menubars.
  • QStyle::SH_ItemView_ChangeHighlightOnFocus - gray out selected items when losing focus.
  • QStyle::SH_Widget_ShareActivation - turn on sharing activation with floating modeless dialogs.
  • QStyle::SH_TabBar_SelectMouseType - which type of mouse event should cause a tab to be selected.
  • QStyle::SH_ComboBox_Popup - allows popups as a combobox dropdown menu.
  • QStyle::SH_Workspace_FillSpaceOnMaximize - the workspace should maximize the client area.
  • QStyle::SH_TitleBar_NoBorder - the titlebar has no border
  • QStyle::SH_ScrollBar_StopMouseOverSlider - stops autorepeat when slider reaches mouse
  • QStyle::SH_BlinkCursorWhenTextSelected - whether cursor should blink when text is selected
  • QStyle::SH_RichText_FullWidthSelection - whether richtext selections should extend the full width of the document.
  • QStyle::SH_PopupMenu_Scrollable - whether popupmenu's must support scrolling.
  • QStyle::SH_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also styleHint().

QStyle::StylePixmap

This enum represents a StylePixmap. A StylePixmap is a pixmap that can follow some existing GUI style or guideline.

  • QStyle::SP_TitleBarMinButton - minimize button on titlebars. For example, in a QWorkspace.
  • QStyle::SP_TitleBarMaxButton - maximize button on titlebars.
  • QStyle::SP_TitleBarCloseButton - close button on titlebars.
  • QStyle::SP_TitleBarNormalButton - normal (restore) button on titlebars.
  • QStyle::SP_TitleBarShadeButton - shade button on titlebars.
  • QStyle::SP_TitleBarUnshadeButton - unshade button on titlebars.
  • QStyle::SP_MessageBoxInformation - the 'information' icon.
  • QStyle::SP_MessageBoxWarning - the 'warning' icon.
  • QStyle::SP_MessageBoxCritical - the 'critical' icon.

  • QStyle::SP_DockWindowCloseButton - close button on dock windows; see also QDockWindow.

  • QStyle::SP_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also stylePixmap().

QStyle::SubControl

This enum represents a SubControl within a ComplexControl.

  • QStyle::SC_None - special value that matches no other SubControl.

  • QStyle::SC_ScrollBarAddLine - scrollbar add line (i.e. down/right arrow); see also QScrollbar.
  • QStyle::SC_ScrollBarSubLine - scrollbar sub line (i.e. up/left arrow).
  • QStyle::SC_ScrollBarAddPage - scrollbar add page (i.e. page down).
  • QStyle::SC_ScrollBarSubPage - scrollbar sub page (i.e. page up).
  • QStyle::SC_ScrollBarFirst - scrollbar first line (i.e. home).
  • QStyle::SC_ScrollBarLast - scrollbar last line (i.e. end).
  • QStyle::SC_ScrollBarSlider - scrollbar slider handle.
  • QStyle::SC_ScrollBarGroove - special subcontrol which contains the area in which the slider handle may move.

  • QStyle::SC_SpinWidgetUp - spinwidget up/increase; see also QSpinBox.
  • QStyle::SC_SpinWidgetDown - spinwidget down/decrease.
  • QStyle::SC_SpinWidgetFrame - spinwidget frame.
  • QStyle::SC_SpinWidgetEditField - spinwidget edit field.
  • QStyle::SC_SpinWidgetButtonField - spinwidget button field.

  • QStyle::SC_ComboBoxEditField - combobox edit field; see also QComboBox.
  • QStyle::SC_ComboBoxArrow - combobox arrow
  • QStyle::SC_ComboBoxFrame - combobox frame

  • QStyle::SC_SliderGroove - special subcontrol which contains the area in which the slider handle may move.
  • QStyle::SC_SliderHandle - slider handle.
  • QStyle::SC_SliderTickmarks - slider tickmarks.

  • QStyle::SC_ToolButton - tool button; see also QToolbutton.
  • QStyle::SC_ToolButtonMenu - subcontrol for opening a popup menu in a tool button; see also QPopupMenu.

  • QStyle::SC_TitleBarSysMenu - system menu button (i.e. restore, close, etc.).
  • QStyle::SC_TitleBarMinButton - minimize button.
  • QStyle::SC_TitleBarMaxButton - maximize button.
  • QStyle::SC_TitleBarCloseButton - close button.
  • QStyle::SC_TitleBarLabel - window title label.
  • QStyle::SC_TitleBarNormalButton - normal (restore) button.
  • QStyle::SC_TitleBarShadeButton - shade button.
  • QStyle::SC_TitleBarUnshadeButton - unshade button.

  • QStyle::SC_ListView - the list view area.
  • QStyle::SC_ListViewBranch - (internal)
  • QStyle::SC_ListViewExpand - expand item (i.e. show/hide child items).

  • QStyle::SC_All - special value that matches all SubControls.

See also ComplexControl.

QStyle::SubRect

This enum represents a sub-area of a widget. Style implementations would use these areas to draw the different parts of a widget.

  • QStyle::SR_PushButtonContents - area containing the label (iconset with text or pixmap).
  • QStyle::SR_PushButtonFocusRect - area for the focus rect (usually larger than the contents rect).
  • QStyle::SR_CheckBoxIndicator - area for the state indicator (e.g. check mark).
  • QStyle::SR_CheckBoxContents - area for the label (text or pixmap).
  • QStyle::SR_CheckBoxFocusRect - area for the focus indicator.

  • QStyle::SR_RadioButtonIndicator - area for the state indicator.
  • QStyle::SR_RadioButtonContents - area for the label.
  • QStyle::SR_RadioButtonFocusRect - area for the focus indicator.

  • QStyle::SR_ComboBoxFocusRect - area for the focus indicator.

  • QStyle::SR_SliderFocusRect - area for the focus indicator.

  • QStyle::SR_DockWindowHandleRect - area for the tear-off handle.

  • QStyle::SR_ProgressBarGroove - area for the groove.
  • QStyle::SR_ProgressBarContents - area for the progress indicator.
  • QStyle::SR_ProgressBarLabel - area for the text label.

  • QStyle::SR_ToolButtonContents - area for the tool button's label.

  • QStyle::SR_CustomBase - base value for custom ControlElements. All values above this are reserved for custom use. Therefore, custom values must be greater than this value.

See also subRect().

Member Function Documentation

QStyle::QStyle ()

Constructs a QStyle.

QStyle::~QStyle () [virtual]

Destroys the style and frees all allocated resources.

int QStyle::defaultFrameWidth () const

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

void QStyle::drawComplexControl ( ComplexControl control, QPainter * p, const QWidget * widget, const QRect & r, const QColorGroup & cg, SFlags how = Style_Default, SCFlags sub = SC_All, SCFlags subActive = SC_None, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Draws the ComplexControl control using the painter p in the area r. Colors are used from the color group cg. The sub argument specifies which SubControls to draw. Multiple SubControls can be OR'ed together. The subActive argument specifies which SubControl is active.

The rect r should be in logical coordinates. Reimplementations of this function should use visualRect() to change the logical coordinates into screen coordinates when using drawPrimitive() and drawControl().

The how argument is used to control how the ComplexControl is drawn. Multiple flags can OR'ed together. See the table below for an explanation of which flags are used with the various ComplexControls.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of control. The opt argument can be used to pass extra information required when drawing the ComplexControl. Note that opt may be the default value even for ComplexControls that can make use of the extra options. See the table below for the appropriate widget and opt usage:

ComplexControl & Widget Cast | Style Flags | Notes | Options | Notes
CC_SpinWidget(const QSpinWidget *) | Style_Enabled | Set if the spinwidget is enabled. | Unused.
Style_HasFocus | Set if the spinwidget has input focus.
CC_ComboBox(const QComboBox *) | Style_Enabled | Set if the combobox is enabled. | Unused.
Style_HasFocus | Set if the combobox has input focus.
CC_ScrollBar(const QScrollBar *) | Style_Enabled | Set if the scrollbar is enabled. | Unused.
Style_HasFocus | Set if the scrollbar has input focus.
CC_Slider(const QSlider *) | Style_Enabled | Set if the slider is enabled. | Unused.
Style_HasFocus | Set if the slider has input focus.
CC_ToolButton(const QToolButton *) Style_Enabled Set if the toolbutton is enabled. QStyleOption ( ArrowType t )
  • opt.arrowType()
When the tool button only contains an arrow, t is the arrow's type.
Style_HasFocus | Set if the toolbutton has input focus.
Style_Down | Set if the toolbutton is down (ie. mouse button or space pressed).
Style_On | Set if the toolbutton is a toggle button and is toggled on.
Style_AutoRaise | Set if the toolbutton has auto-raise enabled.
Style_Raised | Set if the button is not down, not on and doesn't contain the mouse when auto-raise is enabled.
CC_TitleBar(const QWidget *) | Style_Enabled | Set if the titlebar is enabled. | Unused.
CC_ListView(const QListView *) Style_Enabled Set if the titlebar is enabled. QStyleOption ( QListViewItem *item )
  • opt.listViewItem()
item is the item that needs branches drawn

See also ComplexControl and SubControl.

void QStyle::drawComplexControlMask ( ComplexControl control, QPainter * p, const QWidget * widget, const QRect & r, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Draw a bitmask for the ComplexControl control using the painter p in the area r. See drawComplexControl() for an explanation of the use of the widget and opt arguments.

The rect r should be in logical coordinates. Reimplementations of this function should use visualRect() to change the logical corrdinates into screen coordinates when using drawPrimitive() and drawControl().

See also drawComplexControl() and ComplexControl.

void QStyle::drawControl ( ControlElement element, QPainter * p, const QWidget * widget, const QRect & r, const QColorGroup & cg, SFlags how = Style_Default, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Draws the ControlElement element using the painter p in the area r. Colors are used from the color group cg.

The rect r should be in screen coordinates.

The how argument is used to control how the ControlElement is drawn. Multiple flags can be OR'ed together. See the table below for an explanation of which flags are used with the various ControlElements.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of element. The opt argument can be used to pass extra information required when drawing the ControlElement. Note that opt may be the default value even for ControlElements that can make use of the extra options. See the table below for the appropriate widget and opt usage:

ControlElement & Widget Cast | Style Flags | Notes | Options | Notes
CE_PushButton(const QPushButton *)

and

CE_PushButtonLabel(const QPushButton *)

Style_Enabled Set if the button is enabled. Unused.
Style_HasFocus | Set if the button has input focus.
Style_Raised | Set if the button is not down, not on and not flat.
Style_On | Set if the button is a toggle button and toggled on.
Style_Down | Set if the button is down (i.e., the mouse button or space bar is pressed on the button).
Style_ButtonDefault | Set if the button is a default button.
CE_CheckBox(const QCheckBox *)

and

CE_CheckBoxLabel(const QCheckBox *)

Style_Enabled Set if the checkbox is enabled. Unused.
Style_HasFocus | Set if the checkbox has input focus.
Style_On | Set if the checkbox is checked.
Style_Off | Set if the checkbox is not checked.
Style_NoChange | Set if the checkbox is in the NoChange state.
Style_Down | Set if the checkbox is down (i.e., the mouse button or space bar is pressed on the button).
CE_RadioButton(const QRadioButton *)

and

CE_RadioButtonLabel(const QRadioButton *)

Style_Enabled Set if the radiobutton is enabled. Unused.
Style_HasFocus | Set if the radiobutton has input focus.
Style_On | Set if the radiobutton is checked.
Style_Off | Set if the radiobutton is not checked.
Style_Down | Set if the radiobutton is down (i.e., the mouse button or space bar is pressed on the radiobutton).
CE_TabBarTab(const QTabBar *)

and

CE_TabBarLabel(const QTabBar *)

Style_Enabled Set if the tabbar and tab is enabled. QStyleOption ( QTab *t )
  • opt.tab()
t is the QTab being drawn.
Style_Selected | Set if the tab is the current tab.
CE_ProgressBarGroove(const QProgressBar *)

and

CE_ProgressBarContents(const QProgressBar *)

and

CE_ProgressBarLabel(const QProgressBar *)

Style_Enabled Set if the progressbar is enabled. Unused.
Style_HasFocus | Set if the progressbar has input focus.
CE_PopupMenuItem(const QPopupMenu *) Style_Enabled Set if the menuitem is enabled. QStyleOption ( QMenuItem *mi, int tabwidth, int maxpmwidth )
  • opt.menuItem()
  • opt.tabWidth()
  • opt.maxIconWidth()
mi is the menu item being drawn. QMenuItem is currently an internal class.
Style_Active | Set if the menuitem is the current item. | tabwidth is the width of the tab column where key accelerators are drawn.
Style_Down | Set if the menuitem is down (i.e., the mouse button or space bar is pressed). | maxpmwidth is the maximum width of the check column where checkmarks and iconsets are drawn.
CE_MenuBarItem(const QMenuBar *) Style_Enabled Set if the menuitem is enabled QStyleOption ( QMenuItem *mi )
  • opt.menuItem()
mi is the menu item being drawn.
Style_Active | Set if the menuitem is the current item.
Style_Down | Set if the menuitem is down (i.e., a mouse button or the space bar is pressed).
Style_HasFocus | Set if the menubar has input focus.
CE_ToolButtonLabel(const QToolButton *) Style_Enabled Set if the toolbutton is enabled. QStyleOption ( ArrowType t )
  • opt.arrowType()
When the tool button only contains an arrow, t is the arrow's type.
Style_HasFocus | Set if the toolbutton has input focus.
Style_Down | Set if the toolbutton is down (i.e., a mouse button or the space is pressed).
Style_On | Set if the toolbutton is a toggle button and is toggled on.
Style_AutoRaise | Set if the toolbutton has auto-raise enabled.
Style_MouseOver | Set if the mouse pointer is over the toolbutton.
Style_Raised | Set if the button is not down, not on and doesn't contain the mouse when auto-raise is enabled.

See also ControlElement and StyleFlags.

void QStyle::drawControlMask ( ControlElement element, QPainter * p, const QWidget * widget, const QRect & r, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Draw a bitmask for the ControlElement element using the painter p in the area r. See drawControl() for an explanation of the use of the widget and opt arguments.

The rect r should be in screen coordinates.

See also drawControl() and ControlElement.

void QStyle::drawItem ( QPainter * p, const QRect & r, int flags, const QColorGroup & g, bool enabled, const QPixmap * pixmap, const QString & text, int len = -1, const QColor * penColor = 0 ) const [virtual]

Draws the text or pixmap in rectangle r using painter p and color group g. The pen color is specified with penColor. The enabled bool indicates whether or not the item is enabled; when reimplementing this bool should influence how the item is drawn. If len is -1 (the default) all the text is drawn; otherwise only the first len characters of text are drawn. The text is aligned and wrapped according to the alignment flags (see Qt::AlignmentFlags).

By default, if both the text and the pixmap are not null, the pixmap is drawn and the text is ignored.

void QStyle::drawPrimitive ( PrimitiveElement pe, QPainter * p, const QRect & r, const QColorGroup & cg, SFlags flags = Style_Default, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Draws the style PrimitiveElement pe using the painter p in the area r. Colors are used from the color group cg.

The rect r should be in screen coordinates.

The flags argument is used to control how the PrimitiveElement is drawn. Multiple flags can be OR'ed together.

For example, a pressed button would be drawn with the flags Style_Enabled and Style_Down.

The opt argument can be used to control how various PrimitiveElements are drawn. Note that opt may be the default value even for PrimitiveElements that make use of extra options. When opt is non-default, it is used as follows:

PrimitiveElement Options Notes
PE_FocusRect QStyleOption ( const QColor & bg )
  • opt.color()
bg is the background color on which the focus rect is being drawn.
PE_Panel QStyleOption ( int linewidth, int midlinewidth )
  • opt.lineWidth()
  • opt.midLineWidth()
linewidth is the line width for drawing the panel.
midlinewidth is the mid-line width for drawing the panel.
PE_PanelPopup QStyleOption ( int linewidth, int midlinewidth )
  • opt.lineWidth()
  • opt.midLineWidth()
linewidth is the line width for drawing the panel.
midlinewidth is the mid-line width for drawing the panel.
PE_PanelMenuBar QStyleOption ( int linewidth, int midlinewidth )
  • opt.lineWidth()
  • opt.midLineWidth()
linewidth is the line width for drawing the panel.
midlinewidth is the mid-line width for drawing the panel.
PE_PanelDockWindow QStyleOption ( int linewidth, int midlinewidth )
  • opt.lineWidth()
  • opt.midLineWidth()
linewidth is the line width for drawing the panel.
midlinewidth is the mid-line width for drawing the panel.
PE_GroupBoxFrame QStyleOption ( int linewidth, int midlinewidth, int shape, int shadow )
  • opt.lineWidth()
  • opt.midLineWidth()
  • opt.frameShape()
  • opt.frameShadow()
linewidth is the line width for the group box.
midlinewidth is the mid-line width for the group box.
shape is the frame shape for the group box.
shadow is the frame shadow for the group box.

For all other PrimitiveElements, opt is unused.

See also StyleFlags.

Example: themes/wood.cpp.

QRect QStyle::itemRect ( QPainter * p, const QRect & r, int flags, bool enabled, const QPixmap * pixmap, const QString & text, int len = -1 ) const [virtual]

Returns the appropriate area (see below) within rectangle r in which to draw the text or pixmap using painter p. If len is -1 (the default) all the text is drawn; otherwise only the first len characters of text are drawn. The text is aligned in accordance with the alignment flags (see Qt::AlignmentFlags). The enabled bool indicates whether or not the item is enabled.

If r is larger than the area needed to render the text the rectangle that is returned will be offset within r in accordance with the alignment flags. For example if flags is AlignCenter the returned rectangle will be centered within r. If r is smaller than the area needed the rectangle that is returned will be larger than r (the smallest rectangle large enough to render the text or pixmap).

By default, if both the text and the pixmap are not null, the pixmap is drawn and the text is ignored.

int QStyle::pixelMetric ( PixelMetric metric, const QWidget * widget = 0 ) const [pure virtual]

Returns the pixel metric for metric. The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of metric. Note that widget may be zero even for PixelMetrics that can make use of widget. See the table below for the appropriate widget casts:

PixelMetric | Widget Cast
PM_SliderControlThickness | (const QSlider *)
PM_SliderLength | (const QSlider *)
PM_SliderTickmarkOffset | (const QSlider *)
PM_SliderSpaceAvailable | (const QSlider *)
PM_TabBarTabOverlap | (const QTabBar *)
PM_TabBarTabHSpace | (const QTabBar *)
PM_TabBarTabVSpace | (const QTabBar *)
PM_TabBarBaseHeight | (const QTabBar *)
PM_TabBarBaseOverlap | (const QTabBar *)

void QStyle::polish ( QWidget * ) [virtual]

Initializes the appearance of a widget.

This function is called for every widget at some point after it has been fully created but just before it is shown the very first time.

Reasonable actions in this function might be to call QWidget::setBackgroundMode() for the widget. An example of highly unreasonable use would be setting the geometry! Reimplementing this function gives you a back-door through which you can change the appearance of a widget. With Qt 3.0's style engine you will rarely need to write your own polish(); instead reimplement drawItem(), drawPrimitive(), etc.

The QWidget::inherits() function may provide enough information to allow class-specific customizations. But be careful not to hard-code things too much because new QStyle subclasses are expected to work reasonably with all current and future widgets.

See also unPolish().

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

void QStyle::polish ( QApplication * ) [virtual]

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

Late initialization of the QApplication object.

See also unPolish().

void QStyle::polish ( QPalette & ) [virtual]

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

The style may have certain requirements for color palettes. In this function it has the chance to change the palette according to these requirements.

See also QPalette and QApplication::setPalette().

void QStyle::polishPopupMenu ( QPopupMenu * ) [pure virtual]

Polishes the popup menu according to the GUI style. This usually means setting the mouse tracking (QPopupMenu::setMouseTracking()) and whether the menu is checkable by default (QPopupMenu::setCheckable()).

SubControl QStyle::querySubControl ( ComplexControl control, const QWidget * widget, const QPoint & pos, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Returns the SubControl for widget at the point pos. The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of control. The opt argument can be used to pass extra information required when drawing the ComplexControl. Note that opt may be the default value even for ComplexControls that can make use of the extra options. See drawComplexControl() for an explanation of the widget and opt arguments.

Note that pos is passed in screen coordinates. When using querySubControlMetrics() to check for hits and misses, use visualRect() to change the logical coordinates into screen coordinates.

See also drawComplexControl(), ComplexControl, SubControl and querySubControlMetrics().

QRect QStyle::querySubControlMetrics ( ComplexControl control, const QWidget * widget, SubControl subcontrol, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Returns the rect for the SubControl subcontrol for widget in logical coordinates.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of control. The opt argument can be used to pass extra information required when drawing the ComplexControl. Note that opt may be the default value even for ComplexControls that can make use of the extra options. See drawComplexControl() for an explanation of the widget and opt arguments.

See also drawComplexControl(), ComplexControl and SubControl.

QSize QStyle::scrollBarExtent () const

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

QSize QStyle::sizeFromContents ( ContentsType contents, const QWidget * widget, const QSize & contentsSize, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Returns the size of widget based on the contents size contentsSize.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of contents. The opt argument can be used to pass extra information required when calculating the size. Note that opt may be the default value even for ContentsTypes that can make use of the extra options. See the table below for the appropriate widget and opt usage:

ContentsType | Widget Cast | Options | Notes
CT_PushButton | (const QPushButton *) | Unused.
CT_CheckBox | (const QCheckBox *) | Unused.
CT_RadioButton | (const QRadioButton *) | Unused.
CT_ToolButton | (const QToolButton *) | Unused.
CT_ComboBox | (const QComboBox *) | Unused.
CT_Splitter | (const QSplitter *) | Unused.
CT_DockWindow | (const QDockWindow *) | Unused.
CT_ProgressBar | (const QProgressBar *) | Unused.
CT_PopupMenuItem (const QPopupMenu *) QStyleOption ( QMenuItem *mi )
  • opt.menuItem()
mi is the menu item to use when calculating the size. QMenuItem is currently an internal class.

int QStyle::styleHint ( StyleHint stylehint, const QWidget * widget = 0, const QStyleOption & opt = QStyleOption::Default, QStyleHintReturn * returnData = 0 ) const [pure virtual]

Returns the style hint stylehint for widget. Currently, widget, opt, and returnData are unused; they're included to allow for future enhancements.

For an explanation of the return value see StyleHint.

QPixmap QStyle::stylePixmap ( StylePixmap stylepixmap, const QWidget * widget = 0, const QStyleOption & opt = QStyleOption::Default ) const [pure virtual]

Returns a pixmap for stylepixmap.

The opt argument can be used to pass extra information required when drawing the ControlElement. Note that opt may be the default value even for StylePixmaps that can make use of the extra options. Currently, the opt argument is unused.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of stylepixmap. See the table below for the appropriate widget casts:

StylePixmap | Widget Cast
SP_TitleBarMinButton | (const QWidget *)
SP_TitleBarMaxButton | (const QWidget *)
SP_TitleBarCloseButton | (const QWidget *)
SP_TitleBarNormalButton | (const QWidget *)
SP_TitleBarShadeButton | (const QWidget *)
SP_TitleBarUnshadeButton | (const QWidget *)
SP_DockWindowCloseButton | (const QDockWindow *)

See also StylePixmap.

QRect QStyle::subRect ( SubRect subrect, const QWidget * widget ) const [pure virtual]

Returns the sub-area subrect for the widget in logical coordinates.

The widget argument is a pointer to a QWidget or one of its subclasses. The widget can be cast to the appropriate type based on the value of subrect. See the table below for the appropriate widget casts:

SubRect | Widget Cast
SR_PushButtonContents | (const QPushButton *)
SR_PushButtonFocusRect | (const QPushButton *)
SR_CheckBoxIndicator | (const QCheckBox *)
SR_CheckBoxContents | (const QCheckBox *)
SR_CheckBoxFocusRect | (const QCheckBox *)
SR_RadioButtonIndicator | (const QRadioButton *)
SR_RadioButtonContents | (const QRadioButton *)
SR_RadioButtonFocusRect | (const QRadioButton *)
SR_ComboBoxFocusRect | (const QComboBox *)
SR_DockWindowHandleRect | (const QWidget *)
SR_ProgressBarGroove | (const QProgressBar *)
SR_ProgressBarContents | (const QProgressBar *)
SR_ProgressBarLabel | (const QProgressBar *)

The tear-off handle (SR_DockWindowHandleRect) for QDockWindow is a private class. Use QWidget::parentWidget() to access the QDockWindow:

        if ( !widget->parentWidget() )
            return;
        const QDockWindow *dw = (const QDockWindow *) widget->parentWidget();

See also SubRect.

void QStyle::tabbarMetrics ( const QWidget * t, int & hf, int & vf, int & ov ) const

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

void QStyle::unPolish ( QWidget * ) [virtual]

Undoes the initialization of a widget's appearance.

This function is the counterpart to polish. It is called for every polished widget when the style is dynamically changed. The former style has to unpolish its settings before the new style can polish them again.

See also polish().

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

void QStyle::unPolish ( QApplication * ) [virtual]

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

Undoes the application polish.

See also polish().

QRect QStyle::visualRect ( const QRect & logical, const QWidget * w ) [static]

Returns the rect logical in screen coordinates. The bounding rect for widget w is used to perform the translation. This function is provided to aid style implementors in supporting right-to-left mode.

See also QApplication::reverseLayout().

QRect QStyle::visualRect ( const QRect & logical, const QRect & bounding ) [static]

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

Returns the rect logical in screen coordinates. The rect bounding is used to perform the translation. This function is provided to aid style implementors in supporting right-to-left mode.

See also QApplication::reverseLayout().

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


qstyle.h Include File

qstyle.h

This is the verbatim text of the qstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qstyle.h   3.0.5   edited May 7 22:37 $
**
** Definition of QStyle class
**
** Created : 980616
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QSTYLE_H
#define QSTYLE_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_STYLE

class QPopupMenu;
class QStylePrivate;
class QMenuItem;
class QTab;
class QListViewItem;

class QStyleOption {
public:
    enum StyleOptionDefault { Default };

    QStyleOption(StyleOptionDefault=Default) : def(TRUE) {}

    // Note: we don't use default arguments since that is unnecessary
    // initialization.
    QStyleOption(int in1, int in2) :
    def(FALSE), i1(in1), i2(in2) {}
    QStyleOption(int in1, int in2, int in3, int in4) :
    def(FALSE), i1(in1), i2(in2), i3(in3), i4(in4) {}
    QStyleOption(QMenuItem* m) : def(FALSE), mi(m) {}
    QStyleOption(QMenuItem* m, int in1) : def(FALSE), mi(m), i1(in1) {}
    QStyleOption(QMenuItem* m, int in1, int in2) : def(FALSE), mi(m), i1(in1), i2(in2) {}
    QStyleOption(const QColor& c) : def(FALSE), cl(&c) {}
    QStyleOption(QTab* t) : def(FALSE), tb(t) {}
    QStyleOption(QListViewItem* i) : def(FALSE), li(i) {}
    QStyleOption(Qt::ArrowType a) : def(FALSE), i1((int)a) {}

    bool isDefault() const { return def; }

    int lineWidth() const { return i1; }
    int midLineWidth() const { return i2; }
    int frameShape() const { return i3; }
    int frameShadow() const { return i4; }

    QMenuItem* menuItem() const { return mi; }
    int maxIconWidth() const { return i1; }
    int tabWidth() const { return i2; }

    const QColor& color() const { return *cl; }

    QTab* tab() const { return tb; }

    QListViewItem* listViewItem() const { return li; }

    Qt::ArrowType arrowType() const { return (Qt::ArrowType)i1; }

private:
    // NOTE: none of these components have constructors.
    bool def;
    bool b1,b2,b3; // reserved
    QMenuItem* mi;
    QTab* tb;
    QListViewItem* li;
    const QColor* cl;
    int i1, i2, i3, i4;
    int i5, i6; // reserved
    void *p1, *p2, *p3, *p4, *p5; // reserved
    // (padded to 64 bytes on some architectures)
};

class QStyleHintReturn; // not defined yet

class Q_EXPORT QStyle: public QObject
{
    Q_OBJECT

public:
    QStyle();
    virtual ~QStyle();

    // New QStyle API - most of these should probably be pure virtual

    virtual void polish( QWidget * );
    virtual void unPolish( QWidget * );

    virtual void polish( QApplication * );
    virtual void unPolish( QApplication * );

    virtual void polish( QPalette & );

    virtual void polishPopupMenu( QPopupMenu* ) = 0;

    virtual QRect itemRect( QPainter *p, const QRect &r,
                int flags, bool enabled,
                const QPixmap *pixmap,
                const QString &text, int len = -1 ) const;

    virtual void drawItem( QPainter *p, const QRect &r,
               int flags, const QColorGroup &g, bool enabled,
               const QPixmap *pixmap, const QString &text,
               int len = -1, const QColor *penColor = 0 ) const;

    enum PrimitiveElement {
    PE_ButtonCommand,
    PE_ButtonDefault,
    PE_ButtonBevel,
    PE_ButtonTool,
    PE_ButtonDropDown,

    PE_FocusRect,

    PE_ArrowUp,
    PE_ArrowDown,
    PE_ArrowRight,
    PE_ArrowLeft,

    PE_SpinWidgetUp,
    PE_SpinWidgetDown,
    PE_SpinWidgetPlus,
    PE_SpinWidgetMinus,

    PE_Indicator,
    PE_IndicatorMask,
    PE_ExclusiveIndicator,
    PE_ExclusiveIndicatorMask,

    PE_DockWindowHandle,
    PE_DockWindowSeparator,
    PE_DockWindowResizeHandle,

    PE_Splitter,

    PE_Panel,
    PE_PanelPopup,
    PE_PanelMenuBar,
    PE_PanelDockWindow,

    PE_TabBarBase,

    PE_HeaderSection,
    PE_HeaderArrow,
    PE_StatusBarSection,

    PE_GroupBoxFrame,

    PE_Separator,

    PE_SizeGrip,

    PE_CheckMark,

    PE_ScrollBarAddLine,
    PE_ScrollBarSubLine,
    PE_ScrollBarAddPage,
    PE_ScrollBarSubPage,
    PE_ScrollBarSlider,
    PE_ScrollBarFirst,
    PE_ScrollBarLast,

    PE_ProgressBarChunk,

    PE_PanelLineEdit,
    PE_PanelTabWidget,

    PE_WindowFrame,

    // do not add any values below/greater this
    PE_CustomBase =			0xf000000
    };

    enum StyleFlags {
    Style_Default = 		0x00000000,
    Style_Enabled = 		0x00000001,
    Style_Raised =			0x00000002,
    Style_Sunken =	 		0x00000004,
    Style_Off =			0x00000008,
    Style_NoChange =		0x00000010,
    Style_On =			0x00000020,
    Style_Down =			0x00000040,
    Style_Horizontal =		0x00000080,
    Style_HasFocus =		0x00000100,
    Style_Top =			0x00000200,
    Style_Bottom =			0x00000400,
    Style_FocusAtBorder =		0x00000800,
    Style_AutoRaise =		0x00001000,
    Style_MouseOver =		0x00002000,
    Style_Up =			0x00004000,
    Style_Selected =	 	0x00008000,
    Style_Active =			0x00010000,
    Style_ButtonDefault =		0x00020000
    };
    typedef uint SFlags;

    virtual void drawPrimitive( PrimitiveElement pe,
                QPainter *p,
                const QRect &r,
                const QColorGroup &cg,
                SFlags flags = Style_Default,
                const QStyleOption& = QStyleOption::Default ) const = 0;

    enum ControlElement {
    CE_PushButton,
    CE_PushButtonLabel,

    CE_CheckBox,
    CE_CheckBoxLabel,

    CE_RadioButton,
    CE_RadioButtonLabel,

    CE_TabBarTab,
    CE_TabBarLabel,

    CE_ProgressBarGroove,
    CE_ProgressBarContents,
    CE_ProgressBarLabel,

    CE_PopupMenuItem,
    CE_MenuBarItem,

    CE_ToolButtonLabel,
    CE_PopupMenuScroller,

    // do not add any values below/greater than this
    CE_CustomBase =		0xf0000000
    };

    virtual void drawControl( ControlElement element,
                  QPainter *p,
                  const QWidget *widget,
                  const QRect &r,
                  const QColorGroup &cg,
                  SFlags how = Style_Default,
                  const QStyleOption& = QStyleOption::Default ) const = 0;
    virtual void drawControlMask( ControlElement element,
                  QPainter *p,
                  const QWidget *widget,
                  const QRect &r,
                  const QStyleOption& = QStyleOption::Default ) const = 0;

    enum SubRect {
    SR_PushButtonContents,
    SR_PushButtonFocusRect,

    SR_CheckBoxIndicator,
    SR_CheckBoxContents,
    SR_CheckBoxFocusRect,

    SR_RadioButtonIndicator,
    SR_RadioButtonContents,
    SR_RadioButtonFocusRect,

    SR_ComboBoxFocusRect,

    SR_SliderFocusRect,

    SR_DockWindowHandleRect,

    SR_ProgressBarGroove,
    SR_ProgressBarContents,
    SR_ProgressBarLabel,

    SR_ToolButtonContents,

    // do not add any values below/greater than this
    SR_CustomBase =		0xf0000000
    };

    virtual QRect subRect( SubRect r, const QWidget *widget ) const = 0;

    enum ComplexControl{
    CC_SpinWidget,
    CC_ComboBox,
    CC_ScrollBar,
    CC_Slider,
    CC_ToolButton,
    CC_TitleBar,
    CC_ListView,

    // do not add any values below/greater than this
    CC_CustomBase =		0xf0000000
    };

    enum SubControl {
    SC_None =			0x00000000,

    SC_ScrollBarAddLine =		0x00000001,
    SC_ScrollBarSubLine =		0x00000002,
    SC_ScrollBarAddPage =		0x00000004,
    SC_ScrollBarSubPage =		0x00000008,
    SC_ScrollBarFirst =		0x00000010,
    SC_ScrollBarLast =		0x00000020,
    SC_ScrollBarSlider =		0x00000040,
    SC_ScrollBarGroove =		0x00000080,

    SC_SpinWidgetUp =		0x00000001,
    SC_SpinWidgetDown =		0x00000002,
    SC_SpinWidgetFrame =		0x00000004,
    SC_SpinWidgetEditField =	0x00000008,
    SC_SpinWidgetButtonField =	0x00000010,

    SC_ComboBoxFrame =		0x00000001,
    SC_ComboBoxEditField =		0x00000002,
    SC_ComboBoxArrow =		0x00000004,

    SC_SliderGroove =		0x00000001,
    SC_SliderHandle = 		0x00000002,
    SC_SliderTickmarks = 		0x00000004,

    SC_ToolButton =			0x00000001,
    SC_ToolButtonMenu =		0x00000002,

    SC_TitleBarLabel =		0x00000001,
    SC_TitleBarSysMenu =		0x00000002,
    SC_TitleBarMinButton =		0x00000004,
    SC_TitleBarMaxButton =		0x00000008,
    SC_TitleBarCloseButton =	0x00000010,
    SC_TitleBarNormalButton =	0x00000020,
    SC_TitleBarShadeButton =	0x00000040,
    SC_TitleBarUnshadeButton =	0x00000080,

    SC_ListView =			0x00000001,
    SC_ListViewBranch =		0x00000002,
    SC_ListViewExpand =		0x00000004,

    SC_All =			0xffffffff
    };
    typedef uint SCFlags;

    virtual void drawComplexControl( ComplexControl control,
                     QPainter *p,
                     const QWidget *widget,
                     const QRect &r,
                     const QColorGroup &cg,
                     SFlags how = Style_Default,
                     SCFlags sub = SC_All,
                     SCFlags subActive = SC_None,
                     const QStyleOption& = QStyleOption::Default ) const = 0;
    virtual void drawComplexControlMask( ComplexControl control,
                     QPainter *p,
                     const QWidget *widget,
                     const QRect &r,
                     const QStyleOption& = QStyleOption::Default ) const = 0;

    virtual QRect querySubControlMetrics( ComplexControl control,
                      const QWidget *widget,
                      SubControl sc,
                      const QStyleOption& = QStyleOption::Default ) const = 0;
    virtual SubControl querySubControl( ComplexControl control,
                    const QWidget *widget,
                    const QPoint &pos,
                    const QStyleOption& = QStyleOption::Default ) const = 0;

    enum PixelMetric {
    PM_ButtonMargin,
    PM_ButtonDefaultIndicator,
    PM_MenuButtonIndicator,
    PM_ButtonShiftHorizontal,
    PM_ButtonShiftVertical,

    PM_DefaultFrameWidth,
    PM_SpinBoxFrameWidth,

    PM_MaximumDragDistance,

    PM_ScrollBarExtent,
    PM_ScrollBarSliderMin,

    PM_SliderThickness,	       	// total slider thickness
    PM_SliderControlThickness,    	// thickness of the business part
    PM_SliderLength,		// total length of slider
    PM_SliderTickmarkOffset,	//
    PM_SliderSpaceAvailable,	// available space for slider to move

    PM_DockWindowSeparatorExtent,
    PM_DockWindowHandleExtent,
    PM_DockWindowFrameWidth,

    PM_MenuBarFrameWidth,

    PM_TabBarTabOverlap,
    PM_TabBarTabHSpace,
    PM_TabBarTabVSpace,
    PM_TabBarBaseHeight,
    PM_TabBarBaseOverlap,

    PM_ProgressBarChunkWidth,

    PM_SplitterWidth,
    PM_TitleBarHeight,

    PM_IndicatorWidth,
    PM_IndicatorHeight,
    PM_ExclusiveIndicatorWidth,
    PM_ExclusiveIndicatorHeight,
    PM_PopupMenuScrollerHeight,

    // do not add any values below/greater than this
    PM_CustomBase =		0xf0000000
    };

    virtual int pixelMetric( PixelMetric metric,
                 const QWidget *widget = 0 ) const = 0;

    enum ContentsType {
    CT_PushButton,
    CT_CheckBox,
    CT_RadioButton,
    CT_ToolButton,
    CT_ComboBox,
    CT_Splitter,
    CT_DockWindow,
    CT_ProgressBar,
    CT_PopupMenuItem,

    // do not add any values below/greater than this
    CT_CustomBase =		0xf0000000
    };

    virtual QSize sizeFromContents( ContentsType contents,
                    const QWidget *widget,
                    const QSize &contentsSize,
                    const QStyleOption& = QStyleOption::Default ) const = 0;

    enum StyleHint  {
    // ...
    // the general hints
    // ...
           // disabled text should be etched, ala Windows
    SH_EtchDisabledText,

    // the GUI style enum, argh!
    SH_GUIStyle,

    // ...
    // widget specific hints
    // ...
    SH_ScrollBar_BackgroundMode,
    SH_ScrollBar_MiddleClickAbsolutePosition,
    SH_ScrollBar_ScrollWhenPointerLeavesControl,

    // QEvent::Type - which mouse event to select a tab
    SH_TabBar_SelectMouseType,

    SH_TabBar_Alignment,

    SH_Header_ArrowAlignment,

    // bool - sliders snap to values while moving, ala Windows
    SH_Slider_SnapToValue,

    // bool - key presses handled in a sloppy manner - ie. left on a vertical
    // slider subtracts a line
    SH_Slider_SloppyKeyEvents,

    // bool - center button on progress dialogs, ala Motif, else right aligned
    // perhaps this should be a Qt::Alignment value
    SH_ProgressDialog_CenterCancelButton,

    // Qt::AlignmentFlags - text label alignment in progress dialogs
    // Center on windows, Auto|VCenter otherwize
    SH_ProgressDialog_TextLabelAlignment,

    // bool - right align buttons on print dialog, ala Windows
    SH_PrintDialog_RightAlignButtons,

    // bool - 1 or 2 pixel space between the menubar and the dockarea, ala Windows
    // this *REALLY* needs a better name
    SH_MainWindow_SpaceBelowMenuBar,

    // bool - select the text in the line edit about the listbox when selecting
    // an item from the listbox, or when the line edit receives focus, ala Windows
    SH_FontDialog_SelectAssociatedText,

    // bool - allows disabled menu items to be active
    SH_PopupMenu_AllowActiveAndDisabled,

    // bool - pressing space activates item, ala Motif
    SH_PopupMenu_SpaceActivatesItem,

    // int - number of milliseconds to wait before opening a submenu
    // 256 on windows, 96 on motif
    SH_PopupMenu_SubMenuPopupDelay,

    // bool - should scrollviews draw their frame only around contents (ala Motif),
    // or around contents, scrollbars and corner widgets (ala Windows) ?
    SH_ScrollView_FrameOnlyAroundContents,

    // bool - menubars items are navigatable by pressing alt, followed by using
    // the arrow keys to select the desired item
    SH_MenuBar_AltKeyNavigation,

    // bool - mouse tracking in combobox dropdown lists
    SH_ComboBox_ListMouseTracking,

    // bool - mouse tracking in popupmenus
    SH_PopupMenu_MouseTracking,

    // bool - mouse tracking in menubars
    SH_MenuBar_MouseTracking,

    // bool - gray out selected items when loosing focus
    SH_ItemView_ChangeHighlightOnFocus,

    // bool - supports shared activation among modeless widgets
    SH_Widget_ShareActivation,

    // bool - workspace should just maximize the client area
    SH_Workspace_FillSpaceOnMaximize,

    // bool - supports popup menu comboboxes
    SH_ComboBox_Popup,

    // bool - titlebar has no border
    SH_TitleBar_NoBorder,

    // bool - stop scrollbar at mouse
    SH_ScrollBar_StopMouseOverSlider,

    //bool - blink cursort with selected text
    SH_BlinkCursorWhenTextSelected,

    //bool - richtext selections extend the full width of the docuemnt
    SH_RichText_FullWidthSelection,

    //bool - popupmenu supports scrolling instead of multicolumn mode
    SH_PopupMenu_Scrollable,

    // do not add any values below/greater than this
    SH_CustomBase =		0xf0000000
    };

    virtual int styleHint( StyleHint stylehint,
               const QWidget *widget = 0,
               const QStyleOption& = QStyleOption::Default,
               QStyleHintReturn* returnData = 0
               ) const = 0;

    enum StylePixmap {
    SP_TitleBarMinButton,
    SP_TitleBarMaxButton,
    SP_TitleBarCloseButton,
    SP_TitleBarNormalButton,
    SP_TitleBarShadeButton,
    SP_TitleBarUnshadeButton,
    SP_DockWindowCloseButton,
    SP_MessageBoxInformation,
    SP_MessageBoxWarning,
    SP_MessageBoxCritical,

    // do not add any values below/greater than this
    SP_CustomBase =		0xf0000000
    };

    virtual QPixmap stylePixmap( StylePixmap stylepixmap,
                 const QWidget *widget = 0,
                 const QStyleOption& = QStyleOption::Default ) const = 0;

    static QRect visualRect( const QRect &logical, const QWidget *w );

    static QRect visualRect( const QRect &logical, const QRect &bounding );

    // Old 2.x QStyle API

#ifndef QT_NO_COMPAT
    int defaultFrameWidth() const
    {
    return pixelMetric( PM_DefaultFrameWidth );
    }
    void tabbarMetrics( const QWidget* t,
            int& hf, int& vf, int& ov ) const
    {
    hf = pixelMetric( PM_TabBarTabHSpace, t );
    vf = pixelMetric( PM_TabBarTabVSpace, t );
    ov = pixelMetric( PM_TabBarBaseOverlap, t );
    }
    QSize scrollBarExtent() const
    {
    return QSize(pixelMetric(PM_ScrollBarExtent),
             pixelMetric(PM_ScrollBarExtent));
    }
#endif

private:
    QStylePrivate * d;

#if defined(Q_DISABLE_COPY)
    QStyle( const QStyle & );
    QStyle& operator=( const QStyle & );
#endif
};

#endif // QT_NO_STYLE
#endif // QSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStyle Member List

Complete Member List for QStyle

This is the complete list of member functions for QStyle, including inherited members.

  • QStyle()
  • ~QStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • visualRect()


QStyleFactory Class

QStyleFactory Class Reference

The QStyleFactory class creates QStyle objects. More...

#include <qstylefactory.h>

List of all member functions.

Static Public Members

  • QStringList keys ()
  • QStyle * create ( const QString & key )

Detailed Description

The QStyleFactory class creates QStyle objects.

The style factory creates a QStyle object for a given key with QStyleFactory::create(key).

The styles are either built-in or dynamically loaded from a style plugin (see QStylePlugin).

QStyleFactory::keys() returns a list of valid keys, typically including "windows", "motif", "cde", "motifplus", "platinum", "sgi" and "compact". Depending on the platform, "windowsxp", "aqua" or "macintosh" may be available.

Member Function Documentation

QStyle * QStyleFactory::create ( const QString & key ) [static]

Creates a QStyle object that matches key. This is either a built-in style, or a style from a style plugin.

See also keys().

Example: themes/wood.cpp.

QStringList QStyleFactory::keys () [static]

Returns the list of keys this factory can create styles for.

See also create().

Example: themes/themes.cpp.

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


qstylefactory.h Include File

qstylefactory.h

This is the verbatim text of the qstylefactory.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** ...
**
** Copyright (C) 2000-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTYLEFACTORY_H
#define QSTYLEFACTORY_H

#ifndef QT_H
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_STYLE

class QString;
class QStyle;

class Q_EXPORT QStyleFactory
{
public:
#ifndef QT_NO_STRINGLIST
    static QStringList keys();
#endif
    static QStyle *create( const QString& );
};

#endif //QT_NO_STYLE

#endif //QSTYLEFACTORY_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStyleFactory Member List

Complete Member List for QStyleFactory

This is the complete list of member functions for QStyleFactory, including inherited members.

  • create()
  • keys()


QStyleOption Class

QStyleOption Class Reference

The QStyleOption class specifies optional parameters for QStyle functions. More...

#include <qstyle.h>

List of all member functions.

Public Members

  • enum StyleOptionDefault { Default }
  • QStyleOption ( StyleOptionDefault = Default )
  • QStyleOption ( int in1, int in2 )
  • QStyleOption ( int in1, int in2, int in3, int in4 )
  • QStyleOption ( QMenuItem * m )
  • QStyleOption ( QMenuItem * m, int in1 )
  • QStyleOption ( QMenuItem * m, int in1, int in2 )
  • QStyleOption ( const QColor & c )
  • QStyleOption ( QTab * t )
  • QStyleOption ( QListViewItem * i )
  • QStyleOption ( Qt::ArrowType a )
  • bool isDefault () const
  • int lineWidth () const
  • int midLineWidth () const
  • int frameShape () const
  • int frameShadow () const
  • QMenuItem * menuItem () const
  • int maxIconWidth () const
  • int tabWidth () const
  • const QColor & color () const
  • QTab * tab () const
  • QListViewItem * listViewItem () const
  • Qt::ArrowType arrowType () const

Detailed Description

The QStyleOption class specifies optional parameters for QStyle functions.

Some QStyle functions take an optional argument specifying extra information that is required for a paritical primitive or control. So that the QStyle class can be extended, QStyleOption is used to provide a variable-argument for these options.

The QStyleOption class has constructors for each type of optional argument, and this set of constructors may be extended in future Qt releases. There are also corresponding access functions that return the optional arguments: these too may be extended.

For each constructor, you should refer to the documentation of the QStyle functions to see the meaning of the arguments.

When calling QStyle functions from your own widgets, you must only pass either the default QStyleOption or the argument that QStyle is documented to accept. For example, if the function expects QStyleOption(QMenuItem *, int), passing QStyleOption(QMenuItem *) leaves the optional integer argument uninitialized.

When subclassing QStyle, you must similarly only expect the default or documented arguments. The other arguments will have uninitialized values.

If you make your own QStyle subclasses and your own widgets, you can make a subclass of QStyleOption to pass additional arguments to your QStyle subclass. You will need to cast the "const QStyleOption&" argument to your subclass, so be sure your style has been called from your widget.

See also Widget Appearance and Style.

Member Type Documentation

QStyleOption::StyleOptionDefault

This enum value can be passed as the optional argument to any QStyle function.

  • QStyleOption::Default

Member Function Documentation

QStyleOption::QStyleOption ( StyleOptionDefault = Default )

The default option. This can always be passed as the optional argument to QStyle functions.

QStyleOption::QStyleOption ( int in1, int in2 )

Pass two integers, in1 and in2. For example, linewidth and midlinewidth.

QStyleOption::QStyleOption ( int in1, int in2, int in3, int in4 )

Pass four integers, in1, in2, in3 and in4.

QStyleOption::QStyleOption ( QMenuItem * m )

Pass a menu item, m.

QStyleOption::QStyleOption ( QMenuItem * m, int in1 )

Pass a menu item and an integer, m and in1.

QStyleOption::QStyleOption ( QMenuItem * m, int in1, int in2 )

Pass a menu item and two integers, m, in1 and in2.

QStyleOption::QStyleOption ( const QColor & c )

Pass a color, c.

QStyleOption::QStyleOption ( QTab * t )

Pass a QTab, t.

QStyleOption::QStyleOption ( QListViewItem * i )

Pass a QListViewItem, i.

QStyleOption::QStyleOption ( Qt::ArrowType a )

Pass an Qt::ArrowType, a.

Qt::ArrowType QStyleOption::arrowType () const

Returns an arrow type if the appropriate constructor was called; otherwise the return value is undefined.

const QColor & QStyleOption::color () const

Returns a color if the appropriate constructor was called; otherwise the return value is undefined.

int QStyleOption::frameShadow () const

Returns a QFrame::Shadow value if the appropriate constructor was called; otherwise the return value is undefined.

int QStyleOption::frameShape () const

Returns a QFrame::Shape value if the appropriate constructor was called; otherwise the return value is undefined.

bool QStyleOption::isDefault () const

Returns TRUE if the option was constructed with the default constructor; otherwise returns FALSE.

int QStyleOption::lineWidth () const

Returns the line width if the appropriate constructor was called; otherwise the return value is undefined.

QListViewItem * QStyleOption::listViewItem () const

Returns a QListView item if the appropriate constructor was called; otherwise the return value is undefined.

int QStyleOption::maxIconWidth () const

Returns the maximum width of the menu item check area if the appropriate constructor was called; otherwise the return value is undefined.

QMenuItem * QStyleOption::menuItem () const

Returns a menu item if the appropriate constructor was called; otherwise the return value is undefined.

int QStyleOption::midLineWidth () const

Returns the mid-line width if the appropriate constructor was called; otherwise the return value is undefined.

QTab * QStyleOption::tab () const

Returns a QTabBar tab if the appropriate constructor was called; otherwise the return value is undefined.

int QStyleOption::tabWidth () const

Returns the tab indent width if the appropriate constructor was called; otherwise the return value is undefined.

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


QStyleOption Member List

Complete Member List for QStyleOption

This is the complete list of member functions for QStyleOption, including inherited members.

  • QStyleOption()
  • arrowType()
  • color()
  • frameShadow()
  • frameShape()
  • isDefault()
  • lineWidth()
  • listViewItem()
  • maxIconWidth()
  • menuItem()
  • midLineWidth()
  • tab()
  • tabWidth()


QStylePlugin Class

QStylePlugin Class Reference

The QStylePlugin class provides an abstract base for custom QStyle plugins. More...

#include <qstyleplugin.h>

List of all member functions.

Public Members

  • QStylePlugin ()
  • ~QStylePlugin ()
  • virtual QStringList keys () const = 0
  • virtual QStyle * create ( const QString & key ) = 0

Detailed Description

The QStylePlugin class provides an abstract base for custom QStyle plugins.

The style plugin is a simple plugin interface that makes it easy to create custom styles that can be loaded dynamically into applications with a QStyleFactory.

Writing a style plugin is achieved by subclassing this base class, reimplementing the pure virtual functions keys() and create(), and exporting the class with the Q_EXPORT_PLUGIN macro. See the plugins documentation for an example.

See also Plugins.

Member Function Documentation

QStylePlugin::QStylePlugin ()

Constructs a style plugin. This is invoked automatically by the Q_EXPORT_PLUGIN macro.

QStylePlugin::~QStylePlugin ()

Destroys the style plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

QStyle * QStylePlugin::create ( const QString & key ) [pure virtual]

Creates and returns a QStyle object for the style key key. The style key is usually the class name of the required style.

See also keys().

QStringList QStylePlugin::keys () const [pure virtual]

Returns the list of style keys this plugin supports.

These keys are usually the class names of the custom styles that are implemented in the plugin.

See also create().

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


qstyleplugin.h Include File

qstyleplugin.h

This is the verbatim text of the qstyleplugin.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qstyleplugin.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QStylePlugin class
**
** Created : 010920
**
** Copyright (C) 2001 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTYLEPLUGIN_H
#define QSTYLEPLUGIN_H

#ifndef QT_H
#include "qgplugin.h"
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_STYLE
#ifndef QT_NO_COMPONENT

class QStyle;
class QStylePluginPrivate;

class Q_EXPORT QStylePlugin : public QGPlugin
{
    Q_OBJECT
public:
    QStylePlugin();
    ~QStylePlugin();

    virtual QStringList keys() const = 0;
    virtual QStyle *create( const QString &key ) = 0;

private:
    QStylePluginPrivate *d;
};

#endif // QT_NO_COMPONENT
#endif // QT_NO_STYLE

#endif // QSTYLEPLUGIN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStylePlugin Member List

Complete Member List for QStylePlugin

This is the complete list of member functions for QStylePlugin, including inherited members.

  • QStylePlugin()
  • ~QStylePlugin()
  • create()
  • keys()


QStyleSheet Class

QStyleSheet Class Reference

The QStyleSheet class is a collection of styles for rich text rendering and a generator of tags. More...

#include <qstylesheet.h>

Inherits QObject.

List of all member functions.

Public Members

  • QStyleSheet ( QObject * parent = 0, const char * name = 0 )
  • virtual ~QStyleSheet ()
  • QStyleSheetItem * item ( const QString & name )
  • const QStyleSheetItem * item ( const QString & name ) const
  • virtual QTextCustomItem * tag ( const QString & name, const QMap<QString, QString> & attr, const QString & context, const QMimeSourceFactory & factory, bool emptyTag, QTextDocument * doc ) const
  • virtual void scaleFont ( QFont & font, int logicalSize ) const
  • virtual void error ( const QString & msg ) const

Static Public Members

  • QStyleSheet * defaultSheet ()
  • void setDefaultSheet ( QStyleSheet * sheet )
  • QString escape ( const QString & plain )
  • QString convertFromPlainText ( const QString & plain, QStyleSheetItem::WhiteSpaceMode mode = QStyleSheetItem::WhiteSpacePre )
  • bool mightBeRichText ( const QString & text )

Detailed Description

The QStyleSheet class is a collection of styles for rich text rendering and a generator of tags.

By creating QStyleSheetItem objects for a style sheet you build a definition of a set of tags. This definition will be used by the internal rich text rendering system to parse and display text documents to which the style sheet applies. Rich text is normally visualized in a QTextView or a QTextBrowser. However, QLabel, QWhatsThis and QMessageBox also support it, and other classes are likely to follow. With QSimpleRichText it is possible to use the rich text renderer for custom widgets as well.

The default QStyleSheet object has the following style bindings, sorted by structuring bindings, anchors, character style bindings (i.e. inline styles), special elements such as horizontal lines or images, and other tags. In addition, rich text supports simple HTML tables.

The structuring tags are

Structuring tags | Notes
<qt>...</qt> A Qt rich text document. It understands the following attributes:
  • title -- The caption of the document. This attribute is easily accessible with QTextView::documentTitle().
  • type -- The type of the document. The default type is page. It indicates that the document is displayed in a page of its own. Another style is detail, which can be used to explain certain expressions in more detail in a few sentences. For detail, QTextBrowser will then keep the current page and display the new document in a small popup similar to QWhatsThis. Note that links will not work in documents with <qt type="detail">...</qt>.
  • bgcolor -- The background color, for example bgcolor="yellow" or bgcolor="#0000FF".
  • background -- The background pixmap, for example background="granite.xpm". The pixmap name will be resolved by a QMimeSourceFactory().
  • text -- The default text color, for example text="red".
  • link -- The link color, for example link="green".
<h1>...</h1> | A top-level heading.
<h2>...</h2> | A sublevel heading.
<h3>...</h3> | A sub-sublevel heading.
<p>...</p> | A left-aligned paragraph. Adjust the alignment with the align attribute. Possible values are left, right and center.
<center>...
</center> 		A centered paragraph.
<blockquote>...
</blockquote> 		An indented paragraph that is useful for quotes.
<ul>...</ul> | An unordered list. You can also pass a type argument to define the bullet style. The default is type=disc; other types are circle and square.
<ol>...</ol> | An ordered list. You can also pass a type argument to define the enumeration label style. The default is type="1"; other types are "a" and "A".
<li>...</li> | A list item. This tag can be used only within the context of <ol> or <ul>.
<pre>...</pre> | For larger chunks of code. Whitespaces in the contents are preserved. For small bits of code use the inline-style code.

Anchors and links are done with a single tag:

Anchor tags Notes
<a>...</a> An anchor or link.
  • A link is created by using an href attribute, for example
    <a href="target.qml">Link Text</a>. Links to targets within a document are achieved in the same way as for HTML, e.g.
    <a href="target.qml#subtitle">Link Text</a>.
  • A target is created by using a name attribute, for example
    <a name="subtitle"><h2>Sub Title</h2></a>.

The default character style bindings are

Style tags | Notes
<em>...</em> | Emphasized. By default this is the same as <i>...</i> (italic).
<strong>...</strong> | Strong. By default this is the same as <b>...</b> (bold).
<i>...</i> | Italic font style.
<b>...</b> | Bold font style.
<u>...</u> | Underlined font style.
<s>...</s> | Strike out font style.
<big>...</big> | A larger font size.
<small>...</small> | A smaller font size.
<code>...</code> | Indicates code. By default this is the same as <tt>...</tt> (typewriter). For larger junks of code use the block-tag <pre>.
<tt>...</tt> | Typewriter font style.
<font>...</font> Customizes the font size, family and text color. The tag understands the following attributes:
  • color -- The text color, for example color="red" or color="#FF0000".
  • size -- The logical size of the font. Logical sizes 1 to 7 are supported. The value may either be absolute (for example, size=3) or relative (size=-2). In the latter case the sizes are simply added.
  • face -- The family of the font, for example face=times.

Special elements are:

Special tags | Notes
<img> | An image. The image name for the mime source factory is given in the source attribute, for example <img src="qt.xpm"> The image tag also understands the attributes width and height that determine the size of the image. If the pixmap does not fit the specified size it will be scaled automatically (by using QImage::smoothScale()). The align attribute determines where the image is placed. By default, an image is placed inline just like a normal character. Specify left or right to place the image at the respective side.
<hr> | A horizonal line.
<br> | A line break.
<nobr>...</nobr> | No break. Prevents word wrap.

In addition, rich text supports simple HTML tables. A table consists of one or more rows each of which contains one or more cells. Cells are either data cells or header cells, depending on their content. Cells which span rows and columns are supported.

Table tags | Notes
<table>...</table> A table. Tables support the following attributes:
  • bgcolor -- The background color.
  • width -- The table width. This is either an absolute pixel width or a relative percentage of the table's width, for example width=80%.
  • border -- The width of the table border. The default is 0 (= no border).
  • cellspacing -- Additional space around the table cells. The default is 2.
  • cellpadding -- Additional space around the contents of table cells. The default is 1.
<tr>...</tr> A table row. This is only valid within a table. Rows support the following attribute:
  • bgcolor -- The background color.
<th>...</th> | A table header cell. Similar to td, but defaults to center alignment and a bold font.
<td>...</td> A table data cell. This is only valid within a tr. Cells support the following attributes:
  • bgcolor -- The background color.
  • width -- The cell width. This is either an absolute pixel width or a relative percentage of table's width, for example width=50%.
  • colspan -- Specifies how many columns this cell spans. The default is 1.
  • rowspan -- Specifies how many rows this cell spans. The default is 1.
  • align -- Alignment; possible values are left, right, and center. The default is left.

See also Graphics Classes, Help System and Text Related Classes.

Member Function Documentation

QStyleSheet::QStyleSheet ( QObject * parent = 0, const char * name = 0 )

Creates a style sheet called name, with parent parent. Like any QObject it will be deleted when its parent is destroyed (if the child still exists).

By default the style sheet has the tag definitions defined above.

QStyleSheet::~QStyleSheet () [virtual]

Destroys the style sheet. All styles inserted into the style sheet will be deleted.

QString QStyleSheet::convertFromPlainText ( const QString & plain, QStyleSheetItem::WhiteSpaceMode mode = QStyleSheetItem::WhiteSpacePre ) [static]

Auxiliary function. Converts the plain text string plain to a rich text formatted paragraph while preserving most of its look.

mode defines the whitespace mode. Possible values are QStyleSheetItem::WhiteSpacePre (no wrapping, all whitespaces preserved) and QStyleSheetItem::WhiteSpaceNormal (wrapping, simplified whitespaces).

See also escape().

QStyleSheet * QStyleSheet::defaultSheet () [static]

Returns the application-wide default style sheet. This style sheet is used by rich text rendering classes such as QSimpleRichText, QWhatsThis and QMessageBox to define the rendering style and available tags within rich text documents. It also serves as the initial style sheet for the more complex render widgets, QTextEdit and QTextBrowser.

See also setDefaultSheet().

void QStyleSheet::error ( const QString & msg ) const [virtual]

This virtual function is called when an error occurs when processing rich text. Reimplement it if you need to catch error messages.

Errors might occur if some rich text strings contain tags that are not understood by the stylesheet, if some tags are nested incorrectly, or if tags are not closed properly.

msg is the error message.

QString QStyleSheet::escape ( const QString & plain ) [static]

Auxiliary function. Converts the plain text string plain to a rich text formatted string with any HTML meta-characters escaped.

See also convertFromPlainText().

QStyleSheetItem * QStyleSheet::item ( const QString & name )

Returns the style called name or 0 if there is no such style.

const QStyleSheetItem * QStyleSheet::item ( const QString & name ) const

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

Returns the style called name or 0 if there is no such style (const version)

bool QStyleSheet::mightBeRichText ( const QString & text ) [static]

Returns TRUE if the string text is likely to be rich text; otherwise returns FALSE.

This function uses a fast and therefore simple heuristic. It mainly checks whether there is something that looks like a tag before the first line break. Although the result may be correct for common cases, there is no guarantee.

void QStyleSheet::scaleFont ( QFont & font, int logicalSize ) const [virtual]

Scales the font font to the appropriate physical point size corresponding to the logical font size logicalSize.

When calling this function, font has a point size corresponding to the logical font size 3.

Logical font sizes range from 1 to 7, with 1 being the smallest.

See also QStyleSheetItem::logicalFontSize(), QStyleSheetItem::logicalFontSizeStep() and QFont::setPointSize().

void QStyleSheet::setDefaultSheet ( QStyleSheet * sheet ) [static]

Sets the application-wide default style sheet to sheet, deleting any style sheet previously set. The ownership is transferred to QStyleSheet.

See also defaultSheet().

QTextCustomItem * QStyleSheet::tag ( const QString & name, const QMap<QString, QString> & attr, const QString & context, const QMimeSourceFactory & factory, bool emptyTag, QTextDocument * doc ) const [virtual]

This function is under development and is subject to change.

Generates an internal object for the tag called name, given the attributes attr, and using additional information provided by the mime source factory factory.

context is the optional context of the document, i.e. the path to look for relative links. This becomes important if the text contains relative references, for example within image tags. QSimpleRichText always uses the default mime source factory (see QMimeSourceFactory::defaultFactory()) to resolve these references. The context will then be used to calculate the absolute path. See QMimeSourceFactory::makeAbsolute() for details.

emptyTag and doc are for internal use only.

This function should not be used in application code.

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


qstylesheet.h Include File

qstylesheet.h

This is the verbatim text of the qstylesheet.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qstylesheet.h   3.0.5   edited Jun 13 10:38 $
**
** Definition of the QStyleSheet class
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QSTYLESHEET_H
#define QSTYLESHEET_H

#ifndef QT_H
#include "qstring.h"
#include "qvaluelist.h"
#include "qptrvector.h"
#include "qdict.h"
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_RICHTEXT

class QStyleSheet;
class QTextDocument;
template<class Key, class T> class QMap;
class QStyleSheetItemData;

class Q_EXPORT QStyleSheetItem : public Qt
{
public:
    QStyleSheetItem( QStyleSheet* parent, const QString& name );
    QStyleSheetItem( const QStyleSheetItem & );
    ~QStyleSheetItem();

    QString name() const;

    QStyleSheet* styleSheet();
    const QStyleSheet* styleSheet() const;

    enum AdditionalStyleValues { Undefined  = - 1};

    enum DisplayMode {
    DisplayBlock,
    DisplayInline,
    DisplayListItem,
    DisplayNone
    };

    DisplayMode displayMode() const;
    void setDisplayMode(DisplayMode m);

    int alignment() const;
    void setAlignment( int f);

    enum VerticalAlignment {
    VAlignBaseline,
    VAlignSub,
    VAlignSuper
    };

    VerticalAlignment verticalAlignment() const;
    void setVerticalAlignment( VerticalAlignment valign );

    int fontWeight() const;
    void setFontWeight(int w);

    int logicalFontSize() const;
    void setLogicalFontSize(int s);

    int logicalFontSizeStep() const;
    void setLogicalFontSizeStep( int s );

    int fontSize() const;
    void setFontSize(int s);

    QString fontFamily() const;
    void setFontFamily( const QString& );

    int numberOfColumns() const;
    void setNumberOfColumns(int ncols);

    QColor color() const;
    void setColor( const QColor &);

    bool fontItalic() const;
    void setFontItalic( bool );
    bool definesFontItalic() const;

    bool fontUnderline() const;
    void setFontUnderline( bool );
    bool definesFontUnderline() const;

    bool fontStrikeOut() const;
    void setFontStrikeOut( bool );
    bool definesFontStrikeOut() const;

    bool isAnchor() const;
    void setAnchor(bool anc);

    enum WhiteSpaceMode { WhiteSpaceNormal, WhiteSpacePre, WhiteSpaceNoWrap };
    WhiteSpaceMode whiteSpaceMode() const;
    void setWhiteSpaceMode(WhiteSpaceMode m);

    enum Margin {
    MarginLeft,
    MarginRight,
    MarginTop,
    MarginBottom,
    MarginFirstLine,
    MarginAll,
    MarginVertical,
    MarginHorizontal
    };

    int margin( Margin m) const;
    void setMargin( Margin, int);

    enum ListStyle {
    ListDisc,
    ListCircle,
    ListSquare,
    ListDecimal,
    ListLowerAlpha,
    ListUpperAlpha
    };

    ListStyle listStyle() const;
    void setListStyle( ListStyle );

    QString contexts() const;
    void setContexts( const QString& );
    bool allowedInContext( const QStyleSheetItem* ) const;

    bool selfNesting() const;
    void setSelfNesting( bool );

    void setLineSpacing( int ls );
    int lineSpacing() const;

private:
    void init();
    QStyleSheetItemData* d;
};

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QDict<QStyleSheetItem>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QValueList< QPtrVector<QStyleSheetItem> >;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrVector<QStyleSheetItem>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QValueList<QStyleSheetItem::ListStyle>;
// MOC_SKIP_END
#endif

class QTextCustomItem;

class Q_EXPORT QStyleSheet : public QObject
{
    Q_OBJECT
public:
    QStyleSheet( QObject *parent=0, const char *name=0 );
    virtual ~QStyleSheet();

    static QStyleSheet* defaultSheet();
    static void setDefaultSheet( QStyleSheet* );

    QStyleSheetItem* item( const QString& name);
    const QStyleSheetItem* item( const QString& name) const;

    void insert( QStyleSheetItem* item);

    virtual QTextCustomItem* tag( const QString& name,
                const QMap<QString, QString> &attr,
                const QString& context,
                const QMimeSourceFactory& factory,
                bool emptyTag, QTextDocument *doc ) const;

    static QString escape( const QString& );
    static QString convertFromPlainText( const QString&, QStyleSheetItem::WhiteSpaceMode mode = QStyleSheetItem::WhiteSpacePre );
    static bool mightBeRichText( const QString& );

    virtual void scaleFont( QFont& font, int logicalSize ) const;

    virtual void error( const QString& ) const;

private:
    void init();
    QDict<QStyleSheetItem> styles;
    QStyleSheetItem* nullstyle;
};

#endif // QT_NO_RICHTEXT

#endif // QSTYLESHEET_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QStyleSheet Member List

Complete Member List for QStyleSheet

This is the complete list of member functions for QStyleSheet, including inherited members.

  • QStyleSheet()
  • ~QStyleSheet()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • convertFromPlainText()
  • customEvent()
  • defaultSheet()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • error()
  • escape()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • item()
  • killTimer()
  • killTimers()
  • metaObject()
  • mightBeRichText()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • scaleFont()
  • sender()
  • setDefaultSheet()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • tag()
  • timerEvent()
  • tr()
  • trUtf8()


QStyleSheetItem Class

QStyleSheetItem Class Reference

The QStyleSheetItem class provides an encapsulation of a set of text styles. More...

#include <qstylesheet.h>

Inherits Qt.

List of all member functions.

Public Members

  • QStyleSheetItem ( QStyleSheet * parent, const QString & name )
  • QStyleSheetItem ( const QStyleSheetItem & other )
  • ~QStyleSheetItem ()
  • QString name () const
  • QStyleSheet * styleSheet ()
  • const QStyleSheet * styleSheet () const
  • enum DisplayMode { DisplayBlock, DisplayInline, DisplayListItem, DisplayNone }
  • DisplayMode displayMode () const
  • void setDisplayMode ( DisplayMode m )
  • int alignment () const
  • void setAlignment ( int f )
  • enum VerticalAlignment { VAlignBaseline, VAlignSub, VAlignSuper }
  • VerticalAlignment verticalAlignment () const
  • void setVerticalAlignment ( VerticalAlignment valign )
  • int fontWeight () const
  • void setFontWeight ( int w )
  • int logicalFontSize () const
  • void setLogicalFontSize ( int s )
  • int logicalFontSizeStep () const
  • void setLogicalFontSizeStep ( int s )
  • int fontSize () const
  • void setFontSize ( int s )
  • QString fontFamily () const
  • void setFontFamily ( const QString & fam )
  • int numberOfColumns () const (obsolete)
  • void setNumberOfColumns ( int ncols ) (obsolete)
  • QColor color () const
  • void setColor ( const QColor & c )
  • bool fontItalic () const
  • void setFontItalic ( bool italic )
  • bool definesFontItalic () const
  • bool fontUnderline () const
  • void setFontUnderline ( bool underline )
  • bool definesFontUnderline () const
  • bool fontStrikeOut () const
  • void setFontStrikeOut ( bool strikeOut )
  • bool definesFontStrikeOut () const
  • bool isAnchor () const
  • void setAnchor ( bool anc )
  • enum WhiteSpaceMode { WhiteSpaceNormal, WhiteSpacePre, WhiteSpaceNoWrap }
  • WhiteSpaceMode whiteSpaceMode () const
  • void setWhiteSpaceMode ( WhiteSpaceMode m )
  • enum Margin { MarginLeft, MarginRight, MarginTop, MarginBottom, MarginFirstLine, MarginAll, MarginVertical, MarginHorizontal }
  • int margin ( Margin m ) const
  • void setMargin ( Margin m, int v )
  • enum ListStyle { ListDisc, ListCircle, ListSquare, ListDecimal, ListLowerAlpha, ListUpperAlpha }
  • ListStyle listStyle () const
  • void setListStyle ( ListStyle s )
  • QString contexts () const
  • void setContexts ( const QString & c )
  • bool allowedInContext ( const QStyleSheetItem * s ) const
  • bool selfNesting () const
  • void setSelfNesting ( bool nesting )
  • void setLineSpacing ( int ls )
  • int lineSpacing () const (obsolete)

Detailed Description

The QStyleSheetItem class provides an encapsulation of a set of text styles.

A style sheet item consists of a name and a set of attributes that specifiy its font, color, etc. When used in a style sheet (see styleSheet()), items define the name() of a rich text tag and the display property changes associated with it.

The display mode attribute indicates whether the item is a block, an inline element or a list element; see setDisplayMode(). The treatment of whitespace is controlled by the white space mode; see setWhiteSpaceMode(). An item's margins are set with setMargin(), In the case of list items, the list style is set with setListStyle(). An item may be a hypertext link anchor; see setAnchor(). Other attributes are set with setAlignment(), setVerticalAlignment(), setFontFamily(), setFontSize(), setFontWeight(), setFontItalic(), setFontUnderline(), setFontStrikeOut and setColor().

See also Text Related Classes.

Member Type Documentation

QStyleSheetItem::DisplayMode

This enum type defines the way adjacent elements are displayed.

  • QStyleSheetItem::DisplayBlock - elements are displayed as a rectangular block (e.g. <p>...</p>).
  • QStyleSheetItem::DisplayInline - elements are displayed in a horizontally flowing sequence (e.g. <em>...</em>).
  • QStyleSheetItem::DisplayListItem - elements are displayed in a vertical sequence (e.g. <li>...</li>).
  • QStyleSheetItem::DisplayNone - elements are not displayed at all.

QStyleSheetItem::ListStyle

This enum type defines how the items in a list are prefixed when displayed.

  • QStyleSheetItem::ListDisc - a filled circle (i.e. a bullet)
  • QStyleSheetItem::ListCircle - an unfilled circle
  • QStyleSheetItem::ListSquare - a filled square
  • QStyleSheetItem::ListDecimal - an integer in base 10: 1, 2, 3, ...
  • QStyleSheetItem::ListLowerAlpha - a lowercase letter: a, b, c, ...
  • QStyleSheetItem::ListUpperAlpha - an uppercase letter: A, B, C, ...

QStyleSheetItem::Margin

  • QStyleSheetItem::MarginLeft - left margin
  • QStyleSheetItem::MarginRight - right margin
  • QStyleSheetItem::MarginTop - top margin
  • QStyleSheetItem::MarginBottom - bottom margin
  • QStyleSheetItem::MarginAll - all margins (left, right, top and bottom)
  • QStyleSheetItem::MarginVertical - top and bottom margins
  • QStyleSheetItem::MarginHorizontal - left and right margins
  • QStyleSheetItem::MarginFirstLine - margin (indentation) of the first line of a paragarph (in addition to the MarginLeft of the paragraph)

QStyleSheetItem::VerticalAlignment

This enum type defines the way elements are aligned vertically. This is only supported for text elements.

  • QStyleSheetItem::VAlignBaseline - align the baseline of the element (or the bottom, if the element doesn't have a baseline) with the baseline of the parent
  • QStyleSheetItem::VAlignSub - subscript the element
  • QStyleSheetItem::VAlignSuper - superscript the element

QStyleSheetItem::WhiteSpaceMode

This enum defines the ways in which QStyleSheet can treat whitespace.

  • QStyleSheetItem::WhiteSpaceNormal - any sequence of whitespace (including line-breaks) is equivalent to a single space.
  • QStyleSheetItem::WhiteSpacePre - whitespace must be output exactly as given in the input.
  • QStyleSheetItem::WhiteSpaceNoWrap - multiple spaces are collapsed as with WhiteSpaceNormal, but no automatic line-breaks occur. To break lines manually, use the <br> tag.

Member Function Documentation

QStyleSheetItem::QStyleSheetItem ( QStyleSheet * parent, const QString & name )

Constructs a new style called name for the stylesheet parent.

All properties in QStyleSheetItem are initially in the "do not change" state, except display mode, which defaults to DisplayInline.

QStyleSheetItem::QStyleSheetItem ( const QStyleSheetItem & other )

Copy constructor. Constructs a copy of other that is not bound to any style sheet.

QStyleSheetItem::~QStyleSheetItem ()

Destroys the style. Note that QStyleSheetItem objects become owned by QStyleSheet when they are created.

int QStyleSheetItem::alignment () const

Returns the alignment of this style. Possible values are AlignAuto, AlignLeft, AlignRight, AlignCenter or AlignJustify.

See also setAlignment() and Qt::AlignmentFlags.

bool QStyleSheetItem::allowedInContext ( const QStyleSheetItem * s ) const

Returns TRUE if this style can be nested into an element of style s; otherwise returns FALSE.

See also contexts() and setContexts().

QColor QStyleSheetItem::color () const

Returns the text color of this style or an invalid color if no color has been set.

See also setColor() and QColor::isValid().

QString QStyleSheetItem::contexts () const

Returns a space-separated list of names of styles that may contain elements of this style. If nothing has been set, contexts() returns an empty string, which indicates that this style can be nested everywhere.

See also setContexts().

bool QStyleSheetItem::definesFontItalic () const

Returns TRUE if the style defines a font shape; otherwise returns FALSE. A style does not define any shape until setFontItalic() is called.

See also setFontItalic() and fontItalic().

bool QStyleSheetItem::definesFontStrikeOut () const

Returns TRUE if the style defines a setting for the strikeOut property of the font; otherwise returns FALSE. A style does not define this until setFontStrikeOut() is called.

See also setFontStrikeOut() and fontStrikeOut().

bool QStyleSheetItem::definesFontUnderline () const

Returns TRUE if the style defines a setting for the underline property of the font; otherwise returns FALSE. A style does not define this until setFontUnderline() is called.

See also setFontUnderline() and fontUnderline().

DisplayMode QStyleSheetItem::displayMode () const

Returns the display mode of the style.

See also setDisplayMode().

QString QStyleSheetItem::fontFamily () const

Returns the font family setting of the style. This is either a valid font family or QString::null if no family has been set.

See also setFontFamily(), QFont::family() and QFont::setFamily().

bool QStyleSheetItem::fontItalic () const

Returns TRUE if the style sets an italic font; otherwise returns FALSE.

See also setFontItalic() and definesFontItalic().

int QStyleSheetItem::fontSize () const

Returns the font size setting of the style. This is either a valid point size or QStyleSheetItem::Undefined.

See also setFontSize(), QFont::pointSize() and QFont::setPointSize().

bool QStyleSheetItem::fontStrikeOut () const

Returns TRUE if the style sets a strike out font; otherwise returns FALSE.

See also setFontStrikeOut() and definesFontStrikeOut().

bool QStyleSheetItem::fontUnderline () const

Returns TRUE if the style sets an underlined font; otherwise returns FALSE.

See also setFontUnderline() and definesFontUnderline().

int QStyleSheetItem::fontWeight () const

Returns the font weight setting of the style. This is either a valid QFont::Weight or the value QStyleSheetItem::Undefined.

See also setFontWeight() and QFont.

bool QStyleSheetItem::isAnchor () const

Returns whether this style is an anchor.

See also setAnchor().

int QStyleSheetItem::lineSpacing () const

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

Returns the linespacing

ListStyle QStyleSheetItem::listStyle () const

Returns the list style of the style.

See also setListStyle() and ListStyle.

int QStyleSheetItem::logicalFontSize () const

Returns the logical font size setting of the style. This is either a valid size between 1 and 7 or QStyleSheetItem::Undefined.

See also setLogicalFontSize(), setLogicalFontSizeStep(), QFont::pointSize() and QFont::setPointSize().

int QStyleSheetItem::logicalFontSizeStep () const

Returns the logical font size step of this style.

The default is 0. Tags such as big define +1; small defines -1.

See also setLogicalFontSizeStep().

int QStyleSheetItem::margin ( Margin m ) const

Returns the width of margin m in pixels.

The margin, m, can be MarginLeft, MarginRight, MarginTop, MarginBottom, MarginAll, MarginVertical or MarginHorizontal.

See also setMargin() and Margin.

QString QStyleSheetItem::name () const

Returns the name of the style item.

int QStyleSheetItem::numberOfColumns () const

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

Returns the number of columns for this style.

See also setNumberOfColumns(), displayMode() and setDisplayMode().

bool QStyleSheetItem::selfNesting () const

Returns TRUE if this style has self-nesting enabled; otherwise returns FALSE.

See also setSelfNesting().

void QStyleSheetItem::setAlignment ( int f )

Sets the alignment to f. This only makes sense for styles with a display mode of DisplayBlock. Possible values are AlignAuto, AlignLeft, AlignRight, AlignCenter or AlignJustify.

See also alignment(), displayMode() and Qt::AlignmentFlags.

void QStyleSheetItem::setAnchor ( bool anc )

If anc is TRUE, sets this style to be an anchor (hypertext link); otherwise sets it to not be an anchor. Elements in this style link to other documents or anchors.

See also isAnchor().

void QStyleSheetItem::setColor ( const QColor & c )

Sets the text color of this style to c.

See also color().

void QStyleSheetItem::setContexts ( const QString & c )

Sets a space-separated list of names of styles that may contain elements of this style. If c is empty, the style can be nested everywhere.

See also contexts().

void QStyleSheetItem::setDisplayMode ( DisplayMode m )

Sets the display mode of the style to m.

See also displayMode().

void QStyleSheetItem::setFontFamily ( const QString & fam )

Sets the font family setting of the style to fam.

See also fontFamily(), QFont::family() and QFont::setFamily().

void QStyleSheetItem::setFontItalic ( bool italic )

If italic is TRUE sets italic for the style; otherwise sets upright.

See also fontItalic() and definesFontItalic().

void QStyleSheetItem::setFontSize ( int s )

Sets the font size setting of the style to s points.

See also fontSize(), QFont::pointSize() and QFont::setPointSize().

void QStyleSheetItem::setFontStrikeOut ( bool strikeOut )

If strikeOut is TRUE, sets strike out for the style; otherwise sets no strike out.

See also fontStrikeOut() and definesFontStrikeOut().

void QStyleSheetItem::setFontUnderline ( bool underline )

If underline is TRUE, sets underline for the style; otherwise sets no underline.

See also fontUnderline() and definesFontUnderline().

void QStyleSheetItem::setFontWeight ( int w )

Sets the font weight setting of the style to w. Valid values are those defined by QFont::Weight.

See also QFont and fontWeight().

void QStyleSheetItem::setListStyle ( ListStyle s )

Sets the list style of the style to s.

This is used by nested elements that have a display mode of DisplayListItem.

See also listStyle(), DisplayMode and ListStyle.

void QStyleSheetItem::setLogicalFontSize ( int s )

Sets the logical font size setting of the style to s. Valid logical sizes are 1 to 7.

See also logicalFontSize(), QFont::pointSize() and QFont::setPointSize().

void QStyleSheetItem::setLogicalFontSizeStep ( int s )

Sets the logical font size step of this style to s.

See also logicalFontSizeStep().

void QStyleSheetItem::setMargin ( Margin m, int v )

Sets the width of margin m to v pixels.

The margin, m, can be MarginLeft, MarginRight, MarginTop, MarginBottom, MarginAll, MarginVertical or MarginHorizontal. The value v must be >= 0.

See also margin().

void QStyleSheetItem::setNumberOfColumns ( int ncols )

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

Sets the number of columns for this style. Elements in the style are divided into columns.

This makes sense only if the style uses a block display mode (see QStyleSheetItem::DisplayMode).

See also numberOfColumns().

void QStyleSheetItem::setSelfNesting ( bool nesting )

Sets the self-nesting property for this style to nesting.

In order to support "dirty" HTML, paragraphs <p> and list items <li> are not self-nesting. This means that starting a new paragraph or list item automatically closes the previous one.

See also selfNesting().

void QStyleSheetItem::setVerticalAlignment ( VerticalAlignment valign )

Sets the vertical alignment to valign. Possible values are VAlignBaseline, VAlignSub or VAlignSuper.

The vertical alignment property is not inherited.

See also verticalAlignment().

void QStyleSheetItem::setWhiteSpaceMode ( WhiteSpaceMode m )

Sets the whitespace mode to m.

See also WhiteSpaceMode.

QStyleSheet * QStyleSheetItem::styleSheet ()

Returns the style sheet this item is in.

const QStyleSheet * QStyleSheetItem::styleSheet () const

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

Returns the style sheet this item is in.

VerticalAlignment QStyleSheetItem::verticalAlignment () const

Returns the vertical alignment of the style. Possible values are VAlignBaseline, VAlignSub or VAlignSuper.

See also setVerticalAlignment().

WhiteSpaceMode QStyleSheetItem::whiteSpaceMode () const

Returns the whitespace mode.

See also setWhiteSpaceMode() and WhiteSpaceMode.

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


QStyleSheetItem Member List

Complete Member List for QStyleSheetItem

This is the complete list of member functions for QStyleSheetItem, including inherited members.

  • QStyleSheetItem()
  • ~QStyleSheetItem()
  • alignment()
  • allowedInContext()
  • color()
  • contexts()
  • definesFontItalic()
  • definesFontStrikeOut()
  • definesFontUnderline()
  • displayMode()
  • fontFamily()
  • fontItalic()
  • fontSize()
  • fontStrikeOut()
  • fontUnderline()
  • fontWeight()
  • isAnchor()
  • lineSpacing()
  • listStyle()
  • logicalFontSize()
  • logicalFontSizeStep()
  • margin()
  • name()
  • numberOfColumns()
  • selfNesting()
  • setAlignment()
  • setAnchor()
  • setColor()
  • setContexts()
  • setDisplayMode()
  • setFontFamily()
  • setFontItalic()
  • setFontSize()
  • setFontStrikeOut()
  • setFontUnderline()
  • setFontWeight()
  • setListStyle()
  • setLogicalFontSize()
  • setLogicalFontSizeStep()
  • setMargin()
  • setNumberOfColumns()
  • setSelfNesting()
  • setVerticalAlignment()
  • setWhiteSpaceMode()
  • styleSheet()
  • verticalAlignment()
  • whiteSpaceMode()


Qt类

Qt类参考

Qt类是一个提供所需的像全局变量一样的大量不同的标识符的命名空间。 详情请见……

#include <qnamespace.h>

被QObject、QPixmap、QBrush、QCanvasItem、QCursor、QPainter、QEvent、QIconViewItem、QKeySequence、QListViewItem、QCustomMenuItem、QPen、QStyleSheetItem、QTab、QTableItem、QThread、QToolTip和QWhatsThis继承。

所有成员函数列表。

公有成员

  • enum ButtonState { NoButton = 0x0000, LeftButton = 0x0001, RightButton = 0x0002, MidButton = 0x0004, MouseButtonMask = 0x00ff, ShiftButton = 0x0100, ControlButton = 0x0200, AltButton = 0x0400, MetaButton = 0x0800, KeyButtonMask = 0x0fff, Keypad = 0x4000 }
  • enum Orientation { Horizontal = 0, Vertical }
  • enum AlignmentFlags { AlignAuto = 0x0000, AlignLeft = 0x0001, AlignRight = 0x0002, AlignHCenter = 0x0004, AlignJustify = 0x0008, AlignHorizontal_Mask = AlignLeft | AlignRight | AlignHCenter | AlignJustify, AlignTop = 0x0010, AlignBottom = 0x0020, AlignVCenter = 0x0040, AlignVertical_Mask = AlignTop | AlignBottom | AlignVCenter, AlignCenter = AlignVCenter | AlignHCenter }
  • enum TextFlags { SingleLine = 0x0080, DontClip = 0x0100, ExpandTabs = 0x0200, ShowPrefix = 0x0400, WordBreak = 0x0800, BreakAnywhere = 0x1000, DontPrint = 0x2000, NoAccel = 0x4000 }
  • enum WidgetState { WState_Created = 0x00000001, WState_Disabled = 0x00000002, WState_Visible = 0x00000004, WState_ForceHide = 0x00000008, WState_OwnCursor = 0x00000010, WState_MouseTracking = 0x00000020, WState_CompressKeys = 0x00000040, WState_BlockUpdates = 0x00000080, WState_InPaintEvent = 0x00000100, WState_Reparented = 0x00000200, WState_ConfigPending = 0x00000400, WState_Resized = 0x00000800, WState_AutoMask = 0x00001000, WState_Polished = 0x00002000, WState_DND = 0x00004000, WState_Reserved0 = 0x00008000, WState_Reserved1 = 0x00010000, WState_Reserved2 = 0x00020000, WState_Reserved3 = 0x00040000, WState_Maximized = 0x00080000, WState_Minimized = 0x00100000, WState_ForceDisabled = 0x00200000, WState_Exposed = 0x00400000, WState_HasMouse = 0x00800000 }
  • enum WidgetFlags { WType_TopLevel = 0x00000001, WType_Dialog = 0x00000002, WType_Popup = 0x00000004, WType_Desktop = 0x00000008, WType_Mask = 0x0000000f, WStyle_Customize = 0x00000010, WStyle_NormalBorder = 0x00000020, WStyle_DialogBorder = 0x00000040, WStyle_NoBorder = 0x00002000, WStyle_Title = 0x00000080, WStyle_SysMenu = 0x00000100, WStyle_Minimize = 0x00000200, WStyle_Maximize = 0x00000400, WStyle_MinMax = WStyle_Minimize | WStyle_Maximize, WStyle_Tool = 0x00000800, WStyle_StaysOnTop = 0x00001000, WStyle_ContextHelp = 0x00004000, WStyle_Reserved = 0x00008000, WStyle_Mask = 0x0000fff0, WDestructiveClose = 0x00010000, WPaintDesktop = 0x00020000, WPaintUnclipped = 0x00040000, WPaintClever = 0x00080000, WResizeNoErase = 0x00100000, WMouseNoMask = 0x00200000, WStaticContents = 0x00400000, WRepaintNoErase = 0x00800000, WX11BypassWM = 0x01000000, WWinOwnDC = 0x00000000, WGroupLeader = 0x02000000, WShowModal = 0x04000000, WNoMousePropagation = 0x08000000, WSubWindow = 0x10000000, WNorthWestGravity = WStaticContents, WType_Modal = WType_Dialog | WShowModal, WStyle_Dialog = WType_Dialog, WStyle_NoBorderEx = WStyle_NoBorder }
  • enum ImageConversionFlags { ColorMode_Mask = 0x00000003, AutoColor = 0x00000000, ColorOnly = 0x00000003, MonoOnly = 0x00000002, AlphaDither_Mask = 0x0000000c, ThresholdAlphaDither = 0x00000000, OrderedAlphaDither = 0x00000004, DiffuseAlphaDither = 0x00000008, NoAlpha = 0x0000000c, Dither_Mask = 0x00000030, DiffuseDither = 0x00000000, OrderedDither = 0x00000010, ThresholdDither = 0x00000020, DitherMode_Mask = 0x000000c0, AutoDither = 0x00000000, PreferDither = 0x00000040, AvoidDither = 0x00000080 }
  • enum BGMode { TransparentMode, OpaqueMode }
  • enum PaintUnit { PixelUnit, LoMetricUnit, HiMetricUnit, LoEnglishUnit, HiEnglishUnit, TwipsUnit }
  • enum GUIStyle { MacStyle, WindowsStyle, Win3Style, PMStyle, MotifStyle } (obsolete)
  • enum Modifier { SHIFT = 0x00200000, CTRL = 0x00400000, ALT = 0x00800000, MODIFIER_MASK = 0x00e00000, UNICODE_ACCEL = 0x10000000, ASCII_ACCEL = UNICODE_ACCEL }
  • enum Key { Key_Escape = 0x1000, Key_Tab = 0x1001, Key_Backtab = 0x1002, Key_BackTab = Key_Backtab, Key_Backspace = 0x1003, Key_BackSpace = Key_Backspace, Key_Return = 0x1004, Key_Enter = 0x1005, Key_Insert = 0x1006, Key_Delete = 0x1007, Key_Pause = 0x1008, Key_Print = 0x1009, Key_SysReq = 0x100a, Key_Home = 0x1010, Key_End = 0x1011, Key_Left = 0x1012, Key_Up = 0x1013, Key_Right = 0x1014, Key_Down = 0x1015, Key_Prior = 0x1016, Key_PageUp = Key_Prior, Key_Next = 0x1017, Key_PageDown = Key_Next, Key_Shift = 0x1020, Key_Control = 0x1021, Key_Meta = 0x1022, Key_Alt = 0x1023, Key_CapsLock = 0x1024, Key_NumLock = 0x1025, Key_ScrollLock = 0x1026, Key_F1 = 0x1030, Key_F2 = 0x1031, Key_F3 = 0x1032, Key_F4 = 0x1033, Key_F5 = 0x1034, Key_F6 = 0x1035, Key_F7 = 0x1036, Key_F8 = 0x1037, Key_F9 = 0x1038, Key_F10 = 0x1039, Key_F11 = 0x103a, Key_F12 = 0x103b, Key_F13 = 0x103c, Key_F14 = 0x103d, Key_F15 = 0x103e, Key_F16 = 0x103f, Key_F17 = 0x1040, Key_F18 = 0x1041, Key_F19 = 0x1042, Key_F20 = 0x1043, Key_F21 = 0x1044, Key_F22 = 0x1045, Key_F23 = 0x1046, Key_F24 = 0x1047, Key_F25 = 0x1048, Key_F26 = 0x1049, Key_F27 = 0x104a, Key_F28 = 0x104b, Key_F29 = 0x104c, Key_F30 = 0x104d, Key_F31 = 0x104e, Key_F32 = 0x104f, Key_F33 = 0x1050, Key_F34 = 0x1051, Key_F35 = 0x1052, Key_Super_L = 0x1053, Key_Super_R = 0x1054, Key_Menu = 0x1055, Key_Hyper_L = 0x1056, Key_Hyper_R = 0x1057, Key_Help = 0x1058, Key_Direction_L = 0x1059, Key_Direction_R = 0x1060, Key_Space = 0x20, Key_Any = Key_Space, Key_Exclam = 0x21, Key_QuoteDbl = 0x22, Key_NumberSign = 0x23, Key_Dollar = 0x24, Key_Percent = 0x25, Key_Ampersand = 0x26, Key_Apostrophe = 0x27, Key_ParenLeft = 0x28, Key_ParenRight = 0x29, Key_Asterisk = 0x2a, Key_Plus = 0x2b, Key_Comma = 0x2c, Key_Minus = 0x2d, Key_Period = 0x2e, Key_Slash = 0x2f, Key_0 = 0x30, Key_1 = 0x31, Key_2 = 0x32, Key_3 = 0x33, Key_4 = 0x34, Key_5 = 0x35, Key_6 = 0x36, Key_7 = 0x37, Key_8 = 0x38, Key_9 = 0x39, Key_Colon = 0x3a, Key_Semicolon = 0x3b, Key_Less = 0x3c, Key_Equal = 0x3d, Key_Greater = 0x3e, Key_Question = 0x3f, Key_At = 0x40, Key_A = 0x41, Key_B = 0x42, Key_C = 0x43, Key_D = 0x44, Key_E = 0x45, Key_F = 0x46, Key_G = 0x47, Key_H = 0x48, Key_I = 0x49, Key_J = 0x4a, Key_K = 0x4b, Key_L = 0x4c, Key_M = 0x4d, Key_N = 0x4e, Key_O = 0x4f, Key_P = 0x50, Key_Q = 0x51, Key_R = 0x52, Key_S = 0x53, Key_T = 0x54, Key_U = 0x55, Key_V = 0x56, Key_W = 0x57, Key_X = 0x58, Key_Y = 0x59, Key_Z = 0x5a, Key_BracketLeft = 0x5b, Key_Backslash = 0x5c, Key_BracketRight = 0x5d, Key_AsciiCircum = 0x5e, Key_Underscore = 0x5f, Key_QuoteLeft = 0x60, Key_BraceLeft = 0x7b, Key_Bar = 0x7c, Key_BraceRight = 0x7d, Key_AsciiTilde = 0x7e, Key_nobreakspace = 0x0a0, Key_exclamdown = 0x0a1, Key_cent = 0x0a2, Key_sterling = 0x0a3, Key_currency = 0x0a4, Key_yen = 0x0a5, Key_brokenbar = 0x0a6, Key_section = 0x0a7, Key_diaeresis = 0x0a8, Key_copyright = 0x0a9, Key_ordfeminine = 0x0aa, Key_guillemotleft = 0x0ab, Key_notsign = 0x0ac, Key_hyphen = 0x0ad, Key_registered = 0x0ae, Key_macron = 0x0af, Key_degree = 0x0b0, Key_plusminus = 0x0b1, Key_twosuperior = 0x0b2, Key_threesuperior = 0x0b3, Key_acute = 0x0b4, Key_mu = 0x0b5, Key_paragraph = 0x0b6, Key_periodcentered = 0x0b7, Key_cedilla = 0x0b8, Key_onesuperior = 0x0b9, Key_masculine = 0x0ba, Key_guillemotright = 0x0bb, Key_onequarter = 0x0bc, Key_onehalf = 0x0bd, Key_threequarters = 0x0be, Key_questiondown = 0x0bf, Key_Agrave = 0x0c0, Key_Aacute = 0x0c1, Key_Acircumflex = 0x0c2, Key_Atilde = 0x0c3, Key_Adiaeresis = 0x0c4, Key_Aring = 0x0c5, Key_AE = 0x0c6, Key_Ccedilla = 0x0c7, Key_Egrave = 0x0c8, Key_Eacute = 0x0c9, Key_Ecircumflex = 0x0ca, Key_Ediaeresis = 0x0cb, Key_Igrave = 0x0cc, Key_Iacute = 0x0cd, Key_Icircumflex = 0x0ce, Key_Idiaeresis = 0x0cf, Key_ETH = 0x0d0, Key_Ntilde = 0x0d1, Key_Ograve = 0x0d2, Key_Oacute = 0x0d3, Key_Ocircumflex = 0x0d4, Key_Otilde = 0x0d5, Key_Odiaeresis = 0x0d6, Key_multiply = 0x0d7, Key_Ooblique = 0x0d8, Key_Ugrave = 0x0d9, Key_Uacute = 0x0da, Key_Ucircumflex = 0x0db, Key_Udiaeresis = 0x0dc, Key_Yacute = 0x0dd, Key_THORN = 0x0de, Key_ssharp = 0x0df, Key_agrave = 0x0e0, Key_aacute = 0x0e1, Key_acircumflex = 0x0e2, Key_atilde = 0x0e3, Key_adiaeresis = 0x0e4, Key_aring = 0x0e5, Key_ae = 0x0e6, Key_ccedilla = 0x0e7, Key_egrave = 0x0e8, Key_eacute = 0x0e9, Key_ecircumflex = 0x0ea, Key_ediaeresis = 0x0eb, Key_igrave = 0x0ec, Key_iacute = 0x0ed, Key_icircumflex = 0x0ee, Key_idiaeresis = 0x0ef, Key_eth = 0x0f0, Key_ntilde = 0x0f1, Key_ograve = 0x0f2, Key_oacute = 0x0f3, Key_ocircumflex = 0x0f4, Key_otilde = 0x0f5, Key_odiaeresis = 0x0f6, Key_division = 0x0f7, Key_oslash = 0x0f8, Key_ugrave = 0x0f9, Key_uacute = 0x0fa, Key_ucircumflex = 0x0fb, Key_udiaeresis = 0x0fc, Key_yacute = 0x0fd, Key_thorn = 0x0fe, Key_ydiaeresis = 0x0ff, Key_unknown = 0xffff }
  • enum ArrowType { UpArrow, DownArrow, LeftArrow, RightArrow }
  • enum RasterOp { CopyROP, OrROP, XorROP, NotAndROP, EraseROP = NotAndROP, NotCopyROP, NotOrROP, NotXorROP, AndROP, NotEraseROP = AndROP, NotROP, ClearROP, SetROP, NopROP, AndNotROP, OrNotROP, NandROP, NorROP, LastROP = NorROP }
  • enum PenStyle { NoPen, SolidLine, DashLine, DotLine, DashDotLine, DashDotDotLine, MPenStyle = 0x0f }
  • enum PenCapStyle { FlatCap = 0x00, SquareCap = 0x10, RoundCap = 0x20, MPenCapStyle = 0x30 }
  • enum PenJoinStyle { MiterJoin = 0x00, BevelJoin = 0x40, RoundJoin = 0x80, MPenJoinStyle = 0xc0 }
  • enum BrushStyle { NoBrush, SolidPattern, Dense1Pattern, Dense2Pattern, Dense3Pattern, Dense4Pattern, Dense5Pattern, Dense6Pattern, Dense7Pattern, HorPattern, VerPattern, CrossPattern, BDiagPattern, FDiagPattern, DiagCrossPattern, CustomPattern = 24 }
  • enum WindowsVersion { WV_32s = 0x0001, WV_95 = 0x0002, WV_98 = 0x0003, WV_Me = 0x0004, WV_DOS_based = 0x000f, WV_NT = 0x0010, WV_2000 = 0x0020, WV_XP = 0x0030, WV_NT_based = 0x00f0 }
  • enum UIEffect { UI_General, UI_AnimateMenu, UI_FadeMenu, UI_AnimateCombo, UI_AnimateTooltip, UI_FadeTooltip }
  • enum CursorShape { ArrowCursor, UpArrowCursor, CrossCursor, WaitCursor, IbeamCursor, SizeVerCursor, SizeHorCursor, SizeBDiagCursor, SizeFDiagCursor, SizeAllCursor, BlankCursor, SplitVCursor, SplitHCursor, PointingHandCursor, ForbiddenCursor, WhatsThisCursor, LastCursor = WhatsThisCursor, BitmapCursor = 24 }
  • enum TextFormat { PlainText, RichText, AutoText }
  • enum Dock { DockUnmanaged, DockTornOff, DockTop, DockBottom, DockRight, DockLeft, DockMinimized, Unmanaged = DockUnmanaged, TornOff = DockTornOff, Top = DockTop, Bottom = DockBottom, Right = DockRight, Left = DockLeft, Minimized = DockMinimized }
  • enum DateFormat { TextDate, ISODate, LocalDate }
  • enum BackgroundMode { FixedColor, FixedPixmap, NoBackground, PaletteForeground, PaletteButton, PaletteLight, PaletteMidlight, PaletteDark, PaletteMid, PaletteText, PaletteBrightText, PaletteBase, PaletteBackground, PaletteShadow, PaletteHighlight, PaletteHighlightedText, PaletteButtonText, PaletteLink, PaletteLinkVisited, X11ParentRelative }
  • enum StringComparisonMode { CaseSensitive = 0x00001, BeginsWith = 0x00002, EndsWith = 0x00004, Contains = 0x00008, ExactMatch = 0x00010 }
  • typedef void * HANDLE

详细描述

Qt类是一个提供所需的像全局变量一样的大量不同的标识符的命名空间。

通常情况下，你可以忽略这个类。QObject和一些其它类继承了它，所以在这个Qt命名空间中定义的所有标识符通常情况下都可以无限制的使用。

然而，有时你也许需要说Qt::black，而不仅仅是black，特别是在静态功能函数中（比如一些类工厂）。

参见杂项类。

成员类型文档

Qt::AlignmentFlags

这个枚举类型是用来描述对齐方式的。它包含水平和垂直标记。

水平标记有：

  • Qt::AlignAuto - 根据语言对齐。对于绝大多数是左对齐，对于阿拉伯语和希伯莱语是右对齐。
  • Qt::AlignLeft - 左对齐。
  • Qt::AlignRight - 右对齐。
  • Qt::AlignHCenter - 在可用空间中水平方向中间对齐。
  • Qt::AlignJustify - 在可用空间中调整文本。 并不是在所有情况下都可以工作，并且在一些情况下会被解释成AlignAuto。

垂直标记有：

  • Qt::AlignTop - 上对齐。
  • Qt::AlignBottom - 下对齐。
  • Qt::AlignVCenter - 在可用空间中垂直方向中间对齐。

你一次只能使用一次水平标记。这里有一个二维的标记：

  • Qt::AlignCenter - 水平和垂直都中间对齐。

你每次最多使用一个水平标记和一个垂直标记。AlignCenter既是水平也是垂直。

掩码:

  • Qt::AlignHorizontal_Mask
  • Qt::AlignVertical_Mask

冲突的标记组合有未定义的意义。

Qt::ArrowType

  • Qt::UpArrow
  • Qt::DownArrow
  • Qt::LeftArrow
  • Qt::RightArrow

Qt::BGMode

背景模式

  • Qt::TransparentMode
  • Qt::OpaqueMode

Qt::BackgroundMode

这个枚举类型描述了窗口部件的背景是如何变化的，就像窗口部件的调色板变化一样。

这里的背景就是当paintEvent()被调用的时候窗口部件所包含的东西。为了使闪烁最小化，在窗口部件它应是最普通的颜色或者像素映射。对于PaletteBackground，使用colorGroup().brush（QColorGroup::Background）等等。这里也有三个特殊的值，列在了最后：

  • Qt::PaletteForeground
  • Qt::PaletteBackground
  • Qt::PaletteButton
  • Qt::PaletteLight
  • Qt::PaletteMidlight
  • Qt::PaletteDark
  • Qt::PaletteMid
  • Qt::PaletteText
  • Qt::PaletteBrightText
  • Qt::PaletteButtonText
  • Qt::PaletteBase
  • Qt::PaletteShadow
  • Qt::PaletteHighlight
  • Qt::PaletteHighlightedText
  • Qt::NoBackground - 窗口部件在paintEvent()之前不被清空。如果窗口部件的绘画事件一直在所有的像素上绘画，使用这个模式既会很快也会没有闪烁。
  • Qt::FixedColor - 窗口部件被一个固定的颜色清空，通常情况下不同于paletter()中的那些。使用setPaletteBackgroundColor()来设置。
  • Qt::FixedPixmap - 窗口部件被一个固定的像素映射清空，通常情况下不同于paletter()中的那些。使用setPaletteBackgroundPixmap()来设置。
  • Qt::PaletteLink
  • Qt::PaletteLinkVisited
  • Qt::X11ParentRelative - （仅供内部使用）

尽管FixedColor和FixedPixmap有时是正确的，如果你使用它们，当桌面颜色方案发生变化时，请测试一下你的应用程序。（在X11上，一个快速的测试方法是“./myapp -bg paleblue”。在Windows上，你必须使用控制面板。）

See also QWidget::backgroundMode, QWidget::backgroundMode, QWidget::setBackgroundPixmap() and QWidget::paletteBackgroundColor.

Qt::BrushStyle

  • Qt::NoBrush
  • Qt::SolidPattern
  • Qt::Dense1Pattern
  • Qt::Dense2Pattern
  • Qt::Dense3Pattern
  • Qt::Dense4Pattern
  • Qt::Dense5Pattern
  • Qt::Dense6Pattern
  • Qt::Dense7Pattern
  • Qt::HorPattern
  • Qt::VerPattern
  • Qt::CrossPattern
  • Qt::BDiagPattern
  • Qt::FDiagPattern
  • Qt::DiagCrossPattern
  • Qt::CustomPattern

Qt::ButtonState

这个枚举类型描述了鼠标和组合键的状态。

  • Qt::NoButton - 当按键状态不指向任何按键时使用（参加QMouseEvent::button()）。
  • Qt::LeftButton - 如果左键被按，或者事件指向左键时被设置。（左键也许是左手用鼠标的右键。）
  • Qt::RightButton - 右键。
  • Qt::MidButton - 中键。
  • Qt::ShiftButton - 键盘上的Shift键也被按下了。
  • Qt::ControlButton - 键盘上的Ctrl键也被按下了。
  • Qt::AltButton - 键盘上的Alt（或者Meta）键也被按下了。
  • Qt::MetaButton - 键盘上的Meta键也被按下了。
  • Qt::Keypad - 小键盘区的按键被按下了。
  • Qt::KeyButtonMask - Shift键、Control键和Alt键的一个掩码。
  • Qt::MouseButtonMask - 左键、右键和中键的一个掩码。

Qt::CursorShape

这个枚举类型定义了可以使用的大量光标。

  • Qt::ArrowCursor - 标准箭头光标
  • Qt::UpArrowCursor - 向上的箭头
  • Qt::CrossCursor - 十字
  • Qt::WaitCursor - 沙漏/观察
  • Qt::IbeamCursor - 文本条目
  • Qt::SizeVerCursor - 垂直重定义大小
  • Qt::SizeHorCursor - 水平重定义大小
  • Qt::SizeBDiagCursor - 斜线重定义大小 (/)
  • Qt::SizeFDiagCursor - 斜线重定义大小 (\)
  • Qt::SizeAllCursor - 所有方向重定义大小
  • Qt::BlankCursor - 空白/不可见光标
  • Qt::SplitVCursor - 垂直分隔
  • Qt::SplitHCursor - 水平分隔
  • Qt::PointingHandCursor - 一个指示手
  • Qt::ForbiddenCursor - 一个带有斜线的圆圈
  • Qt::WhatsThisCursor - 一个带有问好的箭头
  • Qt::BitmapCursor

ArrowCursor是普通状态下窗口部件的默认值。

Qt::DateFormat

  • Qt::TextDate - （默认的）Qt格式
  • Qt::ISODate - ISO 8601扩展格式（YYYY-MM-DD，或者带有时间，YYYY-MM-DDTHH:MM:SS）
  • Qt::LocalDate - 由本地决定的格式

Qt::Dock

每一个锚接窗口的位置可能是如下之一：

  • Qt::DockTop - 在中心窗口部件之上，在菜单条之下。
  • Qt::DockBottom - 在中心窗口部件之下，在状态条之上。
  • Qt::DockLeft - 在中心窗口部件的左面。
  • Qt::DockRight - 在中心窗口部件的右面。
  • Qt::DockMinimized - 锚接窗口没有被显示（这是一个有效的“隐藏”锚接区域）；所有被最小化的锚接窗口的处理被画在菜单条下面的一行里面。
  • Qt::DockTornOff - 锚接窗口作为它自己的顶层窗口浮动着，通常在主窗口之上。
  • Qt::DockUnmanaged - 不被QMainWindow管理。

Qt::GUIStyle

这个类型是废弃的。它被提供是为了让旧的代码能继续工作。我们强烈建议在新的代码中不要使用它了。

  • Qt::WindowsStyle
  • Qt::MotifStyle
  • Qt::MacStyle
  • Qt::Win3Style
  • Qt::PMStyle

Qt::ImageConversionFlags

变换标记是下列这些值的位的或运算。被标记为“（默认）”的选项将在没有其它值被设置的时候使用（因为默认值是零）：

Color/Mono preference (ignored for QBitmap)

  • Qt::AutoColor - （默认）- 如果图片的深度为1并且仅包含黑色和白色像素，那么像素映射就是黑白的。
  • Qt::ColorOnly - 像素映射被抖动/转换为本地显示深度。
  • Qt::MonoOnly - 像素映射变为黑白的。如果需要，会使用所选择的抖动算法抖动它。

RGB通道的抖动模式选择

  • Qt::DiffuseDither - （默认）- 一个高质量的抖动。
  • Qt::OrderedDither - 一个更快的，更加规则的抖动。
  • Qt::ThresholdDither - 没有抖动；最靠近的颜色将被使用。

Alpha通道的抖动模式选择

  • Qt::ThresholdAlphaDither - （默认）- 没有抖动。
  • Qt::OrderedAlphaDither - 一个更快的，更加规则的抖动。
  • Qt::DiffuseAlphaDither - 一个高质量的抖动。
  • Qt::NoAlpha - 不支持的。

颜色匹配与抖动选择

  • Qt::PreferDither - （当转化为像素映射时的默认项）- 当图像被转化为8位时，总是抖动为32为图像。
  • Qt::AvoidDither - （当打算保存为文件而转化时的默认项） - 只有在图像超过256色并且它将被转化为8位时，抖动32位图像。
  • Qt::AutoDither - 不支持的。

下面这些不是可以直接使用的值，只是为上述类提供的掩码：

  • Qt::ColorMode_Mask - 颜色模式的掩码。
  • Qt::Dither_Mask - RGB通道的抖动模式的掩码。
  • Qt::AlphaDither_Mask - Alpha通道的抖动模式的掩码。
  • Qt::DitherMode_Mask - 在抖动中决定颜色匹配的选择的模式的掩码。

使用0就会把变化标记全部设置为默认选项。

Qt::Key

Qt中使用的键的名称。

  • Qt::Key_Escape
  • Qt::Key_Tab
  • Qt::Key_Backtab
  • Qt::Key_Backspace
  • Qt::Key_Return
  • Qt::Key_Enter
  • Qt::Key_Insert
  • Qt::Key_Delete
  • Qt::Key_Pause
  • Qt::Key_Print
  • Qt::Key_SysReq
  • Qt::Key_Home
  • Qt::Key_End
  • Qt::Key_Left
  • Qt::Key_Up
  • Qt::Key_Right
  • Qt::Key_Down
  • Qt::Key_Prior
  • Qt::Key_Next
  • Qt::Key_Shift
  • Qt::Key_Control
  • Qt::Key_Meta
  • Qt::Key_Alt
  • Qt::Key_CapsLock
  • Qt::Key_NumLock
  • Qt::Key_ScrollLock
  • Qt::Key_F1
  • Qt::Key_F2
  • Qt::Key_F3
  • Qt::Key_F4
  • Qt::Key_F5
  • Qt::Key_F6
  • Qt::Key_F7
  • Qt::Key_F8
  • Qt::Key_F9
  • Qt::Key_F10
  • Qt::Key_F11
  • Qt::Key_F12
  • Qt::Key_F13
  • Qt::Key_F14
  • Qt::Key_F15
  • Qt::Key_F16
  • Qt::Key_F17
  • Qt::Key_F18
  • Qt::Key_F19
  • Qt::Key_F20
  • Qt::Key_F21
  • Qt::Key_F22
  • Qt::Key_F23
  • Qt::Key_F24
  • Qt::Key_F25
  • Qt::Key_F26
  • Qt::Key_F27
  • Qt::Key_F28
  • Qt::Key_F29
  • Qt::Key_F30
  • Qt::Key_F31
  • Qt::Key_F32
  • Qt::Key_F33
  • Qt::Key_F34
  • Qt::Key_F35
  • Qt::Key_Super_L
  • Qt::Key_Super_R
  • Qt::Key_Menu
  • Qt::Key_Hyper_L
  • Qt::Key_Hyper_R
  • Qt::Key_Help
  • Qt::Key_Space
  • Qt::Key_Any
  • Qt::Key_Exclam
  • Qt::Key_QuoteDbl
  • Qt::Key_NumberSign
  • Qt::Key_Dollar
  • Qt::Key_Percent
  • Qt::Key_Ampersand
  • Qt::Key_Apostrophe
  • Qt::Key_ParenLeft
  • Qt::Key_ParenRight
  • Qt::Key_Asterisk
  • Qt::Key_Plus
  • Qt::Key_Comma
  • Qt::Key_Minus
  • Qt::Key_Period
  • Qt::Key_Slash
  • Qt::Key_0
  • Qt::Key_1
  • Qt::Key_2
  • Qt::Key_3
  • Qt::Key_4
  • Qt::Key_5
  • Qt::Key_6
  • Qt::Key_7
  • Qt::Key_8
  • Qt::Key_9
  • Qt::Key_Colon
  • Qt::Key_Semicolon
  • Qt::Key_Less
  • Qt::Key_Equal
  • Qt::Key_Greater
  • Qt::Key_Question
  • Qt::Key_At
  • Qt::Key_A
  • Qt::Key_B
  • Qt::Key_C
  • Qt::Key_D
  • Qt::Key_E
  • Qt::Key_F
  • Qt::Key_G
  • Qt::Key_H
  • Qt::Key_I
  • Qt::Key_J
  • Qt::Key_K
  • Qt::Key_L
  • Qt::Key_M
  • Qt::Key_N
  • Qt::Key_O
  • Qt::Key_P
  • Qt::Key_Q
  • Qt::Key_R
  • Qt::Key_S
  • Qt::Key_T
  • Qt::Key_U
  • Qt::Key_V
  • Qt::Key_W
  • Qt::Key_X
  • Qt::Key_Y
  • Qt::Key_Z
  • Qt::Key_BracketLeft
  • Qt::Key_Backslash
  • Qt::Key_BracketRight
  • Qt::Key_AsciiCircum
  • Qt::Key_Underscore
  • Qt::Key_QuoteLeft
  • Qt::Key_BraceLeft
  • Qt::Key_Bar
  • Qt::Key_BraceRight
  • Qt::Key_AsciiTilde
  • Qt::Key_nobreakspace
  • Qt::Key_exclamdown
  • Qt::Key_cent
  • Qt::Key_sterling
  • Qt::Key_currency
  • Qt::Key_yen
  • Qt::Key_brokenbar
  • Qt::Key_section
  • Qt::Key_diaeresis
  • Qt::Key_copyright
  • Qt::Key_ordfeminine
  • Qt::Key_guillemotleft
  • Qt::Key_notsign
  • Qt::Key_hyphen
  • Qt::Key_registered
  • Qt::Key_macron
  • Qt::Key_degree
  • Qt::Key_plusminus
  • Qt::Key_twosuperior
  • Qt::Key_threesuperior
  • Qt::Key_acute
  • Qt::Key_mu
  • Qt::Key_paragraph
  • Qt::Key_periodcentered
  • Qt::Key_cedilla
  • Qt::Key_onesuperior
  • Qt::Key_masculine
  • Qt::Key_guillemotright
  • Qt::Key_onequarter
  • Qt::Key_onehalf
  • Qt::Key_threequarters
  • Qt::Key_questiondown
  • Qt::Key_Agrave
  • Qt::Key_Aacute
  • Qt::Key_Acircumflex
  • Qt::Key_Atilde
  • Qt::Key_Adiaeresis
  • Qt::Key_Aring
  • Qt::Key_AE
  • Qt::Key_Ccedilla
  • Qt::Key_Egrave
  • Qt::Key_Eacute
  • Qt::Key_Ecircumflex
  • Qt::Key_Ediaeresis
  • Qt::Key_Igrave
  • Qt::Key_Iacute
  • Qt::Key_Icircumflex
  • Qt::Key_Idiaeresis
  • Qt::Key_ETH
  • Qt::Key_Ntilde
  • Qt::Key_Ograve
  • Qt::Key_Oacute
  • Qt::Key_Ocircumflex
  • Qt::Key_Otilde
  • Qt::Key_Odiaeresis
  • Qt::Key_multiply
  • Qt::Key_Ooblique
  • Qt::Key_Ugrave
  • Qt::Key_Uacute
  • Qt::Key_Ucircumflex
  • Qt::Key_Udiaeresis
  • Qt::Key_Yacute
  • Qt::Key_THORN
  • Qt::Key_ssharp
  • Qt::Key_agrave
  • Qt::Key_aacute
  • Qt::Key_acircumflex
  • Qt::Key_atilde
  • Qt::Key_adiaeresis
  • Qt::Key_aring
  • Qt::Key_ae
  • Qt::Key_ccedilla
  • Qt::Key_egrave
  • Qt::Key_eacute
  • Qt::Key_ecircumflex
  • Qt::Key_ediaeresis
  • Qt::Key_igrave
  • Qt::Key_iacute
  • Qt::Key_icircumflex
  • Qt::Key_idiaeresis
  • Qt::Key_eth
  • Qt::Key_ntilde
  • Qt::Key_ograve
  • Qt::Key_oacute
  • Qt::Key_ocircumflex
  • Qt::Key_otilde
  • Qt::Key_odiaeresis
  • Qt::Key_division
  • Qt::Key_oslash
  • Qt::Key_ugrave
  • Qt::Key_uacute
  • Qt::Key_ucircumflex
  • Qt::Key_udiaeresis
  • Qt::Key_yacute
  • Qt::Key_thorn
  • Qt::Key_ydiaeresis
  • Qt::Key_unknown
  • Qt::Key_Direction_L - 仅供内部使用
  • Qt::Key_Direction_R - 仅供内部使用

Qt::Modifier

这个枚举类型描述了Qt支持的键盘组合键。

  • Qt::SHIFT - 所有标准键盘都提供了Shift键。
  • Qt::CTRL - Ctrl键。
  • Qt::ALT - 通常情况下是Alt键，但不是AltGr。
  • Qt::MODIFIER_MASK - 是Shift、Ctrl和Alt的一个掩码。
  • Qt::UNICODE_ACCEL - 加速键被指定作为一个Unicode代码值，不是作为一个Qt键。

Qt::Orientation

这个类型被用来使用表示一个对象的方位。

  • Qt::Horizontal
  • Qt::Vertical

举例来说，方位在QScrollBar中被使用。

Qt::PaintUnit

  • Qt::PixelUnit
  • Qt::LoMetricUnit - obsolete
  • Qt::HiMetricUnit - obsolete
  • Qt::LoEnglishUnit - obsolete
  • Qt::HiEnglishUnit - obsolete
  • Qt::TwipsUnit - obsolete

Qt::PenCapStyle

这个枚举类型定义了被Qt支持的画笔顶端风格，比如，线段顶端可以使用QPainter画出来。

  • Qt::FlatCap - 一个方形的线段顶端，但不覆盖线段的终点。
  • Qt::SquareCap - 一个方形的线段顶端，覆盖线段的终点并且超过它线段宽度的一半。
  • Qt::RoundCap - 一个圆形的线段顶端。
  • Qt::MPenCapStyle - 画笔顶端风格掩码。

Pen Cap Styles

Qt::PenJoinStyle

这个枚举类型定义了Qt支持的画笔连接风格，比如，两个相连的线段可以使用QPainter画出来。

  • Qt::MiterJoin - 线的外边界线被延伸并形成一个角度，并且这个区域将被填充。
  • Qt::BevelJoin - 在两个线之间的三角形缺口被填充。
  • Qt::RoundJoin - 在两个线间的圆弧被填充。
  • Qt::MPenJoinStyle - 画笔连接风格掩码。

Pen Join Styles

Qt::PenStyle

这个枚举类型定义了画笔风格，可以由QPainter画出。这些风格有

  • Qt::NoPen - 根本就没有线。比如，QPainter::drawRect()填充但没有绘制任何边界线。
  • Qt::SolidLine - 一个简单的线。
  • Qt::DashLine - 由一些像素分隔的短线。
  • Qt::DotLine - 由一些像素分隔的点。
  • Qt::DashDotLine - 轮流交替的点和短线。
  • Qt::DashDotDotLine - 一个短线，两个点，一个短线，两个点。
  • Qt::MPenStyle - 画笔风格的掩码。

Qt::RasterOp

这个枚举类型被用来描述把东西写到绘画设备上的方式。源（src）（你要写的）的每一个位和对应位的目标（dst）像素的相互作用。

  • Qt::CopyROP - dst = src
  • Qt::OrROP - dst = src OR dst
  • Qt::XorROP - dst = src XOR dst
  • Qt::NotAndROP - dst = (NOT src) AND dst
  • Qt::EraseROP - NotAndROP的一个别名
  • Qt::NotCopyROP - dst = NOT src
  • Qt::NotOrROP - dst = (NOT src) OR dst
  • Qt::NotXorROP - dst = (NOT src) XOR dst
  • Qt::AndROP - dst = src AND dst
  • Qt::NotEraseROP - AndROP的一个别名
  • Qt::NotROP - dst = NOT dst
  • Qt::ClearROP - dst = 0
  • Qt::SetROP - dst = 1
  • Qt::NopROP - dst = dst
  • Qt::AndNotROP - dst = src AND (NOT dst)
  • Qt::OrNotROP - dst = src OR (NOT dst)
  • Qt::NandROP - dst = NOT (src AND dst)
  • Qt::NorROP - dst = NOT (src OR dst)

到目前为止，最有用的是CopyROP和XorROP。

在Qt/Mac上，只有CopyROP、OrROP、XorROP、NotAndROP、NotCopyROP、NotOrROP、NotXorROP和AndROP被支持。

Qt::StringComparisonMode

这个枚举类型是当搜索一个条目时被用来设置字符串比较模式的。例如，这是在QListBox、QListView和QIconView中实现的。我们将用“目标”字符串来指代正在被搜索的字符串。

  • Qt::CaseSensitive - 字符串必须区分大小写。
  • Qt::ExactMatch - 目标字符串和搜索字符串必须正确地匹配。
  • Qt::BeginsWith - 目标字符串必须是由搜索字符串开始的。
  • Qt::EndsWith - 目标字符串必须是由搜索字符串结束的。
  • Qt::Contains - 目标字符串包含搜索字符串。

如果你用这些标记的或来搜索（不包括CaseSensitive），搜索标准必须按下列顺序：ExactMatch、BeginsWith、EndsWith、Contains。

除非CaseSensitive被设置，匹配将是大小写不敏感的。CaseSensitive可以和其它任何标记使用或来组合。

Qt::TextFlags

这个枚举类型是用来定义一些修饰标记。这些标记中的一些只能在文章打印时有意义。

  • Qt::SingleLine - 把所有的控制字符作为空格处理并且都打印在一行之内。
  • Qt::DontClip - 如果不能在给定边界内存在,就打印到外面。
  • Qt::ExpandTabs - 把U+0009字符（ASCII的制表符）字符移动到下一个制表符处。
  • Qt::ShowPrefix - 显示字符“&P”作为P（作为实例，请看QButton）。如果要用“与”符号（“&”），请使用“&&”。
  • Qt::WordBreak - 在适当的点换行，比如在字的分界处。
  • Qt::BreakAnywhere - 在任何地方换行，甚至是字的当中。
  • Qt::NoAccel - ShowPrefix的同义词。
  • Qt::DontPrint - （内部的）

你可以按你所想用的数量来使用修饰标记，除了SingleLine和WordBreak不能在一起使用。

一个不适当的给定使用的标记（比如，在QGridLayout::addWidget()中使用ShowPrefix）一般被忽略。

Qt::TextFormat

这个枚举类型用在可以显示纯文本和多信息文本的窗口部件中，比如QLabel。它用于决定一个文本字符串是否应该解释为它自己或者其它。通过向setTextFormat()函数传递一个这样的枚举值就可以很简单的做到这一点。

  • Qt::PlainText - 文本字符串被解释为纯文本字符串。
  • Qt::RichText - 文本字符串通过使用当前的QStyleSheet::defaultSheet()被解释为多信息文本字符串。
  • Qt::AutoText - 如果QStyleSheet::mightBeRichText()返回真，文本字符串被解释为RichText，否则为PlainText。

Qt::UIEffect

  • Qt::UI_General
  • Qt::UI_AnimateMenu
  • Qt::UI_FadeMenu
  • Qt::UI_AnimateCombo
  • Qt::UI_AnimateTooltip
  • Qt::UI_FadeTooltip

Qt::WidgetFlags

这个枚举类型是用来指定窗口部件的窗口系统属性的。它们通常情况下没用，但是在一些场合是必需的。这些标记中的一些依赖于窗口管理器是否支持它们。

主要类型有

  • Qt::WType_TopLevel - 表明这个窗口部件是顶级的，通常有一个窗口系统框架和其它的。
  • Qt::WType_Dialog - 表明这个窗口部件是顶级的，并且应该被修饰为一个对话框（比如，作为特色，在标题栏中没有最大化和最小化按钮）。如果你想使用它作为一个模式对话框，它应该从另一个窗口中被运行，或者有一个父窗口并且这个标记必须和WShowModal一起使用。如果你使用了模式对话框，这个对话框将会防止应用程序的其它顶级窗口获得任何输入。WType_Dialog隐含了WType_TopLevel。我们指的是作为一个二级窗口作为顶级窗口需要有父窗口。（请参考WGroupLeader。）
  • Qt::WType_Popup - 表明这个窗口部件是一个弹出式的顶级窗口部件，比如它是模式的，但是供弹出菜单使用的窗口系统框架。WType_Popup隐含了WType_TopLevel。
  • Qt::WType_Desktop - 表明这个窗口部件是着明。请参考下面的WPaintDesktop。WType_Desktop隐含了WType_TopLevel。

这里还有大量的标记可以用来自定义顶级窗口的外观。这些对于其它窗口没有任何效果的：

  • Qt::WStyle_Customize - 表明WStyle_*标记应该被用来替换默认标记来构建窗口。
  • Qt::WStyle_NormalBorder - 给窗口一个普通边界。这个不能和WStyle_DialogBorder或WStyle_NoBorder一起使用。
  • Qt::WStyle_DialogBorder - 给窗口一个窄的对话框边界。这个不能和WStyle_NormalBorder或WStyle_NoBorder。
  • Qt::WStyle_NoBorder - 产生一个没有边界的窗口。注意：用户不可以通过窗口系统来移动或者重新定义无边界窗口的大小。这个标记不可以和WStyle_NormalBorder或WStyle_DialogBorder一起使用。在Windows中，这个标记正常工作。在X11中，这个标记的结果取决于窗口管理器和它们对于MOTIF和/或NETWM提示的理解的能力：现在存在的现代窗口管理器中的绝大部分都可以处理这些。通过WX11BypassWM，你可以完全地绕过窗口管理器。这样的结果就是无边界窗口根本无法被管理了（比如，除非你手工地调用setActiveWindow()就无法获得键盘输入）。
  • Qt::WStyle_NoBorderEx - 这个值是废弃的。它的效果和使用WStyle_NoBorder是一样的。
  • Qt::WStyle_Title - 给窗口一个标题栏。
  • Qt::WStyle_SysMenu - 添加一个窗口系统菜单。
  • Qt::WStyle_Minimize - 添加一个最小化按钮。注意：在Windows下，为了使它能够正常工作，它必须和WStyle_SysMenu一起组合使用。
  • Qt::WStyle_Maximize - 添加一个最大化按钮。注意：在Windows下，为了使它能够正常工作，它必须和WStyle_SysMenu一起组合使用。
  • Qt::WStyle_MinMax - 和WStyle_Minimize|WStyle_Maximize是一样的。注意：在Windows下，为了使它能够正常工作，它必须和WStyle_SysMenu一起组合使用。
  • Qt::WStyle_ContextHelp - 添加一个上下文帮助按钮到对话框上。
  • Qt::WStyle_Tool - 使这个窗口变为一个工具窗口。一个工具窗口经常是一个比含有正常标题栏和休息的窗口更小的窗口，很典型的用于工具按钮的集合。如果它有一个父窗口，工具窗口将总被放在它的上面。如果它没有父窗口，你需要考虑同时传递一个WStyle_StaysOnTop。如果窗口系统支持它，一个工具窗口将会被使用更亮的框架来修饰。它也可以和WStyle_NoBorder一起组合使用。
  • Qt::WStyle_StaysOnTop - 通知窗口系统这个窗口应该放在所有其它窗口的上面。
  • Qt::WStyle_Dialog - 表明这个窗口是它的父窗口（比如，一个对话框）的逻辑子窗口。这个窗口将没有自己的任务栏条目并且通过窗口系统它将被保持在它的父窗口上面。通常当它的父窗口最小化时，它也最小化。如果没有自定义，这个窗口将会被一个稍微简单一些的标题栏修饰。这个标记被QDialog使用。

修饰标记：

  • Qt::WDestructiveClose - 当窗口部件已经接收到closeEvent()，或者当窗口部件试图忽略closeEvent()但不能的时候，使Qt删除这个窗口部件。
  • Qt::WPaintDesktop - 把桌面的绘制事件给这个窗口部件。
  • Qt::WPaintUnclipped - 使在这个窗口部件上的所有的绘制操作都不能被省略。在它前面的这个窗口部件的子窗口部件或者其它窗口部件不能把它上面的绘制区域省略掉。
  • Qt::WPaintClever - 表明Qt不应该试图优化重绘这个窗口部件，但是相反，在窗口系统上直接传递重绘事件。（这样往往会产生更多的事件和更小的重绘区域。）
  • Qt::WResizeNoErase - 表明重新定义窗口部件的大小不应该删除它。这样允许比较聪明的重绘来避免闪烁。
  • Qt::WMouseNoMask - 表明即使这个窗口部件有一个障板，它想获得它的整个矩形区域内的鼠标时间。
  • Qt::WStaticContents - 表明这个窗口部件的内容是向西北方向对齐的并且是静态度。当重新定义大小的时候，这个窗口部件将只接收它自己之内的新的可见的部分的绘制事件。
  • Qt::WRepaintNoErase - 表明这个窗口绘制所有的象素。更新、滚动和焦点改变都不会因此删除这个窗口部件。这样允许比较聪明的重绘来避免闪烁。
  • Qt::WGroupLeader - 使这个窗口为一个组领导。一个组领导不应该有父窗口（比如，它应该是一个顶级窗口）。组领导的任何子孙窗口（直接的或见解的）都在它这个组里，其它窗口不在。如果你从一个组中显示一个次要的窗口（比如，显示一个最上端父窗口为组领导的窗口），对于组内其它窗口它是模式的，但对于组外的它是非模式的。

其它标记。

  • Qt::WShowModal - 参看WType_Dialog

内部标记。

  • Qt::WNoMousePropagation
  • Qt::WStaticContents
  • Qt::WStyle_Reserved
  • Qt::WSubWindow
  • Qt::WType_Modal
  • Qt::WWinOwnDC
  • Qt::WX11BypassWM
  • Qt::WStyle_Mask
  • Qt::WType_Mask

Qt::WidgetState

内部标记。

  • Qt::WState_Created
  • Qt::WState_Disabled
  • Qt::WState_Visible
  • Qt::WState_ForceHide
  • Qt::WState_OwnCursor
  • Qt::WState_MouseTracking
  • Qt::WState_CompressKeys
  • Qt::WState_BlockUpdates
  • Qt::WState_InPaintEvent
  • Qt::WState_Reparented
  • Qt::WState_ConfigPending
  • Qt::WState_Resized
  • Qt::WState_AutoMask
  • Qt::WState_Polished
  • Qt::WState_DND
  • Qt::WState_Reserved0
  • Qt::WState_Reserved1
  • Qt::WState_Reserved2
  • Qt::WState_Reserved3
  • Qt::WState_Maximized
  • Qt::WState_Minimized
  • Qt::WState_ForceDisabled
  • Qt::WState_Exposed
  • Qt::WState_HasMouse

Qt::WindowsVersion

  • Qt::WV_32s
  • Qt::WV_95
  • Qt::WV_98
  • Qt::WV_Me
  • Qt::WV_DOS_based
  • Qt::WV_NT
  • Qt::WV_2000
  • Qt::WV_XP
  • Qt::WV_NT_based

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt Member List

Complete Member List for Qt

This is the complete list of member functions for Qt, including inherited members.


Qt模板库

Qt模板库（QTL）是一套提供对象容器的模板。如果你的编译器不能用到一个适当的STL实现，QTL可以替代它。它提供了对象的列表、对象的矢量（动态数组）、从一种类型到其它的映射（或字典），并且有关联的迭代器和算法。一个容器是可以包含和管理其它对象的一个对象并且提供迭代器来允许被包含的对象能够被访问。

QTL类的命名约定与其他Qt类一致（比如，count()、isEmpty()）。它们也提供额外的函数来兼容STL算法，比如size()和empty()。程序员也可以像使用STL的map一样来使用它们。

与STL相比，QTL仅仅包含了STL容器应用程序接口的最重要的特性，没有平台差异，通常要慢一些并且经常扩展为更少的对象代码。

如果你不能复制你所想要存储的对象，你最好使用QPtrCollection和它的朋友。它们就是被设计用来正确地处理这些类型的指针语义。这将适用于比如所有继承QObject的类。QObject没有一个复制构造函数，所以把它们作为值来使用是不可能的。你也许可以选择存储QObject的指针到QValueList，但是直接使用QPtrList看起来是对这类应用程序领域的更好的选择。QPtrList，像所有其它的基于QPtrCollection的容器，提供了比一个速度优化了的基于值的容器更多健全的检查。

如果你有一些实现值语义的对象，并且在你的目标平台没有可用的STL，Qt模板库就可以替代它。值语义至少需要以下这些：

  • 一个复制构造函数，
  • 一个赋值操作符和
  • 一个默认构造函数，比如一个没有任何参数的构造函数。

注意一个快速的复制构造函数对于容器的总性能是完全至关重要的，因为许多复制操作将会发生。

如果你打算排序你的数据，那么你必须在你的数据类中实现operator<()。

基于值的类的候选对象有QRect、QPoint、QSize、QString和所有简单的C++类型，比如int、bool和double。

Qt模板库是因为速度而被设计。迭代器是非常快的。为了实现这样的性能，所以就比基于QPtrCollection的类做了更少的错误检查。一个QTL容器，比如，没有跟踪任何关联的迭代器。这样就在比如删除项目的时候没有自动地执行有效性检查，但无论如何，它提供了很快很好的性能。

迭代器

Qt模板库处理值对象，而不是指针对象。因为这一点，没有比迭代器更好的遍历容器的方法了。一个迭代器的大小和一个普通指针的大小相同并没有什么不好的。

为了遍历一个容器，就像这样使用循环：

    typedef QValueList<int> List;
    List l;
    for( List::Iterator it = l.begin(); it != l.end(); ++it )
        printf( "Number is %i\n", *it );

begin()返回指向第一个元素的迭代器，而end()返回的则是在最后一个元素之后的一个迭代器。end()标明的是一个无效的位置，它永远不能被解除引用。它只是任何一次迭代的终止条件，也许是从begin()开始的。为了最快的速度，我们使用前置的操作符（++it、--it）替代后置的操作符（it++、it--）来增加或减少迭代器，因为前置的比后置的更快一点。

同样的概念适用于所有其它容器类：

    typedef QMap<QString,QString> Map;
    Map map;
    for( Map::iterator it = map.begin(); it != map.end(); ++it )
        printf( "Key=%s Data=%s\n", it.key().ascii(), it.data().ascii() );

    typedef QValueVector<int> Vector;
    Vector vec;
    for( Vector::iterator it = vec.begin(); it != vec.end(); ++it )
        printf( "Data=%d\n", *it );

这里有两种迭代器，上述的例子中显示的是可变的迭代器，还有一种返回当前对象的常量引用的常量迭代器。不论容器本身是一个常量，或者要把一个成员变量放到一个常量函数中，都需要常量迭代器。把一个常量迭代器赋值为一个普通的迭代器是不被允许的，因为它违法了常量语义。

算法

Qt模板库定义了大量的操作它的容器的算法。这些算法被作为模板函数实现并且提供了可以适用于任何提供迭代器的容器（甚至是你自己的容器）的有用的通用代码。

qHeapSort()和qBubbleSort()提供了著名的排序算法。你可以像这样使用它们：

    typedef QValueList<int> List;
    List l;
    l << 42 << 100 << 1234 << 12 << 8;
    qHeapSort( l );

    List l2;
    l2 << 42 << 100 << 1234 << 12 << 8;
    List::Iterator b = l2.find( 100 );
    List::Iterator e = l2.find( 8 );
    qHeapSort( b, e );

    double arr[] = { 3.2, 5.6, 8.9 };
    qHeapSort( arr, arr + 3 );

第一个实例是对整个列表进行排序。第二个实例是对两个迭代器之间的所有元素进行排序，也就是100、1234和12。第三个实例显示的是迭代器的行为就像指针一样并且它就可以被作为指针使用。

如果使用你自己的数据类型，你必须在你的数据类中实现operator<()。

自然地，这些排序模板在常量迭代器下不能工作。

另一个有用的是qSwap()。它交换两个变量的值：

    QString second( "Einstein" );
    QString name( "Albert" );
    qSwap( second, name );

另一个模板函数是qCount()。它统计一个容器中一个值出现的次数。例如：

    QValueList<int> l;
    l.push_back( 1 );
    l.push_back( 1 );
    l.push_back( 1 );
    l.push_back( 2 );
    int c = 0;
    qCount( l.begin(), l.end(), 1, c ); // c == 3

另一个模板函数是qFind()。它发现一个容器中一个值的第一个出现位置。例如：

    QValueList<int> l;
    l.push_back( 1 );
    l.push_back( 1 );
    l.push_back( 1 );
    l.push_back( 2 );
    QValueListIterator<int> it = qFind( l.begin(), l.end(), 2 );

另一个模板函数是qFill()。它用一个值的复制来填充一个范围。例如：

    QValueVector<int> v(3);
    qFill( v.begin(), v.end(), 99 ); // v包含99, 99, 99

另一个模板函数是qEqual()。它比较两个范围的元素是否相等。注意两个范围的元素数量是不被考虑的，只有第一个范围的元素与第二个范围的对应元素都相等的时候（因此，两个范围都必须有效），它们就相等。例如：

    QValueVector<int> v1(3);
    v1[0] = 1;
    v1[2] = 2;
    v1[3] = 3;

    QValueVector<int> v2(5);
    v1[0] = 1;
    v1[2] = 2;
    v1[3] = 3;
    v1[4] = 4;
    v1[5] = 5;

    bool b = qEqual( v1.begin(), v2.end(), v2.begin() );
    // b == TRUE

另一个模板函数是qCopy()。它复制一个范围的元素到OutputIterator，在这个例子中它是一个QTexOStreamIterator：

    QValueList<int> l;
    l.push_back( 100 );
    l.push_back( 200 );
    l.push_back( 300 );
    QTextOStream str( stdout );
    qCopy( l.begin(), l.end(), QTextOStreamIterator(str) );

另一个模板函数是qCopyBackward()。它复制一个容器或者它的一部分到一个OutputIterator，但是以向后的方式，例如：

    QValueVector<int> vec(3);
    vec.push_back( 100 );
    vec.push_back( 200 );
    vec.push_back( 300 );
    QValueVector<int> another;
    qCopyBackward( vec.begin(), vec.end(), another.begin() );
    // “another”现在包含100、200、300
    // 无论如何元素都被一次性复制
    // 是按倒序排列的（300、200、100）

另外，你可以把任何一个Qt模板库的迭代器作为OutputIterator使用。只需要注意迭代器的右面现在存在的元素和你所想要插入的一样多。下面这个例子就说明了这些：

    QStringList l1, l2;
    l1 << "Weis" << "Ettrich" << "Arnt" << "Sue";
    l2 << "Torben" << "Matthias";
    qCopy( l2.begin(), l2.end(), l1.begin() );

    QValueVector<QString> v( l1.size(), "Dave" );
    qCopy( l2.begin(), l2.end(), v.begin() );

这段代码结束后，列表l1包含“Torben”、“Matthias”、“Arnt”和“Sue”，前面的内容被覆盖了。矢量v包含“Torben”、“Matthias”、“Dave”和“Dave”，也是前面的内容被覆盖了。

如果你写了新的算法，请考虑把它们写成模板函数，这样就可以使它们能够用在尽可能多的容器上了。在上一个例子中，你可以很容易地使用qCopy()打印出一个标准C++数组：

    int arr[] = { 100, 200, 300 };
    QTextOStream str( stdout );
    qCopy( arr, arr + 3, QTextOStreamIterator( str ) );

流

所有提到的容器都可以通过不同的流操作符被串行化。这里是一个例子。

    QDataStream str(...);
    QValueList<QRect> l;
    // ……在这里填充这个列表
    str << l;

容易可以这样被再一次地读入：

    QValueList<QRect> l;
    str >> l;

这些也同样适用于QStringList、QValueStack和QMap

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTab Class

QTab Class Reference

The QTab class provides the structures in a QTabBar. More...

#include <qtabbar.h>

Inherits Qt.

List of all member functions.

Public Members

  • QTab ()
  • virtual ~QTab ()
  • QTab ( const QString & text )
  • QTab ( const QIconSet & icon, const QString & text = QString::null )
  • void setText ( const QString & text )
  • QString text () const
  • void setIconSet ( const QIconSet & icon )
  • QIconSet * iconSet () const
  • void setRect ( const QRect & rect )
  • QRect rect () const
  • void setEnabled ( bool enable )
  • bool isEnabled () const
  • void setIdentifier ( int i )
  • int identifier () const

Detailed Description

The QTab class provides the structures in a QTabBar.

This class is used for custom QTabBar tab headings.

See also QTabBar and Advanced Widgets.

Member Function Documentation

QTab::QTab ()

Constructs an empty tab. All fields are set to empty.

QTab::QTab ( const QString & text )

Constructs a tab with the text, text.

QTab::QTab ( const QIconSet & icon, const QString & text = QString::null )

Constructs a tab with an icon and the text, text.

QTab::~QTab () [virtual]

Destroys the tab and frees up all allocated resources

QIconSet * QTab::iconSet () const

Return the QIconSet of the QTab.

int QTab::identifier () const

Return the identifier for the QTab.

bool QTab::isEnabled () const

Returns TRUE if the QTab is enabled, otherwise return FALSE.

QRect QTab::rect () const

Return the QRect for the QTab.

void QTab::setEnabled ( bool enable )

If enable is TRUE enable the QTab, otherwise disable it.

void QTab::setIconSet ( const QIconSet & icon )

Sets the tab iconset to icon

void QTab::setIdentifier ( int i )

Set the identifier for the QTab to i. Each identifier for a QTabBar must be unique

void QTab::setRect ( const QRect & rect )

Set the QTab QRect to rect.

void QTab::setText ( const QString & text )

Sets the text of the tab to text.

QString QTab::text () const

Return the text of the QTab label.

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


QTab Member List

Complete Member List for QTab

This is the complete list of member functions for QTab, including inherited members.

  • QTab()
  • ~QTab()
  • iconSet()
  • identifier()
  • isEnabled()
  • rect()
  • setEnabled()
  • setIconSet()
  • setIdentifier()
  • setRect()
  • setText()
  • text()


QTabBar Class

QTabBar Class Reference

The QTabBar class provides a tab bar, e.g. for use in tabbed dialogs. More...

#include <qtabbar.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QTabBar ( QWidget * parent = 0, const char * name = 0 )
  • ~QTabBar ()
  • enum Shape { RoundedAbove, RoundedBelow, TriangularAbove, TriangularBelow }
  • Shape shape () const
  • virtual void setShape ( Shape )
  • virtual int addTab ( QTab * newTab )
  • virtual int insertTab ( QTab * newTab, int index = -1 )
  • virtual void removeTab ( QTab * t )
  • virtual void setTabEnabled ( int id, bool enabled )
  • bool isTabEnabled ( int id ) const
  • int currentTab () const
  • int keyboardFocusTab () const
  • QTab * tab ( int id ) const
  • QTab * tabAt ( int index ) const
  • int indexOf ( int id ) const
  • int count () const
  • virtual void layoutTabs ()
  • virtual QTab * selectTab ( const QPoint & p ) const
  • void removeToolTip ( int index )
  • void setToolTip ( int index, const QString & tip )
  • QString toolTip ( int index ) const

Public Slots

  • virtual void setCurrentTab ( int )
  • virtual void setCurrentTab ( QTab * tab )

Signals

  • void selected ( int id )

Properties

  • int count - the number of tabs in the tab bar (read only)
  • int currentTab - the id of the currently visible tab in the tab bar
  • int keyboardFocusTab - the id of the tab that currently has the keyboard focus (read only)
  • Shape shape - the shape of the tabs in the tab bar

Protected Members

  • virtual void paint ( QPainter * p, QTab * t, bool selected ) const
  • virtual void paintLabel ( QPainter * p, const QRect & br, QTab * t, bool has_focus ) const
  • virtual void paintEvent ( QPaintEvent * e )
  • QPtrList<QTab> * tabList ()

Detailed Description

The QTabBar class provides a tab bar, e.g. for use in tabbed dialogs.

QTabBar is straightforward to use; it draws the tabs using one of the predefined shapes, and emits a signal when a tab is selected. It can be subclassed to tailor the look and feel.

The choice of tab shape is a matter of taste, although tab dialogs (preferences and the like) invariably use RoundedAbove, and nobody uses TriangularAbove. Tab controls in windows other than dialogs almost always use either RoundedBelow or TriangularBelow. Many spreadsheets and other tab controls in which all the pages are essentially similar use TriangularBelow, whereas RoundedBelow is used mostly when the pages are different (e.g. a multi-page tool palette).

The most important part of QTabBar's API is the signal selected(). This is emitted whenever the selected page changes (even at startup, when the selected page changes from 'none'). There is also a slot, setCurrentTab(), which can be used to select a page programmatically.

QTabBar creates automatic accelerator keys in the manner of QButton; e.g. if a tab's label is "&Graphics", Alt+G becomes an accelerator key for switching to that tab.

The following virtual functions may need to be reimplemented:

  • paint() paints a single tab. paintEvent() calls paint() for each tab so that any overlap will look right.
  • addTab() creates a new tab and adds it to the bar.
  • selectTab() decides which tab, if any, the user selects with the mouse.

The index of the current tab is returned by currentTab(). The tab with a particular index is returned by tabAt(), the tab with a particular id is returned by tab(). The index of a tab is returned by indexOf(). The current tab can be set by index or tab pointer using one of the setCurrentTab() functions.

See also Advanced Widgets.

Member Type Documentation

QTabBar::Shape

This enum type lists the built-in shapes supported by QTabBar:
  • QTabBar::RoundedAbove - the normal rounded look above the pages
  • QTabBar::RoundedBelow - the normal rounded look below the pages
  • QTabBar::TriangularAbove - triangular tabs above the pages (very unusual; included for completeness)
  • QTabBar::TriangularBelow - triangular tabs similar to those used in the spreadsheet Excel, for example

Member Function Documentation

QTabBar::QTabBar ( QWidget * parent = 0, const char * name = 0 )

Constructs a new, empty tab bar; the parent and name arguments are passed on to the QWidget constructor.

QTabBar::~QTabBar ()

Destroys the tab control, freeing memory used.

int QTabBar::addTab ( QTab * newTab ) [virtual]

Adds the tab, newTab, to the tab control.

Sets newTab's id to a new id and places the tab just to the right of the existing tabs. If the tab's label contains an ampersand, the letter following the ampersand is used as an accelerator for the tab, e.g. if the label is "Bro&wse" then Alt+W becomes an accelerator which will move the focus to this tab. Returns the id.

See also insertTab().

int QTabBar::count () const

Returns the number of tabs in the tab bar. See the "count" property for details.

int QTabBar::currentTab () const

Returns the id of the currently visible tab in the tab bar. See the "currentTab" property for details.

int QTabBar::indexOf ( int id ) const

Returns the position index of the tab with id id.

See also tabAt().

int QTabBar::insertTab ( QTab * newTab, int index = -1 ) [virtual]

Inserts the tab, newTab, into the tab control.

If index is not specified, the tab is simply added. Otherwise it's inserted at the specified position.

Sets newTab's id to a new id. If the tab's label contains an ampersand, the letter following the ampersand is used as an accelerator for the tab, e.g. if the label is "Bro&wse" then Alt+W becomes an accelerator which will move the focus to this tab. Returns the id.

See also addTab().

bool QTabBar::isTabEnabled ( int id ) const

Returns TRUE if the tab with id id is enabled, or FALSE if it is disabled or there is no such tab.

See also setTabEnabled().

int QTabBar::keyboardFocusTab () const

Returns the id of the tab that currently has the keyboard focus. See the "keyboardFocusTab" property for details.

void QTabBar::layoutTabs () [virtual]

Lays out all existing tabs according to their label and their iconset.

void QTabBar::paint ( QPainter * p, QTab * t, bool selected ) const [virtual protected]

Paints the tab t using painter p. If and only if selected is TRUE, t is drawn currently selected.

This virtual function may be reimplemented to change the look of QTabBar. If you decide to reimplement it, you may also need to reimplement sizeHint().

void QTabBar::paintEvent ( QPaintEvent * e ) [virtual protected]

Repaints the tab row. All the painting is done by paint(); paintEvent() only decides which tabs need painting and in what order. The event is passed in e.

See also paint().

Reimplemented from QWidget.

void QTabBar::paintLabel ( QPainter * p, const QRect & br, QTab * t, bool has_focus ) const [virtual protected]

Paints the label of tab t centered in rectangle br using painter p. A focus indication is drawn if has_focus is TRUE.

void QTabBar::removeTab ( QTab * t ) [virtual]

Removes tab t from the tab control, and deletes the tab.

void QTabBar::removeToolTip ( int index )

Removes the tool tip for the tab at index index.

QTab * QTabBar::selectTab ( const QPoint & p ) const [virtual]

This virtual function is called by the mouse event handlers to determine which tab is pressed. The default implementation returns a pointer to the tab whose bounding rectangle contains p, if exactly one tab's bounding rectangle contains p. Otherwise it returns 0.

See also mousePressEvent() and mouseReleaseEvent().

void QTabBar::selected ( int id ) [signal]

QTabBar emits this signal whenever any tab is selected, whether by the program or by the user. The argument id is the id of the tab as returned by addTab().

show() is guaranteed to emit this signal; you can display your page in a slot connected to this signal.

void QTabBar::setCurrentTab ( int ) [virtual slot]

Sets the id of the currently visible tab in the tab bar. See the "currentTab" property for details.

void QTabBar::setCurrentTab ( QTab * tab ) [virtual slot]

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

Raises tab and emits the selected() signal unless the tab was already current.

See also currentTab and selected().

void QTabBar::setShape ( Shape ) [virtual]

Sets the shape of the tabs in the tab bar. See the "shape" property for details.

void QTabBar::setTabEnabled ( int id, bool enabled ) [virtual]

Enables tab id if enabled is TRUE or disables it if enabled is FALSE. If id is currently selected, setTabEnabled(FALSE) makes another tab selected.

setTabEnabled() updates the display if this causes a change in id's status.

See also update() and isTabEnabled().

void QTabBar::setToolTip ( int index, const QString & tip )

Sets the tool tip for the tab at index index to tip.

Shape QTabBar::shape () const

Returns the shape of the tabs in the tab bar. See the "shape" property for details.

QTab * QTabBar::tab ( int id ) const

Returns a pointer to the tab with id id or 0 if there is no such tab.

See also count.

QTab * QTabBar::tabAt ( int index ) const

Returns a pointer to the tab at the position index.

See also indexOf().

QPtrList<QTab> * QTabBar::tabList () [protected]

The list of QTab objects in the tab bar.

QString QTabBar::toolTip ( int index ) const

Returns the tool tip for the tab at index index.

Property Documentation

int count

This property holds the number of tabs in the tab bar.

Get this property's value with count().

See also tab().

int currentTab

This property holds the id of the currently visible tab in the tab bar.

If no tab page is currently visible, -1 will be the current value for this property. Even if the property value is not -1, you cannot assume that the user can see the relevant page, or that the tab is enabled. When you need to display something the value of this property represents the best page to display.

When this property is set to id, it will raise the tab with the id id and emit the selected() signal.

See also selected() and isTabEnabled().

Set this property's value with setCurrentTab() and get this property's value with currentTab().

int keyboardFocusTab

This property holds the id of the tab that currently has the keyboard focus.

This property contains the id of the tab that currently has the keyboard focus. If the tab bar does not have keyboard focus, the value of this property will be -1.

Get this property's value with keyboardFocusTab().

Shape shape

This property holds the shape of the tabs in the tab bar.

The value of this property can be one of the following: RoundedAbove (default), RoundedBelow, TriangularAbove or TriangularBelow.

See also Shape.

Set this property's value with setShape() and get this property's value with shape().

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


qtabbar.h Include File

qtabbar.h

This is the verbatim text of the qtabbar.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtabbar.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTab and QTabBar classes
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTABBAR_H
#define QTABBAR_H

#ifndef QT_H
#include "qwidget.h"
#include "qptrlist.h"
#endif // QT_H

#ifndef QT_NO_TABBAR

class QTabBar;
class QIconSet;

class Q_EXPORT QTab : public Qt
{
    friend class QTabBar;
    friend class QTabWidget;

public:
    QTab();
    virtual ~QTab();
    QTab( const QString& text );
    QTab( const QIconSet& icon, const QString& text = QString::null );

    void setText( const QString& text);
    QString text() const { return label; }
    void setIconSet( const QIconSet& icon );
    QIconSet* iconSet() const { return iconset; }
    void setRect( const QRect& rect ) { r = rect; }
    QRect rect() const { return r; }
    void setEnabled( bool enable ) { enabled = enable; }
    bool isEnabled() const { return enabled; }
    void setIdentifier( int i ) { id = i; }
    int identifier() const { return id; }

private:
    void setTabBar( QTabBar *tb );
    QString label;
    QRect r; // the bounding rectangle of this (may overlap with others)
    bool enabled;
    int id;
    QIconSet* iconset; // optional iconset
    QTabBar *tb;
};

struct QTabPrivate;
//class *QAccel;

class Q_EXPORT QTabBar: public QWidget
{
    Q_OBJECT
    Q_ENUMS( Shape )
    Q_PROPERTY( Shape shape READ shape WRITE setShape )
    Q_PROPERTY( int currentTab READ currentTab WRITE setCurrentTab )
    Q_PROPERTY( int count READ count )
    Q_PROPERTY( int keyboardFocusTab READ keyboardFocusTab )

public:
    QTabBar( QWidget* parent=0, const char* name=0 );
    ~QTabBar();

    enum Shape { RoundedAbove, RoundedBelow,
         TriangularAbove, TriangularBelow };

    Shape shape() const;
    virtual void setShape( Shape );

    void show();

    virtual int addTab( QTab * );
    virtual int insertTab( QTab *, int index = -1 );
    virtual void removeTab( QTab * );

    virtual void setTabEnabled( int, bool );
    bool isTabEnabled( int ) const;

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    int currentTab() const;
    int keyboardFocusTab() const;

    QTab * tab( int ) const;
    QTab * tabAt( int ) const;
    int indexOf( int ) const;
    int count() const;

    virtual void layoutTabs();
    virtual QTab * selectTab( const QPoint & p ) const;

    void 	removeToolTip( int index );
    void     	setToolTip( int index, const QString & tip );
    QString 	toolTip( int index ) const;

public slots:
    virtual void setCurrentTab( int );
    virtual void setCurrentTab( QTab * );

signals:
    void  selected( int );

protected:
    virtual void paint( QPainter *, QTab *, bool ) const; // ### not const
    virtual void paintLabel( QPainter*, const QRect&, QTab*, bool ) const;

    void focusInEvent( QFocusEvent *e );
    void focusOutEvent( QFocusEvent *e );

    void resizeEvent( QResizeEvent * );
    void paintEvent( QPaintEvent * );
    void mousePressEvent ( QMouseEvent * );
    void mouseMoveEvent ( QMouseEvent * );
    void mouseReleaseEvent ( QMouseEvent * );
    void keyPressEvent( QKeyEvent * );
    void styleChange( QStyle& );
    void fontChange ( const QFont & );

    QPtrList<QTab> * tabList();

private slots:
    void scrollTabs();

private:
    QPtrList<QTab> * l;
    QPtrList<QTab> * lstatic;
    void makeVisible( QTab* t  );
    void updateArrowButtons();
    QTabPrivate * d;

    friend class QTabBarToolTip;
    friend class QTab;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTabBar( const QTabBar & );
    QTabBar& operator=( const QTabBar & );
#endif
};

#endif // QT_NO_TABBAR

#endif // QTABBAR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTabBar Member List

Complete Member List for QTabBar

This is the complete list of member functions for QTabBar, including inherited members.

  • QTabBar()
  • ~QTabBar()
  • acceptDrops()
  • addTab()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • count()
  • create()
  • currentTab()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertTab()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTabEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardFocusTab()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • layoutTabs()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paint()
  • paintEvent()
  • paintLabel()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeTab()
  • removeToolTip()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • selectTab()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCurrentTab()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setShape()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabEnabled()
  • setTabOrder()
  • setToolTip()
  • setUpdatesEnabled()
  • setWFlags()
  • shape()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tab()
  • tabAt()
  • tabList()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • toolTip()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QTabDialog类

QTabDialog类参考

QTabDialog类提供了一个被标签的窗口部件的栈。 详情请见……

#include <qtabdialog.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • QTabDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )
  • ~QTabDialog ()
  • virtual void setFont ( const QFont & font )
  • void addTab ( QWidget * child, const QString & label )
  • void addTab ( QWidget * child, const QIconSet & iconset, const QString & label )
  • void addTab ( QWidget * child, QTab * tab )
  • void insertTab ( QWidget * child, const QString & label, int index = -1 )
  • void insertTab ( QWidget * child, const QIconSet & iconset, const QString & label, int index = -1 )
  • void insertTab ( QWidget * child, QTab * tab, int index = -1 )
  • void changeTab ( QWidget * w, const QString & label )
  • void changeTab ( QWidget * w, const QIconSet & iconset, const QString & label )
  • bool isTabEnabled ( QWidget * w ) const
  • void setTabEnabled ( QWidget * w, bool enable )
  • bool isTabEnabled ( const char * name ) const （废弃）
  • void setTabEnabled ( const char * name, bool enable ) （废弃）
  • void showPage ( QWidget * w )
  • void removePage ( QWidget * w )
  • QString tabLabel ( QWidget * w )
  • QWidget * currentPage () const
  • void setDefaultButton ( const QString & text )
  • void setDefaultButton ()
  • bool hasDefaultButton () const
  • void setHelpButton ( const QString & text )
  • void setHelpButton ()
  • bool hasHelpButton () const
  • void setCancelButton ( const QString & text )
  • void setCancelButton ()
  • bool hasCancelButton () const
  • void setApplyButton ( const QString & text )
  • void setApplyButton ()
  • bool hasApplyButton () const
  • void setOkButton ( const QString & text )
  • void setOkButton ()
  • bool hasOkButton () const

信号

  • void aboutToShow ()
  • void applyButtonPressed ()
  • void cancelButtonPressed ()
  • void defaultButtonPressed ()
  • void helpButtonPressed ()
  • void currentChanged ( QWidget * )
  • void selected ( const QString & ) （废弃）

保护成员

  • void setTabBar ( QTabBar * tb )
  • QTabBar * tabBar () const

详细描述

QTabDialog类提供了一个被标签的窗口部件的栈。

被标签的对话框就是一个在里面有几个“标签页”是可用的对话框。通过点击标签页的标签或者通过按下被指出的Alt+letter键组合，用户可以选择他们想使用的标签页。

QTabDialog提供了一个由标签组成的单一一排在上面组成的标签栏，每一个标签都有一个关联的窗口部件包含着那个标签的标签页。另外，QTabDialog提供了一个OK按钮和下述几个可选按钮：Apply、Cancel、Defaults和Help。

使用QTabDialog的常用方法是在构造函数中像下面这样做：

  1. 创建一个QTabDialog。
  2. 为标签对话框中的每一个页面创建一个QWidget，把它们的自对象插入进去，为它们设置几何形状管理，并且使用addTab()（或者insertTab()）来为它设置一个标签和键盘快捷键。
  3. 使用setOkButton()、setApplyButton()、setDefaultsButton()、setCancelButton()和setHelpButton()为标签对话框设置按钮。
  4. 连接信号和槽。

如果你没有调用addTab()，你已经创建的页面将不是可见的。不要把你提供给QWidget构造函数的对象名称和你提供给addTab()的标签弄混，addTab()中的是出现在窗口部件的标签伤得用户可视名称并且可以有一个快捷键，而窗口部件的名称主要用语调试。

几乎所有应用程序不得不把applyButtonPressed()信号连接到什么上，当OK或者Apply被点击时，applyButtonPressed()被发射，并且你的槽必须复制对话框的状态到应用程序中。

这里有其它几个可能有用的信号：

  • cancelButtonPressed() is emitted when the user clicks Cancel. 当用户点击Cancel时，cancelButtonPressed()被发射。
  • 当用户点击Defaults时，defaultButtonPressed()被发射，它被连接的槽应该重置这个对话框为应用程序的默认值。
  • 当用户点击Help时，helpButtonPressed()被发射。
  • 在show()开始时，aboutToShow()被发射，如果在标签对话框的创建和show()被调用的时候之间有应用程序的状态发生改变的机会，你必须把这个信号连接到重置对话框状态的槽上。
  • 当用户选择一个页时，currentChanged()被发射。

每个标签在任何给定的时间都可以是生效的或者失效的（请参考setTabEnabled()）。如果一个标签生效，标签文本就会被绘制为黑色并且用户可以选择这个标签。如果一个标签失效，标签文本就会被一种不同的方式绘制并且用户也就不可以选择它了。注意，尽管一个标签是失效的，这页仍是可见的，例如，如果所有的标签都变为失效了。

你可以使用changeTab()来改变标签的文本和图标集。标签页可以用removePage()移除并且用showPage()显示。当前页由currentPage()给定。

QTabDialog不支持在侧面或者底下的标签，你也不能设置或者重新找回可见的页。如果你需要比QTabDialog提供的更多的功能，可以考虑考虑使用可以放置QTabWidget的QTabBar的QDialog。

QTabDialog的绝大部分功能是由QTabWidget提供的。

也可以参考QDialog和对话框类。

成员函数文档

QTabDialog::QTabDialog ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )

构造一个只有OK按钮的QTabDialog。parent、name、modal和窗口部件标记 f参数被传递给QDialog的构造函数。

QTabDialog::~QTabDialog ()

销毁这个标签对话框。

void QTabDialog::aboutToShow () [信号]

当设置对话框的内容的状态的时候，这个信号被show()发射。对话框应该反映当它出现的时候应用程序的当前状态，如果在你调用QTabDialog::QTabDialog()和QTabDialog::show()之间，有改变应用程序的状态的可能性的话，你应该在一个槽中设置对话框的状态并且把它和这个信号连接起来。

这主要适用于保持隐藏的QTabDialog对象，而不是那些被创建、被显示然后被删除的。

也可以参考applyButtonPressed()、show()和cancelButtonPressed()。

void QTabDialog::addTab ( QWidget * child, const QString & label )

把另外一个标签和页添加到这个标签视中。

新的页是child，标签文本是label。注意窗口部件名称（你提供给窗口部件构造函数和给setTabEnabled()的，例如）和标签文本的不同。这个窗口部件名称用于应用程序内部并且是不变的，而标签文本是被显示在屏幕上并且可以根据语言和其它因素变化的。

如果标签的label包含“&”，那么在“&”后面的字符就会被用作这个标签的快捷键，例如，如果标签为“Bro&wse”，那么Alt+W就变成了快捷键，它会使焦点移到这个标签的。

如果在show()之后调用addTab()，屏幕将会闪烁并且用户也许会困惑。

也可以参考insertTab()。

void QTabDialog::addTab ( QWidget * child, const QIconSet & iconset, const QString & label )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本的函数显示child标签上的iconset和label。

void QTabDialog::addTab ( QWidget * child, QTab * tab )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这是一个添加标签的底层方法，和其它addTab()方法相似。如果你正在使用setTabBar()来设置一个QTabBar继承类并且为QTab的子类重载QTabBar::paint()函数，这个方法就很有用了。

child是要被放置到新标签页的窗口部件。tab就是要显示在标签页上的标签——通常它显示一个标签文本或者一个图标来标识标签页。

void QTabDialog::applyButtonPressed () [信号]

当Apply或者OK按钮之一被点击时，这个信号被发射。

它应该被连接到一个（或几个）根据对话框状态改变应用程序状态的槽。

也可以参考cancelButtonPressed()、defaultButtonPressed()和setApplyButton()。

void QTabDialog::cancelButtonPressed () [信号]

当Cancel按钮被点击时，这个信号被发射。它自动被连接到将会隐藏对话框的QDialog::reject()。

Cancel按钮一点也不会改变应用程序的状态，所以你应该不需要把它和任何槽连接起来。

也可以参考applyButtonPressed()、defaultButtonPressed()和setCancelButton()。

void QTabDialog::changeTab ( QWidget * w, const QIconSet & iconset, const QString & label )

改变标签页w的图标集和标签文本分别为iconset和label。

void QTabDialog::changeTab ( QWidget * w, const QString & label )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

为标签页w定义新的label。

void QTabDialog::currentChanged ( QWidget * ) [信号]

只要当前页发生改变，这个信号就被发射。

也可以参考currentPage()、showPage()和tabLabel()。

QWidget * QTabDialog::currentPage () const

返回当前正在被标签对话框显示的页的指针。标签对话框会尽它最大努力来保证这个值不会为0（但是如果你也足够努力的话，它可能就是了）。

void QTabDialog::defaultButtonPressed () [信号]

当Defaults按钮被按下时，这个信号被发射。它应该重置对话框（但不是应用程序）为“出厂默认设置”。

直到用户点击Apply或者OK之前，应用程序的状态不应改变。

也可以参考applyButtonPressed()、cancelButtonPressed()和setDefaultButton()。

bool QTabDialog::hasApplyButton () const

如果标签对话框已经有了一个Apply按钮，返回真，否则返回假。

也可以参考setApplyButton()、applyButtonPressed()、hasCancelButton()和hasDefaultButton()。

bool QTabDialog::hasCancelButton () const

如果标签对话框已经有了一个Cancel按钮，返回真，否则返回假。

也可以参考setCancelButton()、cancelButtonPressed()、hasApplyButton()和hasDefaultButton()。

bool QTabDialog::hasDefaultButton () const

如果标签对话框已经有了一个Defaults按钮，返回真，否则返回假。

也可以参考setDefaultButton()、defaultButtonPressed()、hasApplyButton()和hasCancelButton()。

bool QTabDialog::hasHelpButton () const

如果标签对话框已经有了一个Help按钮，返回真，否则返回假。

也可以参考setHelpButton()、helpButtonPressed()、hasApplyButton()和hasCancelButton()。

bool QTabDialog::hasOkButton () const

如果标签对话框已经有了一个OK按钮，返回真，否则返回假。

也可以参考setOkButton()、hasApplyButton()、hasCancelButton()和hasDefaultButton()。

void QTabDialog::helpButtonPressed () [信号]

当Help按钮被按下时，这个信号被发射。它可以用来呈现关于如何使用这个对话框的信息。

也可以参考applyButtonPressed()、cancelButtonPressed()和setHelpButton()。

void QTabDialog::insertTab ( QWidget * child, const QString & label, int index = -1 )

在标签视中插入另一个标签和页。

新的页是child，标签文本是label。注意窗口部件名称（你提供给窗口部件构造函数和给setTabEnabled()的，例如）和标签文本的不同。这个窗口部件名称用于应用程序内部并且是不变的，而标签文本是被显示在屏幕上并且可以根据语言和其它因素变化的。

如果标签的label包含“&”，那么在“&”后面的字符就会被用作这个标签的快捷键，例如，如果标签为“Bro&wse”，那么Alt+W就变成了快捷键，它会使焦点移到这个标签的。

如果index没有被指定，那么这个标签只是被简单添加。否则它就会被插入在特定位置。

如果在show()之后调用insertTab()，屏幕将会闪烁并且用户也许会困惑。

也可以参考addTab()。

void QTabDialog::insertTab ( QWidget * child, const QIconSet & iconset, const QString & label, int index = -1 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本的函数显示child标签上的iconset和label。

void QTabDialog::insertTab ( QWidget * child, QTab * tab, int index = -1 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这是一个添加标签的底层方法，和其它insertTab()方法相似。如果你正在使用setTabBar()来设置一个QTabBar继承类并且为QTab的子类重载QTabBar::paint()函数，这个方法就很有用了。

child是要被放置到新标签页的窗口部件。tab就是要显示在标签页上的标签——通常它显示一个标签文本或者一个图标来标识标签页。index是这个标签页应该被插入的位置。

bool QTabDialog::isTabEnabled ( QWidget * w ) const

如果页w是生效的，返回真，否则返回假。

也可以参考setTabEnabled()和QWidget::enabled。

bool QTabDialog::isTabEnabled ( const char * name ) const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

如果对象名称为name的页是生效的，返回真，否则返回假。

如果name为0或者没有这样一个名称的页，isTabEnabled()返回假。

也可以参考setTabEnabled()和QWidget::enabled。

void QTabDialog::removePage ( QWidget * w )

从窗口部件栈中移除页w。但不删除w。

也可以参考showPage()、QTabWidget::removePage()和QWidgetStack::removeWidget()。

void QTabDialog::selected ( const QString & ) [信号]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

只要一个标签被选择（升起），这个信号就被发射，包括在第一个show()期间。

也可以参考raise()。

void QTabDialog::setApplyButton ( const QString & text )

把Apply按钮添加到对话框。按钮文本被设置为text。

Apply按钮应该把对话框中的当前设置提交给应用程序，并且保持对话框是可视的。

当Apply被点击时，applyButtonPressed()信号被发射。

如果text为零字符串，就没有按钮被显示。

也可以参考setCancelButton()、setDefaultButton()和applyButtonPressed()。

void QTabDialog::setApplyButton ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把Apply按钮添加到对话框。按钮文本被设置为本地化的“Apply”。

void QTabDialog::setCancelButton ( const QString & text )

把Cancel按钮添加到对话框。按钮文本被设置为text。

Cancel按钮也应该把标签视被弹出之前的设置返回给应用程序，或者如果用户已经点击了Apply，就把最近一次Apply的状态立即返回。

当Cancel被点击时，cancelButtonPressed()信号被发射。同时对话框被关闭。

如果text为零字符串，就没有按钮被显示。

也可以参考setApplyButton()、setDefaultButton()和cancelButtonPressed()。

void QTabDialog::setCancelButton ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把Cancel按钮添加到对话框。按钮文本被设置为本地化的“Cancel”。

void QTabDialog::setDefaultButton ( const QString & text )

把Defaults按钮添加到对话框。按钮文本被设置为text。

Defaults按钮应该把对话框（但不是应用程序）设置回应用程序的默认值。

当Defaults被点击时，defaultButtonPressed()信号被发射。

如果text为零字符串，就没有按钮被显示。

也可以参考setApplyButton()、setCancelButton()和defaultButtonPressed()。

void QTabDialog::setDefaultButton ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把Defaults按钮添加到对话框。按钮文本被设置为本地化的“Defaults”。

void QTabDialog::setFont ( const QFont & font ) [虚]

设置标签的字体为font。

如果窗口部件是可视的，显示会立即更新字体。根据旧字体和新字体的大小，也许会导致一些几何形状的变化。

从QWidget中重新实现。

void QTabDialog::setHelpButton ( const QString & text )

把Help按钮添加到对话框。按钮文本被设置为text。

当Help被点击时，helpButtonPressed()信号被发射。

如果text为零字符串，就没有按钮被显示。

也可以参考setApplyButton()、setCancelButton()和helpButtonPressed()。

void QTabDialog::setHelpButton ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把Help按钮添加到对话框。按钮文本被设置为本地化的“Help”。

void QTabDialog::setOkButton ( const QString & text )

把OK按钮添加到对话框。按钮文本被设置为text。 当OK按钮被点击时，applyButtonPressed()信号被发射，并且把对话框中的当前设置提交给应用程序。然后对话框关闭。

如果text为零字符串，就没有按钮被显示。

也可以参考setCancelButton()、setDefaultButton()和applyButtonPressed()。

void QTabDialog::setOkButton ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把OK按钮添加到对话框。按钮文本被设置为本地化的“OK”。

void QTabDialog::setTabBar ( QTabBar * tb ) [保护]

替换对话框上面的QTabBar为给定的标签栏tb。注意这必须在任何标签被添加之前调用，否则行为是不确定的。

也可以参考tabBar()。

void QTabDialog::setTabEnabled ( QWidget * w, bool enable )

如果enable为真，页w就生效，否则w就失效。页的标签被适当地重新绘制。

QTabWidget在内部使用QWidget::setEnabled()，而不是保留一个不同的标记。

注意失效的标签和标签页可以是可视的。如果这个页已经可视，QTabWidget不会隐藏它，如果所有的页都是失效地，QTabWidget将会显示其中一个。

也可以参考isTabEnabled()和QWidget::enabled。

void QTabDialog::setTabEnabled ( const char * name, bool enable )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

找到对象名称为name的页，根据enable的值来使它生效/失效并且适当地重新绘制页的标签。

QTabWidget在内部使用QWidget::setEnabled()，而不是保留一个不同的标记。

注意失效的标签和标签页可以是可视的。如果这个页已经可视，QTabWidget不会隐藏它，如果所有的页都是失效地，QTabWidget将会显示其中一个。

因为标签文本也许在多语言应用程序中是变化的，所以使用对象名称（而不是标签文本）。

也可以参考isTabEnabled()和QWidget::enabled。

void QTabDialog::showPage ( QWidget * w )

确保窗口部件w被显示。这主要用于快捷键。

警告： 如果没有仔细使用，这个函数很容易让用户惊奇或者混乱。

也可以参考QTabBar::currentTab。

QTabBar * QTabDialog::tabBar () const [保护]

返回当前设置的QTabBar。

也可以参考setTabBar()。

QString QTabDialog::tabLabel ( QWidget * w )

返回w页的标签文本。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtabdialog.h包含文件

qtabdialog.h

这里是qtabdialog.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtabdialog.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTabDialog class
**
** Created : 960825
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTABDIALOG_H
#define QTABDIALOG_H

#ifndef QT_H
#include "qdialog.h"
#include "qiconset.h"
#endif // QT_H

#ifndef QT_NO_TABDIALOG

class  QTabBar;
class  QTab;
class  QTabDialogPrivate;

class Q_EXPORT QTabDialog : public QDialog
{
    Q_OBJECT
public:
    QTabDialog( QWidget* parent=0, const char* name=0, bool modal=FALSE,
        WFlags f=0 );
    ~QTabDialog();

    void show();
    void setFont( const QFont & font );

    void addTab( QWidget *, const QString &);
    void addTab( QWidget *child, const QIconSet& iconset, const QString &label);
    void addTab( QWidget *, QTab* );

    void insertTab( QWidget *, const QString &, int index = -1);
    void insertTab( QWidget *child, const QIconSet& iconset, const QString &label, int index = -1);
    void insertTab( QWidget *, QTab*, int index = -1 );

    void changeTab( QWidget *, const QString &);
    void changeTab( QWidget *child, const QIconSet& iconset, const QString &label);

    bool isTabEnabled(  QWidget * ) const;
    void setTabEnabled( QWidget *, bool );
    bool isTabEnabled( const char* ) const; // compatibility
    void setTabEnabled( const char*, bool ); // compatibility

    void showPage( QWidget * );
    void removePage( QWidget * );
    QString tabLabel( QWidget * );

    QWidget * currentPage() const;

    void setDefaultButton( const QString &text );
    void setDefaultButton();
    bool hasDefaultButton() const;

    void setHelpButton( const QString &text );
    void setHelpButton();
    bool hasHelpButton() const;

    void setCancelButton( const QString &text );
    void setCancelButton();
    bool hasCancelButton() const;

    void setApplyButton( const QString &text );
    void setApplyButton();
    bool hasApplyButton() const;

#ifndef Q_QDOC
    void setOKButton( const QString &text = QString::null );
#endif
    void setOkButton( const QString &text );
    void setOkButton();
    bool hasOkButton() const;

protected:
    void paintEvent( QPaintEvent * );
    void resizeEvent( QResizeEvent * );
    void styleChange( QStyle& );
    void setTabBar( QTabBar* );
    QTabBar* tabBar() const;

signals:
    void aboutToShow();

    void applyButtonPressed();
    void cancelButtonPressed();
    void defaultButtonPressed();
    void helpButtonPressed();

    void currentChanged( QWidget * );
    void selected( const QString& ); // obsolete

private slots:
    void showTab( int i );

private:
    void setSizes();
    void setUpLayout();

    QTabDialogPrivate *d;
private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTabDialog( const QTabDialog & );
    QTabDialog& operator=( const QTabDialog & );
#endif
};

#endif // QT_NO_TABDIALOG

#endif // QTABDIALOG_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTabDialog成员列表

完整的QTabDialog成员列表

这里是QTabDialog,成员函数的完整列表，包括继承的成员。

  • QTabDialog()
  • ~QTabDialog()
  • aboutToShow()
  • accept()
  • acceptDrops()
  • addTab()
  • adjustSize()
  • applyButtonPressed()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • cancelButtonPressed()
  • caption()
  • changeTab()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • currentChanged()
  • currentPage()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • defaultButtonPressed()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasApplyButton()
  • hasCancelButton()
  • hasDefaultButton()
  • hasFocus()
  • hasHelpButton()
  • hasMouse()
  • hasMouseTracking()
  • hasOkButton()
  • height()
  • heightForWidth()
  • helpButtonPressed()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insertTab()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTabEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removePage()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setApplyButton()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCancelButton()
  • setCaption()
  • setCursor()
  • setDefaultButton()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setHelpButton()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOkButton()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabBar()
  • setTabEnabled()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showPage()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabBar()
  • tabLabel()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTable类

QTable类参考
[表格模块]

QTable类提供了一个灵活的和可编辑的表格部件。 详见……

#include <qtable.h>

继承了QScrollView。

被QDataTable所继承。

所有成员函数的列表。

公有成员

  • QTable ( QWidget * parent = 0, const char * name = 0 )
  • QTable ( int numRows, int numCols, QWidget * parent = 0, const char * name = 0 )
  • ~QTable ()
  • QHeader * horizontalHeader () const
  • QHeader * verticalHeader () const
  • enum SelectionMode { Single, Multi, SingleRow, MultiRow, NoSelection }
  • virtual void setSelectionMode ( SelectionMode mode )
  • SelectionMode selectionMode () const
  • virtual void setItem ( int row, int col, QTableItem * item )
  • virtual void setText ( int row, int col, const QString & text )
  • virtual void setPixmap ( int row, int col, const QPixmap & pix )
  • virtual QTableItem * item ( int row, int col ) const
  • virtual QString text ( int row, int col ) const
  • virtual QPixmap pixmap ( int row, int col ) const
  • virtual void clearCell ( int row, int col )
  • virtual QRect cellGeometry ( int row, int col ) const
  • virtual int columnWidth ( int col ) const
  • virtual int rowHeight ( int row ) const
  • virtual int columnPos ( int col ) const
  • virtual int rowPos ( int row ) const
  • virtual int columnAt ( int x ) const
  • virtual int rowAt ( int y ) const
  • virtual int numRows () const
  • virtual int numCols () const
  • void updateCell ( int row, int col )
  • int currentRow () const
  • int currentColumn () const
  • void ensureCellVisible ( int row, int col )
  • bool isSelected ( int row, int col ) const
  • bool isRowSelected ( int row, bool full = FALSE ) const
  • bool isColumnSelected ( int col, bool full = FALSE ) const
  • int numSelections () const
  • QTableSelection selection ( int num ) const
  • virtual int addSelection ( const QTableSelection & s )
  • virtual void removeSelection ( const QTableSelection & s )
  • virtual void removeSelection ( int num )
  • virtual int currentSelection () const
  • bool showGrid () const
  • bool columnMovingEnabled () const
  • bool rowMovingEnabled () const
  • virtual void sortColumn ( int col, bool ascending = TRUE, bool wholeRows = FALSE )
  • bool sorting () const
  • virtual void takeItem ( QTableItem * i )
  • virtual void setCellWidget ( int row, int col, QWidget * e )
  • virtual QWidget * cellWidget ( int row, int col ) const
  • virtual void clearCellWidget ( int row, int col )
  • virtual QRect cellRect ( int row, int col ) const
  • virtual void paintCell ( QPainter * p, int row, int col, const QRect & cr, bool selected )
  • virtual void paintCell ( QPainter * p, int row, int col, const QRect & cr, bool selected, const QColorGroup & cg )
  • virtual void paintFocus ( QPainter * p, const QRect & cr )
  • bool isReadOnly () const
  • bool isRowReadOnly ( int row ) const
  • bool isColumnReadOnly ( int col ) const
  • void repaintSelections ()
  • enum FocusStyle { FollowStyle, SpreadSheet }
  • virtual void setFocusStyle ( FocusStyle fs )
  • FocusStyle focusStyle () const

公有槽

  • virtual void setNumRows ( int r )
  • virtual void setNumCols ( int r )
  • virtual void setShowGrid ( bool b )
  • virtual void hideRow ( int row )
  • virtual void hideColumn ( int col )
  • virtual void showRow ( int row )
  • virtual void showColumn ( int col )
  • virtual void setColumnWidth ( int col, int w )
  • virtual void setRowHeight ( int row, int h )
  • virtual void adjustColumn ( int col )
  • virtual void adjustRow ( int row )
  • virtual void setColumnStretchable ( int col, bool stretch )
  • virtual void setRowStretchable ( int row, bool stretch )
  • bool isColumnStretchable ( int col ) const
  • bool isRowStretchable ( int row ) const
  • virtual void setSorting ( bool b )
  • virtual void swapRows ( int row1, int row2, bool swapHeader = FALSE )
  • virtual void swapColumns ( int col1, int col2, bool swapHeader = FALSE )
  • virtual void swapCells ( int row1, int col1, int row2, int col2 )
  • virtual void setLeftMargin ( int m )
  • virtual void setTopMargin ( int m )
  • virtual void setCurrentCell ( int row, int col )
  • void clearSelection ( bool repaint = TRUE )
  • virtual void setColumnMovingEnabled ( bool b )
  • virtual void setRowMovingEnabled ( bool b )
  • virtual void setReadOnly ( bool b )
  • virtual void setRowReadOnly ( int row, bool ro )
  • virtual void setColumnReadOnly ( int col, bool ro )
  • virtual void setDragEnabled ( bool b )
  • bool dragEnabled () const
  • virtual void insertRows ( int row, int count = 1 )
  • virtual void insertColumns ( int col, int count = 1 )
  • virtual void removeRow ( int row )
  • virtual void removeRows ( const QMemArray<int> & rows )
  • virtual void removeColumn ( int col )
  • virtual void removeColumns ( const QMemArray<int> & cols )
  • virtual void editCell ( int row, int col, bool replace = FALSE )

信号

  • void currentChanged ( int row, int col )
  • void clicked ( int row, int col, int button, const QPoint & mousePos )
  • void doubleClicked ( int row, int col, int button, const QPoint & mousePos )
  • void pressed ( int row, int col, int button, const QPoint & mousePos )
  • void selectionChanged ()
  • void valueChanged ( int row, int col )
  • void contextMenuRequested ( int row, int col, const QPoint & pos )
  • void dropped ( QDropEvent * e )

属性

  • bool columnMovingEnabled - 用户是否可以移动列
  • FocusStyle focusStyle - 当前的（焦点所在的）单元格如何绘制
  • int numCols - 表格中的列数
  • int numRows - 表格中的行数
  • bool readOnly - 表格是否是只读的
  • bool rowMovingEnabled - 用户是否可以移动行
  • SelectionMode selectionMode - 当前的选中模式
  • bool showGrid - 是否显示表格的栅格
  • bool sorting - 点击列标题是否对该列排序

保护成员

  • enum EditMode { NotEditing, Editing, Replacing }
  • virtual void drawContents ( QPainter * p, int cx, int cy, int cw, int ch )
  • void setEditMode ( EditMode mode, int row, int col )
  • virtual void contentsDragEnterEvent ( QDragEnterEvent * e )
  • virtual void contentsDragMoveEvent ( QDragMoveEvent * e )
  • virtual void contentsDragLeaveEvent ( QDragLeaveEvent * e )
  • virtual void contentsDropEvent ( QDropEvent * e )
  • virtual QDragObject * dragObject ()
  • virtual void startDrag ()
  • virtual void paintEmptyArea ( QPainter * p, int cx, int cy, int cw, int ch )
  • virtual void activateNextCell ()
  • virtual QWidget * createEditor ( int row, int col, bool initFromCell ) const
  • virtual void setCellContentFromEditor ( int row, int col )
  • virtual QWidget * beginEdit ( int row, int col, bool replace )
  • virtual void endEdit ( int row, int col, bool accept, bool replace )
  • virtual void resizeData ( int len )
  • virtual void insertWidget ( int row, int col, QWidget * w )
  • int indexOf ( int row, int col ) const
  • bool isEditing () const
  • EditMode editMode () const
  • int currEditRow () const
  • int currEditCol () const

保护槽

  • virtual void columnWidthChanged ( int col )
  • virtual void rowHeightChanged ( int row )
  • virtual void columnIndexChanged ( int section, int fromIndex, int toIndex )
  • virtual void rowIndexChanged ( int section, int fromIndex, int toIndex )
  • virtual void columnClicked ( int col )

详细描述

QTable类提供了一个灵活的和可编辑的表格部件。

鉴于所提供功能的复杂性，QTable确实包含了许多API，尽管如此，它还是易于使用的。QTable提供的功能可以处理标题（headers）、行列（rows和columns）、单元格（cells）和选中区域（selections）。QTable还含有内嵌编辑（in-place editing）和拖放（drag和drop），以及一批有用的信号。QTable有效率地支持很大的表格，例如有百万行乘百万列单元格的表格也毫无问题。QTable内存使用节约，未用的单元格没有内存开销。

    QTable *table = new QTable( 100, 250, this );
    table->setPixmap( 3, 2, pix );
    table->setText( 3, 2, "A pixmap" );

第一行代码构造了一个指定行列数目的表格。然后我们在同一个 单元格插入一个象素映射（pixmap）和一些文本，象素映射在文本的左边。QTable的单元格可以使用QTableItem、QComboTableItem或者QCheckTableItem来填充。缺省情况下显示行号的垂直标题在表格的左部，而显示列标的水平标题在上部。（显示的数字从1开始，尽管在QTable内部行列都是由零开始计数。）

如果你想使用鼠标跟踪（mouse tracking），对视口（viewport）调用setMouseTracking(TRUE) （参见QScrollView）。

标题

QTable支持一个标题列，用来显示行号；以及一个标题行，用来显示列标。要设置行列标签（label），需要对由verticalHeader()和horizontalHeader()分别返回的指针使用QHeader::setLabel()。垂直标题显示在表格的左边内，宽度由setLeftMargin()设置。水平标题显示在表格的上边内，高度由setTopMargin()设置。表格的栅格可以通过setShowGrid()来开关。如果要隐藏水平标题，调用hide()，以及setTopMargin( 0 )，以使得标题所在的区域减为零尺寸。

标题标签是通过他们的区域编号（section number）来生成索引的。注意，QHeader关于区域编号的缺省行为为QTable而覆盖（overrided）了。参见下面在“行列”一节讨论行列移动时的相关解释。

行列

行列的尺寸由setRowHeight()和setColumnWidth()设置。如果要使得某行高到足以全部显示最高的表项（item），可以使用adjustRow()。类似地，adjustColumn()使某列宽至全部显示最宽的表项。使用setRowStretchable()和setColumnStretchable()，可以让行高、列宽在表格的高宽变化时自动调整。

行列的隐藏显示可以使用hideRow()、hideColumn()、showRow()和showColumn()。插入新的行列使用insertRows()和insertColumns()。如果你设置setNumRows()或者setNumCols()为比numRows()或者numCols()还要大，额外的行列会添加在下面（行）或者右边（列）。已有的行列可以使用removeRow()和removeColumn()来删除，多个行列则是removeRows()和removeColumns()。

使用rowMovingEnabled()和columnMovingEnabled()，行列可以设置为可移动的，也就是说，用户能够拖动放置他们。基于性能原因，QHeader区域编号的缺省行为被QTable重写。现在在QTable中，当一行或者一列被拖放，其区域编号也变为新的位置。这样，QHeader的区域（section）和索引就没有不同了。QTable中的QHeader类没有提供独立于用户界面次序的索引机制。

表格可以使用sortColumn()来排序。如果setSorting()设置为TRUE，用户可以点击列标题以对该列排序。行之间可以用swapRows()来交换；列则是swapColumns()；而单元格则是swapCells()。

对于可编辑的表格（参见setReadOnly()），可以使用setRowReadOnly()和setColumnReadOnly()来设置个别行列的只读属性。（单元格是可编辑还是只读取决于其设置和该单元格的QTableItem::EditType。）

焦点所在的行和列分别由currentRow()和currentColumn()返回。

尽管许多QTable函数以行列进行操作，indexOf()函数可以返回一个识别特定单元格的整数。

单元格

表格构造初始，QTable所有的单元格都是空的。

有两种方法来填充表格的单元格。首先也是最简单的方法是使用QTableItem或者QTableItem的子类。第二种方法对很大的稀疏表格有用，它不使用QTableItem，而是自己重新实现一些函数。我们下面按顺序看看这两种方法。

在单元格内放置一个字符串，使用setText()。这个函数将为还不存在的单元格生成一个新的QTableItem，然后显示里面的文本。缺省情况下表项的部件是QLineEdit。使用setPixmap()，单元格也可以放置一个象素映射，而且也在必要时生成表项。单元格可以同时包括象素映射和文本，象素映射显示在文本的左边。另一种方法是构造一个QTableItem或者QTableItem的子类，设置其属性，然后使用setItem()以插入到单元格中。

如果需要含有组合框的单元格，使用QComboTableItem类；类似地，含有多选框的单元格要用QCheckTableItem类。这些表项的样子和行为都类似组合框或者多选框，然而极少耗费内存。

        for ( int j = 0; j < numRows; ++j )
            table.setItem( j, 1, new QCheckTableItem( &table, "Check me" ) );
上面的例子中，我们生成了一列QCheckTableItem，用setItem()插入到表格中。

QTable拥有其QTableItem的所有权，在自己被销毁时也会删除他们。你可以使用takeItem()来获得一个表项的所有权，用它来在单元格之间移动单元格的内容，不论是不是属于同一个表格。（也参见swapCells()）。

QTableItem中的文本，与QComboTableItem和QCheckTableItem中的值一样，其内嵌编辑都是自动进行的。单元格可以是可编辑或者只读的，参见QTableItem::EditType。如果要精细地控制编辑，参见beginEdit()和endEdit()。

使用item()，可以把单元格的内容作为一个QTableItem取得；类似地，使用text()作为字符串取得，使用pixmap()作为象素映射取得（如果有的话）。单元格的范围矩形由cellGeometry()来给定。使用updateCell()来重绘单元格，例如在使用clearCell()删除单元格之后，清除其显示。可以使用ensureCellVisible()来迫使表格滚动至显示某个特定单元格的位置。isSelected()函数表明一个单元格是否被选中。

可以使用setCellWidget()来使你自己的部件代替单元格的部件，但是写QTableItem的子类可能更为简便。单元格的部件（如果有的话）可以使用clearCellWidget()来删去。

大表格

对于大稀疏表格，使用QTableItem或者其他部件的效率不高。解决的办法是：如应该表现的那样绘制单元格，在需求时生成和销毁单元格编辑器。

这种方法需要你重新实现几个函数。重写paintCell()以显示你的数据，createEditor()和setCellContentFromEditor()以方便内嵌编辑。重要的是，重写resizeData()为空，以防止QTable试图生成一个大数组。还需要重写item()、setItem()、clearCell()，和insertWidget()、cellWidget()和clearCellWidget()。几乎所有情况下（像排序、删除和插入行列等）你必须重写swapRows()、swapCells()和swapColumns()，包括标题操作。

如果你用一个QTableItem和QWidget的字典来表述活动的单元格，也就是说，只保存了对实际使用的单元格的引用，大部分函数可以用一行代码来实现。（参见table/bigtable/main.cpp的例子。）

更多单元格的信息参见QTableItem文档。

选中区域

QTable支持单一选中区域、多重选中区域（多个单元格）和无选中区域。选中模式由setSelectionMode()设置。使用isSelected()来判断一个特定的单元格是否被选中，而isRowSelected()和isColumnSelected()则是判断行、列。

QTable支持多重选中区域。你可以使用addSelection()来在编程中选择单元格。选中区域的个数由numSelections()给出。当前选中区域由currentSelection()返回。可以使用removeSelection()来删去一个选中区域，和clearSelection()来删去所有的选中区域。选中区域是QTableSelection对象。

信号

当用户点击一个单元格时，信号currentChanged()被发送。你也可以连接到低层次的信号clicked()、doubleClicked()和pressed()上。如果用户改变了选中区域，信号selectionChanged()被发送；类似地，单元格值改变将发送valueChanged()信号。如果右键单击（或者按下平台特定的键序列），信号contextMenuRequested()被发送。如果用户放置了一个拖动或者一个对象，信号dropped()与放置事件（drop event）一起被发送。

也参见高级部件。

成员类型文档

QTable::EditMode

  • QTable::NotEditing - 当前没有被编辑的单元格。
  • QTable::Editing - 当前有一个单元格被编辑。编辑器使用单元格的原内容为初始值。
  • QTable::Replacing - 当前有一个单元格被编辑。编辑器没有使用单元格的原内容为初始值。

QTable::FocusStyle

指明当前单元格（焦点所在）如何被绘制。

  • QTable::FollowStyle - 当前单元格按照当前的风格（style）被绘制，而且如果当前单元格在选中区域内，其背景也绘制为选中。
  • QTable::SpreadSheet - 当前单元格按照在电子表格里被绘制。这意味着，单元格由包围它的一个黑色矩形所指示出来，而且其背景也总是使用部件的底色——即使被选中。

QTable::SelectionMode

  • QTable::NoSelection - 用户不能选中单元格。
  • QTable::Single - 用户只能选中一个单一区域的单元格。
  • QTable::Multi - 用户可以选中多重区域的单元格。
  • QTable::SingleRow - 用户一次选中一行（总是当前表项所在的那一行）。
  • QTable::MultiRow - 用户可以选中多行。

成员函数文档

QTable::QTable ( QWidget * parent = 0, const char * name = 0 )

生成一个空表格对象，命名为name，作为parent的子部件。

如果使用QTableItem，在填充表格前要调用setNumRows()和setNumCols()以设置表格尺寸。

也参见QWidget::clearWFlags()和Qt::WidgetFlags。

QTable::QTable ( int numRows, int numCols, QWidget * parent = 0, const char * name = 0 )

构造空表格，命名为name，行数为numRows，列数为numCols，是parent的子部件。

如果使用QTableItem填充表格，可以生成QTableItem、QComboTableItem和QCheckTableItem表项并且使用setItem()插入到表格中。（使用QTableItem的另外一种方法可参见关于大表格的注意事项。）

也参见QWidget::clearWFlags()和Qt::WidgetFlags。

QTable::~QTable ()

解构器（Destructor）。删除QTable对象使用的所有资源，包括所有的QTableItem及其部件。

void QTable::activateNextCell () [virtual protected]

用来在内嵌编辑使用回车键完成后，激活下一个单元格。

缺省行为是由上到下，也就是说，移到当前编辑单元格的下方的单元格。如果需要不同的响应行为，例如由左至右，需要重写这个函数。

int QTable::addSelection ( const QTableSelection & s ) [virtual]

给表格增加一个由s所描述的选中区域，返回其个数，在选中区域非法时返回-1。

切记调用QTableSelection::init()和QTableSelection::expandTo()以使得选中区域合法（也参见QTableSelection::isActive()）。

也参见numSelections()、removeSelection()和clearSelection()。

void QTable::adjustColumn ( int col ) [virtual slot]

调整col列的大小，以使得列宽足以显示该列最宽的表项。

也参见adjustRow()。

已在QDataTable中重新实现。

void QTable::adjustRow ( int row ) [virtual slot]

调整row行的大小，以使得行高足以显示该行最高的表项。

也参见adjustColumn()。

QWidget * QTable::beginEdit ( int row, int col, bool replace ) [virtual protected]

用来启动在row、col的单元格的编辑器。通过生成一个编辑器（调用createEditor()）和使用setCellWidget()把单元格的编辑器设置为新生成的编辑器，实现编辑过程。（编辑完成后，调用endEdit()以把单元格内容替换为编辑器的结果。）如果replace为TRUE，编辑器会以单元格内容（如果有的话）为初始值，也就是说，用户来修改原来单元格的内容；否则，用户将输入新的数据。

也参见endEdit()。

QRect QTable::cellGeometry ( int row, int col ) const [virtual]

以内容坐标（content coordinates）返回在row、col的单元格的范围矩形（bounding rectangle）。

QRect QTable::cellRect ( int row, int col ) const [virtual]

返回在单元格坐标系统中row、col单元格的几何结构（geometry）。在paintCell()时使用方便。等价于QRect( QPoint(0,0)、cellGeometry( row, col)。size() );

也参见cellGeometry()。

例子：chart/setdataform.cpp。

QWidget * QTable::cellWidget ( int row, int col ) const [virtual]

返回在row、col的单元格中所设置的部件，如果未设置则返回0。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

也参见clearCellWidget()和setCellWidget()。

例子：chart/setdataform.cpp。

void QTable::clearCell ( int row, int col ) [virtual]

删去在row、col的QTableItem。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

void QTable::clearCellWidget ( int row, int col ) [virtual]

删去在row、col的单元格中所设置的部件（如果有的话）。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

本函数删去在row、col坐标的部件。注意：部件不是立即被删去，而是对部件调用QObject::deleteLater()以避免时序问题。

也参见cellWidget()和setCellWidget()。

void QTable::clearSelection ( bool repaint = TRUE ) [slot]

清除所有选中区域，如果repaint为TRUE则重绘适当的区域。

也参见removeSelection()。

void QTable::clicked ( int row, int col, int button, const QPoint & mousePos ) [signal]

当鼠标按键button被点击时，本信号被发送。事件发生所在的单元格在row、col，鼠标位置在mousePos结构里。

例子：chart/setdataform.cpp。

int QTable::columnAt ( int x ) const [virtual]

返回在位置x的列的序数。x必须以内容坐标的形式给出。

也参见columnPos()和rowAt()。

void QTable::columnClicked ( int col ) [virtual protected slot]

当列col被点击时调用。缺省的实现是如果sorting()为TRUE则对该列排序。

void QTable::columnIndexChanged ( int section, int fromIndex, int toIndex ) [virtual protected slot]

当列的顺序将被改变时调用，也就是说，当用户从fromIndex到toIndex移动列标题section的时候。

如果要编程上改变列的顺序，可以调用swapRows()或者swapColumns()。

也参见QHeader::indexChange()和rowIndexChanged()。

bool QTable::columnMovingEnabled () const

如果用户可以移动列，返回TRUE；否则返回FALSE。详情参见"columnMovingEnabled"属性。

int QTable::columnPos ( int col ) const [virtual]

以内容坐标的形式返回列col的x坐标。

也参见columnAt()和rowPos()。

int QTable::columnWidth ( int col ) const [virtual]

返回列col的宽度。

也参见setColumnWidth()和rowHeight()。

void QTable::columnWidthChanged ( int col ) [virtual protected slot]

无论何时列col的宽度改变，都应该调用本函数。它更新受影响的各个列的几何特性，重绘表格以反映所做的改变。

void QTable::contentsDragEnterEvent ( QDragEnterEvent * e ) [virtual protected]

本事件处理者（event handler）当QTable对象接收到一个QDragEnterEvent e时调用，也就是说，当用户按下鼠标按键以拖拉什么东西的时候。

焦点移到QDragEnterEvent所发生的单元格处。

由QScrollView处重新实现。

void QTable::contentsDragLeaveEvent ( QDragLeaveEvent * e ) [virtual protected]

本事件处理者当一个拖拉动作伴随事件e离开这个QTable对象时调用。

由QScrollView处重新实现。

void QTable::contentsDragMoveEvent ( QDragMoveEvent * e ) [virtual protected]

本事件处理者当QTable对象接收到一个QDragMoveEvent e时调用，也就是说，当用户确实拖拽了鼠标的时候。

焦点移到QDragMoveEvent所发生的单元格处。

由QScrollView处重新实现。

void QTable::contentsDropEvent ( QDropEvent * e ) [virtual protected]

本事件处理者当用户以在这个QTable上放置什么东西来结束一次拖放，并从而触发了这个放置事件e的时候调用。

由QScrollView处重新实现。

void QTable::contextMenuRequested ( int row, int col, const QPoint & pos ) [signal]

当用户用鼠标右键（或者一个系统特定键盘键）调用上下文菜单（context menu）时，本信号被发送。事件发生的单元格在row、col处。pos是上下文菜单在全局坐标系统中的出现位置。

QWidget * QTable::createEditor ( int row, int col, bool initFromCell ) const [virtual protected]

返回一个部件，可以用作在row、col处的单元格的内容编辑器。

若initFromCell为TRUE，该编辑器用于编辑此单元格的当前内容（这样编辑器部件就应该使用该内容作为初始值）。若initFromCell为FALSE，单元格的内容被用户在本函数生成的部件中新输入的内容所替代。

缺省的功能描述如下：如果initFromCell为TRUE，或者单元格包含一个QTableItem并且该表项的QTableItem::isReplaceable()为FALSE，那么该单元格被要求生成一个适当的编辑器（使用QTableItem::createEditor()）。否则QLineEdit被用作编辑器。

如果要为单元格创建你自己的编辑器，需要实现定制的QTableItem子类和重写QTableItem::createEditor()。

如果不使用QTableItem，而且不想使用QLineEdit作为缺省的编辑器，需要写QTable的子类和用类似下面的代码重写本函数：

    QTableItem *i = item( row, col );
    if ( initFromCell || ( i && !i->isReplaceable() ) )
        // If we had a QTableItem ask the base class to create the editor
        return QTable::createEditor( row, col, initFromCell );
    else
        return ...(create your editor)
编辑器部件的所有权被传递给调用者。

如果重写了本函数，对于只读的单元格要返回0。你将需要重写setCellContentFromEditor()以得到用户的输入数据。

也参见QTableItem::createEditor()。

int QTable::currEditCol () const [protected]

返回当前被编辑的列。

int QTable::currEditRow () const [protected]

返回当前被编辑的行。

void QTable::currentChanged ( int row, int col ) [signal]

当当前单元格已变为row、col时，本信号被发送。

例子：chart/setdataform.cpp。

int QTable::currentColumn () const

返回当前列。

也参见currentRow()。

例子：chart/setdataform.cpp。

int QTable::currentRow () const

返回当前行。

也参见currentColumn()。

例子：chart/setdataform.cpp。

int QTable::currentSelection () const [virtual]

返回当前选中区域的个数，如果没有则返回-1。

也参见numSelections()。

void QTable::doubleClicked ( int row, int col, int button, const QPoint & mousePos ) [signal]

当鼠标按键button被双击时，本信号被发送。事件发生所在的单元格在row、col，鼠标位置在mousePos结构里。

bool QTable::dragEnabled () const [slot]

如果本函数返回TRUE，则表格支持拖拽。

也参见setDragEnabled()。

QDragObject * QTable::dragObject () [virtual protected]

如果用户对一个选中的单元格按下鼠标键，开始移动（也就是拖拽），并且dragEnabled()为TRUE，本函数被调用，以得到一个拖拽对象。一次使用该对象的拖拽立即开始，除非dragObject()返回0。

缺省情况下本函数返回0。你可以重新实现它，依所选表项来生成一个QDragObject。

也参见dropped()。

void QTable::drawContents ( QPainter * p, int cx, int cy, int cw, int ch ) [virtual protected]

在画具（painter）p上绘制表格内容。本函数已优化，从而只绘制在位置cx、cy的，宽cw象素，高ch象素的裁减矩形内的单元格。

另外，drawContents()高亮显示当前单元格。

由QScrollView处重新实现。

void QTable::dropped ( QDropEvent * e ) [signal]

当表格上发生一次放置事件时，本信号被发送。

e包含了放置事件的信息。

void QTable::editCell ( int row, int col, bool replace = FALSE ) [virtual slot]

开始编辑在row、col处的单元格。

如果replace为TRUE，编辑结束时单元格的内容将被编辑器的内容替代，也就是说，用户将输入新的数据；否则，单元格的当前内容（如果有的话）将在编辑器里被修改。

也参见beginEdit()。

EditMode QTable::editMode () const [protected]

返回当前编辑模式。

void QTable::endEdit ( int row, int col, bool accept, bool replace ) [virtual protected]

当在row、col处的单元格的内嵌编辑被要求停止时，本函数被调用。

如果该单元格未被编辑，或者accept为FALSE，函数返回，单元格的内容保持不变。

如果accept为TRUE，编辑器的内容一定要传递给响应的单元格。如果replace为TRUE，该单元格的内容应该被编辑器的内容替代（这意味着删去该单元格的QTableItem而新建一个）；否则（如果可能的话）， 编辑器的内容应该只放到该单元格已经存在的QTableItem中。

如果该单元格的内容应该被替换，或者没有QTableItem，那么setCellContentFromEditor()被调用。否则，对于该单元格的QTableItem，QTableItem::setContentFromEditor()被调用。

最后，clearCellWidget()被调用，以删去编辑器部件。

也参见setCellContentFromEditor()和beginEdit()。

void QTable::ensureCellVisible ( int row, int col )

滚动表格，使得在row、col处的单元格可见。

FocusStyle QTable::focusStyle () const

返回当前（焦点）单元格如何被绘制。详情参见"focusStyle"属性。

void QTable::hideColumn ( int col ) [virtual slot]

隐藏列col。

也参见showColumn()和hideRow()。

void QTable::hideRow ( int row ) [virtual slot]

隐藏行row。

也参见showRow()和hideColumn()。

QHeader * QTable::horizontalHeader () const

返回表格的顶部QHeader。

该标题包含列标。

要修改列标，使用QHeader::setLabel()，例如，

        horizontalHeader()->setLabel( 0, tr( "File" ) );

也参见verticalHeader()、setTopMargin()和QHeader。

例子：chart/setdataform.cpp和table/small-table-demo/main.cpp。

int QTable::indexOf ( int row, int col ) const [protected]

返回单一整数，它通过把二维的表格映射为一维数组来标识详细的row和col。

这很有用，例如如果你要使用QIntDict，以把整数映射到稀疏表格中的使用的单元格上。

void QTable::insertColumns ( int col, int count = 1 ) [virtual slot]

在列col处插入count个空列。

也参见insertRows()和removeColumn()。

void QTable::insertRows ( int row, int count = 1 ) [virtual slot]

在行row处插入count个空行。

也参见insertColumns()和removeRow()。

void QTable::insertWidget ( int row, int col, QWidget * w ) [virtual protected]

在内部数据结构里，在row、col处插入部件w。详情参见setCellWidget()的文档。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

bool QTable::isColumnReadOnly ( int col ) const

返回列col是否只读。

该列的某个单元格是可编辑还是只读，取决于该单元格的EditType和这个设置：参见QTableItem::EditType。

也参见setColumnReadOnly()和isRowReadOnly()。

bool QTable::isColumnSelected ( int col, bool full = FALSE ) const

如果列col被选中，返回TRUE；否则返回FALSE。

如果full为FALSE（缺省的情况），“列被选中”意味着该列的至少一个单元格被选中；如果full为TRUE，“列被选中”则意味着该列所有的单元格都被选中。

也参见isRowSelected()和isSelected()。

bool QTable::isColumnStretchable ( int col ) const [slot]

如果列col可伸缩，返回TRUE；否则返回FALSE。

也参见setColumnStretchable()和isRowStretchable()。

bool QTable::isEditing () const [protected]

如果EditMode为Editing或者Replacing，返回TRUE。如果EditMode为NotEditing返回FALSE。

也参见QTable::EditMode。

bool QTable::isReadOnly () const

如果表格只读，返回TRUE；否则返回FALSE。详情参见"readOnly"属性。

bool QTable::isRowReadOnly ( int row ) const

返回行row是否只读。

该行的某个单元格是可编辑还是只读，取决于该单元格的EditType和这个设置：参见QTableItem::EditType。

也参见setRowReadOnly()和isColumnReadOnly()。

bool QTable::isRowSelected ( int row, bool full = FALSE ) const

如果行row被选中，返回TRUE；否则返回FALSE。

如果full为FALSE（缺省的情况），“行被选中”意味着该行的至少一个单元格被选中；如果full为TRUE，“行被选中”则意味着该行所有的单元格都被选中。

也参见isColumnSelected()和isSelected()。

bool QTable::isRowStretchable ( int row ) const [slot]

如果行row可伸缩，返回TRUE；否则返回FALSE。

也参见setRowStretchable()和isColumnStretchable()。

bool QTable::isSelected ( int row, int col ) const

如果row、col处的单元格被选中，返回TRUE；否则返回FALSE。

也参见isRowSelected()和isColumnSelected()。

QTableItem * QTable::item ( int row, int col ) const [virtual]

返回QTableItem，它代表着在row、col处的单元格的内容。

如果row或者col超出范围，或者该单元格没有设置内容，item()返回0。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

也参见setItem()。

int QTable::numCols () const [virtual]

返回表格中的列数。详情参见"numCols"属性。

在QDataTable处被重新实现。

int QTable::numRows () const [virtual]

返回表格中的行数。详情参见"numRows"属性。

在QDataTable处被重新实现。

int QTable::numSelections () const

返回当前选中区域的数目。

也参见currentSelection()。

void QTable::paintCell ( QPainter * p, int row, int col, const QRect & cr, bool selected, const QColorGroup & cg ) [virtual]

在画具p上绘制在row、col处的单元格。该画具已经被转变为单元格原有的。cr描述了在内容坐标系统中单元格的坐标。

如果selected为TRUE，单元格将高亮显示。

cg是应用来绘制该单元格内容的颜色组。

如果你想绘制定制的单元格内容，例如右对齐的文本，你必须要么重写paintCell()，要么写QTableItem的子类并且重写QTableItem::paint()以完成定制绘制。

如果你想使用QTableItem的子类，例如用来保存数据结构，那么重写QTableItem::paint()也许最合适。对于你要立即绘制的数据，例如从数据库中得到的数据，则可能最好是重写paintCell()。注意，如果你重写paintCell()，也就是说不使用QTableItems，你就必须重写其他一些函数：参见关于大表格的注意事项。

注意，缺省情况下为提高效率，画具并没有裁剪。如果你需要裁剪，使用如下代码：

    p->setClipRect( cellRect(row, col), QPainter::CoordPainter );
    //... your drawing code
    p->setClipping( FALSE );

void QTable::paintCell ( QPainter * p, int row, int col, const QRect & cr, bool selected ) [virtual]

这是一个重载的成员函数，为便利而提供。其行为本质上类似上一个函数。

使用另外的那个paintCell()函数。本函数只是为了反向兼容性。

void QTable::paintEmptyArea ( QPainter * p, int cx, int cy, int cw, int ch ) [virtual protected]

本函数以画具p的背景色，填充从cx、cy位置开始的，宽cw象素，高ch象素的矩形。

paintEmptyArea()被drawContents()调用，以擦除或者填充未用区域。

void QTable::paintFocus ( QPainter * p, const QRect & cr ) [virtual]

绘制当前单元格的焦点矩形（参见currentRow()、currentColumn()）。

画具p已经被转变为单元格原有的，cr则指定了以内容坐标形式的单元格几何特性。

QPixmap QTable::pixmap ( int row, int col ) const [virtual]

返回为在row、col处的单元格设置的象素映射，如果该单元格不含象素映射，返回无效象素映射（null-pixmap）。

也参见setPixmap()。

例子：chart/setdataform.cpp。

void QTable::pressed ( int row, int col, int button, const QPoint & mousePos ) [signal]

当鼠标按键button被按下时，本信号被发送。事件发生所在的单元格在row、col，鼠标位置在mousePos结构里。

void QTable::removeColumn ( int col ) [virtual slot]

删去列col，并且删除其所有单元格，包括单元格中可能有的任何表项和部件。

也参见removeColumns()、hideColumn()、insertColumns()和removeRow()。

void QTable::removeColumns ( const QMemArray<int> & cols ) [virtual slot]

删去数组cols中的列，并且删除其所有单元格，包括单元格中可能有的任何表项和部件。

传入的数组必须只包含合法的列（在0到numCols() - 1的范围内），没有重复，按升序排列。

也参见removeColumn()、insertColumns()和removeRows()。

void QTable::removeRow ( int row ) [virtual slot]

删去行row，并且删除其所有单元格，包括单元格中可能有的任何表项和部件。

也参见hideRow()、insertRows()、removeColumn()和removeRows()。

void QTable::removeRows ( const QMemArray<int> & rows ) [virtual slot]

删去数组rows中的行，并且删除其所有单元格，包括单元格中可能有的任何表项和部件。

传入的数组必须只包含合法的行（在0到numRows() - 1的范围内），没有重复，按升序排列。

也参见removeRow()、insertRows()和removeColumns()。

void QTable::removeSelection ( const QTableSelection & s ) [virtual]

如果表格中有选中区域s，该选中区域从表格中被删去。

也参见addSelection()和numSelections()。

void QTable::removeSelection ( int num ) [virtual]

这是一个重载的成员函数，为便利而提供。其行为本质上类似上一个函数。

从表格中删去编号为num的选中区域。

也参见numSelections()、addSelection()和clearSelection()。

void QTable::repaintSelections ()

重绘所有的选中区域。

void QTable::resizeData ( int len ) [virtual protected]

当QTable的内部数组需要调整大小至len个元素时被调用。

如果不使用QTableItem，需要重写本函数为空方法以免浪费内存。更多详情参见关于大表格的注意事项。

int QTable::rowAt ( int y ) const [virtual]

返回在位置y的行的序数。y必须以内容坐标的形式给出。

也参见rowPos()和columnAt()。

int QTable::rowHeight ( int row ) const [virtual]

返回行row的高度。

也参见setRowHeight()和columnWidth()。

例子：table/small-table-demo/main.cpp。

void QTable::rowHeightChanged ( int row ) [virtual protected slot]

无论何时行row的宽度改变，都应该调用本函数。它更新受影响的各个行的几何特性，重绘表格以反映所做的改变。

void QTable::rowIndexChanged ( int section, int fromIndex, int toIndex ) [virtual protected slot]

当行的顺序将被改变时调用，也就是说，当用户从fromIndex到toIndex移动行标题section的时候。

如果要编程上改变行的顺序，可以调用swapRows()或者swapColumns()。

也参见QHeader::indexChange()和columnIndexChanged()。

bool QTable::rowMovingEnabled () const

如果用户可以移动行，返回TRUE；否则返回FALSE。详情参见"rowMovingEnabled"属性。

int QTable::rowPos ( int row ) const [virtual]

以内容坐标的形式返回行row的y坐标。

也参见rowAt()和columnPos()。

QTableSelection QTable::selection ( int num ) const

返回编号为num的选中区域，或者一个空QTableSelection，如果num超出范围的话（参见QTableSelection::isNull()）。

void QTable::selectionChanged () [signal]

无论何时选中区域改变，本信号被发送。

也参见QTableSelection。

SelectionMode QTable::selectionMode () const

返回当前选中模式。详情参见"selectionMode"属性。

void QTable::setCellContentFromEditor ( int row, int col ) [virtual protected]

用来以在row、col处的单元格的编辑器的内容，替换该单元格内容。如果该单元格已经有一个QTableItem，则先被删去（参见clearCell()）。

例如如果你想依编辑器的内容来生成不同的QTableItem，就需要重写本函数。

如果不需要QTableItem，你就需要重写本函数，以把用户输入数据保存到你的数据结构中。（参见关于大表格的注意事项。）

也参见QTableItem::setContentFromEditor()和createEditor()。

void QTable::setCellWidget ( int row, int col, QWidget * e ) [virtual]

把部件e放置到在row、col处的单元格中，并且在单元格几何特性改变时负责定位和调整大小。

缺省情况下，部件被插入到numRows()×numCols()个元素的向量中。对于很大的表格，你很可能会要把部件存储到消耗更少内存的数据结构中。（参见关于大表格的注意事项）。为了支持使用你自己的数据结构，本函数调用insertWidget()以增加部件到内部数据结构。要使用你自己的数据结构，需要重写insertWidget()、cellWidget()和clearCellWidget()。

单元格的部件是使用“new”操作符动态生成的，一旦表格被销毁，也自动被销毁。当使用setCellWidget()时，表格拥有部件的所有权。

例子：chart/setdataform.cpp。

void QTable::setColumnMovingEnabled ( bool b ) [virtual slot]

设置用户是否可以移动列为b。详情参见"columnMovingEnabled"属性。

void QTable::setColumnReadOnly ( int col, bool ro ) [virtual slot]

如果ro为TRUE，列col被设置为只读；否则被设置为可编辑。

该列的某个单元格是可编辑还是只读，取决于该单元格的EditType和这个设置：参见QTableItem::EditType。

也参见isColumnReadOnly()、setRowReadOnly()和readOnly。

例子：chart/setdataform.cpp。

void QTable::setColumnStretchable ( int col, bool stretch ) [virtual slot]

如果stretch为TRUE，列col被设置为可伸缩；否则被设置为不可伸缩。

如果表格部件的宽度减少或者增加，可伸缩的列将尽可能适合空间地变窄或者变宽。用户不能手动调整可伸缩的列的大小。

也参见isColumnStretchable()、setRowStretchable()和adjustColumn()。

void QTable::setColumnWidth ( int col, int w ) [virtual slot]

调整列col为w象素宽。

也参见columnWidth()和setRowHeight()。

例子：chart/setdataform.cpp。

Reimplemented in QDataTable。

void QTable::setCurrentCell ( int row, int col ) [virtual slot]

把焦点移到在row、col的单元格上。

也参见currentRow()和currentColumn()。

void QTable::setDragEnabled ( bool b ) [virtual slot]

如果b为TRUE，当用户对选中的单元格按下且移动鼠标时，表格开始一个拖拽事件（参见dragObject()）。

void QTable::setEditMode ( EditMode mode, int row, int col ) [protected]

设置当前的编辑模式为mode，当前编辑行为row，当前编辑列为col。

也参见EditMode。

void QTable::setFocusStyle ( FocusStyle fs ) [virtual]

设置当前（焦点）单元格如何绘制为fs。详情参见"focusStyle"属性。

void QTable::setItem ( int row, int col, QTableItem * item ) [virtual]

把表项item插入到表格的行row、列column col，且重绘该单元格。如果该单元格已存在一个表项，删除且用item替换之。表格拥有表项的所有权。

如果不使用QTableItem，需要重写本函数：参见关于大表格的注意事项。

也参见item()和takeItem()。

例子：table/small-table-demo/main.cpp。

void QTable::setLeftMargin ( int m ) [virtual slot]

设置左边界为m象素宽。

显示行号的verticalHeader()占据这个边界位置。

在阿拉伯（arabic）或者希伯莱（hebrew）localization中，verticalHeader()出现在表格的右边，本函数将设置右边界。

也参见leftMargin()、setTopMargin()和verticalHeader()。

void QTable::setNumCols ( int r ) [virtual slot]

设置表格中列数为r。详情参见"numCols"属性。

void QTable::setNumRows ( int r ) [virtual slot]

设置表格中行数为r。详情参见"numRows"属性。

void QTable::setPixmap ( int row, int col, const QPixmap & pix ) [virtual]

设置在row、col处的单元格中的象素映射为pix。

如果单元格中没有表项，则生成一个EditType为OnTyping的QTableItem；否则，已存在的表项的象素映射（如果有的话）被pix所替代。

注意：QComboTableItem和QCheckTableItem不显示象素映射。

也参见pixmap()、setText()、setItem()和QTableItem::setPixmap()。

例子：chart/setdataform.cpp和table/small-table-demo/main.cpp。

void QTable::setReadOnly ( bool b ) [virtual slot]

设置表格是否只读为b。详情参见"readOnly"属性。

void QTable::setRowHeight ( int row, int h ) [virtual slot]

调整行row为h象素高。

也参见rowHeight()和setColumnWidth()。

void QTable::setRowMovingEnabled ( bool b ) [virtual slot]

设置用户是否可以移动行为b。详情参见"rowMovingEnabled"属性。

void QTable::setRowReadOnly ( int row, bool ro ) [virtual slot]

如果ro为TRUE，行row被设置为只读；否则被设置为可编辑。

该行的某个单元格是可编辑还是只读，取决于该单元格的EditType和这个设置：参见QTableItem::EditType。

也参见isRowReadOnly()、setColumnReadOnly()和readOnly。

void QTable::setRowStretchable ( int row, bool stretch ) [virtual slot]

如果stretch为TRUE，行row被设置为可伸缩；否则被设置为不可伸缩。

如果表格部件的高度减少或者增加，可伸缩的行将尽可能适合空间地变矮或者变高。用户不能手动调整可伸缩的行的大小。

也参见isRowStretchable()和setColumnStretchable()。

void QTable::setSelectionMode ( SelectionMode mode ) [virtual]

设置当前选中模式为mode。详情参见"selectionMode"属性。

void QTable::setShowGrid ( bool b ) [virtual slot]

设置表格的栅格是否显示为b。详情参见"showGrid"属性。

void QTable::setSorting ( bool b ) [virtual slot]

设置点击列标题是否对该列排序为b。详情参见"sorting"属性。

void QTable::setText ( int row, int col, const QString & text ) [virtual]

设置在row、col处的单元格的文本为text。

如果单元格中没有表项，则生成一个EditType为OnTyping的QTableItem；否则，已存在的表项的文本（如果有的话）被text所替代。

也参见text()、setPixmap()、setItem()和QTableItem::setText()。

例子：chart/setdataform.cpp和table/small-table-demo/main.cpp。

void QTable::setTopMargin ( int m ) [virtual slot]

设置顶部边界为m象素高。

显示列标的horizontalHeader()占据这个边界位置。

也参见topMargin()和setLeftMargin()。

void QTable::showColumn ( int col ) [virtual slot]

显示列col。

也参见hideColumn()和showRow()。

bool QTable::showGrid () const

如果表格的栅格可见，返回TRUE；否则返回FALSE。详情参见"showGrid"属性。

void QTable::showRow ( int row ) [virtual slot]

显示行row。

也参见hideRow()和showColumn()。

void QTable::sortColumn ( int col, bool ascending = TRUE, bool wholeRows = FALSE ) [virtual]

对列col排序。如果ascending为TRUE，按升序；否则按降序。

如果wholeRows为TRUE，用swapRows()对全部行排序；否则，只用swapCells()对该列的单元格排序。

注意：如果不使用QTableItem，需要重写swapRows()和swapCells()。（参见关于大表格的注意事项。）

也参见swapRows()。

例子：table/statistics/statistics.cpp。

在QDataTable处被重新实现。

bool QTable::sorting () const

如果点击列标题则对该列排序，返回TRUE；否则返回FALSE。详情参见"sorting"属性。

void QTable::startDrag () [virtual protected]

开始一次拖拽。

通常你不必调用或者重新本函数。

也参见dragObject()。

void QTable::swapCells ( int row1, int col1, int row2, int col2 ) [virtual slot]

交换在row1、col1处的单元格和在row2、col2处的单元格的内容。

当对表格排序时，本函数也被调用。

如果不使用QTableItem，同时也想使用户可以交换单元格，那么你需要重写本函数。（参见关于大表格的注意事项。）

也参见swapColumns()和swapRows()。

void QTable::swapColumns ( int col1, int col2, bool swapHeader = FALSE ) [virtual slot]

交换列col1与列col2。

本函数用于交换两列的位置。当用户改变列顺序（参见setColumnMovingEnabled()）和对列排序的时候被调用。

如果不使用QTableItem，同时也想使用户可以交换列，那么你需要重写本函数。（参见关于大表格的注意事项。）

如果swapHeader为TRUE，列标题的内容也要交换。

也参见swapCells()。

void QTable::swapRows ( int row1, int row2, bool swapHeader = FALSE ) [virtual slot]

交换行row1与行row2的数据。

本函数用于交换两行的位置。当用户改变行顺序（参见setRowMovingEnabled()）和对行排序的时候被调用。

如果不使用QTableItem，同时也想使用户可以交换行，那么你需要重写本函数。（参见关于大表格的注意事项。）

如果swapHeader为TRUE，行标题的内容也要交换。

也参见swapColumns()和swapCells()。

void QTable::takeItem ( QTableItem * i ) [virtual]

把表项i拿出表格。本函数并不删除该表项。你必须要么自己删除该表项，要么把它插入一个表格里（使用setItem()），让这个表格拥有它的所有权。

使用本函数，你可以在一个表格内把表项从一个单元格移到另一个，或者在表格之间移动表项。用setItem()再插入该表项。

如果要交换两个单元格，使用swapCells()。

QString QTable::text ( int row, int col ) const [virtual]

返回在row、col处的单元格中的文本，或者空字符串，如果相应的表项不存在或者没有文本。

也参见setText()和setPixmap()。

例子：chart/setdataform.cpp。

在QDataTable处被重新实现。

void QTable::updateCell ( int row, int col )

重绘在row、col处的单元格。

void QTable::valueChanged ( int row, int col ) [signal]

当用户改变在row、col处的单元格的值时，本信号被发送。

例子：chart/setdataform.cpp。

QHeader * QTable::verticalHeader () const

返回表格的左QHeader。

该标题含有行号。

也参见horizontalHeader()、setLeftMargin()和QHeader。

属性文档

bool columnMovingEnabled

本属性决定用户是否可以移动列。

缺省为FALSE。

也参见rowMovingEnabled。

用setColumnMovingEnabled()设置本属性值，用columnMovingEnabled()得到本属性值。

FocusStyle focusStyle

本属性决定当前（焦点）单元格如何绘制。

缺省风格为SpreadSheet。

也参见QTable::FocusStyle。

用setFocusStyle()设置本属性值，用focusStyle()得到本属性值。

int numCols

本属性决定表格中列的数目。

用setNumCols()设置本属性值，用numCols()得到本属性值。

也参见numRows。

int numRows

本属性决定表格中行的数目。

用setNumRows()设置本属性值，用numRows()得到本属性值。

也参见numCols。

bool readOnly

本属性决定表格是否是只读的。

表格的某个单元格是可编辑还是只读，取决于该单元格的EditType和这个设置：参见QTableItem::EditType。

也参见QWidget::enabled、setColumnReadOnly()和setRowReadOnly()。

用setReadOnly()设置本属性值，用isReadOnly()得到本属性值。

bool rowMovingEnabled

本属性决定用户是否可以移动行。

缺省为FALSE。

也参见columnMovingEnabled。

用setRowMovingEnabled()设置本属性值，用rowMovingEnabled()得到本属性值。

SelectionMode selectionMode

本属性决定当前选中模式。

缺省模式为Multi，即允许用户选中多重区域的单元格。

也参见SelectionMode和selectionMode。

用setSelectionMode()设置本属性值，用selectionMode()得到本属性值。

bool showGrid

本属性决定表格栅格是否显示。

缺省为显示栅格。

用setShowGrid()设置本属性值，用showGrid()得到本属性值。

bool sorting

本属性决定点击列标题是否对该列排序。

用setSorting()设置本属性值，用sorting()得到本属性值。

也参见sortColumn()。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


qtable.h包含文件

qtable.h

这里是qtable.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
**
** Definition of QTable widget class
**
** Created : 000607
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the table module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTABLE_H
#define QTABLE_H

#ifndef QT_H
#include <qscrollview.h>
#include <qpixmap.h>
#include <qptrvector.h>
#include <qheader.h>
#include <qmemarray.h>
#include <qptrlist.h>
#include <qguardedptr.h>
#include <qshared.h>
#include <qintdict.h>
#include <qstringlist.h>
#endif // QT_H

#ifndef QT_NO_TABLE

class QTableHeader;
class QValidator;
class QTable;
class QPaintEvent;
class QTimer;
class QResizeEvent;
class QComboBox;
class QCheckBox;
class QDragObject;

struct QTablePrivate;
struct QTableHeaderPrivate;

class Q_EXPORT QTableSelection
{
public:
    QTableSelection();
    void init( int row, int col );
    void expandTo( int row, int col );
    bool operator==( const QTableSelection &s ) const;
    bool operator!=( const QTableSelection &s ) const { return !(operator==(s)); }

    int topRow() const { return tRow; }
    int bottomRow() const { return bRow; }
    int leftCol() const { return lCol; }
    int rightCol() const { return rCol; }
    int anchorRow() const { return aRow; }
    int anchorCol() const { return aCol; }

    bool isActive() const { return active; }

private:
    uint active : 1;
    uint inited : 1;
    int tRow, lCol, bRow, rCol;
    int aRow, aCol;
};

class Q_EXPORT QTableItem : public Qt
{
    friend class QTable;

public:
    enum EditType { Never, OnTyping, WhenCurrent, Always };

    QTableItem( QTable *table, EditType et, const QString &text );
    QTableItem( QTable *table, EditType et, const QString &text,
                const QPixmap &p );
    virtual ~QTableItem();

    virtual QPixmap pixmap() const;
    virtual QString text() const;
    virtual void setPixmap( const QPixmap &p );
    virtual void setText( const QString &t );
    QTable *table() const { return t; }

    virtual int alignment() const;
    virtual void setWordWrap( bool b );
    bool wordWrap() const;

    EditType editType() const;
    virtual QWidget *createEditor() const;
    virtual void setContentFromEditor( QWidget *w );
    virtual void setReplaceable( bool );
    bool isReplaceable() const;

    virtual QString key() const;
    virtual QSize sizeHint() const;

    virtual void setSpan( int rs, int cs );
    int rowSpan() const;
    int colSpan() const;

    virtual void setRow( int r );
    virtual void setCol( int c );
    int row() const;
    int col() const;

    virtual void paint( QPainter *p, const QColorGroup &cg,
                        const QRect &cr, bool selected );

    void updateEditor( int oldRow, int oldCol );

    virtual void setEnabled( bool b );
    bool isEnabled() const;

    virtual int rtti() const;
    static int RTTI;

private:
    QString txt;
    QPixmap pix;
    QTable *t;
    EditType edType;
    uint wordwrap : 1;
    uint tcha : 1;
    uint enabled : 1;
    int rw, cl;
    int rowspan, colspan;

};

class Q_EXPORT QComboTableItem : public QTableItem
{
public:
    QComboTableItem( QTable *table, const QStringList &list, bool editable = FALSE );
    virtual QWidget *createEditor() const;
    virtual void setContentFromEditor( QWidget *w );
    virtual void paint( QPainter *p, const QColorGroup &cg,
                        const QRect &cr, bool selected );
    virtual void setCurrentItem( int i );
    virtual void setCurrentItem( const QString &i );
    int currentItem() const;
    QString currentText() const;
    int count() const;
    QString text( int i ) const;
    virtual void setEditable( bool b );
    bool isEditable() const;
    virtual void setStringList( const QStringList &l );

    int rtti() const;
    static int RTTI;

private:
    QComboBox *cb;
    QStringList entries;
    int current;
    bool edit;
    static QComboBox *fakeCombo;

};

class Q_EXPORT QCheckTableItem : public QTableItem
{
public:
    QCheckTableItem( QTable *table, const QString &txt );
    virtual QWidget *createEditor() const;
    virtual void setContentFromEditor( QWidget *w );
    virtual void paint( QPainter *p, const QColorGroup &cg,
                        const QRect &cr, bool selected );
    virtual void setChecked( bool b );
    bool isChecked() const;

    int rtti() const;
    static int RTTI;

private:
    QCheckBox *cb;
    bool checked;

};

#if defined(Q_TEMPLATEDLL)
// MOC_SKIP_BEGIN
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrVector<QTableItem>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrVector<QWidget>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QPtrList<QTableSelection>;
Q_TEMPLATE_EXTERN template class Q_EXPORT QIntDict<int>;
// MOC_SKIP_END
#endif

class Q_EXPORT QTable : public QScrollView
{
    Q_OBJECT
    Q_ENUMS( SelectionMode FocusStyle )
    Q_PROPERTY( int numRows READ numRows WRITE setNumRows )
    Q_PROPERTY( int numCols READ numCols WRITE setNumCols )
    Q_PROPERTY( bool showGrid READ showGrid WRITE setShowGrid )
    Q_PROPERTY( bool rowMovingEnabled READ rowMovingEnabled WRITE setRowMovingEnabled )
    Q_PROPERTY( bool columnMovingEnabled READ columnMovingEnabled WRITE setColumnMovingEnabled )
    Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly )
    Q_PROPERTY( bool sorting READ sorting WRITE setSorting )
    Q_PROPERTY( SelectionMode selectionMode READ selectionMode WRITE setSelectionMode )
    Q_PROPERTY( FocusStyle focusStyle READ focusStyle WRITE setFocusStyle )

    friend class QTableHeader;
    friend class QComboTableItem;
    friend class QCheckTableItem;
    friend class QTableItem;

public:
    QTable( QWidget* parent=0, const char* name=0 );
    QTable( int numRows, int numCols,
            QWidget* parent=0, const char* name=0 );
    ~QTable();

    QHeader *horizontalHeader() const;
    QHeader *verticalHeader() const;

    enum SelectionMode { Single, Multi, SingleRow, MultiRow, NoSelection };
    virtual void setSelectionMode( SelectionMode mode );
    SelectionMode selectionMode() const;

    virtual void setItem( int row, int col, QTableItem *item );
    virtual void setText( int row, int col, const QString &text );
    virtual void setPixmap( int row, int col, const QPixmap &pix );
    virtual QTableItem *item( int row, int col ) const;
    virtual QString text( int row, int col ) const;
    virtual QPixmap pixmap( int row, int col ) const;
    virtual void clearCell( int row, int col );

    virtual QRect cellGeometry( int row, int col ) const;
    virtual int columnWidth( int col ) const;
    virtual int rowHeight( int row ) const;
    virtual int columnPos( int col ) const;
    virtual int rowPos( int row ) const;
    virtual int columnAt( int x ) const;
    virtual int rowAt( int y ) const;

    virtual int numRows() const;
    virtual int numCols() const;

    void updateCell( int row, int col );

    bool eventFilter( QObject * o, QEvent * );

    int currentRow() const { return curRow; }
    int currentColumn() const { return curCol; }
    void ensureCellVisible( int row, int col );

    bool isSelected( int row, int col ) const;
    bool isRowSelected( int row, bool full = FALSE ) const;
    bool isColumnSelected( int col, bool full = FALSE ) const;
    int numSelections() const;
    QTableSelection selection( int num ) const;
    virtual int addSelection( const QTableSelection &s );
    virtual void removeSelection( const QTableSelection &s );
    virtual void removeSelection( int num );
    virtual int currentSelection() const;

    bool showGrid() const;

    bool columnMovingEnabled() const;
    bool rowMovingEnabled() const;

    virtual void sortColumn( int col, bool ascending = TRUE,
                             bool wholeRows = FALSE );
    bool sorting() const;

    virtual void takeItem( QTableItem *i );

    virtual void setCellWidget( int row, int col, QWidget *e );
    virtual QWidget *cellWidget( int row, int col ) const;
    virtual void clearCellWidget( int row, int col );

    virtual QRect cellRect( int row, int col ) const;

    virtual void paintCell( QPainter *p, int row, int col,
                            const QRect &cr, bool selected );
    virtual void paintCell( QPainter *p, int row, int col,
                            const QRect &cr, bool selected, const QColorGroup &cg );
    virtual void paintFocus( QPainter *p, const QRect &r );
    QSize sizeHint() const;

    bool isReadOnly() const;
    bool isRowReadOnly( int row ) const;
    bool isColumnReadOnly( int col ) const;

    void setEnabled( bool b );

    void repaintSelections();

    enum FocusStyle { FollowStyle, SpreadSheet };
    virtual void setFocusStyle( FocusStyle fs );
    FocusStyle focusStyle() const;

public slots:
    virtual void setNumRows( int r );
    virtual void setNumCols( int r );
    virtual void setShowGrid( bool b );
    virtual void hideRow( int row );
    virtual void hideColumn( int col );
    virtual void showRow( int row );
    virtual void showColumn( int col );

    virtual void setColumnWidth( int col, int w );
    virtual void setRowHeight( int row, int h );

    virtual void adjustColumn( int col );
    virtual void adjustRow( int row );

    virtual void setColumnStretchable( int col, bool stretch );
    virtual void setRowStretchable( int row, bool stretch );
    bool isColumnStretchable( int col ) const;
    bool isRowStretchable( int row ) const;
    virtual void setSorting( bool b );
    virtual void swapRows( int row1, int row2, bool swapHeader = FALSE );
    virtual void swapColumns( int col1, int col2, bool swapHeader = FALSE );
    virtual void swapCells( int row1, int col1, int row2, int col2 );

    virtual void setLeftMargin( int m );
    virtual void setTopMargin( int m );
    virtual void setCurrentCell( int row, int col );
    void clearSelection( bool repaint = TRUE );
    virtual void setColumnMovingEnabled( bool b );
    virtual void setRowMovingEnabled( bool b );

    virtual void setReadOnly( bool b );
    virtual void setRowReadOnly( int row, bool ro );
    virtual void setColumnReadOnly( int col, bool ro );

    virtual void setDragEnabled( bool b );
    bool dragEnabled() const;

    virtual void insertRows( int row, int count = 1 );
    virtual void insertColumns( int col, int count = 1 );
    virtual void removeRow( int row );
    virtual void removeRows( const QMemArray<int> &rows );
    virtual void removeColumn( int col );
    virtual void removeColumns( const QMemArray<int> &cols );

    virtual void editCell( int row, int col, bool replace = FALSE );

protected:
    enum EditMode { NotEditing, Editing, Replacing };
    void drawContents( QPainter *p, int cx, int cy, int cw, int ch );
    void contentsMousePressEvent( QMouseEvent* );
    void contentsMouseMoveEvent( QMouseEvent* );
    void contentsMouseDoubleClickEvent( QMouseEvent* );
    void contentsMouseReleaseEvent( QMouseEvent* );
    void contentsContextMenuEvent( QContextMenuEvent * e );
    void keyPressEvent( QKeyEvent* );
    void focusInEvent( QFocusEvent* );
    void focusOutEvent( QFocusEvent* );
    void viewportResizeEvent( QResizeEvent * );
    void showEvent( QShowEvent *e );
    void setEditMode( EditMode mode, int row, int col );
#ifndef QT_NO_DRAGANDDROP
    virtual void contentsDragEnterEvent( QDragEnterEvent *e );
    virtual void contentsDragMoveEvent( QDragMoveEvent *e );
    virtual void contentsDragLeaveEvent( QDragLeaveEvent *e );
    virtual void contentsDropEvent( QDropEvent *e );
    virtual QDragObject *dragObject();
    virtual void startDrag();
#endif

    virtual void paintEmptyArea( QPainter *p, int cx, int cy, int cw, int ch );
    virtual void activateNextCell();
    virtual QWidget *createEditor( int row, int col, bool initFromCell ) const;
    virtual void setCellContentFromEditor( int row, int col );
    virtual QWidget *beginEdit( int row, int col, bool replace );
    virtual void endEdit( int row, int col, bool accept, bool replace );

    virtual void resizeData( int len );
    virtual void insertWidget( int row, int col, QWidget *w );
    int indexOf( int row, int col ) const;

    void windowActivationChange( bool );
    bool isEditing() const;
    EditMode editMode() const;
    int currEditRow() const;
    int currEditCol() const;

protected slots:
    virtual void columnWidthChanged( int col );
    virtual void rowHeightChanged( int row );
    virtual void columnIndexChanged( int section, int fromIndex, int toIndex );
    virtual void rowIndexChanged( int section, int fromIndex, int toIndex );
    virtual void columnClicked( int col );

signals:
    void currentChanged( int row, int col );
    void clicked( int row, int col, int button, const QPoint &mousePos );
    void doubleClicked( int row, int col, int button, const QPoint &mousePos );
    void pressed( int row, int col, int button, const QPoint &mousePos );
    void selectionChanged();
    void valueChanged( int row, int col );
    void contextMenuRequested( int row, int col, const QPoint &pos );
#ifndef QT_NO_DRAGANDDROP
    void dropped( QDropEvent *e );
#endif

private slots:
    void doAutoScroll();
    void doValueChanged();
    void updateGeometriesSlot();

private:
    void contentsMousePressEventEx( QMouseEvent* );
    void drawContents( QPainter* );
    void updateGeometries();
    void repaintSelections( QTableSelection *oldSelection,
                            QTableSelection *newSelection,
                            bool updateVertical = TRUE,
                            bool updateHorizontal = TRUE );
    QRect rangeGeometry( int topRow, int leftCol,
                         int bottomRow, int rightCol, bool &optimize );
    void fixRow( int &row, int y );
    void fixCol( int &col, int x );

    void init( int numRows, int numCols );
    QSize tableSize() const;
    void repaintCell( int row, int col );
    void contentsToViewport2( int x, int y, int& vx, int& vy );
    QPoint contentsToViewport2( const QPoint &p );
    void viewportToContents2( int vx, int vy, int& x, int& y );
    QPoint viewportToContents2( const QPoint &p );

    void updateRowWidgets( int row );
    void updateColWidgets( int col );
    bool isSelected( int row, int col, bool includeCurrent ) const;
    void setCurrentCell( int row, int col, bool updateSelections );
    void fixCell( int &row, int &col, int key );
    void delayedUpdateGeometries();
    struct TableWidget
    {
    TableWidget( QWidget *w, int r, int c ) : wid( w ), row( r ), col ( c ) {}
    QWidget *wid;
    int row, col;
    };
    void saveContents( QPtrVector<QTableItem> &tmp,
               QPtrVector<TableWidget> &tmp2 );
    void updateHeaderAndResizeContents( QTableHeader *header,
                    int num, int colRow,
                    int width, bool &updateBefore );
    void restoreContents( QPtrVector<QTableItem> &tmp,
              QPtrVector<TableWidget> &tmp2 );
    void finishContentsResze( bool updateBefore );

private:
    QPtrVector<QTableItem> contents;
    QPtrVector<QWidget> widgets;
    int curRow;
    int curCol;
    QTableHeader *leftHeader, *topHeader;
    EditMode edMode;
    int editCol, editRow;
    QPtrList<QTableSelection> selections;
    QTableSelection *currentSel;
    QTimer *autoScrollTimer;
    int lastSortCol;
    bool sGrid : 1;
    bool mRows : 1;
    bool mCols : 1;
    bool asc : 1;
    bool doSort : 1;
    bool mousePressed : 1;
    bool readOnly : 1;
    bool shouldClearSelection : 1;
    bool dEnabled : 1;
    bool context_menu : 1;
    bool drawActiveSelection : 1;
    bool was_visible : 1;
    SelectionMode selMode;
    int pressedRow, pressedCol;
    QTablePrivate *d;
    QIntDict<int> roRows;
    QIntDict<int> roCols;
    int startDragRow;
    int startDragCol;
    QPoint dragStartPos;
    int oldCurrentRow, oldCurrentCol;
    QWidget *topLeftCorner;
    FocusStyle focusStl;
    QSize cachedSizeHint;

};

#endif // QT_NO_TABLE
#endif // TABLE_H

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTable成员列表

完整的QTable成员列表

这里是QTable成员函数的完整列表，包括继承的成员。

  • QTable()
  • ~QTable()
  • acceptDrops()
  • activateNextCell()
  • addChild()
  • addSelection()
  • adjustColumn()
  • adjustRow()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • beginEdit()
  • blockSignals()
  • bottomMargin()
  • caption()
  • cellGeometry()
  • cellRect()
  • cellWidget()
  • center()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearCell()
  • clearCellWidget()
  • clearFocus()
  • clearMask()
  • clearSelection()
  • clearWFlags()
  • clicked()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columnAt()
  • columnClicked()
  • columnIndexChanged()
  • columnMovingEnabled()
  • columnPos()
  • columnWidth()
  • columnWidthChanged()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • contextMenuEvent()
  • contextMenuRequested()
  • cornerWidget()
  • create()
  • createEditor()
  • currEditCol()
  • currEditRow()
  • currentChanged()
  • currentColumn()
  • currentRow()
  • currentSelection()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doubleClicked()
  • dragAutoScroll()
  • dragEnabled()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • dragObject()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dropped()
  • dumpObjectInfo()
  • dumpObjectTree()
  • editCell()
  • editMode()
  • enableClipper()
  • enabledChange()
  • endEdit()
  • ensureCellVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusStyle()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideColumn()
  • hideEvent()
  • hideRow()
  • highPriority()
  • horizontalHeader()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertColumns()
  • insertRows()
  • insertWidget()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isColumnReadOnly()
  • isColumnSelected()
  • isColumnStretchable()
  • isDesktop()
  • isDialog()
  • isEditing()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isReadOnly()
  • isRowReadOnly()
  • isRowSelected()
  • isRowStretchable()
  • isSelected()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • item()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numCols()
  • numRows()
  • numSelections()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintCell()
  • paintEmptyArea()
  • paintEvent()
  • paintFocus()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeColumn()
  • removeColumns()
  • removeEventFilter()
  • removeRow()
  • removeRows()
  • removeSelection()
  • repaint()
  • repaintContents()
  • repaintSelections()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeData()
  • resizeEvent()
  • resizePolicy()
  • rightMargin()
  • rowAt()
  • rowHeight()
  • rowHeightChanged()
  • rowIndexChanged()
  • rowMovingEnabled()
  • rowPos()
  • scroll()
  • scrollBy()
  • selection()
  • selectionChanged()
  • selectionMode()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellContentFromEditor()
  • setCellWidget()
  • setColumnMovingEnabled()
  • setColumnReadOnly()
  • setColumnStretchable()
  • setColumnWidth()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentCell()
  • setCursor()
  • setDisabled()
  • setDragAutoScroll()
  • setDragEnabled()
  • setEditMode()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFocusStyle()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItem()
  • setKeyCompression()
  • setLeftMargin()
  • setLineWidth()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNumCols()
  • setNumRows()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setRowHeight()
  • setRowMovingEnabled()
  • setRowReadOnly()
  • setRowStretchable()
  • setSelectionMode()
  • setShowGrid()
  • setSizeIncrement()
  • setSizePolicy()
  • setSorting()
  • setStaticBackground()
  • setStyle()
  • setTabOrder()
  • setText()
  • setTopMargin()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setWFlags()
  • show()
  • showChild()
  • showColumn()
  • showEvent()
  • showFullScreen()
  • showGrid()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showRow()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • sortColumn()
  • sorting()
  • stackUnder()
  • startDrag()
  • startTimer()
  • style()
  • styleChange()
  • swapCells()
  • swapColumns()
  • swapRows()
  • tabletEvent()
  • takeItem()
  • testWFlags()
  • text()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateCell()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • valueChanged()
  • verticalHeader()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTableItem类

QTableItem类参考
[表格模块]

QTableItem类为QTable单元格提供内容。 详见……

#include <qtable.h>

继承了Qt。

被QComboTableItem和QCheckTableItem所继承。

所有成员函数的列表。

公共成员

  • enum EditType { Never, OnTyping, WhenCurrent, Always }
  • QTableItem ( QTable * table, EditType et, const QString & text )
  • QTableItem ( QTable * table, EditType et, const QString & text, const QPixmap & p )
  • virtual ~QTableItem ()
  • virtual QPixmap pixmap () const
  • virtual QString text () const
  • virtual void setPixmap ( const QPixmap & p )
  • virtual void setText ( const QString & str )
  • QTable * table () const
  • virtual int alignment () const
  • virtual void setWordWrap ( bool b )
  • bool wordWrap () const
  • EditType editType () const
  • virtual QWidget * createEditor () const
  • virtual void setContentFromEditor ( QWidget * w )
  • virtual void setReplaceable ( bool b )
  • bool isReplaceable () const
  • virtual QString key () const
  • virtual QSize sizeHint () const
  • virtual void setSpan ( int rs, int cs )
  • int rowSpan () const
  • int colSpan () const
  • virtual void setRow ( int r )
  • virtual void setCol ( int c )
  • int row () const
  • int col () const
  • virtual void paint ( QPainter * p, const QColorGroup & cg, const QRect & cr, bool selected )
  • virtual void setEnabled ( bool b )
  • bool isEnabled () const
  • virtual int rtti () const

详细描述

QTableItem类为QTable单元格提供内容。

在很多应用中，QTableItem都适合于显示和编辑QTable单元格。而在需要生成很大的表格的情况下，你可能更喜欢另一种方法，而不是使用QTableItem：参见关于大表格的注意事项。

QTableItem包含着一个单元格的数据，缺省情况下是一个字符串和一个象素映射。表项还包括单元格的显示大小和数据对齐方式，同时指定了单元格的EditType和用于内嵌编辑的编辑器（缺省为QLineEdit）。如果你需要多选框，使用QCheckTableItem；需要组合框则使用QComboTableItem。EditType（在构造器中设置的）决定单元格的内容是否可以被编辑；setReplaceable()设置了单元格是否可以被另外一个单元格的内容所替换。

如果指定了象素映射，总是显示在文本在左边。可以分别用setText()和setPixmap()来改变文本或者象素映射。对于文本可以使用setWordWrap()。表项的对齐方式在构造器中设置。

如果你想用自己的部件而不是QLineEdit来编辑单元格内容，那就重新实现createEditor()和setContentFromEditor()。如果要显示定制的内容，就重写paint()。

对表项排序使用了key()函数；缺省情况下返回表项的文本()。重写key()以定制你的表项排序方式。

使用QTable::setItem()把表项插入到表格中。如果你把表项插入到一个已经有表项的单元格中，原有的表项被删去。

例子：

    for ( int row = 0; row < table->numRows(); row++ ) {
        for ( int col = 0; col < table->numCols(); col++ ) {
            table->setItem( row, col,
                new QTableItem( table, WhenCurrent, QString::number( row * col ) ) );
        }
    }

如果要在相同或者不同的表格中把表项从一个单元格移到另一个，可以使用QTable::takeItem()和QTable::setItem()，但是也可以参见QTable::swapCells()。

表项可以以标准删除的方式来删去；表格和单元格将会相应地更新。

也参见QCheckTableItem、QComboTableItem和高级部件。

成员类型文档

QTableItem::EditType

本枚举用于定义单元格是可编辑还是只读（与其他设置共同作用），和单元格应如何被显示。

  • QTableItem::Always - 单元格总是看起来可编辑。

使用这个EditType确保了用createEditor()生成的编辑器（缺省为QLineEdit）总是可见。这暗示了内容的对齐方式：缺省编辑器的所有东西（即使数字）都是左对齐，而单元格的数字值缺省为右对齐。

如果编辑类型为Always的单元格对齐不正确，你可以为这些表项重写createEditor()。

  • QTableItem::WhenCurrent - 只有当单元格有键盘焦点（参见QTable::setCurrentCell()）时，该单元格是看起来可编辑的。
  • QTableItem::OnTyping - 只有当用户在单元格中打字或者对单元格双击时，该单元格是看起来可编辑的。这类似于WhenCurrent的作用，但是也许更好一点。

当QTableItem对象在使用方便的函数如QTable::setText()和QTable::setPixmap()时生成的时候，其编辑类型缺省为OnTyping。

  • QTableItem::Never - 单元格不可编辑。

只有当对于该单元格所在的行QTable::isRowReadOnly()为FALSE，对于该单元格所在的行QTable::isColumnReadOnly()为FALSE，而且QTable::isReadOnly()为FALSE时，单元格才是实际可编辑的。

QComboTableItem有一个isEditable()属性，用于指示用户是可以输入自己的文本还是限制于从已有列表中选择。只有当QComboTableItem依照以上描述的EditType一样是可编辑的时，它才可以交互。

成员函数文档

QTableItem::QTableItem ( QTable * table, EditType et, const QString & text )

使用文本text来生成表格table的一个子项。该表项的EditType为et。

该表项使用QLineEdit作为编辑器，文字不自动回行，占据一个单元格。可使用QTable::setItem()以把该表项插入到表格中。

表格拥有表项的所有权，所以一个表项不应该同时被插入多个表格中。

QTableItem::QTableItem ( QTable * table, EditType et, const QString & text, const QPixmap & p )

使用文本text和象素映射p来生成表格table的一个子项。该表项的EditType为et。

表项把象素映射显示在文本的左边。表项使用QLineEdit用于文本编辑，文字不自动回行，占据一个单元格。可使用QTable::setItem()以把该表项插入到表格中。

表格拥有表项的所有权，所以一个表项不应该同时被插入多个表格中。

QTableItem::~QTableItem () [virtual]

该解构器删去这个表项，并且释放所有分配的资源。

如果该表项在某个表格中（也就是说，被使用setItem()插入到表格中），将被从表格和它所占据的单元格中删去。

int QTableItem::alignment () const [virtual]

本对齐函数返回单元格的文本内容在绘制时如何对齐。缺省的实现是：数字右对齐，其他文本左对齐。

也参见Qt::AlignmentFlags。

int QTableItem::col () const

返回表项所在列。如果单元格跨越多列，本函数返回最左一列。

也参见row()和setCol()。

int QTableItem::colSpan () const

返回表项跨越的列数，通常是1。

也参见setSpan()和rowSpan()。

QWidget * QTableItem::createEditor () const [virtual]

本虚拟函数生成一个编辑器，用户用它来编辑单元格的内容。缺省的实现是生成一个QLineEdit。

如果本函数返回0，则单元格为只读。

返回的部件最好是可见的，理想状态下以QTable::viewport()为父部件。

如果重写本函数，你几乎肯定需要重写setContentFromEditor()，可能需要重写sizeHint()。

    QWidget *ComboItem::createEditor() const
    {
        // create an editor - a combobox in our case
        ( (ComboItem*)this )->cb = new QComboBox( table()->viewport() );
        QObject::connect( cb, SIGNAL( activated( int ) ), table(), SLOT( doValueChanged() ) );
        cb->insertItem( "Yes" );
        cb->insertItem( "No" );
        // and initialize it
        cb->setCurrentItem( text() == "No" ? 1 : 0 );
        return cb;

也参见QTable::createEditor()、setContentFromEditor()和QTable::viewport()。

例子：table/statistics/statistics.cpp。

EditType QTableItem::editType () const

返回表项的编辑类型。

这是在表项构造时设置的。

也参见EditType和QTableItem()。

bool QTableItem::isEnabled () const

如果表项为激活，返回TRUE；否则返回FALSE。

也参见setEnabled()。

bool QTableItem::isReplaceable () const

本函数返回的是，单元格的内容是否能被另一个表项的内容替换。跨越多个单元格的表项不管这个设置，其内容不能被另一个表项替换。

（这不同于EditType，因为EditType是关于用户是否能改变单元格的内容。）

也参见setReplaceable()和EditType。

QString QTableItem::key () const [virtual]

本虚拟函数返回用于排序的关键字。缺省的实现是返回相关表项的text()。

也参见QTable::sorting。

void QTableItem::paint ( QPainter * p, const QColorGroup & cg, const QRect & cr, bool selected ) [virtual]

本虚拟函数用于在矩形区域cr内绘制一个表项的内容，使用的画具为p，颜色组为cg。

若selected为TRUE，单元格高亮显示。

通常不必使用本函数，但如果要绘制单元格的定制内容，你就需要重写。

注意：为提高效率，该画具缺省并未剪裁。如果需要剪裁，使用

    p->setClipRect( table()->cellRect(row, col), QPainter::ClipPainter );
    //... your drawing code
    p->setClipping( FALSE );

例子：table/statistics/statistics.cpp。

QPixmap QTableItem::pixmap () const [virtual]

返回表项的象素映射，如果没有则是一个空象素映射。

也参见setPixmap()和text()。

int QTableItem::row () const

返回表项所在行。如果单元格跨越多行，本函数返回最上一行。

也参见col()和setRow()。

int QTableItem::rowSpan () const

返回表项跨越的行数，通常是1。

也参见setSpan()和colSpan()。

int QTableItem::rtti () const [virtual]

返回这个表项的运行时类型判别（Returns the Run Time Type Identification）值，对于QTableItem为0。

尽管经常被主张正统的人（purist）所不取，对于QTable来说，运行时类型判别还是很有用的，原因是它考虑了有效的索引存储机制。

当你基于QTableItem生成子类时，确保每一个子类返回一个唯一的运行时类型判别rtti()值。建议使用大于1000的值，最好是大的随机数，以允许对该类的扩展。

也参见QCheckTableItem::rtti()和QComboTableItem::rtti()。

在QComboTableItem和QCheckTableItem中被重写。

void QTableItem::setCol ( int c ) [virtual]

设置列c为表项的列。通常不必调用本函数。

如果单元格跨越多列，本函数设置最左一列，并保持该多单元格表项的宽度。

也参见col()、setRow()和colSpan()。

void QTableItem::setContentFromEditor ( QWidget * w ) [virtual]

只要单元格的内容被编辑器w编辑过，QTable调用本虚拟函数，把新值拷贝到QTableItem中。

如果你重写了createEditor()，而且返回的不是QLineEdit，你几乎肯定要重写本函数。

    void ComboItem::setContentFromEditor( QWidget *w )
    {
        // the user changed the value of the combobox, so synchronize the
        // value of the item (its text), with the value of the combobox
        if ( w->inherits( "QComboBox" ) )
            setText( ( (QComboBox*)w )->currentText() );
        else
            QTableItem::setContentFromEditor( w );

也参见QTable::setCellContentFromEditor()。

例子：table/statistics/statistics.cpp。

void QTableItem::setEnabled ( bool b ) [virtual]

如果b为TRUE，该表项被激活；如果b为FALSE，该表项被设为失效。

失效的表项不响应用户交互。

也参见isEnabled()。

void QTableItem::setPixmap ( const QPixmap & p ) [virtual]

设置象素映射p为本表项的象素映射。

注意：setPixmap()并没有更新表项所属的单元格。使用QTable::updateCell()来重绘单元格内容。

对于QComboTableItem和QCheckTableItem，本函数没有可见的影响。

也参见QTable::setPixmap()、pixmap()和setText()。

void QTableItem::setReplaceable ( bool b ) [virtual]

如果b为TRUE，可以用一个QTableItem的内容来替换另一个单元格的内容。如果b为FALSE，则不可以。跨越多个单元格的表项，其内容不能被其他表项替换。

（这不同于EditType，因为EditType是关于用户是否能改变单元格的内容。）

也参见isReplaceable()。

void QTableItem::setRow ( int r ) [virtual]

设置行r为表项的行。通常不必调用本函数。

如果单元格跨越多行，本函数设置最上一行，并保持该多单元格表项的高度。

也参见row()、setCol()和rowSpan()。

void QTableItem::setSpan ( int rs, int cs ) [virtual]

改变该QTableItem的范围，使其跨越多个单元格，覆盖rs个行和cs个列。左上的单元格为原始单元格。

警告：只有当表项已经使用例如QTable::setItem()等方法插入到表格中时，本函数才起作用。本函数也核对以确保rs行和cs列在表格范围内，如果不是则不改变跨越而直接返回。

也参见rowSpan()和colSpan()。

void QTableItem::setText ( const QString & str ) [virtual]

把表项的文本改变为str。

注意在；setText()并没有更新表项所属的单元格。使用QTable::updateCell()来重绘单元格内容。

也参见QTable::setText()、text()、setPixmap()和QTable::updateCell()。

例子：table/statistics/statistics.cpp。

void QTableItem::setWordWrap ( bool b ) [virtual]

如果b为TRUE，单元格的文本将在必要时多行自动回行，以适应单元格的宽度；否则文本将只在一行内显示。

也参见wordWrap()、QTable::adjustColumn()和QTable::setColumnStretchable()。

QSize QTableItem::sizeHint () const [virtual]

本虚拟函数单元格要显示全部内容所需要的大小。

如果写QTableItem的子类，一般要重写本函数。

QTable * QTableItem::table () const

返回该表项所属的QTable。

也参见QTable::setItem()和QTableItem()。

QString QTableItem::text () const [virtual]

提供该表项的文本，如果没有文本则是一个空字符串。

如果editMode()为Always，之前setContentFromEditor()被调用，以使编辑器的当前值被返回。

如果editMode()是别的，而且单元格的编辑器激活，那么如果编辑器不是QLineEdit，setContentFromEditor()就被调用。这意味着，在这种情况下，如果用户输入文本，那么直到用户认可新数据（比如说按下回车或者Tab键），text()返回的都是表项的原始值。对于其他的编辑器（例如组合框），setContentFromEditor()总是被调用，所以也总是返回编辑器当前显示的值。

也参见setText()和pixmap()。

bool QTableItem::wordWrap () const

如果单元格能自动回行，返回TRUE；否则返回FALSE。

也参见setWordWrap()。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTableItem成员列表

完整的QTableItem成员列表

这里是QTableItem成员函数的完整列表，包括继承的成员。

  • QTableItem()
  • ~QTableItem()
  • alignment()
  • col()
  • colSpan()
  • createEditor()
  • editType()
  • isEnabled()
  • isReplaceable()
  • key()
  • paint()
  • pixmap()
  • row()
  • rowSpan()
  • rtti()
  • setCol()
  • setContentFromEditor()
  • setEnabled()
  • setPixmap()
  • setReplaceable()
  • setRow()
  • setSpan()
  • setText()
  • setWordWrap()
  • sizeHint()
  • table()
  • text()
  • wordWrap()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTableSelection类

QTableSelection类参考
[表格模块]

QTableSelection类提供对QTable中的选中区域的处理。 详见……

#include <qtable.h>

所有成员函数的列表。

公共成员

  • QTableSelection ()
  • void init ( int row, int col )
  • void expandTo ( int row, int col )
  • bool operator== ( const QTableSelection & s ) const
  • bool operator!= ( const QTableSelection & s ) const
  • int topRow () const
  • int bottomRow () const
  • int leftCol () const
  • int rightCol () const
  • int anchorRow () const
  • int anchorCol () const
  • bool isActive () const

详细描述

QTableSelection类提供对QTable中的选中区域的处理。

选中区域（selection）是QTable中一个单元格的矩形集合。这个矩形集合中的一个叫做锚单元格（anchor cell），它是第一个被选中的单元格。init()函数设置锚单元格和只包括这个单元格的选中矩形。；expandTo()函数则把选中矩形扩展为包括其他单元格。

有几个查询区域范围的处理函数：anchorRow()和anchorCol()返回锚的位置；leftCol()、rightCol()、topRow()和bottomRow()返回矩形的四边。这四个都是选中区域的一部分。

一个新生成的QTableSelection是非活动的——isActive()返回FALSE。你必须使用init()和expandTo()以激活它。

也参见QTable、QTable::addSelection()、QTable::selection()和高级部件。

成员函数文档

QTableSelection::QTableSelection ()

生成一个非活动的选中区域。使用init()和expandTo()来激活它。

int QTableSelection::anchorCol () const

返回选中区域的锚的列。

也参见anchorRow()和expandTo()。

int QTableSelection::anchorRow () const

返回选中区域的锚的行。

也参见anchorCol()和expandTo()。

int QTableSelection::bottomRow () const

返回选中区域的底行。

也参见topRow()、leftCol()和rightCol()。

void QTableSelection::expandTo ( int row, int col )

把选中区域扩展到包括单元格row、col。新的选中区域矩形是row、col和之前的选中区域矩形的边界范围矩形（bounding rectangle）。调用本函数后，选中区域被激活。

如果未调用init()，本函数什么也不做。

也参见init()和isActive()。

void QTableSelection::init ( int row, int col )

把选中区域的锚设置为单元格row、col，并且该选中区域只包含这个单元格。

要扩展选中区域以包括其他单元格，调用expandTo()。

也参见isActive()。

bool QTableSelection::isActive () const

返回选中区域是否激活。选中区域在init()和expandTo()被调用之后被激活。

int QTableSelection::leftCol () const

返回选中区域的左边列。

也参见topRow()、bottomRow()和rightCol()。

bool QTableSelection::operator!= ( const QTableSelection & s ) const

如果s与选中区域不包含同样的单元格，返回TRUE；否则返回FALSE。

bool QTableSelection::operator== ( const QTableSelection & s ) const

如果s与选中区域包含同样的单元格，返回TRUE；否则返回FALSE。

int QTableSelection::rightCol () const

返回选中区域的右边列。

也参见topRow()、bottomRow()和leftCol()。

int QTableSelection::topRow () const

返回选中区域的顶行。

也参见bottomRow()、leftCol()和rightCol()。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTableSelection成员列表

完整的QTableSelection成员列表

这里是QTableSelection成员函数的完整列表，包括继承的成员。

  • QTableSelection()
  • anchorCol()
  • anchorRow()
  • bottomRow()
  • expandTo()
  • init()
  • isActive()
  • leftCol()
  • operator!=()
  • operator==()
  • rightCol()
  • topRow()

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


QTabletEvent Class

QTabletEvent Class Reference

The QTabletEvent class contains parameters that describe a Tablet event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • enum TabletDevice { NoDevice = -1, Puck, Stylus, Eraser }
  • QTabletEvent ( const QPoint & pos, int device, int pressure, int xTilt, int yTilt, const QPair<int, int> & uId )
  • QTabletEvent ( const QPoint & pos, const QPoint & globalPos, int device, int pressure, int xTilt, int yTilt, const QPair<int, int> & uId )
  • int pressure () const
  • int xTilt () const
  • int yTilt () const
  • const QPoint & pos () const
  • const QPoint & globalPos () const
  • int x () const
  • int y () const
  • int globalX () const
  • int globalY () const
  • TabletDevice device () const
  • int isAccepted () const
  • void accept ()
  • void ignore ()
  • QPair<int, int> uniqueId ()

Detailed Description

The QTabletEvent class contains parameters that describe a Tablet event.

Tablet Events are generated from a Wacom© tablet. Most of the time you will want to deal with events from the tablet as if they were events from a mouse, for example retrieving the position with x(), y(), pos(), globalX(), globalY() and globalPos(). In some situations you may wish to retrieve the extra information provided by the tablet device driver, for example, you might want to adjust color brightness based on pressure. QTabletEvent allows you to get the pressure(), the xTilt() and yTilt(), as well as the type of device being used with device() (see TabletDevice).

A tablet event contains a special accept flag that indicates whether the receiver wants the event. You should call QTabletEvent::accept() if you handle the tablet event; otherwise it will be sent to the parent widget.

The QWidget::setEnabled() function can be used to enable or disable mouse and keyboard events for a widget.

The event handler QWidget::tabletEvent() receives tablet events.

See also Event Classes.

Member Type Documentation

QTabletEvent::TabletDevice

This enum defines what type of device is generating the event.

  • QTabletEvent::NoDevice - No device, or an unknown device.
  • QTabletEvent::Puck - A Puck (a device that is similar to a flat mouse with a transparent circle with cross-hairs).
  • QTabletEvent::Stylus - A Stylus (the narrow end of the pen).
  • QTabletEvent::Eraser - An Eraser (the broad end of the pen).

Member Function Documentation

QTabletEvent::QTabletEvent ( const QPoint & pos, int device, int pressure, int xTilt, int yTilt, const QPair<int, int> & uId )

Constructs a tablet event object.

The globalPos() is initialized to QCursor::pos(), i.e. pos, which is usually (but not always) correct. Use the other constructor if you need to specify the global position explicitly. device contains the device type, pressure contains the pressure exerted on the device, xTilt and yTilt contain the device's degrees of tilt from the X and Y axis respectively. The uId contains an event id.

See also pos(), device(), pressure(), xTilt() and yTilt().

QTabletEvent::QTabletEvent ( const QPoint & pos, const QPoint & globalPos, int device, int pressure, int xTilt, int yTilt, const QPair<int, int> & uId )

Constructs a tablet event object. The position when the event occurred is is given in pos and globalPos. device contains the device type, pressure contains the pressure exerted on the device, xTilt and yTilt contain the device's degrees of tilt from the X and Y axis respectively. The uId contains an event id.

On Irix, globalPos will contain the high-resolution coordinates received from the tablet device driver, instead of from the windowing system.

See also pos(), globalPos(), device(), pressure(), xTilt() and yTilt().

void QTabletEvent::accept ()

Sets the accept flag of the tablet event object.

Setting the accept flag indicates that the receiver of the event wants the tablet event. Unwanted tablet events are sent to the parent widget.

The accept flag is set by default.

See also ignore().

TabletDevice QTabletEvent::device () const

Returns the type of device that generated the event. Useful if you want one end of the pen to do something different than the other.

See also TabletDevice.

const QPoint & QTabletEvent::globalPos () const

Returns the global position of the device at the time of the event. This is important on asynchronous windows systems like X11; whenever you move your widgets around in response to mouse events, globalPos() can differ significantly from the current position QCursor::pos().

See also globalX() and globalY().

int QTabletEvent::globalX () const

Returns the global x-position of the mouse pointer at the time of the event.

See also globalY() and globalPos().

int QTabletEvent::globalY () const

Returns the global y-position of the mouse pointer at the time of the event.

See also globalX() and globalPos().

void QTabletEvent::ignore ()

Clears the accept flag parameter of the tablet event object.

Clearing the accept flag indicates that the event receiver does not want the tablet event. Unwanted tablet events are sent to the parent widget.

The accept flag is set by default.

See also accept().

int QTabletEvent::isAccepted () const

Returns TRUE if the receiver of the event handles the tablet event; otherwise returns FALSE.

const QPoint & QTabletEvent::pos () const

Returns the position of the device, relative to the widget that received the event.

If you move widgets around in response to mouse events, use globalPos() instead of this function.

See also x(), y() and globalPos().

int QTabletEvent::pressure () const

Returns the pressure that is exerted on the device. This number is a value from 0 (no pressure) to 255 (maximum pressure). The pressure is always scaled to be within this range no matter how many pressure levels the underlying hardware supports.

QPair<int, int> QTabletEvent::uniqueId ()

Returns a unique ID for the current device. It is possible to generate a unique ID for any Wacom© device. This makes it possible to differentiate between multiple devices being used at the same time on the tablet. The first member contains a value for the type, the second member contains a physical ID obtained from the device. Each combination of these values is unique. Note: for different platforms, the first value is different due to different driver implementations.

int QTabletEvent::x () const

Returns the x-position of the device, relative to the widget that received the event.

See also y() and pos().

int QTabletEvent::xTilt () const

Returns the difference from the perpendicular in the X Axis. Positive values are towards the tablet's physical right. The angle is in the range -60 to +60 degrees.

See also yTilt().

int QTabletEvent::y () const

Returns the y-position of the device, relative to the widget that received the event.

See also x() and pos().

int QTabletEvent::yTilt () const

Returns the difference from the perpendicular in the Y Axis. Positive values are towards the bottom of the tablet. The angle is within the range -60 to +60 degrees.

See also xTilt().

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


QTabletEvent Member List

Complete Member List for QTabletEvent

This is the complete list of member functions for QTabletEvent, including inherited members.

  • QTabletEvent()
  • accept()
  • device()
  • globalPos()
  • globalX()
  • globalY()
  • ignore()
  • isAccepted()
  • pos()
  • pressure()
  • spontaneous()
  • type()
  • uniqueId()
  • x()
  • xTilt()
  • y()
  • yTilt()


QTabWidget Class

QTabWidget Class Reference

The QTabWidget class provides a stack of tabbed widgets. More...

#include <qtabwidget.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QTabWidget ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • virtual void addTab ( QWidget * child, const QString & label )
  • virtual void addTab ( QWidget * child, const QIconSet & iconset, const QString & label )
  • virtual void addTab ( QWidget * child, QTab * tab )
  • virtual void insertTab ( QWidget * child, const QString & label, int index = -1 )
  • virtual void insertTab ( QWidget * child, const QIconSet & iconset, const QString & label, int index = -1 )
  • virtual void insertTab ( QWidget * child, QTab * tab, int index = -1 )
  • void changeTab ( QWidget * w, const QString & label )
  • void changeTab ( QWidget * w, const QIconSet & iconset, const QString & label )
  • bool isTabEnabled ( QWidget * w ) const
  • void setTabEnabled ( QWidget * w, bool enable )
  • QString tabLabel ( QWidget * w ) const
  • void setTabLabel ( QWidget * w, const QString & l )
  • QIconSet tabIconSet ( QWidget * w ) const
  • void setTabIconSet ( QWidget * w, const QIconSet & iconset )
  • void removeTabToolTip ( QWidget * w )
  • void setTabToolTip ( QWidget * w, const QString & tip )
  • QString tabToolTip ( QWidget * w ) const
  • QWidget * currentPage () const
  • QWidget * page ( int index ) const
  • QString label ( int index ) const
  • int currentPageIndex () const
  • int indexOf ( QWidget * w ) const
  • enum TabPosition { Top, Bottom }
  • TabPosition tabPosition () const
  • void setTabPosition ( TabPosition )
  • enum TabShape { Rounded, Triangular }
  • TabShape tabShape () const
  • void setTabShape ( TabShape s )
  • int margin () const
  • void setMargin ( int )
  • int count () const

Public Slots

  • void setCurrentPage ( int )
  • virtual void showPage ( QWidget * w )
  • virtual void removePage ( QWidget * w )

Signals

  • void currentChanged ( QWidget * )

Properties

  • bool autoMask - whether the tab widget is automatically masked (read only)
  • int count - the number of tabs in the tab bar (read only)
  • int currentPage - the index position of the current tab page
  • int margin - the margin in this tab widget
  • TabPosition tabPosition - the position of the tabs in this tab widget
  • TabShape tabShape - the shape of the tabs in this tab widget

Protected Members

  • void setTabBar ( QTabBar * tb )
  • QTabBar * tabBar () const

Detailed Description

The QTabWidget class provides a stack of tabbed widgets.

A tabbed widget is a widget that has a tab bar of tabs, and for each tab a "page" which is a widget. The user selects which page to see and use by clicking on its tab or by pressing the indicated Alt+letter key combination.

QTabWidget provides a single row of tabs along the top or bottom of the pages (see TabPosition).

The normal way to use QTabWidget is to do the following in the constructor:

  1. Create a QTabWidget.
  2. Create a QWidget for each of the pages in the tab dialog, insert children into it, set up geometry management for it and use addTab() (or insertTab()) to set up a tab and keyboard accelerator for it.
  3. Connect to the signals and slots.

The position of the tabs is set with setTabPosition(), their shape with setTabShape(), and their margin with setMargin().

If you don't call addTab() the page you have created will not be visible. Don't confuse the object name you supply to the QWidget constructor and the tab label you supply to addTab(). addTab() takes a name which indicates an accelerator and is meaningful and descriptive to the user, whereas the widget name is used primarily for debugging.

The signal currentChanged() is emitted when the user selects a page.

The current page is available as an index position with currentPageIndex() or as a wiget pointer with currentPage(). You can retrieve a pointer to a page with a given index using page(), and can find the index position of a page with indexOf(). Use setCurrentPage() to show a particular page by index, or showPage() to show a page by widget pointer.

You can change a tab's label and iconset using changeTab() or setTabLabel() and setTabIconSet(). A tab page can be removed with removePage().

Each tab is either enabled or disabled at any given time (see setTabEnabled()). If a tab is enabled, the tab text is drawn in black and the user can select that tab. If it is disabled, the tab is drawn in a different way and the user cannot select that tab. Note that even if a tab is disabled, the page can still be visible, for example if all of the tabs happen to be disabled.

Although tab widgets can be a very good way to split up a complex dialog, it's also very easy to get into a mess. See QTabDialog for some design hints.

Most of the functionality in QTabWidget is provided by a QTabBar (at the top, providing the tabs) and a QWidgetStack (most of the area, organizing the individual pages).

See also QTabDialog, Advanced Widgets and Organizers.

Member Type Documentation

QTabWidget::TabPosition

This enum type defines where QTabWidget can draw the tab row:

  • QTabWidget::Top - above the pages
  • QTabWidget::Bottom - below the pages

QTabWidget::TabShape

This enum type defines the shape of the tabs:

  • QTabWidget::Rounded - rounded look (normal)
  • QTabWidget::Triangular - triangular look (very unusual, included for completeness)

Member Function Documentation

QTabWidget::QTabWidget ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a tabbed widget with parent parent, name name, and widget flags f.

void QTabWidget::addTab ( QWidget * child, const QString & label ) [virtual]

Adds another tab and page to the tab view.

The new page is child; the tab's label is label. Note the difference between the widget name (which you supply to widget constructors and to setTabEnabled(), for example) and the tab label. The name is internal to the program and invariant, whereas the label is shown on-screen and may vary according to language and other factors.

If the tab's label contains an ampersand, the letter following the ampersand is used as an accelerator for the tab, e.g. if the label is "Bro&wse" then Alt+W becomes an accelerator which will move the focus to this tab.

If you call addTab() after show() the screen will flicker and the user may be confused.

See also insertTab().

Examples: addressbook/centralwidget.cpp and themes/themes.cpp.

void QTabWidget::addTab ( QWidget * child, const QIconSet & iconset, const QString & label ) [virtual]

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

Adds another tab and page to the tab view.

This function is the same as addTab(), but with an additional iconset.

void QTabWidget::addTab ( QWidget * child, QTab * tab ) [virtual]

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

This is a low-level function for adding tabs. It is useful if you are using setTabBar() to set a QTabBar subclass with an overridden QTabBar::paint() routine for a subclass of QTab. The child is the new page and tab is the tab to put the child on.

void QTabWidget::changeTab ( QWidget * w, const QString & label )

Defines a new label for page w's tab.

void QTabWidget::changeTab ( QWidget * w, const QIconSet & iconset, const QString & label )

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

Defines a new iconset and a new label for page w's tab.

int QTabWidget::count () const

Returns the number of tabs in the tab bar. See the "count" property for details.

void QTabWidget::currentChanged ( QWidget * ) [signal]

This signal is emitted whenever the current page changes. The parameter is the new current page.

See also currentPage(), showPage() and tabLabel().

QWidget * QTabWidget::currentPage () const

Returns a pointer to the page currently being displayed by the tab dialog. The tab dialog does its best to make sure that this value is never 0 (but if you try hard enough, it can be).

int QTabWidget::currentPageIndex () const

Returns the index position of the current tab page. See the "currentPage" property for details.

int QTabWidget::indexOf ( QWidget * w ) const

Returns the index position of page w, or -1 if the widget cannot be found.

void QTabWidget::insertTab ( QWidget * child, const QString & label, int index = -1 ) [virtual]

Inserts another tab and page to the tab view.

The new page is child; the tab's label is label. Note the difference between the widget name (which you supply to widget constructors and to setTabEnabled(), for example) and the tab label. The name is internal to the program and invariant, whereas the label is shown on-screen and may vary according to language and other factors.

If the tab's label contains an ampersand, the letter following the ampersand is used as an accelerator for the tab, e.g. if the label is "Bro&wse" then Alt+W becomes an accelerator which will move the focus to this tab.

If index is not specified, the tab is simply added. Otherwise it is inserted at the specified position.

If you call insertTab() after show(), the screen will flicker and the user may be confused.

See also addTab().

void QTabWidget::insertTab ( QWidget * child, const QIconSet & iconset, const QString & label, int index = -1 ) [virtual]

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

Inserts another tab and page to the tab view.

This function is the same as insertTab(), but with an additional iconset.

void QTabWidget::insertTab ( QWidget * child, QTab * tab, int index = -1 ) [virtual]

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

This is a lower-level method for inserting tabs, similar to the other insertTab() method. It is useful if you are using setTabBar() to set a QTabBar subclass with an overridden QTabBar::paint() routine for a subclass of QTab. The child is the new page, tab is the tab to put the child on and index is the position in the tab bar that this page should occupy.

bool QTabWidget::isTabEnabled ( QWidget * w ) const

Returns TRUE if the page w is enabled; otherwise returns FALSE.

See also setTabEnabled() and QWidget::enabled.

QString QTabWidget::label ( int index ) const

Returns the label of the tab at index position index.

int QTabWidget::margin () const

Returns the margin in this tab widget. See the "margin" property for details.

QWidget * QTabWidget::page ( int index ) const

Returns the tab page at index position index.

void QTabWidget::removePage ( QWidget * w ) [virtual slot]

Removes page w from this stack of widgets. Does not delete w.

See also showPage() and QWidgetStack::removeWidget().

void QTabWidget::removeTabToolTip ( QWidget * w )

Removes the tab tool tip for page w. If the page does not have a tip, nothing happens.

See also setTabToolTip() and tabToolTip().

void QTabWidget::setCurrentPage ( int ) [slot]

Sets the index position of the current tab page. See the "currentPage" property for details.

void QTabWidget::setMargin ( int )

Sets the margin in this tab widget. See the "margin" property for details.

void QTabWidget::setTabBar ( QTabBar * tb ) [protected]

Replaces the QTabBar heading the dialog by the tab bar tb. Note that this must be called before any tabs have been added, or the behavior is undefined.

See also tabBar().

void QTabWidget::setTabEnabled ( QWidget * w, bool enable )

If enable is TRUE, page w is enabled; otherwise page w is disabled. The page's tab is redrawn appropriately.

QTabWidget uses QWidget::setEnabled() internally, rather than keeping a separate flag.

Note that even a disabled tab/page may be visible. If the page is visible already, QTabWidget will not hide it; if all the pages are disabled, QTabWidget will show one of them.

See also isTabEnabled() and QWidget::enabled.

void QTabWidget::setTabIconSet ( QWidget * w, const QIconSet & iconset )

Sets the iconset for page w to iconset.

void QTabWidget::setTabLabel ( QWidget * w, const QString & l )

Sets the tab label for page w to l

void QTabWidget::setTabPosition ( TabPosition )

Sets the position of the tabs in this tab widget. See the "tabPosition" property for details.

void QTabWidget::setTabShape ( TabShape s )

Sets the shape of the tabs in this tab widget to s. See the "tabShape" property for details.

void QTabWidget::setTabToolTip ( QWidget * w, const QString & tip )

Sets the tab tool tip for page w to tip.

See also removeTabToolTip() and tabToolTip().

void QTabWidget::showPage ( QWidget * w ) [virtual slot]

Ensures that page w is shown. This is useful mainly for accelerators.

Warning: Used carelessly, this function can easily surprise or confuse the user.

See also QTabBar::currentTab.

QTabBar * QTabWidget::tabBar () const [protected]

Returns the currently set QTabBar.

See also setTabBar().

QIconSet QTabWidget::tabIconSet ( QWidget * w ) const

Returns the iconset of page w.

QString QTabWidget::tabLabel ( QWidget * w ) const

Returns the label text for the tab on page w.

TabPosition QTabWidget::tabPosition () const

Returns the position of the tabs in this tab widget. See the "tabPosition" property for details.

TabShape QTabWidget::tabShape () const

Returns the shape of the tabs in this tab widget. See the "tabShape" property for details.

QString QTabWidget::tabToolTip ( QWidget * w ) const

Returns the tab tool tip for page w.

See also setTabToolTip() and removeTabToolTip().

Property Documentation

bool autoMask

This property holds whether the tab widget is automatically masked.

See also QWidget::autoMask.

int count

This property holds the number of tabs in the tab bar.

Get this property's value with count().

int currentPage

This property holds the index position of the current tab page.

Set this property's value with setCurrentPage() and get this property's value with currentPageIndex().

See also QTabBar::currentTab.

int margin

This property holds the margin in this tab widget.

The margin is the distance between the innermost pixel of the frame and the outermost pixel of the pages.

Set this property's value with setMargin() and get this property's value with margin().

TabPosition tabPosition

This property holds the position of the tabs in this tab widget.

Possible values for this property are QTabWidget::Top and QTabWidget::Bottom.

See also TabPosition.

Set this property's value with setTabPosition() and get this property's value with tabPosition().

TabShape tabShape

This property holds the shape of the tabs in this tab widget.

Possible values for this property are QTabWidget::Rounded (default) or QTabWidget::Triangular.

See also TabShape.

Set this property's value with setTabShape() and get this property's value with tabShape().

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


qtabwidget.h Include File

qtabwidget.h

This is the verbatim text of the qtabwidget.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtabwidget.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTabWidget class
**
** Created : 990318
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTABWIDGET_H
#define QTABWIDGET_H

#ifndef QT_H
#include "qwidget.h"
#include "qiconset.h"
#endif // QT_H

#ifndef QT_NO_TABWIDGET

class QTabBar;
class QTabWidgetData;
class QTab;
class QWidgetStack;

class Q_EXPORT QTabWidget : public QWidget
{
    Q_OBJECT
    Q_ENUMS( TabPosition )
    Q_ENUMS( TabShape )
    Q_PROPERTY( TabPosition tabPosition READ tabPosition WRITE setTabPosition )
    Q_PROPERTY( TabShape tabShape READ tabShape WRITE setTabShape )
    Q_PROPERTY( int margin READ margin WRITE setMargin )
    Q_PROPERTY( int currentPage READ currentPageIndex WRITE setCurrentPage )
    Q_PROPERTY( int count READ count )
    Q_OVERRIDE( bool autoMask DESIGNABLE true SCRIPTABLE true )

public:
    QTabWidget( QWidget *parent = 0, const char *name = 0, WFlags f = 0 );
    ~QTabWidget();

    virtual void addTab( QWidget *, const QString & );
    virtual void addTab( QWidget *child, const QIconSet& iconset,
             const QString &label );
    virtual void addTab( QWidget *, QTab* );

    virtual void insertTab( QWidget *, const QString &, int index = -1 );
    virtual void insertTab( QWidget *child, const QIconSet& iconset,
                const QString &label, int index = -1 );
    virtual void insertTab( QWidget *, QTab*, int index = -1 );

    void changeTab( QWidget *, const QString &);
    void changeTab( QWidget *child, const QIconSet& iconset,
            const QString &label );

    bool isTabEnabled(  QWidget * ) const;
    void setTabEnabled( QWidget *, bool );

    QString tabLabel( QWidget * ) const;
    void setTabLabel( QWidget *p, const QString &l );

    QIconSet tabIconSet( QWidget * w ) const;
    void setTabIconSet( QWidget * w, const QIconSet & iconset );

    void removeTabToolTip( QWidget * w );
    void setTabToolTip( QWidget * w, const QString & tip );
    QString tabToolTip( QWidget * w ) const;

    QWidget * currentPage() const;
    QWidget *page( int ) const;
    QString label( int ) const;
    int currentPageIndex() const;
    int indexOf( QWidget * ) const;

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

    enum TabPosition { Top, Bottom };
    TabPosition tabPosition() const;
    void setTabPosition( TabPosition );

    enum TabShape { Rounded, Triangular };
    TabShape tabShape() const;
    void setTabShape( TabShape s );

    int margin() const;
    void setMargin( int );

    int count() const;

public slots:
    void setCurrentPage( int );
    virtual void showPage( QWidget * );
    virtual void removePage( QWidget * );

protected:
    void showEvent( QShowEvent * );
    void resizeEvent( QResizeEvent * );
    void setTabBar( QTabBar * );
    QTabBar* tabBar() const;
    void styleChange( QStyle& );
    void updateMask();
    bool eventFilter( QObject *, QEvent * );

signals:
    void currentChanged( QWidget * );
#ifndef Q_QDOC
    void selected( const QString& );
#endif

private slots:
    void showTab( int i );

private:
    QTabWidgetData *d;
    void setUpLayout( bool = FALSE );

    friend class QTabDialog;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTabWidget( const QTabWidget & );
    QTabWidget& operator=( const QTabWidget & );
#endif
};

#endif // QT_NO_TABWIDGET

#endif // QTABWIDGET_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTabWidget Member List

Complete Member List for QTabWidget

This is the complete list of member functions for QTabWidget, including inherited members.

  • QTabWidget()
  • acceptDrops()
  • addTab()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • changeTab()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • count()
  • create()
  • currentChanged()
  • currentPage()
  • currentPageIndex()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertTab()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTabEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • label()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • page()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removePage()
  • removeTabToolTip()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCurrentPage()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabBar()
  • setTabEnabled()
  • setTabIconSet()
  • setTabLabel()
  • setTabOrder()
  • setTabPosition()
  • setTabShape()
  • setTabToolTip()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showPage()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabBar()
  • tabIconSet()
  • tabLabel()
  • tabPosition()
  • tabShape()
  • tabToolTip()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QTextBrowser Class

QTextBrowser Class Reference

The QTextBrowser class provides a rich text browser with hypertext navigation. More...

#include <qtextbrowser.h>

Inherits QTextEdit.

List of all member functions.

Public Members

  • QTextBrowser ( QWidget * parent = 0, const char * name = 0 )
  • QString source () const

Public Slots

  • virtual void setSource ( const QString & name )
  • virtual void backward ()
  • virtual void forward ()
  • virtual void home ()
  • virtual void reload ()

Signals

  • void backwardAvailable ( bool available )
  • void forwardAvailable ( bool available )
  • void highlighted ( const QString & href )
  • void linkClicked ( const QString & link )

Properties

  • QString source - the name of the currently displayed document

Protected Members

  • virtual void keyPressEvent ( QKeyEvent * e )

Detailed Description

The QTextBrowser class provides a rich text browser with hypertext navigation.

This class extends QTextEdit (in read-only mode), adding some navigation functionality so that users can follow links in hypertext documents. The contents of QTextEdit is set with setText(), but QTextBrowser has an additional function, setSource(), which makes it possible to set the text to a named document. The name is looked up in the text view's mime source factory. If a document name ends with an anchor (for example, "#anchor"), the text browser automatically scrolls to that position (using scrollToAnchor()). When the user clicks on a hyperlink, the browser will call setSource() itself, with the link's href value as argument.

QTextBrowser provides backward() and forward() slots which you can use to implement Back and Forward buttons. The home() slot sets the text to the very first document displayed. The linkClicked() signal is emitted when the user clicks a link.

By using QTextEdit::setMimeSourceFactory() you can provide your own subclass of QMimeSourceFactory. This makes it possible to access data from anywhere, for example from a network or from a database. See QMimeSourceFactory::data() for details.

If you intend using the mime factory to read the data directly from the file system, you may have to specify the encoding for the file extension you are using. For example:

  mimeSourceFactory()->setExtensionType("qml", "text/utf8");
This is to ensure that the factory is able to resolve the document names.

If you want to provide your users with editable rich text use QTextEdit. If you want a text browser without hypertext navigation use QTextEdit, and use QTextEdit::setReadOnly() to disable editing. If you just need to display a small piece of rich text use QSimpleRichText or QLabel.

See also Advanced Widgets, Help System and Text Related Classes.

Member Function Documentation

QTextBrowser::QTextBrowser ( QWidget * parent = 0, const char * name = 0 )

Constructs an empty QTextBrowser with parent parent called name.

void QTextBrowser::backward () [virtual slot]

Changes the document displayed to the previous document in the list of documents built by navigating links. Does nothing if there is no previous document.

See also forward() and backwardAvailable().

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::backwardAvailable ( bool available ) [signal]

This signal is emitted when the availability of the backward() changes. available is FALSE when the user is at home(); otherwise it is TRUE.

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::forward () [virtual slot]

Changes the document displayed to the next document in the list of documents built by navigating links. Does nothing if there is no next document.

See also backward() and forwardAvailable().

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::forwardAvailable ( bool available ) [signal]

This signal is emitted when the availability of the forward() changes. available is TRUE after the user navigates backward() and FALSE when the user navigates or goes forward().

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::highlighted ( const QString & href ) [signal]

This signal is emitted when the user has selected but not activated a link in the document. href is the value of the href tag in the link.

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::home () [virtual slot]

Changes the document displayed to be the first document the browser displayed.

Example: helpviewer/helpwindow.cpp.

void QTextBrowser::keyPressEvent ( QKeyEvent * e ) [virtual protected]

The event e is used to provide the following keyboard shortcuts:
  • Alt+Left Arrow - backward()
  • Alt+Right Arrow - forward()
  • Alt+Up Arrow - home()

Reimplemented from QTextEdit.

void QTextBrowser::linkClicked ( const QString & link ) [signal]

This signal is emitted when the user clicks a link. The link is the value of the href i.e. the name of the target document.

void QTextBrowser::reload () [virtual slot]

Reloads the current set source

void QTextBrowser::setSource ( const QString & name ) [virtual slot]

Sets the name of the currently displayed document to name. See the "source" property for details.

QString QTextBrowser::source () const

Returns the name of the currently displayed document. See the "source" property for details.

Property Documentation

QString source

This property holds the name of the currently displayed document.

This is a null string if no document is displayed or the source is unknown.

Setting this property uses the mimeSourceFactory to lookup the named document. It also checks for optional anchors and scrolls the document accordingly.

If the first tag in the document is <qt type=detail>, the document is displayed as a popup rather than as new document in the browser window itself. Otherwise, the document is displayed normally in the text browser with the text set to the contents of the named document with setText().

If you are using the filesystem access capabilities of the mime source factory, you must ensure that the factory knows about the encoding of specified files; otherwise no data will be available. The default factory handles a couple of common file extensions such as *.html and *.txt with reasonable defaults. See QMimeSourceFactory::data() for details.

Set this property's value with setSource() and get this property's value with source().

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


qtextbrowser.h Include File

qtextbrowser.h

This is the verbatim text of the qtextbrowser.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtextbrowser.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the QTextBrowser class
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTBROWSER_H
#define QTEXTBROWSER_H

#ifndef QT_H
#include "qptrlist.h"
#include "qpixmap.h"
#include "qscrollview.h"
#include "qcolor.h"
#include "qtextedit.h"
#endif // QT_H

#ifndef QT_NO_TEXTBROWSER

class QTextBrowserData;

class Q_EXPORT QTextBrowser : public QTextEdit
{
    Q_OBJECT
    Q_PROPERTY( QString source READ source WRITE setSource )

public:
    QTextBrowser( QWidget* parent=0, const char* name=0 );
    ~QTextBrowser();

    QString source() const;

public slots:
    virtual void setSource(const QString& name);
    virtual void backward();
    virtual void forward();
    virtual void home();
    virtual void reload();
    void setText( const QString &txt ) { setText( txt, QString::null ); }
    virtual void setText( const QString &txt, const QString &context );

signals:
    void backwardAvailable( bool );
    void forwardAvailable( bool );
    void highlighted( const QString& );
    void linkClicked( const QString& );

protected:
    void keyPressEvent( QKeyEvent * e);

private:
    void popupDetail( const QString& contents, const QPoint& pos );
    bool linksEnabled() const { return TRUE; }
    void emitHighlighted( const QString &s ) { emit highlighted( s ); }
    void emitLinkClicked( const QString &s ) { emit linkClicked( s ); }
    QTextBrowserData *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTextBrowser( const QTextBrowser & );
    QTextBrowser& operator=( const QTextBrowser & );
#endif
};

#endif // QT_NO_TEXTBROWSER

#endif // QTEXTBROWSER_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTextBrowser Member List

Complete Member List for QTextBrowser

This is the complete list of member functions for QTextBrowser, including inherited members.

  • QTextBrowser()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • alignment()
  • anchorAt()
  • append()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • backward()
  • backwardAvailable()
  • baseSize()
  • blockSignals()
  • bold()
  • bottomMargin()
  • caption()
  • center()
  • charAt()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearParagraphBackground()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • color()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • context()
  • contextMenuEvent()
  • copy()
  • copyAvailable()
  • cornerWidget()
  • create()
  • createPopupMenu()
  • currentAlignmentChanged()
  • currentColorChanged()
  • currentFontChanged()
  • currentVerticalAlignmentChanged()
  • cursor()
  • cursorPositionChanged()
  • customEvent()
  • customWhatsThis()
  • cut()
  • del()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doKeyboardAction()
  • documentTitle()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureCursorVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • family()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • forward()
  • forwardAvailable()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getCursorPosition()
  • getSelection()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasSelectedText()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • highlighted()
  • home()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indent()
  • inherits()
  • insert()
  • insertAt()
  • insertChild()
  • insertParagraph()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isModified()
  • isOverwriteMode()
  • isPopup()
  • isReadOnly()
  • isRedoAvailable()
  • isTopLevel()
  • isUndoAvailable()
  • isUndoRedoEnabled()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • italic()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • length()
  • lineOfChar()
  • lineWidth()
  • lines()
  • linesOfParagraph()
  • linkClicked()
  • linkUnderline()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • mimeSourceFactory()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • modificationChanged()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveCursor()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • paper()
  • paragraphAt()
  • paragraphBackgroundColor()
  • paragraphLength()
  • paragraphRect()
  • paragraphs()
  • parent()
  • parentWidget()
  • paste()
  • pasteSubType()
  • placeCursor()
  • pointSize()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • redoAvailable()
  • releaseKeyboard()
  • releaseMouse()
  • reload()
  • removeChild()
  • removeEventFilter()
  • removeParagraph()
  • removeSelectedText()
  • removeSelection()
  • repaint()
  • repaintChanged()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • returnPressed()
  • rightMargin()
  • scroll()
  • scrollBy()
  • scrollToAnchor()
  • scrollToBottom()
  • selectAll()
  • selectedText()
  • selectionChanged()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBold()
  • setCaption()
  • setColor()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentFont()
  • setCursor()
  • setCursorPosition()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFamily()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItalic()
  • setKeyCompression()
  • setLineWidth()
  • setLinkUnderline()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMimeSourceFactory()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setModified()
  • setMouseTracking()
  • setName()
  • setOverwriteMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPaper()
  • setParagraphBackgroundColor()
  • setPointSize()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setSelection()
  • setSelectionAttributes()
  • setSizeIncrement()
  • setSizePolicy()
  • setSource()
  • setStaticBackground()
  • setStyle()
  • setStyleSheet()
  • setTabOrder()
  • setTabStopWidth()
  • setText()
  • setTextFormat()
  • setUnderline()
  • setUndoDepth()
  • setUndoRedoEnabled()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setVerticalAlignment()
  • setWFlags()
  • setWordWrap()
  • setWrapColumnOrWidth()
  • setWrapPolicy()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • source()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • styleSheet()
  • tabStopWidth()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • textCursor()
  • textFormat()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • underline()
  • undo()
  • undoAvailable()
  • undoDepth()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrap()
  • wrapColumnOrWidth()
  • wrapPolicy()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()
  • zoomIn()
  • zoomOut()
  • zoomTo()


QTextCodec Class

QTextCodec Class Reference

The QTextCodec class provides conversion between text encodings. More...

#include <qtextcodec.h>

Inherited by QEucJpCodec, QEucKrCodec, QGb18030Codec, QJisCodec, QHebrewCodec, QSjisCodec and QTsciiCodec.

List of all member functions.

Public Members

  • virtual ~QTextCodec ()
  • virtual const char * name () const = 0
  • virtual const char * mimeName () const
  • virtual int mibEnum () const = 0
  • virtual QTextDecoder * makeDecoder () const
  • virtual QTextEncoder * makeEncoder () const
  • virtual QString toUnicode ( const char * chars, int len ) const
  • virtual QCString fromUnicode ( const QString & uc, int & lenInOut ) const
  • QCString fromUnicode ( const QString & uc ) const
  • QString toUnicode ( const QByteArray & a, int len ) const
  • QString toUnicode ( const QByteArray & a ) const
  • QString toUnicode ( const QCString & a, int len ) const
  • QString toUnicode ( const QCString & a ) const
  • QString toUnicode ( const char * chars ) const
  • virtual bool canEncode ( QChar ch ) const
  • virtual bool canEncode ( const QString & s ) const
  • virtual int heuristicContentMatch ( const char * chars, int len ) const = 0
  • virtual int heuristicNameMatch ( const char * hint ) const

Static Public Members

  • QTextCodec * loadCharmap ( QIODevice * iod )
  • QTextCodec * loadCharmapFile ( QString filename )
  • QTextCodec * codecForMib ( int mib )
  • QTextCodec * codecForName ( const char * name, int accuracy = 0 )
  • QTextCodec * codecForContent ( const char * chars, int len )
  • QTextCodec * codecForIndex ( int i )
  • QTextCodec * codecForLocale ()
  • void setCodecForLocale ( QTextCodec * c )
  • void deleteAllCodecs ()
  • const char * locale ()

Protected Members

  • QTextCodec ()

Static Protected Members

  • int simpleHeuristicNameMatch ( const char * name, const char * hint )

Detailed Description

The QTextCodec class provides conversion between text encodings.

Qt uses Unicode to store, draw and manipulate strings. In many situations you may wish to deal with data that uses a different encoding. For example, most japanese documents are still stored in Shift-JIS or ISO2022, while Russian users often have their documents in KOI8-R or CP1251.

Qt provides a set of QTextCodec classes to help with converting non-Unicode formats to and from Unicode. You can also create your own codec classes (see later).

The supported encodings are:

  • Big5 -- Chinese
  • eucJP -- Japanese
  • eucKR -- Korean
  • GBK -- Chinese
  • JIS7 -- Japanese
  • Shift-JIS -- Japanese
  • TSCII -- Tamil
  • utf8 -- Unicode, 8-bit
  • utf16 -- Unicode
  • KOI8-R -- Russian
  • KOI8-U -- Ukrainian
  • ISO8859-1 -- Western
  • ISO8859-2 -- Central European
  • ISO8859-3 -- Central European
  • ISO8859-4 -- Baltic
  • ISO8859-5 -- Cyrillic
  • ISO8859-6 -- Arabic
  • ISO8859-7 -- Greek
  • ISO8859-8 -- Hebrew, visually ordered
  • ISO8859-8-i -- Hebrew, logically ordered
  • ISO8859-9 -- Turkish
  • ISO8859-10
  • ISO8859-13
  • ISO8859-14
  • ISO8859-15 -- Western
  • CP850
  • CP874
  • CP1250 -- Central European
  • CP1251 -- Cyrillic
  • CP1252 -- Western
  • CP1253 -- Greek
  • CP1254 -- Turkish
  • CP1255 -- Hebrew
  • CP1256 -- Arabic
  • CP1257 -- Baltic
  • CP1258
  • Apple Roman
  • TIS-620 -- Thai

QTextCodecs can be used as follows to convert some locally encoded string to Unicode. Suppose you have some string encoded in Russian KOI8-R encoding, and want to convert it to Unicode. The simple way to do this is:

  QCString locallyEncoded = "..."; // text to convert
  QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); // get the codec for KOI8-R
  QString unicodeString = codec->toUnicode( locallyEncoded );

After this, unicodeString holds the text converted to Unicode. Converting a string from Unicode to the local encoding is just as easy:

  QString unicodeString = "..."; // any Unicode text
  QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); // get the codec for KOI8-R
  QCString locallyEncoded = codec->fromUnicode( unicodeString );

Some care must be taken when trying to convert the data in chunks, for example, when receiving it over a network. In such cases it is possible that a multi-byte character will be split over two chunks. At best this might result in the loss of a character and at worst cause the entire conversion to fail.

The approach to use in these situations is to create a QTextDecoder object for the codec and use this QTextDecoder for the whole decoding process, as shown below:

  QTextCodec *c = QTextCodec::codecForName( "Shift-JIS" );
  QTextDecoder *decoder = c->makeDecoder();

  QString unicodeString;
  while( receiving_data ) {
      QByteArray chunk = new_data;
      unicodeString += decoder->toUnicode( chunk.data(), chunk.length() );
  }

The QTextDecoder object maintains state between chunks and therefore works correctly even if a multi-byte character is split between chunks.

Creating your own Codec class

By making objects of subclasses of QTextCodec, support for new text encodings can be added to Qt.

More recently created QTextCodec objects take precedence over earlier ones.

You may find it more convenient to make your codec class available as a plugin; see the plugin documentation for more details.

The abstract virtual functions describe the encoder to the system and the coder is used as required in the different text file formats supported by QTextStream, and under X11, for the locale-specific character input and output.

To add support for another 8-bit encoding to Qt, make a subclass of QTextCodec and implement at least the following methods:

   const char* name() const
Return the official name for the encoding.

   int mibEnum() const
Return the MIB enum for the encoding if it is listed in the IANA character-sets encoding file.

If the encoding is multi-byte then it will have "state"; that is, the interpretation of some bytes will be dependent on some preceding bytes. For such encodings, you must implement:

   QTextDecoder* makeDecoder() const
Return a QTextDecoder that remembers incomplete multi-byte sequence prefixes or other required state.

If the encoding does not require state, you should implement:

   QString toUnicode(const char* chars, int len) const
Converts len characters from chars to Unicode.

The base QTextCodec class has default implementations of the above two functions, but they are mutually recursive, so you must re-implement at least one of them, or both for improved efficiency.

For conversion from Unicode to 8-bit encodings, it is rarely necessary to maintain state. However, two functions similar to the two above are used for encoding:

   QTextEncoder* makeEncoder() const
Return a QTextDecoder.

   QCString fromUnicode(const QString& uc, int& lenInOut ) const
Converts lenInOut characters (of type QChar) from the start of the string uc, returning a QCString result, and also returning the length of the result in lenInOut.

Again, these are mutually recursive so only one needs to be implemented, or both if greater efficiency is possible.

Finally, you must implement:

   int heuristicContentMatch(const char* chars, int len) const
Gives a value indicating how likely it is that len characters from chars are in the encoding.

A good model for this function is the QWindowsLocalCodec::heuristicContentMatch function found in the Qt sources.

A QTextCodec subclass might have improved performance if you also re-implement:

   bool canEncode( QChar ) const
Test if a Unicode character can be encoded.

   bool canEncode( const QString& ) const
Test if a string of Unicode characters can be encoded.

   int heuristicNameMatch(const char* hint) const
Test if a possibly non-standard name is referring to the codec.

Codecs can also be created as plugins.

See also Internationalization with Qt.

Member Function Documentation

QTextCodec::QTextCodec () [protected]

Constructs a QTextCodec, and gives it the highest precedence. The QTextCodec should always be constructed on the heap (i.e. with new()), and once constructed it becomes the responsibility of Qt to delete it (which is done at QApplication destruction).

QTextCodec::~QTextCodec () [virtual]

Destroys the QTextCodec. Note that you should not delete codecs yourself: once created they become Qt's responsibility.

bool QTextCodec::canEncode ( QChar ch ) const [virtual]

Returns TRUE if the unicode character ch can be fully encoded with this codec; otherwise returns FALSE. The default implementation tests if the result of toUnicode(fromUnicode(ch)) is the original ch. Subclasses may be able to improve the efficiency.

bool QTextCodec::canEncode ( const QString & s ) const [virtual]

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

s contains the string being tested for encode-ability.

QTextCodec * QTextCodec::codecForContent ( const char * chars, int len ) [static]

Searches all installed QTextCodec objects, returning the one which most recognizes the given content. May return 0.

Note that this is often a poor choice, since character encodings often use most of the available character sequences, and so only by linguistic analysis could a true match be made.

chars contains the string to check, and len contains the number of characters in the string to use.

See also heuristicContentMatch().

Example: qwerty/qwerty.cpp.

QTextCodec * QTextCodec::codecForIndex ( int i ) [static]

Returns the QTextCodec i positions from the most recently inserted codec, or 0 if there is no such QTextCodec. Thus, codecForIndex(0) returns the most recently created QTextCodec.

Example: qwerty/qwerty.cpp.

QTextCodec * QTextCodec::codecForLocale () [static]

Returns a pointer to the codec most suitable for this locale.

Example: qwerty/qwerty.cpp.

QTextCodec * QTextCodec::codecForMib ( int mib ) [static]

Returns the QTextCodec which matches the MIBenum mib.

QTextCodec * QTextCodec::codecForName ( const char * name, int accuracy = 0 ) [static]

Searches all installed QTextCodec objects and returns the one which best matches name. Returns a null pointer if no codec's heuristicNameMatch() reports a match better than accuracy, or if name is a null string.

See also heuristicNameMatch().

void QTextCodec::deleteAllCodecs () [static]

Deletes all the created codecs.

Warning: Do not call this function.

QApplication calls this just before exiting, to delete any QTextCodec objects that may be lying around. Since various other classes hold pointers to QTextCodec objects, it is not safe to call this function earlier.

If you are using the utility classes (like QString) but not using QApplication, calling this function at the very end of your application can be helpful to chase down memory leaks, as QTextCodec objects will not show up.

QCString QTextCodec::fromUnicode ( const QString & uc, int & lenInOut ) const [virtual]

Subclasses of QTextCodec must reimplement either this function or makeEncoder(). It converts the first lenInOut characters of uc from Unicode to the encoding of the subclass. If lenInOut is negative or too large, the length of uc is used instead.

Converts lenInOut characters (not bytes) from uc, producing a QCString. lenInOut will be set to the length of the result (in bytes).

The default implementation makes an encoder with makeEncoder() and converts the input with that. Note that the default makeEncoder() implementation makes an encoder that simply calls this function, hence subclasses must reimplement one function or the other to avoid infinite recursion.

Reimplemented in QHebrewCodec.

QCString QTextCodec::fromUnicode ( const QString & uc ) const

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

uc is the unicode source string.

int QTextCodec::heuristicContentMatch ( const char * chars, int len ) const [pure virtual]

Subclasses of QTextCodec must reimplement this function. It examines the first len bytes of chars and returns a value indicating how likely it is that the string is a prefix of text encoded in the encoding of the subclass. A negative return value indicates that the text is detectably not in the encoding (e.g. it contains characters undefined in the encoding). A return value of 0 indicates that the text should be decoded with this codec rather than as ASCII, but there is no particular evidence. The value should range up to len. Thus, most decoders will return -1, 0, or -len.

The characters are not null terminated.

See also codecForContent().

int QTextCodec::heuristicNameMatch ( const char * hint ) const [virtual]

Returns a value indicating how likely it is that this decoder is appropriate for decoding some format that has the given name. The name is compared with the hint.

A good match returns a positive number around the length of the string. A bad match is negative.

The default implementation calls simpleHeuristicNameMatch() with the name of the codec.

QTextCodec * QTextCodec::loadCharmap ( QIODevice * iod ) [static]

Reads a POSIX2 charmap definition from iod. The parser recognizes the following lines:

<code_set_name> name
<escape_char> character
% alias alias
CHARMAP
<token> /xhexbyte <Uunicode> ...
<token> /ddecbyte <Uunicode> ...
<token> /octbyte <Uunicode> ...
<token> /any/any... <Uunicode> ...
END CHARMAP

The resulting QTextCodec is returned (and also added to the global list of codecs). The name() of the result is taken from the code_set_name.

Note that a codec constructed in this way uses much more memory and is slower than a hand-written QTextCodec subclass, since tables in code are in memory shared by all applications simultaneously using Qt.

See also loadCharmapFile().

Example: qwerty/qwerty.cpp.

QTextCodec * QTextCodec::loadCharmapFile ( QString filename ) [static]

A convenience function for loadCharmap() that loads the charmap definition from the file filename.

const char * QTextCodec::locale () [static]

Returns a string representing the current language.

Example: i18n/main.cpp.

QTextDecoder * QTextCodec::makeDecoder () const [virtual]

Creates a QTextDecoder which stores enough state to decode chunks of char* data to create chunks of Unicode data. The default implementation creates a stateless decoder, which is sufficient for only the simplest encodings where each byte corresponds to exactly one Unicode character.

The caller is responsible for deleting the returned object.

QTextEncoder * QTextCodec::makeEncoder () const [virtual]

Creates a QTextEncoder which stores enough state to encode chunks of Unicode data as char* data. The default implementation creates a stateless encoder, which is sufficient for only the simplest encodings where each Unicode character corresponds to exactly one character.

The caller is responsible for deleting the returned object.

int QTextCodec::mibEnum () const [pure virtual]

Subclasses of QTextCodec must reimplement this function. It returns the MIBenum (see the IANA character-sets encoding file for more information). It is important that each QTextCodec subclass returns the correct unique value for this function.

Reimplemented in QEucJpCodec.

const char * QTextCodec::mimeName () const [virtual]

Returns the preferred mime name of the encoding as defined in the IANA character-sets encoding file.

Reimplemented in QEucJpCodec, QEucKrCodec, QGbkCodec, QJisCodec, QHebrewCodec and QSjisCodec.

const char * QTextCodec::name () const [pure virtual]

Subclasses of QTextCodec must reimplement this function. It returns the name of the encoding supported by the subclass. When choosing a name for an encoding, consider these points:

  • On X11, heuristicNameMatch( const char * hint ) is used to test if a the QTextCodec can convert between Unicode and the encoding of a font with encoding hint, such as "iso8859-1" for Latin-1 fonts, "koi8-r" for Russian KOI8 fonts. The default algorithm of heuristicNameMatch() uses name().
  • Some applications may use this function to present encodings to the end user.

Example: qwerty/qwerty.cpp.

void QTextCodec::setCodecForLocale ( QTextCodec * c ) [static]

Set the codec to c; this will be returned by codecForLocale(). This might be needed for some applications that want to use their own mechanism for setting the locale.

See also codecForLocale().

int QTextCodec::simpleHeuristicNameMatch ( const char * name, const char * hint ) [static protected]

A simple utility function for heuristicNameMatch(): it does some very minor character-skipping so that almost-exact matches score high. name is the text we're matching and hint is used for the comparison.

QString QTextCodec::toUnicode ( const char * chars, int len ) const [virtual]

Subclasses of QTextCodec must reimplement this function or makeDecoder(). It converts the first len characters of chars to Unicode.

The default implementation makes a decoder with makeDecoder() and converts the input with that. Note that the default makeDecoder() implementation makes a decoder that simply calls this function, hence subclasses must reimplement one function or the other to avoid infinite recursion.

QString QTextCodec::toUnicode ( const QByteArray & a, int len ) const

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

a contains the source characters; len contains the number of characters in a to use.

QString QTextCodec::toUnicode ( const QByteArray & a ) const

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

a contains the source characters.

QString QTextCodec::toUnicode ( const QCString & a, int len ) const

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

a contains the source characters; len contains the number of characters in a to use.

QString QTextCodec::toUnicode ( const QCString & a ) const

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

a contains the source characters.

QString QTextCodec::toUnicode ( const char * chars ) const

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

chars contains the source characters.

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


qtextcodec.h Include File

qtextcodec.h

This is the verbatim text of the qtextcodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtextcodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTextCodec class
**
** Created : 981015
**
** Copyright (C) 1998-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTCODEC_H
#define QTEXTCODEC_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_TEXTCODEC

class QTextCodec;
class QIODevice;
class QFont;

class Q_EXPORT QTextEncoder {
public:
    virtual ~QTextEncoder();
    virtual QCString fromUnicode(const QString& uc, int& lenInOut) = 0;
};

class Q_EXPORT QTextDecoder {
public:
    virtual ~QTextDecoder();
    virtual QString toUnicode(const char* chars, int len) = 0;
};

class Q_EXPORT QTextCodec {
public:
    virtual ~QTextCodec();

#ifndef QT_NO_CODECS
    static QTextCodec* loadCharmap(QIODevice*);
    static QTextCodec* loadCharmapFile(QString filename);
#endif //QT_NO_CODECS
    static QTextCodec* codecForMib(int mib);
    static QTextCodec* codecForName(const char* hint, int accuracy=0);
    static QTextCodec* codecForContent(const char* chars, int len);
    static QTextCodec* codecForIndex(int i);
    static QTextCodec* codecForLocale();
    static void setCodecForLocale(QTextCodec *c);

    static void deleteAllCodecs();

    static const char* locale();

    virtual const char* name() const = 0;
    virtual const char* mimeName() const;
    virtual int mibEnum() const = 0;

    virtual QTextDecoder* makeDecoder() const;
    virtual QTextEncoder* makeEncoder() const;

    virtual QString toUnicode(const char* chars, int len) const;
    virtual QCString fromUnicode(const QString& uc, int& lenInOut) const;

    QCString fromUnicode(const QString& uc) const;
    QString toUnicode(const QByteArray&, int len) const;
    QString toUnicode(const QByteArray&) const;
    QString toUnicode(const QCString&, int len) const;
    QString toUnicode(const QCString&) const;
    QString toUnicode(const char* chars) const;
    virtual bool canEncode( QChar ) const;
    virtual bool canEncode( const QString& ) const;

    virtual int heuristicContentMatch(const char* chars, int len) const = 0;
    virtual int heuristicNameMatch(const char* hint) const;

    virtual QByteArray fromUnicode(const QString& uc, int from, int len) const;
    virtual unsigned short characterFromUnicode(const QString &str, int pos) const;

protected:
    QTextCodec();
    static int simpleHeuristicNameMatch(const char* name, const char* hint);

    friend class QFont;
};
#endif // QT_NO_TEXTCODEC
#endif // QTEXTCODEC_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTextCodec Member List

Complete Member List for QTextCodec

This is the complete list of member functions for QTextCodec, including inherited members.

  • QTextCodec()
  • ~QTextCodec()
  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QTextCodecPlugin Class

QTextCodecPlugin Class Reference

The QTextCodecPlugin class provides an abstract base for custom QTextCodec plugins. More...

#include <qtextcodecplugin.h>

List of all member functions.

Public Members

  • QTextCodecPlugin ()
  • ~QTextCodecPlugin ()
  • virtual QStringList names () const = 0
  • virtual QTextCodec * createForName ( const QString & name ) = 0
  • virtual QValueList<int> mibEnums () const = 0
  • virtual QTextCodec * createForMib ( int mib ) = 0

Detailed Description

The QTextCodecPlugin class provides an abstract base for custom QTextCodec plugins.

The text codec plugin is a simple plugin interface that makes it easy to create custom text codecs that can be loaded dynamically into applications.

Writing a text codec plugin is achieved by subclassing this base class, reimplementing the pure virtual functions names(), createForName(), mibEnums() and createForMib(), and exporting the class with the Q_EXPORT_PLUGIN macro. See the Qt Plugins documentation for details.

See the IANA character-sets encoding file for more information on mime names and mib enums.

See also Plugins.

Member Function Documentation

QTextCodecPlugin::QTextCodecPlugin ()

Constructs a text codec plugin. This is invoked automatically by the Q_EXPORT_PLUGIN macro.

QTextCodecPlugin::~QTextCodecPlugin ()

Destroys the text codec plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

QTextCodec * QTextCodecPlugin::createForMib ( int mib ) [pure virtual]

Creates a QTextCodec object for the mib enum mib.

(See the IANA character-sets encoding file for more information)

See also mibEnums().

QTextCodec * QTextCodecPlugin::createForName ( const QString & name ) [pure virtual]

Creates a QTextCodec object for the codec called name.

See also names().

QValueList<int> QTextCodecPlugin::mibEnums () const [pure virtual]

Returns the list of mib enums this plugin supports.

See also createForMib().

QStringList QTextCodecPlugin::names () const [pure virtual]

Returns the list of mime names this plugin supports.

See also createForName().

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


qtextcodecplugin.h Include File

qtextcodecplugin.h

This is the verbatim text of the qtextcodecplugin.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtextcodecplugin.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTextCodecPlugin class
**
** Created : 010920
**
** Copyright (C) 2001 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTCODECPLUGIN_H
#define QTEXTCODECPLUGIN_H

#ifndef QT_H
#include "qgplugin.h"
#include "qstringlist.h"
#endif // QT_H

#ifndef QT_NO_TEXTCODECPLUGIN
class QTextCodec;
class QTextCodecPluginPrivate;

class Q_EXPORT QTextCodecPlugin : public QGPlugin
{
    Q_OBJECT
public:
    QTextCodecPlugin();
    ~QTextCodecPlugin();

    virtual QStringList names() const = 0;
    virtual QTextCodec *createForName( const QString &name ) = 0;

    virtual QValueList<int> mibEnums() const = 0;
    virtual QTextCodec *createForMib( int mib ) = 0;

private:
    QTextCodecPluginPrivate *d;
};
#endif // QT_NO_TEXTCODECPLUGIN
#endif // QTEXTCODECPLUGIN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTextCodecPlugin Member List

Complete Member List for QTextCodecPlugin

This is the complete list of member functions for QTextCodecPlugin, including inherited members.

  • QTextCodecPlugin()
  • ~QTextCodecPlugin()
  • createForMib()
  • createForName()
  • mibEnums()
  • names()


QTextDecoder Class

QTextDecoder Class Reference

The QTextDecoder class provides a state-based decoder. More...

#include <qtextcodec.h>

List of all member functions.

Public Members

  • virtual ~QTextDecoder ()
  • virtual QString toUnicode ( const char * chars, int len ) = 0

Detailed Description

The QTextDecoder class provides a state-based decoder.

The decoder converts a text format into Unicode, remembering any state that is required between calls.

See also QTextCodec::makeEncoder() and Internationalization with Qt.

Member Function Documentation

QTextDecoder::~QTextDecoder () [virtual]

Destroys the decoder.

QString QTextDecoder::toUnicode ( const char * chars, int len ) [pure virtual]

Converts the first len bytes in chars to Unicode, returning the result.

If not all characters are used (e.g. if only part of a multi-byte encoding is at the end of the characters), the decoder remembers enough state to continue with the next call to this function.

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


QTextDecoder Member List

Complete Member List for QTextDecoder

This is the complete list of member functions for QTextDecoder, including inherited members.

  • ~QTextDecoder()
  • toUnicode()


QTextDrag Class

QTextDrag Class Reference

The QTextDrag class is a drag and drop object for transferring plain and Unicode text. More...

#include <qdragobject.h>

Inherits QDragObject.

List of all member functions.

Public Members

  • QTextDrag ( const QString & text, QWidget * dragSource = 0, const char * name = 0 )
  • QTextDrag ( QWidget * dragSource = 0, const char * name = 0 )
  • ~QTextDrag ()
  • virtual void setText ( const QString & text )
  • virtual void setSubtype ( const QCString & st )

Static Public Members

  • bool canDecode ( const QMimeSource * e )
  • bool decode ( const QMimeSource * e, QString & str )
  • bool decode ( const QMimeSource * e, QString & str, QCString & subtype )

Detailed Description

The QTextDrag class is a drag and drop object for transferring plain and Unicode text.

Plain text is passed in a QString which may contain multiple lines (i.e. may contain newline characters).

Qt provides no built-in mechanism for delivering only a single-line.

For more information about drag and drop, see the QDragObject class and the drag and drop documentation.

See also Drag And Drop Classes.

Member Function Documentation

QTextDrag::QTextDrag ( const QString & text, QWidget * dragSource = 0, const char * name = 0 )

Constructs a text drag object and sets its data to text. dragSource must be the drag source; name is the object name.

QTextDrag::QTextDrag ( QWidget * dragSource = 0, const char * name = 0 )

Constructs a default text drag object. dragSource must be the drag source; name is the object name.

QTextDrag::~QTextDrag ()

Destroys the text drag object and frees up all allocated resources.

bool QTextDrag::canDecode ( const QMimeSource * e ) [static]

Returns TRUE if the information in e can be decoded into a QString; otherwise returns FALSE.

See also decode().

Example: iconview/simple_dd/main.cpp.

bool QTextDrag::decode ( const QMimeSource * e, QString & str ) [static]

Attempts to decode the dropped information in e into str. Returns TRUE if successful; otherwise returns FALSE.

See also canDecode().

Example: iconview/simple_dd/main.cpp.

bool QTextDrag::decode ( const QMimeSource * e, QString & str, QCString & subtype ) [static]

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

Attempts to decode the dropped information in e into str. Returns TRUE if successful; otherwise returns FALSE. If subtype is null, any text subtype is accepted; otherwise only the specified subtype is accepted.

See also canDecode().

void QTextDrag::setSubtype ( const QCString & st ) [virtual]

Sets the MIME subtype of the text being dragged to st. The default subtype is "plain", so the default MIME type of the text is "text/plain". You might use this to declare that the text is "text/html" by calling setSubtype("html").

void QTextDrag::setText ( const QString & text ) [virtual]

Sets the text to be dragged to text. You will need to call this if you did not pass the text during construction.

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


QTextDrag Member List

Complete Member List for QTextDrag

This is the complete list of member functions for QTextDrag, including inherited members.

  • QTextDrag()
  • ~QTextDrag()
  • blockSignals()
  • canDecode()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • decode()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setName()
  • setPixmap()
  • setProperty()
  • setSubtype()
  • setText()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()


QTextEdit类

QTextEdit类参考

QTextEdit窗口部件提供了强大的单页面的多信息文本编辑器。 详情请见……

#include <qtextedit.h>

继承了QScrollView。

被QMultiLineEdit、QTextBrowser和QTextView继承。

所有成员函数的列表。

公有成员

  • enum WordWrap { NoWrap, WidgetWidth, FixedPixelWidth, FixedColumnWidth }
  • enum WrapPolicy { AtWordBoundary, Anywhere, AtWhiteSpace = AtWordBoundary }
  • enum KeyboardAction { ActionBackspace, ActionDelete, ActionReturn, ActionKill }
  • enum CursorAction { MoveBackward, MoveForward, MoveWordBackward, MoveWordForward, MoveUp, MoveDown, MoveLineStart, MoveLineEnd, MoveHome, MoveEnd, MovePgUp, MovePgDown }
  • enum VerticalAlignment { AlignNormal, AlignSuperScript, AlignSubScript }
  • QTextEdit ( const QString & text, const QString & context = QString::null, QWidget * parent = 0, const char * name = 0 )
  • QTextEdit ( QWidget * parent = 0, const char * name = 0 )
  • QString text () const
  • QString text ( int para ) const
  • TextFormat textFormat () const
  • QString context () const
  • QString documentTitle () const
  • void getSelection ( int * paraFrom, int * indexFrom, int * paraTo, int * indexTo, int selNum = 0 ) const
  • virtual bool find ( const QString & expr, bool cs, bool wo, bool forward = TRUE, int * para = 0, int * index = 0 )
  • int paragraphs () const
  • int lines () const
  • int linesOfParagraph ( int para ) const
  • int lineOfChar ( int para, int index )
  • int length () const
  • QRect paragraphRect ( int para ) const
  • int paragraphAt ( const QPoint & pos ) const
  • int charAt ( const QPoint & pos, int * para ) const
  • int paragraphLength ( int para ) const
  • QStyleSheet * styleSheet () const
  • QMimeSourceFactory * mimeSourceFactory () const
  • QBrush paper () const
  • bool linkUnderline () const
  • virtual int heightForWidth ( int w ) const
  • bool hasSelectedText () const
  • QString selectedText () const
  • bool isUndoAvailable () const
  • bool isRedoAvailable () const
  • WordWrap wordWrap () const
  • int wrapColumnOrWidth () const
  • WrapPolicy wrapPolicy () const
  • int tabStopWidth () const
  • QString anchorAt ( const QPoint & pos )
  • bool isReadOnly () const
  • void getCursorPosition ( int * para, int * index ) const
  • bool isModified () const
  • bool italic () const
  • bool bold () const
  • bool underline () const
  • QString family () const
  • int pointSize () const
  • QColor color () const
  • QFont font () const
  • int alignment () const
  • int undoDepth () const
  • bool isOverwriteMode () const
  • QColor paragraphBackgroundColor ( int para ) const
  • bool isUndoRedoEnabled () const

公有槽

  • virtual void setMimeSourceFactory ( QMimeSourceFactory * factory )
  • virtual void setStyleSheet ( QStyleSheet * styleSheet )
  • virtual void scrollToAnchor ( const QString & name )
  • virtual void setPaper ( const QBrush & pap )
  • virtual void setLinkUnderline ( bool )
  • virtual void setWordWrap ( WordWrap mode )
  • virtual void setWrapColumnOrWidth ( int )
  • virtual void setWrapPolicy ( WrapPolicy policy )
  • virtual void copy ()
  • virtual void append ( const QString & text )
  • void setText ( const QString & txt )
  • virtual void setText ( const QString & text, const QString & context )
  • virtual void setTextFormat ( TextFormat f )
  • virtual void selectAll ( bool select = TRUE )
  • virtual void setTabStopWidth ( int ts )
  • virtual void zoomIn ( int range )
  • virtual void zoomIn ()
  • virtual void zoomOut ( int range )
  • virtual void zoomOut ()
  • virtual void zoomTo ( int size )
  • virtual void setReadOnly ( bool b )
  • virtual void undo ()
  • virtual void redo ()
  • virtual void cut ()
  • virtual void paste ()
  • virtual void pasteSubType ( const QCString & subtype )
  • virtual void clear ()
  • virtual void del ()
  • virtual void indent ()
  • virtual void setItalic ( bool b )
  • virtual void setBold ( bool b )
  • virtual void setUnderline ( bool b )
  • virtual void setFamily ( const QString & fontFamily )
  • virtual void setPointSize ( int s )
  • virtual void setColor ( const QColor & c )
  • virtual void setVerticalAlignment ( VerticalAlignment a )
  • virtual void setAlignment ( int a )
  • virtual void setCursorPosition ( int para, int index )
  • virtual void setSelection ( int paraFrom, int indexFrom, int paraTo, int indexTo, int selNum = 0 )
  • virtual void setSelectionAttributes ( int selNum, const QColor & back, bool invertText )
  • virtual void setModified ( bool m )
  • virtual void setUndoDepth ( int d )
  • virtual void ensureCursorVisible ()
  • virtual void placeCursor ( const QPoint & pos, QTextCursor * c = 0 )
  • virtual void moveCursor ( CursorAction action, bool select )
  • virtual void doKeyboardAction ( KeyboardAction action )
  • virtual void removeSelectedText ( int selNum = 0 )
  • virtual void removeSelection ( int selNum = 0 )
  • virtual void setCurrentFont ( const QFont & f )
  • virtual void setOverwriteMode ( bool b )
  • virtual void scrollToBottom ()
  • virtual void insert ( const QString & text, bool indent = FALSE, bool checkNewLine = TRUE, bool removeSelected = TRUE )
  • virtual void insertAt ( const QString & text, int para, int index )
  • virtual void removeParagraph ( int para )
  • virtual void insertParagraph ( const QString & text, int para )
  • virtual void setParagraphBackgroundColor ( int para, const QColor & bg )
  • virtual void clearParagraphBackground ( int para )
  • virtual void setUndoRedoEnabled ( bool b )

信号

  • void textChanged ()
  • void selectionChanged ()
  • void copyAvailable ( bool yes )
  • void undoAvailable ( bool yes )
  • void redoAvailable ( bool yes )
  • void currentFontChanged ( const QFont & f )
  • void currentColorChanged ( const QColor & c )
  • void currentAlignmentChanged ( int a )
  • void currentVerticalAlignmentChanged ( VerticalAlignment a )
  • void cursorPositionChanged ( QTextCursor * c )
  • void cursorPositionChanged ( int para, int pos )
  • void returnPressed ()
  • void modificationChanged ( bool m )

属性

  • QString documentTitle - 从文本中分析出的文档标题 （只读）
  • bool hasSelectedText - 是否有文本被选择到选择区0中 （只读）
  • int length - 文本的字符数 （只读）
  • bool linkUnderline - 超文本链接是否使用下划线
  • bool modified - 文档是否已经被用户修改
  • bool overwriteMode - 文本编辑的覆盖模式
  • QBrush paper - 背景（纸）的画刷
  • bool readOnly - 文本编辑是否只读
  • QString selectedText - 被选择的文本（在选择区0中）或者如果当前没有被选择的文本（在选择区0中）就是空字符串 （只读）
  • int tabStopWidth - tab stop的象素宽度s
  • QString text - 文本编辑的文本
  • TextFormat textFormat - 文本格式：多信息文本、一般文本或者自动文本
  • int undoDepth - 撤销历史的深度
  • bool undoRedoEnabled - 撤销/恢复是否生效
  • WordWrap wordWrap - 自动换行模式
  • int wrapColumnOrWidth - 被自动换行的文本的位置（根据自动换行模式来决定是像素还是列）
  • WrapPolicy wrapPolicy - 自动换行策略，在空白符号还是在任何地方

保护成员

  • void repaintChanged ()
  • virtual void keyPressEvent ( QKeyEvent * e )
  • virtual bool focusNextPrevChild ( bool n )
  • QTextCursor * textCursor () const
  • virtual QPopupMenu * createPopupMenu ( const QPoint & pos )
  • virtual QPopupMenu * createPopupMenu () (obsolete)

详细描述

QTextEdit窗口部件提供了强大的单页面的多信息文本编辑器。

  • 介绍和概念
  • 使用QTextEdit作为一个显示窗口部件
    • 只读的键绑定
  • 使用QTextEdit作为一个编辑器
    • 编辑键绑定

介绍和概念

QTextEdit是一个高级的所见即所得的支持使用HTML风格标记的多信息文本格式的查看器/编辑器。它对于处理大文档和快速相应用户的输入进行了优化。

QTextEdit操作的三个模式：

模式 | 命令 | 注释
一般文本编辑器 | setTextFormat(PlainText) | 使用setText()设置文本，text()可以返回一般文本。文本属性（比如颜色）可以被设置，但是一般文本总是被返回。1.
多信息文本编辑器 | setTextFormat(RichText) | 使用setText()设置文本，text()可以返回多信息文本。多信息文本编辑是相当受限制的。例如你不能设置边白或者插入图片（尽管你可以读取并且正确地显示具有边白和包含图片的文件）。这个模式对于编辑少量的多信息文本是非常有用的。2.
文本查看器3. | setReadOnly(TRUE) | 使用setText()或append()（这个没有撤销历史，所以更快并且使用更少的内存）来设置文本，text()根据textFormat()返回一般文本或者多信息文本。这个模式可以正确显示HTML中一个比较大的子集。

1.我们不建议使用QTextEdit来创建语法高亮的编辑器，因为现在的应用编程接口对于这个目的是不够的。我们希望能在以后的发行中发行一个支持语法高亮的更加完整的应用编程接口。

2.在稍后的Qt发行中计划推出一个更完整的支持设置边白、图片等等的应用编程接口。

3.Qt 3.1将提供一个日志浏览器模式，它是专门为快速地并且有效使用内存地显示大量的只读文本而优化的。

我们建议你总是调用setTextFormat()来设置你想使用的模式。如果你是用AutoText，那么setText()和append()将会试图决定给定的文本是一般文本还是多信息文本。如果你使用RichText，那么setText()和append()总是假设给定的文本是多信息文本。insert()简单的插入给定的文本。

QTextEdit在段落和字符上工作。段落就是被自动换行来适应窗口部件的宽度的被格式化的字符串。默认情况下当读取一般文本时，两个换行符确定一个段落。一个文档由零或更多个段落组成，索引从0开始。字符是基于每一个段落来被索引的，也是从0开始。段落中的单字根据段落的alignment()进行对齐。段落被硬换行分隔。段落中的字符都有自己的属性，例如字体和颜色。

文本编辑文档使用如下概念：

  • 当前格式 -- 这是当前光标位置的格式，如果存在被选择文本，也是它的格式。
  • 当前段落 -- 包含光标的段落。

QTextEdit可以显示图片（使用QMimeSourceFactory）、列表和表格。如果文本太大以至于不能在文本编辑的视口中查看时，滚动条将会出现。文本编辑可以载入一般文本和HTML文件（HTML3.2和4的子集）。表现风格和有效标记集由styleSheet()来定义。自定义标记可以被创建并且被放置到样式单中。可以使用setStyleSheet()改变样式单，具体情况请参考QStyleSheet。通过图片标记识别的图片如果它们可以被使用文本编辑的QMimeSourceFactory解释的话就可以被显示，请参考setMimeSourceFactory()。

如果你想要一个有更多导航的文本浏览器，请使用QTextBrowser。如果你只是想显示一小条多信息文本，请使用QLabel或者QSimpleRichText。

如果你创建一个新的QTextEdit并且想允许用户编辑多信息文本，请调用setTextFormat(Qt::RichText)来确保文本被看做多信息文本。（多信息文本使用HTML标记来设置文本格式属性。关于被支持的HTML标记的信息请参考QStyleSheet。）如果你不明确地调用setTextFormat()，文本编辑将会猜测文本自己是多信息文本还是一般文本。这也就是说如果文本看起来像HTML或XML，它可能被解释为多信息文本，所以你应该调用setTextFormat(Qt::PlainText)来保护这些文本。

注意我们并不是要为Qt添加一个具有所有特征的网页浏览器窗口部件（因为这将很容易使Qt的大小加倍并且只有很少的应用程序可以从这里受益）。Qt中的多信息文本支持是被设计为应用程序提供一个快速、可移植并且有效率地方式来添加合理的在线帮助工具，并且提供一个多信息文本编辑器的基础。

使用QTextEdit作为一个显示窗口部件

QTextEdit可以显示一个包括表格和图片的大的HTML子集。

文本通过使用setText()来设置或者替换，它删除任何已经存在的文本并且用传递给setText()调用的文本替换它。如果你使用继承HTML（强制使用setTextFormat(RichText)）调用setText()，并且然后调用text()，返回的文本可能有不同的标签，但是它们呈现的都是一样的。文本可以使用insert()、paste()、pasteSubType()和append()来插入。被添加的文本没有进入撤销历史中，这使得append()更快并且消耗更少的内存。文本也可以被cut()。整个文本可以使用clear()来被删除并且被选择的文本可以使用removeSelectedText()来被删除。被选择（被标记）的文本也可以使用del()来被删除（如果没有文本被选择，这将删除光标右面的字符）。

可以使用setText()和text()来达到载入和保存文本的目的，例如：

    QFile file( fileName ); // 从文件中读取文本
    if ( file.open( IO_ReadOnly ) ) {
        QTextStream ts( &file );
        textEdit->setText( ts.read() );
    }

    QFile file( fileName ); // 把文本写入到文件中
    if ( file.open( IO_WriteOnly ) ) {
        QTextStream ts( &file );
        ts << textEdit->text();
        textEdit->setModified( FALSE );
    }

默认这个文本编辑会在空白符号处自动换行来适应文本编辑窗口部件。setWordWrap()函数用来指定你想要的自动换行方式，或者如果你不像要任何自动换行，请使用NoWrap。调用setWordWrap()来设置固定的像素宽度FixedPixelWidth，或者由setWrapColumnOrWidth()确定的像素或者列数的字符列数（例如80列）FixedColumnWidth。如果你是用自动换行来适应窗口部件的宽度WidgetWidth，你可以使用setWrapPolicy()来指定是在空白符号或者任何地方自动换行。

背景色的设置与其它窗口部件不同，使用setPaper()。你可以指定画刷风格是一个普通颜色或者一个复杂的像素映射。

超文本链接可以自动加上下划线，这个可以通过setLinkUnderline()来改变。tab stop宽度可以使用setTabStopWidth()来设置。

zoomIn()和zoomOut()函数能够用来通过增加（对于zoomOut()是减少）使用的点的大小来重新定义文本的大小。

lines()函数返回文本中的行数并且paragraphs()返回段落数。特定段落中的函数可以通过linesOfParagraph()返回。整个文本的字符长度可以通过length()返回。

你可以滚动到文本中的一个锚，也就是通过scrollToAnchor()到达<a name="anchor">。find()函数可以被用来找到和选择文本中的给定字符串。

只读的QTextEdit提供了和（废弃的）QTextEdit相同的功能。（QTextView仍被提供用来保证旧代码的兼容性。）

只读的键绑定

当QTextEdit被使用的时候，只读的键绑定仅限于浏览，并且文本只能被鼠标选定：

按键 | 操作
UpArrow | 向上移动一行
DownArrow | 向下移动一行
LeftArrow | 向左移动一个字符
RightArrow | 向右移动一个字符
PageUp | 向上移动一页（视口）
PageDown | 向下移动一页（视口）
Home | 移动到文本开始处
End | 移动到文本结束处
Shift+Wheel | 水平的滚动文本（Wheel就是鼠标滚轮）
Ctrl+Wheel | 缩放文本

文本编辑也可以提供一些元信息。例如，documentTitle()函数将返回来自HTML的<title>标签中的文本。

文本编辑中显示的文本有一个context。context就是文本编辑的QMimeSourceFactory用来解析文件和图片的定位的路径。当查询数据时，它被传递给mimeSourceFactory()。（请参考See QTextEdit()和context()。）

使用QTextEdit作为一个编辑器

使用QTextEdit作为显示窗口部件的所有信息这里也适用。

当前格式属性可以通过setItalic()、setBold()、setUnderline()、setFamily()（字体族）、setPointSize()、setColor()和setCurrentFont()来设置。当前段落的对齐方式使用setAlignment()来设置。

使用setSelection()来选择文本。setSelectionAttributes()函数用来指出被选择文本应该如何被显示。使用hasSelectedText()来搜索是否有任何文本被选择。当前被选择文本的位置可以由getSelection()提供并且被选择文本本身被selectedText()返回。选择可以使用copy()来复制到剪贴板，或者使用cut()剪切到剪贴板中。它可以被removeSelectedText()删除。使用selectAll()可以选择（或者取消选择）整个文本。QTextEdit支持多重选择。绝大多数选择函数是在默认选择（选择区0）中操作。如果用户按下非选择键，例如没有按下Shift的情况下的一个光标键，所有选择都被清空。

使用setCursorPosition()和getCursorPosition()可以分别设置和获得光标的位置。当光标被移动，信号currentFontChanged()、currentColorChanged()和currentAlignmentChanged()被发射来影响新光标位置的字体、颜色和对齐方式。

如果文本改变了，textChanged()信号被发射，并且如果用户通过按下回车键或者换行键插入一个新行，returnPressed()被发射。如果文本已经被修改，isModified()函数将会返回真。

QTextEdit提供基于命令的撤销和恢复。使用setUndoDepth()可以设置命令历史的深度，默认为100步。调用undo()或redo()可以撤销或者恢复上一次操作。信号undoAvailable()和redoAvailable()表明撤销和恢复操作是否可以被执行。

indent()函数用来再次缩进一个段落。它对于代码编辑器是很有用的，例如，Qt设计器的代码编辑器中，Ctrl+I调用indent()函数。

编辑键绑定

编辑中被实现的键绑定的列表：

按键 | 操作
Backspace | 删除光标左侧的字符
Delete | 删除光标右侧的字符
Ctrl+A | 移动光标到行首
Ctrl+B | 向左移动光标一个字符
Ctrl+C | 复制标定的文本到剪贴板（也就是Windows下的Ctrl+Insert）
Ctrl+D | 删除光标右侧的字符
Ctrl+E | 移动光标到行尾
Ctrl+F | 向右移动光标一个字符
Ctrl+H | 删除光标左侧的字符
Ctrl+K | 删除到行尾
Ctrl+N | 移动光标到下一行
Ctrl+P | 移动光标到上一行
Ctrl+V | 把剪贴板文本粘贴到行编辑中（也就是Windows下的Shift+Insert）
Ctrl+X | 剪切标定的文本，复制到剪贴板（也就是Windows下的Shift+Delete）
Ctrl+Z | 撤销最后一次操作
Ctrl+Y | 恢复最后一次操作
LeftArrow | 向左移动光标一个字符
Ctrl+LeftArrow | 向左移动光标一个单字
RightArrow | 向右移动光标一个字符
Ctrl+RightArrow | 向右移动光标一个单字
UpArrow | 移动光标到上一行
Ctrl+UpArrow | 移动光标到上一个单字
DownArrow | 移动光标到下一行
Ctrl+Down Arrow | 移动光标到下一个单字
PageUp | 移动光标到上一页
PageDown | 移动光标到下一页
Home | 移动光标到行首
Ctrl+Home | 移动光标到文首
End | 移动光标到行尾
Ctrl+End | 移动光标到文尾
Shift+Wheel | 水平的滚动文本（Wheel就是鼠标滚轮）
Ctrl+Wheel | 缩放文本

要选择（标定）文本，按下一个移动键的同时按住Shift键，例如Shift+右箭头将会选择右面的字符，并且Shift+Ctrl+右箭头将会选择右面的单字，等等。

默认情况下，文本编辑窗口部件在插入模式下工作，所以用户输入的文本都被插入到文本编辑中并且光标右面的文本都会移动到不碍事的地方。使用setOverwriteMode()，这个模式可以被改为覆盖，这时新文本将覆盖光标右面存在的任何文本。

也可以参考基本窗口部件和文本相关类。

成员类型文档

QTextEdit::CursorAction

这个枚举变量被moveCursor()使用，它用来指定光标应该被移动的方向：

  • QTextEdit::MoveBackward - 向后移动光标一个字符
  • QTextEdit::MoveWordBackward - 向后移动光标一个单字
  • QTextEdit::MoveForward - 向前移动光标一个字符
  • QTextEdit::MoveWordForward - 向前移动光标一个单字
  • QTextEdit::MoveUp - 向上移动光标一行
  • QTextEdit::MoveDown - 向下移动光标一行
  • QTextEdit::MoveLineStart - 移动光标到行首
  • QTextEdit::MoveLineEnd - 移动光标到行尾
  • QTextEdit::MoveHome - 移动光标到文首
  • QTextEdit::MoveEnd - 移动光标到文尾
  • QTextEdit::MovePgUp - 向上移动光标一页
  • QTextEdit::MovePgDown - 向下移动光标一页

QTextEdit::KeyboardAction

这个枚举变量被doKeyboardAction()使用，它用来指定哪个操作被执行：

  • QTextEdit::ActionBackspace - 删除光标左面的字符。
  • QTextEdit::ActionDelete - 删除光标右面的字符。
  • QTextEdit::ActionReturn - 在光标位置分割段落。
  • QTextEdit::ActionKill - 如果光标不在段尾，从光标位置删除字符，直到段尾。如果光标在段尾，删除段尾的硬回车符——这将会导致这个段落和随后的段落被连接在一起。

QTextEdit::VerticalAlignment

这个枚举变量被用来设置文本的垂直对齐方式。

  • QTextEdit::AlignNormal - 普通对齐
  • QTextEdit::AlignSuperScript - 上标
  • QTextEdit::AlignSubScript - 下标

QTextEdit::WordWrap

这个枚举变量定义了QTextEdit的自动换行模式。下面这些值是有效的：

  • QTextEdit::NoWrap - 不自动换行。
  • QTextEdit::WidgetWidth - 在窗口部件的当前宽度自动换行（这是默认的）。默认在空白符号处自动换行，这可以使用setWrapPolicy()来改变。
  • QTextEdit::FixedPixelWidth - 从窗口部件的左侧开始的固定数量的象素数自动换行。象素的数量可以通过wrapColumnOrWidth()来设置。
  • QTextEdit::FixedColumnWidth - 从窗口部件左侧开始的固定数量的列数自动换行。列数可以通过wrapColumnOrWidth()设置。如果你需要使用等宽文本在设备上显示很好的格式文本，这是很有用的，例如标准的VT100终端，你可以把wrapColumnOrWidth()设置为80。

也可以参考wordWrap和wordWrap。

QTextEdit::WrapPolicy

这个枚举变量定义了自动换行模式在哪里自动换行。

下面这些值是有效的：

  • QTextEdit::AtWhiteSpace - 在空白符号处（空格或者换行）自动换行。
  • QTextEdit::Anywhere - 在任何情况下自动换行，包括单字中。
  • QTextEdit::AtWordBoundary - 不要使用这个不赞成的值（它是AtWhiteSpace的同义字，请使用后者替换它）。

也可以参考wrapPolicy。

成员函数文档

QTextEdit::QTextEdit ( const QString & text, const QString & context = QString::null, QWidget * parent = 0, const char * name = 0 )

使用父对象parent和名称name构造一个QTextEdit。文本编辑将使用上下文context来显示文本text。

context是文本编辑的QMimeSourceFactory用来解析文件和图片的定位的路径。当查询数据时，它被传递给mimeSourceFactory()。

例如，如果文本包含一个文本标签<img src="image.png">，并且上下文为“path/to/look/in”，那么QMimeSourceFactory将会试图从“path/to/look/in/image.png”载入图片。如果标签为<img src="/image.png">，context将不会被使用（因为QMimeSourceFactory识别出了我们使用的是绝对路径）并且将会试图载入“/image.png”。context也可以正确的适用于hrefs，例如<a href="target.html">Target</a>，将会被识别为“path/to/look/in/target.html”。

QTextEdit::QTextEdit ( QWidget * parent = 0, const char * name = 0 )

使用父对象parent和名称name构造一个空的QTextEdit。

int QTextEdit::alignment () const

返回当前段落的对齐方式。

也可以参考setAlignment()。

QString QTextEdit::anchorAt ( const QPoint & pos )

如果在pos位置有一个锚（在内容坐标中），它的名称被返回，否则返回空字符串。

void QTextEdit::append ( const QString & text ) [虚 槽]

把文本text添加到文本编辑的结尾。注意这个函数会清空撤销/恢复历史。

实例：network/clientserver/client/client.cpp、network/clientserver/server/server.cpp、network/httpd/httpd.cpp和process/process.cpp。

bool QTextEdit::bold () const

如果当前格式是粗体的，返回真，否则返回假。

也可以参考setBold()。

int QTextEdit::charAt ( const QPoint & pos, int * para ) const

返回在pos位置（在内容坐标中）的字符的索引（相对于它的段落）。如果para不为零，*para被设置为当前段落。如果在pos没有字符，-1被返回。

void QTextEdit::clear () [虚 槽]

删除文本编辑中的所有文本。

也可以参考cut(), removeSelectedText()和text。

void QTextEdit::clearParagraphBackground ( int para ) [虚 槽]

清除para段落的背景色，所以背景色将再次被使用。

QColor QTextEdit::color () const

返回当前格式的颜色。

也可以参考setColor()和paper。

QString QTextEdit::context () const

返回编辑的context。context是文本编辑的QMimeSourceFactory用来解析文件和图片的定位的路径。

也可以参考text。

实例：helpviewer/helpwindow.cpp和qdir/qdir.cpp。

void QTextEdit::copy () [虚 槽]

复制任何选择文本（从选择区0中）到剪贴板。

也可以参考hasSelectedText和copyAvailable()。

void QTextEdit::copyAvailable ( bool yes ) [信号]

当文本编辑中的文本被选择或者取消选择时，这个信号被发射。

当文本被选择时，这个信号被发射，这时yes被设置为真。如果没有文本被选择或者如果被选择文本被取消选择，这个信号被发射，这时yes被设置为假。

如果yes为真，那么copy()可以被用来复制所选文本到剪贴板。如果yes为假，那么copy()什么也不做。

也可以参考selectionChanged()。

QPopupMenu * QTextEdit::createPopupMenu ( const QPoint & pos ) [虚 保护]

这个函数被用来在文档pos位置创建一个右键弹出菜单。如果你想创建一个自定义弹出菜单，重新实现这个函数并且返回被创建的弹出菜单。弹出菜单的所有权被传递给调用者。

QPopupMenu * QTextEdit::createPopupMenu () [虚 保护]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数被用来创建一个右键弹出菜单。如果你想创建一个自定义弹出菜单，重新实现这个函数并且返回被创建的弹出菜单。弹出菜单的所有权被传递给调用者。

这个函数只有在createPopupMenu( const QPoint & )返回0时才能被调用。

void QTextEdit::currentAlignmentChanged ( int a ) [信号]

如果当前段落的对齐方式已经改变时，这个信号被发射。

新的对齐方式是a。

也可以参考setAlignment()。

void QTextEdit::currentColorChanged ( const QColor & c ) [信号]

如果当前格式的颜色已经改变时，这个信号被发射。

新的颜色是c。

也可以参考setColor()。

void QTextEdit::currentFontChanged ( const QFont & f ) [信号]

如果当前格式的字体已经改变时，这个信号被发射。

新的字体是f。

也可以参考setCurrentFont()。

void QTextEdit::currentVerticalAlignmentChanged ( VerticalAlignment a ) [信号]

如果当前格式的垂直对齐方式已经改变时，这个信号被发射。

新的垂直对齐方式是a。

也可以参考setVerticalAlignment()。

void QTextEdit::cursorPositionChanged ( QTextCursor * c ) [信号]

如果光标位置发生改变，这个信号被发射。c指向文本光标对象。

也可以参考setCursorPosition()。

void QTextEdit::cursorPositionChanged ( int para, int pos ) [信号]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果光标位置发生改变，这个信号被发射。para包含段落索引并且pos包含段落中的字符位置。

也可以参考setCursorPosition()。

void QTextEdit::cut () [虚 槽]

复制被选择文本（从选择区0中）到剪贴板并且从文本编辑中删除它。

如果没有被选择文本（在选择区0中），就什么也不发生。

也可以参考QTextEdit::copy(), paste()和pasteSubType()。

void QTextEdit::del () [虚 槽]

如果有被选择文本（在选择区0中），它就被删除。如果没有被选择文本（在选择区0中），文本光标右面的字符被删除。

也可以参考removeSelectedText()和cut()。

void QTextEdit::doKeyboardAction ( KeyboardAction action ) [虚 槽]

执行键盘操作action。这通常被键盘事件处理器调用。

QString QTextEdit::documentTitle () const

返回从文本中解析的文档标题。详细情况请参考“documentTitle”属性。

void QTextEdit::ensureCursorVisible () [虚 槽]

如果需要，确保滚动文本编辑时光标是可视的。

也可以参考setCursorPosition()。

QString QTextEdit::family () const

返回当前格式的字体族。

也可以参考setFamily(), setCurrentFont()和setPointSize()。

bool QTextEdit::find ( const QString & expr, bool cs, bool wo, bool forward = TRUE, int * para = 0, int * index = 0 ) [虚]

找到字符串expr下一个出现位置。如果expr被找到，返回真，否则返回假。

如果para和index都为零，搜索将从当前光标位置开始。如果para和index全不为零，搜索将从*para段的*index字符位置开始。

如果cs为真，搜索是区分大小写的，否则它是不区分大小写的。如果wo为真，搜索将查找匹配整个单字的，否则它搜索任何匹配的文本。如果forward为真（默认），搜索将从开始位置到文尾进行工作，否则它从开始位置到文首进行工作。

如果expr被找到，函数返回真。如果index和para不为零，被找到的匹配项的第一个字符的段落号被放到*para，并且这个字符在段落中的索引位置被放到*index。

如果expr没有被找到，函数返回假。如果index和para不为零，并且expr没有被找到，*index和*para都是不确定的。

bool QTextEdit::focusNextPrevChild ( bool n ) [虚 保护]

重新实现用来允许链接间移动焦点。如果n为真，tab把焦点移动到下一个子对象，如果n为假，tab把焦点移动到上一个子对象。如果焦点被移动，返回真，否则返回假。

QFont QTextEdit::font () const

返回当前格式的字体。

也可以参考setCurrentFont(), setFamily()和setPointSize()。

实例：action/application.cpp、application/application.cpp、mdi/application.cpp和qwerty/qwerty.cpp。

void QTextEdit::getCursorPosition ( int * para, int * index ) const

这个函数设置*para和*index参数到当前光标位置。para和index必须为非空整形指针。

也可以参考setCursorPosition()。

void QTextEdit::getSelection ( int * paraFrom, int * indexFrom, int * paraTo, int * indexTo, int selNum = 0 ) const

如果有选择，*paraFrom被设置为选择开始的段落号并且*paraTo被设置为选择结束的段落号。（它们可以是相同的。）*indexFrom被设置为*paraFrom中选择的开始索引并且*indexTo被设置为*paraTo中选择的结束缩影。

如果没有选择，*paraFrom、*indexFrom、*paraTo和 *indexTo都被设置为-1。

paraFrom、indexFrom、paraTo和indexTo都必须为非空整形指针。

selNum是选择的数量（多重选择是被支持的）。它默认为0（默认选择）。

也可以参考setSelection()和selectedText。

bool QTextEdit::hasSelectedText () const

如果在选择区0中一些文本被选择，返回真，否则返回假。详细情况请参考“hasSelectedText”属性。

int QTextEdit::heightForWidth ( int w ) const [虚]

返回如果文本编辑有w象素宽，文本编辑需要有多少象素高才能显示所有文本。

从QWidget中被重新实现。

void QTextEdit::indent () [虚 槽]

重新缩进当前段落。

void QTextEdit::insert ( const QString & text, bool indent = FALSE, bool checkNewLine = TRUE, bool removeSelected = TRUE ) [虚 槽]

在当前光标位置插入text。如果indent为真，这个段落被重新缩进。如果checkNewLine为真，在text中的新行符导致真正的硬换行（也就是新的段落）。如果checkNewLine为假，text重的新行符的行为是不确定的。如果checkNewLine为假，如果text包含新行符，编辑器的行为是不确定的。如果removeSelected为真，任何被选择文本（在选择区0中）在文本被插入之前被移除。

也可以参考paste()和pasteSubType()。

void QTextEdit::insertAt ( const QString & text, int para, int index ) [虚 槽]

在para段落和index位置插入text。

void QTextEdit::insertParagraph ( const QString & text, int para ) [虚 槽]

在位置para插入text作为段落。如果para为-1，这些文本被追加。

bool QTextEdit::isModified () const

如果文档已经被用户修改，返回真，否则返回假。详细情况请参考“modified”属性。

bool QTextEdit::isOverwriteMode () const

返回文本编辑的覆盖模式。详细情况请参考“overwriteMode”属性。

bool QTextEdit::isReadOnly () const

如果文本编辑是只读的，返回真，否则返回假。详细情况请参考“readOnly”属性。

bool QTextEdit::isRedoAvailable () const

返回恢复是否可用。

bool QTextEdit::isUndoAvailable () const

返回撤销是否可用。

bool QTextEdit::isUndoRedoEnabled () const

如果撤销/恢复是生效的，返回真，否则返回假。详细情况请参考“undoRedoEnabled”属性。

bool QTextEdit::italic () const

如果当前格式是斜体的，返回真，否则返回假。

也可以参考setItalic()。

void QTextEdit::keyPressEvent ( QKeyEvent * e ) [虚 保护]

处理键盘事件e。默认情况，键盘事件是用来提供键盘导航和文本编辑的。

从QWidget中被重新实现。

在QTextBrowser中被重新实现。

int QTextEdit::length () const

返回文本中的字符数。详细情况请参考“length”属性。

int QTextEdit::lineOfChar ( int para, int index )

返回在para段落的index位置出现的字符在段落中的行数。index位置是相对于段首的位置。如果没有这个段落或者在index位置没有这样一个字符（也就是说索引超出范围），-1被返回。

int QTextEdit::lines () const

返回文本编辑中的行数，它可以为0。

警告： 这个函数也许比较慢。行数会在自动换行期间发生改变，所以这个函数不得不遍历所有的段落并且分别得到它们的行数。

实例：action/application.cpp和application/application.cpp。

int QTextEdit::linesOfParagraph ( int para ) const

返回para段落的行数，或者如果在para索引没有这个段落，返回-1。

bool QTextEdit::linkUnderline () const

如果超文本链接将显示下划线，返回真，否则返回假。详细情况请参考“linkUnderline”属性。

QMimeSourceFactory * QTextEdit::mimeSourceFactory () const

返回这个文档编辑当前使用的QMimeSourceFactory。

也可以参考setMimeSourceFactory()。

实例：helpviewer/helpwindow.cpp和qdir/qdir.cpp。

void QTextEdit::modificationChanged ( bool m ) [信号]

当文档修改发生改变时，这个信号被发射。如果m为真，文档被修改了，否则修改状态已经被重置为未修改。

也可以参考modified。

void QTextEdit::moveCursor ( CursorAction action, bool select ) [虚 槽]

根据action移动文本光标。这通常被一些键盘事件处理器使用。select指定从当前光标位置到新位置之间的文本是否应该被选定。

QBrush QTextEdit::paper () const

返回背景（纸）的画刷。详细情况请参考“paper”属性。

int QTextEdit::paragraphAt ( const QPoint & pos ) const

返回在pos位置（在内容坐标中）的段落，或者如果在pos索引没有段落，返回-1。

QColor QTextEdit::paragraphBackgroundColor ( int para ) const

返回para段落的背景色或者如果para超出范围或者这个段落没有背景设置，返回一个无效的颜色。

int QTextEdit::paragraphLength ( int para ) const

返回para段落的长度（字符数），或者如果para超出范围或者这个段落没有背景设置，返回-1。

QRect QTextEdit::paragraphRect ( int para ) const

返回para段落在内容坐标中的矩形，或者如果para超出范围，返回一个无效矩形。

int QTextEdit::paragraphs () const

返回文本中的段落数，它可以为0。

void QTextEdit::paste () [虚 槽]

把剪贴板中的文本粘贴到文本编辑的当前光标位置。只有一般文本能够被粘贴。

如果剪贴板中没有文本，就什么也没发生。

也可以参考pasteSubType(), cut()和QTextEdit::copy()。

void QTextEdit::pasteSubType ( const QCString & subtype ) [虚 槽]

把剪贴板中格式为subtype的文本粘贴到文本编辑的当前光标位置。subtype可以是“plain”或“html”。

如果剪贴板中没有subtype格式的文本，就什么也没发生。

也可以参考paste(), cut()和QTextEdit::copy()。

void QTextEdit::placeCursor ( const QPoint & pos, QTextCursor * c = 0 ) [虚 槽]

在离pos位置（在内容坐标中）最近的字符放置光标c。如果c为0，默认的文本光标被放置。

也可以参考setCursorPosition()。

int QTextEdit::pointSize () const

返回当前格式的字体的点的大小。

也可以参考setFamily(), setCurrentFont()和setPointSize()。

void QTextEdit::redo () [虚 槽]

恢复上一次操作。

如果没有操作可以恢复，例如，在撤销/恢复历史中没有恢复步骤，就什么也没发生。

也可以参考redoAvailable(), undo()和undoDepth。

void QTextEdit::redoAvailable ( bool yes ) [信号]

当恢复的可用性发生改变时，这个信号被发射。如果yes为真，那么redo()可以一直工作到redoAvailable( FALSE )被发射。

也可以参考redo()和undoDepth。

void QTextEdit::removeParagraph ( int para ) [虚 槽]

移除para段落。

void QTextEdit::removeSelectedText ( int selNum = 0 ) [虚 槽]

删除selNum（默认为0）选择区中的被选定文本（也就是默认选择的文本）。如果没有被选定文本，就什么也没发生。

也可以参考selectedText和removeSelection()。

void QTextEdit::removeSelection ( int selNum = 0 ) [虚 槽]

移除selNum（默认为0）选择区。这不会移除被选定文本。

也可以参考removeSelectedText()。

void QTextEdit::repaintChanged () [保护]

重新绘制任何已经改变的段落。

尽管在内部广泛地使用，但是你也不应该需要自己调用这个函数。

void QTextEdit::returnPressed () [信号]

如果用户按下回车键或者换行键，这个信号被发射。

void QTextEdit::scrollToAnchor ( const QString & name ) [虚 槽]

滚动文本编辑来使在被叫作name的锚的文本可视，如果它在文档中可以被发现的话。如果这个锚不能被找到，就没有滚动发生。锚是使用HTML锚标签，也就是<a name="target">定义的。

void QTextEdit::scrollToBottom () [虚 槽]

滚动到文本的底部并且如果需要就重新执行格式操作。

void QTextEdit::selectAll ( bool select = TRUE ) [虚 槽]

如果select为真（默认），所有的文本都被选择作为选择区0。如果select为假，所有的文本都被取消选择，也就是默认选择区（选择区0）被清空。

也可以参考selectedText。

QString QTextEdit::selectedText () const

返回被选定文本（从选择区0中）或者如果当前没有被选定文本（在选择区0中）返回空字符串。详细情况请参考“selectedText”属性。

void QTextEdit::selectionChanged () [信号]

只要选择发生改变，这个信号就被发射。

也可以参考setSelection()和copyAvailable()。

void QTextEdit::setAlignment ( int a ) [虚 槽]

设置当前段落的对齐方式为a。有效的对齐方式为Qt::AlignLeft、Qt::AlignRight、Qt::AlignJustify和Qt::AlignCenter（这个是水平中间）。

在QMultiLineEdit中被重新实现。

void QTextEdit::setBold ( bool b ) [虚 槽]

如果b为真，设置当前格式为粗体，否则设置当前格式为非粗体。

也可以参考bold()。

void QTextEdit::setColor ( const QColor & c ) [虚 槽]

设置当前格式的颜色，也就是文本的颜色，为c。

也可以参考color()和paper。

实例：action/actiongroup/editor.cpp。

void QTextEdit::setCurrentFont ( const QFont & f ) [虚 槽]

设置当前格式的字体为f。

也可以参考font(), setPointSize()和setFamily()。

void QTextEdit::setCursorPosition ( int para, int index ) [虚 槽]

设置光标到para段落的index位置。

也可以参考getCursorPosition()。

void QTextEdit::setFamily ( const QString & fontFamily ) [虚 槽]

设置当前格式的字体族为fontFamily。

也可以参考family()和setCurrentFont()。

void QTextEdit::setItalic ( bool b ) [虚 槽]

如果b为真，设置当前格式为斜体，否则设置当前格式为非斜体。

也可以参考italic()。

void QTextEdit::setLinkUnderline ( bool ) [虚 槽]

设置超文本链接是否显示下划线。详细情况请参考“linkUnderline”属性。

void QTextEdit::setMimeSourceFactory ( QMimeSourceFactory * factory ) [虚 槽]

设置文本编辑的mime源工厂为 factory。详细情况请参考QMimeSourceFactory。

也可以参考mimeSourceFactory()。

void QTextEdit::setModified ( bool m ) [虚 槽]

设置文档是否已经被用户修改为m。详细情况请参考“modified”属性。

void QTextEdit::setOverwriteMode ( bool b ) [虚 槽]

设置文本编辑的覆盖模式为b。详细情况请参考“overwriteMode”属性。

void QTextEdit::setPaper ( const QBrush & pap ) [虚 槽]

设置背景（纸）的画刷为pap。详细情况请参考“paper”属性。

void QTextEdit::setParagraphBackgroundColor ( int para, const QColor & bg ) [虚 槽]

设置para段落的背景色为bg。

void QTextEdit::setPointSize ( int s ) [虚 槽]

设置当前格式的点大小为s。

注意如果s为0或者负数，这个函数的行为是不确定的。

也可以参考pointSize(), setCurrentFont()和setFamily()。

void QTextEdit::setReadOnly ( bool b ) [虚 槽]

设置文本编辑是否只读为b。详细情况请参考“readOnly”属性。

void QTextEdit::setSelection ( int paraFrom, int indexFrom, int paraTo, int indexTo, int selNum = 0 ) [虚 槽]

设置一个选择从paraFrom段落的indexFrom位置开始，直到paraTo段落的indexTo位置结束。有不同id（selNum）的选择区不会被移除，有相同id（selNum）的选择区会被移除。

使用selNum选择区的选择设置。如果selNum为0，这个就是默任选择了。

如果selNum为0，光标被移动到这个选择的结尾，否则光标位置保持不变。

也可以参考getSelection()和selectedText。

void QTextEdit::setSelectionAttributes ( int selNum, const QColor & back, bool invertText ) [虚 槽]

设置selNum选择区的背景色为back并且指定这个选择区的文本是否应该被使用invertText反白。

这个只在selNum > 0的时候工作。默认选择（selNum == 0）从这个窗口部件的colorGroup()得到它的属性。

void QTextEdit::setStyleSheet ( QStyleSheet * styleSheet ) [虚 槽]

设置这个文本编辑使用的样式单为styleSheet。改变仅对通过setText()或append()新增的文本有效。

也可以参考styleSheet()。

void QTextEdit::setTabStopWidth ( int ts ) [虚 槽]

设置tab stop宽度为ts象素。详细情况请参考“tabStopWidth”属性。

void QTextEdit::setText ( const QString & txt ) [槽]

设置文本编辑的文本为txt。详细情况请参考“text”属性。

void QTextEdit::setText ( const QString & text, const QString & context ) [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

改变文本编辑的文本为txt并且上下文为context。任何以前的文本都被移除。

text可以被解释为一般文本或者多信息文本，取决于textFormat()。默认设置为AutoText，也就是说文本编辑从text中自动检测格式。

选项context就是文本编辑的QMimeSourceFactory用来解析文件和图片的定位的路径。（请参考QTextEdit::QTextEdit()。）当查询数据时，它被传递给mimeSourceFactory()。

注意这个函数会清空撤销/恢复历史。

也可以参考text和textFormat。

void QTextEdit::setTextFormat ( TextFormat f ) [虚 槽]

设置文本格式：多信息文本、一般文本或者自动文本为f。详细情况请参考“textFormat”属性。

void QTextEdit::setUnderline ( bool b ) [虚 槽]

如果b为真，设置当前格式是有下划线的，否则设置当前格式是没有下划线的。

也可以参考underline()。

void QTextEdit::setUndoDepth ( int d ) [虚 槽]

设置撤销历史的深度为d。详细情况请参考“undoDepth”属性。

void QTextEdit::setUndoRedoEnabled ( bool b ) [虚 槽]

设置撤销/恢复是否生效为b。详细情况请参考“undoRedoEnabled”属性。

void QTextEdit::setVerticalAlignment ( VerticalAlignment a ) [虚 槽]

设置当前格式的垂直对齐方式，也就是文本的，为a。

也可以参考color()和paper。

void QTextEdit::setWordWrap ( WordWrap mode ) [虚 槽]

设置自动换行模式为mode。详细情况请参考“wordWrap”属性。

void QTextEdit::setWrapColumnOrWidth ( int ) [虚 槽]

设置将被自动换行的文本的位置（根据自动换行模式决定是象素还是列数）。详细情况请参考“wrapColumnOrWidth”属性。

void QTextEdit::setWrapPolicy ( WrapPolicy policy ) [虚 槽]

设置自动换行策略，是在空白符号还是在任意处为policy。详细情况请参考“wrapPolicy”属性。

QStyleSheet * QTextEdit::styleSheet () const

返回文本编辑中当前使用的QStyleSheet。

也可以参考setStyleSheet()。

实例：helpviewer/helpwindow.cpp。

int QTextEdit::tabStopWidth () const

返回tab stop的象素宽度。详细情况请参考“tabStopWidth”属性。

QString QTextEdit::text () const

返回文本编辑的文本。详细情况请参考“text”属性。

QString QTextEdit::text ( int para ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回para段落的文本。

如果textFormat()为RichText，文本将包含HTML格式标签。

void QTextEdit::textChanged () [信号]

只要文本编辑中的文本发生改变，这个信号就被发射。

也可以参考text和append()。

实例：helpviewer/helpwindow.cpp、qwerty/qwerty.cpp和rot13/rot13.cpp。

QTextCursor * QTextEdit::textCursor () const [保护]

返回文本编辑的文本光标。

警告： QTextCursor不在公有的应用编程接口中，但在一些特殊环境中你也许需要使用它。

TextFormat QTextEdit::textFormat () const

返回文本格式：多信息文本、一般文本或者自动文本。详细情况请参考“textFormat”属性。

bool QTextEdit::underline () const

如果当前格式是有下划线的，返回真，否则返回假。

也可以参考setUnderline()。

void QTextEdit::undo () [虚 槽]

撤销上一次操作。

如果没有操作可以撤销，例如在撤销/恢复历史中没有撤销步骤，那就什么也没发生。

也可以参考undoAvailable(), redo()和undoDepth。

void QTextEdit::undoAvailable ( bool yes ) [信号]

当撤销的可能性发生变化时，这个信号被发射。如果yes为真，那么undo()将会一直工作到undoAvailable( FALSE )下一次被发射为止。

也可以参考undo()和undoDepth。

int QTextEdit::undoDepth () const

返回撤销历史的深度。详细情况请参考“undoDepth”属性。

WordWrap QTextEdit::wordWrap () const

返回自动换行模式。详细情况请参考“wordWrap”属性。

int QTextEdit::wrapColumnOrWidth () const

返回将被自动换行的文本的位置（根据自动换行模式决定是象素还是列数）。详细情况请参考“wrapColumnOrWidth”属性。

WrapPolicy QTextEdit::wrapPolicy () const

返回自动换行策略是在空白符号还是在任意处。详细情况请参考“wrapPolicy”属性。

void QTextEdit::zoomIn ( int range ) [虚 槽]

通过把基本字体大小增大range点并且重新计算所有字体大小来放大文本。这不会改变任何图片的大小。

也可以参考zoomOut()。

void QTextEdit::zoomIn () [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

通过把基本字体大小增大1点并且重新计算所有字体大小来放大文本。这不会改变任何图片的大小。

也可以参考zoomOut()。

void QTextEdit::zoomOut ( int range ) [虚 槽]

通过把基本字体大小缩小range点并且重新计算所有字体大小来放大文本。这不会改变任何图片的大小。

也可以参考zoomIn()。

void QTextEdit::zoomOut () [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

通过把基本字体大小缩小1点并且重新计算所有字体大小来放大文本。这不会改变任何图片的大小。

也可以参考zoomIn()。

void QTextEdit::zoomTo ( int size ) [虚 槽]

通过把基本字体大小变为size点并且重新计算所有字体大小来显示文本。这不会改变任何图片的大小。

属性文档

QString documentTitle

这个属性保存的是从文本中分析出的文档标题。

对于PlainText，标题将为空字符串。对于RichText，如果存在，标题将为<title>标签之间的文本，否则为空字符串。

通过documentTitle()来获得属性值。

bool hasSelectedText

这个属性保存的是是否有文本被选择到选择区0中。

通过hasSelectedText()来获得属性值。

int length

这个属性保存的是文本的字符数。

通过length()来获得属性值。

bool linkUnderline

这个属性保存的是超文本链接是否使用下划线。

如果为真（默认），超文本链接将被显示下划线。如果为假，链接将不被显示下划线。

通过setLinkUnderline()设置属性值并且通过linkUnderline()来获得属性值。

bool modified

这个属性保存的是文档是否已经被用户修改。

通过setModified()设置属性值并且通过isModified()来获得属性值。

bool overwriteMode

这个属性保存的是文本编辑的覆盖模式。

如果为真（默认），用户输入的文本都被插入到文本编辑中并且光标右面的文本都会移动到不碍事的地方。如果为假，编辑器是覆盖模式，也就是说新文本将覆盖光标右面存在的任何文本。

通过setOverwriteMode()设置属性值并且通过isOverwriteMode()来获得属性值。

QBrush paper

这个属性保存的是背景（纸）的画刷。

这个画刷是当前用于绘制文本编辑的背景的。初始设置是空画刷。

通过setPaper()设置属性值并且通过paper()来获得属性值。

bool readOnly

这个属性保存的是文本编辑是否只读。

在只读的文本编辑中，用户只能在文本中浏览和选择文本，修改文本是不可能的。

这个属性默认为假。

通过setReadOnly()设置属性值并且通过isReadOnly()来获得属性值。

QString selectedText

这个属性保存的是被选择的文本（在选择区0中）或者如果当前没有被选择的文本（在选择区0中）就是空字符串。

这个文本不管文本格式总是被作为PlainText返回。在Qt的未来的版本中，根据文本格式，HTML的子集可能被返回。

也可以参考hasSelectedText。

通过selectedText()来获得属性质。

int tabStopWidth

这个属性保存的是tab stop的象素宽度。

通过setTabStopWidth()设置属性值并且通过tabStopWidth()来获得属性值。

QString text

这个属性保存的是文本编辑的文本。

这里没有默认文本。

在设置的时候，任何以前的文本都被删除了。

根据textFormat()，文本可以被作为一般文本或者多信息文本来解释。默认设置为AutoText，也就是说文本编辑自动探测文本格式。

对于多信息文本，在可编辑的QTextEdit上调用text()将会导致文本会被文本编辑重新生成。这也许意味着被返回的QString也许和原来被设置的不同。

也可以参考textFormat。

通过setText()设置属性值并且通过text()来获得属性值。

TextFormat textFormat

这个属性保存的是文本格式：多信息文本、一般文本或者自动文本。

文本格式是下列之一：

  • PlainText - 所有的文本，除了新行符，包括空格都被逐字地显示。只要文本中出现一个新行符，文本编辑就插入一个硬换行并且开始一个新的段落。
  • RichText - 多信息文本表现。可用的样式在默认样式单QStyleSheet::defaultSheet()中定义。
  • AutoText - 这是默认值。文本编辑会自动探测哪一个表现样式更好，PlainText或RichText这个是通过使用QStyleSheet::mightBeRichText()函数完成的。

通过setTextFormat()设置属性值并且通过textFormat()来获得属性值。

int undoDepth

这个属性保存的是撤销历史的深度。

也就是撤销/恢复历史中的最大步数。默认为100。

也可以参考undo()和redo()。

通过setUndoDepth()设置属性值并且通过undoDepth()来获得属性值。

bool undoRedoEnabled

这个属性保存的是撤销/恢复是否生效。

默认为真。

通过setUndoRedoEnabled()设置属性值并且通过isUndoRedoEnabled()来得到属性值。

WordWrap wordWrap

这个属性保存的是自动换行模式。

默认模式是WidgetWidth，也就是在文本编辑右边缘的单字将被自动换行。在空白字符处自动换行，保证整个单字不被分割。如果你想在单字内自动换行，请使用setWrapPolicy()。如果你设置自动换行模式为FixedPixelWidth或者FixedColumnWidth，你也应该调用setWrapColumnOrWidth()你希望的宽度。

也可以参考WordWrap、wrapColumnOrWidth和wrapPolicy。

通过setWordWrap()设置属性值并且通过wordWrap()来获得属性值。

int wrapColumnOrWidth

这个属性保存的是被自动换行的文本的位置（根据自动换行模式来决定是像素还是列）。

如果自动换行模式为FixedPixelWidth，那么这个值就是从文本编辑左边界开始需要自动换行的象素数量。如果自动换行模式为FixedColumnWidth，那么这个值就是从文本编辑左边界开始需要自动换行的列数。

也可以参考wordWrap。

通过setWrapColumnOrWidth()设置属性值并且通过wrapColumnOrWidth()来获得属性值。

WrapPolicy wrapPolicy

这个属性保存的是自动换行策略，在空白符号还是在任何地方。

当自动换行模式不是NoWrap的时候，定义文本在哪里自动换行。可以选择的是AtWhiteSpace（默认）和Anywhere。

也可以参考wordWrap。

通过setWrapPolicy()设置属性值并且通过wrapPolicy()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtextedit.h包含文件

qtextedit.h

这里是qtextedit.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtextedit.h   3.0.5   edited Jun 11 11:18 $
**
** Definition of the QTextEdit class
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTEDIT_H
#define QTEXTEDIT_H

#ifndef QT_H
#include "qscrollview.h"
#include "qstylesheet.h"
#include "qptrvector.h"
#include "qvaluelist.h"
#endif // QT_H

#ifndef QT_NO_TEXTEDIT
class QPainter;
class QTextDocument;
class QTextCursor;
class QKeyEvent;
class QResizeEvent;
class QMouseEvent;
class QTimer;
class QTextString;
class QTextCommand;
class QTextParagraph;
class QTextFormat;
class QFont;
class QColor;
class QTextEdit;
class QTextBrowser;
class QTextString;
struct QUndoRedoInfoPrivate;
class QPopupMenu;
class QTextEditPrivate;

class Q_EXPORT QTextEdit : public QScrollView
{
    friend class QTextBrowser;

    Q_OBJECT
    Q_ENUMS( WordWrap WrapPolicy )
    Q_PROPERTY( TextFormat textFormat READ textFormat WRITE setTextFormat )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( QBrush paper READ paper WRITE setPaper )
    Q_PROPERTY( bool linkUnderline READ linkUnderline WRITE setLinkUnderline )
    Q_PROPERTY( QString documentTitle READ documentTitle )
    Q_PROPERTY( int length READ length )
    Q_PROPERTY( WordWrap wordWrap READ wordWrap WRITE setWordWrap )
    Q_PROPERTY( int wrapColumnOrWidth READ wrapColumnOrWidth WRITE setWrapColumnOrWidth )
    Q_PROPERTY( WrapPolicy wrapPolicy READ wrapPolicy WRITE setWrapPolicy )
    Q_PROPERTY( bool hasSelectedText READ hasSelectedText )
    Q_PROPERTY( QString selectedText READ selectedText )
    Q_PROPERTY( int undoDepth READ undoDepth WRITE setUndoDepth )
    Q_PROPERTY( bool overwriteMode READ isOverwriteMode WRITE setOverwriteMode )
    Q_PROPERTY( bool modified READ isModified WRITE setModified DESIGNABLE false )
    Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly )
    Q_PROPERTY( bool undoRedoEnabled READ isUndoRedoEnabled WRITE setUndoRedoEnabled )
    Q_PROPERTY( int tabStopWidth READ tabStopWidth WRITE setTabStopWidth )

public:
    enum WordWrap {
    NoWrap,
    WidgetWidth,
    FixedPixelWidth,
    FixedColumnWidth
    };

    enum WrapPolicy {
    AtWordBoundary,
    Anywhere,
    AtWhiteSpace = AtWordBoundary // deprecated, don't use
    };

    enum KeyboardAction {
    ActionBackspace,
    ActionDelete,
    ActionReturn,
    ActionKill
    };

    enum CursorAction {
    MoveBackward,
    MoveForward,
    MoveWordBackward,
    MoveWordForward,
    MoveUp,
    MoveDown,
    MoveLineStart,
    MoveLineEnd,
    MoveHome,
    MoveEnd,
    MovePgUp,
    MovePgDown
    };

    enum VerticalAlignment {
    AlignNormal,
    AlignSuperScript,
    AlignSubScript
    };

    QTextEdit( const QString& text, const QString& context = QString::null,
           QWidget* parent=0, const char* name=0);
    QTextEdit( QWidget* parent=0, const char* name=0 );
    virtual ~QTextEdit();
    void setPalette( const QPalette & );

    QString text() const;
    QString text( int para ) const;
    TextFormat textFormat() const;
    QString context() const;
    QString documentTitle() const;

    void getSelection( int *paraFrom, int *indexFrom,
            int *paraTo, int *indexTo, int selNum = 0 ) const;
    virtual bool find( const QString &expr, bool cs, bool wo, bool forward = TRUE,
               int *para = 0, int *index = 0 );

    int paragraphs() const;
    int lines() const;
    int linesOfParagraph( int para ) const;
    int lineOfChar( int para, int chr );
    int length() const;
    QRect paragraphRect( int para ) const;
    int paragraphAt( const QPoint &pos ) const;
    int charAt( const QPoint &pos, int *para ) const;
    int paragraphLength( int para ) const;

    QStyleSheet* styleSheet() const;
    QMimeSourceFactory* mimeSourceFactory() const;

    QBrush paper() const;
    bool linkUnderline() const;

    int heightForWidth( int w ) const;

    bool hasSelectedText() const;
    QString selectedText() const;
    bool isUndoAvailable() const;
    bool isRedoAvailable() const;

    WordWrap wordWrap() const;
    int wrapColumnOrWidth() const;
    WrapPolicy wrapPolicy() const;

    int tabStopWidth() const;

    QString anchorAt( const QPoint& pos );

    QSize sizeHint() const;

    bool isReadOnly() const { return readonly; }

    void getCursorPosition( int *parag, int *index ) const;

    bool isModified() const;
    bool italic() const;
    bool bold() const;
    bool underline() const;
    QString family() const;
    int pointSize() const;
    QColor color() const;
    QFont font() const;
    int alignment() const;
    int undoDepth() const;

    // do not use, will go away
    virtual bool getFormat( int para, int index, QFont *font, QColor *color, VerticalAlignment *verticalAlignment );
    // do not use, will go away
    virtual bool getParagraphFormat( int para, QFont *font, QColor *color,
                     VerticalAlignment *verticalAlignment, int *alignment,
                     QStyleSheetItem::DisplayMode *displayMode,
                     QStyleSheetItem::ListStyle *listStyle,
                     int *listDepth );

    bool isOverwriteMode() const { return overWrite; }
    QColor paragraphBackgroundColor( int para ) const;

    bool isUndoRedoEnabled() const;
    bool eventFilter( QObject *o, QEvent *e );

public slots:
    void setEnabled( bool );
    virtual void setMimeSourceFactory( QMimeSourceFactory* factory );
    virtual void setStyleSheet( QStyleSheet* styleSheet );
    virtual void scrollToAnchor( const QString& name );
    virtual void setPaper( const QBrush& pap );
    virtual void setLinkUnderline( bool );

    virtual void setWordWrap( WordWrap mode );
    virtual void setWrapColumnOrWidth( int );
    virtual void setWrapPolicy( WrapPolicy policy );

    virtual void copy();
    virtual void append( const QString& text );

    void setText( const QString &txt ) { setText( txt, QString::null ); }
    virtual void setText( const QString &txt, const QString &context );
    virtual void setTextFormat( TextFormat f );

    virtual void selectAll( bool select = TRUE );
    virtual void setTabStopWidth( int ts );
    virtual void zoomIn( int range );
    virtual void zoomIn() { zoomIn( 1 ); }
    virtual void zoomOut( int range );
    virtual void zoomOut() { zoomOut( 1 ); }
    virtual void zoomTo( int size );

    virtual void sync();
    virtual void setReadOnly( bool b );

    virtual void undo();
    virtual void redo();
    virtual void cut();
    virtual void paste();
#ifndef QT_NO_CLIPBOARD
    virtual void pasteSubType( const QCString &subtype );
#endif
    virtual void clear();
    virtual void del();
    virtual void indent();
    virtual void setItalic( bool b );
    virtual void setBold( bool b );
    virtual void setUnderline( bool b );
    virtual void setFamily( const QString &f );
    virtual void setPointSize( int s );
    virtual void setColor( const QColor &c );
    virtual void setFont( const QFont &f );
    virtual void setVerticalAlignment( VerticalAlignment a );
    virtual void setAlignment( int a );

    // do not use, will go away
    virtual void setParagType( QStyleSheetItem::DisplayMode dm, QStyleSheetItem::ListStyle listStyle );

    virtual void setCursorPosition( int parag, int index );
    virtual void setSelection( int parag_from, int index_from, int parag_to, int index_to, int selNum = 0 );
    virtual void setSelectionAttributes( int selNum, const QColor &back, bool invertText );
    virtual void setModified( bool m );
    virtual void resetFormat();
    virtual void setUndoDepth( int d );
    virtual void setFormat( QTextFormat *f, int flags );
    virtual void ensureCursorVisible();
    virtual void placeCursor( const QPoint &pos, QTextCursor *c = 0 );
    virtual void moveCursor( CursorAction action, bool select );
    virtual void doKeyboardAction( KeyboardAction action );
    virtual void removeSelectedText( int selNum = 0 );
    virtual void removeSelection( int selNum = 0 );
    virtual void setCurrentFont( const QFont &f );
    virtual void setOverwriteMode( bool b ) { overWrite = b; }

    virtual void scrollToBottom();

    virtual void insert( const QString &text, bool indent = FALSE, bool checkNewLine = TRUE, bool removeSelected = TRUE );
    virtual void insertAt( const QString &text, int para, int index );
    virtual void removeParagraph( int para );
    virtual void insertParagraph( const QString &text, int para );

    virtual void setParagraphBackgroundColor( int para, const QColor &bg );
    virtual void clearParagraphBackground( int para );

    virtual void setUndoRedoEnabled( bool b );

signals:
    void textChanged();
    void selectionChanged();
    void copyAvailable( bool );
    void undoAvailable( bool yes );
    void redoAvailable( bool yes );
    void currentFontChanged( const QFont &f );
    void currentColorChanged( const QColor &c );
    void currentAlignmentChanged( int a );
    void currentVerticalAlignmentChanged( VerticalAlignment a );
    void cursorPositionChanged( QTextCursor *c );
    void cursorPositionChanged( int para, int pos );
    void returnPressed();
    void modificationChanged( bool m );

protected:
    void repaintChanged();
    void updateStyles();
    void drawContents( QPainter *p, int cx, int cy, int cw, int ch );
    bool event( QEvent *e );
    void keyPressEvent( QKeyEvent *e );
    void resizeEvent( QResizeEvent *e );
    void viewportResizeEvent( QResizeEvent* );
    void contentsMousePressEvent( QMouseEvent *e );
    void contentsMouseMoveEvent( QMouseEvent *e );
    void contentsMouseReleaseEvent( QMouseEvent *e );
    void contentsMouseDoubleClickEvent( QMouseEvent *e );
#ifndef QT_NO_WHEELEVENT
    void contentsWheelEvent( QWheelEvent *e );
#endif
    void imStartEvent( QIMEvent * );
    void imComposeEvent( QIMEvent * );
    void imEndEvent( QIMEvent * );
#ifndef QT_NO_DRAGANDDROP
    void contentsDragEnterEvent( QDragEnterEvent *e );
    void contentsDragMoveEvent( QDragMoveEvent *e );
    void contentsDragLeaveEvent( QDragLeaveEvent *e );
    void contentsDropEvent( QDropEvent *e );
#endif
    void contentsContextMenuEvent( QContextMenuEvent *e );
    bool focusNextPrevChild( bool next );
    QTextDocument *document() const;
    QTextCursor *textCursor() const;
    void setDocument( QTextDocument *doc );
    virtual QPopupMenu *createPopupMenu( const QPoint& pos );
    virtual QPopupMenu *createPopupMenu();
    void drawCursor( bool visible );

    void windowActivationChange( bool );

protected slots:
    virtual void doChangeInterval();

private slots:
    void formatMore();
    void doResize();
    void autoScrollTimerDone();
    void blinkCursor();
    void setModified();
    void startDrag();
    void documentWidthChanged( int w );
    void clipboardChanged();

private:
    struct Q_EXPORT UndoRedoInfo {
    enum Type { Invalid, Insert, Delete, Backspace, Return, RemoveSelected, Format, Style };

    UndoRedoInfo( QTextDocument *dc );
    ~UndoRedoInfo();
    void clear();
    bool valid() const;

    QUndoRedoInfoPrivate *d;
    int id;
    int index;
    int eid;
    int eindex;
    QTextFormat *format;
    int flags;
    Type type;
    QTextDocument *doc;
    QByteArray styleInformation;
    };

private:
    void updateCursor( const QPoint & pos );
    void handleMouseMove( const QPoint& pos );
    void drawContents( QPainter * );
    virtual bool linksEnabled() const { return FALSE; }
    void init();
    void checkUndoRedoInfo( UndoRedoInfo::Type t );
    void updateCurrentFormat();
    bool handleReadOnlyKeyEvent( QKeyEvent *e );
    void makeParagVisible( QTextParagraph *p );
#ifndef QT_NO_MIME
    QCString pickSpecial(QMimeSource* ms, bool always_ask, const QPoint&);
#endif
#ifndef QT_NO_MIMECLIPBOARD
    void pasteSpecial(const QPoint&);
#endif
    void setFontInternal( const QFont &f );

    virtual void emitHighlighted( const QString & ) {}
    virtual void emitLinkClicked( const QString & ) {}

    void readFormats( QTextCursor &c1, QTextCursor &c2, QTextString &text, bool fillStyles = FALSE );
    void clearUndoRedo();
    void paintDocument( bool drawAll, QPainter *p, int cx = -1, int cy = -1, int cw = -1, int ch = -1 );
    void moveCursor( CursorAction action );
    void ensureFormatted( QTextParagraph *p );
    void placeCursor( const QPoint &pos, QTextCursor *c, bool link );
    void updateMicroFocusHint();

private:
    QTextDocument *doc;
    QTextCursor *cursor;
    QTimer *formatTimer, *scrollTimer, *changeIntervalTimer, *blinkTimer, *dragStartTimer;
    QTextParagraph *lastFormatted;
    int interval;
    UndoRedoInfo undoRedoInfo;
    QTextFormat *currentFormat;
    int currentAlignment;
    QPoint oldMousePos, mousePos;
    QPoint dragStartPos;
    QString onLink;
    WordWrap wrapMode;
    WrapPolicy wPolicy;
    int wrapWidth;
    QString pressedLink;
    QTextEditPrivate *d;
    bool inDoubleClick : 1;
    bool mousePressed : 1;
    bool cursorVisible : 1;
    bool blinkCursorVisible : 1;
    bool readOnly : 1;
    bool modified : 1;
    bool mightStartDrag : 1;
    bool inDnD : 1;
    bool readonly : 1;
    bool undoEnabled : 1;
    bool overWrite : 1;
};

inline QTextDocument *QTextEdit::document() const
{
    return doc;
}

inline QTextCursor *QTextEdit::textCursor() const
{
    return cursor;
}

inline void QTextEdit::setCurrentFont( const QFont &f )
{
    QTextEdit::setFontInternal( f );
}

#endif //QT_NO_TEXTEDIT
#endif //QTEXTVIEW_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextEdit成员列表

完整的QTextEdit成员列表

这里是QTextEdit成员函数的完整列表，包括继承的成员。

  • QTextEdit()
  • acceptDrops()
  • addChild()
  • adjustSize()
  • alignment()
  • anchorAt()
  • append()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bold()
  • bottomMargin()
  • caption()
  • center()
  • charAt()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearParagraphBackground()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • color()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • context()
  • contextMenuEvent()
  • copy()
  • copyAvailable()
  • cornerWidget()
  • create()
  • createPopupMenu()
  • currentAlignmentChanged()
  • currentColorChanged()
  • currentFontChanged()
  • currentVerticalAlignmentChanged()
  • cursor()
  • cursorPositionChanged()
  • customEvent()
  • customWhatsThis()
  • cut()
  • del()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doKeyboardAction()
  • documentTitle()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureCursorVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • family()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getCursorPosition()
  • getSelection()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasSelectedText()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indent()
  • inherits()
  • insert()
  • insertAt()
  • insertChild()
  • insertParagraph()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isModified()
  • isOverwriteMode()
  • isPopup()
  • isReadOnly()
  • isRedoAvailable()
  • isTopLevel()
  • isUndoAvailable()
  • isUndoRedoEnabled()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • italic()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • length()
  • lineOfChar()
  • lineWidth()
  • lines()
  • linesOfParagraph()
  • linkUnderline()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • mimeSourceFactory()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • modificationChanged()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveCursor()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • paper()
  • paragraphAt()
  • paragraphBackgroundColor()
  • paragraphLength()
  • paragraphRect()
  • paragraphs()
  • parent()
  • parentWidget()
  • paste()
  • pasteSubType()
  • placeCursor()
  • pointSize()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • redoAvailable()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeParagraph()
  • removeSelectedText()
  • removeSelection()
  • repaint()
  • repaintChanged()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • returnPressed()
  • rightMargin()
  • scroll()
  • scrollBy()
  • scrollToAnchor()
  • scrollToBottom()
  • selectAll()
  • selectedText()
  • selectionChanged()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBold()
  • setCaption()
  • setColor()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentFont()
  • setCursor()
  • setCursorPosition()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFamily()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItalic()
  • setKeyCompression()
  • setLineWidth()
  • setLinkUnderline()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMimeSourceFactory()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setModified()
  • setMouseTracking()
  • setName()
  • setOverwriteMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPaper()
  • setParagraphBackgroundColor()
  • setPointSize()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setSelection()
  • setSelectionAttributes()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setStyleSheet()
  • setTabOrder()
  • setTabStopWidth()
  • setText()
  • setTextFormat()
  • setUnderline()
  • setUndoDepth()
  • setUndoRedoEnabled()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setVerticalAlignment()
  • setWFlags()
  • setWordWrap()
  • setWrapColumnOrWidth()
  • setWrapPolicy()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • styleSheet()
  • tabStopWidth()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • textCursor()
  • textFormat()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • underline()
  • undo()
  • undoAvailable()
  • undoDepth()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrap()
  • wrapColumnOrWidth()
  • wrapPolicy()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()
  • zoomIn()
  • zoomOut()
  • zoomTo()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextEncoder Class

QTextEncoder Class Reference

The QTextEncoder class provides a state-based encoder. More...

#include <qtextcodec.h>

List of all member functions.

Public Members

  • virtual ~QTextEncoder ()
  • virtual QCString fromUnicode ( const QString & uc, int & lenInOut ) = 0

Detailed Description

The QTextEncoder class provides a state-based encoder.

The encoder converts Unicode into another format, remembering any state that is required between calls.

See also QTextCodec::makeEncoder() and Internationalization with Qt.

Member Function Documentation

QTextEncoder::~QTextEncoder () [virtual]

Destroys the encoder.

QCString QTextEncoder::fromUnicode ( const QString & uc, int & lenInOut ) [pure virtual]

Converts lenInOut characters (not bytes) from uc, producing a QCString. lenInOut will be set to the length of the result (in bytes).

The encoder is free to record state to use when subsequent calls are made to this function (for example, it might change modes with escape sequences if needed during the encoding of one string, then assume that mode applies when a subsequent call begins).

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


QTextEncoder Member List

Complete Member List for QTextEncoder

This is the complete list of member functions for QTextEncoder, including inherited members.

  • ~QTextEncoder()
  • fromUnicode()


QTextIStream类

QTextIStream类参考

QTextIStream类是为输入流提供方便的类。 详情请见……

#include <qtextstream.h>

继承了QTextStream。

所有成员函数的列表。

公有成员

  • QTextIStream ( const QString * s )
  • QTextIStream ( QByteArray ba )
  • QTextIStream ( FILE * f )

详细描述

QTextIStream类是为输入流提供方便的类。

对于简单的任务，代码应该更简单，所以这个类是速记的，所以没有传递mode参数给普通的QTextStream的构造函数。

这是一个很简单的例子，就是读这样的东西：

    QString data = "123 456";
    int a, b;
    QTextIStream(&data) >> a >> b;

也可以参考QTextOStream、输入/输出和网络和文本相关类。

成员函数文档

QTextIStream::QTextIStream ( const QString * s )

构造一个从字符串s中读取的流。

QTextIStream::QTextIStream ( QByteArray ba )

构造一个从数组ba中读取的流。

QTextIStream::QTextIStream ( FILE * f )

构造一个从文件f中读取的流。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextIStream成员列表

完整的QTextIStream成员列表

这里是QTextIStream成员函数的完整列表，包括继承的成员。

  • QTextIStream()
  • atEnd()
  • device()
  • eof()
  • fill()
  • flags()
  • operator<<()
  • operator>>()
  • precision()
  • read()
  • readLine()
  • readRawBytes()
  • reset()
  • setCodec()
  • setDevice()
  • setEncoding()
  • setf()
  • skipWhiteSpace()
  • unsetDevice()
  • unsetf()
  • width()
  • writeRawBytes()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextOStream类

QTextOStream类参考

QTextOStream类是为输出流提供方便的类。 详情请见……

#include <qtextstream.h>

继承了QTextStream。

所有成员函数的列表。

公有成员

  • QTextOStream ( QString * s )
  • QTextOStream ( QByteArray ba )
  • QTextOStream ( FILE * f )

详细描述

QTextOStream类是为输出流提供方便的类。

对于简单的任务，代码应该更简单，所以这个类是速记的，所以没有传递mode参数给普通的QTextStream的构造函数。

这是一个很简单的例子，就是写这样的东西：

    QString result;
    QTextOStream(&result) << "pi = " << 3.14;

See also 输入/输出和网络和文本相关类。

成员函数文档

QTextOStream::QTextOStream ( QString * s )

构造一个向字符串s写的流。

QTextOStream::QTextOStream ( QByteArray ba )

构造一个向数组ba写的流。

QTextOStream::QTextOStream ( FILE * f )

构造一个向文件f写的流。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextOStream成员列表

完整的QTextOStream成员列表

这里是QTextOStream成员函数的完整列表，包括继承的成员。

  • QTextOStream()
  • atEnd()
  • device()
  • eof()
  • fill()
  • flags()
  • operator<<()
  • operator>>()
  • precision()
  • read()
  • readLine()
  • readRawBytes()
  • reset()
  • setCodec()
  • setDevice()
  • setEncoding()
  • setf()
  • skipWhiteSpace()
  • unsetDevice()
  • unsetf()
  • width()
  • writeRawBytes()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextStream类

QTextStream类参考

QTextStream类提供了使用QIODevice读写文本的基本功能。 详情请见……

#include <qtextstream.h>

由QTextIStream和QTextOStream继承。

所有成员函数的列表。

公有成员

  • enum Encoding { Locale, Latin1, Unicode, UnicodeNetworkOrder, UnicodeReverse, RawUnicode, UnicodeUTF8 }
  • void setEncoding ( Encoding e )
  • void setCodec ( QTextCodec * codec )
  • QTextStream ()
  • QTextStream ( QIODevice * iod )
  • QTextStream ( QString * str, int filemode )
  • QTextStream ( QString & str, int filemode ) (obsolete)
  • QTextStream ( QByteArray a, int mode )
  • QTextStream ( FILE * fh, int mode )
  • virtual ~QTextStream ()
  • QIODevice * device () const
  • void setDevice ( QIODevice * iod )
  • void unsetDevice ()
  • bool atEnd () const
  • bool eof () const (obsolete)
  • QTextStream & operator>> ( QChar & c )
  • QTextStream & operator>> ( char & c )
  • QTextStream & operator>> ( signed short & i )
  • QTextStream & operator>> ( unsigned short & i )
  • QTextStream & operator>> ( signed int & i )
  • QTextStream & operator>> ( unsigned int & i )
  • QTextStream & operator>> ( signed long & i )
  • QTextStream & operator>> ( unsigned long & i )
  • QTextStream & operator>> ( float & f )
  • QTextStream & operator>> ( double & f )
  • QTextStream & operator>> ( char * s )
  • QTextStream & operator>> ( QString & str )
  • QTextStream & operator>> ( QCString & str )
  • QTextStream & operator<< ( QChar c )
  • QTextStream & operator<< ( char c )
  • QTextStream & operator<< ( signed short i )
  • QTextStream & operator<< ( unsigned short i )
  • QTextStream & operator<< ( signed int i )
  • QTextStream & operator<< ( unsigned int i )
  • QTextStream & operator<< ( signed long i )
  • QTextStream & operator<< ( unsigned long i )
  • QTextStream & operator<< ( float f )
  • QTextStream & operator<< ( double f )
  • QTextStream & operator<< ( const char * s )
  • QTextStream & operator<< ( const QString & s )
  • QTextStream & operator<< ( const QCString & s )
  • QTextStream & operator<< ( void * ptr )
  • QTextStream & readRawBytes ( char * s, uint len )
  • QTextStream & writeRawBytes ( const char * s, uint len )
  • QString readLine ()
  • QString read ()
  • void skipWhiteSpace ()
  • int flags () const
  • int flags ( int f )
  • int setf ( int bits )
  • int setf ( int bits, int mask )
  • int unsetf ( int bits )
  • void reset ()
  • int width () const
  • int width ( int w )
  • int fill () const
  • int fill ( int f )
  • int precision () const
  • int precision ( int p )

详细描述

QTextStream类提供了使用QIODevice读写文本的基本功能。

文本流类的功能界面和标准的C++的iostream类非常相似。iostream和QTextStream的不同点是我们的流操作在一个很容易被继承的QIODevice上，而iostream只能操作一个不能被继承的FILE *指针。

Qt提供了几个和iostream相似的全局函数：

  • bin设置QTextStream来读/写二进制数字
  • oct设置QTextStream来读/写八进制数字
  • dec设置QTextStream来读/写十进制数字
  • hex设置QTextStream来读/写十六进制数字
  • endl强制换行
  • flush强制QIODevice刷新任何被缓存的数据
  • ws作为任何可用的控制符（在输入的时候）
  • reset重新设置QTextStream为它的缺省模式（请见reset()）
  • qSetW(int)设置字段宽度作为指定参数
  • qSetFill(int)设置填充字符作为指定参数
  • qSetPrecision(int)设置精确度作为指定参数

警告：默认情况下，QTextStream在读取流的时候，会自动地检测流中的数字是十进制、八进制、十六进制或者二进制格式。具体情况是，一个以“0”为开头的数字是八进制的，比如顺序为“0100”将会被解释为64。

QTextStream类读写文本，它不适合处理二进制数据（而QDataStream是适合的）。

默认情况下，输出的是使用本地8位编码后的Unicode文本（比如，QString）。这些可以使用setEncoding()方法进行改变。对于输入，QTextStream会自动检测标准Unicode“字节顺序标记的”文本文件，否则会使用本地8位编码。

QIODevice在构造函数中被设置，或者之后在setDevice()中使用。如果输入到达了atEnd()，返回真。数据可以使用operator>>()重载操作符读到适当类型的变量中，或者使用read()把它作为整个部分读到一个单一的字符串中，或者使用readLine()把一次读一行。使用skipWhiteSpace()可以忽略控制符。你可以使用flags()或setf()来设置流的标记。这个流也支持width()、precision()和 fill()，使用reset()可以重新恢复默认设置。

也可以参考QDataStream、输入/输出和网络和文本相关类.

成员类型文档

QTextStream::Encoding

  • QTextStream::Locale
  • QTextStream::Latin1
  • QTextStream::Unicode
  • QTextStream::UnicodeNetworkOrder
  • QTextStream::UnicodeReverse
  • QTextStream::RawUnicode
  • QTextStream::UnicodeUTF8

成员函数文档

QTextStream::QTextStream ()

构造一个没有IO设备的文本流。

QTextStream::QTextStream ( QIODevice * iod )

构造一个使用iodIO设备的文本流。

QTextStream::QTextStream ( QString * str, int filemode )

构造一个通过内部设备操作UnicodeQString的str的文本流。filemode参数会被传递给设备的open()函数，请参考QIODevice::mode()。

如果你使用setEncoding()或setCodec()来设置一个编码或者编码器，当文本流在QString上操作时，这个设置将被忽略。

实例：

    QString str;
    QTextStream ts( &str, IO_WriteOnly );
    ts << "pi = " << 3.14; // str == "pi = 3.14"

写数据到文本流将会修改字符串的内容。如果所写的内容超过字符串的范围，字符串会被扩大。注意字符串不会被截短。

    QString str = "pi = 3.14";
    QTextStream ts( &str, IO_WriteOnly );
    ts <<  "2+2 = " << 2+2; // str == "2+2 = 414"

注意因为QString是Unicode的，你不应该在这样的流上使用readRawBytes()或writeRawBytes()。

QTextStream::QTextStream ( QString & str, int filemode )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个构造函数和使用一个QString*参数的构造函数一样。

QTextStream::QTextStream ( QByteArray a, int mode )

构造一个通过内部QBuffer设备操作字节数组a的文本流。filemode参数会被传递给设备的open()函数，请参考QIODevice::mode()。

实例：

    QByteArray array;
    QTextStream ts( array, IO_WriteOnly );
    ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14"

写数据到文本流将会修改数组的内容。如果所写的内容超过数组的范围，数组会被扩大。

同样的实例，使用QBuffer：

    QByteArray array;
    QBuffer buf( array );
    buf.open( IO_WriteOnly );
    QTextStream ts( &buf );
    ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14"
    buf.close();

QTextStream::QTextStream ( FILE * fh, int mode )

构造一个通过内部的QFile设备操作已经存在的文件句柄fh的文本流。filemode参数会被传递给设备的open()函数，请参考QIODevice::mode()。

注意如果你创建了一个QTextStreamcout或者也被其他类型的另一个变量使用的另一个名称，一些连接器也许会搞混这两个变量，这经常会导致程序崩溃。

QTextStream::~QTextStream () [虚]

销毁这个文本流。

这个析构函数对当前IO设备没有任何影响。

bool QTextStream::atEnd () const

如果IO设备已经达到终点（流或文件的终点），或者如果没有IO设备被设置，返回真，否则返回假。

也可以参考QIODevice::atEnd()。

实例：addressbook/centralwidget.cpp和grapher/grapher.cpp。

QIODevice * QTextStream::device () const

返回当前设置的IO设备。

也可以参考setDevice()和unsetDevice()。

bool QTextStream::eof () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数已经被重新命名为atEnd()。

也可以参考QIODevice::atEnd()。

实例：chart/chartform_files.cpp。

int QTextStream::fill () const

返回填充字符。默认值是“ ”（空格）。

int QTextStream::fill ( int f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置填充字符为f。返回以前的填充字符。

int QTextStream::flags () const

返回当前的流标记。默认值为0。

标记的意义是：

  • skipws - 当前不被使用了，控制符总是被忽略
  • left - 数字字段左对齐
  • right - 当前不被使用了（默认情况下，数字字段是右对齐的）
  • internal - 在+/-和值的中间填充空格
  • bin - 输入和输出只使用二进制
  • oct - 输入和输出只使用八进制
  • dec - 输入和输出只使用十进制
  • hex - 输入和输出只使用十六进制
  • showbase - 如果使用bin、oct或hex格式，数字输出使用0b、0和0x注释
  • showpoint - 当前不被使用了
  • uppercase - 使用0B和0X，而不用0b和0x
  • showpos - 对正数显示+
  • scientific - 对浮点数使用科学记数法
  • fixed - 对浮点数使用固定的位数

注意，如果没有设置bin、oct、dec或hex，那么一个以0开始的值被认为是八进制的，以0x开始的被认为是十六进制的，以0b开始的被认为是二进制的，其它的都被认为是十进制的。

也可以参考setf()和unsetf()。

int QTextStream::flags ( int f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置流标记为f。返回以前的流标记。

也可以参考setf()和unsetf()。

QTextStream & QTextStream::operator<< ( QChar c )

写字符 c到流中并且返回流的引用。

字符 c不依赖于QTextStream的编码设置，被假设为Latin1编码。

QTextStream & QTextStream::operator<< ( char c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写字符 c到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( signed short i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写短整型 i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( unsigned short i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写无符号的短整型i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( signed int i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写有符号的整型 i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( unsigned int i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写无符号的整型 i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( signed long i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写有符号的长整型 i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( unsigned long i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写无符号的长整型 i到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( float f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写单精实型 f到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( double f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写双精实型 f到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( const char * s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个字符串到流中并且返回流的引用。

字符串s不依赖于QTextStream的编码设置，被假设为Latin1编码。

QTextStream & QTextStream::operator<< ( const QString & s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个s到流中并且返回流的引用。

QTextStream & QTextStream::operator<< ( const QCString & s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个s到流中并且返回流的引用。

字符串s不依赖于QTextStream的编码设置，被假设为Latin1编码。

QTextStream & QTextStream::operator<< ( void * ptr )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

写一个指针到流中并且返回流的引用。

ptr是被作为十六进制的无符号的长整型输出的。

QTextStream & QTextStream::operator>> ( QChar & c )

从流中读取一个字符 c并且返回流的引用。 注意控制符不被忽略。

QTextStream & QTextStream::operator>> ( char & c )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个字符 c并且返回流的引用。

QTextStream & QTextStream::operator>> ( signed short & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个短整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( unsigned short & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的短整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( signed int & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个有符号的整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( unsigned int & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( signed long & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个有符号的长整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( unsigned long & i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个无符号的长整型 i并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( float & f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个单精实型 f并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( double & f )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个双精实型 f并且返回流的引用。对于所希望的输入格式的说明，请参考flags()。

QTextStream & QTextStream::operator>> ( char * s )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个“词”s并且返回流的引用。对于所希望的输入格式的说明。

一个词是由isspace()返回假的字符组成。

QTextStream & QTextStream::operator>> ( QString & str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个“词”str并且返回流的引用。对于所希望的输入格式的说明。

一个词是由isspace()返回假的字符组成。

QTextStream & QTextStream::operator>> ( QCString & str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

从流中读取一个“词”str并且返回流的引用。对于所希望的输入格式的说明。

一个词是由isspace()返回假的字符组成。

int QTextStream::precision () const

返回精确度。默认值为6。

int QTextStream::precision ( int p )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置精确度为p。返回以前设置的精确度。

QString QTextStream::read ()

读取整个流并且返回包含文本的字符串。

也可以参考QIODevice::readLine().

实例：action/application.cpp、application/application.cpp、mdi/application.cpp、qdir/qdir.cpp和qwerty/qwerty.cpp。

QString QTextStream::readLine ()

读取流中的一行并且返回包含文本的字符串。

返回的字符串不包含任何换行符和回车符。注意这是和QIODevice::readLine()不一样的，后者不会省略一行最后的换行符。

在EOF处，你会得到一个零QString。在读取一个空行时你得到的QString是空的，但不是零。

也可以参考QIODevice::readLine()。

实例：addressbook/centralwidget.cpp和chart/element.cpp。

QTextStream & QTextStream::readRawBytes ( char * s, uint len )

从流中读取len字节放到s中并且返回流的引用。

缓存s必须被预先分配。

注意这个函数中不使用任何编码方式。

警告：除非流的编码方式被设置为Unicode或者Latin1，这个函数的行为会是不确定的。

也可以参考QIODevice::readBlock()。

void QTextStream::reset ()

重新设置文本流为默认设置。

  • 所有标记被设置为0。
  • 所有字段宽度被设置为0。
  • 所有填充字符被设置为“ ”（空格）。
  • 精确度被设置为6。

也可以参考setf()、width()、fill()和precision()。

void QTextStream::setCodec ( QTextCodec * codec )

设置流的编码器为codec。如果不设置，会自动设置为Unicode。

注意这个函数的调用应该发生在这个流进行读/写数据之前。

也可以参考setEncoding()。

实例：qwerty/qwerty.cpp。

void QTextStream::setDevice ( QIODevice * iod )

设置IO设备为iod。

也可以参考device()和unsetDevice()。

void QTextStream::setEncoding ( Encoding e )

设置这个流的编码为e，e为下列之一：
  • Locale - 使用本地文件格式（如果本地没有设置，就是Latin1），但是会在输入时自动检测是否Unicode（utf16）。
  • Unicode - 使用Unicode（utf16）作为输入和输出。输出将会根据当前平台中最有效率的顺序写出来（比如，QString内部使用的顺序）。
  • UnicodeUTF8 - 使用Unicode（utf8）作为输入和输出。如果使用它作为输入，它将会自动检测是否utf16，如果是的话，将会使用它代替utf8。
  • Latin1 - ISO-8859-1。将不会自动检测utf16。
  • UnicodeNetworkOrder - 使用网络顺序的Unicode（utf16）作为输入和输出。当读取不使用字节顺序标记的Unicode的时候是有用的。
  • UnicodeReverse - 使用与网络顺序相反的顺序的Unicode（utf16）作为输入和输出。当读取不使用字节顺序标记或者当写供bug很多的Windows应用程序读取的数据的Unicode的时候是有用的。
  • RawUnicode - 就像Unicode，但是不写字节顺序标记，也不自动检测字节顺序标记。只有当写供一个单独进程使用的非永久保存的数据的时候是有用的。

Locale和所有的Unicode编码，除了RawUnicode，都将看输入流的头两个字节来决定字节顺序。这个初始的字节顺序标记将会在读数据之前省略掉。

注意这个函数的调用应该发生在这个流进行读/写数据之前。

也可以参考setCodec()。

实例：network/httpd/httpd.cpp和qwerty/qwerty.cpp。

int QTextStream::setf ( int bits )

设置流的标记位为bits。返回以前设置的流标记。

和flags( flags() | bits )是一样的。

也可以参考unsetf()。

int QTextStream::setf ( int bits, int mask )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。 设置流的标记位为bits和一个位掩码mask。返回以前设置的流标记。

和flags( (flags() & ~mask) | (bits & mask) )是一样的。

也可以参考unsetf()。

void QTextStream::skipWhiteSpace ()

放置读指针在第一个非控制字符上。

void QTextStream::unsetDevice ()

清除IO设备。这个和调用setDevice( 0 )一样。

也可以参考device()和setDevice()。

int QTextStream::unsetf ( int bits )

清空流标记位bits。返回以前设置的流标记。

和flags( flags() & ~mask )是一样的。

也可以参考setf()。

int QTextStream::width () const

返回字段宽度。默认值为0。

int QTextStream::width ( int w )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置字段宽度为w。返回以前设置的字段宽度。

QTextStream & QTextStream::writeRawBytes ( const char * s, uint len )

从s写len字节到流中并且返回流的引用。

注意这个函数没有使用任何编码。

也可以参考QIODevice::writeBlock()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtextstream.h包含文件

qtextstream.h

这里是qtextstream.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtextstream.h   3.0.5   edited May 22 16:20 $
**
** Definition of QTextStream class
**
** Created : 940922
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTSTREAM_H
#define QTEXTSTREAM_H

#ifndef QT_H
#include "qiodevice.h"
#include "qstring.h"
#include <stdio.h>
#endif // QT_H

#ifndef QT_NO_TEXTSTREAM
class QTextCodec;
class QTextDecoder;

class QTextStreamPrivate;

class Q_EXPORT QTextStream				// text stream class
{
public:
    enum Encoding { Locale, Latin1, Unicode, UnicodeNetworkOrder,
            UnicodeReverse, RawUnicode, UnicodeUTF8 };

    void	setEncoding( Encoding );
#ifndef QT_NO_TEXTCODEC
    void	setCodec( QTextCodec* );
#endif

    //    Encoding encoding() const { return cmode; }

    QTextStream();
    QTextStream( QIODevice * );
    QTextStream( QString*, int mode );
    QTextStream( QString&, int mode );		// obsolete
    QTextStream( QByteArray, int mode );
    QTextStream( FILE *, int mode );
    virtual ~QTextStream();

    QIODevice	*device() const;
    void	 setDevice( QIODevice * );
    void	 unsetDevice();

    bool	 atEnd() const;
    bool	 eof() const;

    QTextStream &operator>>( QChar & );
    QTextStream &operator>>( char & );
    QTextStream &operator>>( signed short & );
    QTextStream &operator>>( unsigned short & );
    QTextStream &operator>>( signed int & );
    QTextStream &operator>>( unsigned int & );
    QTextStream &operator>>( signed long & );
    QTextStream &operator>>( unsigned long & );
    QTextStream &operator>>( float & );
    QTextStream &operator>>( double & );
    QTextStream &operator>>( char * );
    QTextStream &operator>>( QString & );
    QTextStream &operator>>( QCString & );

    QTextStream &operator<<( QChar );
    QTextStream &operator<<( char );
    QTextStream &operator<<( signed short );
    QTextStream &operator<<( unsigned short );
    QTextStream &operator<<( signed int );
    QTextStream &operator<<( unsigned int );
    QTextStream &operator<<( signed long );
    QTextStream &operator<<( unsigned long );
    QTextStream &operator<<( float );
    QTextStream &operator<<( double );
    QTextStream &operator<<( const char* );
    QTextStream &operator<<( const QString & );
    QTextStream &operator<<( const QCString & );
    QTextStream &operator<<( void * );		// any pointer

    QTextStream &readRawBytes( char *, uint len );
    QTextStream &writeRawBytes( const char* , uint len );

    QString	readLine();
    QString	read();
    void	skipWhiteSpace();

    enum {
    skipws	  = 0x0001,			// skip whitespace on input
    left	  = 0x0002,			// left-adjust output
    right	  = 0x0004,			// right-adjust output
    internal  = 0x0008,			// pad after sign
    bin	  = 0x0010,			// binary format integer
    oct	  = 0x0020,			// octal format integer
    dec	  = 0x0040,			// decimal format integer
    hex	  = 0x0080,			// hex format integer
    showbase  = 0x0100,			// show base indicator
    showpoint = 0x0200,			// force decimal point (float)
    uppercase = 0x0400,			// upper-case hex output
    showpos	  = 0x0800,			// add '+' to positive integers
    scientific= 0x1000,			// scientific float output
    fixed	  = 0x2000			// fixed float output
    };

    static const int basefield;			// bin | oct | dec | hex
    static const int adjustfield;		// left | right | internal
    static const int floatfield;		// scientific | fixed

    int	  flags() const;
    int	  flags( int f );
    int	  setf( int bits );
    int	  setf( int bits, int mask );
    int	  unsetf( int bits );

    void  reset();

    int	  width()	const;
    int	  width( int );
    int	  fill()	const;
    int	  fill( int );
    int	  precision()	const;
    int	  precision( int );

private:
    long	input_int();
    void	init();
    QTextStream &output_int( int, ulong, bool );
    QIODevice	*dev;

    int		fflags;
    int		fwidth;
    int		fillchar;
    int		fprec;
    bool	doUnicodeHeader;
    bool	owndev;
    QTextCodec 	*mapper;
    QTextStreamPrivate * d;
    QChar	unused1; // ### remove in Qt 4.0
    bool	latin1;
    bool 	internalOrder;
    bool	networkOrder;
    void	*unused2; // ### remove in Qt 4.0

    QChar	eat_ws();
    uint 	ts_getline( QChar* );
    void	ts_ungetc( QChar );
    QChar	ts_getc();
    uint	ts_getbuf( QChar*, uint );
    void	ts_putc(int);
    void	ts_putc(QChar);
    bool	ts_isspace(QChar);
    bool	ts_isdigit(QChar);
    ulong	input_bin();
    ulong	input_oct();
    ulong	input_dec();
    ulong	input_hex();
    double	input_double();
    QTextStream &writeBlock( const char* p, uint len );
    QTextStream &writeBlock( const QChar* p, uint len );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTextStream( const QTextStream & );
    QTextStream &operator=( const QTextStream & );
#endif
};

typedef QTextStream QTS;

class Q_EXPORT QTextIStream : public QTextStream {
public:
    QTextIStream( const QString* s ) :
    QTextStream((QString*)s,IO_ReadOnly) { }
    QTextIStream( QByteArray ba ) :
    QTextStream(ba,IO_ReadOnly) { }
    QTextIStream( FILE *f ) :
    QTextStream(f,IO_ReadOnly) { }
};

class Q_EXPORT QTextOStream : public QTextStream {
public:
    QTextOStream( QString* s ) :
    QTextStream(s,IO_WriteOnly) { }
    QTextOStream( QByteArray ba ) :
    QTextStream(ba,IO_WriteOnly) { }
    QTextOStream( FILE *f ) :
    QTextStream(f,IO_WriteOnly) { }
};

/*****************************************************************************
  QTextStream inline functions
 *****************************************************************************/

inline QIODevice *QTextStream::device() const
{ return dev; }

inline bool QTextStream::atEnd() const
{ return dev ? dev->atEnd() : FALSE; }

inline bool QTextStream::eof() const
{ return atEnd(); }

inline int QTextStream::flags() const
{ return fflags; }

inline int QTextStream::flags( int f )
{ int oldf = fflags;  fflags = f;  return oldf; }

inline int QTextStream::setf( int bits )
{ int oldf = fflags;  fflags |= bits;  return oldf; }

inline int QTextStream::setf( int bits, int mask )
{ int oldf = fflags;  fflags = (fflags & ~mask) | (bits & mask); return oldf; }

inline int QTextStream::unsetf( int bits )
{ int oldf = fflags;  fflags &= ~bits;	return oldf; }

inline int QTextStream::width() const
{ return fwidth; }

inline int QTextStream::width( int w )
{ int oldw = fwidth;  fwidth = w;  return oldw;	 }

inline int QTextStream::fill() const
{ return fillchar; }

inline int QTextStream::fill( int f )
{ int oldc = fillchar;	fillchar = f;  return oldc;  }

inline int QTextStream::precision() const
{ return fprec; }

inline int QTextStream::precision( int p )
{ int oldp = fprec;  fprec = p;	 return oldp;  }

/*!
  Returns one character from the stream, or EOF.
*/
inline QChar QTextStream::ts_getc()
{ QChar r; return ( ts_getbuf( &r,1 ) == 1 ? r : QChar((ushort)0xffff) ); }

/*****************************************************************************
  QTextStream manipulators
 *****************************************************************************/

typedef QTextStream & (*QTSFUNC)(QTextStream &);// manipulator function
typedef int (QTextStream::*QTSMFI)(int);	// manipulator w/int argument

class Q_EXPORT QTSManip {			// text stream manipulator
public:
    QTSManip( QTSMFI m, int a ) { mf=m; arg=a; }
    void exec( QTextStream &s ) { (s.*mf)(arg); }
private:
    QTSMFI mf;					// QTextStream member function
    int	   arg;					// member function argument
};

Q_EXPORT inline QTextStream &operator>>( QTextStream &s, QTSFUNC f )
{ return (*f)( s ); }

Q_EXPORT inline QTextStream &operator<<( QTextStream &s, QTSFUNC f )
{ return (*f)( s ); }

Q_EXPORT inline QTextStream &operator<<( QTextStream &s, QTSManip m )
{ m.exec(s); return s; }

Q_EXPORT QTextStream &bin( QTextStream &s );	// set bin notation
Q_EXPORT QTextStream &oct( QTextStream &s );	// set oct notation
Q_EXPORT QTextStream &dec( QTextStream &s );	// set dec notation
Q_EXPORT QTextStream &hex( QTextStream &s );	// set hex notation
Q_EXPORT QTextStream &endl( QTextStream &s );	// insert EOL ('\n')
Q_EXPORT QTextStream &flush( QTextStream &s );	// flush output
Q_EXPORT QTextStream &ws( QTextStream &s );	// eat whitespace on input
Q_EXPORT QTextStream &reset( QTextStream &s );	// set default flags

Q_EXPORT inline QTSManip qSetW( int w )
{
    QTSMFI func = &QTextStream::width;
    return QTSManip(func,w);
}

Q_EXPORT inline QTSManip qSetFill( int f )
{
    QTSMFI func = &QTextStream::fill;
    return QTSManip(func,f);
}

Q_EXPORT inline QTSManip qSetPrecision( int p )
{
    QTSMFI func = &QTextStream::precision;
    return QTSManip(func,p);
}

#endif // QT_NO_TEXTSTREAM
#endif // QTEXTSTREAM_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextStream成员列表

完整的QTextStream成员列表

这里是QTextStream成员函数的完整列表，包括继承的成员。

  • QTextStream()
  • ~QTextStream()
  • atEnd()
  • device()
  • eof()
  • fill()
  • flags()
  • operator<<()
  • operator>>()
  • precision()
  • read()
  • readLine()
  • readRawBytes()
  • reset()
  • setCodec()
  • setDevice()
  • setEncoding()
  • setf()
  • skipWhiteSpace()
  • unsetDevice()
  • unsetf()
  • width()
  • writeRawBytes()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTextView Class

QTextView Class Reference
[obsolete]

The QTextView class provides a rich-text viewer. More...

#include <qtextview.h>

Inherits QTextEdit.

List of all member functions.

Properties

  • bool overwriteMode - whether new text overwrites or pushes aside existing text (read only)
  • int undoDepth - the number of undoable steps (read only)

Detailed Description

The QTextView class provides a rich-text viewer.

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

This class wraps a read-only QTextEdit. Use a QTextEdit instead, and call setReadOnly(TRUE) to disable editing.

Property Documentation

bool overwriteMode

This property holds whether new text overwrites or pushes aside existing text.

int undoDepth

This property holds the number of undoable steps.

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


qtextview.h Include File

qtextview.h

This is the verbatim text of the qtextview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtextview.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the QTextView class
**
** Created : 990101
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTEXTVIEW_H
#define QTEXTVIEW_H

#ifndef QT_H
#include "qtextedit.h"
#endif // QT_H

#ifndef QT_NO_TEXTVIEW

class Q_EXPORT QTextView : public QTextEdit
{
    Q_OBJECT
    Q_OVERRIDE( int undoDepth DESIGNABLE false SCRIPTABLE false )
    Q_OVERRIDE( bool overwriteMode DESIGNABLE false SCRIPTABLE false )

public:
    QTextView( const QString& text, const QString& context = QString::null,
           QWidget* parent=0, const char* name=0);
    QTextView( QWidget* parent=0, const char* name=0 );

    virtual ~QTextView();

};

#endif //QT_NO_TEXTVIEW
#endif //QTEXTVIEW_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTextView Member List

Complete Member List for QTextView

This is the complete list of member functions for QTextView, including inherited members.

  • acceptDrops()
  • addChild()
  • adjustSize()
  • alignment()
  • anchorAt()
  • append()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • bold()
  • bottomMargin()
  • caption()
  • center()
  • charAt()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • childIsVisible()
  • childX()
  • childY()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearParagraphBackground()
  • clearWFlags()
  • clipper()
  • close()
  • closeEvent()
  • cmd()
  • color()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsContextMenuEvent()
  • contentsDragEnterEvent()
  • contentsDragLeaveEvent()
  • contentsDragMoveEvent()
  • contentsDropEvent()
  • contentsHeight()
  • contentsMouseDoubleClickEvent()
  • contentsMouseMoveEvent()
  • contentsMousePressEvent()
  • contentsMouseReleaseEvent()
  • contentsMoving()
  • contentsRect()
  • contentsToViewport()
  • contentsWheelEvent()
  • contentsWidth()
  • contentsX()
  • contentsY()
  • context()
  • contextMenuEvent()
  • copy()
  • copyAvailable()
  • cornerWidget()
  • create()
  • createPopupMenu()
  • currentAlignmentChanged()
  • currentColorChanged()
  • currentFontChanged()
  • currentVerticalAlignmentChanged()
  • cursor()
  • cursorPositionChanged()
  • customEvent()
  • customWhatsThis()
  • cut()
  • del()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doKeyboardAction()
  • documentTitle()
  • dragAutoScroll()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawContentsOffset()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enableClipper()
  • enabledChange()
  • ensureCursorVisible()
  • ensureVisible()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • family()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getCursorPosition()
  • getSelection()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hScrollBarMode()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • hasSelectedText()
  • hasStaticBackground()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indent()
  • inherits()
  • insert()
  • insertAt()
  • insertChild()
  • insertParagraph()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isModified()
  • isOverwriteMode()
  • isPopup()
  • isReadOnly()
  • isRedoAvailable()
  • isTopLevel()
  • isUndoAvailable()
  • isUndoRedoEnabled()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • italic()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • leftMargin()
  • length()
  • lineOfChar()
  • lineWidth()
  • lines()
  • linesOfParagraph()
  • linkUnderline()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • mimeSourceFactory()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • modificationChanged()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveChild()
  • moveCursor()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • paper()
  • paragraphAt()
  • paragraphBackgroundColor()
  • paragraphLength()
  • paragraphRect()
  • paragraphs()
  • parent()
  • parentWidget()
  • paste()
  • pasteSubType()
  • placeCursor()
  • pointSize()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • redoAvailable()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeParagraph()
  • removeSelectedText()
  • removeSelection()
  • repaint()
  • repaintChanged()
  • repaintContents()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeContents()
  • resizeEvent()
  • resizePolicy()
  • returnPressed()
  • rightMargin()
  • scroll()
  • scrollBy()
  • scrollToAnchor()
  • scrollToBottom()
  • selectAll()
  • selectedText()
  • selectionChanged()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setBold()
  • setCaption()
  • setColor()
  • setContentsPos()
  • setCornerWidget()
  • setCurrentFont()
  • setCursor()
  • setCursorPosition()
  • setDisabled()
  • setDragAutoScroll()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFamily()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHBarGeometry()
  • setHScrollBarMode()
  • setIcon()
  • setIconText()
  • setItalic()
  • setKeyCompression()
  • setLineWidth()
  • setLinkUnderline()
  • setMargin()
  • setMargins()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMimeSourceFactory()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setModified()
  • setMouseTracking()
  • setName()
  • setOverwriteMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPaper()
  • setParagraphBackgroundColor()
  • setPointSize()
  • setProperty()
  • setReadOnly()
  • setResizePolicy()
  • setSelection()
  • setSelectionAttributes()
  • setSizeIncrement()
  • setSizePolicy()
  • setStaticBackground()
  • setStyle()
  • setStyleSheet()
  • setTabOrder()
  • setTabStopWidth()
  • setText()
  • setTextFormat()
  • setUnderline()
  • setUndoDepth()
  • setUndoRedoEnabled()
  • setUpdatesEnabled()
  • setVBarGeometry()
  • setVScrollBarMode()
  • setVerticalAlignment()
  • setWFlags()
  • setWordWrap()
  • setWrapColumnOrWidth()
  • setWrapPolicy()
  • show()
  • showChild()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • styleSheet()
  • tabStopWidth()
  • tabletEvent()
  • testWFlags()
  • text()
  • textChanged()
  • textCursor()
  • textFormat()
  • timerEvent()
  • topLevelWidget()
  • topMargin()
  • tr()
  • trUtf8()
  • underline()
  • undo()
  • undoAvailable()
  • undoDepth()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateContents()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • vScrollBarMode()
  • verticalScrollBar()
  • viewport()
  • viewportPaintEvent()
  • viewportResizeEvent()
  • viewportSize()
  • viewportToContents()
  • visibleHeight()
  • visibleRect()
  • visibleWidth()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrap()
  • wrapColumnOrWidth()
  • wrapPolicy()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()
  • zoomIn()
  • zoomOut()
  • zoomTo()


QThread类

QThread类参考

QThread类提供了与系统无关的线程。 详情请见……

#include <qthread.h>

继承了Qt。

所有成员函数的列表。

公有成员

  • QThread ()
  • virtual ~QThread ()
  • bool wait ( unsigned long time = ULONG_MAX )
  • void start ()
  • bool finished () const
  • bool running () const

静态公有成员

  • Qt::HANDLE currentThread ()
  • void postEvent ( QObject * receiver, QEvent * event )
  • void exit ()

保护成员

  • virtual void run () = 0

静态保护成员

  • void sleep ( unsigned long secs )
  • void msleep ( unsigned long msecs )
  • void usleep ( unsigned long usecs )

详细描述

QThread类提供了与系统无关的线程。

QThread代表在程序中一个单独的线程控制，在多任务操作系统中，它和同一进程中的其它线程共享数据，但运行起来就像一个单独的程序一样。它不是在main()中开始，QThread是在run()中开始运行的。你继承run()并且在其中包含你的代码。例如：

    class MyThread : public QThread {

    public:

        virtual void run();

    };

    void MyThread::run()
    {
        for( int count = 0; count < 20; count++ ) {
            sleep( 1 );
            qDebug( "Ping!" );
        }
    }

    int main()
    {
        MyThread a;
        MyThread b;
        a.start();
        b.start();
        a.wait();
        b.wait();
    }

这将会开始两个线程，每个线程在屏幕上写20次“Ping!”并且退出。在main()的结尾调用wait()是必需的，因为main()的结束会终结整个程序，它会杀掉所有其它线程。当每个MyThread运行到MyThread::run()结尾时，它就结束运行，就好像一个应用程序离开main()时所做的一样。

也可以参考Qt中支持的线程、环境类和线程类。

成员函数文档

QThread::QThread ()

构造一个新的线程。这个线程将直到start()被调用的时候才开始运行。

QThread::~QThread () [虚]

QThread析构函数。

注意删除QThread对象将不会停止它所代表的线程的运行。删除一个运行中的线程（比如finished()返回假）将可能导致程序崩溃这样的结果。你可以对线程运行wait()来确定程序运行结束。

Qt::HANDLE QThread::currentThread () [静态]

这返回当前执行的线程的线程句柄。

警告：这个函数返回的句柄用于内部目的并且不应该在任何应用程序代码中使用它。在Windows中，返回值是当前线程的假句柄，并且它不能用于数字比较。

void QThread::exit () [静态]

结束调用线程的执行并且唤醒任何等待它终止的线程。

bool QThread::finished () const

如果线程完成，返回真，否则返回假。

void QThread::msleep ( unsigned long msecs ) [静态 保护]

与系统无关的睡眠。这将导致当前线程睡眠msecs毫秒。

void QThread::postEvent ( QObject * receiver, QEvent * event ) [静态]

提供一个从一个不是事件线程的线程发送一个事件到一个对象的方法。

如下是已经完成的：

  • event被放进队列；
  • 事件线程被唤醒；
  • 事件线程发送事件到receiver对象。
重要的是请注意事件的事件处理器当它被调用时，它是被事件线程调用，而不是被调用QThread::postEvent()的线程所调用。

因为QThread::postEvent()发送事件到QApplication的事件队列，你必须在调用QThread::postEvent()之前创建QApplication对象。

事件必须在堆上分配，因为发送事件的队列会得到事件的所有权并且一旦这个事件被发送成功，它将被删除。

也可以参考QApplication::postEvent()。

void QThread::run () [纯虚 保护]

这个方法是纯虚的，并且为了能够做有用的工作必须在继承类中被重新实现。这个方法的返回将会结束线程的执行。

也可以参考wait()。

bool QThread::running () const

如果线程正在运行，返回真，否则返回假。

void QThread::sleep ( unsigned long secs ) [静态 保护]

与系统无关的睡眠。这将导致当前线程睡眠secs秒。

void QThread::start ()

通过调用run()（必须在QThread子类中重新实现来包含你的代码）开始这个线程的执行。如果你试图开始一个已经运行的线程，这个调用将一直等待，直到这个线程完成，然后再重新开始这个线程。

void QThread::usleep ( unsigned long usecs ) [静态 保护]

与系统无关的睡眠。这将导致当前线程睡眠usecs微秒。

bool QThread::wait ( unsigned long time = ULONG_MAX )

这将提供和POSIX pthread_join相似的功能。一个线程调用了它将会一直阻塞，知道下述条件之一满足时继续：
  • 这个QThread对象所关联的线程已经结束执行（比如，当它从run()中返回）。如果线程完成，这个函数将返回真。如果线程还没有开始呢，这个函数也返回真。
  • time毫秒过去了。如果time是ULONG_MAX（默认值），然后等待将永远不会超时（线程必须从run()中返回）。如果等待时间到了，这个函数将返回假。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qthread.h包含文件

qthread.h

这里是qthread.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qthread.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QThread class
**
** Created : 931107
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTHREAD_H
#define QTHREAD_H

#if defined(QT_THREAD_SUPPORT)

#ifndef QT_H
#include "qwindowdefs.h"
#ifndef QT_NO_COMPAT
#include "qmutex.h"
#include "qsemaphore.h"
#include "qwaitcondition.h"
#endif
#endif // QT_H

class QThreadPrivate;

class Q_EXPORT QThread : public Qt
{
    friend class QThreadPrivate;
public:
    static Qt::HANDLE currentThread();
    static void postEvent( QObject *,QEvent * );
    static void initialize();
    static void cleanup();

    static void exit();

    QThread();
    virtual ~QThread();

    // default argument causes thread to block indefinately
    bool wait( unsigned long time = ULONG_MAX );

    void start();

    bool finished() const;
    bool running() const;

protected:
    virtual void run() = 0;

    static void sleep( unsigned long );
    static void msleep( unsigned long );
    static void usleep( unsigned long );

private:
    QThreadPrivate * d;

#if defined(Q_DISABLE_COPY)
    QThread( const QThread & );
    QThread &operator=( const QThread & );
#endif
};

#endif

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QThread成员列表

完整的QThread成员列表

这里是QThread成员函数的完整列表，包括继承的成员。

  • QThread()
  • ~QThread()
  • currentThread()
  • exit()
  • finished()
  • msleep()
  • postEvent()
  • run()
  • running()
  • sleep()
  • start()
  • usleep()
  • wait()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Display Images in Qt-supported Formats

This example displays images which are in any format supported by Qt. Combining this with the Qt ImageIO Extension adds PNG image support to your browser. It demonstrates the use of the QNPInstance::streamAsFile() function.

To build the example, you must first build the Qt Netscape Plugin Extension library. Then type make in extensions/nsplugin/examples/qtimage/ and copy the resulting qtimage.so or npqtimage.dll to the Plugins directory of your web browser.

This plugin displays a PNG format image.

New image formats can be supported by adding new image I/O handlers to the Qt library (see QImage::defineIOHandler), thus providing the functionality in both applications and WWW plugins from the same code.

This plugin supports transparency and scaling of the image, just like GIFs in most web browsers.

Implementation:

// Qt stuff
#include "qnp.h"
#include <qpainter.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include "qpngio.h"

#include <math.h>
#include <stdlib.h>
#include <stdio.h>

class ImageView : public QNPWidget {
public:
    ImageView()
    {
        popup = new QPopupMenu;
        popup->insertItem("Left as");
        popup->insertItem("An exercise");
        popup->insertItem("For the");
        popup->insertItem("Reader!");
    }

    void paintEvent(QPaintEvent* event)
    {
        QPainter p(this);
        p.setClipRect(event->rect());

        if ( pm.size() == size() ) {
            p.drawPixmap(0,0,pm);
        } else {
            if ( pmScaled.size() != size() ) {
                QWMatrix m;
                m.scale((double)width()/pm.width(),
                        (double)height()/pm.height());
                pmScaled = pm.xForm(m);
            }
            p.drawPixmap(0,0,pmScaled);
        }
    }

    void mousePressEvent(QMouseEvent* e)
    {
        popup->popup(mapToGlobal(e->pos()));
    }

    void showImage(const QImage& image)
    {
        pm.convertFromImage(image, QPixmap::Color);
        repaint( FALSE );
    }

private:
    QPixmap pm;
    QPixmap pmScaled;
    QPopupMenu* popup;
};

class ImageLoader : public QNPInstance {
    ImageView* iv;
    QImage image;

public:
    ImageLoader() : iv(0)
    {
    }

    QNPWidget* newWindow()
    {
        iv = new ImageView;
        imageToIV();
        return iv;
    }

    void imageToIV()
    {
        if (!iv || image.isNull()) return;

        iv->showImage(image);
        image.reset();
    }

    bool newStreamCreated(QNPStream*, StreamMode& smode)
    {
        smode = AsFileOnly;
        return TRUE;
    }

    void streamAsFile(QNPStream*, const char* fname)
    {
        //qInitPngIO();

        image = QImage(fname);
        if ( image.isNull() )
            fprintf(stderr, "Could not convert file: %s\n", fname);
        imageToIV();
    }
};

class ImagePlugin : public QNPlugin {

public:
    ImagePlugin()
    {
    }

    QNPInstance* newInstance()
    {
        return new ImageLoader;
    }

    const char* getMIMEDescription() const
    {
        return "image/x-png:png:PNG Image;"
               "image/png:png:PNG Image;"
               "image/x-portable-bitmap:pbm:PBM Image;"
               "image/x-portable-graymap:pgm:PGM Image;"
               "image/x-portable-pixmap:ppm:PPM Image;"
               "image/bmp:bmp:BMP Image;"
               "image/x-ms-bmp:bmp:BMP Image;"
               "image/x-xpixmap:xpm:XPM Image;"
               "image/xpm:xpm:XPM Image";
    }

    const char * getPluginNameString() const
    {
        return "Qt-based Image Plugin";
    }

    const char * getPluginDescriptionString() const
    {
        return "Supports all image formats supported by Qt";
    }
};

QNPlugin* QNPlugin::create()
{
    return new ImagePlugin;
}

See also LiveConnect Examples.


QTime类

QTime类参考

QTime类提供了时钟时间功能。 详情请见……

#include <qdatetime.h>

所有成员函数的列表。

公有成员

  • QTime ()
  • QTime ( int h, int m, int s = 0, int ms = 0 )
  • bool isNull () const
  • bool isValid () const
  • int hour () const
  • int minute () const
  • int second () const
  • int msec () const
  • QString toString ( Qt::DateFormat f = Qt::TextDate ) const
  • QString toString ( const QString & format ) const
  • bool setHMS ( int h, int m, int s, int ms = 0 )
  • QTime addSecs ( int nsecs ) const
  • int secsTo ( const QTime & t ) const
  • QTime addMSecs ( int ms ) const
  • int msecsTo ( const QTime & t ) const
  • bool operator== ( const QTime & t ) const
  • bool operator!= ( const QTime & t ) const
  • bool operator< ( const QTime & t ) const
  • bool operator<= ( const QTime & t ) const
  • bool operator> ( const QTime & t ) const
  • bool operator>= ( const QTime & t ) const
  • void start ()
  • int restart ()
  • int elapsed () const

静态公有成员

  • QTime currentTime ()
  • QTime fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate )
  • bool isValid ( int h, int m, int s, int ms = 0 )

相关函数

  • QDataStream & operator<< ( QDataStream & s, const QTime & t )
  • QDataStream & operator>> ( QDataStream & s, QTime & t )

详细描述

QTime类提供了时钟时间功能。

QTime对象包含时钟时间，比如从午夜开始的时、分、秒和毫秒数。它可以从系统时钟中读取当前的时间并且度量时间的跨度。它提供比较时间和操作时间的函数，比如加上一定的秒或毫秒。

QTime操作的是24小时时钟格式，它没有AM/PM概念。它操作的是本地时间，它不知道有关时区或白天时间的概念。

QTime对象通常可以由明白地给定的时、分、秒和毫秒数字来创建，或者使用静态函数currentTime()让QTime对象包含系统时钟时间。注意精确性取决于下面操作系统的精确性，不是所有的操作系统都有毫秒级精确度的。

hour()、minute()、second()和msec()函数提供了对时、分、秒和毫秒数字的访问。toString()提供了文本格式的相同信息。

QTime提供了一整套的操作符来比较两个QTime对象，在这里小于表示早一些，大于表示晚一些。

一个给定时间之后给定的秒或毫秒数的时间可以使用addSecs()或addMSecs()得到。相对地，两个时间的秒（或毫秒）数可以使用secsTo()或msecsTo()得到。

QTime可以使用start()、restart()和elapsed()函数度量流逝的时间。

也可以参考QDate、QDateTime和时间和日期。

成员函数文档

QTime::QTime ()

构造一个时、分、秒和毫秒都是0的时间，比如，00:00:00.000（午夜）。这是一个有效的时间。

也可以参考isValid()。

QTime::QTime ( int h, int m, int s = 0, int ms = 0 )

构造一个时、分、秒和毫秒分别为h、m、s和ms的时间。

h必须在0－23之间，m和s必须在0－59之间，ms必须在0－999之间。

也可以参考isValid()。

QTime QTime::addMSecs ( int ms ) const

返回这个时间对象ms毫秒之后的一个时间对象（或者ms毫秒之前的，如果它是一个负数）。

注意如果这个时间过了午夜，它将被转换。请参考addSecs()中的实例。

也可以参考addSecs()和msecsTo()。

QTime QTime::addSecs ( int nsecs ) const

返回这个时间对象nsecs秒之后的一个时间对象（或者nsecs秒之前的，如果它是一个负数）。

注意如果这个时间过了午夜，它将被转换。

实例：

    QTime n( 14, 0, 0 );                // n == 14:00:00
    QTime t;
    t = n.addSecs( 70 );                // t == 14:01:10
    t = n.addSecs( -70 );               // t == 13:58:50
    t = n.addSecs( 10*60*60 + 5 );      // t == 00:00:05
    t = n.addSecs( -15*60*60 );         // t == 23:00:00

也可以参考addMSecs()、secsTo()和QDateTime::addSecs()。

QTime QTime::currentTime () [静态]

返回当前时间，来自于系统时钟。

注意精确性取决于下面操作系统的精确性，不是所有的操作系统都有毫秒级精确度的。

实例：aclock/aclock.cpp、dclock/dclock.cpp、t12/cannon.cpp和tictac/tictac.cpp。

int QTime::elapsed () const

返回从最后一次调用start()或restart()到现在已经过去的毫秒数。

注意如果在最后一次调用start()或restart()后24小时，计数器转换为0。

注意精确性取决于下面操作系统的精确性，不是所有的操作系统都有毫秒级精确度的。

警告： 如果最后一次调用start()或restart()之后，系统时钟设置发生了改变，结果将是不确定的。

也可以参考start()和restart()。

QTime QTime::fromString ( const QString & s, Qt::DateFormat f = Qt::TextDate ) [静态]

通过给定的字符串s，使用格式f，返回这个QTime，或者如果这是不可能的话返回一个无效的时间。

注意Qt::LocalDate在这里不能使用。

int QTime::hour () const

返回时间的小时部分（0－23）。

实例：tictac/tictac.cpp。

bool QTime::isNull () const

如果时间和00:00:00.000相等，返回真，否则返回假。零时间是有效的。

也可以参考isValid()。

bool QTime::isValid () const

如果时间是有效的，返回真，否则返回假。时间23:30:55.746是有效的，而24:12:30是无效的。

也可以参考isNull()。

bool QTime::isValid ( int h, int m, int s, int ms = 0 ) [静态]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果时间是有效的，返回真，否则返回假。

如果h在0－23之间、m和s在0－59之间、ms在0－999之间，时间是有效的。

实例：

    QTime::isValid(21, 10, 30); // 返回真
    QTime::isValid(22, 5,  62); // 返回假

int QTime::minute () const

返回时间的分钟部分（0－59）。

实例：aclock/aclock.cpp和tictac/tictac.cpp。

int QTime::msec () const

返回时间的毫秒部分（0－999）。

int QTime::msecsTo ( const QTime & t ) const

返回这个时间到t的毫秒数（如果t早于这个时间，返回的为负数）。

因为QTime只能度量一天之内的时间，而且一天内只有86400000毫秒，所以结果就应该在-86400000毫秒和86400000毫秒之间。

也可以参考secsTo()。

bool QTime::operator!= ( const QTime & t ) const

如果这个时间不等于t，返回真，否则返回假。

bool QTime::operator< ( const QTime & t ) const

如果这个时间早于t，返回真，否则返回假。

bool QTime::operator<= ( const QTime & t ) const

如果这个时间不晚于t，返回真，否则返回假。

bool QTime::operator== ( const QTime & t ) const

如果这个时间等于t，返回真，否则返回假。

bool QTime::operator> ( const QTime & t ) const

如果这个时间晚于t，返回真，否则返回假。

bool QTime::operator>= ( const QTime & t ) const

如果这个时间不早于t，返回真，否则返回假。

int QTime::restart ()

设置这个时间为当前时间并且返回从最后一次调用start()或restart()到现在过去的毫秒数。

这个函数保证是原子的并且这样对于重复度量是非常方便的。调用start()开始第一次度量，然后调用restart()来做以后的每一次度量。

注意如果在最后一次调用start()或restart()后24小时，计数器转换为0。

警告： 如果最后一次调用start()或restart()之后，系统时钟设置发生了改变，结果将是不确定的。

也可以参考start()、elapsed()和currentTime()。

int QTime::second () const

返回时间的秒部分（0－59）。

实例：tictac/tictac.cpp。

int QTime::secsTo ( const QTime & t ) const

返回这个时间到t的秒数（如果t早于这个时间，返回的为负数）。

因为QTime只能度量一天之内的时间，而且一天内只有86400秒，所以结果就应该在-86400秒和86400秒之间。

也可以参考addSecs() and QDateTime::secsTo().

实例：t12/cannon.cpp。

bool QTime::setHMS ( int h, int m, int s, int ms = 0 )

设置时间的时、分、秒和毫秒分别为h、m、s和ms。

h必须在0－23之间，m和s必须在0－59之间，ms必须在0－999之间。如果设置的时间有效，返回真，否则返回假。

也可以参考isValid()。

void QTime::start ()

设置这个时间为当前时间。这是实际上使用来计时的：

    QTime t;
    t.start();                     // 开始计时
    ... // 一些任务
    qDebug( "%d\n", t.elapsed() ); // 打印过去的毫秒数

也可以参考restart()、elapsed()和currentTime()。

QString QTime::toString ( const QString & format ) const

返回一个字符串的时间。format参数决定了结果字符串的格式。

这些是可能用到的表达式：

  • h - 没有前置0的数字的小时（0－23或者如果显示AM/PM时，1－12）
  • hh - 前置0的数字的小时（00－23或者如果显示AM/PM时，01－12）
  • m - 没有前置0的数字的分钟（0－59）
  • mm - 前置0的数字的分钟（00－59）
  • s - 没有前置0的数字的秒（0－59）
  • ss - 前置0的数字的秒（00－59）
  • z - 没有前置0的数字的毫秒（0－999）
  • zzz - 前置0的数字的毫秒（000－999）
  • AP - 切换为AM/PM显示。AP将被“AM”或“PM”替换。
  • ap - 切换为am/pm显示。ap将被“am”或“pm”替换。

所有其他输入字符都将被忽略。

格式字符串实例（假设这个QTime为14:13:09.042）

  • “hh:mm:ss.zzz”的结果将是“14:13:09.042”
  • “h:m:s ap”的结果将是“2:13:9 pm”

也可以参考QDate::toString()和QTime::toString()。

QString QTime::toString ( Qt::DateFormat f = Qt::TextDate ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回一个字符串的时间。f参数决定了结果字符串的格式。

如果f是Qt::TextDate，字符串格式是HH:MM:SS，比日午夜前一秒是“23:59:59”。

如果f是Qt::ISODate，字符串格式遵循ISO 8601表示时间的说明，也就是HH:MM:SS。

如果f是Qt::LocalDate，字符串格式依赖于系统的本地设置。

相关函数

QDataStream & operator<< ( QDataStream & s, const QTime & t )

写时间t到流s中。

也可以参考QDataStream操作符的格式。

QDataStream & operator>> ( QDataStream & s, QTime & t )

从流s中读取一个时间到t中。

也可以参考QDataStream操作符的格式。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTime成员列表

完整的QTime成员列表

这里是QTime成员函数的完整列表，包括继承的成员。

  • QTime()
  • addMSecs()
  • addSecs()
  • currentTime()
  • elapsed()
  • fromString()
  • hour()
  • isNull()
  • isValid()
  • minute()
  • msec()
  • msecsTo()
  • operator!=()
  • operator<()
  • operator<=()
  • operator==()
  • operator>()
  • operator>=()
  • restart()
  • second()
  • secsTo()
  • setHMS()
  • start()
  • toString()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTimeEdit Class

QTimeEdit Class Reference

The QTimeEdit class provides a time editor. More...

#include <qdatetimeedit.h>

List of all member functions.

Public Members

  • QTimeEdit ( QWidget * parent = 0, const char * name = 0 )
  • QTimeEdit ( const QTime & time, QWidget * parent = 0, const char * name = 0 )
  • ~QTimeEdit ()
  • virtual void setTime ( const QTime & time )
  • QTime time () const
  • virtual void setAutoAdvance ( bool advance )
  • bool autoAdvance () const
  • virtual void setMinValue ( const QTime & d )
  • QTime minValue () const
  • virtual void setMaxValue ( const QTime & d )
  • QTime maxValue () const
  • virtual void setRange ( const QTime & min, const QTime & max )
  • QString separator () const
  • virtual void setSeparator ( const QString & s )

Signals

  • void valueChanged ( const QTime & time )

Properties

  • bool autoAdvance - whether the editor automatically advances to the next section
  • QTime maxValue - the maximum time value
  • QTime minValue - the minimum time value
  • QTime time - the time value of the editor

Protected Members

  • virtual QString sectionFormattedText ( int sec )
  • virtual void setHour ( int h )
  • virtual void setMinute ( int m )
  • virtual void setSecond ( int s )

Protected Slots

  • void updateButtons ()

Detailed Description

The QTimeEdit class provides a time editor.

QTimeEdit allows the user to edit times by using the keyboard or the arrow keys to increase/decrease time values. The arrow keys can be used to move from section to section within the QTimeEdit box. The user can automatically be moved to the next section once they complete a section using setAutoAdvance(). Times appear in hour, minute, second order. It is recommended that the QTimeEdit be initialised with a time, e.g.

    QTime timeNow = QTime::currentTime();
    QTimeEdit *timeEdit = new QTimeEdit( timeNow, this );
    timeEdit->setRange( timeNow, timeNow.addSecs( 60 * 60 ) );
Here we've created a QTimeEdit widget set to the current time. We've also set the minimum value to the current time and the maximum time to one hour from now.

The maximum and minimum values for a time value in the time editor default to the maximum and minimum values for a QTime. You can change this by calling setMinValue(), setMaxValue() or setRange().

Terminology: A QTimeWidget consists of three sections, one each for the hour, minute and second. You can change the separator character using setSeparator(), by default the separator is read from the system's settings.

Date Time Widgets

See also QTime, QDateEdit, QDateTimeEdit, Advanced Widgets and Time and Date.

Member Function Documentation

QTimeEdit::QTimeEdit ( QWidget * parent = 0, const char * name = 0 )

Constructs an empty time edit with parent parent and name name.

QTimeEdit::QTimeEdit ( const QTime & time, QWidget * parent = 0, const char * name = 0 )

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

Constructs a time edit with the initial time value, time, parent parent and name name.

QTimeEdit::~QTimeEdit ()

Destroys the object and frees any allocated resources.

bool QTimeEdit::autoAdvance () const

Returns TRUE if the editor automatically advances to the next section; otherwise returns FALSE. See the "autoAdvance" property for details.

QTime QTimeEdit::maxValue () const

Returns the maximum time value. See the "maxValue" property for details.

QTime QTimeEdit::minValue () const

Returns the minimum time value. See the "minValue" property for details.

QString QTimeEdit::sectionFormattedText ( int sec ) [virtual protected]

Returns the formatted number for section sec. This will correspond to either the hour, minute or second section, depending on sec.

QString QTimeEdit::separator () const

Returns the separator for the editor.

void QTimeEdit::setAutoAdvance ( bool advance ) [virtual]

Sets whether the editor automatically advances to the next section to advance. See the "autoAdvance" property for details.

void QTimeEdit::setHour ( int h ) [virtual protected]

Sets the hour to h, which must be a valid hour, i.e. in the range 0..24.

void QTimeEdit::setMaxValue ( const QTime & d ) [virtual]

Sets the maximum time value to d. See the "maxValue" property for details.

void QTimeEdit::setMinValue ( const QTime & d ) [virtual]

Sets the minimum time value to d. See the "minValue" property for details.

void QTimeEdit::setMinute ( int m ) [virtual protected]

Sets the minute to m, which must be a valid minute, i.e. in the range 0..59.

void QTimeEdit::setRange ( const QTime & min, const QTime & max ) [virtual]

Sets the valid input range for the editor to be from min to max inclusive. If min is invalid no minimum time is set. Similarly, if max is invalid no maximum time is set.

void QTimeEdit::setSecond ( int s ) [virtual protected]

Sets the second to s, which must be a valid second, i.e. in the range 0..59.

void QTimeEdit::setSeparator ( const QString & s ) [virtual]

Sets the separator to s. Note that currently only the first character of s is used.

void QTimeEdit::setTime ( const QTime & time ) [virtual]

Sets the time value of the editor to time. See the "time" property for details.

QTime QTimeEdit::time () const

Returns the time value of the editor. See the "time" property for details.

void QTimeEdit::updateButtons () [protected slot]

Enables/disables the push buttons according to the min/max time for this widget.

void QTimeEdit::valueChanged ( const QTime & time ) [signal]

This signal is emitted whenever the editor's value changes. The time parameter is the new value.

Property Documentation

bool autoAdvance

This property holds whether the editor automatically advances to the next section.

If autoAdvance is TRUE, the editor will automatically advance focus to the next time section if a user has completed a section. The default is FALSE.

Set this property's value with setAutoAdvance() and get this property's value with autoAdvance().

QTime maxValue

This property holds the maximum time value.

Setting the maximum time value is equivalent to calling QTimeEdit::setRange( minValue(), t ), where t is the maximum time. The default maximum time is 23:59:59.

Set this property's value with setMaxValue() and get this property's value with maxValue().

QTime minValue

This property holds the minimum time value.

Setting the minimum time value is equivalent to calling QTimeEdit::setRange( t, maxValue() ), where t is the minimum time. The default minimum time is 00:00:00.

Set this property's value with setMinValue() and get this property's value with minValue().

QTime time

This property holds the time value of the editor.

When changing the time property, if the time is less than minValue(), or is greater than maxValue(), nothing happens.

Set this property's value with setTime() and get this property's value with time().

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


QTimeEdit Member List

Complete Member List for QTimeEdit

This is the complete list of member functions for QTimeEdit, including inherited members.

  • QTimeEdit()
  • ~QTimeEdit()
  • autoAdvance()
  • maxValue()
  • minValue()
  • sectionFormattedText()
  • separator()
  • setAutoAdvance()
  • setHour()
  • setMaxValue()
  • setMinValue()
  • setMinute()
  • setRange()
  • setSecond()
  • setSeparator()
  • setTime()
  • time()
  • updateButtons()
  • valueChanged()


QTimer类

QTimer类参考

QTimer类提供了定时器信号和单触发定时器。 详情请见……

#include <qtimer.h>

继承了QObject。

所有成员函数的列表。

公有成员

  • QTimer ( QObject * parent = 0, const char * name = 0 )
  • ~QTimer ()
  • bool isActive () const
  • int start ( int msec, bool sshot = FALSE )
  • void changeInterval ( int msec )
  • void stop ()

信号

  • void timeout ()

静态公有成员

  • void singleShot ( int msec, QObject * receiver, const char * member )

详细描述

QTimer类提供了定时器信号和单触发定时器。

它在内部使用定时器事件来提供更通用的定时器。QTimer很容易使用：创建一个QTimer，使用start()来开始并且把它的timeout()连接到适当的槽。当这段时间过去了，它将会发射timeout()信号。

注意当QTimer的父对象被销毁时，它也会被自动销毁。

实例：

        QTimer *timer = new QTimer( myObject );
        connect( timer, SIGNAL(timeout()), myObject, SLOT(timerDone()) );
        timer->start( 2000, TRUE ); // 2秒单触发定时器

你也可以使用静态的singleShot()函数来创建单触发定时器。

作为一个特殊情况，一旦窗口系统事件队列中的所有事件都已经被处理完，一个定时为0的QTimer就会到时间了。

这也可以用来当提供迅速的用户界面时来做比较繁重的工作。

        QTimer *t = new QTimer( myObject );
        connect( t, SIGNAL(timeout()), SLOT(processOneThing()) );
        t->start( 0, FALSE );

myObject->processOneThing()将会被重复调用并且应该很快返回（通常在处理一个数据项之后），这样Qt可以把事件传送给窗口部件并且一旦它完成这个工作就停止这个定时器。这是在图形用户界面应用程序中实现繁重的工作的一个典型方法，现在多线程可以在越来越多的平台上使用，并且我们希望无效事件最终被线程替代。

注意QTimer的精确度依赖于底下的操作系统和硬件。绝大多数平台支持20毫秒的精确度，一些平台可以提供更高的。如果Qt不能传送定时器触发所要求的数量，它将会默默地抛弃一些。

另一个使用QTimer的方法是为你的对象调用QObject::startTimer()和在你的类中（当然必须继承QObject）重新实现QObject::timerEvent()事件处理器。缺点是timerEvent()不支持像单触发定时器或信号那样的高级水平。

一些操作系统限制可能用到的定时器的数量，Qt会尽力在限制范围内工作。

也可以参考事件类和时间和日期。

成员函数文档

QTimer::QTimer ( QObject * parent = 0, const char * name = 0 )

构造一个被称作name，父对象为parent的定时器。

注意这个父对象的析构函数将会销毁这个定时器对象。

QTimer::~QTimer ()

销毁这个定时器。

void QTimer::changeInterval ( int msec )

改变定时间隔为msec毫秒。

如果这个定时器信号是运行的，它将会被停止并且重新开始，否则它将会被开始。

也可以参考start()和isActive()。

bool QTimer::isActive () const

如果定时器正在运行，返回真，否则返回假。

实例：t11/cannon.cpp。

void QTimer::singleShot ( int msec, QObject * receiver, const char * member ) [静态]

这个静态函数在一个给定时间间隔之后调用一个槽。

使用这个函数是非常方便的，因为你不需要被timerEvent或创建一个本地QTimer对象所困扰。

实例：

        #include <qapplication.h>
        #include <qtimer.h>

        int main( int argc, char **argv )
        {
            QApplication a( argc, argv );
            QTimer::singleShot( 10*60*1000, &a, SLOT(quit()) );
                ... // 创建并且显示你的窗口部件
            return a.exec();
        }

这个示例程序会自动在10分钟之后终止（也就是600000毫秒）。

receiver是正在接收的对象并且member是一个槽。时间间隔是msec。

int QTimer::start ( int msec, bool sshot = FALSE )

开始一个msec毫秒定时的定时器。

如果sshot为真，这个定时器将只会被激活一次，否则它将会持续到它被停止。

任何正在运行的定时器将被停止。

也可以参考singleShot()、stop()、changeInterval()和isActive()。

实例：aclock/aclock.cpp、dirview/dirview.cpp、forever/forever.cpp、hello/hello.cpp、t11/cannon.cpp和t13/cannon.cpp。

void QTimer::stop ()

停止这个定时器。

也可以参考start()。

实例：dirview/dirview.cpp、t11/cannon.cpp、t12/cannon.cpp和t13/cannon.cpp。

void QTimer::timeout () [信号]

当定时器被激活时，这个信号被发射。

实例：aclock/aclock.cpp、dirview/dirview.cpp、forever/forever.cpp、hello/hello.cpp和t11/cannon.cpp。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtimer.h包含文件

qtimer.h

这里是qtimer.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtimer.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTimer class
**
** Created : 931111
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTIMER_H
#define QTIMER_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

class Q_EXPORT QTimer : public QObject
{
    Q_OBJECT
public:
    QTimer( QObject *parent=0, const char *name=0 );
   ~QTimer();

    bool	isActive() const;

    int		start( int msec, bool sshot = FALSE );
    void	changeInterval( int msec );
    void	stop();

    static void singleShot( int msec, QObject *receiver, const char *member );

signals:
    void	timeout();

protected:
    bool	event( QEvent * );

private:
    int id;
    uint single : 1;
    uint nulltimer : 1;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTimer( const QTimer & );
    QTimer &operator=( const QTimer & );
#endif
};

inline bool QTimer::isActive() const
{
    return id >= 0;
}

#endif // QTIMER_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTimer成员列表

完整的QTimer成员列表

这里是QTimer成员函数的完整列表，包括继承的成员。

  • QTimer()
  • ~QTimer()
  • blockSignals()
  • changeInterval()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActive()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • singleShot()
  • start()
  • startTimer()
  • stop()
  • timeout()
  • timerEvent()
  • tr()
  • trUtf8()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTimerEvent类

QTimerEvent类参考

QTimerEvent类包含描述一个定时器事件的参数。 详情请见……

#include <qevent.h>

继承了QEvent。

所有成员函数的列表。

公有成员

  • QTimerEvent ( int timerId )
  • int timerId () const

详细描述

QTimerEvent类包含描述一个定时器事件的参数。

定时器事件被按规则的间隔发送给有开始定时的一个或多个定时器的对象。每一个定时器有一个唯一的标识符。一个定时器被使用QObject::startTimer()开始。

QTimer类提供了可以使用信号而不是事件的高级编程接口。它也提供单触发定时器。

事件处理器QObject::timerEvent()接收定时器事件。

也可以参考QTimer、QObject::timerEvent()、QObject::startTimer()、QObject::killTimer()、QObject::killTimers()和事件类。

成员函数文档

QTimerEvent::QTimerEvent ( int timerId )

构造一个定时器标识符为timerId的定时器事件对象。

int QTimerEvent::timerId () const

返回唯一的定时器标识符，和QObject::startTimer()返回的是同一个标识符。

实例：dclock/dclock.cpp。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QTimerEvent成员列表

完整的QTimerEvent成员列表

这里是QTimerEvent成员函数的完整列表，包括继承的成员。

  • QTimerEvent()
  • spontaneous()
  • timerId()
  • type()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt模板库类

Qt模板库（QTL）是一套提供对象容器的模板。请看Qt模板库

QMap | 提供基于值的一个字典的模板类
QMapConstIterator | QMap的常量迭代器
QMapIterator | QMap的迭代器
QPair | 提供基于值的一对元素的模板类
QValueList | 提供基于值的一个双向链表的模板类
QValueListConstIterator | QValueList的常量迭代器
QValueListIterator | QValueList的迭代器
QValueStack | 提供基于值的一个堆栈模板类
QValueVector | 提供基于值的一个动态数组模板类

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


A Tiny QTL Example

This tiny example shows a QValueListIterator.

Implementation:

/****************************************************************************
** $Id:  qt/qvaluelistiterator.cpp   3.0.5   edited Jun 25 11:41 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qvaluelist.h>
#include <qstring.h>
#include <qwindowdefs.h>
#include <stdio.h>

class Employee
{
public:
    Employee(): s(0) {}
    Employee( const QString& name, int salary )
        : n(name), s(salary) {}

    QString name() const { return n; }

    int salary() const { return s; }
    void setSalary( int salary ) { s = salary; }

    // this is here to support very old compilers
#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const Employee & ) const { return FALSE; }
#endif

private:
    QString n;
    int s;
};

int main( int, char** )
{
    typedef QValueList<Employee> EmployeeList;
    EmployeeList list;

    list.append( Employee("Bill", 50000) );
    list.append( Employee("Steve",80000) );
    list.append( Employee("Ron",  60000) );

    Employee joe( "Joe", 50000 );
    list.append( joe );
    joe.setSalary( 4000 );

    EmployeeList::ConstIterator it = list.begin();
    while( it != list.end() ) {
        printf( "%s earns %d\n", (*it).name().latin1(), (*it).salary() );
        ++it;
    }

    return 0;
}

See also Examples.


QtMultiLineEdit Class

QtMultiLineEdit Class Reference
[obsolete]

The QtMultiLineEdit widget is a simple editor for inputting text. More...

#include <qtmultilineedit.h>

Inherits QtTableView.

List of all member functions.

Public Members

  • QtMultiLineEdit ( QWidget * parent = 0, const char * name = 0 )
  • ~QtMultiLineEdit ()
  • QString textLine ( int line ) const
  • int numLines () const
  • virtual QSize minimumSizeHint () const
  • virtual void insertLine ( const QString & txt, int line = -1 )
  • virtual void insertAt ( const QString & s, int line, int col, bool mark = FALSE )
  • virtual void removeLine ( int line )
  • void cursorPosition ( int * line, int * col ) const (obsolete)
  • virtual void setCursorPosition ( int line, int col, bool mark = FALSE )
  • void getCursorPosition ( int * line, int * col ) const
  • bool atBeginning () const
  • bool atEnd () const
  • virtual void setFixedVisibleLines ( int lines )
  • int maxLineWidth () const
  • void setAlignment ( int flags )
  • int alignment () const
  • virtual void setValidator ( const QValidator * v )
  • const QValidator * validator () const
  • void setEdited ( bool )
  • bool edited () const
  • void cursorWordForward ( bool mark )
  • void cursorWordBackward ( bool mark )
  • enum EchoMode { Normal, NoEcho, Password }
  • virtual void setEchoMode ( EchoMode )
  • EchoMode echoMode () const
  • void setMaxLength ( int )
  • int maxLength () const
  • virtual void setMaxLineLength ( int m )
  • int maxLineLength () const
  • virtual void setMaxLines ( int )
  • int maxLines () const
  • virtual void setHMargin ( int )
  • int hMargin () const
  • virtual void setSelection ( int row_from, int col_from, int row_to, int col_to )
  • enum WordWrap { NoWrap, WidgetWidth, FixedPixelWidth, FixedColumnWidth }
  • void setWordWrap ( WordWrap mode )
  • WordWrap wordWrap () const
  • void setWrapColumnOrWidth ( int )
  • int wrapColumnOrWidth () const
  • enum WrapPolicy { AtWhiteSpace, Anywhere }
  • void setWrapPolicy ( WrapPolicy policy )
  • WrapPolicy wrapPolicy () const
  • bool autoUpdate () const
  • virtual void setAutoUpdate ( bool )
  • void setUndoEnabled ( bool )
  • bool isUndoEnabled () const
  • void setUndoDepth ( int )
  • int undoDepth () const
  • bool isReadOnly () const
  • bool isOverwriteMode () const
  • QString text () const
  • int length () const

Public Slots

  • virtual void setText ( const QString & )
  • virtual void setReadOnly ( bool )
  • virtual void setOverwriteMode ( bool )
  • void clear ()
  • void append ( const QString & s )
  • void deselect ()
  • void selectAll ()
  • void paste ()
  • void pasteSubType ( const QCString & subtype )
  • void copyText () const (obsolete)
  • void copy () const
  • void cut ()
  • void insert ( const QString & s )
  • void undo ()
  • void redo ()

Signals

  • void textChanged ()
  • void returnPressed ()
  • void undoAvailable ( bool yes )
  • void redoAvailable ( bool yes )
  • void copyAvailable ( bool yes )

Static Public Members

  • void setDefaultTabStop ( int ex )
  • int defaultTabStop ()

Properties

  • Alignment alignment - the alignment
  • bool atBeginning - whether the cursor is at the beginning (read only)
  • bool atEnd - whether the cursor is at the end (read only)
  • bool autoUpdate - whether auto update is enabled
  • EchoMode echoMode - the echo mode
  • bool edited - whether the text had been edited
  • int hMargin - the horizontal margin The horizontal margin current set. The default is 3
  • int length - the length of the text (read only)
  • int maxLength - the maximum length of the text
  • int maxLineWidth - the maximum line width in pixels Returns the width in pixels of the longest text line in this editor (read only)
  • int maxLines - the maximum number of lines The currently set line limit, or -1 if there is no limit (the default)
  • int numLines - the number of lines in the multi-line edit (read only)
  • bool overWriteMode - the overwrite mode
  • bool readOnly - whether the multi-line edit is read-only
  • QString text - the multi-line edit's text
  • int undoDepth - the undo depth
  • bool undoEnabled - whether undo is enabled
  • WordWrap wordWrap - the word wrap mode
  • int wrapColumnOrWidth - the wrap width in columns or pixels The wrap column or wrap width, depending on the word wrap mode
  • WrapPolicy wrapPolicy - the wrap policy mode The default is \c AtWhiteSpace

Protected Members

  • virtual void paintCell ( QPainter * painter, int row, int col )
  • virtual void keyPressEvent ( QKeyEvent * e )
  • virtual void focusInEvent ( QFocusEvent * )
  • bool hasMarkedText () const
  • QString markedText () const
  • int textWidth ( int line )
  • int textWidth ( const QString & s )
  • QPoint cursorPoint () const
  • virtual void insert ( const QString & str, bool mark )
  • virtual void newLine ()
  • virtual void killLine ()
  • virtual void pageUp ( bool mark = FALSE )
  • virtual void pageDown ( bool mark = FALSE )
  • virtual void cursorLeft ( bool mark = FALSE, bool wrap = TRUE )
  • virtual void cursorRight ( bool mark = FALSE, bool wrap = TRUE )
  • virtual void cursorUp ( bool mark = FALSE )
  • virtual void cursorDown ( bool mark = FALSE )
  • virtual void backspace ()
  • virtual void del ()
  • virtual void home ( bool mark = FALSE )
  • virtual void end ( bool mark = FALSE )
  • bool getMarkedRegion ( int * line1, int * col1, int * line2, int * col2 ) const
  • int lineLength ( int line ) const
  • QString * getString ( int line ) const
  • bool isEndOfParagraph ( int row ) const
  • QString stringShown ( int row ) const
  • void insertChar ( QChar c )

Detailed Description

The QtMultiLineEdit widget is a simple editor for inputting text.

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

The QtMultiLineEdit widget provides multiple line text input and display. It is intended for moderate amounts of text. There are no arbitrary limitations, but if you try to handle megabytes of data, performance will suffer.

Per default, the edit widget does not perform any word wrapping. This can be adjusted by calling setWordWrap(). Both dynamic wrapping according to the visible width or a fixed number of character or pixels is supported.

The widget can be used to display text by calling setReadOnly(TRUE).

The default key bindings are described in keyPressEvent(); they cannot be customized except by inheriting the class.

Member Type Documentation

QtMultiLineEdit::EchoMode

This enum type describes the ways in which QLineEdit can display its contents. The currently defined values are:

  • Normal - display characters as they are entered. This is the default.

  • NoEcho - do not display anything.

  • Password - display asterisks instead of the characters actually entered.

See also echoMode, echoMode and QLineEdit::EchoMode.

QtMultiLineEdit::WordWrap

This enum describes the multiline edit's word wrap mode.

The following values are valid:

  • NoWrap - no word wrap at all.
  • WidgetWidth - word wrap depending on the current width of the editor widget
  • FixedPixelWidth - wrap according to a fix amount of pixels ( see wrapColumnOrWidth() )
  • FixedColumnWidth - wrap according to a fix character column. This is useful whenever you need formatted text that can also be displayed gracefully on devices with monospaced fonts, for example a standard VT100 terminal. In that case wrapColumnOrWidth() should typically be set to 80.

See also wordWrap.

QtMultiLineEdit::WrapPolicy

Defines where text can be wrapped in word wrap mode.

The following values are valid:

  • AtWhiteSpace - break only after whitespace
  • Anywhere - break anywhere

See also wrapPolicy.

Member Function Documentation

QtMultiLineEdit::QtMultiLineEdit ( QWidget * parent = 0, const char * name = 0 )

Constructs a new, empty, QtMultiLineEdit with parent parent and called name.

QtMultiLineEdit::~QtMultiLineEdit ()

Destroys the QtMultiLineEdit

int QtMultiLineEdit::alignment () const

Returns the alignment. See the "alignment" property for details.

void QtMultiLineEdit::append ( const QString & s ) [slot]

Appends s to the text.

bool QtMultiLineEdit::atBeginning () const

Returns TRUE if the cursor is at the beginning; otherwise returns FALSE. See the "atBeginning" property for details.

bool QtMultiLineEdit::atEnd () const

Returns TRUE if the cursor is at the end; otherwise returns FALSE. See the "atEnd" property for details.

bool QtMultiLineEdit::autoUpdate () const

Returns TRUE if auto update is enabled; otherwise returns FALSE. See the "autoUpdate" property for details.

void QtMultiLineEdit::backspace () [virtual protected]

Deletes the character on the left side of the text cursor and moves the cursor one position to the left. If a text has been marked by the user (e.g. by clicking and dragging) the cursor is put at the beginning of the marked text and the marked text is removed.

See also del().

void QtMultiLineEdit::clear () [slot]

Removes all text.

void QtMultiLineEdit::copy () const [slot]

Copies the marked text to the clipboard. Will copy only if echoMode() is Normal.

void QtMultiLineEdit::copyAvailable ( bool yes ) [signal]

This signal is emitted when the availability of cut/copy changes. If yes is TRUE, then cut() and copy() will work until copyAvailable( FALSE ) is next emitted.

void QtMultiLineEdit::copyText () const [slot]

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

Backward compatibility.

void QtMultiLineEdit::cursorDown ( bool mark = FALSE ) [virtual protected]

Moves the cursor one line down. If mark is TRUE, the text is marked.

See also cursorUp(), cursorLeft() and cursorRight().

void QtMultiLineEdit::cursorLeft ( bool mark = FALSE, bool wrap = TRUE ) [virtual protected]

Moves the cursor one character to the left. If mark is TRUE, the text is marked. If wrap is TRUE, the cursor moves to the end of the previous line if it is placed at the beginning of the current line.

See also cursorRight(), cursorUp() and cursorDown().

QPoint QtMultiLineEdit::cursorPoint () const [protected]

Returns the top center point where the cursor is drawn

void QtMultiLineEdit::cursorPosition ( int * line, int * col ) const

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

Use getCursorPosition() instead.

void QtMultiLineEdit::cursorRight ( bool mark = FALSE, bool wrap = TRUE ) [virtual protected]

Moves the cursor one character to the right. If mark is TRUE, the text is marked. If wrap is TRUE, the cursor moves to the beginning of the next line if it is placed at the end of the current line.

See also cursorLeft(), cursorUp() and cursorDown().

void QtMultiLineEdit::cursorUp ( bool mark = FALSE ) [virtual protected]

Moves the cursor up one line. If mark is TRUE, the text is marked.

See also cursorDown(), cursorLeft() and cursorRight().

void QtMultiLineEdit::cursorWordBackward ( bool mark )

Moves the cursor one word to the left. If mark is TRUE, the text is marked.

See also cursorWordForward().

void QtMultiLineEdit::cursorWordForward ( bool mark )

Moves the cursor one word to the right. If mark is TRUE, the text is marked.

See also cursorWordBackward().

void QtMultiLineEdit::cut () [slot]

Copies the selected text to the clipboard and deletes the selected text.

int QtMultiLineEdit::defaultTabStop () [static]

Returns the distance between tab stops.

See also setDefaultTabStop().

void QtMultiLineEdit::del () [virtual protected]

Deletes the character on the right side of the text cursor. If a text has been marked by the user (e.g. by clicking and dragging) the cursor is put at the beginning of the marked text and the marked text is removed.

See also backspace().

void QtMultiLineEdit::deselect () [slot]

Deselects all text (i.e. removes marking) and leaves the cursor at the current position.

EchoMode QtMultiLineEdit::echoMode () const

Returns the echo mode. See the "echoMode" property for details.

bool QtMultiLineEdit::edited () const

Returns TRUE if the text had been edited; otherwise returns FALSE. See the "edited" property for details.

void QtMultiLineEdit::end ( bool mark = FALSE ) [virtual protected]

Moves the text cursor to the right end of the line. If mark is TRUE text is marked towards the last position. If it is FALSE and the cursor is moved, all marked text is unmarked.

See also home().

void QtMultiLineEdit::focusInEvent ( QFocusEvent * ) [virtual protected]

Starts the cursor blinking.

Reimplemented from QWidget.

void QtMultiLineEdit::getCursorPosition ( int * line, int * col ) const

Returns the current line and character position within that line, in the variables pointed to by line and col respectively.

See also setCursorPosition().

bool QtMultiLineEdit::getMarkedRegion ( int * line1, int * col1, int * line2, int * col2 ) const [protected]

If there is marked text, sets line1, col1, line2 and col2 to the start and end of the marked region and returns TRUE. Returns FALSE if there is no marked text.

QString * QtMultiLineEdit::getString ( int line ) const [protected]

Returns a pointer to the text at line line.

int QtMultiLineEdit::hMargin () const

Returns the horizontal margin The horizontal margin current set. The default is 3. See the "hMargin" property for details.

bool QtMultiLineEdit::hasMarkedText () const [protected]

Returns TRUE if there is marked text.

void QtMultiLineEdit::home ( bool mark = FALSE ) [virtual protected]

Moves the text cursor to the left end of the line. If mark is TRUE, text is marked towards the first position. If it is FALSE and the cursor is moved, all marked text is unmarked.

See also end().

void QtMultiLineEdit::insert ( const QString & s ) [slot]

Inserts s at the current cursor position.

void QtMultiLineEdit::insert ( const QString & str, bool mark ) [virtual protected]

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

Inserts string str at the current cursor position. If mark is TRUE the string is marked.

void QtMultiLineEdit::insertAt ( const QString & s, int line, int col, bool mark = FALSE ) [virtual]

Inserts s at line number line, after character number col in the line. If s contains newline characters, new lines are inserted. If mark is TRUE the inserted text is selected.

The cursor position is adjusted. If the insertion position is equal to the cursor position, the cursor is placed after the end of the new text.

void QtMultiLineEdit::insertChar ( QChar c ) [protected]

Inserts c at the current cursor position. (this function is provided for backward compatibility - it simply calls insert()).

void QtMultiLineEdit::insertLine ( const QString & txt, int line = -1 ) [virtual]

Inserts txt at line number line. If line is less than zero, or larger than the number of rows, the new text is put at the end. If txt contains newline characters, several lines are inserted.

The cursor position is not changed.

bool QtMultiLineEdit::isEndOfParagraph ( int row ) const [protected]

Returns wether row is the last row in a paragraph.

This function is only interesting in word wrap mode, otherwise its return value is always TRUE.

See also wordWrap.

bool QtMultiLineEdit::isOverwriteMode () const

Returns the overwrite mode. See the "overWriteMode" property for details.

bool QtMultiLineEdit::isReadOnly () const

Returns TRUE if the multi-line edit is read-only; otherwise returns FALSE. See the "readOnly" property for details.

bool QtMultiLineEdit::isUndoEnabled () const

Returns TRUE if undo is enabled; otherwise returns FALSE. See the "undoEnabled" property for details.

void QtMultiLineEdit::keyPressEvent ( QKeyEvent * e ) [virtual protected]

The key press event handler converts a key press in event e to some line editor action.

Here are the default key bindings when isReadOnly() is FALSE:

  • Left Arrow Move the cursor one character leftwards
  • Right Arrow Move the cursor one character rightwards
  • Up Arrow Move the cursor one line upwards
  • Down Arrow Move the cursor one line downwards
  • Page Up Move the cursor one page upwards
  • Page Down Move the cursor one page downwards
  • Backspace Delete the character to the left of the cursor
  • Home Move the cursor to the beginning of the line
  • End Move the cursor to the end of the line
  • Delete Delete the character to the right of the cursor
  • Shift - Left Arrow Mark text one character leftwards
  • Shift - Right Arrow Mark text one character rightwards
  • Control-A Move the cursor to the beginning of the line
  • Control-B Move the cursor one character leftwards
  • Control-C Copy the marked text to the clipboard
  • Control-D Delete the character to the right of the cursor
  • Control-E Move the cursor to the end of the line
  • Control-F Move the cursor one character rightwards
  • Control-H Delete the character to the left of the cursor
  • Control-K Delete to end of line
  • Control-N Move the cursor one line downwards
  • Control-P Move the cursor one line upwards
  • Control-V Paste the clipboard text into line edit
  • Control-X Cut the marked text, copy to clipboard
  • Control-Z Undo the last operation
  • Control-Y Redo the last operation
  • Control - Left Arrow Move the cursor one word leftwards
  • Control - Right Arrow Move the cursor one word rightwards
  • Control - Up Arrow Move the cursor one word upwards
  • Control - Down Arrow Move the cursor one word downwards
  • Control - Home Arrow Move the cursor to the beginning of the text
  • Control - End Arrow Move the cursor to the end of the text
In addition, the following key bindings are used on Windows:
  • Shift - Delete Cut the marked text, copy to clipboard
  • Shift - Insert Paste the clipboard text into line edit
  • Control - Insert Copy the marked text to the clipboard
All other keys with valid ASCII codes insert themselves into the line.

Here are the default key bindings when isReadOnly() is TRUE:

  • Left Arrow Scrolls the table rightwards
  • Right Arrow Scrolls the table rightwards
  • Up Arrow Scrolls the table one line downwards
  • Down Arrow Scrolls the table one line upwards
  • Page Up Scrolls the table one page downwards
  • Page Down Scrolls the table one page upwards
  • Control-C Copy the marked text to the clipboard

Reimplemented from QWidget.

void QtMultiLineEdit::killLine () [virtual protected]

Deletes text from the current cursor position to the end of the line.

int QtMultiLineEdit::length () const

Returns the length of the text. See the "length" property for details.

int QtMultiLineEdit::lineLength ( int line ) const [protected]

Returns the number of characters at line number line.

QString QtMultiLineEdit::markedText () const [protected]

Returns a copy of the marked text.

int QtMultiLineEdit::maxLength () const

Returns the maximum length of the text. See the "maxLength" property for details.

int QtMultiLineEdit::maxLineLength () const

Returns the currently set line length limit, or -1 if there is no limit (this is the default).

See also setMaxLineLength().

int QtMultiLineEdit::maxLineWidth () const

Returns the maximum line width in pixels Returns the width in pixels of the longest text line in this editor. See the "maxLineWidth" property for details.

int QtMultiLineEdit::maxLines () const

Returns the maximum number of lines The currently set line limit, or -1 if there is no limit (the default). See the "maxLines" property for details.

QSize QtMultiLineEdit::minimumSizeHint () const [virtual]

Returns a size sufficient for one character, and scroll bars.

Reimplemented from QWidget.

void QtMultiLineEdit::newLine () [virtual protected]

Makes a line break at the current cursor position.

int QtMultiLineEdit::numLines () const

Returns the number of lines in the multi-line edit. See the "numLines" property for details.

void QtMultiLineEdit::pageDown ( bool mark = FALSE ) [virtual protected]

Moves the cursor one page down. If mark is TRUE, the text is marked.

void QtMultiLineEdit::pageUp ( bool mark = FALSE ) [virtual protected]

Moves the cursor one page up. If mark is TRUE, the text is marked.

void QtMultiLineEdit::paintCell ( QPainter * painter, int row, int col ) [virtual protected]

Implements the basic drawing logic. Paints the line at row row using painter painter. The col parameter is ignored.

Reimplemented from QtTableView.

void QtMultiLineEdit::paste () [slot]

Copies plain text from the clipboard onto the current cursor position. Any marked text is first deleted.

void QtMultiLineEdit::pasteSubType ( const QCString & subtype ) [slot]

Copies text in MIME subtype subtype from the clipboard onto the current cursor position. Any marked text is first deleted.

void QtMultiLineEdit::redo () [slot]

Redoes the last text operation.

void QtMultiLineEdit::redoAvailable ( bool yes ) [signal]

This signal is emitted when the availability of redo changes. If yes is TRUE, then redo() will work until redoAvailable( FALSE ) is next emitted.

void QtMultiLineEdit::removeLine ( int line ) [virtual]

Deletes the line at line number line. If line is less than zero, or larger than the number of lines, no line is deleted.

void QtMultiLineEdit::returnPressed () [signal]

This signal is emitted when the user presses the return or enter key. It is not emitted if isReadOnly() is TRUE.

See also textChanged().

void QtMultiLineEdit::selectAll () [slot]

Selects all text without moving the cursor.

void QtMultiLineEdit::setAlignment ( int flags )

Sets the alignment to flags. See the "alignment" property for details.

void QtMultiLineEdit::setAutoUpdate ( bool ) [virtual]

Sets whether auto update is enabled. See the "autoUpdate" property for details.

Reimplemented from QtTableView.

void QtMultiLineEdit::setCursorPosition ( int line, int col, bool mark = FALSE ) [virtual]

Sets the cursor position to character number col in line number line. The parameters are adjusted to lie within the legal range.

If mark is FALSE, the selection is cleared. otherwise it is extended

See also cursorPosition().

void QtMultiLineEdit::setDefaultTabStop ( int ex ) [static]

Sets the distance between tab stops for all QtMultiLineEdit instances to ex, which is measured in multiples of the width of a lower case 'x' in the widget's font. The initial value is 8.

Warning: This function does not cause a redraw. It is best to call it before any QtMultiLineEdit widgets are shown.

See also defaultTabStop().

void QtMultiLineEdit::setEchoMode ( EchoMode ) [virtual]

Sets the echo mode. See the "echoMode" property for details.

void QtMultiLineEdit::setEdited ( bool )

Sets whether the text had been edited. See the "edited" property for details.

void QtMultiLineEdit::setFixedVisibleLines ( int lines ) [virtual]

Sets the fixed height of the QtMultiLineEdit so that lines text lines are visible given the current font.

See also maxLines and setFixedHeight().

void QtMultiLineEdit::setHMargin ( int ) [virtual]

Sets the horizontal margin The horizontal margin current set. The default is 3. See the "hMargin" property for details.

void QtMultiLineEdit::setMaxLength ( int )

Sets the maximum length of the text. See the "maxLength" property for details.

void QtMultiLineEdit::setMaxLineLength ( int m ) [virtual]

Sets the maximum length of lines to m. Use -1 for unlimited (the default). Existing long lines will be truncated.

See also maxLineLength().

void QtMultiLineEdit::setMaxLines ( int ) [virtual]

Sets the maximum number of lines The currently set line limit, or -1 if there is no limit (the default). See the "maxLines" property for details.

void QtMultiLineEdit::setOverwriteMode ( bool ) [virtual slot]

Sets the overwrite mode. See the "overWriteMode" property for details.

void QtMultiLineEdit::setReadOnly ( bool ) [virtual slot]

Sets whether the multi-line edit is read-only. See the "readOnly" property for details.

void QtMultiLineEdit::setSelection ( int row_from, int col_from, int row_to, int col_to ) [virtual]

Marks the text starting at row_from, col_from and ending at row_to, col_to.

void QtMultiLineEdit::setText ( const QString & ) [virtual slot]

Sets the multi-line edit's text. See the "text" property for details.

void QtMultiLineEdit::setUndoDepth ( int )

Sets the undo depth. See the "undoDepth" property for details.

void QtMultiLineEdit::setUndoEnabled ( bool )

Sets whether undo is enabled. See the "undoEnabled" property for details.

void QtMultiLineEdit::setValidator ( const QValidator * v ) [virtual]

Not supported at this time. v is the validator to set.

void QtMultiLineEdit::setWordWrap ( WordWrap mode )

Sets the word wrap mode to mode. See the "wordWrap" property for details.

void QtMultiLineEdit::setWrapColumnOrWidth ( int )

Sets the wrap width in columns or pixels The wrap column or wrap width, depending on the word wrap mode. See the "wrapColumnOrWidth" property for details.

void QtMultiLineEdit::setWrapPolicy ( WrapPolicy policy )

Sets the wrap policy mode The default is AtWhiteSpace to policy. See the "wrapPolicy" property for details.

QString QtMultiLineEdit::stringShown ( int row ) const [protected]

Returns the string shown at line row, including processing of the echoMode().

QString QtMultiLineEdit::text () const

Returns the multi-line edit's text. See the "text" property for details.

void QtMultiLineEdit::textChanged () [signal]

This signal is emitted when the text is changed by an event or by a slot. Note that the signal is not emitted when you call a non-slot function such as insertLine().

See also returnPressed().

QString QtMultiLineEdit::textLine ( int line ) const

Returns the text at line number line (possibly the empty string), or a null string if line is invalid.

int QtMultiLineEdit::textWidth ( int line ) [protected]

Returns the width in pixels of the text at line line.

int QtMultiLineEdit::textWidth ( const QString & s ) [protected]

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

Returns the width in pixels of the string s. NOTE: only appropriate for whole lines.

void QtMultiLineEdit::undo () [slot]

Undoes the last text operation.

void QtMultiLineEdit::undoAvailable ( bool yes ) [signal]

This signal is emitted when the availability of undo changes. If yes is TRUE, then undo() will work until undoAvailable( FALSE ) is next emitted.

int QtMultiLineEdit::undoDepth () const

Returns the undo depth. See the "undoDepth" property for details.

const QValidator * QtMultiLineEdit::validator () const

Not supported at this time.

WordWrap QtMultiLineEdit::wordWrap () const

Returns the word wrap mode. See the "wordWrap" property for details.

int QtMultiLineEdit::wrapColumnOrWidth () const

Returns the wrap width in columns or pixels The wrap column or wrap width, depending on the word wrap mode. See the "wrapColumnOrWidth" property for details.

WrapPolicy QtMultiLineEdit::wrapPolicy () const

Returns the wrap policy mode The default is AtWhiteSpace. See the "wrapPolicy" property for details.

Property Documentation

Alignment alignment

This property holds the alignment.

Possible values are AlignLeft, Align(H)Center and AlignRight.

See also Qt::AlignmentFlags.

Set this property's value with setAlignment() and get this property's value with alignment().

bool atBeginning

This property holds whether the cursor is at the beginning.

atBeginning() returns TRUE if the cursor is placed at the beginning of the text.

Get this property's value with atBeginning().

bool atEnd

This property holds whether the cursor is at the end.

atEnd() returns TRUE if the cursor is placed at the end of the text.

Get this property's value with atEnd().

bool autoUpdate

This property holds whether auto update is enabled.

autoUpdate() returns TRUE if the view updates itself automatically whenever it is changed in some way.

If autoUpdate() is TRUE (this is the default) then the editor updates itself automatically whenever it has changed in some way (generally, when text has been inserted or deleted).

If autoUpdate() is FALSE, the view does NOT repaint itself, or update its internal state variables itself when it is changed. This can be useful to avoid flicker during large changes, and is singularly useless otherwise: Disable auto-update, do the changes, re-enable auto-update, and call repaint().

Warning: Do not leave the view in this state for a long time (i.e. between events ). If, for example, the user interacts with the view when auto-update is off, strange things can happen.

Setting auto-update to TRUE does not repaint the view, you must call repaint() to do this (preferable repaint(FALSE) to avoid flicker).

See also repaint().

Set this property's value with setAutoUpdate() and get this property's value with autoUpdate().

EchoMode echoMode

This property holds the echo mode.

Set this property's value with setEchoMode() and get this property's value with echoMode().

bool edited

This property holds whether the text had been edited.

edited() returns the edited flag of the line edit. If this returns FALSE, the contents has not been changed since the construction of the QtMultiLineEdit (or the last call to setEdited( FALSE ), if any). If it returns TRUE, the contents have been edited, or setEdited( TRUE ) has been called.

setEdited() sets the edited flag of this line edit to e. The edited flag is never read by QtMultiLineEdit, but is changed to TRUE whenever the user changes its contents.

This is useful e.g. for things that need to provide a default value, but cannot find the default at once. Just open the widget without the best default and when the default is known, check the edited() return value and set the line edit's contents if the user has not started editing the line edit. Another example is to detect whether the contents need saving.

Set this property's value with setEdited() and get this property's value with edited().

int hMargin

This property holds the horizontal margin The horizontal margin current set. The default is 3.

Set this property's value with setHMargin() and get this property's value with hMargin().

int length

This property holds the length of the text.

Get this property's value with length().

int maxLength

This property holds the maximum length of the text.

The currently set text length limit, or -1 if there is no limit (this is the default).

Set this property's value with setMaxLength() and get this property's value with maxLength().

int maxLineWidth

This property holds the maximum line width in pixels Returns the width in pixels of the longest text line in this editor.

Get this property's value with maxLineWidth().

int maxLines

This property holds the maximum number of lines The currently set line limit, or -1 if there is no limit (the default).

Note that excess lines are deleted from the bottom of the lines. If you want teletype behaviour with lines disappearing from the top as the limit is exceed, you probably just want to use removeLine(0) prior to adding an excess line.

Set this property's value with setMaxLines() and get this property's value with maxLines().

int numLines

This property holds the number of lines in the multi-line edit.

numLines() returns the number of lines in the editor. The count includes any empty lines at top and bottom, so for an empty editor this method will return 1.

Get this property's value with numLines().

bool overWriteMode

This property holds the overwrite mode.

Set this property's value with setOverwriteMode() and get this property's value with isOverwriteMode().

bool readOnly

This property holds whether the multi-line edit is read-only.

Set this property's value with setReadOnly() and get this property's value with isReadOnly().

QString text

This property holds the multi-line edit's text.

Set this property's value with setText() and get this property's value with text().

int undoDepth

This property holds the undo depth.

The maximum number of operations that can be stored on the undo stack.

See also undoDepth.

Set this property's value with setUndoDepth() and get this property's value with undoDepth().

bool undoEnabled

This property holds whether undo is enabled.

Set this property's value with setUndoEnabled() and get this property's value with isUndoEnabled().

WordWrap wordWrap

This property holds the word wrap mode.

By default, wrapping keeps words intact. To allow breaking within words, set the wrap policy to Anywhere (see setWrapPolicy() ).

The default wrap mode is NoWrap.

See also wrapColumnOrWidth and wrapPolicy.

Set this property's value with setWordWrap() and get this property's value with wordWrap().

int wrapColumnOrWidth

This property holds the wrap width in columns or pixels The wrap column or wrap width, depending on the word wrap mode.

Set this property's value with setWrapColumnOrWidth() and get this property's value with wrapColumnOrWidth().

See also wordWrap and wrapColumnOrWidth.

WrapPolicy wrapPolicy

This property holds the wrap policy mode The default is AtWhiteSpace.

Set this property's value with setWrapPolicy() and get this property's value with wrapPolicy().

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


qtmultilineedit.h Include File

qtmultilineedit.h

This is the verbatim text of the qtmultilineedit.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qtmultilineedit.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QtMultiLineEdit widget class
**
** Created : 961005
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file contains a class moved out of the Qt GUI Toolkit API. It
** may be used, distributed and modified without limitation.
**
**********************************************************************/

#ifndef QTMULTILINEEDIT_H
#define QTMULTILINEEDIT_H

#ifndef QT_H
#include "qttableview.h"
#include "qstring.h"
#include "qptrlist.h"
#endif // QT_H

#ifndef QT_NO_QTMULTILINEEDIT

struct QtMultiLineData;
class QtMultiLineEditCommand;
class QValidator;

class QtMultiLineEdit : public QtTableView
{
    Q_OBJECT
    Q_ENUMS( EchoMode WordWrap WrapPolicy )
    Q_PROPERTY( int numLines READ numLines )
    Q_PROPERTY( bool atBeginning READ atBeginning )
    Q_PROPERTY( bool atEnd READ atEnd )
    Q_PROPERTY( int maxLineWidth READ maxLineWidth )
    Q_PROPERTY( Alignment alignment READ alignment WRITE setAlignment )
    Q_PROPERTY( bool edited READ edited WRITE setEdited DESIGNABLE false )
    Q_PROPERTY( EchoMode echoMode READ echoMode WRITE setEchoMode )
    Q_PROPERTY( int maxLength READ maxLength WRITE setMaxLength )
    Q_PROPERTY( int maxLines READ maxLines WRITE setMaxLines )
    Q_PROPERTY( int hMargin READ hMargin WRITE setHMargin )
    Q_PROPERTY( WordWrap wordWrap READ wordWrap WRITE setWordWrap )
    Q_PROPERTY( int wrapColumnOrWidth READ wrapColumnOrWidth WRITE setWrapColumnOrWidth )
    Q_PROPERTY( WrapPolicy wrapPolicy READ wrapPolicy WRITE setWrapPolicy )
    Q_PROPERTY( bool autoUpdate READ autoUpdate WRITE setAutoUpdate DESIGNABLE false )
    Q_PROPERTY( bool undoEnabled READ isUndoEnabled WRITE setUndoEnabled )
    Q_PROPERTY( int undoDepth READ undoDepth WRITE setUndoDepth )
    Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly )
    Q_PROPERTY( bool overWriteMode READ isOverwriteMode WRITE setOverwriteMode )
    Q_PROPERTY( QString text READ text WRITE setText )
    Q_PROPERTY( int length READ length )

public:
    QtMultiLineEdit( QWidget *parent=0, const char *name=0 );
   ~QtMultiLineEdit();

    QString textLine( int line ) const;
    int numLines() const;

    QSize sizeHint() const;
    QSize minimumSizeHint() const;
    QSizePolicy sizePolicy() const;

    virtual void setFont( const QFont &font );

    virtual void insertLine( const QString &s, int line = -1 );
    virtual void insertAt( const QString &s, int line, int col, bool mark = FALSE );
    virtual void removeLine( int line );

    void cursorPosition( int *line, int *col ) const;
    virtual void setCursorPosition( int line, int col, bool mark = FALSE );
    void getCursorPosition( int *line, int *col ) const;
    bool atBeginning() const;
    bool atEnd() const;

    virtual void setFixedVisibleLines( int lines );

    int maxLineWidth() const;

    void setAlignment( int flags );
    int alignment() const;

    virtual void setValidator( const QValidator * );
    const QValidator * validator() const;

    void setEdited( bool );
    bool edited() const;

    void cursorWordForward( bool mark );
    void cursorWordBackward( bool mark );

    enum EchoMode { Normal, NoEcho, Password };
    virtual void setEchoMode( EchoMode );
    EchoMode echoMode() const;

    void setMaxLength(int);
    int maxLength() const;
    virtual void setMaxLineLength(int);
    int maxLineLength() const;
    virtual void setMaxLines(int);
    int maxLines() const;
    virtual void setHMargin(int);
    int hMargin() const;

    virtual void setSelection( int row_from, int col_from, int row_to, int col_t );

    enum WordWrap {
    NoWrap,
    WidgetWidth,
    FixedPixelWidth,
    FixedColumnWidth
    };
    void setWordWrap( WordWrap mode );
    WordWrap wordWrap() const;
    void setWrapColumnOrWidth( int );
    int wrapColumnOrWidth() const;

    enum WrapPolicy {
    AtWhiteSpace,
    Anywhere
    };
    void setWrapPolicy( WrapPolicy policy );
    WrapPolicy wrapPolicy() const;

    bool autoUpdate()	const;
    virtual void setAutoUpdate( bool );

    void setUndoEnabled( bool );
    bool isUndoEnabled() const;
    void setUndoDepth( int );
    int undoDepth() const;

    bool isReadOnly() const;
    bool isOverwriteMode() const;

    QString text() const;

    int length() const;

    static void setDefaultTabStop( int ex );
    static int defaultTabStop();
public slots:
    virtual void       setText( const QString &);
    virtual void       setReadOnly( bool );
    virtual void       setOverwriteMode( bool );

    void       clear();
    void       append( const QString &);
    void       deselect();
    void       selectAll();
#ifndef QT_NO_CLIPBOARD
    void       paste();
    void       pasteSubType(const QCString& subtype);
    void       copyText() const;
    void       copy() const;
    void       cut();
#endif
    void       insert( const QString& );
    void       undo();
    void       redo();

signals:
    void	textChanged();
    void	returnPressed();
    void	undoAvailable( bool );
    void	redoAvailable( bool );
    void	copyAvailable( bool );

protected:
    void	paintCell( QPainter *, int row, int col );
    bool	event( QEvent * );

    void	mousePressEvent( QMouseEvent * );
    void	mouseMoveEvent( QMouseEvent * );
    void	mouseReleaseEvent( QMouseEvent * );
    void	mouseDoubleClickEvent( QMouseEvent * );
    void 	wheelEvent( QWheelEvent * );
    void	keyPressEvent( QKeyEvent * );
    void	focusInEvent( QFocusEvent * );
    void	focusOutEvent( QFocusEvent * );
    void	timerEvent( QTimerEvent * );
    void	leaveEvent( QEvent * );
    void	resizeEvent( QResizeEvent * );

    bool	focusNextPrevChild( bool );

#ifndef QT_NO_DRAGANDDROP
    void	dragMoveEvent( QDragMoveEvent* );
    void	dragEnterEvent( QDragEnterEvent * );
    void	dropEvent( QDropEvent* );
    void	dragLeaveEvent( QDragLeaveEvent* );
#endif

    bool	hasMarkedText() const;
    QString	markedText() const;
    int		textWidth( int );
    int		textWidth( const QString &);

    QPoint	cursorPoint() const;

protected:
    virtual void insert( const QString&, bool mark );
    virtual void newLine();
    virtual void killLine();
    virtual void pageUp( bool mark=FALSE );
    virtual void pageDown( bool mark=FALSE );
    virtual void cursorLeft( bool mark=FALSE, bool wrap = TRUE );
    virtual void cursorRight( bool mark=FALSE, bool wrap = TRUE );
    virtual void cursorUp( bool mark=FALSE );
    virtual void cursorDown( bool mark=FALSE );
    virtual void backspace();
    virtual void del();
    virtual void home( bool mark=FALSE );
    virtual void end( bool mark=FALSE );

    bool getMarkedRegion( int *line1, int *col1,
              int *line2, int *col2 ) const;
    int lineLength( int row ) const;
    QString *getString( int row ) const;
    bool isEndOfParagraph( int row ) const;
    QString stringShown( int row ) const;

protected:
    bool	cursorOn;
    void	insertChar( QChar );

private slots:
    void	clipboardChanged();
    void	blinkTimerTimeout();
    void	scrollTimerTimeout();
    void	dndTimeout();

private:
#ifndef QT_NO_MIME
    QCString pickSpecial(QMimeSource* ms, bool always_ask, const QPoint&);
#endif
#ifndef QT_NO_MIMECLIPBOARD
    void       pasteSpecial(const QPoint&);
#endif
    struct QtMultiLineEditRow {
    QtMultiLineEditRow( QString string, int width, bool nl = TRUE )
        :s(string), w(width), newline( nl )
    {
    };
    QString s;
    int w;
    bool newline;
    };
    QPtrList<QtMultiLineEditRow> *contents;
    QtMultiLineData *d;

    bool	readOnly;
    bool	dummy;
    bool	markIsOn;
    bool	dragScrolling ;
    bool	dragMarking;
    bool	textDirty;
    bool	wordMark;
    bool	overWrite;

    int		cursorX;
    int		cursorY;
    int		markAnchorX;
    int		markAnchorY;
    int		markDragX;
    int		markDragY;
    int		curXPos;	// cell coord of cursor
    int		blinkTimer; // #### not used anymore - remove in 3.0
    int		scrollTimer; // #### not used anymore - remove in 3.0

    int		mapFromView( int xPos, int row );
    int		mapToView( int xIndex, int row );

    void	pixelPosToCursorPos(QPoint p, int* x, int* y) const;
    void	setCursorPixelPosition(QPoint p, bool clear_mark=TRUE);

    void	setWidth( int );
    void	updateCellWidth();
    bool 	partiallyInvisible( int row );
    void	makeVisible();
    void	setBottomCell( int row );

    void 	newMark( int posx, int posy, bool copy=TRUE );
    void 	markWord( int posx, int posy );
    void	extendSelectionWord( int &newX, int&newY);
    int 	charClass( QChar );
    void	turnMark( bool on );
    bool	inMark( int posx, int posy ) const;
    bool	beforeMark( int posx, int posy ) const;
    bool	afterMark( int posx, int posy ) const;
    int		setNumRowsAndTruncate();

#ifndef QT_NO_DRAGANDDROP
    void	doDrag();
#endif
    void	startAutoScroll();
    void	stopAutoScroll();

    void	cursorLeft( bool mark, bool clear_mark, bool wrap );
    void	cursorRight( bool mark, bool clear_mark, bool wrap );
    void	cursorUp( bool mark, bool clear_mark );
    void	cursorDown( bool mark, bool clear_mark );

    void	wrapLine( int line, int removed = 0);
    void	rebreakParagraph( int line, int removed = 0 );
    void	rebreakAll();
    void	insertAtAux( const QString &s, int line, int col, bool mark = FALSE );
    void	killLineAux();
    void	delAux();
    int	positionToOffsetInternal( int row, int col ) const;
    void	offsetToPositionInternal( int position, int *row, int *col ) const;
    void	deleteNextChar( int offset, int row, int col );

    void addUndoCmd( QtMultiLineEditCommand* );
    void addRedoCmd( QtMultiLineEditCommand* );
    void processCmd( QtMultiLineEditCommand*, bool );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QtMultiLineEdit( const QtMultiLineEdit & );
    QtMultiLineEdit &operator=( const QtMultiLineEdit & );
#endif
};

inline bool QtMultiLineEdit::isReadOnly() const { return readOnly; }

inline bool QtMultiLineEdit::isOverwriteMode() const { return overWrite; }

inline void QtMultiLineEdit::setOverwriteMode( bool on )
{
    overWrite = on;
 }

inline int QtMultiLineEdit::lineLength( int row ) const
{
    return contents->at( row )->s.length();
}

inline bool QtMultiLineEdit::atEnd() const
{
    return cursorY == (int)contents->count() - 1
    && cursorX == lineLength( cursorY ) ;
}

inline bool QtMultiLineEdit::atBeginning() const
{
    return cursorY == 0 && cursorX == 0;
}

inline QString *QtMultiLineEdit::getString( int row ) const
{
    return &(contents->at( row )->s);
}

inline int QtMultiLineEdit::numLines() const
{
    return contents->count();
}

#endif // QT_NO_QTMULTILINEEDIT

#endif // QTMULTILINEDIT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QtMultiLineEdit Member List

Complete Member List for QtMultiLineEdit

This is the complete list of member functions for QtMultiLineEdit, including inherited members.

  • QtMultiLineEdit()
  • ~QtMultiLineEdit()
  • acceptDrops()
  • adjustSize()
  • alignment()
  • append()
  • atBeginning()
  • atEnd()
  • autoMask()
  • autoUpdate()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • backspace()
  • baseSize()
  • blockSignals()
  • caption()
  • cellHeight()
  • cellUpdateRect()
  • cellWidth()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearTableFlags()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colIsVisible()
  • colXPos()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • copy()
  • copyAvailable()
  • copyText()
  • create()
  • cursor()
  • cursorDown()
  • cursorLeft()
  • cursorPoint()
  • cursorPosition()
  • cursorRight()
  • cursorUp()
  • cursorWordBackward()
  • cursorWordForward()
  • customEvent()
  • customWhatsThis()
  • cut()
  • defaultTabStop()
  • del()
  • deleteLater()
  • deselect()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • echoMode()
  • edited()
  • enabledChange()
  • end()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • findCol()
  • findRow()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getCursorPosition()
  • getMarkedRegion()
  • getString()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • hMargin()
  • handle()
  • hasFocus()
  • hasMarkedText()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • home()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertAt()
  • insertChar()
  • insertChild()
  • insertLine()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isEndOfParagraph()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isOverwriteMode()
  • isPopup()
  • isReadOnly()
  • isTopLevel()
  • isUndoEnabled()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killLine()
  • killTimer()
  • killTimers()
  • lastColVisible()
  • lastRowVisible()
  • layout()
  • leaveEvent()
  • leftCell()
  • length()
  • lineLength()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • markedText()
  • maxColOffset()
  • maxLength()
  • maxLineLength()
  • maxLineWidth()
  • maxLines()
  • maxRowOffset()
  • maxViewX()
  • maxViewY()
  • maxXOffset()
  • maxYOffset()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minViewX()
  • minViewY()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • newLine()
  • normalizeSignalSlot()
  • numCols()
  • numLines()
  • numRows()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • pageDown()
  • pageUp()
  • paintCell()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • paste()
  • pasteSubType()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • redo()
  • redoAvailable()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeLine()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • returnPressed()
  • rowIsVisible()
  • rowYPos()
  • scroll()
  • selectAll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setAutoUpdate()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellHeight()
  • setCellWidth()
  • setCursor()
  • setCursorPosition()
  • setDefaultTabStop()
  • setDisabled()
  • setEchoMode()
  • setEdited()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedVisibleLines()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHMargin()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLeftCell()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaxLength()
  • setMaxLineLength()
  • setMaxLines()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNumCols()
  • setNumRows()
  • setOffset()
  • setOverwriteMode()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setReadOnly()
  • setSelection()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTableFlags()
  • setText()
  • setTopCell()
  • setTopLeftCell()
  • setUndoDepth()
  • setUndoEnabled()
  • setUpdatesEnabled()
  • setValidator()
  • setWFlags()
  • setWordWrap()
  • setWrapColumnOrWidth()
  • setWrapPolicy()
  • setXOffset()
  • setYOffset()
  • setupPainter()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • stringShown()
  • style()
  • styleChange()
  • tableFlags()
  • tabletEvent()
  • testTableFlags()
  • testWFlags()
  • text()
  • textChanged()
  • textLine()
  • textWidth()
  • timerEvent()
  • topCell()
  • topLevelWidget()
  • totalHeight()
  • totalWidth()
  • tr()
  • trUtf8()
  • undo()
  • undoAvailable()
  • undoDepth()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateCell()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • updateTableSize()
  • validator()
  • verticalScrollBar()
  • viewHeight()
  • viewRect()
  • viewWidth()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • wordWrap()
  • wrapColumnOrWidth()
  • wrapPolicy()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xOffset()
  • y()
  • yOffset()


QToolBar类

QToolBar类参考

QToolBar类提供乐意可以包含工具按钮这类的窗口部件的可移动的面板。 详情请见……

#include <qtoolbar.h>

继承了QDockWindow。

所有成员函数的列表。

公有成员

  • QToolBar ( const QString & label, QMainWindow *, ToolBarDock = DockTop, bool newLine = FALSE, const char * name = 0 ) (obsolete)
  • QToolBar ( const QString & label, QMainWindow * mainWindow, QWidget * parent, bool newLine = FALSE, const char * name = 0, WFlags f = 0 )
  • QToolBar ( QMainWindow * parent = 0, const char * name = 0 )
  • void addSeparator ()
  • QMainWindow * mainWindow () const
  • virtual void setStretchableWidget ( QWidget * w )
  • virtual void setLabel ( const QString & )
  • QString label () const
  • virtual void clear ()

属性

  • QString label - 工具条的标签

详细描述

QToolBar类提供乐意可以包含工具按钮这类的窗口部件的可移动的面板。

工具条是包含一套控制的面板，通常表现为小图标。它用于提供常用命令或者选项的快速访问。在QMainWindow里面，用户可以锚接区域里面或者之间拖动工具条。工具条也可以被拖动出任何锚接区域而作为顶级窗口自由浮动。

QToolBar是QDockWindow的特殊化，并且提供QDockWindow的所有功能。

为了使用QToolBar，你可以简单的把QToolBar创建为QMainWindow的子对象，从左到右（或者从上到下）创建许多QToolButton窗口部件（或者其他窗口部件）并且当你想要一个分隔符，请调用addSeparator()。当工具条被浮动时，标题会使用在构造函数中给定的标签。这个可以通过setLabel()来改变。

        QToolBar * fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );
        fileOpenAction->addTo( fileTools );
        fileSaveAction->addTo( fileTools );

这是从application/application.cpp实例中提取出来的，显示了把新的工具条创建为QMainWindow的子对象并且添加两个QAction。

你可以在工具条中使用绝大多数窗口部件，最常用的时QToolButton和QComboBox。

注意如果你在一个已经可视的QToolBar上创建一个新的窗口部件，这个窗口部件可以在没有明显调用show()的情况下就会自动变为可视（这和Qt中其他窗口部件容器不一样）。总之，请为你放入可视的QToolBar的所有窗口部件明显地调用show()，这个行为也许在未来会被确定下来。

QToolBar，像QDockWindow一样，可以被定位在QDockArea中或者像顶级窗口一样浮动。QMainWindow提供了四个QDockArea（上、下、左、右）。当你创建一个新工具条（像上述实例一样）作为QMainWindow的子对象时，这个工具条会被添加到上面的锚接区域。你可以通过调用QMainWindow::moveDockWindow()把它移动到其它锚接区域（或者浮动起来）。QDockarea在行中布局它们的窗口。

如果主窗口被重新定义大小，这样工具条所占的区域会变小以至于不能显示所有窗口部件，这时一个小箭头按钮（看起来像指向右的V形符号，“»”）将会根据工具条的方向显示在工具条的右面或者下面。点击这个按钮将会弹出一个菜单来显示那些“过剩的”项。

通常工具条将会得到它所需要的空间。可是，通过setHorizontalStretchable()、setVerticalStretchable()或 setStretchableWidget()，你可以告诉主窗口在指定的方向延伸工具条来填充所有可用的空间。

工具条在水平方向或者垂直方向（详细情况请参考orientation()）上排列它的按钮。通常QDockArea将会为你设置正确的方向，但是你可以使用setOrientation()来自己设置它并且通过连接到orientationChanged()信号来跟踪任何变化。

你可以使用clear()方法来移除工具条的所有条目。

Toolbar (dock window)

一个浮动的QToolbar（锚接窗口）

也可以参考QToolButton、QMainWindow、Parts of Isys on Visual Design、图形用户界面设计手册：工具条和主窗口和相关类。

成员函数文档

QToolBar::QToolBar ( const QString & label, QMainWindow *, ToolBarDock = DockTop, bool newLine = FALSE, const char * name = 0 )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

QToolBar::QToolBar ( const QString & label, QMainWindow * mainWindow, QWidget * parent, bool newLine = FALSE, const char * name = 0, WFlags f = 0 )

构造一个空的水平工具条。

工具条是parent的子对象并且被mainWindow管理。label和newLine 参数被直接传递给QMainWindow::addDockWindow()。name是对象名称并且f是窗口部件标记。

如果你想创建已经取消锚接正在浮动的工具条或者状态条中的工具条时请使用这个构造函数。

QToolBar::QToolBar ( QMainWindow * parent = 0, const char * name = 0 )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

构造一个在parent的上面锚接区域中的父对象为parent并且名称为name的空工具条。没有任何标签并且不需要一个新行。

void QToolBar::addSeparator ()

在工具条的右面/下面添加一个分隔符。

实例：chart/chartform.cpp、fileiconview/mainwindow.cpp、helpviewer/helpwindow.cpp、qfd/fontdisplayer.cpp和scribble/scribble.cpp。

void QToolBar::clear () [虚]

删除工具条的所有子窗口部件。

QString QToolBar::label () const

返回工具条的标签。详细情况请参考“label”属性。

QMainWindow * QToolBar::mainWindow () const

返回一个管理这个工具条的QMainWindow的指针。

void QToolBar::setLabel ( const QString & ) [虚]

设置工具条的标签。详细情况请参考“label”属性。

void QToolBar::setStretchableWidget ( QWidget * w ) [虚]

如果这个工具条被需要延伸，设置窗口部件w被延伸。

因为QMainWindow正确调整它里面的锚接区域，或者因为这个工具条的isVerticalStretchable()或者isHorizontalStretchable()被设置为真，这个延伸的请求也许会发生。

如果你调用这个函数并且工具条还不是可延伸的，setStretchable()被调用。

也可以参考QMainWindow::rightJustification、setVerticalStretchable()和setHorizontalStretchable()。

实例：fileiconview/mainwindow.cpp和helpviewer/helpwindow.cpp。

属性文档

QString label

这个属性保存的是工具条的标签。

如果工具条被浮动，标签就变为工具条窗口的标题。这里没有默认标签文本。

通过setLabel()设置属性值并且通过label()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtoolbar.h包含文件

qtoolbar.h

这里是qtoolbar.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtoolbar.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QToolBar class
**
** Created : 980306
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTOOLBAR_H
#define QTOOLBAR_H

#ifndef QT_H
#include "qdockwindow.h"
#endif // QT_H

#ifndef QT_NO_TOOLBAR

class QMainWindow;
class QButton;
class QBoxLayout;
class QToolBarPrivate;

class Q_EXPORT QToolBar: public QDockWindow
{
    Q_OBJECT
    Q_PROPERTY( QString label READ label WRITE setLabel )

public:
    QToolBar( const QString &label,
          QMainWindow *, ToolBarDock = DockTop,
          bool newLine = FALSE, const char* name=0 );
    QToolBar( const QString &label, QMainWindow *, QWidget *,
          bool newLine = FALSE, const char* name=0, WFlags f = 0 );
    QToolBar( QMainWindow* parent=0, const char* name=0 );
    ~QToolBar();

    void addSeparator();

    void show();
    void hide();

    QMainWindow * mainWindow() const;

    virtual void setStretchableWidget( QWidget * );

    bool event( QEvent * e );

    virtual void setLabel( const QString & );
    QString label() const;

    virtual void clear();

    QSize minimumSize() const;
    QSize minimumSizeHint() const;

    void setOrientation( Orientation o );
    void setMinimumSize( int minw, int minh );

protected:
    void resizeEvent( QResizeEvent *e );
    void styleChange( QStyle & );

private slots:
    void popupSelected( int id );
    void emulateButtonClicked();
    void setupArrowMenu();

private:
    void init();

    QToolBarPrivate * d;
    QMainWindow * mw;
    QWidget * sw;
    QString l;

    friend class QMainWindow;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QToolBar( const QToolBar & );
    QToolBar& operator=( const QToolBar & );
#endif
};

#endif // QT_NO_TOOLBAR

#endif // QTOOLBAR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QToolBar成员列表

完整的QToolBar成员列表

这里是QToolBar成员函数的完整列表，包括继承的成员。

  • QToolBar()
  • acceptDrops()
  • addSeparator()
  • adjustSize()
  • area()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • boxLayout()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clear()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • closeMode()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dock()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • fixedExtent()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isCloseEnabled()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isHorizontalStretchable()
  • isHorizontallyStretchable()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isMovingEnabled()
  • isPopup()
  • isResizeEnabled()
  • isStretchable()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVerticalStretchable()
  • isVerticallyStretchable()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • label()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mainWindow()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • newLine()
  • normalizeSignalSlot()
  • objectTrees()
  • offset()
  • opaqueMoving()
  • orientation()
  • orientationChanged()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • place()
  • placeChanged()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCloseMode()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedExtentHeight()
  • setFixedExtentWidth()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setHorizontalStretchable()
  • setHorizontallyStretchable()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLabel()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setMovingEnabled()
  • setName()
  • setNewLine()
  • setOffset()
  • setOpaqueMoving()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResizeEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStretchableWidget()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setVerticalStretchable()
  • setVerticallyStretchable()
  • setWFlags()
  • setWidget()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • undock()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibilityChanged()
  • visibleRect()
  • wheelEvent()
  • widget()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QToolButton类

QToolButton类参考

QToolButton类提供了用于命令或者选项的可以快速访问的按钮，通常可以用在QToolBar里面。 详情请见……

#include <qtoolbutton.h>

继承了QButton。

所有成员函数的列表。

公有成员

  • QToolButton ( QWidget * parent, const char * name = 0 )
  • QToolButton ( const QIconSet & iconSet, const QString & textLabel, const QString & grouptext, QObject * receiver, const char * slot, QToolBar * parent, const char * name = 0 )
  • QToolButton ( ArrowType type, QWidget * parent, const char * name = 0 )
  • ~QToolButton ()
  • void setOnIconSet ( const QIconSet & ) （废弃）
  • void setOffIconSet ( const QIconSet & ) （废弃）
  • void setIconSet ( const QIconSet & set, bool on ) （废弃）
  • QIconSet onIconSet () const （废弃）
  • QIconSet offIconSet () const （废弃）
  • QIconSet iconSet ( bool on ) const （废弃）
  • virtual void setIconSet ( const QIconSet & )
  • QIconSet iconSet () const
  • bool usesBigPixmap () const
  • bool usesTextLabel () const
  • QString textLabel () const
  • void setPopup ( QPopupMenu * popup )
  • QPopupMenu * popup () const
  • void setPopupDelay ( int delay )
  • int popupDelay () const
  • void openPopup ()
  • void setAutoRaise ( bool enable )
  • bool autoRaise () const

公有槽

  • virtual void setUsesBigPixmap ( bool enable )
  • virtual void setUsesTextLabel ( bool enable )
  • virtual void setTextLabel ( const QString & newLabel, bool tipToo )
  • virtual void setToggleButton ( bool enable )
  • virtual void setOn ( bool enable )
  • void toggle ()
  • void setTextLabel ( const QString & )

属性

  • bool autoRaise - 自动浮起是否生效
  • QIconSet iconSet - 提供显示在按钮上的图标的图标集
  • QIconSet offIconSet - 当按钮在“关”状态时使用的图标集 （废弃）
  • bool on - 工具按钮是否为开
  • QIconSet onIconSet - 当按钮在“开”状态时使用的图标集 （废弃）
  • int popupDelay - 在按下按钮和出现关联的弹出按钮之间的以毫秒为单位的时间
  • QString textLabel - 按钮的标签
  • bool toggleButton - 工具按钮是否是切换按钮
  • bool usesBigPixmap - 工具按钮是否使用大的像素映射
  • bool usesTextLabel - 工具按钮是否在按钮像素映射下方显示标签

保护成员

  • bool uses3D () const

详细描述

QToolButton类提供了用于命令或者选项的可以快速访问的按钮，通常可以用在QToolBar里面。

工具按钮是提供对特定命令或者选项快速访问的特殊按钮。和普通的命令按钮不同，工具按钮通常不显示文本标签，而是图标。它的经典用法事选择工具，例如在一个绘图程序中的“笔”工具。这个被QToolButton作为切换按钮重新实现。（请参考setToggleButton()）。

QToolButton支持自动浮起。在自动浮起模式中，按钮只有在鼠标指向它的时候才绘制三维的框架。当按钮被用在QToolBar里面的时候，这个特征会自动被启用。可以使用setAutoRaise()来改变它。

工具按钮的图标是被设置为QIconSet。这使得它可以为失效和激活状态指定不同的像素映射。当按钮的功能不可用的时候，失效的像素映射被使用。当因为用户用鼠标指向按钮而自动浮起时，激活的像素映射被显示。

按钮的外观和尺寸可以通过setUsesBigPixmap()和setUsesTextLabel()来调节。当被用在QToolBar里面时，按钮会自动地调节来适合QMainWindow的设置（请参考QMainWindow::setUsesTextLabel()和QMainWindow::setUsesBigPixmaps()）。

工具按钮可以提供一个弹出菜单的额外选择。这个特征有时对于网页浏览器中的“后退”按钮是有用的。在按下按钮一段时间之后，一个菜单会弹出来显示所有可以后退浏览的可能页面。你可以使用setPopup()来为QToolButton设置一个弹出菜单。默认延时是600毫秒，你可以使用setPopupDelay()来调节它。

Toolbar with Toolbuttons

一个有QToolbutton的浮动的QToolbar

也可以参考QPushButton、QToolBar、QMainWindow、图形用户界面设计手册：推动按钮和基本窗口部件。

成员函数文档

QToolButton::QToolButton ( QWidget * parent, const char * name = 0 )

构造一个父对象为parent并且名称为name的空工具按钮。

QToolButton::QToolButton ( const QIconSet & iconSet, const QString & textLabel, const QString & grouptext, QObject * receiver, const char * slot, QToolBar * parent, const char * name = 0 )

构造一个父对象为parent（必须为QToolBar）并且名称为name的工具按钮。

工具按钮将显示iconSet，它的文本标签和工具提示设置为textLabel并且它的状态条信息设置为grouptext。它将被连接到receiver对象的slot槽。

QToolButton::QToolButton ( ArrowType type, QWidget * parent, const char * name = 0 )

把工具按钮构造为箭头按钮。ArrowType type定义了箭头的方向。可用的值为LeftArrow、RightArrow、UpArrow和DownArrow。

箭头按钮的自动重复默认是打开的。

parent和name参数被发送给QWidget构造函数。

QToolButton::~QToolButton ()

销毁这个对象并且释放任何被分配的资源。

bool QToolButton::autoRaise () const

如果自动浮起有效，返回真，否则返回假。详细情况请参考“autoRaise”属性。

QIconSet QToolButton::iconSet () const

返回提供显示在按钮上的图标的图标集。详细情况请参考“iconSet”属性。

QIconSet QToolButton::iconSet ( bool on ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

从Qt 3.0开始，QIconSet可以包含开和关两套图标了。

为了方便移植，这个函数将忽略on参数并且返回iconSet属性。如果你依赖于on参数，你也许要把你的代码升级到QIconSet开/关机制了。

QIconSet QToolButton::offIconSet () const

返回当按钮在“关”状态下被使用的图标集。详细情况请参考“offIconSet”属性。

QIconSet QToolButton::onIconSet () const

返回当按钮在“开”状态下被使用的图标集。详细情况请参考“onIconSet”属性。

void QToolButton::openPopup ()

打开（弹出）关联的弹出菜单。如果没有这样的菜单，这个函数就什么也不做。直到这个弹出菜单已经被用户关闭，这个函数才会返回。

QPopupMenu * QToolButton::popup () const

返回关联的弹出菜单，或者如果没有定义弹出菜单，返回0。

也可以参考setPopup()。

int QToolButton::popupDelay () const

返回在按下按钮和出现关联的弹出按钮之间的以毫秒为单位的时间。详细情况请参考“popupDelay”属性。

void QToolButton::setAutoRaise ( bool enable )

设置自动浮起是否有效为enable。详细情况请参考“autoRaise”属性。

void QToolButton::setIconSet ( const QIconSet & ) [虚]

设置提供显示在按钮上的图标的图标集。详细情况请参考“iconSet”属性。

void QToolButton::setIconSet ( const QIconSet & set, bool on )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

从Qt 3.0开始，QIconSet可以包含开和关两套图标了。

为了方便移植，这个函数将忽略on参数并且返回iconSet属性。如果你依赖于on参数，你也许要把你的代码升级到QIconSet开/关机制了。

也可以参考iconSet和QIconSet::State。

void QToolButton::setOffIconSet ( const QIconSet & )

设置当按钮在“关”状态下被使用的图标集。详细情况请参考“offIconSet”属性。

void QToolButton::setOn ( bool enable ) [虚 槽]

设置按钮是否为开为enable。详细情况请参考“on”属性。

void QToolButton::setOnIconSet ( const QIconSet & )

设置当按钮在“开”状态下被使用的图标集。详细情况请参考“onIconSet”属性。

void QToolButton::setPopup ( QPopupMenu * popup )

把弹出菜单popup和这个工具按钮关联起来。

每次在工具按钮被按下一定时间之后，弹出菜单将被显示。一个经典的实例是一些网页浏览器的工具条上的“后退”按钮。如果用户点击它，浏览器简单地后退浏览到上一页。如果用户按下这个按钮一段时间，工具按钮会显示一个包含当前历史列表的菜单。

弹出菜单的所有权不会被传递给工具按钮。

也可以参考popup()。

void QToolButton::setPopupDelay ( int delay )

设置在按下按钮和出现关联的弹出按钮之间的以毫秒为单位的时间。详细情况请参考“popupDelay”属性。

void QToolButton::setTextLabel ( const QString & ) [槽]

设置按钮的标签。详细情况请参考“textLabel”属性。

void QToolButton::setTextLabel ( const QString & newLabel, bool tipToo ) [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置按钮的标签为newLabel并且如果tipToo为真，自动地把工具提示也设置为newLabel。

void QToolButton::setToggleButton ( bool enable ) [虚 槽]

设置工具按钮是否是切换按钮为enable。详细情况请参考“toggleButton”属性。

void QToolButton::setUsesBigPixmap ( bool enable ) [虚 槽]

设置工具按钮是否使用大的像素映射为enable。详细情况请参考“usesBigPixmap”属性。

void QToolButton::setUsesTextLabel ( bool enable ) [虚 槽]

设置工具按钮是否在按钮像素映射下方显示标签为enable。详细情况请参考“usesTextLabel”属性。

QString QToolButton::textLabel () const

返回按钮的标签。详细情况请参考“textLabel”属性。

void QToolButton::toggle () [槽]

切换工具按钮的状态。

这个函数对于非切换按钮无效。

也可以参考toggleButton和toggled()。

bool QToolButton::uses3D () const [保护]

如果这个按钮应该被使用浮起的边缘绘制，返回真，否则返回假。

也可以参考drawButton()。

bool QToolButton::usesBigPixmap () const

如果工具按钮使用大地像素映射，返回真，否则返回假。详细情况请参考“usesBigPixmap”属性。

bool QToolButton::usesTextLabel () const

如果工具按钮在按钮像素映射下方显示标签，返回真，否则返回假。详细情况请参考“usesTextLabel”属性。

属性文档

bool autoRaise

这个属性保存的是自动浮起是否生效。

默认是失效的（也就是假）。

通过setAutoRaise()设置属性值并且通过autoRaise()来获得属性值。

QIconSet iconSet

这个属性保存的是提供显示在按钮上的图标的图标集。

设置这个属性把QToolButton::pixmap设置为零像素映射。没有默认图标集。

也可以参考pixmap、toggleButton和on。

通过setIconSet()设置属性值并且通过iconSet()来获得属性值。

QIconSet offIconSet

这个属性保存的是当按钮在“关”状态时使用的图标集。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

从Qt 3.0开始，QIconSet可以包含开和关两套图标了。现在QToolButton::iconSet属性替换了QToolButton::onIconSet和QToolButton::offIconSet。

为了方便移植，这个函数将忽略on参数并且返回iconSet属性。如果你依赖于on参数，你也许要把你的代码升级到QIconSet开/关机制了。

也可以参考iconSet和QIconSet::State。

通过setOffIconSet()设置属性值并且通过offIconSet()来获得属性值。

bool on

这个属性保存的是工具按钮是否为开。

这个属性对于非切换按钮无效。默认为假（也就是关）。

也可以参考toggleButton和toggle()。

通过setOn()设置属性值。

QIconSet onIconSet

这个属性保存的是当按钮在“开”状态时使用的图标集。

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

从Qt 3.0开始，QIconSet可以包含开和关两套图标了。现在QToolButton::iconSet属性替换了QToolButton::onIconSet和QToolButton::offIconSet。

为了方便移植，这个函数将忽略on参数并且返回iconSet属性。如果你依赖于on参数，你也许要把你的代码升级到QIconSet开/关机制了。

也可以参考iconSet和QIconSet::State。

通过setOnIconSet()设置属性值并且通过onIconSet()来获得属性值。

int popupDelay

这个属性保存的是在按下按钮和出现关联的弹出按钮之间的以毫秒为单位的时间。

通常是在半秒左右。0值可以为工具按钮设置一个特殊区域来打开弹出菜单。

也可以参考setPopup()。

通过setPopupDelay()设置属性值并且通过popupDelay()来获得属性值。

QString textLabel

这个属性保存的是按钮的标签。

设置这个属性会自动地设置这个文本为工具提示。

通过setTextLabel()设置属性值并且通过textLabel()来获得属性值。

bool toggleButton

这个属性保存的是工具按钮是否是切换按钮。

切换按钮像检查框一样也有开/关状态。默认情况下，工具按钮不是切换按钮。

也可以参考on和toggle()。

通过setToggleButton()设置属性值。

bool usesBigPixmap

这个属性保存的是工具按钮是否使用大的像素映射。

QToolButton自动地链接这个属性到它所在的QMainWindow中的相应信号。我们强烈建议你使用QMainWindow::setUsesBigPixmaps()来替代它。

这个属性默认为真。

警告： 如果你设置一些按钮（在QMainWindow中）使用大的像素映射并且其它的使用小的像素映射，QMainWindow可能不能得到正确的几何形状。

通过setUsesBigPixmap()设置属性值并且通过usesBigPixmap()来获得属性值。

bool usesTextLabel

这个属性保存的是工具按钮是否在按钮像素映射下方显示标签。

默认为假。

QToolButton自动地链接这个槽到它所在的QMainWindow中的相应信号。

通过setUsesTextLabel()设置属性值并且通过usesTextLabel()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qtoolbutton.h包含文件

qtoolbutton.h

这里是qtoolbutton.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qtoolbutton.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QToolButton class
**
** Created : 979899
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTOOLBUTTON_H
#define QTOOLBUTTON_H

#ifndef QT_H
#include "qbutton.h"
#include "qstring.h"
#include "qpixmap.h"
#include "qiconset.h"
#endif // QT_H

#ifndef QT_NO_TOOLBUTTON

class QToolButtonPrivate;
class QToolBar;
class QPopupMenu;

class Q_EXPORT QToolButton : public QButton
{
    Q_OBJECT

    Q_PROPERTY( QIconSet iconSet READ iconSet WRITE setIconSet )
    Q_PROPERTY( QIconSet onIconSet READ onIconSet WRITE setOnIconSet DESIGNABLE false STORED false )
    Q_PROPERTY( QIconSet offIconSet READ offIconSet WRITE setOffIconSet DESIGNABLE false STORED false )
    Q_PROPERTY( bool usesBigPixmap READ usesBigPixmap WRITE setUsesBigPixmap )
    Q_PROPERTY( bool usesTextLabel READ usesTextLabel WRITE setUsesTextLabel )
    Q_PROPERTY( QString textLabel READ textLabel WRITE setTextLabel )
    Q_PROPERTY( int popupDelay READ popupDelay WRITE setPopupDelay )
    Q_PROPERTY( bool autoRaise READ autoRaise WRITE setAutoRaise )

    Q_OVERRIDE( bool toggleButton WRITE setToggleButton )
    Q_OVERRIDE( bool on WRITE setOn )

public:
    QToolButton( QWidget * parent, const char* name=0 );
#ifndef QT_NO_TOOLBAR
    QToolButton( const QIconSet& s, const QString &textLabel,
         const QString& grouptext,
         QObject * receiver, const char* slot,
         QToolBar * parent, const char* name=0 );
#endif
    QToolButton( ArrowType type, QWidget *parent, const char* name=0 );
    ~QToolButton();

    QSize sizeHint() const;
    QSize minimumSizeHint() const;

#ifndef QT_NO_COMPAT
    void setOnIconSet( const QIconSet& );
    void setOffIconSet( const QIconSet& );
    void setIconSet( const QIconSet &, bool on );
    QIconSet onIconSet() const;
    QIconSet offIconSet( ) const;
    QIconSet iconSet( bool on ) const;
#endif
    virtual void setIconSet( const QIconSet & );
    QIconSet iconSet() const;

    bool usesBigPixmap() const { return ubp; }
    bool usesTextLabel() const { return utl; }
    QString textLabel() const { return tl; }

#ifndef QT_NO_POPUPMENU
    void setPopup( QPopupMenu* popup );
    QPopupMenu* popup() const;

    void setPopupDelay( int delay );
    int popupDelay() const;

    void openPopup();
#endif

    void setAutoRaise( bool enable );
    bool autoRaise() const;

public slots:
    virtual void setUsesBigPixmap( bool enable );
    virtual void setUsesTextLabel( bool enable );
    virtual void setTextLabel( const QString &, bool );

    virtual void setToggleButton( bool enable );

    virtual void setOn( bool enable );
    void toggle();
    void setTextLabel( const QString & );

protected:
    void mousePressEvent( QMouseEvent * );
    void drawButton( QPainter * );
    void drawButtonLabel(QPainter *);

    void enterEvent( QEvent * );
    void leaveEvent( QEvent * );
    void moveEvent( QMoveEvent * );

    bool uses3D() const;

    bool eventFilter( QObject *o, QEvent *e );

#ifndef QT_NO_PALETTE
    void paletteChange( const QPalette & );
#endif

private slots:
    void popupTimerDone();
    void popupPressed();

private:
    void init();
    bool isOnAndNoOnPixmap();

    QPixmap bp;
    int bpID;
    QPixmap sp;
    int spID;

    QString tl;

    QToolButtonPrivate *d;
    QIconSet *s;

    uint utl : 1;
    uint ubp : 1;
    uint hasArrow : 1;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QToolButton( const QToolButton & );
    QToolButton& operator=( const QToolButton & );
#endif
};

#endif // QT_NO_TOOLBUTTON

#endif // QTOOLBUTTON_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QToolButton成员列表

完整的QToolButton成员列表

这里是QToolButton成员函数的完整列表，包括继承的成员。

  • QToolButton()
  • ~QToolButton()
  • accel()
  • acceptDrops()
  • adjustSize()
  • animateClick()
  • autoMask()
  • autoRaise()
  • autoRepeat()
  • autoResize()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawButton()
  • drawButtonLabel()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • group()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • hitButton()
  • icon()
  • iconSet()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isDown()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusiveToggle()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isOn()
  • isPopup()
  • isToggleButton()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • offIconSet()
  • onIconSet()
  • openPopup()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • pixmap()
  • polish()
  • popup()
  • popupDelay()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAccel()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setAutoRaise()
  • setAutoRepeat()
  • setAutoResize()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setDown()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconSet()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOffIconSet()
  • setOn()
  • setOnIconSet()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setPixmap()
  • setPopup()
  • setPopupDelay()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setState()
  • setStyle()
  • setTabOrder()
  • setText()
  • setTextLabel()
  • setToggleButton()
  • setToggleType()
  • setUpdatesEnabled()
  • setUsesBigPixmap()
  • setUsesTextLabel()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • state()
  • stateChanged()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • text()
  • textLabel()
  • timerEvent()
  • toggle()
  • toggleType()
  • toggled()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • uses3D()
  • usesBigPixmap()
  • usesTextLabel()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QToolTip Class

QToolTip Class Reference

The QToolTip class provides tool tips (balloon help) for any widget or rectangular part of a widget. More...

#include <qtooltip.h>

Inherits Qt.

List of all member functions.

Public Members

  • QToolTip ( QWidget * widget, QToolTipGroup * group = 0 )
  • QWidget * parentWidget () const
  • QToolTipGroup * group () const

Static Public Members

  • void add ( QWidget * widget, const QString & text )
  • void add ( QWidget * widget, const QString & text, QToolTipGroup * group, const QString & longText )
  • void remove ( QWidget * widget )
  • void add ( QWidget * widget, const QRect & rect, const QString & text )
  • void add ( QWidget * widget, const QRect & rect, const QString & text, QToolTipGroup * group, const QString & groupText )
  • void remove ( QWidget * widget, const QRect & rect )
  • QString textFor ( QWidget * widget, const QPoint & pos = QPoint ( ) )
  • void hide ()
  • QFont font ()
  • void setFont ( const QFont & font )
  • QPalette palette ()
  • void setPalette ( const QPalette & palette )
  • void setEnabled ( bool enable ) (obsolete)
  • bool enabled () (obsolete)
  • void setGloballyEnabled ( bool enable )
  • bool isGloballyEnabled ()

Protected Members

  • virtual void maybeTip ( const QPoint & p ) = 0
  • void tip ( const QRect & rect, const QString & text )
  • void tip ( const QRect & rect, const QString & text, const QString & groupText )
  • void clear ()

Detailed Description

The QToolTip class provides tool tips (balloon help) for any widget or rectangular part of a widget.

The tip is a short, single line of text reminding the user of the widget's or rectangle's function. It is drawn immediately below the region in a distinctive black-on-yellow combination.

QToolTipGroup provides a way for tool tips to display another text elsewhere (most often in a status bar).

At any point in time, QToolTip is either dormant or active. In dormant mode the tips are not shown and in active mode they are. The mode is global, not particular to any one widget.

QToolTip switches from dormant to active mode when the user hovers the mouse on a tip-equipped region for a second or so and remains active until the user either clicks a mouse button, presses a key, lets the mouse hover for five seconds or moves the mouse outside all tip-equipped regions for at least a second.

The QToolTip class can be used in three different ways:

  1. Adding a tip to an entire widget.
  2. Adding a tip to a fixed rectangle within a widget.
  3. Adding a tip to a dynamic rectangle within a widget.

To add a tip to a widget, call the static function QToolTip::add() with the widget and tip as arguments:

    QToolTip::add( quitButton, "Leave the application" );

This is the simplest and most common use of QToolTip. The tip will be deleted automatically when quitButton is deleted, but you can remove it yourself, too:

    QToolTip::remove( quitButton );

You can also display another text (typically in a status bar), courtesy of QToolTipGroup. This example assumes that g is a QToolTipGroup * and is already connected to the appropriate status bar:

    QToolTip::add( quitButton, "Leave the application", g,
                   "Leave the application, prompting to save if necessary" );
    QToolTip::add( closeButton, "Close this window", g,
                   "Close this window, prompting to save if necessary" );

To add a tip to a fixed rectangle within a widget, call the static function QToolTip::add() with the widget, rectangle and tip as arguments. (See the tooltip/tooltip.cpp example.) Again, you can supply a QToolTipGroup * and another text if you want.

Both of these are one-liners and cover the majority of cases. The third and most general way to use QToolTip requires you to reimplement a pure virtual function to decide whether to pop up a tool tip. The tooltip/tooltip.cpp example demonstrates this too. This mode can be used to implement tips for text that can move as the user scrolls, for example.

To use QToolTip like this, you need to subclass QToolTip and reimplement maybeTip(). QToolTip calls maybeTip() when a tip should pop up, and maybeTip decides whether to show a tip.

Tool tips can be globally disabled using QToolTip::setGloballyEnabled() or disabled in groups with QToolTipGroup::setEnabled().

You can retreive the text of a tooltip for a given position within a widget using textFor().

The global tooltip font and palette can be set with the static setFont() and setPalette() functions respectively.

See also QStatusBar, QWhatsThis, QToolTipGroup, GUI Design Handbook: Tool Tip and Help System.

Member Function Documentation

QToolTip::QToolTip ( QWidget * widget, QToolTipGroup * group = 0 )

Constructs a tool tip object. This is necessary only if you need tool tips on regions that can move within the widget (most often because the widget's contents can scroll).

widget is the widget you want to add dynamic tool tips to and group (optional) is the tool tip group they should belong to.

Warning: QToolTip is not a subclass of QObject, so the instance of QToolTip is not deleted when widget is deleted.

See also maybeTip().

void QToolTip::add ( QWidget * widget, const QString & text ) [static]

Adds a tool tip to widget. text is the text to be shown in the tool tip.

This is the most common entry point to the QToolTip class; it is suitable for adding tool tips to buttons, check boxes, combo boxes and so on.

Examples: qdir/qdir.cpp, scribble/scribble.cpp and tooltip/tooltip.cpp.

void QToolTip::add ( QWidget * widget, const QString & text, QToolTipGroup * group, const QString & longText ) [static]

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

Adds a tool tip to widget and to tool tip group group.

text is the text shown in the tool tip and longText is the text emitted from group.

Normally, longText is shown in a status bar or similar.

void QToolTip::add ( QWidget * widget, const QRect & rect, const QString & text ) [static]

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

Adds a tool tip to a fixed rectangle, rect, within widget. text is the text shown in the tool tip.

void QToolTip::add ( QWidget * widget, const QRect & rect, const QString & text, QToolTipGroup * group, const QString & groupText ) [static]

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

Adds a tool tip to an entire widget and to tool tip group group. The tooltip will disappear when the mouse leaves the rect.

text is the text shown in the tool tip and groupText is the text emitted from group.

Normally, groupText is shown in a status bar or similar.

void QToolTip::clear () [protected]

Immediately removes all tool tips for this tooltip's parent widget.

bool QToolTip::enabled () [static]

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

QFont QToolTip::font () [static]

Returns the font common to all tool tips.

See also setFont().

QToolTipGroup * QToolTip::group () const

Returns the tool tip group this QToolTip is a member of or 0 if it isn't a member of any group.

The tool tip group is the object responsible for maintaining contact between tool tips and a status bar or something else which can show the longer help text.

See also parentWidget() and QToolTipGroup.

void QToolTip::hide () [static]

Hides any tip that is currently being shown.

Normally, there is no need to call this function; QToolTip takes care of showing and hiding the tips as the user moves the mouse.

bool QToolTip::isGloballyEnabled () [static]

Returns whether tool tips are enabled globally.

See also setGloballyEnabled().

void QToolTip::maybeTip ( const QPoint & p ) [pure virtual protected]

This pure virtual function is half of the most versatile interface QToolTip offers.

It is called when there is a possibility that a tool tip should be shown and must decide whether there is a tool tip for the point p in the widget that this QToolTip object relates to. If so, maybeTip() must call tip() with the rectangle the tip applies to, the tip's text and optionally the QToolTipGroup details.

p is given in that widget's local coordinates. Most maybeTip() implementations will be of the form:

    if ( <something> ) {
        tip( <something>, <something> );
    }

The first argument to tip() (a rectangle) must encompass p, i.e. the tip must apply to the current mouse position; otherwise QToolTip's operation is undefined.

Note that the tip will disappear once the mouse moves outside the rectangle you give to tip(), and will not reappear if the mouse moves back in - maybeTip() is called again instead.

See also tip().

Example: tooltip/tooltip.cpp.

QPalette QToolTip::palette () [static]

Returns the palette common to all tool tips.

See also setPalette().

QWidget * QToolTip::parentWidget () const

Returns the widget this QToolTip applies to.

The tool tip is destroyed automatically when the parent widget is destroyed.

See also group().

void QToolTip::remove ( QWidget * widget ) [static]

Removes the tool tip from widget.

If there is more than one tool tip on widget, only the one covering the entire widget is removed.

void QToolTip::remove ( QWidget * widget, const QRect & rect ) [static]

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

Removes the tool tip for rect from widget.

If there is more than one tool tip on widget, only the one covering rectangle rect is removed.

void QToolTip::setEnabled ( bool enable ) [static]

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

void QToolTip::setFont ( const QFont & font ) [static]

Sets the font for all tool tips to font.

See also font().

void QToolTip::setGloballyEnabled ( bool enable ) [static]

If enable is TRUE sets all tool tips to be enabled (shown when needed); if enable is FALSE sets all tool tips to be disabled (never shown).

By default, tool tips are enabled. Note that this function affects all tool tips in the entire application.

See also QToolTipGroup::enabled.

void QToolTip::setPalette ( const QPalette & palette ) [static]

Sets the palette for all tool tips to palette.

See also palette().

QString QToolTip::textFor ( QWidget * widget, const QPoint & pos = QPoint ( ) ) [static]

Returns the text for widget at position pos, or a null string if there is no tool tip for the widget.

void QToolTip::tip ( const QRect & rect, const QString & text ) [protected]

Immediately pops up a tip saying text and removes the tip once the cursor moves out of rectangle rect (which is given in the coordinate system of the widget this QToolTip relates to).

The tip will not reappear if the cursor moves back; your maybeTip() has to reinstate it each time.

void QToolTip::tip ( const QRect & rect, const QString & text, const QString & groupText ) [protected]

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

Immediately pops up a tip saying text and removes that tip once the cursor moves out of rectangle rect. groupText is the text emitted from the group.

The tip will not reappear if the cursor moves back; your maybeTip() has to reinstate it each time.

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


qtooltip.h Include File

qtooltip.h

This is the verbatim text of the qtooltip.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtooltip.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Tool Tips (or Balloon Help) for any widget or rectangle
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTOOLTIP_H
#define QTOOLTIP_H

#ifndef QT_H
#include "qwidget.h"
#endif // QT_H

#ifndef QT_NO_TOOLTIP

class QTipManager;
class QIconViewToolTip;
class QListViewToolTip;

class Q_EXPORT QToolTipGroup: public QObject
{
    Q_OBJECT
    Q_PROPERTY( bool delay READ delay WRITE setDelay )
    Q_PROPERTY( bool enabled READ enabled WRITE setEnabled )

public:
    QToolTipGroup( QObject *parent, const char *name = 0 );
   ~QToolTipGroup();

    bool delay() const;
    bool enabled() const;

public slots:
    void setDelay( bool );
    void setEnabled( bool );

signals:
    void showTip( const QString &);
    void removeTip();

private:
    uint del:1;
    uint ena:1;

    friend class QTipManager;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QToolTipGroup( const QToolTipGroup & );
    QToolTipGroup& operator=( const QToolTipGroup & );
#endif
};

class Q_EXPORT QToolTip: public Qt
{
public:
    QToolTip( QWidget *, QToolTipGroup * = 0 );

    static void add( QWidget *, const QString &);
    static void add( QWidget *, const QString &,
             QToolTipGroup *, const QString& );
    static void remove( QWidget * );

    static void add( QWidget *, const QRect &, const QString &);
    static void add( QWidget *, const QRect &, const QString &,
             QToolTipGroup *, const QString& );
    static void remove( QWidget *, const QRect & );

    static QString textFor( QWidget *, const QPoint & pos = QPoint() );

    static void hide();

    static QFont    font();
    static void	    setFont( const QFont & );
    static QPalette palette();
    static void	    setPalette( const QPalette & );

#ifndef QT_NO_COMPAT
    static void	    setEnabled( bool enable ) { setGloballyEnabled( enable ); }
    static bool	    enabled() { return isGloballyEnabled(); }
#endif
    static void	    setGloballyEnabled( bool );
    static bool	    isGloballyEnabled();

protected:
    virtual void maybeTip( const QPoint & ) = 0;
    void    tip( const QRect &, const QString &);
    void    tip( const QRect &, const QString& , const QString &);
    void    clear();

public:
    QWidget	  *parentWidget() const { return p; }
    QToolTipGroup *group()	  const { return g; }

private:
    void    tip( const QRect &, const QRect &, const QString &);
    QWidget	    *p;
    QToolTipGroup   *g;
    static QFont    *ttFont;
    static QPalette *ttPalette;

    friend class QTipManager;
    friend class QIconViewToolTip;
    friend class QListViewToolTip;
};

#endif // QT_NO_TOOLTIP

#endif // QTOOLTIP_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QToolTip Member List

Complete Member List for QToolTip

This is the complete list of member functions for QToolTip, including inherited members.

  • QToolTip()
  • add()
  • clear()
  • enabled()
  • font()
  • group()
  • hide()
  • isGloballyEnabled()
  • maybeTip()
  • palette()
  • parentWidget()
  • remove()
  • setEnabled()
  • setFont()
  • setGloballyEnabled()
  • setPalette()
  • textFor()
  • tip()


QToolTipGroup Class

QToolTipGroup Class Reference

The QToolTipGroup class collects tool tips into related groups. More...

#include <qtooltip.h>

Inherits QObject.

List of all member functions.

Public Members

  • QToolTipGroup ( QObject * parent, const char * name = 0 )
  • ~QToolTipGroup ()
  • bool delay () const
  • bool enabled () const

Public Slots

  • void setDelay ( bool )
  • void setEnabled ( bool )

Signals

  • void showTip ( const QString & longText )
  • void removeTip ()

Properties

  • bool delay - whether the display of the group text is delayed
  • bool enabled - whether tool tips in the group are enabled

Detailed Description

The QToolTipGroup class collects tool tips into related groups.

Tool tips can display two texts: one in the tip and (optionally) one that is typically in a status bar. QToolTipGroup provides a way to link tool tips to this status bar.

QToolTipGroup has practically no API; it is used only as an argument to QToolTip's member functions, for example like this:

    QToolTipGroup * g = new QToolTipGroup( this, "tool tip relay" );
    connect( g, SIGNAL(showTip(const QString&)),
             myLabel, SLOT(setText(const QString&)) );
    connect( g, SIGNAL(removeTip()),
             myLabel, SLOT(clear()) );
    QToolTip::add( giraffeButton, "feed giraffe",
                   g, "Give the giraffe a meal" );
    QToolTip::add( gorillaButton, "feed gorilla",
                   g, "Give the gorilla a meal" );

This example makes the object myLabel (which you have to supply) display (one assumes, though you can make myLabel do anything, of course) the strings "Give the giraffe a meal" and "Give the gorilla a meal" while the relevant tool tips are being displayed.

Deleting a tool tip group removes the tool tips in it.

See also Help System.

Member Function Documentation

QToolTipGroup::QToolTipGroup ( QObject * parent, const char * name = 0 )

Constructs a tool tip group with parent parent and name name.

QToolTipGroup::~QToolTipGroup ()

Destroys this tool tip group and all tool tips in it.

bool QToolTipGroup::delay () const

Returns TRUE if the display of the group text is delayed; otherwise returns FALSE. See the "delay" property for details.

bool QToolTipGroup::enabled () const

Returns TRUE if tool tips in the group are enabled; otherwise returns FALSE. See the "enabled" property for details.

void QToolTipGroup::removeTip () [signal]

This signal is emitted when a tool tip in this group is hidden. See the QToolTipGroup documentation for an example of use.

See also showTip().

void QToolTipGroup::setDelay ( bool ) [slot]

Sets whether the display of the group text is delayed. See the "delay" property for details.

void QToolTipGroup::setEnabled ( bool ) [slot]

Sets whether tool tips in the group are enabled. See the "enabled" property for details.

void QToolTipGroup::showTip ( const QString & longText ) [signal]

This signal is emitted when one of the tool tips in the group is displayed. longText is the extra text for the displayed tool tip.

See also removeTip().

Property Documentation

bool delay

This property holds whether the display of the group text is delayed.

If set to TRUE (the default), the group text is displayed at the time of the tool tip. Otherwise, the group text is displayed immediately when the cursor enters the widget.

Set this property's value with setDelay() and get this property's value with delay().

bool enabled

This property holds whether tool tips in the group are enabled.

This property's default is TRUE.

Set this property's value with setEnabled() and get this property's value with enabled().

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


QToolTipGroup Member List

Complete Member List for QToolTipGroup

This is the complete list of member functions for QToolTipGroup, including inherited members.

  • QToolTipGroup()
  • ~QToolTipGroup()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • delay()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabled()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • removeTip()
  • sender()
  • setDelay()
  • setEnabled()
  • setName()
  • setProperty()
  • showTip()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QTranslator Class

QTranslator Class Reference

The QTranslator class provides internationalization support for text output. More...

#include <qtranslator.h>

Inherits QObject.

List of all member functions.

Public Members

  • QTranslator ( QObject * parent, const char * name = 0 )
  • ~QTranslator ()
  • QString find ( const char * context, const char * sourceText, const char * comment = 0 ) const (obsolete)
  • virtual QTranslatorMessage findMessage ( const char * context, const char * sourceText, const char * comment ) const
  • bool load ( const QString & filename, const QString & directory = QString::null, const QString & search_delimiters = QString::null, const QString & suffix = QString::null )
  • void clear ()
  • enum SaveMode { Everything, Stripped }
  • bool save ( const QString & filename, SaveMode mode = Everything )
  • void insert ( const QTranslatorMessage & message )
  • void insert ( const char * context, const char * sourceText, const QString & translation ) (obsolete)
  • void remove ( const QTranslatorMessage & message )
  • void remove ( const char * context, const char * sourceText ) (obsolete)
  • bool contains ( const char * context, const char * sourceText, const char * comment = 0 ) const
  • void squeeze ( SaveMode mode = Everything )
  • void unsqueeze ()
  • QValueList<QTranslatorMessage> messages () const

Detailed Description

The QTranslator class provides internationalization support for text output.

An object of this class contains a set of QTranslatorMessage objects, each of which specifies a translation from a source language to a target language. QTranslator provides functions to look up translations, add new ones, remove them, load and save them, etc.

The most common use of QTranslator is to: load a translator file created with Qt Linguist, install it using QApplication::installTranslator(), and use it via QObject::tr(). For example:

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

        QTranslator translator( 0 );
        translator.load( "french.qm", "." );
        app.installTranslator( &translator );

        MyWidget m;
        app.setMainWidget( &m );
        m.show();

        return app.exec();
    }

Most applications will never need to do anything else with this class. The other functions provided by this class are useful for applications that work on translator files.

We call a translation a "messsage". For this reason, translation files are sometimes referred to as "message files".

It is possible to lookup a translation using findMessage() (as tr() and QApplication::translate() do) and contains(), to insert a new translation messsage using insert(), and to remove one using remove().

Translation tools often need more information than the bare source text and translation, for example, context information to help the translator. But end-user programs that are using translations usually only need lookup. To cater for these different needs, QTranslator can use stripped translator files that use the minimum of memory and which support little more functionality than findMessage().

Thus, load() may not load enough information to make anything more than findMessage() work. save() has an argument indicating whether to save just this minimum of information or to save everything.

"Everything" means that for each translation item the following information is kept:

  • The translated text - the return value from tr().
  • The input key:
    • The source text - usually the argument to tr().
    • The context - usually the class name for the tr() caller.
    • The comment - a comment that helps disambiguate different uses of the same text in the same context.

The minimum for each item is just the information necessary for findMessage() to return the right text. This may include the source, context and comment, but usually it is just a hash value and the translated text.

For example, the "Cancel" in a dialog might have "Anuluj" when the program runs in Polish (in this case the source text would be "Cancel"). The context would (normally) be the dialog's class name; there would normally be no comment, and the translated text would be "Anuluj".

But it's not always so simple. The Spanish version of a printer dialog with settings for two-sided printing and binding would probably require both "Activado" and "Activada" as translations for "Enabled". In this case the source text would be "Enabled" in both cases, and the context would be the dialog's class name, but the two items would have disambiguating comments such as "two-sided printing" for one and "binding" for the other. The comment enables the translator to choose the appropriate gender for the Spanish version, and enables Qt to distinguish between translations.

Note that when QTranslator loads a stripped file, most functions do not work. The functions that do work with stripped files are explicitly documented as such.

See also QTranslatorMessage, QApplication::installTranslator(), QApplication::removeTranslator(), QObject::tr(), QApplication::translate(), Environment Classes and Internationalization with Qt.

Member Type Documentation

QTranslator::SaveMode

This enum type defines how QTranslator writes translation files. There are two modes:

  • QTranslator::Everything - files are saved with all available information
  • QTranslator::Stripped - files are saved with just enough information for end-user applications

Note that when QTranslator loads a stripped file, most functions do not work. The functions that do work with stripped files are explicitly documented as such.

Member Function Documentation

QTranslator::QTranslator ( QObject * parent, const char * name = 0 )

Constructs an empty message file object that is not connected to any file. The object is called name with parent parent.

QTranslator::~QTranslator ()

Destroys the object and frees any allocated resources.

void QTranslator::clear ()

Empties this translator of all contents.

This function works with stripped translator files.

bool QTranslator::contains ( const char * context, const char * sourceText, const char * comment = 0 ) const

Returns TRUE if this message file contains a message with the key (context, sourceText, comment); otherwise returns FALSE.

This function works with stripped translator files.

(This is is a one-liner that calls find().)

QString QTranslator::find ( const char * context, const char * sourceText, const char * comment = 0 ) const

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

Please use findMessage() instead.

Returns the translation for the key (context, sourceText, comment) or QString::null if there is none in this translator.

QTranslatorMessage QTranslator::findMessage ( const char * context, const char * sourceText, const char * comment ) const [virtual]

Returns the QTranslatorMessage for the key (context, sourceText, comment).

void QTranslator::insert ( const QTranslatorMessage & message )

Inserts message into this message file.

This function does not work with stripped translator files. It may appear to, but that is not dependable.

See also remove().

void QTranslator::insert ( const char * context, const char * sourceText, const QString & translation )

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

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

bool QTranslator::load ( const QString & filename, const QString & directory = QString::null, const QString & search_delimiters = QString::null, const QString & suffix = QString::null )

Loads filename, which may be an absolute file name or relative to directory. The previous contents of this translator object is discarded.

If the full file name does not exist, other file names are tried in the following order:

  1. File name with suffix appended (".qm" if the suffix is QString::null).
  2. File name with text after a character in search_delimiters stripped ("_." is the default for search_delimiters if it is QString::null).
  3. File name stripped and suffix appended.
  4. File name stripped further, etc.

For example, an application running in the fr_CA locale (French-speaking Canada) might call load("foo.fr_ca", "/opt/foolib"). load() would then try to open the first existing readable file from this list:

  1. /opt/foolib/foo.fr_ca
  2. /opt/foolib/foo.fr_ca.qm
  3. /opt/foolib/foo.fr
  4. /opt/foolib/foo.fr.qm
  5. /opt/foolib/foo
  6. /opt/foolib/foo.qm

See also save().

Example: i18n/main.cpp.

QValueList<QTranslatorMessage> QTranslator::messages () const

Returns a list of the messages in the translator. This function is rather slow. Because it is seldom called, it's optimized for simplicity and small size, rather than speed.

If you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QTranslatorMessage> list = myTranslator.messages();
    QValueList<QTranslatorMessage>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

void QTranslator::remove ( const QTranslatorMessage & message )

Removes message from this translator.

This function works with stripped translator files.

See also insert().

void QTranslator::remove ( const char * context, const char * sourceText )

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

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

Removes the translation associated to the key (context, sourceText, "") from this translator.

bool QTranslator::save ( const QString & filename, SaveMode mode = Everything )

Saves this message file to filename, overwriting the previous contents of filename. If mode is Everything (the default), all the information is preserved. If mode is Stripped, any information that is not necessary for findMessage() is stripped away.

See also load().

void QTranslator::squeeze ( SaveMode mode = Everything )

Converts this message file to the compact format used to store message files on disk.

You should never need to call this directly; save() and other functions call it as necessary. mode is for internal use.

See also save() and unsqueeze().

void QTranslator::unsqueeze ()

Converts this message file into an easily modifiable data structure, less compact than the format used in the files.

You should never need to call this function; it is called by insert() and friends as necessary.

See also squeeze().

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


qtranslator.h Include File

qtranslator.h

This is the verbatim text of the qtranslator.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtranslator.h   3.0.5   edited Jan 25 14:51 $
**
** Definition of the translator class
**
** Created : 980906
**
** Copyright (C) 1998-99 by Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTRANSLATOR_H
#define QTRANSLATOR_H

#ifndef QT_H
#include "qobject.h"
#include "qvaluelist.h"
#endif // QT_H

#ifndef QT_NO_TRANSLATION

class QTranslatorPrivate;

class Q_EXPORT QTranslatorMessage
{
public:
    QTranslatorMessage();
    QTranslatorMessage( const char * context,
            const char * sourceText,
            const char * comment,
            const QString& translation = QString::null );
    QTranslatorMessage( QDataStream & );
    QTranslatorMessage( const QTranslatorMessage & m );

    QTranslatorMessage & operator=( const QTranslatorMessage & m );

    uint hash() const { return h; }
    const char *context() const { return cx; }
    const char *sourceText() const { return st; }
    const char *comment() const { return cm; }

    void setTranslation( const QString & translation ) { tn = translation; }
    QString translation() const { return tn; }

    enum Prefix { NoPrefix, Hash, HashContext, HashContextSourceText,
          HashContextSourceTextComment };
    void write( QDataStream & s, bool strip = FALSE,
        Prefix prefix = HashContextSourceTextComment ) const;
    Prefix commonPrefix( const QTranslatorMessage& ) const;

    bool operator==( const QTranslatorMessage& m ) const;
    bool operator!=( const QTranslatorMessage& m ) const
    { return !operator==( m ); }
    bool operator<( const QTranslatorMessage& m ) const;
    bool operator<=( const QTranslatorMessage& m ) const
    { return !m.operator<( *this ); }
    bool operator>( const QTranslatorMessage& m ) const
    { return m.operator<( *this ); }
    bool operator>=( const QTranslatorMessage& m ) const
    { return !operator<( m ); }

private:
    uint h;
    QCString cx;
    QCString st;
    QCString cm;
    QString tn;

    enum Tag { Tag_End = 1, Tag_SourceText16, Tag_Translation, Tag_Context16,
           Tag_Hash, Tag_SourceText, Tag_Context, Tag_Comment,
           Tag_Obsolete1 };
};

class Q_EXPORT QTranslator: public QObject
{
    Q_OBJECT
public:
    QTranslator( QObject * parent, const char * name = 0 );
    ~QTranslator();

#ifndef QT_NO_COMPAT
    QString find( const char *context, const char *sourceText, const char * comment = 0 ) const {
    return findMessage( context, sourceText, comment ).translation();
    }
#endif
    virtual QTranslatorMessage findMessage( const char *, const char *,
                    const char * ) const;

    bool load( const QString & filename,
           const QString & directory = QString::null,
           const QString & search_delimiters = QString::null,
           const QString & suffix = QString::null );

    void clear();

#ifndef QT_NO_TRANSLATION_BUILDER
    enum SaveMode { Everything, Stripped };

    bool save( const QString & filename, SaveMode mode = Everything );

    void insert( const QTranslatorMessage& );
    void insert( const char *context, const char *sourceText, const QString &translation ) {
    insert( QTranslatorMessage(context, sourceText, "", translation) );
    }
    void remove( const QTranslatorMessage& );
    void remove( const char *context, const char *sourceText ) {
    remove( QTranslatorMessage(context, sourceText, "") );
    }
    bool contains( const char *, const char *, const char * comment = 0 ) const;

    void squeeze( SaveMode = Everything );
    void unsqueeze();

    QValueList<QTranslatorMessage> messages() const;
#endif

private:
    QTranslatorPrivate * d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QTranslator( const QTranslator & );
    QTranslator &operator=( const QTranslator & );
#endif
};

#endif // QT_NO_TRANSLATION

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTranslator Member List

Complete Member List for QTranslator

This is the complete list of member functions for QTranslator, including inherited members.

  • QTranslator()
  • ~QTranslator()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clear()
  • connect()
  • connectNotify()
  • contains()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • find()
  • findMessage()
  • highPriority()
  • inherits()
  • insert()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • load()
  • messages()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • remove()
  • removeChild()
  • removeEventFilter()
  • save()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • squeeze()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • unsqueeze()


QTranslatorMessage Class

QTranslatorMessage Class Reference

The API for this class is under development and is subject to change.
We do not recommend the use of this class for production work at this time.

The QTranslatorMessage class contains a translator message and its properties. More...

#include <qtranslator.h>

List of all member functions.

Public Members

  • QTranslatorMessage ()
  • QTranslatorMessage ( const char * context, const char * sourceText, const char * comment, const QString & translation = QString::null )
  • QTranslatorMessage ( QDataStream & stream )
  • QTranslatorMessage ( const QTranslatorMessage & m )
  • QTranslatorMessage & operator= ( const QTranslatorMessage & m )
  • uint hash () const
  • const char * context () const
  • const char * sourceText () const
  • const char * comment () const
  • void setTranslation ( const QString & translation )
  • QString translation () const
  • enum Prefix { NoPrefix, Hash, HashContext, HashContextSourceText, HashContextSourceTextComment }
  • void write ( QDataStream & stream, bool strip = FALSE, Prefix prefix = HashContextSourceTextComment ) const
  • Prefix commonPrefix ( const QTranslatorMessage & m ) const
  • bool operator== ( const QTranslatorMessage & m ) const
  • bool operator!= ( const QTranslatorMessage & m ) const
  • bool operator< ( const QTranslatorMessage & m ) const
  • bool operator<= ( const QTranslatorMessage & m ) const
  • bool operator> ( const QTranslatorMessage & m ) const
  • bool operator>= ( const QTranslatorMessage & m ) const

Detailed Description

The QTranslatorMessage class contains a translator message and its properties.

This class is of no interest to most applications. It is useful for translation tools such as Qt Linguist. It is provided simply to make the API complete and regular.

For a QTranslator object, a lookup key is a triple (context, source text, comment) that uniquely identifies a message. An extended key is a quadruple (hash, context, source text, comment), where hash is computed from the source text and the comment. Unless you plan to read and write messages yourself, you need not worry about the hash value.

QTranslatorMessage stores this triple or quadruple and the relevant translation if there is any.

See also QTranslator, Environment Classes and Internationalization with Qt.

Member Type Documentation

QTranslatorMessage::Prefix

Let (h, c, s, m) be the extended key. The possible prefixes are

  • QTranslatorMessage::NoPrefix - no prefix
  • QTranslatorMessage::Hash - only (h)
  • QTranslatorMessage::HashContext - only (h, c)
  • QTranslatorMessage::HashContextSourceText - only (h, c, s)
  • QTranslatorMessage::HashContextSourceTextComment - the whole extended key, (h, c, s, m)

See also write() and commonPrefix().

Member Function Documentation

QTranslatorMessage::QTranslatorMessage ()

Constructs a translator message with the extended key (0, 0, 0, 0) and QString::null as translation.

QTranslatorMessage::QTranslatorMessage ( const char * context, const char * sourceText, const char * comment, const QString & translation = QString::null )

Constructs an translator message with the extended key (h, context, sourceText, comment), where h is computed from sourceText and comment, and possibly with a translation.

QTranslatorMessage::QTranslatorMessage ( QDataStream & stream )

Constructs a translator message read from the stream. The resulting message may have any combination of content.

See also QTranslator::save().

QTranslatorMessage::QTranslatorMessage ( const QTranslatorMessage & m )

Constructs a copy of translator message m.

const char * QTranslatorMessage::comment () const

Returns the comment for this message (e.g. "File|Save").

Prefix QTranslatorMessage::commonPrefix ( const QTranslatorMessage & m ) const

Returns the widest lookup prefix that is common to this translator message and to message m.

For example, if the extended key is for this message is (71, "PrintDialog", "Yes", "Print?") and that for m is (71, "PrintDialog", "No", "Print?"), this function returns HashContext.

See also write().

const char * QTranslatorMessage::context () const

Returns the context for this message (e.g. "MyDialog").

uint QTranslatorMessage::hash () const

Returns the hash value used internally to represent the lookup key. This value is zero only if this translator message was constructed from a stream containing invalid data.

The hashing function is unspecified, but it will remain unchanged in future versions of Qt.

bool QTranslatorMessage::operator!= ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is different from that of m; otherwise returns FALSE.

bool QTranslatorMessage::operator< ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is lexicographically before than that of m; otherwise returns FALSE.

bool QTranslatorMessage::operator<= ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is lexicographically before that of m or if they are equal; otherwise returns FALSE.

QTranslatorMessage & QTranslatorMessage::operator= ( const QTranslatorMessage & m )

Assigns message m to this translator message and returns a reference to this translator message.

bool QTranslatorMessage::operator== ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is equal to that of m; otherwise returns FALSE.

bool QTranslatorMessage::operator> ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is lexicographically after that of m; otherwise returns FALSE.

bool QTranslatorMessage::operator>= ( const QTranslatorMessage & m ) const

Returns TRUE if the extended key of this object is lexicographically after that of m or if they are equal; otherwise returns FALSE.

void QTranslatorMessage::setTranslation ( const QString & translation )

Sets the translation of the source text to translation.

See also translation().

const char * QTranslatorMessage::sourceText () const

Returns the source text of this message (e.g. "&Save").

QString QTranslatorMessage::translation () const

Returns the translation of the source text (e.g., "&Sauvegarder").

See also setTranslation().

void QTranslatorMessage::write ( QDataStream & stream, bool strip = FALSE, Prefix prefix = HashContextSourceTextComment ) const

Writes this translator message to the stream. If strip is FALSE (the default), all the information in the message is written. If strip is TRUE, only the part of the extended key specified by prefix is written with the translation (HashContextSourceTextComment by default).

See also commonPrefix().

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


QTranslatorMessage Member List

Complete Member List for QTranslatorMessage

This is the complete list of member functions for QTranslatorMessage, including inherited members.

  • QTranslatorMessage()
  • comment()
  • commonPrefix()
  • context()
  • hash()
  • operator!=()
  • operator<()
  • operator<=()
  • operator=()
  • operator==()
  • operator>()
  • operator>=()
  • setTranslation()
  • sourceText()
  • translation()
  • write()


QTsciiCodec Class

QTsciiCodec Class Reference

The QTsciiCodec class provides conversion to and from the Tamil TSCII encoding. More...

#include <qtsciicodec.h>

Inherits QTextCodec.

List of all member functions.

Detailed Description

The QTsciiCodec class provides conversion to and from the Tamil TSCII encoding.

TSCII, formally the Tamil Standard Code Information Interchange specification, is a commonly used charset for Tamils. The official page for the standard is at http://www.tamil.net/tscii/

This codec uses the mapping table found at http://www.geocities.com/Athens/5180/tsciiset.html. Tamil uses composed Unicode which might cause some problems if you are using Unicode fonts instead of TSCII fonts.

The TSCII codec was contributed to Qt by Hans Petter Bieker <bieker@kde.org>. The copyright notice for his code follows:

Copyright 2000 Hans Petter Bieker . All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also Internationalization with Qt.

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


qtsciicodec.h Include File

qtsciicodec.h

This is the verbatim text of the qtsciicodec.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qtsciicodec.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QTSCIICodec class
**
*****************************************************************************/

// Contributed by Hans Petter Bieker <bieker@kde.org>
// See the documentation for their license statement for the code as
// it was at the time of contribution.

#ifndef QTSCIICODEC_H
#define QTSCIICODEC_H

#ifndef QT_H
#include "qtextcodec.h"
#endif // QT_H

#ifndef QT_NO_CODECS

class Q_EXPORT QTsciiCodec : public QTextCodec {
public:
    virtual int mibEnum() const;
    const char* name() const;

    QCString fromUnicode(const QString& uc, int& len_in_out) const;
    QString toUnicode(const char* chars, int len) const;

    int heuristicContentMatch(const char* chars, int len) const;
    int heuristicNameMatch(const char* hint) const;
};

#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QTsciiCodec Member List

Complete Member List for QTsciiCodec

This is the complete list of member functions for QTsciiCodec, including inherited members.

  • canEncode()
  • codecForContent()
  • codecForIndex()
  • codecForLocale()
  • codecForMib()
  • codecForName()
  • deleteAllCodecs()
  • fromUnicode()
  • heuristicContentMatch()
  • heuristicNameMatch()
  • loadCharmap()
  • loadCharmapFile()
  • locale()
  • makeDecoder()
  • makeEncoder()
  • mibEnum()
  • mimeName()
  • name()
  • setCodecForLocale()
  • simpleHeuristicNameMatch()
  • toUnicode()


QtTableView Class

QtTableView Class Reference
[obsolete]

The QtTableView class provides an abstract base for tables. More...

#include <qttableview.h>

Inherits QFrame.

Inherited by QtMultiLineEdit.

List of all member functions.

Public Members

  • void repaint ( bool erase = TRUE )
  • void repaint ( int x, int y, int w, int h, bool erase = TRUE )
  • void repaint ( const QRect & r, bool erase = TRUE )

Protected Members

  • QtTableView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QtTableView ()
  • int numRows () const
  • virtual void setNumRows ( int rows )
  • int numCols () const
  • virtual void setNumCols ( int cols )
  • int topCell () const
  • virtual void setTopCell ( int row )
  • int leftCell () const
  • virtual void setLeftCell ( int col )
  • virtual void setTopLeftCell ( int row, int col )
  • int xOffset () const
  • virtual void setXOffset ( int x )
  • int yOffset () const
  • virtual void setYOffset ( int y )
  • virtual void setOffset ( int x, int y, bool updateScrBars = TRUE )
  • virtual int cellWidth ( int col )
  • virtual int cellHeight ( int row )
  • int cellWidth () const
  • int cellHeight () const
  • virtual void setCellWidth ( int cellWidth )
  • virtual void setCellHeight ( int cellHeight )
  • virtual int totalWidth ()
  • virtual int totalHeight ()
  • uint tableFlags () const
  • bool testTableFlags ( uint f ) const
  • virtual void setTableFlags ( uint f )
  • void clearTableFlags ( uint f = ~0 )
  • bool autoUpdate () const
  • virtual void setAutoUpdate ( bool enable )
  • void updateCell ( int row, int col, bool erase = TRUE )
  • QRect cellUpdateRect () const
  • QRect viewRect () const
  • int lastRowVisible () const
  • int lastColVisible () const
  • bool rowIsVisible ( int row ) const
  • bool colIsVisible ( int col ) const
  • QScrollBar * verticalScrollBar () const
  • QScrollBar * horizontalScrollBar () const
  • virtual void paintCell ( QPainter * p, int row, int col ) = 0
  • virtual void setupPainter ( QPainter * )
  • virtual void paintEvent ( QPaintEvent * e )
  • int findRow ( int yPos ) const
  • int findCol ( int xPos ) const
  • bool rowYPos ( int row, int * yPos ) const
  • bool colXPos ( int col, int * xPos ) const
  • int maxXOffset ()
  • int maxYOffset ()
  • int maxColOffset ()
  • int maxRowOffset ()
  • int minViewX () const
  • int minViewY () const
  • int maxViewX () const
  • int maxViewY () const
  • int viewWidth () const
  • int viewHeight () const
  • void scroll ( int xPixels, int yPixels )
  • void updateScrollBars ()
  • void updateTableSize ()

Detailed Description

The QtTableView class provides an abstract base for tables.

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

A table view consists of a number of abstract cells organized in rows and columns, and a visible part called a view. The cells are identified with a row index and a column index. The top-left cell is in row 0, column 0.

The behavior of the widget can be finely tuned using setTableFlags(); a typical subclass will consist of little more than a call to setTableFlags(), some table content manipulation and an implementation of paintCell(). Subclasses that need cells with variable width or height must reimplement cellHeight() and/or cellWidth(). Use updateTableSize() to tell QtTableView when the width or height has changed.

When you read this documentation, it is important to understand the distinctions among the four pixel coordinate systems involved.

  1. The cell coordinates. (0,0) is the top-left corner of a cell. Cell coordinates are used by functions such as paintCell().

  2. The table coordinates. (0,0) is the top-left corner of the cell at row 0 and column 0. These coordinates are absolute; that is, they are independent of what part of the table is visible at the moment. They are used by functions such as setXOffset() or maxYOffset().

  3. The widget coordinates. (0,0) is the top-left corner of the widget, including the frame. They are used by functions such as repaint().

  4. The view coordinates. (0,0) is the top-left corner of the view, excluding the frame. This is the least-used coordinate system; it is used by functions such as viewWidth().

It is rather unfortunate that we have to use four different coordinate systems, but there was no alternative to provide a flexible and powerful base class.

Note: The row,column indices are always given in that order, i.e., first the vertical (row), then the horizontal (column). This is the opposite order of all pixel operations, which take first the horizontal (x) and then the vertical (y).

Warning: the functions setNumRows(), setNumCols(), setCellHeight(), setCellWidth(), setTableFlags() and clearTableFlags() may cause virtual functions such as cellWidth() and cellHeight() to be called, even if autoUpdate() is FALSE. This may cause errors if relevant state variables are not initialized.

Warning: Experience has shown that use of this widget tends to cause more bugs than expected and our analysis indicates that the widget's very flexibility is the problem. If QScrollView or QListBox can easily be made to do the job you need, we recommend subclassing those widgets rather than QtTableView. In addition, QScrollView makes it easy to have child widgets inside tables, which QtTableView doesn't support at all.

See also QScrollView and GUI Design Handbook: Table.

Member Function Documentation

QtTableView::QtTableView ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) [protected]

Constructs a table view. The parent, name and \f arguments are passed to the QFrame constructor.

The table flags are all cleared (set to 0). Set Tbl_autoVScrollBar or Tbl_autoHScrollBar to get automatic scroll bars and Tbl_clipCellPainting to get safe clipping.

The cell height and cell width are set to 0.

Frame line shapes (QFrame::HLink and QFrame::VLine) are disallowed; see QFrame::setFrameStyle().

Note that the f argument is not table flags but rather widget flags.

QtTableView::~QtTableView () [protected]

Destroys the table view.

bool QtTableView::autoUpdate () const [protected]

Returns TRUE if the view updates itself automatically whenever it is changed in some way.

See also setAutoUpdate().

int QtTableView::cellHeight ( int row ) [virtual protected]

Returns the height of row row in pixels.

This function is virtual and must be reimplemented by subclasses that have variable cell heights. Note that if the total table height changes, updateTableSize() must be called.

See also setCellHeight(), cellWidth() and totalHeight().

int QtTableView::cellHeight () const [protected]

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

Returns the row height, in pixels. Returns 0 if the rows have variable heights.

See also setCellHeight() and cellWidth().

QRect QtTableView::cellUpdateRect () const [protected]

This function should be called only from the paintCell() function in subclasses. It returns the portion of a cell that actually needs to be updated in cell coordinates. This is useful only for non-trivial paintCell().

int QtTableView::cellWidth ( int col ) [virtual protected]

Returns the width of column col in pixels.

This function is virtual and must be reimplemented by subclasses that have variable cell widths. Note that if the total table width changes, updateTableSize() must be called.

See also setCellWidth(), cellHeight(), totalWidth() and updateTableSize().

int QtTableView::cellWidth () const [protected]

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

Returns the column width in pixels. Returns 0 if the columns have variable widths.

See also setCellWidth() and cellHeight().

void QtTableView::clearTableFlags ( uint f = ~0 ) [protected]

Clears the table flags that are set in f.

Example (clears a single flag):

    clearTableFlags( Tbl_snapToGrid );

The default argument clears all flags.

See also setTableFlags(), testTableFlags() and tableFlags().

bool QtTableView::colIsVisible ( int col ) const [protected]

Returns TRUE if col is at least partially visible.

See also rowIsVisible().

bool QtTableView::colXPos ( int col, int * xPos ) const [protected]

Computes the position in the widget of column col.

Returns TRUE and stores the result in *xPos (in widget coordinates) if the column is visible. Returns FALSE and does not modify *xPos if col is invisible or invalid.

See also rowYPos() and findCol().

int QtTableView::findCol ( int xPos ) const [protected]

Returns the index of the column at position xPos, where xPos is in widget coordinates. Returns -1 if xPos is outside the valid range.

See also findRow() and colXPos().

int QtTableView::findRow ( int yPos ) const [protected]

Returns the index of the row at position yPos, where yPos is in widget coordinates. Returns -1 if yPos is outside the valid range.

See also findCol() and rowYPos().

QScrollBar * QtTableView::horizontalScrollBar () const [protected]

Returns a pointer to the horizontal scroll bar mainly so you can connect() to its signals. Note that the scroll bar works in pixel values; use findCol() to translate to cell numbers.

int QtTableView::lastColVisible () const [protected]

Returns the index of the last (right) column in the view. The index of the first column is 0.

If no columns are visible it returns -1. This can happen if the view is too narrow for the first column and Tbl_cutCellsH is set.

See also lastRowVisible().

int QtTableView::lastRowVisible () const [protected]

Returns the index of the last (bottom) row in the view. The index of the first row is 0.

If no rows are visible it returns -1. This can happen if the view is too small for the first row and Tbl_cutCellsV is set.

See also lastColVisible().

int QtTableView::leftCell () const [protected]

Returns the index of the first column in the table that is visible in the view. The index of the very leftmost column is 0.

See also topCell() and setLeftCell().

int QtTableView::maxColOffset () [protected]

Returns the index of the last column, which may be at the left edge of the view.

Depending on the Tbl_scrollLastHCell flag, this may or may not be the last column.

See also maxXOffset() and maxRowOffset().

int QtTableView::maxRowOffset () [protected]

Returns the index of the last row, which may be at the top edge of the view.

Depending on the Tbl_scrollLastVCell flag, this may or may not be the last row.

See also maxYOffset() and maxColOffset().

int QtTableView::maxViewX () const [protected]

Returns the rightmost pixel of the table view in view coordinates. This excludes the frame and any scroll bar, but includes blank pixels to the right of the visible table data.

See also maxViewY(), viewWidth() and contentsRect.

int QtTableView::maxViewY () const [protected]

Returns the bottom pixel of the table view in view coordinates. This excludes the frame and any scroll bar, but includes blank pixels below the visible table data.

See also maxViewX(), viewHeight() and contentsRect.

int QtTableView::maxXOffset () [protected]

Returns the maximum horizontal offset within the table of the view's left edge in table coordinates.

This is used mainly to set the horizontal scroll bar's range.

See also maxColOffset(), maxYOffset() and totalWidth().

int QtTableView::maxYOffset () [protected]

Returns the maximum vertical offset within the table of the view's top edge in table coordinates.

This is used mainly to set the vertical scroll bar's range.

See also maxRowOffset(), maxXOffset() and totalHeight().

int QtTableView::minViewX () const [protected]

Returns the leftmost pixel of the table view in view coordinates. This excludes the frame and any header.

See also maxViewY(), viewWidth() and contentsRect.

int QtTableView::minViewY () const [protected]

Returns the top pixel of the table view in view coordinates. This excludes the frame and any header.

See also maxViewX(), viewHeight() and contentsRect.

int QtTableView::numCols () const [protected]

Returns the number of columns in the table.

See also numRows() and setNumCols().

int QtTableView::numRows () const [protected]

Returns the number of rows in the table.

See also numCols() and setNumRows().

void QtTableView::paintCell ( QPainter * p, int row, int col ) [pure virtual protected]

This pure virtual function is called to paint the single cell at (row,col) using p, which is open when paintCell() is called and must remain open.

The coordinate system is translated so that the origin is at the top-left corner of the cell to be painted, i.e. cell coordinates. Do not scale or shear the coordinate system (or if you do, restore the transformation matrix before you return).

The painter is not clipped by default and for maximum efficiency. For safety, call setTableFlags(Tbl_clipCellPainting) to enable clipping.

See also paintEvent() and setTableFlags().

Reimplemented in QtMultiLineEdit.

void QtTableView::paintEvent ( QPaintEvent * e ) [virtual protected]

Handles paint events, e, for the table view.

Calls paintCell() for the cells that needs to be repainted.

Reimplemented from QFrame.

void QtTableView::repaint ( int x, int y, int w, int h, bool erase = TRUE )

Repaints the table view directly by calling paintEvent() directly unless updates are disabled.

Erases the view area (x,y,w,h) if erase is TRUE. Parameters (x,y) are in widget coordinates.

If w is negative, it is replaced with width() - x. If h is negative, it is replaced with height() - y.

Doing a repaint() usually is faster than doing an update(), but calling update() many times in a row will generate a single paint event.

At present, QtTableView is the only widget that reimplements repaint(). It does this because by clearing and then repainting one cell at at time, it can make the screen flicker less than it would otherwise.

void QtTableView::repaint ( bool erase = TRUE )

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

Repaints the entire view.

void QtTableView::repaint ( const QRect & r, bool erase = TRUE )

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

Replaints rectangle r. If erase is TRUE draws the background using the palette's background.

bool QtTableView::rowIsVisible ( int row ) const [protected]

Returns TRUE if row is at least partially visible.

See also colIsVisible().

bool QtTableView::rowYPos ( int row, int * yPos ) const [protected]

Computes the position in the widget of row row.

Returns TRUE and stores the result in *yPos (in widget coordinates) if the row is visible. Returns FALSE and does not modify *yPos if row is invisible or invalid.

See also colXPos() and findRow().

void QtTableView::scroll ( int xPixels, int yPixels ) [protected]

Moves the visible area of the table right by xPixels and down by yPixels pixels. Both may be negative.

Warning: You might find that QScrollView offers a higher-level of functionality than using QtTableView and this function.

This function is not the same as QWidget::scroll(); in particular, the signs of xPixels and yPixels have the reverse semantics.

See also setXOffset(), setYOffset(), setOffset(), setTopCell() and setLeftCell().

void QtTableView::setAutoUpdate ( bool enable ) [virtual protected]

Sets the auto-update option of the table view to enable.

If enable is TRUE (this is the default), the view updates itself automatically whenever it has changed in some way (for example, when a flag is changed).

If enable is FALSE, the view does NOT repaint itself or update its internal state variables when it is changed. This can be useful to avoid flicker during large changes and is singularly useless otherwise. Disable auto-update, do the changes, re-enable auto-update and call repaint().

Warning: Do not leave the view in this state for a long time (i.e., between events). If, for example, the user interacts with the view when auto-update is off, strange things can happen.

Setting auto-update to TRUE does not repaint the view; you must call repaint() to do this.

See also autoUpdate() and repaint().

Reimplemented in QtMultiLineEdit.

void QtTableView::setCellHeight ( int cellHeight ) [virtual protected]

Sets the height in pixels of the table cells to cellHeight.

Setting it to 0 means that the row height is variable. When set to 0 (this is the default), QtTableView calls the virtual function cellHeight() to get the height.

See also cellHeight(), setCellWidth(), totalHeight() and numRows().

void QtTableView::setCellWidth ( int cellWidth ) [virtual protected]

Sets the width in pixels of the table cells to cellWidth.

Setting it to 0 means that the column width is variable. When set to 0 (this is the default) QtTableView calls the virtual function cellWidth() to get the width.

See also cellWidth(), setCellHeight(), totalWidth() and numCols().

void QtTableView::setLeftCell ( int col ) [virtual protected]

Scrolls the table so that col becomes the leftmost column. The index of the leftmost column is 0.

See also setXOffset(), setTopLeftCell() and setTopCell().

void QtTableView::setNumCols ( int cols ) [virtual protected]

Sets the number of columns of the table to cols (must be non-negative). Does not change leftCell().

The table repaints itself automatically if autoUpdate() is set.

See also numCols(), numRows() and setNumRows().

void QtTableView::setNumRows ( int rows ) [virtual protected]

Sets the number of rows of the table to rows (must be non-negative). Does not change topCell().

The table repaints itself automatically if autoUpdate() is set.

See also numCols(), setNumCols() and numRows().

void QtTableView::setOffset ( int x, int y, bool updateScrBars = TRUE ) [virtual protected]

Scrolls the table so that (x,y) becomes the top-left pixel in the view. Parameters (x,y) are in table coordinates.

The interaction with Tbl_snapTo*Grid is tricky. If updateScrBars is TRUE, the scroll bars are updated.

See also xOffset(), yOffset(), setXOffset(), setYOffset() and setTopLeftCell().

void QtTableView::setTableFlags ( uint f ) [virtual protected]

Sets the table flags to f.

If a flag setting changes the appearance of the table, the table is repainted if - and only if - autoUpdate() is TRUE.

The table flags are mostly single bits, though there are some multibit flags for convenience. Here is a complete list:

Tbl_vScrollBar
- The table has a vertical scroll bar.
Tbl_hScrollBar
- The table has a horizontal scroll bar.
Tbl_autoVScrollBar
- The table has a vertical scroll bar if - and only if - the table is taller than the view.
Tbl_autoHScrollBar
The table has a horizontal scroll bar if - and only if - the table is wider than the view.
Tbl_autoScrollBars
- The union of the previous two flags.
Tbl_clipCellPainting
- The table uses QPainter::setClipRect() to make sure that paintCell() will not draw outside the cell boundaries.
Tbl_cutCellsV
- The table will never show part of a cell at the bottom of the table; if there is not space for all of a cell, the space is left blank.
Tbl_cutCellsH
- The table will never show part of a cell at the right side of the table; if there is not space for all of a cell, the space is left blank.
Tbl_cutCells
- The union of the previous two flags.
Tbl_scrollLastHCell
- When the user scrolls horizontally, let him/her scroll the last cell left until it is at the left edge of the view. If this flag is not set, the user can only scroll to the point where the last cell is completely visible.
Tbl_scrollLastVCell
- When the user scrolls vertically, let him/her scroll the last cell up until it is at the top edge of the view. If this flag is not set, the user can only scroll to the point where the last cell is completely visible.
Tbl_scrollLastCell
- The union of the previous two flags.
Tbl_smoothHScrolling
- The table scrolls as smoothly as possible when the user scrolls horizontally. When this flag is not set, scrolling is done one cell at a time.
Tbl_smoothVScrolling
- The table scrolls as smoothly as possible when scrolling vertically. When this flag is not set, scrolling is done one cell at a time.
Tbl_smoothScrolling
- The union of the previous two flags.
Tbl_snapToHGrid
- Except when the user is actually scrolling, the leftmost column shown snaps to the leftmost edge of the view.
Tbl_snapToVGrid
- Except when the user is actually scrolling, the top row snaps to the top edge of the view.
Tbl_snapToGrid
- The union of the previous two flags.

You can specify more than one flag at a time using bitwise OR.

Example:

    setTableFlags( Tbl_smoothScrolling | Tbl_autoScrollBars );

Warning: The cutCells options (Tbl_cutCells, Tbl_cutCellsH and Tbl_cutCellsV) may cause painting problems when scrollbars are enabled. Do not combine cutCells and scrollbars.

See also clearTableFlags(), testTableFlags() and tableFlags().

void QtTableView::setTopCell ( int row ) [virtual protected]

Scrolls the table so that row becomes the top row. The index of the very first row is 0.

See also setYOffset(), setTopLeftCell() and setLeftCell().

void QtTableView::setTopLeftCell ( int row, int col ) [virtual protected]

Scrolls the table so that the cell at row row and colum col becomes the top-left cell in the view. The cell at the extreme top left of the table is at position (0,0).

See also setLeftCell(), setTopCell() and setOffset().

void QtTableView::setXOffset ( int x ) [virtual protected]

Scrolls the table so that x becomes the leftmost pixel in the view. The x parameter is in table coordinates.

The interaction with Tbl_snapToHGrid is tricky.

See also xOffset(), setYOffset(), setOffset() and setLeftCell().

void QtTableView::setYOffset ( int y ) [virtual protected]

Scrolls the table so that y becomes the top pixel in the view. The y parameter is in table coordinates.

The interaction with Tbl_snapToVGrid is tricky.

See also yOffset(), setXOffset(), setOffset() and setTopCell().

void QtTableView::setupPainter ( QPainter * ) [virtual protected]

This virtual function is called before painting of table cells is started. It can be reimplemented by subclasses that want to to set up the painter in a special way and that do not want to do so for each cell.

uint QtTableView::tableFlags () const [protected]

Returns the union of the table flags that are currently set.

See also setTableFlags(), clearTableFlags() and testTableFlags().

bool QtTableView::testTableFlags ( uint f ) const [protected]

Returns TRUE if any of the table flags in f are currently set, otherwise FALSE.

See also setTableFlags(), clearTableFlags() and tableFlags().

int QtTableView::topCell () const [protected]

Returns the index of the first row in the table that is visible in the view. The index of the first row is 0.

See also leftCell() and setTopCell().

int QtTableView::totalHeight () [virtual protected]

Returns the total height of the table in pixels.

This function is virtual and should be reimplemented by subclasses that have variable cell heights and a non-trivial cellHeight() function, or a large number of rows in the table.

The default implementation may be slow for very tall tables.

See also cellHeight() and totalWidth().

int QtTableView::totalWidth () [virtual protected]

Returns the total width of the table in pixels.

This function is virtual and should be reimplemented by subclasses that have variable cell widths and a non-trivial cellWidth() function, or a large number of columns in the table.

The default implementation may be slow for very wide tables.

See also cellWidth() and totalHeight().

void QtTableView::updateCell ( int row, int col, bool erase = TRUE ) [protected]

Repaints the cell at row row, column col if it is inside the view.

If erase is TRUE, the relevant part of the view is cleared to the background color/pixmap before the contents are repainted.

See also visible.

void QtTableView::updateScrollBars () [protected]

Updates the scroll bars' contents and presence to match the table's state. Generally, you should not need to call this.

See also setTableFlags().

void QtTableView::updateTableSize () [protected]

Updates the scroll bars and internal state.

Call this function when the table view's total size is changed; typically because the result of cellHeight() or cellWidth() have changed.

This function does not repaint the widget.

QScrollBar * QtTableView::verticalScrollBar () const [protected]

Returns a pointer to the vertical scroll bar mainly so you can connect() to its signals. Note that the scroll bar works in pixel values; use findRow() to translate to cell numbers.

int QtTableView::viewHeight () const [protected]

Returns the height of the table view, as such, in view coordinates. This does not include any header, scroll bar or frame, but it does include background pixels below the table data.

See also minViewY(), maxViewY(), viewWidth(), contentsRect and viewRect().

QRect QtTableView::viewRect () const [protected]

Returns the rectangle that is the actual table, excluding any frame, in widget coordinates.

int QtTableView::viewWidth () const [protected]

Returns the width of the table view, as such, in view coordinates. This does not include any header, scroll bar or frame, but it does include background pixels to the right of the table data.

See also minViewX(), maxViewX(), viewHeight(), contentsRect and viewRect().

int QtTableView::xOffset () const [protected]

Returns the x coordinate in table coordinates of the pixel that is currently on the left edge of the view.

See also setXOffset(), yOffset() and leftCell().

int QtTableView::yOffset () const [protected]

Returns the y coordinate in table coordinates of the pixel that is currently on the top edge of the view.

See also setYOffset(), xOffset() and topCell().

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


qttableview.h Include File

qttableview.h

This is the verbatim text of the qttableview.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/**********************************************************************
** $Id:  qt/qttableview.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QtTableView class
**
** Created : 941115
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file contains a class moved out of the Qt GUI Toolkit API. It
** may be used, distributed and modified without limitation.
**
**********************************************************************/

#ifndef QTTABLEVIEW_H
#define QTTABLEVIEW_H

#ifndef QT_H
#include "qframe.h"
#endif // QT_H

#ifndef QT_NO_QTTABLEVIEW

class QScrollBar;
class QCornerSquare;

class QtTableView : public QFrame
{
    Q_OBJECT
public:
    virtual void setBackgroundColor( const QColor & );
    virtual void setPalette( const QPalette & );
    void	show();

    void	repaint( bool erase=TRUE );
    void	repaint( int x, int y, int w, int h, bool erase=TRUE );
    void	repaint( const QRect &, bool erase=TRUE );

protected:
    QtTableView( QWidget *parent=0, const char *name=0, WFlags f=0 );
   ~QtTableView();

    int		numRows()	const;
    virtual void setNumRows( int );
    int		numCols()	const;
    virtual void setNumCols( int );

    int		topCell()	const;
    virtual void setTopCell( int row );
    int		leftCell()	const;
    virtual void setLeftCell( int col );
    virtual void setTopLeftCell( int row, int col );

    int		xOffset()	const;
    virtual void setXOffset( int );
    int		yOffset()	const;
    virtual void setYOffset( int );
    virtual void setOffset( int x, int y, bool updateScrBars = TRUE );

    virtual int cellWidth( int col );
    virtual int cellHeight( int row );
    int		cellWidth()	const;
    int		cellHeight()	const;
    virtual void setCellWidth( int );
    virtual void setCellHeight( int );

    virtual int totalWidth();
    virtual int totalHeight();

    uint	tableFlags()	const;
    bool	testTableFlags( uint f ) const;
    virtual void setTableFlags( uint f );
    void	clearTableFlags( uint f = ~0 );

    bool	autoUpdate()	 const;
    virtual void setAutoUpdate( bool );

    void	updateCell( int row, int column, bool erase=TRUE );

    QRect	cellUpdateRect() const;
    QRect	viewRect()	 const;

    int		lastRowVisible() const;
    int		lastColVisible() const;

    bool	rowIsVisible( int row ) const;
    bool	colIsVisible( int col ) const;

    QScrollBar *verticalScrollBar() const;
    QScrollBar *horizontalScrollBar() const;

private slots:
    void	horSbValue( int );
    void	horSbSliding( int );
    void	horSbSlidingDone();
    void	verSbValue( int );
    void	verSbSliding( int );
    void	verSbSlidingDone();

protected:
    virtual void paintCell( QPainter *, int row, int col ) = 0;
    virtual void setupPainter( QPainter * );

    void	paintEvent( QPaintEvent * );
    void	resizeEvent( QResizeEvent * );

    int		findRow( int yPos ) const;
    int		findCol( int xPos ) const;

    bool	rowYPos( int row, int *yPos ) const;
    bool	colXPos( int col, int *xPos ) const;

    int		maxXOffset();
    int		maxYOffset();
    int		maxColOffset();
    int		maxRowOffset();

    int		minViewX()	const;
    int		minViewY()	const;
    int		maxViewX()	const;
    int		maxViewY()	const;
    int		viewWidth()	const;
    int		viewHeight()	const;

    void	scroll( int xPixels, int yPixels );
    void	updateScrollBars();
    void	updateTableSize();

private:
    void	coverCornerSquare( bool );
    void	snapToGrid( bool horizontal, bool vertical );
    virtual void	setHorScrollBar( bool on, bool update = TRUE );
    virtual void	setVerScrollBar( bool on, bool update = TRUE );
    void	updateView();
    int		findRawRow( int yPos, int *cellMaxY, int *cellMinY = 0,
                bool goOutsideView = FALSE ) const;
    int		findRawCol( int xPos, int *cellMaxX, int *cellMinX = 0,
                bool goOutsideView = FALSE ) const;
    int		maxColsVisible() const;

    void	updateScrollBars( uint );
    void	updateFrameSize();

    void	doAutoScrollBars();
    void	showOrHideScrollBars();

    int		nRows;
    int		nCols;
    int		xOffs, yOffs;
    int		xCellOffs, yCellOffs;
    short	xCellDelta, yCellDelta;
    short	cellH, cellW;

    uint	eraseInPaint		: 1;
    uint	verSliding		: 1;
    uint	verSnappingOff		: 1;
    uint	horSliding		: 1;
    uint	horSnappingOff		: 1;
    uint	coveringCornerSquare	: 1;
    uint	sbDirty			: 8;
    uint	inSbUpdate		: 1;

    uint	tFlags;
    QRect	cellUpdateR;

    QScrollBar *vScrollBar;
    QScrollBar *hScrollBar;
    QCornerSquare *cornerSquare;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QtTableView( const QtTableView & );
    QtTableView &operator=( const QtTableView & );
#endif
};

const uint Tbl_vScrollBar	= 0x00000001;
const uint Tbl_hScrollBar	= 0x00000002;
const uint Tbl_autoVScrollBar	= 0x00000004;
const uint Tbl_autoHScrollBar	= 0x00000008;
const uint Tbl_autoScrollBars	= 0x0000000C;

const uint Tbl_clipCellPainting = 0x00000100;
const uint Tbl_cutCellsV	= 0x00000200;
const uint Tbl_cutCellsH	= 0x00000400;
const uint Tbl_cutCells		= 0x00000600;

const uint Tbl_scrollLastHCell	= 0x00000800;
const uint Tbl_scrollLastVCell	= 0x00001000;
const uint Tbl_scrollLastCell	= 0x00001800;

const uint Tbl_smoothHScrolling = 0x00002000;
const uint Tbl_smoothVScrolling = 0x00004000;
const uint Tbl_smoothScrolling	= 0x00006000;

const uint Tbl_snapToHGrid	= 0x00008000;
const uint Tbl_snapToVGrid	= 0x00010000;
const uint Tbl_snapToGrid	= 0x00018000;

inline int QtTableView::numRows() const
{ return nRows; }

inline int QtTableView::numCols() const
{ return nCols; }

inline int QtTableView::topCell() const
{ return yCellOffs; }

inline int QtTableView::leftCell() const
{ return xCellOffs; }

inline int QtTableView::xOffset() const
{ return xOffs; }

inline int QtTableView::yOffset() const
{ return yOffs; }

inline int QtTableView::cellHeight() const
{ return cellH; }

inline int QtTableView::cellWidth() const
{ return cellW; }

inline uint QtTableView::tableFlags() const
{ return tFlags; }

inline bool QtTableView::testTableFlags( uint f ) const
{ return (tFlags & f) != 0; }

inline QRect QtTableView::cellUpdateRect() const
{ return cellUpdateR; }

inline bool QtTableView::autoUpdate() const
{ return isUpdatesEnabled(); }

inline void QtTableView::repaint( bool erase )
{ repaint( 0, 0, width(), height(), erase ); }

inline void QtTableView::repaint( const QRect &r, bool erase )
{ repaint( r.x(), r.y(), r.width(), r.height(), erase ); }

inline void QtTableView::updateScrollBars()
{ updateScrollBars( 0 ); }

#endif // QT_NO_QTTABLEVIEW

#endif // QTTABLEVIEW_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QtTableView Member List

Complete Member List for QtTableView

This is the complete list of member functions for QtTableView, including inherited members.

  • QtTableView()
  • ~QtTableView()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • autoUpdate()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • cellHeight()
  • cellUpdateRect()
  • cellWidth()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearTableFlags()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colIsVisible()
  • colXPos()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • findCol()
  • findRow()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • horizontalScrollBar()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • lastColVisible()
  • lastRowVisible()
  • layout()
  • leaveEvent()
  • leftCell()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maxColOffset()
  • maxRowOffset()
  • maxViewX()
  • maxViewY()
  • maxXOffset()
  • maxYOffset()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minViewX()
  • minViewY()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • numCols()
  • numRows()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintCell()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • rowIsVisible()
  • rowYPos()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setAutoUpdate()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCellHeight()
  • setCellWidth()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLeftCell()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNumCols()
  • setNumRows()
  • setOffset()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTableFlags()
  • setTopCell()
  • setTopLeftCell()
  • setUpdatesEnabled()
  • setWFlags()
  • setXOffset()
  • setYOffset()
  • setupPainter()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tableFlags()
  • tabletEvent()
  • testTableFlags()
  • testWFlags()
  • timerEvent()
  • topCell()
  • topLevelWidget()
  • totalHeight()
  • totalWidth()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateCell()
  • updateGeometry()
  • updateMask()
  • updateScrollBars()
  • updateTableSize()
  • verticalScrollBar()
  • viewHeight()
  • viewRect()
  • viewWidth()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xOffset()
  • y()
  • yOffset()


QUriDrag Class

QUriDrag Class Reference

The QUriDrag class provides a drag object for a list of URI references. More...

#include <qdragobject.h>

Inherits QStoredDrag.

List of all member functions.

Public Members

  • QUriDrag ( QStrList uris, QWidget * dragSource = 0, const char * name = 0 )
  • QUriDrag ( QWidget * dragSource = 0, const char * name = 0 )
  • ~QUriDrag ()
  • void setFilenames ( const QStringList & fnames ) (obsolete)
  • void setFileNames ( const QStringList & fnames )
  • void setUnicodeUris ( const QStringList & uuris )
  • virtual void setUris ( QStrList uris )

Static Public Members

  • QString uriToLocalFile ( const char * uri )
  • QCString localFileToUri ( const QString & filename )
  • QString uriToUnicodeUri ( const char * uri )
  • QCString unicodeUriToUri ( const QString & uuri )
  • bool canDecode ( const QMimeSource * e )
  • bool decode ( const QMimeSource * e, QStrList & l )
  • bool decodeToUnicodeUris ( const QMimeSource * e, QStringList & l )
  • bool decodeLocalFiles ( const QMimeSource * e, QStringList & l )

Detailed Description

The QUriDrag class provides a drag object for a list of URI references.

URIs are a useful way to refer to files that may be distributed across multiple machines. A URI will often refer to a file on a machine local to both the drag source and the drop target, so the URI can be equivalent to passing a file name but is more extensible.

Use URIs in Unicode form so that the user can comfortably edit and view them. For use in HTTP or other protocols, use the correctly escaped ASCII form.

You can convert a list of file names to file URIs using setFileNames(), or into human-readble form with setUnicodeUris().

Static functions are provided to convert between filenames and URIs, e.g. uriToLocalFile() and localFileToUri(), and to and from human-readable form, e.g. uriToUnicodeUri(), unicodeUriToUri(). You can also decode URIs from a mimesource into a list with decodeLocalFiles() and decodeToUnicodeUris().

See also Drag And Drop Classes.

Member Function Documentation

QUriDrag::QUriDrag ( QStrList uris, QWidget * dragSource = 0, const char * name = 0 )

Constructs an object to drag the list of URIs in uris. The dragSource and name arguments are passed on to QStoredDrag. Note that URIs are always in escaped UTF8 encoding, as defined by the W3C.

QUriDrag::QUriDrag ( QWidget * dragSource = 0, const char * name = 0 )

Constructs an object to drag. You must call setUris() before you start the drag(). Passes dragSource and name to the QStoredDrag constructor.

QUriDrag::~QUriDrag ()

Destroys the object.

bool QUriDrag::canDecode ( const QMimeSource * e ) [static]

Returns TRUE if decode() would be able to decode e; otherwise returns FALSE.

bool QUriDrag::decode ( const QMimeSource * e, QStrList & l ) [static]

Decodes URIs from e, placing the result in l (which is first cleared).

Returns TRUE if e contained a valid list of URIs; otherwise returns FALSE.

Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp.

bool QUriDrag::decodeLocalFiles ( const QMimeSource * e, QStringList & l ) [static]

Decodes URIs from the mime source event e, converts them to local files if they refer to local files, and places them in l (which is first cleared).

Returns TRUE if contained a valid list of URIs; otherwise returns FALSE. The list will be empty if no URIs were local files.

bool QUriDrag::decodeToUnicodeUris ( const QMimeSource * e, QStringList & l ) [static]

Decodes URIs from the mime source event e, converts them to Unicode URIs (only useful for displaying to humans), placing them in l (which is first cleared).

Returns TRUE if contained a valid list of URIs; otherwise returns FALSE.

QCString QUriDrag::localFileToUri ( const QString & filename ) [static]

Returns the URI equivalent to the absolute local file filename.

See also uriToLocalFile().

void QUriDrag::setFileNames ( const QStringList & fnames )

Sets the URIs to be the local-file URIs equivalent to fnames.

See also localFileToUri() and setUris().

void QUriDrag::setFilenames ( const QStringList & fnames )

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

Use setFileNames() instead (notice the N).

void QUriDrag::setUnicodeUris ( const QStringList & uuris )

Sets the URIs in uuris to be the Unicode URIs (only useful for displaying to humans).

See also localFileToUri() and setUris().

Example: dirview/dirview.cpp.

void QUriDrag::setUris ( QStrList uris ) [virtual]

Changes the list of uris to be dragged.

QCString QUriDrag::unicodeUriToUri ( const QString & uuri ) [static]

Returns the URI equivalent of the Unicode URI given in uuri (only useful for displaying to humans).

See also uriToLocalFile().

QString QUriDrag::uriToLocalFile ( const char * uri ) [static]

Returns the name of a local file equivalent to uri or a null string if uri is not a local file.

See also localFileToUri().

QString QUriDrag::uriToUnicodeUri ( const char * uri ) [static]

Returns the Unicode URI (only useful for displaying to humans) equivalent of uri.

See also localFileToUri().

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


QUriDrag Member List

Complete Member List for QUriDrag

This is the complete list of member functions for QUriDrag, including inherited members.

  • QUriDrag()
  • ~QUriDrag()
  • blockSignals()
  • canDecode()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • decode()
  • decodeLocalFiles()
  • decodeToUnicodeUris()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drag()
  • dragCopy()
  • dragLink()
  • dragMove()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encodedData()
  • event()
  • eventFilter()
  • format()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • localFileToUri()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixmap()
  • pixmapHotSpot()
  • property()
  • provides()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • serialNumber()
  • setEncodedData()
  • setFileNames()
  • setFilenames()
  • setName()
  • setPixmap()
  • setProperty()
  • setUnicodeUris()
  • setUris()
  • signalsBlocked()
  • source()
  • startTimer()
  • target()
  • timerEvent()
  • tr()
  • trUtf8()
  • unicodeUriToUri()
  • uriToLocalFile()
  • uriToUnicodeUri()


QUrl Class

QUrl Class Reference
[network module]

The QUrl class provides a URL parser and simplifies working with URLs. More...

#include <qurl.h>

Inherited by QUrlOperator.

List of all member functions.

Public Members

  • QUrl ()
  • QUrl ( const QString & url )
  • QUrl ( const QUrl & url )
  • QUrl ( const QUrl & url, const QString & relUrl, bool checkSlash = FALSE )
  • virtual ~QUrl ()
  • QString protocol () const
  • virtual void setProtocol ( const QString & protocol )
  • QString user () const
  • virtual void setUser ( const QString & user )
  • bool hasUser () const
  • QString password () const
  • virtual void setPassword ( const QString & pass )
  • bool hasPassword () const
  • QString host () const
  • virtual void setHost ( const QString & host )
  • bool hasHost () const
  • int port () const
  • virtual void setPort ( int port )
  • bool hasPort () const
  • QString path ( bool correct = TRUE ) const
  • virtual void setPath ( const QString & path )
  • bool hasPath () const
  • virtual void setEncodedPathAndQuery ( const QString & pathAndQuery )
  • QString encodedPathAndQuery ()
  • virtual void setQuery ( const QString & txt )
  • QString query () const
  • QString ref () const
  • virtual void setRef ( const QString & txt )
  • bool hasRef () const
  • bool isValid () const
  • bool isLocalFile () const
  • virtual void addPath ( const QString & pa )
  • virtual void setFileName ( const QString & name )
  • QString fileName () const
  • QString dirPath () const
  • QUrl & operator= ( const QUrl & url )
  • QUrl & operator= ( const QString & url )
  • bool operator== ( const QUrl & url ) const
  • bool operator== ( const QString & url ) const
  • operator QString () const
  • virtual QString toString ( bool encodedPath = FALSE, bool forcePrependProtocol = TRUE ) const
  • virtual bool cdUp ()

Static Public Members

  • void decode ( QString & url )
  • void encode ( QString & url )
  • bool isRelativeUrl ( const QString & url )

Protected Members

  • virtual void reset ()
  • virtual bool parse ( const QString & url )

Detailed Description

The QUrl class provides a URL parser and simplifies working with URLs.

The QUrl class is provided for simple work with URLs. It can parse, decode, encode, etc.

QUrl works with the decoded path and encoded query in turn.

Example:

http://www.trolltech.com:80/cgi-bin/test%20me.pl?cmd=Hello%20you

Function | Returns
protocol() | "http"
host() | "www.trolltech.com"
port() | 80
path() | "cgi-bin"
fileName() | "test me.pl"
query() | "cmd=Hello%20you"

Example:

http://doc.trolltech.com/qdockarea.html#lines

Function | Returns
protocol() | "http"
host() | "doc.trolltech.com"
fileName() | "qdockarea.html"
ref() | "lines"

The individual parts of a URL can be set with setProtocol(), setHost(), setPort(), setPath(), setFileName(), setRef() and setQuery(). A URL could contain, for example, an ftp address which requires a user name and password; these can be set with setUser() and setPassword().

Because path is always encoded internally you must not use "%00" in the path, although this is okay (but not recommended) for the query.

QUrl is normally used like this:

    QUrl url( "http://www.trolltech.com" );
    // or
    QUrl url( "file:/home/myself/Mail", "Inbox" );

You can then access and manipulate the various parts of the URL.

To make it easy to work with QUrls and QStrings, QUrl implements the necessary cast and assignment operators so you can do following:

    QUrl url( "http://www.trolltech.com" );
    QString s = url;
    // or
    QString s( "http://www.trolltech.com" );
    QUrl url( s );

Use the static functions, encode() and decode() to encode or decode a URL in a string. (They operate on the string in-place.) The isRelativeUrl() static function returns TRUE if the given string is a relative URL.

If you want to use a URL to work on a hierarchical structure (e.g. a local or remote filesystem), you might want to use the subclass QUrlOperator.

See also QUrlOperator, Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QUrl::QUrl ()

Constructs an empty URL that is invalid.

QUrl::QUrl ( const QString & url )

Constructs a URL by parsing the string url.

If you pass a string like "/home/qt", the "file" protocol is assumed.

QUrl::QUrl ( const QUrl & url )

Copy constructor. Copies the data of url.

QUrl::QUrl ( const QUrl & url, const QString & relUrl, bool checkSlash = FALSE )

Constructs an URL taking url as the base (context) and relUrl as a relative URL to url. If relUrl is not relative, relUrl is taken as the new URL.

For example, the path of

    QUrl url( "ftp://ftp.trolltech.com/qt/source", "qt-2.1.0.tar.gz" );
will be "/qt/srource/qt-2.1.0.tar.gz".

On the other hand,

    QUrl url( "ftp://ftp.trolltech.com/qt/source", "/usr/local" );
will result in a new URL, "ftp://ftp.trolltech.com/usr/local", because "/usr/local" isn't relative.

Similarly,

    QUrl url( "ftp://ftp.trolltech.com/qt/source", "file:/usr/local" );
will result in a new URL, with "/usr/local" as the path and "file" as the protocol.

Normally it is expected that the path of url points to a directory, even if the path has no slash at the end. But if you want the constructor to handle the last part of the path as a file name if there is no slash at the end, and to let it be replaced by the file name of relUrl (if it contains one), set checkSlash to TRUE.

QUrl::~QUrl () [virtual]

Destructor.

void QUrl::addPath ( const QString & pa ) [virtual]

Adds the path pa to the path of the URL.

See also setPath() and hasPath().

bool QUrl::cdUp () [virtual]

Changes the directory to one directory up.

See also setPath().

void QUrl::decode ( QString & url ) [static]

Decodes the string url in-place.

See also encode().

QString QUrl::dirPath () const

Returns the directory path of the URL. This is the part of the path of the URL without the fileName(). See the documentation of fileName() for a discussion of what is handled as file name and what is handled as directory path.

See also setPath() and hasPath().

Example: network/networkprotocol/nntp.cpp.

void QUrl::encode ( QString & url ) [static]

Encodes the string url in-place.

See also decode().

QString QUrl::encodedPathAndQuery ()

Returns the encoded path and query.

See also decode().

QString QUrl::fileName () const

Returns the file name of the URL. If the path of the URL doesn't have a slash at the end, the part between the last slash and the end of the path string is considered to be the file name. If the path has a slash at the end, an empty string is returned here.

See also setFileName().

Example: network/networkprotocol/nntp.cpp.

bool QUrl::hasHost () const

Returns TRUE if the URL contains a hostname; otherwise returns FALSE.

See also setHost().

bool QUrl::hasPassword () const

Returns TRUE if the URL contains a password; otherwise returns FALSE.

Warning: Passwords passed in URLs are normally insecure; this is due to the mechanism, not because of Qt.

See also setPassword() and setUser().

bool QUrl::hasPath () const

Returns TRUE if the URL contains a path; otherwise returns FALSE.

See also path() and setPath().

bool QUrl::hasPort () const

Returns TRUE if the URL contains a port; otherwise returns FALSE.

See also setPort().

bool QUrl::hasRef () const

Returns TRUE if the URL has a reference; otherwise returns FALSE.

See also setRef().

bool QUrl::hasUser () const

Returns TRUE if the URL contains a username; otherwise returns FALSE.

See also setUser() and setPassword().

QString QUrl::host () const

Returns the hostname of the URL.

See also setHost() and hasHost().

bool QUrl::isLocalFile () const

Returns TRUE if the URL is a local file; otherwise returns FALSE.

Example: qdir/qdir.cpp.

bool QUrl::isRelativeUrl ( const QString & url ) [static]

Returns TRUE if url is relative; otherwise returns FALSE.

bool QUrl::isValid () const

Returns TRUE if the URL is valid; otherwise returns FALSE. A URL is invalid if it cannot be parsed, for example.

QUrl::operator QString () const

Composes a string version of the URL and returns it.

See also QUrl::toString().

QUrl & QUrl::operator= ( const QUrl & url )

Assigns the data of url to this class.

QUrl & QUrl::operator= ( const QString & url )

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

Parses url and assigns the resulting data to this class.

If you pass a string like "/home/qt" the "file" protocol will be assumed.

bool QUrl::operator== ( const QUrl & url ) const

Compares this URL with url and returns TRUE if they are equal; otherwise returns FALSE.

bool QUrl::operator== ( const QString & url ) const

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

Compares this URL with url. url is parsed first. Returns TRUE if url is equal to this url; otherwise returns FALSE.

bool QUrl::parse ( const QString & url ) [virtual protected]

Parses the url.

QString QUrl::password () const

Returns the password of the URL.

Warning: Passwords passed in URLs are normally insecure; this is due to the mechanism, not because of Qt.

See also setPassword() and setUser().

QString QUrl::path ( bool correct = TRUE ) const

Returns the path of the URL. If correct is TRUE, the path is cleaned (deals with too many or too few slashes, cleans things like "/../..", etc). Otherwise path() returns exactly the path that was parsed or set.

See also setPath() and hasPath().

Example: qdir/qdir.cpp.

int QUrl::port () const

Returns the port of the URL or -1 if no port has been set.

See also setPort().

QString QUrl::protocol () const

Returns the protocol of the URL. Typically, "file", "http", "ftp", etc.

See also setProtocol().

QString QUrl::query () const

Returns the (encoded) query of the URL.

See also setQuery() and decode().

QString QUrl::ref () const

Returns the (encoded) reference of the URL.

See also setRef(), hasRef() and decode().

void QUrl::reset () [virtual protected]

Resets all parts of the URL to their default values and invalidates it.

void QUrl::setEncodedPathAndQuery ( const QString & pathAndQuery ) [virtual]

Parses pathAndQuery for a path and query and sets those values. The whole string must be encoded.

See also encode().

void QUrl::setFileName ( const QString & name ) [virtual]

Sets the file name of the URL to name. If this URL contains a fileName(), the original file name is replaced by name.

See the documentation of fileName() for a more detailed discussion of what is handled as file name and what is handled as a directory path.

See also fileName().

void QUrl::setHost ( const QString & host ) [virtual]

Sets the hostname of the URL to host.

See also host() and hasHost().

void QUrl::setPassword ( const QString & pass ) [virtual]

Sets the password of the URL to pass.

Warning: Passwords passed in URLs are normally insecure; this is due to the mechanism, not because of Qt.

See also password() and setUser().

void QUrl::setPath ( const QString & path ) [virtual]

Sets the path of the URL to path.

See also path() and hasPath().

void QUrl::setPort ( int port ) [virtual]

Sets the port of the URL to port.

See also port().

void QUrl::setProtocol ( const QString & protocol ) [virtual]

Sets the protocol of the URL to protocol. Typically, "file", "http", "ftp", etc.

See also protocol().

void QUrl::setQuery ( const QString & txt ) [virtual]

Sets the query of the URL to txt. txt must be encoded.

See also query() and encode().

void QUrl::setRef ( const QString & txt ) [virtual]

Sets the reference of the URL to txt. txt must be encoded.

See also ref(), hasRef() and encode().

void QUrl::setUser ( const QString & user ) [virtual]

Sets the username of the URL to user.

See also user() and setPassword().

QString QUrl::toString ( bool encodedPath = FALSE, bool forcePrependProtocol = TRUE ) const [virtual]

Composes a string version of the URL and returns it. If encodedPath is TRUE the path in the returned string is encoded. If forcePrependProtocol is TRUE and encodedPath looks like a local filename, the "file:/" protocol is also prepended.

See also encode() and decode().

QString QUrl::user () const

Returns the username of the URL.

See also setUser() and setPassword().

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


qurl.h Include File

qurl.h

This is the verbatim text of the qurl.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qurl.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QUrl class
**
** Created : 950429
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QURL_H
#define QURL_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_NETWORKPROTOCOL

class QUrlPrivate;

class Q_EXPORT QUrl
{
public:
    QUrl();
    QUrl( const QString& url );
    QUrl( const QUrl& url );
    QUrl( const QUrl& url, const QString& relUrl, bool checkSlash = FALSE );
    virtual ~QUrl();

    QString protocol() const;
    virtual void setProtocol( const QString& protocol );

    QString user() const;
    virtual void setUser( const QString& user );
    bool hasUser() const;

    QString password() const;
    virtual void setPassword( const QString& pass );
    bool hasPassword() const;

    QString host() const;
    virtual void setHost( const QString& user );
    bool hasHost() const;

    int port() const;
    virtual void setPort( int port );
    bool hasPort() const;

    QString path( bool correct = TRUE ) const;
    virtual void setPath( const QString& path );
    bool hasPath() const;

    virtual void setEncodedPathAndQuery( const QString& enc );
    QString encodedPathAndQuery();

    virtual void setQuery( const QString& txt );
    QString query() const;

    QString ref() const;
    virtual void setRef( const QString& txt );
    bool hasRef() const;

    bool isValid() const;
    bool isLocalFile() const;

    virtual void addPath( const QString& path );
    virtual void setFileName( const QString& txt );

    QString fileName() const;
    QString dirPath() const;

    QUrl& operator=( const QUrl& url );
    QUrl& operator=( const QString& url );

    bool operator==( const QUrl& url ) const;
    bool operator==( const QString& url ) const;

    static void decode( QString& url );
    static void encode( QString& url );

    operator QString() const;
    virtual QString toString( bool encodedPath = FALSE, bool forcePrependProtocol = TRUE ) const;

    virtual bool cdUp();

    static bool isRelativeUrl( const QString &url );

protected:
    virtual void reset();
    virtual bool parse( const QString& url );

private:
    QUrlPrivate *d;

};

#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QUrl Member List

Complete Member List for QUrl

This is the complete list of member functions for QUrl, including inherited members.

  • QUrl()
  • ~QUrl()
  • addPath()
  • cdUp()
  • decode()
  • dirPath()
  • encode()
  • encodedPathAndQuery()
  • fileName()
  • hasHost()
  • hasPassword()
  • hasPath()
  • hasPort()
  • hasRef()
  • hasUser()
  • host()
  • isLocalFile()
  • isRelativeUrl()
  • isValid()
  • operator QString()
  • operator=()
  • operator==()
  • parse()
  • password()
  • path()
  • port()
  • protocol()
  • query()
  • ref()
  • reset()
  • setEncodedPathAndQuery()
  • setFileName()
  • setHost()
  • setPassword()
  • setPath()
  • setPort()
  • setProtocol()
  • setQuery()
  • setRef()
  • setUser()
  • toString()
  • user()


QUrlInfo Class

QUrlInfo Class Reference

The QUrlInfo class stores information about URLs. More...

#include <qurlinfo.h>

List of all member functions.

Public Members

  • QUrlInfo ()
  • QUrlInfo ( const QUrlOperator & path, const QString & file )
  • QUrlInfo ( const QUrlInfo & ui )
  • QUrlInfo ( const QString & name, int permissions, const QString & owner, const QString & group, uint size, const QDateTime & lastModified, const QDateTime & lastRead, bool isDir, bool isFile, bool isSymLink, bool isWritable, bool isReadable, bool isExecutable )
  • QUrlInfo ( const QUrl & url, int permissions, const QString & owner, const QString & group, uint size, const QDateTime & lastModified, const QDateTime & lastRead, bool isDir, bool isFile, bool isSymLink, bool isWritable, bool isReadable, bool isExecutable )
  • QUrlInfo & operator= ( const QUrlInfo & ui )
  • virtual ~QUrlInfo ()
  • virtual void setName ( const QString & name )
  • virtual void setDir ( bool b )
  • virtual void setFile ( bool b )
  • virtual void setSymLink ( bool b )
  • virtual void setOwner ( const QString & s )
  • virtual void setGroup ( const QString & s )
  • virtual void setSize ( uint s )
  • virtual void setWritable ( bool b )
  • virtual void setReadable ( bool b )
  • virtual void setPermissions ( int p )
  • virtual void setLastModified ( const QDateTime & dt )
  • bool isValid () const
  • QString name () const
  • int permissions () const
  • QString owner () const
  • QString group () const
  • uint size () const
  • QDateTime lastModified () const
  • QDateTime lastRead () const
  • bool isDir () const
  • bool isFile () const
  • bool isSymLink () const
  • bool isWritable () const
  • bool isReadable () const
  • bool isExecutable () const
  • bool operator== ( const QUrlInfo & i ) const

Static Public Members

  • bool greaterThan ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy )
  • bool lessThan ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy )
  • bool equal ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy )

Detailed Description

The QUrlInfo class stores information about URLs.

This class is just a container for storing information about URLs, which is why all information must be passed in the constructor.

Unless you're reimplementing a network protocol you're unlikely to create QUrlInfo objects yourself, but you may receive QUrlInfo objects from functions, e.g. QUrlOperator::info().

 The information that can be retrieved includes name(),
permissions(), owner(), group(), size(), lastModified(),
lastRead(), isDir(), isFile(), isSymLink(), isWritable(),
isReadable() and isExecutable().

See also Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QUrlInfo::QUrlInfo ()

Constructs an invalid QUrlInfo object with default values.

See also isValid().

QUrlInfo::QUrlInfo ( const QUrlOperator & path, const QString & file )

Constructs a QUrlInfo object with information about the file file in the path. It tries to find the information about the file in the QUrlOperator path.

If the information is not found, this constructor creates an invalid QUrlInfo, i.e. isValid() returns FALSE. You should always check if the URL info is valid before relying on the return values of any getter functions.

If file is empty, it defaults to the QUrlOperator path, i.e. to the directory.

See also isValid() and QUrlOperator::info().

QUrlInfo::QUrlInfo ( const QUrlInfo & ui )

Copy constructor, copies ui to this URL info object.

QUrlInfo::QUrlInfo ( const QString & name, int permissions, const QString & owner, const QString & group, uint size, const QDateTime & lastModified, const QDateTime & lastRead, bool isDir, bool isFile, bool isSymLink, bool isWritable, bool isReadable, bool isExecutable )

Constructs a QUrlInfo object by specifying all the URL's information.

The information that is passed is the name, file permissions, owner and group and the file's size. Also passed is the lastModified date/time and the lastRead date/time. Flags are also passed, specifically, isDir, isFile, isSymLink, isWritable, isReadable and isExecutable.

QUrlInfo::QUrlInfo ( const QUrl & url, int permissions, const QString & owner, const QString & group, uint size, const QDateTime & lastModified, const QDateTime & lastRead, bool isDir, bool isFile, bool isSymLink, bool isWritable, bool isReadable, bool isExecutable )

Constructs a QUrlInfo object by specifying all the URL's information.

The information that is passed is the url, file permissions, owner and group and the file's size. Also passed is the lastModified date/time and the lastRead date/time. Flags are also passed, specifically, isDir, isFile, isSymLink, isWritable, isReadable and isExecutable.

QUrlInfo::~QUrlInfo () [virtual]

Destroys the URL info object.

The QUrlOperator object to which this URL referred (if any) is not affected.

bool QUrlInfo::equal ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy ) [static]

Returns TRUE if i1 equals to i2; otherwise returns FALSE. The objects are compared by the value, which is specified by sortBy. This must be one of QDir::Name, QDir::Time or QDir::Size.

bool QUrlInfo::greaterThan ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy ) [static]

Returns TRUE if i1 is greater than i2; otherwise returns FALSE. The objects are compared by the value, which is specified by sortBy. This must be one of QDir::Name, QDir::Time or QDir::Size.

QString QUrlInfo::group () const

Returns the group of the URL.

See also isValid().

bool QUrlInfo::isDir () const

Returns TRUE if the URL is a directory; otherwise returns FALSE.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

bool QUrlInfo::isExecutable () const

Returns TRUE if the URL is executable; otherwise returns FALSE.

See also isValid().

bool QUrlInfo::isFile () const

Returns TRUE if the URL is a file; otherwise returns FALSE.

See also isValid().

bool QUrlInfo::isReadable () const

Returns TRUE if the URL is readable; otherwise returns FALSE.

See also isValid().

bool QUrlInfo::isSymLink () const

Returns TRUE if the URL is a symbolic link; otherwise returns FALSE.

See also isValid().

bool QUrlInfo::isValid () const

Returns TRUE if the URL info is valid; otherwise returns FALSE. Valid means that the QUrlInfo contains real information. For example, a call to QUrlOperator::info() might return a an invalid QUrlInfo, if no information about the requested entry is available.

You should always check if the URL info is valid before relying on the values.

bool QUrlInfo::isWritable () const

Returns TRUE if the URL is writable; otherwise returns FALSE.

See also isValid().

QDateTime QUrlInfo::lastModified () const

Returns the last modification date of the URL.

See also isValid().

QDateTime QUrlInfo::lastRead () const

Returns the date when the URL was last read.

See also isValid().

bool QUrlInfo::lessThan ( const QUrlInfo & i1, const QUrlInfo & i2, int sortBy ) [static]

Returns TRUE if i1 is less than i2; otherwise returns FALSE. The objects are compared by the value, which is specified by sortBy. This must be one of QDir::Name, QDir::Time or QDir::Size.

QString QUrlInfo::name () const

Returns the file name of the URL.

See also isValid().

Examples: network/ftpclient/ftpmainwindow.cpp and network/ftpclient/ftpview.cpp.

QUrlInfo & QUrlInfo::operator= ( const QUrlInfo & ui )

Assigns the values of ui to this QUrlInfo object.

bool QUrlInfo::operator== ( const QUrlInfo & i ) const

Compares this QUrlInfo with i and returns TRUE if they are equal; otherwise returns FALSE.

QString QUrlInfo::owner () const

Returns the owner of the URL.

See also isValid().

int QUrlInfo::permissions () const

Returns the permissions of the URL.

See also isValid().

void QUrlInfo::setDir ( bool b ) [virtual]

If b is TRUE then the URL is set to be a directory; if \b is FALSE then the URL is set not to be a directory (which normally means it is a file). (Note that a URL can refer to both a file and a directory even though most file systems do not support this.)

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

void QUrlInfo::setFile ( bool b ) [virtual]

If b is TRUE then the URL is set to be a file; if \b is FALSE then the URL is set not to be a file (which normally means it is a directory). (Note that a URL can refer to both a file and a directory even though most file systems do not support this.)

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

void QUrlInfo::setGroup ( const QString & s ) [virtual]

Specifies that the owning group of the URL is called s.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

void QUrlInfo::setLastModified ( const QDateTime & dt ) [virtual]

Specifies that the object the URL refers to was last modified at dt.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

void QUrlInfo::setName ( const QString & name ) [virtual]

Sets the name of the URL to name. The name is the full text, for example, "http://doc.trolltech.com/qurlinfo.html".

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

void QUrlInfo::setOwner ( const QString & s ) [virtual]

Specifies that the owner of the URL is called s.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

void QUrlInfo::setPermissions ( int p ) [virtual]

Specifies that the URL has access permisions, p.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

void QUrlInfo::setReadable ( bool b ) [virtual]

Specifies that the URL is readable if b is TRUE and not readable if b is FALSE.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

void QUrlInfo::setSize ( uint s ) [virtual]

Specifies that the URL has size s.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

void QUrlInfo::setSymLink ( bool b ) [virtual]

Specifies that the URL refers to a symbolic link if b is TRUE and that it does not if b is FALSE.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

void QUrlInfo::setWritable ( bool b ) [virtual]

Specifies that the URL is writable if b is TRUE and not writable if b is FALSE.

If you call this function for an invalid URL info, this function turns it into a valid one.

See also isValid().

Example: network/networkprotocol/nntp.cpp.

uint QUrlInfo::size () const

Returns the size of the URL.

See also isValid().

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


qurlinfo.h Include File

qurlinfo.h

This is the verbatim text of the qurlinfo.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qurlinfo.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QUrlInfo class
**
** Created : 950429
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QURLINFO_H
#define QURLINFO_H

#ifndef QT_H
#include "qdatetime.h"
#include "qstring.h"
#endif // QT_H

class QUrlOperator;
class QUrl;
class QUrlInfoPrivate;

class Q_EXPORT QUrlInfo
{
public:
    QUrlInfo();
    QUrlInfo( const QUrlOperator &path, const QString &file );
    QUrlInfo( const QUrlInfo &ui );
    QUrlInfo( const QString &name, int permissions, const QString &owner,
          const QString &group, uint size, const QDateTime &lastModified,
          const QDateTime &lastRead, bool isDir, bool isFile, bool isSymLink,
          bool isWritable, bool isReadable, bool isExecutable );
    QUrlInfo( const QUrl &url, int permissions, const QString &owner,
          const QString &group, uint size, const QDateTime &lastModified,
          const QDateTime &lastRead, bool isDir, bool isFile, bool isSymLink,
          bool isWritable, bool isReadable, bool isExecutable );
    QUrlInfo &operator=( const QUrlInfo &ui );
    virtual ~QUrlInfo();

    virtual void setName( const QString &name );
    virtual void setDir( bool b );
    virtual void setFile( bool b );
    virtual void setSymLink( bool b );
    virtual void setOwner( const QString &s );
    virtual void setGroup( const QString &s );
    virtual void setSize( uint s );
    virtual void setWritable( bool b );
    virtual void setReadable( bool b );
    virtual void setPermissions( int p );
    virtual void setLastModified( const QDateTime &dt );

    bool isValid() const;

    QString name() const;
    int permissions() const;
    QString owner() const;
    QString group() const;
    uint size() const;
    QDateTime lastModified() const;
    QDateTime lastRead() const;
    bool isDir() const;
    bool isFile() const;
    bool isSymLink() const;
    bool isWritable() const;
    bool isReadable() const;
    bool isExecutable() const;

    static bool greaterThan( const QUrlInfo &i1, const QUrlInfo &i2,
                 int sortBy );
    static bool lessThan( const QUrlInfo &i1, const QUrlInfo &i2,
              int sortBy );
    static bool equal( const QUrlInfo &i1, const QUrlInfo &i2,
               int sortBy );

    bool operator==( const QUrlInfo &i ) const;
private:
    QUrlInfoPrivate *d;

};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QUrlInfo Member List

Complete Member List for QUrlInfo

This is the complete list of member functions for QUrlInfo, including inherited members.

  • QUrlInfo()
  • ~QUrlInfo()
  • equal()
  • greaterThan()
  • group()
  • isDir()
  • isExecutable()
  • isFile()
  • isReadable()
  • isSymLink()
  • isValid()
  • isWritable()
  • lastModified()
  • lastRead()
  • lessThan()
  • name()
  • operator=()
  • operator==()
  • owner()
  • permissions()
  • setDir()
  • setFile()
  • setGroup()
  • setLastModified()
  • setName()
  • setOwner()
  • setPermissions()
  • setReadable()
  • setSize()
  • setSymLink()
  • setWritable()
  • size()


QUrlOperator Class

QUrlOperator Class Reference
[network module]

The QUrlOperator class provides common operations on URLs. More...

#include <qurloperator.h>

Inherits QObject and QUrl.

List of all member functions.

Public Members

  • QUrlOperator ()
  • QUrlOperator ( const QString & url )
  • QUrlOperator ( const QUrlOperator & url )
  • QUrlOperator ( const QUrlOperator & url, const QString & relUrl, bool checkSlash = FALSE )
  • virtual ~QUrlOperator ()
  • virtual const QNetworkOperation * listChildren ()
  • virtual const QNetworkOperation * mkdir ( const QString & dirname )
  • virtual const QNetworkOperation * remove ( const QString & filename )
  • virtual const QNetworkOperation * rename ( const QString & oldname, const QString & newname )
  • virtual const QNetworkOperation * get ( const QString & location = QString::null )
  • virtual const QNetworkOperation * put ( const QByteArray & data, const QString & location = QString::null )
  • virtual QPtrList<QNetworkOperation> copy ( const QString & from, const QString & to, bool move = FALSE, bool toPath = TRUE )
  • virtual void copy ( const QStringList & files, const QString & dest, bool move = FALSE )
  • virtual bool isDir ( bool * ok = 0 )
  • virtual void setNameFilter ( const QString & nameFilter )
  • QString nameFilter () const
  • virtual QUrlInfo info ( const QString & entry ) const
  • virtual void stop ()

Signals

  • void newChildren ( const QValueList<QUrlInfo> & i, QNetworkOperation * op )
  • void finished ( QNetworkOperation * op )
  • void start ( QNetworkOperation * op )
  • void createdDirectory ( const QUrlInfo & i, QNetworkOperation * op )
  • void removed ( QNetworkOperation * op )
  • void itemChanged ( QNetworkOperation * op )
  • void data ( const QByteArray & data, QNetworkOperation * op )
  • void dataTransferProgress ( int bytesDone, int bytesTotal, QNetworkOperation * op )
  • void startedNextCopy ( const QPtrList<QNetworkOperation> & lst )
  • void connectionStateChanged ( int state, const QString & data )

Protected Members

  • virtual void clearEntries ()
  • void getNetworkProtocol ()
  • void deleteNetworkProtocol ()

Related Functions

  • void qInitNetworkProtocols ()

Detailed Description

The QUrlOperator class provides common operations on URLs.

This class operates on hierarchical structures (such as filesystems) using URLs. Its API facilitates all the common operations:

Operation | Function
List files | listChildren()
Make a directory | mkdir()
Remove a file | remove()
Rename a file | rename()
Get a file | get()
Put a file | put()
Copy a file | copy()

You can obtain additional information about the URL with isDir() and info(). If a directory is to be traversed using listChildren(), a name filter can be set with setNameFilter().

A QUrlOperator can be used like this, for example to download a file (and assuming that the FTP protocol is registered):

    QUrlOperator *op = new QUrlOperator();
    op->copy( QString("ftp://ftp.trolltech.com/qt/source/qt-2.1.0.tar.gz"),
             "file:/tmp" );

If you want to be notified about success/failure, progress, etc., you can connect to QUrlOperator's signals, e.g. to start(), newChildren(), createdDirectory(), removed(), data(), dataTransferProgress(), startedNextCopy(), connectionStateChanged(), finished(), etc. A network operation can be stopped with stop().

The class uses the functionality of registered network protocols to perform these operations. Depending of the protocol of the URL, it uses an appropriate network protocol class for the operations. Each of the operation functions of QUrlOperator creates a QNetworkOperation object that describes the operation and puts it into the operation queue for the network protocol used. If no suitable protocol could be found (because no implementation of the necessary network protocol is registered), the URL operator emits errors. Not every protocol supports every operation, but error handling deals with this problem.

To register the available network protocols, use the qInitNetworkProtocols() function. The protocols currently supported are:

  • FTP,
  • HTTP,
  • local file system.

For more information about the Qt Network Architecture see the Qt Network Documentation.

See also QNetworkProtocol, QNetworkOperation, Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QUrlOperator::QUrlOperator ()

Constructs a QUrlOperator with an empty (i.e. invalid) URL.

QUrlOperator::QUrlOperator ( const QString & url )

Constructs a QUrlOperator using url and parses this string.

If you pass strings like "/home/qt" the "file" protocol is assumed.

QUrlOperator::QUrlOperator ( const QUrlOperator & url )

Constructs a copy of url.

QUrlOperator::QUrlOperator ( const QUrlOperator & url, const QString & relUrl, bool checkSlash = FALSE )

Constructs a QUrlOperator. The URL on which this QUrlOperator operates is constructed out of the arguments url, relUrl and checkSlash: see the corresponding QUrl constructor for an explanation of these arguments.

QUrlOperator::~QUrlOperator () [virtual]

Destructor.

void QUrlOperator::clearEntries () [virtual protected]

Clears the cache of children.

void QUrlOperator::connectionStateChanged ( int state, const QString & data ) [signal]

This signal is emitted whenever the URL operator's connection state changes. state describes the new state, which is a QNetworkProtocol::ConnectionState value.

data is a string that describes the change of the connection. This can be used to display a message to the user.

QPtrList<QNetworkOperation> QUrlOperator::copy ( const QString & from, const QString & to, bool move = FALSE, bool toPath = TRUE ) [virtual]

Copies the file from to to. If move is TRUE, the file is moved (copied and removed). from must point to a file and to must point to a directory (into which from is copied) unless toPath is set to FALSE. If toPath is set to FALSE then the to variable is assumed to be the absolute file path (destination file path + file name). The copying is done using the get() and put() operations. If you want to be notified about the progress of the operation, connect to the dataTransferProgress() signal. Bear in mind that the get() and put() operations emit this signal through the QUrlOperator. The number of transferred bytes and the total bytes that you receive as arguments in this signal do not relate to the the whole copy operation; they relate first to the get() and then to the put() operation. Always check what type of operation the signal comes from; this is given in the signal's last argument.

At the end, finished() (with success or failure) is emitted, so check the state of the network operation object to see whether or not the operation was successful.

Because a move or copy operation consists of multiple operations (get(), put() and maybe remove()), this function doesn't return a single QNetworkOperation, but rather a list of them. They are in the order: get(), put() and (if applicable) remove().

See also get() and put().

void QUrlOperator::copy ( const QStringList & files, const QString & dest, bool move = FALSE ) [virtual]

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

Copies the files to the directory dest. If move is TRUE the files are moved, not copied. dest must point to a directory.

This function calls copy() for each entry in files in turn. You don't get a result from this function; each time a new copy begins, startedNextCopy() is emitted, with a list of QNetworkOperations that describe the new copy operation.

void QUrlOperator::createdDirectory ( const QUrlInfo & i, QNetworkOperation * op ) [signal]

This signal is emitted when mkdir() succeeds and the directory has been created. i holds the information about the new directory.

op is a pointer to the operation object, which contains all the information about the operation, including the state. op->arg(0) holds the new directory's name.

See also QNetworkOperation and QNetworkProtocol.

void QUrlOperator::data ( const QByteArray & data, QNetworkOperation * op ) [signal]

This signal is emitted when new data has been received after calling get() or put(). op is a pointer to the operation object which contains all the information about the operation, including the state. op->arg(0) holds the name of the file whose data is retrieved and op->rawArg(1) holds the (raw) data.

See also QNetworkOperation and QNetworkProtocol.

void QUrlOperator::dataTransferProgress ( int bytesDone, int bytesTotal, QNetworkOperation * op ) [signal]

This signal is emitted during data transfer (using put() or get()). bytesDone specifies how many bytes of bytesTotal have been transferred. More information about the operation is stored in op, a pointer to the network operation that is processed. bytesTotal may be -1, which means that the total number of bytes is not known.

See also QNetworkOperation and QNetworkProtocol.

void QUrlOperator::deleteNetworkProtocol () [protected]

Deletes the currently used network protocol.

void QUrlOperator::finished ( QNetworkOperation * op ) [signal]

This signal is emitted when an operation of some sort finishes, whether with success or failure. op is a pointer to the operation object, which contains all the information, including the state, of the operation which has been finished. Check the state and error code of the operation object to see whether or not the operation was successful.

See also QNetworkOperation and QNetworkProtocol.

const QNetworkOperation * QUrlOperator::get ( const QString & location = QString::null ) [virtual]

Tells the network protocol to get data from location or, if this is QString::null, to get data from the location to which this URL points (see QUrl::fileName() and QUrl::encodedPathAndQuery()). What happens then depends on the network protocol. The data() signal is emitted when data comes in. Because it's unlikely that all data will come in at once, it is common for multiple data() signals to be emitted. The dataTransferProgress() signal is emitted while processing the operation. At the end, finished() (with success or failure) is emitted, so check the state of the network operation object to see whether or not the operation was successful.

If location is QString::null, the path of this QUrlOperator should point to a file when you use this operation. If location is not empty, it can be a relative URL (a child of the path to which the QUrlOperator points) or an absolute URL.

For example, to get a web page you might do something like this:

    QUrlOperator op( "http://www.whatever.org/cgi-bin/search.pl?cmd=Hello" );
    op.get();

For most other operations, the path of the QUrlOperator must point to a directory. If you want to download a file you could do the following:

    QUrlOperator op( "ftp://ftp.whatever.org/pub" );
    // do some other stuff like op.listChildren() or op.mkdir( "new_dir" )
    op.get( "a_file.txt" );

This will get the data of ftp://ftp.whatever.org/pub/a_file.txt.

Never do anything like this:

    QUrlOperator op( "http://www.whatever.org/cgi-bin" );
    op.get( "search.pl?cmd=Hello" ); // WRONG!

If location is not empty and relative it must not contain any queries or references, just the name of a child. So if you need to specify a query or reference, do it as shown in the first example or specify the full URL (such as http://www.whatever.org/cgi-bin/search.pl?cmd=Hello) as location.

See also copy().

void QUrlOperator::getNetworkProtocol () [protected]

Finds a network protocol for the URL and deletes the old network protocol.

QUrlInfo QUrlOperator::info ( const QString & entry ) const [virtual]

Returns the URL information for the child entry, or returns an empty QUrlInfo object if there is no information available about entry.

bool QUrlOperator::isDir ( bool * ok = 0 ) [virtual]

Returns TRUE if the URL is a directory; otherwise returns FALSE. This may not always work correctly, if the protocol of the URL is something other than file (local filesystem). If you pass a bool pointer as the ok argument, *ok is set to TRUE if the result of this function is known to be correct, and to FALSE otherwise.

void QUrlOperator::itemChanged ( QNetworkOperation * op ) [signal]

This signal is emitted whenever a file which is a child of the URL has been changed, for example by successfully calling rename(). op is a pointer to the operation object which contains all the information about the operation, including the state. op->arg(0) holds the original file name and op->arg(1) holds the new file name (if it was changed).

See also QNetworkOperation and QNetworkProtocol.

const QNetworkOperation * QUrlOperator::listChildren () [virtual]

Starts listing the children of this URL (e.g. the files in the directory). The start() signal is emitted before the first entry is listed and finished() is emitted after the last one. The newChildren() signal is emitted for each list of new entries. If an error occurs, the signal finished() is emitted, so be sure to check the state of the network operation pointer.

Because the operation may not be executed immediately, a pointer to the QNetworkOperation object created by this function is returned. This object contains all the data about the operation and is used to refer to this operation later (e.g. in the signals that are emitted by the QUrlOperator). The return value can also be 0 if the operation object couldn't be created.

The path of this QUrlOperator must to point to a directory (because the children of this directory will be listed), not to a file.

const QNetworkOperation * QUrlOperator::mkdir ( const QString & dirname ) [virtual]

Tries to create a directory (child) with the name dirname. If it is successful, a newChildren() signal with the new child is emitted, and the createdDirectory() signal with the information about the new child is also emitted. The finished() signal (with success or failure) is emitted after the operation has been processed, so check the state of the network operation object to see whether or not the operation was successful.

Because the operation will not be executed immediately, a pointer to the QNetworkOperation object created by this function is returned. This object contains all the data about the operation and is used to refer to this operation later (e.g. in the signals that are emitted by the QUrlOperator). The return value can also be 0 if the operation object couldn't be created.

The path of this QUrlOperator must to point to a directory (not a file) because the new directory will be created in this path.

QString QUrlOperator::nameFilter () const

Returns the name filter of the URL.

See also QUrlOperator::setNameFilter() and QDir::nameFilter().

void QUrlOperator::newChildren ( const QValueList<QUrlInfo> & i, QNetworkOperation * op ) [signal]

This signal is emitted after listChildren() was called and new children (i.e. files) have been read from a list of files. i holds the information about the new files. op is a pointer to the operation object which contains all the information about the operation, including the state.

See also QNetworkOperation and QNetworkProtocol.

const QNetworkOperation * QUrlOperator::put ( const QByteArray & data, const QString & location = QString::null ) [virtual]

This function tells the network protocol to put data in location. If location is empty (QString::null), it puts the data in the location to which the URL points. What happens depends on the network protocol. Depending on the network protocol, some data might come back after putting data, in which case the data() signal is emitted. The dataTransferProgress() signal is emitted during processing of the operation. At the end, finished() (with success or failure) is emitted, so check the state of the network operation object to see whether or not the operation was successful.

If location is QString::null, the path of this QUrlOperator should point to a file when you use this operation. If location is not empty, it can be a relative (a child of the path to which the QUrlOperator points) or an absolute URL.

For putting some data to a file you can do the following:

    QUrlOperator op( "ftp://ftp.whatever.com/home/me/filename.dat" );
    op.put( data );

For most other operations, the path of the QUrlOperator must point to a directory. If you want to upload data to a file you could do the following:

    QUrlOperator op( "ftp://ftp.whatever.com/home/me" );
    // do some other stuff like op.listChildren() or op.mkdir( "new_dir" )
    op.put( data, "filename.dat" );

This will upload the data to ftp://ftp.whatever.com/home/me/filename.dat.

See also copy().

const QNetworkOperation * QUrlOperator::remove ( const QString & filename ) [virtual]

Tries to remove the file (child) filename. If it succeeds the removed() signal is emitted. finished() (with success or failure) is also emitted after the operation has been processed, so check the state of the network operation object to see whether or not the operation was successful.

Because the operation will not be executed immediately, a pointer to the QNetworkOperation object created by this function is returned. This object contains all the data about the operation and is used to refer to this operation later (e.g. in the signals that are emitted by the QUrlOperator). The return value can also be 0 if the operation object couldn't be created.

The path of this QUrlOperator must point to a directory; because if filename is relative, it will try to remove it in this directory.

void QUrlOperator::removed ( QNetworkOperation * op ) [signal]

This signal is emitted when remove() has been succesful and the file has been removed.

op is a pointer to the operation object which contains all the information about the operation, including the state. op->arg(0) holds the name of the file that was removed.

See also QNetworkOperation and QNetworkProtocol.

const QNetworkOperation * QUrlOperator::rename ( const QString & oldname, const QString & newname ) [virtual]

Tries to rename the file (child) called oldname to newname. If it succeeds, the itemChanged() signal is emitted. finished() (with success or failure) is also emitted after the operation has been processed, so check the state of the network operation object to see whether or not the operation was successful.

Because the operation may not be executed immediately, a pointer to the QNetworkOperation object created by this function is returned. This object contains all the data about the operation and is used to refer to this operation later (e.g. in the signals that are emitted by the QUrlOperator). The return value can also be 0 if the operation object couldn't be created.

This path of this QUrlOperator must to point to a directory because oldname and newname are handled relative to this directory.

void QUrlOperator::setNameFilter ( const QString & nameFilter ) [virtual]

Sets the name filter of the URL to nameFilter.

See also QDir::setNameFilter().

void QUrlOperator::start ( QNetworkOperation * op ) [signal]

Some operations (such as listChildren()) emit this signal when they start processing the operation. op is a pointer to the operation object which contains all the information about the operation, including the state.

See also QNetworkOperation and QNetworkProtocol.

void QUrlOperator::startedNextCopy ( const QPtrList<QNetworkOperation> & lst ) [signal]

This signal is emitted if copy() starts a new copy operation. lst contains all QNetworkOperations related to this copy operation.

See also copy().

void QUrlOperator::stop () [virtual]

Stops the current network operation and removes all this QUrlOperator's waiting network operations.

Related Functions

void qInitNetworkProtocols ()

This function registers the network protocols for FTP and HTTP. You have to call this function before you use QUrlOperator for these protocols.

This function is declared in qnetwork.h.

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


qurloperator.h Include File

qurloperator.h

This is the verbatim text of the qurloperator.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qurloperator.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QUrlOperator class
**
** Created : 950429
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QURLOPERATOR_H
#define QURLOPERATOR_H

#ifndef QT_H
#include "qobject.h"
#include "qurl.h"
#include "qptrlist.h"
#include "qnetworkprotocol.h"
#include "qstringlist.h" // QString->QStringList conversion
#endif // QT_H

#ifndef QT_NO_NETWORKPROTOCOL

class QUrlInfo;
class QUrlOperatorPrivate;

class Q_EXPORT QUrlOperator : public QObject, public QUrl
{
    friend class QNetworkProtocol;

    Q_OBJECT

public:
    QUrlOperator();
    QUrlOperator( const QString &urL );
    QUrlOperator( const QUrlOperator& url );
    QUrlOperator( const QUrlOperator& url, const QString& relUrl, bool checkSlash = FALSE );
    virtual ~QUrlOperator();

    virtual void setPath( const QString& path );
    virtual bool cdUp();

    virtual const QNetworkOperation *listChildren();
    virtual const QNetworkOperation *mkdir( const QString &dirname );
    virtual const QNetworkOperation *remove( const QString &filename );
    virtual const QNetworkOperation *rename( const QString &oldname, const QString &newname );
    virtual const QNetworkOperation *get( const QString &location = QString::null );
    virtual const QNetworkOperation *put( const QByteArray &data, const QString &location = QString::null  );
    virtual QPtrList<QNetworkOperation> copy( const QString &from, const QString &to, bool move = FALSE, bool toPath = TRUE );
    virtual void copy( const QStringList &files, const QString &dest, bool move = FALSE );
    virtual bool isDir( bool *ok = 0 );

    virtual void setNameFilter( const QString &nameFilter );
    QString nameFilter() const;

    virtual QUrlInfo info( const QString &entry ) const;

    QUrlOperator& operator=( const QUrlOperator &url );
    QUrlOperator& operator=( const QString &url );

    virtual void stop();

signals:
    void newChildren( const QValueList<QUrlInfo> &, QNetworkOperation *res );
    void finished( QNetworkOperation *res );
    void start( QNetworkOperation *res );
    void createdDirectory( const QUrlInfo &, QNetworkOperation *res );
    void removed( QNetworkOperation *res );
    void itemChanged( QNetworkOperation *res );
    void data( const QByteArray &, QNetworkOperation *res );
    void dataTransferProgress( int bytesDone, int bytesTotal, QNetworkOperation *res );
    void startedNextCopy( const QPtrList<QNetworkOperation> &lst );
    void connectionStateChanged( int state, const QString &data );

protected:
    void reset();
    bool parse( const QString& url );
    virtual bool checkValid();
    virtual void clearEntries();
    void getNetworkProtocol();
    void deleteNetworkProtocol();

private slots:
    const QNetworkOperation *startOperation( QNetworkOperation *op );
    void copyGotData( const QByteArray &data, QNetworkOperation *op );
    void continueCopy( QNetworkOperation *op );
    void finishedCopy();
    void addEntry( const QValueList<QUrlInfo> &i );
    void slotItemChanged( QNetworkOperation *op );

private:
    void deleteOperation( QNetworkOperation *op );

    QUrlOperatorPrivate *d;

};

#endif // QT_NO_NETWORKPROTOCOL

#endif // QURLOPERATOR_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QUrlOperator Member List

Complete Member List for QUrlOperator

This is the complete list of member functions for QUrlOperator, including inherited members.

  • QUrlOperator()
  • ~QUrlOperator()
  • addPath()
  • blockSignals()
  • cdUp()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clearEntries()
  • connect()
  • connectNotify()
  • connectionStateChanged()
  • copy()
  • createdDirectory()
  • customEvent()
  • data()
  • dataTransferProgress()
  • decode()
  • deleteLater()
  • deleteNetworkProtocol()
  • destroyed()
  • dirPath()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • encode()
  • encodedPathAndQuery()
  • event()
  • eventFilter()
  • fileName()
  • finished()
  • get()
  • getNetworkProtocol()
  • hasHost()
  • hasPassword()
  • hasPath()
  • hasPort()
  • hasRef()
  • hasUser()
  • highPriority()
  • host()
  • info()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isDir()
  • isLocalFile()
  • isRelativeUrl()
  • isValid()
  • isWidgetType()
  • itemChanged()
  • killTimer()
  • killTimers()
  • listChildren()
  • metaObject()
  • mkdir()
  • name()
  • nameFilter()
  • newChildren()
  • normalizeSignalSlot()
  • objectTrees()
  • operator QString()
  • operator=()
  • operator==()
  • parent()
  • parse()
  • password()
  • path()
  • port()
  • property()
  • protocol()
  • put()
  • query()
  • queryList()
  • ref()
  • remove()
  • removeChild()
  • removeEventFilter()
  • removed()
  • rename()
  • reset()
  • sender()
  • setEncodedPathAndQuery()
  • setFileName()
  • setHost()
  • setName()
  • setNameFilter()
  • setPassword()
  • setPath()
  • setPort()
  • setProperty()
  • setProtocol()
  • setQuery()
  • setRef()
  • setUser()
  • signalsBlocked()
  • start()
  • startTimer()
  • startedNextCopy()
  • stop()
  • timerEvent()
  • toString()
  • tr()
  • trUtf8()
  • user()


QValidator类

QValidator类参考

QValidator类提供了对输入文本的验证。 详情请见……

#include <qvalidator.h>

继承了QObject。

被QIntValidator、QDoubleValidator和QRegExpValidator继承。

所有成员函数的列表。

公有成员

  • QValidator ( QObject * parent, const char * name = 0 )
  • ~QValidator ()
  • enum State { Invalid, Intermediate, Valid = Intermediate, Acceptable }
  • virtual State validate ( QString & input, int & pos ) const = 0
  • virtual void fixup ( QString & input ) const

详细描述

QValidator类提供了对输入文本的验证。

这个类本身是抽象类。两个子类QIntValidator和QDoubleValidator提供了基本的数字范围检查，并且QRegExpValidator提供了一个使用自定义正则表达式的普通检查。

如果内置的验证器还不够的话，你可以继承QValidator。这个类有两个虚函数：validate()和fixup()。

validate()必须被每个子类重新实现。它根据参数是否有效（子类中来定义这个有效）返回Invalid、Intermediate或Acceptable。

这三种状态需要一些解释。Invalid是指字符串明显地无效。Intermediate是不太明显的——当字符串在不完整的时候（还在被编辑），这个有效的概念是要小心对待的。QValidator把Intermediate定义为一个字符串的属性，既不是明显地无效也不是作为最终结果可以接受的。Acceptable意味着作为最终结果这个字符串是可以接受的。在一个Acceptable字符串被输入的过程中任何似是而非的中间状态都是Intermediate。

这里是一些实例：

  • 对于一个接受从0到999的整数的行编辑，包括边界，42和666都是Acceptable，空字符串和1114是Intermediate并且asdf是Invalid。

  • 对于一个用来接受URL的可以编辑的组合框，任何格式正确的URL都是Acceptable，“http://www.trolltech.com/,”是Intermediate（它可能是被剪切过来的，所以后面有一个逗号），空字符串是有效的（用户可以可以选择和删除所有文本来准备输入一个新的URL）并且“http:///./”是Invalid。

  • 对于一个接受长度的微调框，“11cm”和“1in”是Acceptable，“11”和空字符串是Intermediate并且“http://www.trolltech.com”和“hour”是Invalid。

fixup()为提供了可以修改一些用户错误的验证器。默认实现是什么也不做。例如QLineEdit，如果用户按下回车键并且内容并不有效，这种情况下fixup()可以做些事情了。这样就允许一些Invalid字符串也可以被变为Acceptable。

QValidator通常被QLineEdit、QSpinBox和QComboBox使用。

请参考杂项类。

成员类型文档

QValidator::State

这个枚举类型定义了一个被验证的字符串所存在的状态。现在有三个状态：

  • QValidator::Invalid - 这个字符串是明显地有效。
  • QValidator::Intermediate - 这个字符串在被输入的过程中是似是而非的中间状态。
  • QValidator::Acceptable - 这个字符串作为最终结果是可以接受的，也就是说是有效的。

成员函数文档

QValidator::QValidator ( QObject * parent, const char * name = 0 )

设置被这个验证器使用的内部数据结构。在这个时候还没有人任何数据。parent和name参数被传递给QObject的构造函数。

QValidator::~QValidator ()

销毁这个验证器，释放任何存储和其它被使用的资源。

void QValidator::fixup ( QString & input ) const [虚]

这个函数会根据这个验证器的规则试图改变input来使之有效。它不需要结果是有效的字符串——这个函数的调用者必须在调用之后重新测试，默认是什么也不做。

这个函数的重新实现要改变input，尽管它们可能不生成有效字符串。例如，一个ISBN验证器也许想删除除了数字和“-”之外的任何字符，尽管结果不是一个有效的ISBN，一个姓氏验证器也许想要删除字符串开始和结尾的空白符号，尽管结果字符串并不存在于被接受的姓氏列表中。

State QValidator::validate ( QString & input, int & pos ) const [纯 虚]

如果根据这个验证器的规则，input是有效的，这个纯虚函数返回Invalid，如果看起来再编辑一下就会使结果变为可以接受（例如用户向一个接受10到99的窗口部件中输入了“4”），那么返回Intermediate，如果输入是有效的，就返回Acceptable。

如果需要的话，这个函数可以改变input和pos（光标位置）。

在QIntValidator、QDoubleValidator和QRegExpValidator中被重新实现。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qvalidator.h包含文件

qvalidator.h

这里是qvalidator.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of validator classes
**
** Created : 970610
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVALIDATOR_H
#define QVALIDATOR_H

#ifndef QT_H
#include "qobject.h"
#include "qstring.h" // char*->QString conversion
#include "qregexp.h" // QString->QRegExp conversion
#endif // QT_H

#ifndef QT_NO_VALIDATOR

class Q_EXPORT QValidator : public QObject
{
    Q_OBJECT
public:
    QValidator( QObject * parent, const char *name = 0 );
    ~QValidator();

    enum State { Invalid, Intermediate, Valid=Intermediate, Acceptable };

    virtual State validate( QString &, int & ) const = 0;
    virtual void fixup( QString & ) const;

private:
#if defined(Q_DISABLE_COPY)
    QValidator( const QValidator & );
    QValidator& operator=( const QValidator & );
#endif
};

class Q_EXPORT QIntValidator : public QValidator
{
    Q_OBJECT
    Q_PROPERTY( int bottom READ bottom WRITE setBottom )
    Q_PROPERTY( int top READ top WRITE setTop )

public:
    QIntValidator( QObject * parent, const char *name = 0 );
    QIntValidator( int bottom, int top,
           QObject * parent, const char *name = 0 );
    ~QIntValidator();

    QValidator::State validate( QString &, int & ) const;

    void setBottom( int );
    void setTop( int );
    virtual void setRange( int bottom, int top );

    int bottom() const { return b; }
    int top() const { return t; }

private:
#if defined(Q_DISABLE_COPY)
    QIntValidator( const QIntValidator & );
    QIntValidator& operator=( const QIntValidator & );
#endif

    int b, t;
};

class Q_EXPORT QDoubleValidator : public QValidator
{
    Q_OBJECT
    Q_PROPERTY( double bottom READ bottom WRITE setBottom )
    Q_PROPERTY( double top READ top WRITE setTop )
    Q_PROPERTY( int decimals READ decimals WRITE setDecimals )

public:
    QDoubleValidator( QObject * parent, const char *name = 0 );
    QDoubleValidator( double bottom, double top, int decimals,
              QObject * parent, const char *name = 0 );
    ~QDoubleValidator();

    QValidator::State validate( QString &, int & ) const;

    virtual void setRange( double bottom, double top, int decimals = 0 );
    void setBottom( double );
    void setTop( double );
    void setDecimals( int );

    double bottom() const { return b; }
    double top() const { return t; }
    int decimals() const { return d; }

private:
#if defined(Q_DISABLE_COPY)
    QDoubleValidator( const QDoubleValidator & );
    QDoubleValidator& operator=( const QDoubleValidator & );
#endif

    double b, t;
    int d;
};

class Q_EXPORT QRegExpValidator : public QValidator
{
    Q_OBJECT
    // Q_PROPERTY( QRegExp regExp READ regExp WRITE setRegExp )

public:
    QRegExpValidator( QObject *parent, const char *name = 0 );
    QRegExpValidator( const QRegExp& rx, QObject *parent,
              const char *name = 0 );
    ~QRegExpValidator();

    virtual QValidator::State validate( QString& input, int& pos ) const;

    void setRegExp( const QRegExp& rx );
    const QRegExp& regExp() const { return r; }

private:
#if defined(Q_DISABLE_COPY)
    QRegExpValidator( const QRegExpValidator& );
    QRegExpValidator& operator=( const QRegExpValidator& );
#endif

    QRegExp r;
};

#endif // QT_NO_VALIDATOR

#endif // QVALIDATOR_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValidator成员列表

完整的QValidator成员列表

这里是QValidator成员函数的完整列表，包括继承的成员。

  • QValidator()
  • ~QValidator()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • fixup()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()
  • validate()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueList类

QValueList类参考

QValueList类是一个提供双向链表的基于值的模板类。 详情请见……

#include <qvaluelist.h>

被QCanvasItemList、QStringList和QValueStack继承。

所有成员函数的列表。

公有成员

  • typedef QValueListIterator<T> iterator
  • typedef QValueListConstIterator<T> const_iterator
  • typedef T value_type
  • typedef value_type * pointer
  • typedef const value_type * const_pointer
  • typedef value_type & reference
  • typedef const value_type & const_reference
  • typedef size_t size_type
  • QValueList ()
  • QValueList ( const QValueList<T> & l )
  • QValueList ( const std::list<T> & l )
  • ~QValueList ()
  • QValueList<T> & operator= ( const QValueList<T> & l )
  • QValueList<T> & operator= ( const std::list<T> & l )
  • bool operator== ( const std::list<T> & l ) const
  • bool operator== ( const QValueList<T> & l ) const
  • bool operator!= ( const QValueList<T> & l ) const
  • iterator begin ()
  • const_iterator begin () const
  • iterator end ()
  • const_iterator end () const
  • iterator insert ( iterator it, const T & x )
  • uint remove ( const T & x )
  • void clear ()
  • QValueList<T> & operator<< ( const T & x )
  • size_type size () const
  • bool empty () const
  • void push_front ( const T & x )
  • void push_back ( const T & x )
  • iterator erase ( iterator it )
  • iterator erase ( iterator first, iterator last )
  • reference front ()
  • const_reference front () const
  • reference back ()
  • const_reference back () const
  • void pop_front ()
  • void pop_back ()
  • void insert ( iterator pos, size_type n, const T & x )
  • QValueList<T> operator+ ( const QValueList<T> & l ) const
  • QValueList<T> & operator+= ( const QValueList<T> & l )
  • iterator fromLast ()
  • const_iterator fromLast () const
  • bool isEmpty () const
  • iterator append ( const T & x )
  • iterator prepend ( const T & x )
  • iterator remove ( iterator it )
  • T & first ()
  • const T & first () const
  • T & last ()
  • const T & last () const
  • T & operator[] ( size_type i )
  • const T & operator[] ( size_type i ) const
  • iterator at ( size_type i )
  • const_iterator at ( size_type i ) const
  • iterator find ( const T & x )
  • const_iterator find ( const T & x ) const
  • iterator find ( iterator it, const T & x )
  • const_iterator find ( const_iterator it, const T & x ) const
  • int findIndex ( const T & x ) const
  • size_type contains ( const T & x ) const
  • size_type count () const
  • QValueList<T> & operator+= ( const T & x )
  • typedef QValueListIterator<T> Iterator
  • typedef QValueListConstIterator<T> ConstIterator

相关函数

  • QDataStream & operator>> ( QDataStream & s, QValueList<T> & l )
  • QDataStream & operator<< ( QDataStream & s, const QValueList<T> & l )

详细描述

QValueList类是一个提供双向链表的基于值的模板类。

QValueList是一个像STL一样的列表容器的Qt的实现。如果标准列表不能提供时，你可以在你的应用程序中使用它。QValueList是Qt模板库的一部分。

QValueList<T>定义了一个创建了一个全部为类T的值的列表的一个模板实例。注意QValueList不是存储指针为列表的成员，它保存每个成员的复制。这也就是为什么这些类被称为“基于值”，而QPtrList和QDict是“基于指针”。

QValueList包含并管理一个类型为T的对象的集合并且提供允许找到被包含的对象的迭代器。QValueList拥有它的项。关于更多的所有权语义，请参考QPtrCollection和其它一些基于指针的容器类。

一些类不能在QValueList中使用，例如，所有继承于QObject的类和那些所有实现窗口部件的类。只有值可以用在QValueList中。一个类作为值必须提供以下几点：

  • 一个复制构造函数
  • 一个赋值操作符
  • 一个默认构造函数，比如构造函数中没有使用任何参数。

注意在没有明确的版本被提供的时候，C++默认实现操作符和复制函数。在很多情况下，这就足够了。

QValueList的函数命名和其它Qt类是一致的（比如，count()、isEmpty()）。QValueList也提供兼容STL算法的一些函数，比如size()和empty()。已经熟悉STL的list的程序员也可以使用这些函数。

实例：

class Employee
{
public:
    Employee(): sn(0) {}
    Employee( const QString& forename, const QString& surname, int salary )
        : fn(forename), sn(surname), sal(salary)
    {}

    QString forename() const { return fn; }
    QString surname() const { return sn; }
    int salary() const { return sal; }
    void setSalary( int salary ) { sal = salary; }
private:
    QString fn;
    QString sn;
    int sal;
};

    typedef QValueList<Employee> EmployeeList;
    EmployeeList list;

    list.append( Employee("John", "Doe", 50000) );
    list.append( Employee("Jane", "Williams", 80000) );
    list.append( Employee("Tom", "Jones", 60000) );

    Employee mary( "Mary", "Hawthorne", 90000 );
    list.append( mary );
    mary.setSalary( 100000 );

    EmployeeList::iterator it;
    for ( it = list.begin(); it != list.end(); ++it )
        cout << (*it).surname().latin1() << ", " <<
                (*it).forename().latin1() << " earns " <<
                (*it).salary() << endl;

    // 输出：
    // Doe, John earns 50000
    // Williams, Jane earns 80000
    // Hawthorne, Mary earns 90000
    // Jones, Tom earns 60000

注意最后对Mary的薪水的改变并没有影响列表中的值，这是因为列表中创建了一个Mary条目的复制。

这里有几种方法在列表中找到项。begin()和end()函数返回列表中开始和结尾的迭代器。迭代器的优点是你可以通过对迭代器加/减就可以实现从当前位置向前/后移动了。end()返回的迭代器指向的是容器中最后一个之后的值。结尾之后的迭代器也是和列表关联的，它属于列表，尽管它是不可以解除引用的，operator*()不能返回一个被良好定义的值。如果列表是空的（empty()），begin()和end()返回的值一样。

另一个在列表中找到项的方法是使用qFind()算法。比如：

    QValueList<int> list;
    ...
    QValueList<int>::iterator it = qFind( list.begin(), list.end(), 3 );
    if ( it != list.end() )
        // it指向被找到的项。

同一时间在列表中使用多个迭代器是安全的。如果列表中的一些成员被移除，只有那些指向被移除的成员的迭代器变为无效。向列表中插入项不会使任何一个迭代器无效。为了方便，函数last()返回列表中最后一个项的引用，并且first()返回第一个项的引用。如果列表为空（empty()），last()和first()都会有未定义的行为发生（你的应用程序将会崩溃或者会做一些不可预知的事情）。使用last()和first()时需要注意，比如：

    QValueList<int> list;
    list.append( 1 );
    list.append( 2 );
    list.append( 3 );
    ...
    if ( !list.empty() ) {
        // OK, modify the first item
        int& i = list.first();
        i = 18;
    }
    ...
    QValueList<double> dlist;
    double d = dlist.last(); // undefined

因为QValueList是基于值的，所以在删除列表中的项时，就没有什么要注意的了。列表保存它自己的复制并且如果相应的项或者列表本身被删除时，列表会释放它们。你可以使用clear()来强制列表释放它所有的项。

QValueList是隐含地共享，这也就是说它能够在一个固定时间被复制。如果多个QValueList实例共享相同的数据并且一个需要修改它的内容，这个修改实例将会产生一个复制并且只修改它自己的复制，因此它对其它实例来说是无效的。这就是常说的“写时复制”。如果一个QValueList是在一个多线程程序中被使用，你必须保护所有对列表的访问。请参考QMutex。

向列表中插入项有好几个方法。prepend()和append()函数分别把项插入到列表的开始和结尾。insert()函数有好几种方式并且可以被用来向列表中的特定位置插入一个或多个项。

从列表中移除项也有好几个方法。remove()函数有好几种方式并且可以用来移除列表中的特定项。remove()函数可以根据特定的项的值来找到这个项并且删除它。

列表可以使用sort()函数来排序，或者使用Qt模板库来排序。比如使用qHeapSort()：

实例：

    QValueList<int> l;
    l.append( 5 );
    l.append( 8 );
    l.append( 3 );
    l.append( 4 );
    qHeapSort( l );

也可以参考QValueListIterator、Qt模板库类、隐含地和明示地共享类和非GUI类。

函数类型文档

QValueList::ConstIterator

这个迭代器是QValueListConstIterator的一个实例，类型和QValueList一样。换句话说，如果你QValueList<int>这样示例，ConstIterator就是QValueListConstIterator<int>。几个成员函数使用它，比如QValueList::begin()，它返回一个指向列表中第一个项的迭代器。

在功能上，它和Iterator基本一样。唯一的区别是你不能使用ConstIterator做非常量操作并且如果你使用ConstIterator，编译器经常会产生更好的代码。

也可以参考QValueListIterator和Iterator。

QValueList::Iterator

这个迭代器是QValueListIterator的一个实例，类型和QValueList一样。换句话说，如果你QValueList<int>这样示例，Iterator就是QValueListIterator<int>。几个成员函数使用它，比如QValueList::begin()，它返回一个指向列表中第一个项的迭代器。

在功能上，它和ConstIterator基本一样。唯一的区别是你不能使用ConstIterator做非常量操作并且如果你使用ConstIterator，编译器经常会产生更好的代码。

也可以参考QValueListIterator和ConstIterator。

QValueList::const_iterator

列表的常量迭代器类型，QValueListConstIterator。

QValueList::const_pointer

指向T类型的常量指针。

QValueList::const_reference

T类型的常量引用。

QValueList::iterator

列表的迭代器类型，QValueListIterator。

QValueList::pointer

指向T类型的指针。

QValueList::reference

T类型的引用。

QValueList::size_type

一个无符号整数类型，用来说明变量的大小。

QValueList::value_type

存储在列表中的对象的类型，T。

成员函数文档

QValueList::QValueList ()

构造一个空的列表。

QValueList::QValueList ( const QValueList<T> & l )

构造一个l的复制。

这个操作使用了O(1)时间，因为QValueList是隐含地共享。

第一次对列表的修改会使用O(n)时间。

QValueList::QValueList ( const std::list<T> & l )

构造一个l的复制。

这个构造函数提供了和STL容器的兼容。

QValueList::~QValueList ()

销毁这个列表。在列表中的值的引用和这个列表的所有迭代器都会变为无效。注意检查一个迭代器是否有效将是不可能的——因为QValueList已经为效率而优化了，而不是为错误检查。

iterator QValueList::append ( const T & x )

在列表结尾插入x。

也可以参考insert()和prepend()。

实例：checklists/checklists.cpp和fonts/simple-qfont-demo/viewer.cpp。

const_iterator QValueList::at ( size_type i ) const

返回指向列表中位置为i的项的迭代器，或者如果索引超出范围，返回end()。

警告：这个函数使用的是线性搜索并且对于大的列表这将会非常慢。QValueList没有对随机项访问进行优化。如果你需要随机访问，请使用一个不同的容易，比如QValueVector。

iterator QValueList::at ( size_type i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中位置为i的项的迭代器，或者如果索引超出范围，返回end()。

reference QValueList::back ()

返回指向最后一个项的引用。如果列表中没有最后一个项（比如，empty()返回真），返回值是未定义的。

这个函数的提供是为了兼容STL。它和last()是一样的。

也可以参考front()。

const_reference QValueList::back () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

const_iterator QValueList::begin () const

返回指向列表中第一个项的迭代器。如果列表为空，这个迭代器等于end()。

也可以参考first()和end()。

实例：chart/canvasview.cpp、chart/element.cpp、checklists/checklists.cpp、fonts/simple-qfont-demo/viewer.cpp、network/ftpclient/ftpview.cpp、table/statistics/statistics.cpp和themes/themes.cpp。

iterator QValueList::begin ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中第一个项的迭代器。如果列表为空，这个迭代器等于end()。

也可以参考first()和end()。

void QValueList::clear ()

移除列表中所有的项。

也可以参考remove()。

size_type QValueList::contains ( const T & x ) const

返回列表中值x出现的次数。

size_type QValueList::count () const

返回列表中项的数量。

也可以参考isEmpty()。

实例：chart/element.cpp和table/statistics/statistics.cpp。

bool QValueList::empty () const

如果列表中没有包含任何项，返回真，否则返回假。

也可以参考size()。

iterator QValueList::end ()

返回一个指向列表中最后一项之后的迭代器。如果列表为空，这个迭代器等于begin()。

也可以参考last()和begin()。

实例：chart/canvasview.cpp、chart/element.cpp、checklists/checklists.cpp、fonts/simple-qfont-demo/viewer.cpp、network/ftpclient/ftpview.cpp、sql/overview/insert/main.cpp和table/statistics/statistics.cpp。

const_iterator QValueList::end () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回一个指向列表中最后一项之后的迭代器。如果列表为空，这个迭代器等于begin()。

也可以参考last()和begin()。

iterator QValueList::erase ( iterator it )

从列表中移除it所指向的项。除了it之外其它指向相同项的迭代器一样都无效了。返回一个指向it之后的下一个项的迭代器，或者如果没有这样的项，返回end()。

这个函数的提供是为了兼容STL。它等于remove()。

iterator QValueList::erase ( iterator first, iterator last )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

删除从first到last的所有项（不包括last）。除了指向被移除项的迭代器，其它迭代器都有效。返回last。

iterator QValueList::find ( const T & x )

返回指向列表中第一次出现x的迭代器。

如果没有项匹配，返回end()。

const_iterator QValueList::find ( const T & x ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中第一次出现x的迭代器。

如果没有项匹配，返回end()。

iterator QValueList::find ( iterator it, const T & x )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中从it开始第一次出现x的迭代器。

如果没有项匹配，返回end()。

const_iterator QValueList::find ( const_iterator it, const T & x ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中从it开始第一次出现x的迭代器。

如果没有项匹配，返回end()。

int QValueList::findIndex ( const T & x ) const

返回列表中值x第一次出现的索引。如果没有项匹配，返回-1。

T & QValueList::first ()

返回第一个项的引用。如果列表中没有第一个项（比如，empty()返回真），返回值是未定义的。

也可以参考last()。

实例：network/mail/smtp.cpp。

const T & QValueList::first () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

const_iterator QValueList::fromLast () const

返回指向列表中最后一项的迭代器，或者如果列表中没有最后一项，返回end()。

可以使用end()函数替换。例如：

    QValueList<int> l;
    ……
    QValueList<int>::iterator it = l.end();
    --it;
    if ( it != end() )
        // ……

iterator QValueList::fromLast ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回指向列表中最后一项的迭代器，或者如果列表中没有最后一项，返回end()。

可以使用end()函数替换。例如：

    QValueList<int> l;
    ……
    QValueList<int>::iterator it = l.end();
    --it;
    if ( it != end() )
        // ……

reference QValueList::front ()

返回列表中第一个项的引用。如果列表中没有第一个项（比如，empty()返回真），返回值是为定义的。

这个函数的提供是为了兼容STL。它等于first()。

也可以参考back()。

const_reference QValueList::front () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

iterator QValueList::insert ( iterator it, const T & x )

在迭代器it之前插入值x。

返回指向被插入项的迭代器。

也可以参考append()和prepend()。

实例：themes/themes.cpp。

void QValueList::insert ( iterator pos, size_type n, const T & x )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在位置pos之前，插入x的n个复制。

bool QValueList::isEmpty () const

如果列表没有包含任何项，返回真，否则返回假。

也可以参考count()。

实例：fonts/simple-qfont-demo/viewer.cpp、network/ftpclient/ftpmainwindow.cpp和network/mail/smtp.cpp。

T & QValueList::last ()

返回列表中最后一项的引用。如果列表中没有最后一项（比如，empty()返回真），返回值是为定义的。

const T & QValueList::last () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

bool QValueList::operator!= ( const QValueList<T> & l ) const

比较两个列表。

如果这个列表和l不等，返回真，否则返回假。

QValueList<T> QValueList::operator+ ( const QValueList<T> & l ) const

创建一个新的列表并且用这个列表的项来填充它。然后l项被添加。返回新的列表。

QValueList<T> & QValueList::operator+= ( const QValueList<T> & l )

向这个列表添加l项。返回这个列表的引用。

QValueList<T> & QValueList::operator+= ( const T & x )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

向这个列表添加值x。返回这个列表的引用。

QValueList<T> & QValueList::operator<< ( const T & x )

在列表末尾添加值x。返回这个列表的引用。

QValueList<T> & QValueList::operator= ( const QValueList<T> & l )

把l赋值给这个列表并且返回这个列表的引用。

当前列表的所有迭代器都因为这个操作而变为无效。这个赋值操作消耗O(1)时间，因为QValueList是隐含地共享

QValueList<T> & QValueList::operator= ( const std::list<T> & l )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

把l的内容赋值给这个列表。

当前列表的所有迭代器都因为这个操作而变为无效。

bool QValueList::operator== ( const QValueList<T> & l ) const

比较两个列表。

如果这个列表和l相等，返回真，否则返回假。

bool QValueList::operator== ( const std::list<T> & l ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

如果这个列表和l相等，返回真，否则返回假。

这个操作符的提供是为了和STL容器兼容。

const T & QValueList::operator[] ( size_type i ) const

返回列表中索引为i的项的常量引用。由你来决定检查它是否真的存在。你可以很容易地使用count()函数做到这一点。无论如何，这个操作符没有检查i是否在范围之内并且如果它不存在，将会递送未定义的结果。

警告：这个函数使用的是线性搜索并且对于大的列表这将会非常慢。QValueList没有对随机项访问进行优化。如果你需要随机访问，请使用一个不同的容易，比如QValueVector。

T & QValueList::operator[] ( size_type i )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

Returns a non-const reference to the item with index i.

void QValueList::pop_back ()

移除列表中的最后一项。如果没有最后一项，这个操作是未定义的。

这个函数的提供是为了兼容STL。

void QValueList::pop_front ()

移除列表中的第一个项。如果没有第一个项，这个操作是未定义的。

这个函数的提供是为了兼容STL。

iterator QValueList::prepend ( const T & x )

在列表的开始插入x。

也可以参考insert()和append()。

void QValueList::push_back ( const T & x )

在列表的末尾插入x。

这个函数的提供是为了兼容STL。它等于append()。

void QValueList::push_front ( const T & x )

在列表的开始插入x。

这个函数的提供是为了兼容STL。它等于prepend()。

iterator QValueList::remove ( iterator it )

移除列表中it所指向的项。除了it之外其它指向相同项的迭代器一样都无效了。返回一个指向it之后的下一个项的迭代器，或者如果没有这样的项，返回end()。

也可以参考clear()。

uint QValueList::remove ( const T & x )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

移除所有值为x的项并且返回被移除项的数量。

size_type QValueList::size () const

Returns the number of items in the list.

这个函数的提供是为了兼容STL。它等于count()。

也可以参考empty()。

实例：network/ftpclient/ftpview.cpp。

相关函数

QDataStream & operator<< ( QDataStream & s, const QValueList<T> & l )

写一个列表l到流s中。存储在列表中的类型T也必须实现了这个操作符。

QDataStream & operator>> ( QDataStream & s, QValueList<T> & l )

从流s中读取一个列表l。存储在列表中的类型T也必须实现了这个操作符。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qvaluelist.h包含文件

qvaluelist.h

这里是qvaluelist.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qvaluelist.h   3.0.5   edited Jun 7 04:17 $
**
** Definition of QValueList class
**
** Created : 990406
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVALUELIST_H
#define QVALUELIST_H

#ifndef QT_H
#include "qtl.h"
#include "qshared.h"
#include "qdatastream.h"
#endif // QT_H

#ifndef QT_NO_STL
#include <iterator>
#include <list>
#endif

//#define QT_CHECK_VALUELIST_RANGE

#if defined(Q_CC_MSVC)
#pragma warning(disable:4284) // "return type for operator -> is not a UDT"
#endif

template <class T>
class QValueListNode
{
public:
    QValueListNode( const T& t ) : data( t ) { }
    QValueListNode() { }
#if defined(Q_TEMPLATEDLL)
    // Workaround MS bug in memory de/allocation in DLL vs. EXE
    virtual ~QValueListNode() { }
#endif

    QValueListNode<T>* next;
    QValueListNode<T>* prev;
    T data;
};

template<class T>
class QValueListIterator
{
 public:
    /**
     * Typedefs
     */
    typedef QValueListNode<T>* NodePtr;
#ifndef QT_NO_STL
    typedef std::bidirectional_iterator_tag  iterator_category;
#endif
    typedef T        value_type;
    typedef size_t size_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif
    typedef T*   pointer;
    typedef T& reference;

    /**
     * Variables
     */
    NodePtr node;

    /**
     * Functions
     */
    QValueListIterator() : node( 0 ) {}
    QValueListIterator( NodePtr p ) : node( p ) {}
    QValueListIterator( const QValueListIterator<T>& it ) : node( it.node ) {}

    bool operator==( const QValueListIterator<T>& it ) const { return node == it.node; }
    bool operator!=( const QValueListIterator<T>& it ) const { return node != it.node; }
    const T& operator*() const { return node->data; }
    T& operator*() { return node->data; }
    // UDT for T = x*
    // T* operator->() const { return &node->data; }

    QValueListIterator<T>& operator++() {
    node = node->next;
    return *this;
    }

    QValueListIterator<T> operator++(int) {
    QValueListIterator<T> tmp = *this;
    node = node->next;
    return tmp;
    }

    QValueListIterator<T>& operator--() {
    node = node->prev;
    return *this;
    }

    QValueListIterator<T> operator--(int) {
    QValueListIterator<T> tmp = *this;
    node = node->prev;
    return tmp;
    }
};

template<class T>
class QValueListConstIterator
{
 public:
    /**
     * Typedefs
     */
    typedef QValueListNode<T>* NodePtr;
#ifndef QT_NO_STL
    typedef std::bidirectional_iterator_tag  iterator_category;
#endif
    typedef T        value_type;
    typedef size_t size_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif
    typedef const T*   pointer;
    typedef const T& reference;

    /**
     * Variables
     */
    NodePtr node;

    /**
     * Functions
     */
    QValueListConstIterator() : node( 0 ) {}
    QValueListConstIterator( NodePtr p ) : node( p ) {}
    QValueListConstIterator( const QValueListConstIterator<T>& it ) : node( it.node ) {}
    QValueListConstIterator( const QValueListIterator<T>& it ) : node( it.node ) {}

    bool operator==( const QValueListConstIterator<T>& it ) const { return node == it.node; }
    bool operator!=( const QValueListConstIterator<T>& it ) const { return node != it.node; }
    const T& operator*() const { return node->data; }
    // UDT for T = x*
    // const T* operator->() const { return &node->data; }

    QValueListConstIterator<T>& operator++() {
    node = node->next;
    return *this;
    }

    QValueListConstIterator<T> operator++(int) {
    QValueListConstIterator<T> tmp = *this;
    node = node->next;
    return tmp;
    }

    QValueListConstIterator<T>& operator--() {
    node = node->prev;
    return *this;
    }

    QValueListConstIterator<T> operator--(int) {
    QValueListConstIterator<T> tmp = *this;
    node = node->prev;
    return tmp;
    }
};

template <class T>
class QValueListPrivate
    : public QShared
{
public:
    /**
     * Typedefs
     */
    typedef QValueListIterator<T> Iterator;
    typedef QValueListConstIterator<T> ConstIterator;
    typedef QValueListNode<T> Node;
    typedef QValueListNode<T>* NodePtr;
    typedef size_t size_type;

    /**
     * Functions
     */
    QValueListPrivate();
    QValueListPrivate( const QValueListPrivate<T>& _p );

    void derefAndDelete() // ### hack to get around hp-cc brain damage
    {
    if ( deref() )
        delete this;
    }

#if defined(Q_TEMPLATEDLL)
    // Workaround MS bug in memory de/allocation in DLL vs. EXE
    virtual
#endif
    ~QValueListPrivate();

    Iterator insert( Iterator it, const T& x );
    Iterator remove( Iterator it );
    NodePtr find( NodePtr start, const T& x ) const;
    int findIndex( NodePtr start, const T& x ) const;
    uint contains( const T& x ) const;
    uint remove( const T& x );
    NodePtr at( size_type i ) const;
    void clear();

    NodePtr node;
    size_type nodes;
};

template <class T>
Q_INLINE_TEMPLATES QValueListPrivate<T>::QValueListPrivate()
{
    node = new Node; node->next = node->prev = node; nodes = 0;
}

template <class T>
Q_INLINE_TEMPLATES QValueListPrivate<T>::QValueListPrivate( const QValueListPrivate<T>& _p )
    : QShared()
{
    node = new Node; node->next = node->prev = node; nodes = 0;
    Iterator b( _p.node->next );
    Iterator e( _p.node );
    Iterator i( node );
    while( b != e )
    insert( i, *b++ );
}

template <class T>
Q_INLINE_TEMPLATES QValueListPrivate<T>::~QValueListPrivate() {
    NodePtr p = node->next;
    while( p != node ) {
    NodePtr x = p->next;
    delete p;
    p = x;
    }
    delete node;
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueListPrivate<T>::Iterator QValueListPrivate<T>::insert( Q_TYPENAME QValueListPrivate<T>::Iterator it, const T& x )
{
    NodePtr p = new Node( x );
    p->next = it.node;
    p->prev = it.node->prev;
    it.node->prev->next = p;
    it.node->prev = p;
    nodes++;
    return p;
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueListPrivate<T>::Iterator QValueListPrivate<T>::remove( Q_TYPENAME QValueListPrivate<T>::Iterator it )
{
    Q_ASSERT ( it.node != node );
    NodePtr next = it.node->next;
    NodePtr prev = it.node->prev;
    prev->next = next;
    next->prev = prev;
    delete it.node;
    nodes--;
    return Iterator( next );
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueListPrivate<T>::NodePtr QValueListPrivate<T>::find( Q_TYPENAME QValueListPrivate<T>::NodePtr start, const T& x ) const
{
    ConstIterator first( start );
    ConstIterator last( node );
    while( first != last) {
    if ( *first == x )
        return first.node;
    ++first;
    }
    return last.node;
}

template <class T>
Q_INLINE_TEMPLATES int QValueListPrivate<T>::findIndex( Q_TYPENAME QValueListPrivate<T>::NodePtr start, const T& x ) const
{
    ConstIterator first( start );
    ConstIterator last( node );
    int pos = 0;
    while( first != last) {
    if ( *first == x )
        return pos;
    ++first;
    ++pos;
    }
    return -1;
}

template <class T>
Q_INLINE_TEMPLATES uint QValueListPrivate<T>::contains( const T& x ) const
{
    uint result = 0;
    Iterator first = Iterator( node->next );
    Iterator last = Iterator( node );
    while( first != last) {
    if ( *first == x )
        ++result;
    ++first;
    }
    return result;
}

template <class T>
Q_INLINE_TEMPLATES uint QValueListPrivate<T>::remove( const T& x )
{
    uint result = 0;
    Iterator first = Iterator( node->next );
    Iterator last = Iterator( node );
    while( first != last) {
    if ( *first == x ) {
        first = remove( first );
        ++result;
    } else
        ++first;
    }
    return result;
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueListPrivate<T>::NodePtr QValueListPrivate<T>::at( size_type i ) const
{
    Q_ASSERT( i <= nodes );
    NodePtr p = node->next;
    for( size_type x = 0; x < i; ++x )
    p = p->next;
    return p;
}

template <class T>
Q_INLINE_TEMPLATES void QValueListPrivate<T>::clear()
{
    nodes = 0;
    NodePtr p = node->next;
    while( p != node ) {
    NodePtr next = p->next;
    delete p;
    p = next;
    }
    node->next = node->prev = node;
}

#ifdef QT_CHECK_RANGE
# if !defined( QT_NO_DEBUG ) && defined( QT_CHECK_VALUELIST_RANGE )
#  define QT_CHECK_INVALID_LIST_ELEMENT if ( empty() ) qWarning( "QValueList: Warning invalid element" )
#  define QT_CHECK_INVALID_LIST_ELEMENT_FATAL Q_ASSERT( !empty() );
# else
#  define QT_CHECK_INVALID_LIST_ELEMENT
#  define QT_CHECK_INVALID_LIST_ELEMENT_FATAL
# endif
#else
# define QT_CHECK_INVALID_LIST_ELEMENT
# define QT_CHECK_INVALID_LIST_ELEMENT_FATAL
#endif

template <class T>
class QValueList
{
public:
    /**
     * Typedefs
     */
    typedef QValueListIterator<T> iterator;
    typedef QValueListConstIterator<T> const_iterator;
    typedef T value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef size_t size_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif

    /**
     * API
     */
    QValueList() { sh = new QValueListPrivate<T>; }
    QValueList( const QValueList<T>& l ) { sh = l.sh; sh->ref(); }
#ifndef QT_NO_STL
    QValueList( const Q_TYPENAME std::list<T>& l )
    {
    sh = new QValueListPrivate<T>;
    qCopy( l.begin(), l.end(), std::back_inserter( *this ) );
    }
#endif
    ~QValueList() { sh->derefAndDelete(); }

    QValueList<T>& operator= ( const QValueList<T>& l )
    {
    l.sh->ref();
    sh->derefAndDelete();
    sh = l.sh;
    return *this;
    }
#ifndef QT_NO_STL
    QValueList<T>& operator= ( const Q_TYPENAME std::list<T>& l )
    {
    detach();
    qCopy( l.begin(), l.end(), std::back_inserter( *this ) );
    return *this;
    }
    bool operator== ( const Q_TYPENAME std::list<T>& l ) const
    {
    if ( size() != l.size() )
        return FALSE;
    const_iterator it2 = begin();
#if !defined(Q_CC_MIPS)
    typename
#endif
    std::list<T>::const_iterator it = l.begin();
    for ( ; it2 != end(); ++it2, ++it )
    if ( !((*it2) == (*it)) )
        return FALSE;
    return TRUE;
    }
#endif
    bool operator== ( const QValueList<T>& l ) const;
    bool operator!= ( const QValueList<T>& l ) const { return !( *this == l ); }
    iterator begin() { detach(); return iterator( sh->node->next ); }
    const_iterator begin() const { return const_iterator( sh->node->next ); }
    iterator end() { detach(); return iterator( sh->node ); }
    const_iterator end() const { return const_iterator( sh->node ); }
    iterator insert( iterator it, const T& x ) { detach(); return sh->insert( it, x ); }
    uint remove( const T& x ) { detach(); return sh->remove( x ); }
    void clear();

    QValueList<T>& operator<< ( const T& x )
    {
    append( x );
    return *this;
    }

    size_type size() const { return sh->nodes; }
    bool empty() const { return sh->nodes == 0; }
    void push_front( const T& x ) { detach(); sh->insert( begin(), x ); }
    void push_back( const T& x ) { detach(); sh->insert( end(), x ); }
    iterator erase( iterator pos ) { detach(); return sh->remove( pos ); }
    iterator erase( iterator first, iterator last );
    reference front() { QT_CHECK_INVALID_LIST_ELEMENT_FATAL; return *begin(); }
    const_reference front() const { QT_CHECK_INVALID_LIST_ELEMENT_FATAL; return *begin(); }
    reference back() { QT_CHECK_INVALID_LIST_ELEMENT_FATAL; return *(--end()); }
    const_reference back() const { QT_CHECK_INVALID_LIST_ELEMENT_FATAL; return *(--end()); }
    void pop_front() { QT_CHECK_INVALID_LIST_ELEMENT; erase( begin() ); }
    void pop_back() {
    QT_CHECK_INVALID_LIST_ELEMENT;
    iterator tmp = end();
    erase( --tmp );
    }
    void insert( iterator pos, size_type n, const T& x );
    // Some compilers (incl. vc++) would instantiate this function even if
    // it is not used; this would constrain QValueList to classes that provide
    // an operator<
    /*
    void sort()
    {
    qHeapSort( *this );
    }
    */

    QValueList<T> operator+ ( const QValueList<T>& l ) const;
    QValueList<T>& operator+= ( const QValueList<T>& l );

    iterator fromLast() { detach(); return iterator( sh->node->prev ); }
    const_iterator fromLast() const { return const_iterator( sh->node->prev ); }

    bool isEmpty() const { return ( sh->nodes == 0 ); }

    iterator append( const T& x ) { detach(); return sh->insert( end(), x ); }
    iterator prepend( const T& x ) { detach(); return sh->insert( begin(), x ); }

    iterator remove( iterator it ) { detach(); return sh->remove( it ); }

    T& first() { QT_CHECK_INVALID_LIST_ELEMENT; detach(); return sh->node->next->data; }
    const T& first() const { QT_CHECK_INVALID_LIST_ELEMENT; return sh->node->next->data; }
    T& last() { QT_CHECK_INVALID_LIST_ELEMENT; detach(); return sh->node->prev->data; }
    const T& last() const { QT_CHECK_INVALID_LIST_ELEMENT; return sh->node->prev->data; }

    T& operator[] ( size_type i ) { QT_CHECK_INVALID_LIST_ELEMENT; detach(); return sh->at(i)->data; }
    const T& operator[] ( size_type i ) const { QT_CHECK_INVALID_LIST_ELEMENT; return sh->at(i)->data; }
    iterator at( size_type i ) { QT_CHECK_INVALID_LIST_ELEMENT; detach(); return iterator( sh->at(i) ); }
    const_iterator at( size_type i ) const { QT_CHECK_INVALID_LIST_ELEMENT; return const_iterator( sh->at(i) ); }
    iterator find ( const T& x ) { detach(); return iterator( sh->find( sh->node->next, x) ); }
    const_iterator find ( const T& x ) const { return const_iterator( sh->find( sh->node->next, x) ); }
    iterator find ( iterator it, const T& x ) { detach(); return iterator( sh->find( it.node, x ) ); }
    const_iterator find ( const_iterator it, const T& x ) const { return const_iterator( sh->find( it.node, x ) ); }
    int findIndex( const T& x ) const { return sh->findIndex( sh->node->next, x) ; }
    size_type contains( const T& x ) const { return sh->contains( x ); }

    size_type count() const { return sh->nodes; }

    QValueList<T>& operator+= ( const T& x )
    {
    append( x );
    return *this;
    }
    typedef QValueListIterator<T> Iterator;
    typedef QValueListConstIterator<T> ConstIterator;
    typedef T ValueType;

protected:
    /**
     * Helpers
     */
    void detach() { if ( sh->count > 1 ) detachInternal(); }

    /**
     * Variables
     */
    QValueListPrivate<T>* sh;

private:
    void detachInternal();
};

template <class T>
Q_INLINE_TEMPLATES bool QValueList<T>::operator== ( const QValueList<T>& l ) const
{
    if ( size() != l.size() )
    return FALSE;
    const_iterator it2 = begin();
    const_iterator it = l.begin();
    for( ; it != l.end(); ++it, ++it2 )
    if ( !( *it == *it2 ) )
        return FALSE;
    return TRUE;
}

template <class T>
Q_INLINE_TEMPLATES void QValueList<T>::clear()
{
    if ( sh->count == 1 ) sh->clear(); else { sh->deref(); sh = new QValueListPrivate<T>; }
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueList<T>::iterator QValueList<T>::erase( Q_TYPENAME QValueList<T>::iterator first, Q_TYPENAME QValueList<T>::iterator last )
{
    while ( first != last )
    erase( first++ );
    return last;
}

template <class T>
Q_INLINE_TEMPLATES void QValueList<T>::insert( Q_TYPENAME QValueList<T>::iterator pos, size_type n, const T& x )
{
    for ( ; n > 0; --n )
    insert( pos, x );
}

template <class T>
Q_INLINE_TEMPLATES QValueList<T> QValueList<T>::operator+ ( const QValueList<T>& l ) const
{
    QValueList<T> l2( *this );
    for( const_iterator it = l.begin(); it != l.end(); ++it )
    l2.append( *it );
    return l2;
}

template <class T>
Q_INLINE_TEMPLATES QValueList<T>& QValueList<T>::operator+= ( const QValueList<T>& l )
{
    for( const_iterator it = l.begin(); it != l.end(); ++it )
    append( *it );
    return *this;
}

template <class T>
Q_INLINE_TEMPLATES void QValueList<T>::detachInternal()
{
    sh->deref(); sh = new QValueListPrivate<T>( *sh );
}

#ifndef QT_NO_DATASTREAM
template <class T>
Q_INLINE_TEMPLATES QDataStream& operator>>( QDataStream& s, QValueList<T>& l )
{
    l.clear();
    Q_UINT32 c;
    s >> c;
    for( Q_UINT32 i = 0; i < c; ++i )
    {
    T t;
    s >> t;
    l.append( t );
    if ( s.atEnd() )
        break;
    }
    return s;
}

template <class T>
Q_INLINE_TEMPLATES QDataStream& operator<<( QDataStream& s, const QValueList<T>& l )
{
    s << (Q_UINT32)l.size();
    QValueListConstIterator<T> it = l.begin();
    for( ; it != l.end(); ++it )
    s << *it;
    return s;
}
#endif // QT_NO_DATASTREAM
#endif // QVALUELIST_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueList成员列表

完整的QValueList成员列表

这里是QValueList成员函数的完整列表，包括继承的成员。

  • QValueList()
  • ~QValueList()
  • append()
  • at()
  • back()
  • begin()
  • clear()
  • contains()
  • count()
  • empty()
  • end()
  • erase()
  • find()
  • findIndex()
  • first()
  • fromLast()
  • front()
  • insert()
  • isEmpty()
  • last()
  • operator!=()
  • operator+()
  • operator+=()
  • operator<<()
  • operator=()
  • operator==()
  • operator[]()
  • pop_back()
  • pop_front()
  • prepend()
  • push_back()
  • push_front()
  • remove()
  • size()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueListConstIterator类

QValueListConstIterator类参考

QValueListConstIterator类提供了QValueList的常量迭代器。 详情请见……

#include <qvaluelist.h>

所有成员函数的列表。

公有成员

  • typedef T value_type
  • typedef const T * pointer
  • typedef const T & reference
  • QValueListConstIterator ()
  • QValueListConstIterator ( const QValueListConstIterator<T> & it )
  • QValueListConstIterator ( const QValueListIterator<T> & it )
  • bool operator== ( const QValueListConstIterator<T> & it ) const
  • bool operator!= ( const QValueListConstIterator<T> & it ) const
  • const T & operator* () const
  • QValueListConstIterator<T> & operator++ ()
  • QValueListConstIterator<T> operator++ ( int )
  • QValueListConstIterator<T> & operator-- ()
  • QValueListConstIterator<T> operator-- ( int )

详细描述

QValueListConstIterator类提供了QValueList的常量迭代器。

和QValueListIterator形成对比，这个类是用来遍历一个常量列表的。它不允许对列表中的值进行修改，因为这将会破坏常量的语义。

你可以通过使用QValueList中定义的const_iterator来创建合适的常量迭代器类型。

关于QValueList的迭代器更多的信息，请参考QValueListIterator。

也可以参考QValueListIterator、a href="qvaluelist.html">QValueList、Qt模板库类和非GUI类。

成员类型文档

QValueListConstIterator::pointer

值类型的指针。

QValueListConstIterator::reference

值类型的引用。

QValueListConstIterator::value_type

值的类型，T。

成员函数文档

QValueListConstIterator::QValueListConstIterator ()

创建未定义的迭代器。

QValueListConstIterator::QValueListConstIterator ( const QValueListConstIterator<T> & it )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

构造一个迭代器it的复制。

QValueListConstIterator::QValueListConstIterator ( const QValueListIterator<T> & it )

构造一个迭代器it的复制。

bool QValueListConstIterator::operator!= ( const QValueListConstIterator<T> & it ) const

比较这个迭代器和it并且如果它们指向不同的项，返回真，否则返回假。

const T & QValueListConstIterator::operator* () const

星号操作符。返回当前迭代器项的引用。

QValueListConstIterator<T> & QValueListConstIterator::operator++ ()

前置++让当前项后的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表末尾。增加这个迭代器就会返回end()导致未定义的结果。

QValueListConstIterator<T> QValueListConstIterator::operator++ ( int )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

后置++让当前项后的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表末尾。增加这个迭代器就会返回end()导致未定义的结果。

QValueListConstIterator<T> & QValueListConstIterator::operator-- ()

前置--让当前项前的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表开始。增加这个迭代器就会返回begin()导致未定义的结果。

QValueListConstIterator<T> QValueListConstIterator::operator-- ( int )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

后置--让当前项前的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表开始。增加这个迭代器就会返回begin()导致未定义的结果。

bool QValueListConstIterator::operator== ( const QValueListConstIterator<T> & it ) const

比较这个迭代器和it并且如果它们指向相同的项，返回真，否则返回假。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueListConstIterator成员列表

完整的QValueListConstIterator成员列表

这里是QValueListConstIterator成员函数的完整列表，包括继承的成员。

  • QValueListConstIterator()
  • operator!=()
  • operator*()
  • operator++()
  • operator--()
  • operator==()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueListIterator类

QValueListIterator类参考

QValueListIterator类提供了QValueList的迭代器。 详情请见……

#include <qvaluelist.h>

所有成员函数的列表。

公有成员s

  • typedef T value_type
  • typedef T * pointer
  • typedef T & reference
  • QValueListIterator ()
  • QValueListIterator ( const QValueListIterator<T> & it )
  • bool operator== ( const QValueListIterator<T> & it ) const
  • bool operator!= ( const QValueListIterator<T> & it ) const
  • const T & operator* () const
  • T & operator* ()
  • QValueListIterator<T> & operator++ ()
  • QValueListIterator<T> operator++ ( int )
  • QValueListIterator<T> & operator-- ()
  • QValueListIterator<T> operator-- ( int )

详细描述

QValueListIterator类提供了QValueList的迭代器。

迭代器就是一个可以访问容器类项的类——就是数组中索引的广义化。一个指针“const char *”和一个索引“int[]”都是迭代器，并且这个通用的思想就是为任何数据结构都提供这样的功能。

QValueListIterator类是QValueList实例的迭代器。你可以通过使用QValueList中定义的iterator来创建合适的迭代器类型。

在QValueList中唯一可以用来访问项的方法就是使用迭代器。

实例（全部代码可以参考QValueList）：

    EmployeeList::iterator it;
    for ( it = list.begin(); it != list.end(); ++it )
        cout << (*it).surname().latin1() << ", " <<
                (*it).forename().latin1() << " earns " <<
                (*it).salary() << endl;

    // 输出：
    // Doe, John earns 50000
    // Williams, Jane earns 80000
    // Hawthorne, Mary earns 90000
    // Jones, Tom earns 60000

QValueList对性能和内存使用已经高度优化了。这也就是说，你必须谨慎使用，QValueList不知道所有关于它的迭代器并且迭代器也不知道它们属于哪一个列表。这使得事情变得很快，但是如果你不注意，你就会得到壮观的bug。在引用迭代器或者使用它们作为STL或者QTL中的通用算法的参数时，请确认它们是有效的。

使用未定义的迭代器是未定义的（你的程序也许将会崩溃）。很多Qt函数返回常量值列表，要遍历它们，你应该复制之后再遍历它们的副本。

对于每一个Iterator都有一个ConstIterator。当在一个常量环境中访问QValueList或者如果列表的引用或指针本身是一个常量，那么你就必须使用ConstIterator。它的语义和Iterator一样，但是它返回的是常量引用。

也可以参考QValueList、QValueListConstIterator、Qt模板库类和非GUI类。

成员类型文档

QValueListIterator::pointer

值类型的指针。

QValueListIterator::reference

值类型的引用。

QValueListIterator::value_type

值的类型，T。

成员函数文档

QValueListIterator::QValueListIterator ()

创建未定义的迭代器。

QValueListIterator::QValueListIterator ( const QValueListIterator<T> & it )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

构造一个迭代器it的复制。

bool QValueListIterator::operator!= ( const QValueListIterator<T> & it ) const

比较这个迭代器和it并且如果它们指向不同的项，返回真，否则返回假。

T & QValueListIterator::operator* ()

星号操作符。返回当前迭代器项的引用。

const T & QValueListIterator::operator* () const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

星号操作符。返回当前迭代器项的引用。

QValueListIterator<T> & QValueListIterator::operator++ ()

前置++让当前项后的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表末尾。增加这个迭代器就会返回end()导致未定义的结果。

QValueListIterator<T> QValueListIterator::operator++ ( int )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

后置++让当前项后的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表末尾。增加这个迭代器就会返回end()导致未定义的结果。

QValueListIterator<T> & QValueListIterator::operator-- ()

前置--让当前项前的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表开始。增加这个迭代器就会返回begin()导致未定义的结果。

QValueListIterator<T> QValueListIterator::operator-- ( int )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

后置--让当前项前的一项变为当前向并且返回原来的当前项。迭代器不能检测它是否到达了列表开始。增加这个迭代器就会返回begin()导致未定义的结果。

bool QValueListIterator::operator== ( const QValueListIterator<T> & it ) const

比较这个迭代器和it并且如果它们指向相同的项，返回真，否则返回假。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueListIterator成员列表

完整的QValueListIterator成员列表

这里是QValueListIterator成员函数的完整列表，包括继承的成员。

  • QValueListIterator()
  • operator!=()
  • operator*()
  • operator++()
  • operator--()
  • operator==()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QValueStack Class

QValueStack Class Reference

The QValueStack class is a value-based template class that provides a stack. More...

#include <qvaluestack.h>

Inherits QValueList<T>.

List of all member functions.

Public Members

  • QValueStack ()
  • ~QValueStack ()
  • void push ( const T & d )
  • T pop ()
  • T & top ()
  • const T & top () const

Detailed Description

The QValueStack class is a value-based template class that provides a stack.

Define a template instance QValueStack<X> to create a stack of values that all have the class X. QValueStack is part of the Qt Template Library.

Note that QValueStack does not store pointers to the members of the stack; it holds a copy of every member. That is why these kinds of classes are called "value based"; QPtrStack, QPtrList, and QDict are "reference based".

A stack is a last in, first ut (LIFO) structure. Items are added to the top of the stack with push() and retrieved from the top with pop(). Furthermore, top() provides access to the topmost item without removing it.

Example:

    QValueStack<int> stack;
    stack.push( 1 );
    stack.push( 2 );
    stack.push( 3 );
    while ( ! stack.isEmpty() )
        cout << "Item: " << stack.pop() << endl;

    // Output:
    //  Item: 3
    //  Item: 2
    //  Item: 1

QValueStack is a specialized QValueList provided for convenience. All of QValueList's functionality also applies to QPtrStack, for example the facility to iterate over all elements using QValueStack::Iterator. See QValueListIterator for further details.

Some classes cannot be used within a QValueStack, for example everything derived from QObject and thus all classes that implement widgets. Only values can be used in a QValueStack. To qualify as a value, the class must provide

  • A copy constructor
  • An assignment operator
  • A default constructor, i.e. a constructor that does not take any arguments.

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient.

See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

Member Function Documentation

QValueStack::QValueStack ()

Constructs an empty stack.

QValueStack::~QValueStack ()

Destroys the stack. References to the values in the stack and all iterators of this stack become invalidated. Because QValueStack is highly tuned for performance, you won't see warnings if you use invalid iterators because it is impossible for an iterator to check whether or not it is valid.

T QValueStack::pop ()

Removes the top item from the stack and returns it.

See also top() and push().

void QValueStack::push ( const T & d )

Adds element, d, to the top of the stack. Last in, first out.

This function is equivalent to append().

See also pop() and top().

T & QValueStack::top ()

Returns a reference to the top item of the stack or the item referenced by end() if no such item exists. Note that you must not change the value the end() iterator points to.

This function is equivalent to last().

See also pop(), push() and QValueList::fromLast().

const T & QValueStack::top () const

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

Returns a reference to the top item of the stack or the item referenced by end() if no such item exists.

This function is equivalent to last().

See also pop(), push() and QValueList::fromLast().

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


qvaluestack.h Include File

qvaluestack.h

This is the verbatim text of the qvaluestack.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qvaluestack.h   3.0.5   edited May 29 15:00 $
**
** Definition of QValueStack class
**
** Created : 990925
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVALUESTACK_H
#define QVALUESTACK_H

#ifndef QT_H
#include "qvaluelist.h"
#endif // QT_H

template<class T>
class QValueStack
    : public QValueList<T>
{
public:
    QValueStack() {}
   ~QValueStack() {}
    void  push( const T& d ) { append(d); }
    T pop()
    {
    T elem( this->last() );
    if ( !this->isEmpty() )
        remove( this->fromLast() );
    return elem;
    }
    T& top() { return this->last(); }
    const T& top() const { return this->last(); }
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QValueStack Member List

Complete Member List for QValueStack

This is the complete list of member functions for QValueStack, including inherited members.

  • QValueStack()
  • ~QValueStack()
  • append()
  • at()
  • back()
  • begin()
  • clear()
  • contains()
  • count()
  • empty()
  • end()
  • erase()
  • find()
  • findIndex()
  • first()
  • fromLast()
  • front()
  • insert()
  • isEmpty()
  • last()
  • operator!=()
  • operator+()
  • operator+=()
  • operator<<()
  • operator=()
  • operator==()
  • operator[]()
  • pop()
  • pop_back()
  • pop_front()
  • prepend()
  • push()
  • push_back()
  • push_front()
  • remove()
  • size()
  • top()


QValueVector Class

QValueVector Class Reference

The QValueVector class is a value-based template class that provides a dynamic array. More...

#include <qvaluevector.h>

List of all member functions.

Public Members

  • typedef T value_type
  • typedef value_type * pointer
  • typedef const value_type * const_pointer
  • typedef value_type * iterator
  • typedef const value_type * const_iterator
  • typedef value_type & reference
  • typedef const value_type & const_reference
  • typedef size_t size_type
  • typedef ptrdiff_t difference_type
  • QValueVector ()
  • QValueVector ( const QValueVector<T> & v )
  • QValueVector ( size_type n, const T & val = T ( ) )
  • QValueVector ( std::vector<T> & v )
  • ~QValueVector ()
  • QValueVector<T> & operator= ( const QValueVector<T> & v )
  • QValueVector<T> & operator= ( const std::vector<T> & v )
  • size_type size () const
  • bool empty () const
  • size_type capacity () const
  • iterator begin ()
  • const_iterator begin () const
  • iterator end ()
  • const_iterator end () const
  • reference at ( size_type i, bool * ok = 0 )
  • const_reference at ( size_type i, bool * ok = 0 ) const
  • reference operator[] ( size_type i )
  • const_reference operator[] ( size_type i ) const
  • reference front ()
  • const_reference front () const
  • reference back ()
  • const_reference back () const
  • void push_back ( const T & x )
  • void pop_back ()
  • iterator insert ( iterator pos, const T & x )
  • iterator insert ( iterator pos, size_type n, const T & x )
  • void reserve ( size_type n )
  • void resize ( size_type n, const T & val = T ( ) )
  • void clear ()
  • iterator erase ( iterator pos )
  • iterator erase ( iterator first, iterator last )
  • bool operator== ( const QValueVector<T> & x )
  • bool operator== ( const QValueVector<T> & x ) const

Protected Members

  • void detach ()

Detailed Description

The QValueVector class is a value-based template class that provides a dynamic array.

QValueVector is a Qt implementation of an STL-like vector container. It can be used in your application if the standard vector is not available. QValueVector is part of the Qt Template Library.

QValueVector<T> defines a template instance to create a vector of values that all have the class T. Please note that QValueVector does not store pointers to the members of the vector; it holds a copy of every member. QValueVector is said to be value based; in contrast, QPtrList and QDict are pointer based.

QValueVector contains and manages a collection of objects of type T and provides random access iterators that allow the contained objects to be addressed. QValueVector owns the contained elements. For more relaxed ownership semantics, see QPtrCollection and friends which are pointer-based containers.

QValueVector provides good performance if you append or remove elements from the end of the vector. If you insert or remove elements from anywhere but the end, performance is very bad. The reason for this is that elements will need to be copied into new positions.

Some classes cannot be used within a QValueVector - for example, all classes derived from QObject and thus all classes that implement widgets. Only values can be used in a QValueVector. To qualify as a value the class must provide:

  • A copy constructor
  • An assignment operator
  • A default constructor, i.e., a constructor that does not take any arguments.

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient.

QValueVector uses an STL-like syntax to manipulate and address the objects it contains. See this document for more information.

Example:

    #include <qvaluevector.h>
    #include <qstring.h>
    #include <stdio.h>

    class Employee
    {
    public:
        Employee(): s(0) {}
        Employee( const QString& name, int salary )
            : n(name), s(salary)
        {}

        QString     name()   const              { return n; }
        int         salary() const              { return s; }
        void        setSalary( int salary )     { s = salary; }
    private:
        QString     n;
        int         s;
    };

    int main()
    {
        typedef QValueVector<Employee> EmployeeVector;
        EmployeeVector vec( 4 );        // vector of 4 Employees

        vec[0] = Employee("Bill", 50000);
        vec[1] = Employee("Steve",80000);
        vec[2] = Employee("Ron",  60000);

        Employee joe( "Joe", 50000 );
        vec.push_back( joe );
        joe.setSalary( 4000 );

        EmployeeVector::iterator it;
        for( it = vec.begin(); it != vec.end(); ++it )
            printf( "%s earns %d\n", (*it).name().latin1(), (*it).salary() );

        return 0;
    }

Program output:

        Bill earns 50000
        Steve earns 80000
        Ron earns 60000
        Joe earns 50000

As you can see, the latest changes to Joe's salary did not affect the value in the vector because the vector created a copy of Joe's entry.

Many Qt functions return const value vectors; to iterate over these you should make a copy and iterate over the copy.

There are several ways to find items in the vector. The begin() and end() functions return iterators to the beginning and end of the vector. The advantage of getting an iterator is that you can now move forward or backward from this position by incrementing/decrementing the iterator. The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the vector it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value. If the vector is empty(), the iterator returned by begin() will equal the iterator returned by end().

The fastest way to access an element of a vector is by using operator[]. This function provides random access and will return a reference to the element located at the specified index. Thus, you can access every element directly, in constant time, providing you know the location of the element. It is undefined to access an element that does not exist (your application will probably crash). For example:

  QValueVector<int> vec1;  // an empty vector
  vec1[10] = 4;  // WARNING: undefined, probably a crash

  QValueVector<QString> vec2(25); // initialize with 25 elements
  vec2[10] = "Dave";  // OK

Whenever inserting, removing or referencing elements in a vector, always make sure you are referring to valid positions. For example:

  void func( QValueVector<int>& vec )
  {
      if ( vec.size() > 10 ) {
          vec[9] = 99; // OK
      }
  };

The iterators provided by vector are random access iterators, therefore you can use them with many generic algorithms, for example, algorithms provided by the STL or the QTL.

Another way to find an element in the vector is by using the std::find() or qFind() algorithms. For example:

  QValueVector<int> vec;
  ...
  QValueVector<int>::const_iterator it = qFind( vec.begin(), vec.end(), 3 );
  if ( it != vector.end() )
      // 'it' points to the found element

It is safe to have multiple iterators on the vector at the same time. Since QValueVector manages memory dynamically, all iterators can become invalid if a memory reallocation occurs. For example, if some member of the vector is removed, iterators that point to the removed element and to all following elements become invalidated. Inserting into the middle of the vector will invalidate all iterators. For convenience, the function back() returns a reference to the last element in the vector, and front() one for the first. If the vector is empty(), both back() and front() have undefined behavior (your application will crash or do unpredictable things). Use back() and front() with caution, for example:

  QValueVector<int> vec( 3 );
  vec.push_back( 1 );
  vec.push_back( 2 );
  vec.push_back( 3 );
  ...
  if ( !vec.empty() ) {
      // OK: modify the first element
      int& i = vec.front();
      i = 18;
  }
  ...
  QValueVector<double> dvec;
  double d = dvec.back(); // undefined behavior

Because QValueVector manages memory dynamically, it is recommended to contruct a vector with an initial size. Inserting and removing elements happens fastest when:

  • Inserting or removing elements happens at the end() of the vector
  • The vector does not need to allocate additional memory

By creating a QValueVector with a sufficiently large initial size, there will be less memory allocations. Do not use an initial size that is too big, since it will still take time to construct all the empty entries, and the extra space may be wasted if it is never used.

Because QValueVector is value-based there is no need to be careful about deleting elements in the vector. The vector holds its own copies and will free them if the corresponding member or the vector itself is deleted. You can force the vector to free all of its items with clear().

QValueVector is shared implicitly, which means it can be copied in constant time. If multiple QValueVector instances share the same data and one needs to modify its contents, this modifying instance makes a copy and modifies its private copy; it thus does not affect the other instances. This is often called "copy on write". If a QValueVector is being used in a multi-threaded program, you must protect all access to the vector. See QMutex.

There are several ways to insert elements into the vector. The push_back() function insert elements into the end of the vector. The insert() can be used to add elements at specific positions within the vector (normally, inserting elements at the end() of the vector is fastest).

Items can be also be removed from the vector in several ways. There are several variants of the erase() function which removes a specific element, or range of elements, from the vector.

Vectors can be also sorted with various STL algorithms , or it can be sorted using the Qt Template Library. For example with qBubbleSort():

Example:

    QValueVector<int> v( 4 );
    v.push_back( 5 );
    v.push_back( 8 );
    v.push_back( 3 );
    v.push_back( 4 );
    qBubbleSort( v );

QValueVector stores its elements in contiguous memory. This means that you can use a QValueVector in any situation that requires an array.

See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

Member Type Documentation

QValueVector::const_iterator

The vector's const iterator type.

QValueVector::const_pointer

The const pointer to T type.

QValueVector::const_reference

The const reference to T type.

QValueVector::difference_type

A signed integral type used to represent the distance between two iterators.

QValueVector::iterator

The vector's iterator type.

QValueVector::pointer

The pointer to T type.

QValueVector::reference

The reference to T type.

QValueVector::size_type

An unsigned integral type, used to represent various sizes.

QValueVector::value_type

The type of the object stored in the vector.

Member Function Documentation

QValueVector::QValueVector ()

Constructs an empty vector without any elements. To create a vector which reserves an initial amount of space for elements, use QValueVector(size_type n).

QValueVector::QValueVector ( const QValueVector<T> & v )

Constructs a copy of v.

This operation costs O(1) time because QValueVector is shared implicitly.

The first modification to the vector does however take O(n) time.

QValueVector::QValueVector ( size_type n, const T & val = T ( ) )

Constructs a vector with an initial size of n elements. Each element is initialized with the value of val.

QValueVector::QValueVector ( std::vector<T> & v )

Constructs a copy of v.

This operation costs O(n) time because v is copied.

QValueVector::~QValueVector ()

Destroys the vector, destroying all elements and freeing the memory. References to the values in the vector and all iterators of this vector become invalidated. Note that it is impossible for an iterator to check whether or not it is valid - QValueVector is tuned for performance, not error checking.

reference QValueVector::at ( size_type i, bool * ok = 0 )

Returns a reference to the element with index i. If ok is non-null, and the index i is out of range, *ok is set to FALSE and the returned reference is undefined. If the index i is within the range of the vector, and ok is non-null, *ok is set to TRUE and the returned reference is well defined.

const_reference QValueVector::at ( size_type i, bool * ok = 0 ) const

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

Returns a const reference to the element with index i. If ok is non-null, and the index i is out of range, *ok is set to FALSE and the returned reference is undefined. If the index i is within the range of the vector, and ok is non-null, *ok is set to TRUE and the returned reference is well defined.

reference QValueVector::back ()

Returns a reference to the last element in the vector. If there is no last element, this function has undefined behavior.

const_reference QValueVector::back () const

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

Returns a const reference to the last element in the vector. If there is no last element, this function has undefined behavior.

iterator QValueVector::begin ()

Returns an iterator pointing to the beginning of the vector. If the vector is empty(), the returned iterator will equal end().

const_iterator QValueVector::begin () const

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

Returns a const iterator pointing to the beginning of the vector. If the vector is empty(), the returned iterator will equal end().

size_type QValueVector::capacity () const

Returns the maximum number of elements possible without memory reallocation. If memory reallocation takes place, some or all iterators may become invalidated.

void QValueVector::clear ()

Removes all elements from the vector.

void QValueVector::detach () [protected]

If the vector does not share its data with another QValueVector instance, nothing happens. Otherwise the function creates a new copy of this data and detaches from the shared one. This function is called whenever the vector is modified. The implicit sharing mechanism is implemented this way.

bool QValueVector::empty () const

Returns TRUE if the vector is empty, otherwise FALSE. Equivalent to size()==0, but is faster.

iterator QValueVector::end ()

Returns an iterator pointing behind the last element of the vector.

const_iterator QValueVector::end () const

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

Returns a const iterator pointing behind the last element of the vector.

iterator QValueVector::erase ( iterator pos )

Removes the element at position pos and returns the position of the next element.

iterator QValueVector::erase ( iterator first, iterator last )

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

Removes all elements from first up to but not including last and returns the position of the next element.

reference QValueVector::front ()

Returns a reference to the first element in the vector. If there is no first element, this function has undefined behavior.

const_reference QValueVector::front () const

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

Returns a const reference to the first element in the vector. If there is no first element, this function has undefined behavior.

iterator QValueVector::insert ( iterator pos, const T & x )

Inserts a copy of x at the position immediately before pos.

iterator QValueVector::insert ( iterator pos, size_type n, const T & x )

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

Inserts n copies of x immediately before position x.

QValueVector<T> & QValueVector::operator= ( const QValueVector<T> & v )

Assigns v to this vector and returns a reference to this vector.

All iterators of the current vector become invalidated by this operation. The cost of such an assignment is O(1) since QValueVector is implicitly shared.

QValueVector<T> & QValueVector::operator= ( const std::vector<T> & v )

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

Assigns v to this vector and returns a reference to this vector.

All iterators of the current vector become invalidated by this operation. The cost of this assignment is O(n) since v is copied.

bool QValueVector::operator== ( const QValueVector<T> & x ) const

Returns TRUE if each element in this vector equals each corresponding element in x; otherwise returns FALSE.

bool QValueVector::operator== ( const QValueVector<T> & x )

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

Returns TRUE if each element in this vector equals each corresponding element in x; otherwise returns FALSE.

reference QValueVector::operator[] ( size_type i )

Returns a reference to the element at index i. If i is out of range, this function has undefined behavior.

const_reference QValueVector::operator[] ( size_type i ) const

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

Returns a const reference to the element at index i. If i is out of range, this function has undefined behavior.

void QValueVector::pop_back ()

Removes the last element from the vector.

void QValueVector::push_back ( const T & x )

Appends a copy of x to the end of the vector.

void QValueVector::reserve ( size_type n )

Increases the vector's capacity. If n is less than or equal to capacity(), nothing happens. Otherwise, additional memory is allocated so that capacity() will be increased to a value greater than or equal to n. All iterators will then become invalidated. Note that the vector's size() and the values of existing elements remain unchanged.

void QValueVector::resize ( size_type n, const T & val = T ( ) )

Changes the size of the vector to n. If n is greater than the current size(), elements are added to the end and initialized with the value of val. If n is less than size(), elements are removed from the end. If n is equal to size() nothing happens.

size_type QValueVector::size () const

Returns the number of elements in the vector.

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


qvaluevector.h Include File

qvaluevector.h

This is the verbatim text of the qvaluevector.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
**
** Definition of QValueVector class
**
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVALUEVECTOR_H
#define QVALUEVECTOR_H

#ifndef QT_H
#include "qtl.h"
#include "qshared.h"
#include "qdatastream.h"
#endif // QT_H

#ifndef QT_NO_STL
#include <vector>
#endif

template <class T>
class QValueVectorPrivate
    : public QShared
{
public:

    typedef T value_type;
    typedef T* pointer;

    QValueVectorPrivate()
    : start( 0 ), finish( 0 ), end( 0 )
    {
    }

    QValueVectorPrivate( const QValueVectorPrivate<T>& x );
    QValueVectorPrivate( size_t size );

    void derefAndDelete() // ### hack to get around hp-cc brain damage
    {
    if ( deref() )
        delete this;
    }

#if defined(Q_TEMPLATEDLL)
    // Workaround MS bug in memory de/allocation in DLL vs. EXE
    virtual
#endif
    ~QValueVectorPrivate()
    {
    delete[] start;
    }

    size_t size() const
    {
    return finish - start;
    }

    bool empty() const
    {
    return start == finish;
    }

    size_t capacity() const
    {
    return end - start;
    }

    void insert( pointer pos, const T& x );
    void insert( pointer pos, size_t n, const T& x );
    void reserve( size_t n );

    void clear()
    {
    delete[] start;
    start = 0;
    finish = 0;
    end = 0;
    }

    pointer start;
    pointer finish;
    pointer end;

private:
    pointer growAndCopy( size_t n, pointer s, pointer f );

    QValueVectorPrivate& operator=( const QValueVectorPrivate<T>& x );

};

template <class T>
Q_INLINE_TEMPLATES QValueVectorPrivate<T>::QValueVectorPrivate( const QValueVectorPrivate<T>& x )
    : QShared()
{
    if ( x.size() > 0 ) {
    start = new T[ x.size() ];
    finish = start + x.size();
    end = start + x.size();
    qCopy( x.start, x.finish, start );
    } else {
    start = 0;
    finish = 0;
    end = 0;
    }
}

template <class T>
Q_INLINE_TEMPLATES QValueVectorPrivate<T>::QValueVectorPrivate( size_t size )
{
    if ( size > 0 ) {
    start = new T[size];
    finish = start + size;
    end = start + size;
    } else {
    start = 0;
    finish = 0;
    end = 0;
    }
}

template <class T>
Q_INLINE_TEMPLATES void QValueVectorPrivate<T>::insert( pointer pos, const T& x )
{
    const size_t lastSize = size();
    const size_t n = lastSize !=0 ? 2*lastSize : 1;
    const size_t offset = pos - start;
    pointer newStart = new T[n];
    pointer newFinish = newStart + offset;
    qCopy( start, pos, newStart );
    *newFinish = x;
    qCopy( pos, finish, ++newFinish );
    delete[] start;
    start = newStart;
    finish = newStart + lastSize + 1;
    end = newStart + n;
}

template <class T>
Q_INLINE_TEMPLATES void QValueVectorPrivate<T>::insert( pointer pos, size_t n, const T& x )
{
    if ( size_t( end - finish ) >= n ) {
    // enough room
    const size_t elems_after = finish - pos;
    pointer old_finish = finish;
    if ( elems_after > n ) {
        qCopy( finish - n, finish, finish );
        finish += n;
        qCopyBackward( pos, old_finish - n, old_finish );
        qFill( pos, pos + n, x );
    } else {
        pointer filler = finish;
        size_t i = n - elems_after;
        for ( ; i > 0; --i, ++filler )
        *filler = x;
        finish += n - elems_after;
        qCopy( pos, old_finish, finish );
        finish += elems_after;
        qFill( pos, old_finish, x );
    }
    } else {
    // not enough room
    const size_t lastSize = size();
    const size_t len = lastSize + QMAX( lastSize, n );
    pointer newStart = new T[len];
    pointer newFinish = qCopy( start, pos, newStart );
    // fill up inserted space
    size_t i = n;
    for ( ; i > 0; --i, ++newFinish )
        *newFinish = x;
    newFinish = qCopy( pos, finish, newFinish );
    delete[] start;
    start = newStart;
    finish = newFinish;
    end = newStart + len;
    }
}

template <class T>
Q_INLINE_TEMPLATES void QValueVectorPrivate<T>::reserve( size_t n )
{
    const size_t lastSize = size();
    pointer tmp = growAndCopy( n, start, finish );
    start = tmp;
    finish = tmp + lastSize;
    end = start + n;
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueVectorPrivate<T>::pointer QValueVectorPrivate<T>::growAndCopy( size_t n, pointer s, pointer f )
{
    pointer newStart = new T[n];
    qCopy( s, f, newStart );
    delete[] start;
    return newStart;
}

template <class T>
class QValueVector
{
public:
    typedef T value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type* iterator;
    typedef const value_type* const_iterator;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef size_t size_type;
#ifndef QT_NO_STL
    typedef ptrdiff_t  difference_type;
#else
    typedef int difference_type;
#endif

    QValueVector()
    {
    sh = new QValueVectorPrivate<T>;
    }

    QValueVector( const QValueVector<T>& v )
    {
    sh = v.sh;
    sh->ref();
    }

    QValueVector( size_type n, const T& val = T() );

#ifndef QT_NO_STL
    QValueVector( std::vector<T>& v )
    {
    sh = new QValueVectorPrivate<T>( v.size() );
    qCopy( v.begin(), v.end(), begin() );
    }
#endif

    ~QValueVector()
    {
    sh->derefAndDelete();
    }

    QValueVector<T>& operator= ( const QValueVector<T>& v )
    {
    v.sh->ref();
    sh->derefAndDelete();
    sh = v.sh;
    return *this;
    }

#ifndef QT_NO_STL
    QValueVector<T>& operator= ( const std::vector<T>& v )
    {
    clear();
    resize( v.size() );
    qCopy( v.begin(), v.end(), begin() );
    return *this;
    }
#endif

    size_type size() const
    {
    return sh->size();
    }

    bool empty() const
    {
    return sh->empty();
    }

    size_type capacity() const
    {
    return size_type( sh->capacity() );
    }

    iterator begin()
    {
    detach();
    return sh->start;
    }

    const_iterator begin() const
    {
    return sh->start;
    }

    iterator end()
    {
    detach();
    return sh->finish;
    }

    const_iterator end() const
    {
    return sh->finish;
    }

    reference at( size_type i, bool* ok = 0 )
    {
    detach();
    if ( ok ) {
        if ( i < size() )
        *ok = TRUE;
        else
        *ok = FALSE;
    }
    return *( begin() + i );
    }

    const_reference at( size_type i, bool* ok = 0 ) const
    {
    if ( ok ) {
        if ( i < size() )
        *ok = TRUE;
        else
        *ok = FALSE;
    }
    return *( begin() + i );
    }

    reference operator[]( size_type i )
    {
    detach();
    return *( begin() + i );
    }

    const_reference operator[]( size_type i ) const
    {
    return *( begin() + i );
    }

    reference front()
    {
    Q_ASSERT( !empty() );
    detach();
    return *begin();
    }

    const_reference front() const
    {
    Q_ASSERT( !empty() );
    return *begin();
    }

    reference back()
    {
    Q_ASSERT( !empty() );
    detach();
    return *( end() - 1 );
    }

    const_reference back() const
    {
    Q_ASSERT( !empty() );
    return *( end() - 1 );
    }

    void push_back( const T& x )
    {
    detach();
    if ( sh->finish == sh->end ) {
        sh->reserve( size()+1 );
    }
    *sh->finish = x;
    ++sh->finish;
    }

    void pop_back()
    {
    detach();
    if ( empty() )
        return;
    --sh->finish;
    }

    iterator insert( iterator pos, const T& x );
    iterator insert( iterator pos, size_type n, const T& x );

    void reserve( size_type n )
    {
    if ( capacity() < n ) {
        detach();
        sh->reserve( n );
    }
    }

    void resize( size_type n, const T& val = T() )
    {
    if ( n < size() )
        erase( begin() + n, end() );
    else
        insert( end(), n - size(), val );
    }

    void clear()
    {
    detach();
    sh->clear();
    }

    iterator erase( iterator pos )
    {
    detach();
    if ( pos + 1 != end() )
        qCopy( pos + 1, sh->finish, pos );
    --sh->finish;
    return pos;
    }

    iterator erase( iterator first, iterator last )
    {
    detach();
    qCopy( last, sh->finish, first );
    sh->finish = sh->finish - ( last - first );
    return first;
    }

    bool operator==( const QValueVector<T>& x )
    {
    return qEqual( begin(), end(), x.begin() );
    }

    bool operator==( const QValueVector<T>& x ) const
    {
    return qEqual( begin(), end(), x.begin() );
    }

protected:
    void detach()
    {
    if ( sh->count > 1 ) { detachInternal(); }
    }
    void detachInternal();
    QValueVectorPrivate<T>* sh;
};

template <class T>
Q_INLINE_TEMPLATES QValueVector<T>::QValueVector( size_type n, const T& val )
{
    sh = new QValueVectorPrivate<T>( n );
    qFill( begin(), end(), val );
}

template <class T>
Q_INLINE_TEMPLATES void QValueVector<T>::detachInternal()
{
    sh->deref();
    sh = new QValueVectorPrivate<T>( *sh );
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueVector<T>::iterator QValueVector<T>::insert( iterator pos, const T& x )
{
    size_type offset = pos - sh->start;
    detach();
    if ( pos == end() ) {
    if ( sh->finish == sh->end )
        push_back( x );
    else {
        *sh->finish = x;
        ++sh->finish;
    }
    } else {
    if ( sh->finish == sh->end ) {
        sh->insert( pos, x );
    } else {
        *sh->finish = *(sh->finish - 1);
        ++sh->finish;
        qCopyBackward( pos, sh->finish - 2, sh->finish - 1 );
        *pos = x;
    }
    }
    return begin() + offset;
}

template <class T>
Q_INLINE_TEMPLATES Q_TYPENAME QValueVector<T>::iterator QValueVector<T>::insert( iterator pos, size_type n, const T& x )
{
    if ( n != 0 ) {
    size_type offset = pos - sh->start;
    detach();
    pos = begin() + offset;
    sh->insert( pos, n, x );
    }
    return pos;
}

#ifndef QT_NO_DATASTREAM
template<class T>
Q_INLINE_TEMPLATES QDataStream& operator>>( QDataStream& s, QValueVector<T>& v )
{
    v.clear();
    Q_UINT32 c;
    s >> c;
    v.resize( c );
    for( Q_UINT32 i = 0; i < c; ++i )
    {
    T t;
    s >> t;
    v[i] = t;
    }
    return s;
}

template<class T>
Q_INLINE_TEMPLATES QDataStream& operator<<( QDataStream& s, const QValueVector<T>& v )
{
    s << (Q_UINT32)v.size();
    // ### use typename QValueVector<T>::const_iterator once all supported
    // ### compilers know about the 'typename' keyword.
    const T* it = v.begin();
    for( ; it != v.end(); ++it )
    s << *it;
    return s;
}
#endif // QT_NO_DATASTREAM

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QValueVector Member List

Complete Member List for QValueVector

This is the complete list of member functions for QValueVector, including inherited members.

  • QValueVector()
  • ~QValueVector()
  • at()
  • back()
  • begin()
  • capacity()
  • clear()
  • detach()
  • empty()
  • end()
  • erase()
  • front()
  • insert()
  • operator=()
  • operator==()
  • operator[]()
  • pop_back()
  • push_back()
  • reserve()
  • resize()
  • size()


QVariant Class

QVariant Class Reference

The QVariant class acts like a union for the most common Qt data types. More...

#include <qvariant.h>

List of all member functions.

Public Members

  • enum Type { Invalid, Map, List, String, StringList, Font, Pixmap, Brush, Rect, Size, Color, Palette, ColorGroup, IconSet, Point, Image, Int, UInt, Bool, Double, CString, PointArray, Region, Bitmap, Cursor, SizePolicy, Date, Time, DateTime, ByteArray, BitArray, KeySequence }
  • QVariant ()
  • ~QVariant ()
  • QVariant ( const QVariant & p )
  • QVariant ( QDataStream & s )
  • QVariant ( const QString & val )
  • QVariant ( const QCString & val )
  • QVariant ( const char * val )
  • QVariant ( const QStringList & val )
  • QVariant ( const QFont & val )
  • QVariant ( const QPixmap & val )
  • QVariant ( const QImage & val )
  • QVariant ( const QBrush & val )
  • QVariant ( const QPoint & val )
  • QVariant ( const QRect & val )
  • QVariant ( const QSize & val )
  • QVariant ( const QColor & val )
  • QVariant ( const QPalette & val )
  • QVariant ( const QColorGroup & val )
  • QVariant ( const QIconSet & val )
  • QVariant ( const QPointArray & val )
  • QVariant ( const QRegion & val )
  • QVariant ( const QBitmap & val )
  • QVariant ( const QCursor & val )
  • QVariant ( const QDate & val )
  • QVariant ( const QTime & val )
  • QVariant ( const QDateTime & val )
  • QVariant ( const QByteArray & val )
  • QVariant ( const QBitArray & val )
  • QVariant ( const QKeySequence & val )
  • QVariant ( const QValueList<QVariant> & val )
  • QVariant ( const QMap<QString, QVariant> & val )
  • QVariant ( int val )
  • QVariant ( uint val )
  • QVariant ( bool val, int )
  • QVariant ( double val )
  • QVariant ( QSizePolicy val )
  • QVariant & operator= ( const QVariant & variant )
  • bool operator== ( const QVariant & v ) const
  • bool operator!= ( const QVariant & v ) const
  • Type type () const
  • const char * typeName () const
  • bool canCast ( Type t ) const
  • bool cast ( Type t )
  • bool isValid () const
  • void clear ()
  • const QString toString () const
  • const QCString toCString () const
  • const QStringList toStringList () const
  • const QFont toFont () const
  • const QPixmap toPixmap () const
  • const QImage toImage () const
  • const QBrush toBrush () const
  • const QPoint toPoint () const
  • const QRect toRect () const
  • const QSize toSize () const
  • const QColor toColor () const
  • const QPalette toPalette () const
  • const QColorGroup toColorGroup () const
  • const QIconSet toIconSet () const
  • const QPointArray toPointArray () const
  • const QBitmap toBitmap () const
  • const QRegion toRegion () const
  • const QCursor toCursor () const
  • const QDate toDate () const
  • const QTime toTime () const
  • const QDateTime toDateTime () const
  • const QByteArray toByteArray () const
  • const QBitArray toBitArray () const
  • const QKeySequence toKeySequence () const
  • int toInt ( bool * ok = 0 ) const
  • uint toUInt ( bool * ok = 0 ) const
  • bool toBool () const
  • double toDouble ( bool * ok = 0 ) const
  • const QValueList<QVariant> toList () const
  • const QMap<QString, QVariant> toMap () const
  • QSizePolicy toSizePolicy () const
  • QValueListConstIterator<QString> stringListBegin () const
  • QValueListConstIterator<QString> stringListEnd () const
  • QValueListConstIterator<QVariant> listBegin () const
  • QValueListConstIterator<QVariant> listEnd () const
  • QMapConstIterator<QString, QVariant> mapBegin () const
  • QMapConstIterator<QString, QVariant> mapEnd () const
  • QMapConstIterator<QString, QVariant> mapFind ( const QString & key ) const
  • QString & asString ()
  • QCString & asCString ()
  • QStringList & asStringList ()
  • QFont & asFont ()
  • QPixmap & asPixmap ()
  • QImage & asImage ()
  • QBrush & asBrush ()
  • QPoint & asPoint ()
  • QRect & asRect ()
  • QSize & asSize ()
  • QColor & asColor ()
  • QPalette & asPalette ()
  • QColorGroup & asColorGroup ()
  • QIconSet & asIconSet ()
  • QPointArray & asPointArray ()
  • QBitmap & asBitmap ()
  • QRegion & asRegion ()
  • QCursor & asCursor ()
  • QDate & asDate ()
  • QTime & asTime ()
  • QDateTime & asDateTime ()
  • QByteArray & asByteArray ()
  • QBitArray & asBitArray ()
  • QKeySequence & asKeySequence ()
  • int & asInt ()
  • uint & asUInt ()
  • bool & asBool ()
  • double & asDouble ()
  • QValueList<QVariant> & asList ()
  • QMap<QString, QVariant> & asMap ()
  • QSizePolicy & asSizePolicy ()

Static Public Members

  • const char * typeToName ( Type typ )
  • Type nameToType ( const char * name )

Detailed Description

The QVariant class acts like a union for the most common Qt data types.

Because C++ forbids unions from including types that have non-default constructors or destructors, most interesting Qt classes cannot be used in unions. Without QVariant, this would be a problem for QObject::property() and for database work, etc.

A QVariant object holds a single value of a single type() at a time. (Some type()s are multi-valued, for example a string list.) You can find out what type, T, the variant holds, convert it to a different type using one of the asT() functions, e.g. asSize(), get its value using one of the toT() functions, e.g. toSize(), and check whether the type can be converted to a particular type using canCast().

The methods named toT() (for any supported T, see the Type documentation for a list) are const. If you ask for the stored type, they return a copy of the stored object. If you ask for a type that can be generated from the stored type, toT() copies and converts and leaves the object itself unchanged. If you ask for a type that cannot be generated from the stored type, the result depends on the type (see the function documentation for details).

Note that three data types supported by QVariant are explicitly shared, namely QImage, QPointArray, and QCString, and in these cases the toT() methods return a shallow copy. In almost all cases you must make a deep copy of the returned values before modifying them.

The asT() functions are not const. They do conversion like the toT() methods, set the variant to hold the converted value, and return a reference to the new contents of the variant.

Here is some example code to demonstrate the use of QVariant:

    QDataStream out(...);
    QVariant v(123);          // The variant now contains an int
    int x = v.toInt();        // x = 123
    out << v;                 // Writes a type tag and an int to out
    v = QVariant("hello");    // The variant now contains a QCString
    v = QVariant(tr("hello"));// The variant now contains a QString
    int y = v.toInt();        // y = 0 since v cannot be converted to an int
    QString s = v.toString(); // s = tr("hello")  (see QObject::tr())
    out << v;                 // Writes a type tag and a QString to out
    ...
    QDataStream in(...);      // (opening the previously written stream)
    in >> v;                  // Reads an Int variant
    int z = v.toInt();        // z = 123
    qDebug("Type is %s",      // prints "Type is int"
            v.typeName());
    v.asInt() += 100;         // The variant now hold the value 223.
    v = QVariant( QStringList() );
    v.asStringList().append( "Hello" );

You can even store QValueList s and QMap s in a variant, so you can easily construct arbitrarily complex data structures of arbitrary types. This is very powerful and versatile, but may prove less memory and speed efficient than storing specific types in standard data structures.

See the Collection Classes.

See also Miscellaneous Classes and Object Model.

Member Type Documentation

QVariant::Type

This enum type defines the types of variable that a QVariant can contain.

  • QVariant::Invalid - no type
  • QVariant::BitArray - a QBitArray
  • QVariant::ByteArray - a QByteArray
  • QVariant::Bitmap - a QBitmap
  • QVariant::Bool - a bool
  • QVariant::Brush - a QBrush
  • QVariant::Color - a QColor
  • QVariant::ColorGroup - a QColorGroup
  • QVariant::Cursor - a QCursor
  • QVariant::Date - a QDate
  • QVariant::DateTime - a QDateTime
  • QVariant::Double - a double
  • QVariant::Font - a QFont
  • QVariant::IconSet - a QIconSet
  • QVariant::Image - a QImage
  • QVariant::Int - an int
  • QVariant::KeySequence - a QKeySequence
  • QVariant::List - a QValueList
  • QVariant::Map - a QMap
  • QVariant::Palette - a QPalette
  • QVariant::Pixmap - a QPixmap
  • QVariant::Point - a QPoint
  • QVariant::PointArray - a QPointArray
  • QVariant::Rect - a QRect
  • QVariant::Region - a QRegion
  • QVariant::Size - a QSize
  • QVariant::SizePolicy - a QSizePolicy
  • QVariant::String - a QString
  • QVariant::CString - a QCString
  • QVariant::StringList - a QStringList
  • QVariant::Time - a QTime
  • QVariant::UInt - an unsigned int

Note that Qt's definition of bool depends on the compiler. qglobal.h has the system-dependent definition of bool.

Member Function Documentation

QVariant::QVariant ()

Constructs an invalid variant.

QVariant::QVariant ( const QVariant & p )

Constructs a copy of the variant, p, passed as the argument to this constructor. Usually this is a deep copy, but a shallow copy is made if the stored data type is explicitly shared, as e.g. QImage is.

QVariant::QVariant ( QDataStream & s )

Reads the variant from the data stream, s.

QVariant::QVariant ( const QString & val )

Constructs a new variant with a string value, val.

QVariant::QVariant ( const QCString & val )

Constructs a new variant with a C-string value, val.

If you want to modify the QCString after you've passed it to this constructor, we recommend passing a deep copy (see QCString::copy()).

QVariant::QVariant ( const char * val )

Constructs a new variant with a C-string value of val if val is non-null. The variant creates a deep copy of val.

If val is null, the resulting variant has type Invalid.

QVariant::QVariant ( const QStringList & val )

Constructs a new variant with a string list value, val.

QVariant::QVariant ( const QFont & val )

Constructs a new variant with a font value, val.

QVariant::QVariant ( const QPixmap & val )

Constructs a new variant with a pixmap value, val.

QVariant::QVariant ( const QImage & val )

Constructs a new variant with an image value, val.

Because QImage is explicitly shared, you may need to pass a deep copy to the variant using QImage::copy(), e.g. if you intend changing the image you've passed later on.

QVariant::QVariant ( const QBrush & val )

Constructs a new variant with a brush value, val.

QVariant::QVariant ( const QPoint & val )

Constructs a new variant with a point value, val.

QVariant::QVariant ( const QRect & val )

Constructs a new variant with a rect value, val.

QVariant::QVariant ( const QSize & val )

Constructs a new variant with a size value, val.

QVariant::QVariant ( const QColor & val )

Constructs a new variant with a color value, val.

QVariant::QVariant ( const QPalette & val )

Constructs a new variant with a color palette value, val.

QVariant::QVariant ( const QColorGroup & val )

Constructs a new variant with a color group value, val.

QVariant::QVariant ( const QIconSet & val )

Constructs a new variant with an icon set value, val.

QVariant::QVariant ( const QPointArray & val )

Constructs a new variant with a point array value, val.

Because QPointArray is explicitly shared, you may need to pass a deep copy to the variant using QPointArray::copy(), e.g. if you intend changing the point array you've passed later on.

QVariant::QVariant ( const QRegion & val )

Constructs a new variant with a region value, val.

QVariant::QVariant ( const QBitmap & val )

Constructs a new variant with a bitmap value, val.

QVariant::QVariant ( const QCursor & val )

Constructs a new variant with a cursor value, val.

QVariant::QVariant ( const QDate & val )

Constructs a new variant with a date value, val.

QVariant::QVariant ( const QTime & val )

Constructs a new variant with a time value, val.

QVariant::QVariant ( const QDateTime & val )

Constructs a new variant with a date/time value, val.

QVariant::QVariant ( const QByteArray & val )

Constructs a new variant with a bytearray value, val.

QVariant::QVariant ( const QBitArray & val )

Constructs a new variant with a bitarray value, val.

QVariant::QVariant ( const QKeySequence & val )

Constructs a new variant with a key sequence value, val.

QVariant::QVariant ( const QValueList<QVariant> & val )

Constructs a new variant with a list value, val.

QVariant::QVariant ( const QMap<QString, QVariant> & val )

Constructs a new variant with a map of QVariants, val.

QVariant::QVariant ( int val )

Constructs a new variant with an integer value, val.

QVariant::QVariant ( uint val )

Constructs a new variant with an unsigned integer value, val.

QVariant::QVariant ( bool val, int )

Constructs a new variant with a boolean value, val. The integer argument is a dummy, necessary for compatibility with some compilers.

QVariant::QVariant ( double val )

Constructs a new variant with a floating point value, val.

QVariant::QVariant ( QSizePolicy val )

Constructs a new variant with a size policy value, val.

QVariant::~QVariant ()

Destroys the QVariant and the contained object.

Note that subclasses that reimplement clear() should reimplement the destructor to call clear(). This destructor calls clear(), but because it is the destructor, QVariant::clear() is called rather than a subclass's clear().

QBitArray & QVariant::asBitArray ()

Tries to convert the variant to hold a QBitArray value. If that is not possible then the variant is set to an empty bitarray.

Returns a reference to the stored bitarray.

See also toBitArray().

QBitmap & QVariant::asBitmap ()

Tries to convert the variant to hold a bitmap value. If that is not possible the variant is set to a null bitmap.

Returns a reference to the stored bitmap.

See also toBitmap().

bool & QVariant::asBool ()

Returns the variant's value as bool reference.

QBrush & QVariant::asBrush ()

Tries to convert the variant to hold a brush value. If that is not possible the variant is set to a default black brush.

Returns a reference to the stored brush.

See also toBrush().

QByteArray & QVariant::asByteArray ()

Tries to convert the variant to hold a QByteArray value. If that is not possible then the variant is set to an empty bytearray.

Returns a reference to the stored bytearray.

See also toByteArray().

QCString & QVariant::asCString ()

Tries to convert the variant to hold a string value. If that is not possible the variant is set to an empty string.

Returns a reference to the stored string.

See also toCString().

QColor & QVariant::asColor ()

Tries to convert the variant to hold a QColor value. If that is not possible the variant is set to an invalid color.

Returns a reference to the stored color.

See also toColor() and QColor::isValid().

QColorGroup & QVariant::asColorGroup ()

Tries to convert the variant to hold a QColorGroup value. If that is not possible the variant is set to a color group of all black colors.

Returns a reference to the stored color group.

See also toColorGroup().

QCursor & QVariant::asCursor ()

Tries to convert the variant to hold a QCursor value. If that is not possible the variant is set to a default arrow cursor.

Returns a reference to the stored cursor.

See also toCursor().

QDate & QVariant::asDate ()

Tries to convert the variant to hold a QDate value. If that is not possible then the variant is set to an invalid date.

Returns a reference to the stored date.

See also toDate().

QDateTime & QVariant::asDateTime ()

Tries to convert the variant to hold a QDateTime value. If that is not possible then the variant is set to an invalid date/time.

Returns a reference to the stored date/time.

See also toDateTime().

double & QVariant::asDouble ()

Returns the variant's value as double reference.

QFont & QVariant::asFont ()

Tries to convert the variant to hold a QFont. If that is not possible the variant is set to the application's default font.

Returns a reference to the stored font.

See also toFont().

QIconSet & QVariant::asIconSet ()

Tries to convert the variant to hold a QIconSet value. If that is not possible the variant is set to an empty iconset.

Returns a reference to the stored iconset.

See also toIconSet().

QImage & QVariant::asImage ()

Tries to convert the variant to hold an image value. If that is not possible the variant is set to a null image.

Returns a reference to the stored image.

See also toImage().

int & QVariant::asInt ()

Returns the variant's value as int reference.

QKeySequence & QVariant::asKeySequence ()

Tries to convert the variant to hold a QKeySequence value. If that is not possible then the variant is set to an empty key sequence.

Returns a reference to the stored key sequence.

See also toKeySequence().

QValueList<QVariant> & QVariant::asList ()

Returns the variant's value as variant list reference.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QVariant> list = myVariant.asList();
    QValueList<QVariant>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

QMap<QString, QVariant> & QVariant::asMap ()

Returns the variant's value as variant map reference.

Note that if you want to iterate over the map, you should iterate over a copy, e.g.

    QMap<QString, QVariant> map = myVariant.asMap();
    QMap<QString, QVariant>::Iterator it = map.begin();
    while( it != map.end() ) {
        myProcessing( *it );
        ++it;
    }

QPalette & QVariant::asPalette ()

Tries to convert the variant to hold a QPalette value. If that is not possible the variant is set to a palette of black colors.

Returns a reference to the stored palette.

See also toString().

QPixmap & QVariant::asPixmap ()

Tries to convert the variant to hold a pixmap value. If that is not possible the variant is set to a null pixmap.

Returns a reference to the stored pixmap.

See also toPixmap().

QPoint & QVariant::asPoint ()

Tries to convert the variant to hold a point value. If that is not possible the variant is set to a (0, 0) point.

Returns a reference to the stored point.

See also toPoint().

QPointArray & QVariant::asPointArray ()

Tries to convert the variant to hold a QPointArray value. If that is not possible the variant is set to an empty point array.

Returns a reference to the stored point array.

See also toPointArray().

QRect & QVariant::asRect ()

Tries to convert the variant to hold a rectangle value. If that is not possible the variant is set to an empty rectangle.

Returns a reference to the stored rectangle.

See also toRect().

QRegion & QVariant::asRegion ()

Tries to convert the variant to hold a QRegion value. If that is not possible the variant is set to a null region.

Returns a reference to the stored region.

See also toRegion().

QSize & QVariant::asSize ()

Tries to convert the variant to hold a QSize value. If that is not possible the variant is set to an invalid size.

Returns a reference to the stored size.

See also toSize() and QSize::isValid().

QSizePolicy & QVariant::asSizePolicy ()

Tries to convert the variant to hold a QSizePolicy value. If that fails, the variant is set to an arbitrary (valid) size policy.

QString & QVariant::asString ()

Tries to convert the variant to hold a string value. If that is not possible the variant is set to an empty string.

Returns a reference to the stored string.

See also toString().

QStringList & QVariant::asStringList ()

Tries to convert the variant to hold a QStringList value. If that is not possible the variant is set to an empty string list.

Returns a reference to the stored string list.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myVariant.asStringList();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also toStringList().

QTime & QVariant::asTime ()

Tries to convert the variant to hold a QTime value. If that is not possible then the variant is set to an invalid time.

Returns a reference to the stored time.

See also toTime().

uint & QVariant::asUInt ()

Returns the variant's value as unsigned int reference.

bool QVariant::canCast ( Type t ) const

Returns TRUE if the variant's type can be cast to the requested type, t. Such casting is done automatically when calling the toInt(), toBool(), ... or asInt(), asBool(), ... methods.

The following casts are done automatically:

that can be cast to a string)
Type | Automatically Cast To
Bool | Double, Int, UInt
CString | String
Date | String
DateTime | String, Date, Time
Double | String, Int, Bool, UInt
Int | String, Double, Bool, UInt
List | StringList (if the list contains strings or something
String | CString, Int, Uint, Double, Date, Time, DateTime
StringList | List
Time | String
UInt | String, Double, Bool, Int

bool QVariant::cast ( Type t )

Casts the variant to the requested type. If the cast cannot be done, the variant is set to the default value of the requested type (e.g. an empty string if the requested type t is QVariant::String, an empty point array if the requested type t is QVariant::PointArray, etc). Returns TRUE if the current type of the variant was successfully cast; otherwise returns FALSE.

See also canCast().

void QVariant::clear ()

Convert this variant to type Invalid and free up any resources used.

bool QVariant::isValid () const

Returns TRUE if the storage type of this variant is not QVariant::Invalid; otherwise returns FALSE.

QValueListConstIterator<QVariant> QVariant::listBegin () const

Returns an iterator to the first item in the list if the variant's type is appropriate; otherwise returns a null iterator.

QValueListConstIterator<QVariant> QVariant::listEnd () const

Returns the end iterator for the list if the variant's type is appropriate; otherwise returns a null iterator.

QMapConstIterator<QString, QVariant> QVariant::mapBegin () const

Returns an iterator to the first item in the map, if the variant's type is appropriate; otherwise returns a null iterator.

QMapConstIterator<QString, QVariant> QVariant::mapEnd () const

Returns the end iterator for the map, if the variant's type is appropriate; otherwise returns a null iterator.

QMapConstIterator<QString, QVariant> QVariant::mapFind ( const QString & key ) const

Returns an iterator to the item in the map with key as key, if the variant's type is appropriate and key is a valid key; otherwise returns a null iterator.

Type QVariant::nameToType ( const char * name ) [static]

Converts the string representation of the storage type gven in name, to its enum representation.

If the string representation cannot be converted to any enum representation, the variant is set to Invalid.

bool QVariant::operator!= ( const QVariant & v ) const

Compares this QVariant with v and returns TRUE if they are not equal; otherwise returns FALSE.

QVariant & QVariant::operator= ( const QVariant & variant )

Assigns the value of the variant variant to this variant.

This is a deep copy of the variant, but note that if the variant holds an explicitly shared type such as QImage, a shallow copy is performed.

bool QVariant::operator== ( const QVariant & v ) const

Compares this QVariant with v and returns TRUE if they are equal; otherwise returns FALSE.

QValueListConstIterator<QString> QVariant::stringListBegin () const

Returns an iterator to the first string in the list if the variant's type is StringList; otherwise returns a null iterator.

QValueListConstIterator<QString> QVariant::stringListEnd () const

Returns the end iterator for the list if the variant's type is StringList; otherwise returns a null iterator.

const QBitArray QVariant::toBitArray () const

Returns the variant as a QBitArray if the variant has type() BitArray; otherwise returns an empty bitarray.

See also asBitArray().

const QBitmap QVariant::toBitmap () const

Returns the variant as a QBitmap if the variant has type() Bitmap; otherwise returns a null QBitmap.

See also asBitmap().

bool QVariant::toBool () const

Returns the variant as a bool if the variant has type() Bool.

Returns TRUE if the variant has type Int, UInt or Double and its value is non-zero; otherwise returns FALSE.

See also asBool().

const QBrush QVariant::toBrush () const

Returns the variant as a QBrush if the variant has type() Brush; otherwise returns a default brush (with all black colors).

See also asBrush().

const QByteArray QVariant::toByteArray () const

Returns the variant as a QByteArray if the variant has type() ByteArray; otherwise returns an empty bytearray.

See also asByteArray().

const QCString QVariant::toCString () const

Returns the variant as a QCString if the variant has type() CString or String; otherwise returns 0.

See also asCString().

const QColor QVariant::toColor () const

Returns the variant as a QColor if the variant has type() Color; otherwise returns an invalid color.

See also asColor().

const QColorGroup QVariant::toColorGroup () const

Returns the variant as a QColorGroup if the variant has type() ColorGroup; otherwise returns a completely black color group.

See also asColorGroup().

const QCursor QVariant::toCursor () const

Returns the variant as a QCursor if the variant has type() Cursor; otherwise returns the default arrow cursor.

See also asCursor().

const QDate QVariant::toDate () const

Returns the variant as a QDate if the variant has type() Date, DateTime or String; otherwise returns an invalid date.

Note that if the type() is String an invalid date will be returned if the string cannot be parsed as a Qt::ISODate format date.

See also asDate().

const QDateTime QVariant::toDateTime () const

Returns the variant as a QDateTime if the variant has type() DateTime or String; otherwise returns an invalid date/time.

Note that if the type() is String an invalid date/time will be returned if the string cannot be parsed as a Qt::ISODate format date/time.

See also asDateTime().

double QVariant::toDouble ( bool * ok = 0 ) const

Returns the variant as a double if the variant has type() String, CString, Double, Int, UInt, or Bool; otherwise returns 0.0.

If ok is non-null: *ok is set to TRUE if the value could be converted to a double; otherwise *ok is set to FALSE.

See also asDouble().

const QFont QVariant::toFont () const

Returns the variant as a QFont if the variant has type() Font; otherwise returns the application's default font.

See also asFont().

const QIconSet QVariant::toIconSet () const

Returns the variant as a QIconSet if the variant has type() IconSet; otherwise returns an icon set of null pixmaps.

See also asIconSet().

const QImage QVariant::toImage () const

Returns the variant as a QImage if the variant has type() Image; otherwise returns a null image.

See also asImage().

int QVariant::toInt ( bool * ok = 0 ) const

Returns the variant as an int if the variant has type() String, CString, Int, UInt, Double, Bool or KeySequence; otherwise returns 0.

If ok is non-null: *ok is set to TRUE if the value could be converted to an int; otherwise *ok is set to FALSE.

See also asInt() and canCast().

const QKeySequence QVariant::toKeySequence () const

Returns the variant as a QKeySequence if the variant has type() KeySequence, Int or String; otherwise returns an empty key sequence.

Note that not all Ints and Strings are valid key sequences and in such cases an empty key sequence will be returned.

See also asKeySequence().

const QValueList<QVariant> QVariant::toList () const

Returns the variant as a QValueList if the variant has type() List or StringList; otherwise returns an empty list.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QValueList<QVariant> list = myVariant.toList();
    QValueList<QVariant>::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also asList().

const QMap<QString, QVariant> QVariant::toMap () const

Returns the variant as a QMap if the variant has type() Map; otherwise returns an empty map.

Note that if you want to iterate over the map, you should iterate over a copy, e.g.

    QMap<QString, QVariant> map = myVariant.toMap();
    QMap<QString, QVariant>::Iterator it = map.begin();
    while( it != map.end() ) {
        myProcessing( *it );
        ++it;
    }

See also asMap().

const QPalette QVariant::toPalette () const

Returns the variant as a QPalette if the variant has type() Palette; otherwise returns a completely black palette.

See also asPalette().

const QPixmap QVariant::toPixmap () const

Returns the variant as a QPixmap if the variant has type() Pixmap; otherwise returns a null pixmap.

See also asPixmap().

const QPoint QVariant::toPoint () const

Returns the variant as a QPoint if the variant has type() Point; otherwise returns a point (0, 0).

See also asPoint().

const QPointArray QVariant::toPointArray () const

Returns the variant as a QPointArray if the variant has type() PointArray; otherwise returns an empty QPointArray.

See also asPointArray().

const QRect QVariant::toRect () const

Returns the variant as a QRect if the variant has type() Rect; otherwise returns an empty rectangle.

See also asRect().

const QRegion QVariant::toRegion () const

Returns the variant as a QRegion if the variant has type() Region; otherwise returns an empty QRegion.

See also asRegion().

const QSize QVariant::toSize () const

Returns the variant as a QSize if the variant has type() Size; otherwise returns an invalid size.

See also asSize().

QSizePolicy QVariant::toSizePolicy () const

Returns the variant as a QSizePolicy if the variant has type() SizePolicy; otherwise returns an undefined (but legal) size policy.

const QString QVariant::toString () const

Returns the variant as a QString if the variant has type() String, CString, ByteArray, Int, Uint, Bool, Double, Date, Time, or DateTime; otherwise returns QString::null.

See also asString().

const QStringList QVariant::toStringList () const

Returns the variant as a QStringList if the variant has type() StringList or List of a type that can be converted to QString; otherwise returns an empty list.

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myVariant.toStringList();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

See also asStringList().

const QTime QVariant::toTime () const

Returns the variant as a QTime if the variant has type() Time, DateTime or String; otherwise returns an invalid time.

Note that if the type() is String an invalid time will be returned if the string cannot be parsed as a Qt::ISODate format time.

See also asTime().

uint QVariant::toUInt ( bool * ok = 0 ) const

Returns the variant as an unsigned int if the variant has type() String, CString, UInt, Int, Double, or Bool; otherwise returns 0.

If ok is non-null: *ok is set to TRUE if the value could be converted to an unsigned int; otherwise *ok is set to FALSE.

See also asUInt().

Type QVariant::type () const

Returns the storage type of the value stored in the variant. Usually it's best to test with canCast() whether the variant can deliver the data type you are interested in.

const char * QVariant::typeName () const

Returns the name of the type stored in the variant. The returned strings describe the C++ datatype used to store the data: for example, "QFont", "QString", or "QValueList". An Invalid variant returns 0.

const char * QVariant::typeToName ( Type typ ) [static]

Converts the enum representation of the storage type, typ, to its string representation.

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


qvariant.h Include File

qvariant.h

This is the verbatim text of the qvariant.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qvariant.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QVariant class
**
** Created : 990414
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVARIANT_H
#define QVARIANT_H

#ifndef QT_H
#include "qstring.h"
#endif // QT_H

#ifndef QT_NO_VARIANT
class QString;
class QCString;
class QFont;
class QPixmap;
class QBrush;
class QRect;
class QPoint;
class QImage;
class QSize;
class QColor;
class QPalette;
class QColorGroup;
class QIconSet;
class QDataStream;
class QPointArray;
class QRegion;
class QBitmap;
class QCursor;
class QStringList;
class QSizePolicy;
class QDate;
class QTime;
class QDateTime;
class QBitArray;
class QKeySequence;
// Some headers rejected after QVariant declaration for GCC 2.7.* compatibility
class QVariant;
#ifndef QT_NO_TEMPLATE_VARIANT
template <class T> class QValueList;
template <class T> class QValueListConstIterator;
template <class T> class QValueListNode;
template <class Key, class T> class QMap;
template <class Key, class T> class QMapConstIterator;
#endif

class Q_EXPORT QVariant
{
public:
    enum Type {
    Invalid,
    Map,
    List,
    String,
    StringList,
    Font,
    Pixmap,
    Brush,
    Rect,
    Size,
    Color,
    Palette,
    ColorGroup,
    IconSet,
    Point,
    Image,
    Int,
    UInt,
    Bool,
    Double,
    CString,
    PointArray,
    Region,
    Bitmap,
    Cursor,
    SizePolicy,
    Date,
    Time,
    DateTime,
    ByteArray,
    BitArray,
    KeySequence
    };

    QVariant();
    ~QVariant();
    QVariant( const QVariant& );
#ifndef QT_NO_DATASTREAM
    QVariant( QDataStream& s );
#endif
    QVariant( const QString& );
    QVariant( const QCString& );
    QVariant( const char* );
#ifndef QT_NO_STRINGLIST
    QVariant( const QStringList& );
#endif
    QVariant( const QFont& );
    QVariant( const QPixmap& );
    QVariant( const QImage& );
    QVariant( const QBrush& );
    QVariant( const QPoint& );
    QVariant( const QRect& );
    QVariant( const QSize& );
    QVariant( const QColor& );
    QVariant( const QPalette& );
    QVariant( const QColorGroup& );
    QVariant( const QIconSet& );
    QVariant( const QPointArray& );
    QVariant( const QRegion& );
    QVariant( const QBitmap& );
    QVariant( const QCursor& );
    QVariant( const QDate& );
    QVariant( const QTime& );
    QVariant( const QDateTime& );
    QVariant( const QByteArray& );
    QVariant( const QBitArray& );
    QVariant( const QKeySequence& );
#ifndef QT_NO_TEMPLATE_VARIANT
    QVariant( const QValueList<QVariant>& );
    QVariant( const QMap<QString,QVariant>& );
#endif
    QVariant( int );
    QVariant( uint );
    // ### Problems on some compilers ?
    QVariant( bool, int );
    QVariant( double );
    QVariant( QSizePolicy );

    QVariant& operator= ( const QVariant& );
    bool operator==( const QVariant& ) const;
    bool operator!=( const QVariant& ) const;

    Type type() const;
    const char* typeName() const;

    bool canCast( Type ) const;
    bool cast( Type );

    bool isValid() const;

    void clear();

    const QString toString() const;
    const QCString toCString() const;
#ifndef QT_NO_STRINGLIST
    const QStringList toStringList() const;
#endif
    const QFont toFont() const;
    const QPixmap toPixmap() const;
    const QImage toImage() const;
    const QBrush toBrush() const;
    const QPoint toPoint() const;
    const QRect toRect() const;
    const QSize toSize() const;
    const QColor toColor() const;
    const QPalette toPalette() const;
    const QColorGroup toColorGroup() const;
    const QIconSet toIconSet() const;
    const QPointArray toPointArray() const;
    const QBitmap toBitmap() const;
    const QRegion toRegion() const;
    const QCursor toCursor() const;
    const QDate toDate() const;
    const QTime toTime() const;
    const QDateTime toDateTime() const;
    const QByteArray toByteArray() const;
    const QBitArray toBitArray() const;
    const QKeySequence toKeySequence() const;
    int toInt( bool * ok=0 ) const;
    uint toUInt( bool * ok=0 ) const;
    bool toBool() const;
    double toDouble( bool * ok=0 ) const;
#ifndef QT_NO_TEMPLATE_VARIANT
    const QValueList<QVariant> toList() const;
    const QMap<QString,QVariant> toMap() const;
#endif
    QSizePolicy toSizePolicy() const;

#ifndef QT_NO_TEMPLATE_VARIANT
    QValueListConstIterator<QString> stringListBegin() const;
    QValueListConstIterator<QString> stringListEnd() const;
    QValueListConstIterator<QVariant> listBegin() const;
    QValueListConstIterator<QVariant> listEnd() const;
    QMapConstIterator<QString,QVariant> mapBegin() const;
    QMapConstIterator<QString,QVariant> mapEnd() const;
    QMapConstIterator<QString,QVariant> mapFind( const QString& ) const;
#endif
    QString& asString();
    QCString& asCString();
#ifndef QT_NO_STRINGLIST
    QStringList& asStringList();
#endif
    QFont& asFont();
    QPixmap& asPixmap();
    QImage& asImage();
    QBrush& asBrush();
    QPoint& asPoint();
    QRect& asRect();
    QSize& asSize();
    QColor& asColor();
    QPalette& asPalette();
    QColorGroup& asColorGroup();
    QIconSet& asIconSet();
    QPointArray& asPointArray();
    QBitmap& asBitmap();
    QRegion& asRegion();
    QCursor& asCursor();
    QDate& asDate();
    QTime& asTime();
    QDateTime& asDateTime();
    QByteArray& asByteArray();
    QBitArray& asBitArray();
#ifndef QT_NO_ACCEL
    QKeySequence& asKeySequence();
#endif
    int& asInt();
    uint& asUInt();
    bool& asBool();
    double& asDouble();
#ifndef QT_NO_TEMPLATE_VARIANT
    QValueList<QVariant>& asList();
    QMap<QString,QVariant>& asMap();
#endif
    QSizePolicy& asSizePolicy();

#ifndef QT_NO_DATASTREAM
    void load( QDataStream& );
    void save( QDataStream& ) const;
#endif
    static const char* typeToName( Type typ );
    static Type nameToType( const char* name );

private:
    void detach();

    class Private : public QShared
    {
    public:
        Private();
        Private( Private* );
        ~Private();

        void clear();

        Type typ;
        union
        {
        uint u;
        int i;
        bool b;
        double d;
        void *ptr;
        } value;
    };

    Private* d;
};

// down here for GCC 2.7.* compatibility
#ifndef QT_H
#include "qvaluelist.h"
#include "qstringlist.h"
#include "qmap.h"
#endif // QT_H

inline QVariant::Type QVariant::type() const
{
    return d->typ;
}

inline bool QVariant::isValid() const
{
    return (d->typ != Invalid);
}

#ifndef QT_NO_TEMPLATE_VARIANT
inline QValueListConstIterator<QString> QVariant::stringListBegin() const
{
    if ( d->typ != StringList )
    return QValueListConstIterator<QString>();
    return ((const QStringList*)d->value.ptr)->begin();
}

inline QValueListConstIterator<QString> QVariant::stringListEnd() const
{
    if ( d->typ != StringList )
    return QValueListConstIterator<QString>();
    return ((const QStringList*)d->value.ptr)->end();
}

inline QValueListConstIterator<QVariant> QVariant::listBegin() const
{
    if ( d->typ != List )
    return QValueListConstIterator<QVariant>();
    return ((const QValueList<QVariant>*)d->value.ptr)->begin();
}

inline QValueListConstIterator<QVariant> QVariant::listEnd() const
{
    if ( d->typ != List )
    return QValueListConstIterator<QVariant>();
    return ((const QValueList<QVariant>*)d->value.ptr)->end();
}

inline QMapConstIterator<QString,QVariant> QVariant::mapBegin() const
{
    if ( d->typ != Map )
    return QMapConstIterator<QString,QVariant>();
    return ((const QMap<QString,QVariant>*)d->value.ptr)->begin();
}

inline QMapConstIterator<QString,QVariant> QVariant::mapEnd() const
{
    if ( d->typ != Map )
    return QMapConstIterator<QString,QVariant>();
    return ((const QMap<QString,QVariant>*)d->value.ptr)->end();
}

inline QMapConstIterator<QString,QVariant> QVariant::mapFind( const QString& key ) const
{
    if ( d->typ != Map )
    return QMapConstIterator<QString,QVariant>();
    return ((const QMap<QString,QVariant>*)d->value.ptr)->find( key );
}
#endif

#ifndef QT_NO_DATASTREAM
Q_EXPORT QDataStream& operator>> ( QDataStream& s, QVariant& p );
Q_EXPORT QDataStream& operator<< ( QDataStream& s, const QVariant& p );
Q_EXPORT QDataStream& operator>> ( QDataStream& s, QVariant::Type& p );
Q_EXPORT QDataStream& operator<< ( QDataStream& s, const QVariant::Type p );
#endif

#endif //QT_NO_VARIANT
#endif // QVARIANT_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QVariant Member List

Complete Member List for QVariant

This is the complete list of member functions for QVariant, including inherited members.

  • QVariant()
  • ~QVariant()
  • asBitArray()
  • asBitmap()
  • asBool()
  • asBrush()
  • asByteArray()
  • asCString()
  • asColor()
  • asColorGroup()
  • asCursor()
  • asDate()
  • asDateTime()
  • asDouble()
  • asFont()
  • asIconSet()
  • asImage()
  • asInt()
  • asKeySequence()
  • asList()
  • asMap()
  • asPalette()
  • asPixmap()
  • asPoint()
  • asPointArray()
  • asRect()
  • asRegion()
  • asSize()
  • asSizePolicy()
  • asString()
  • asStringList()
  • asTime()
  • asUInt()
  • canCast()
  • cast()
  • clear()
  • isValid()
  • listBegin()
  • listEnd()
  • mapBegin()
  • mapEnd()
  • mapFind()
  • nameToType()
  • operator!=()
  • operator=()
  • operator==()
  • stringListBegin()
  • stringListEnd()
  • toBitArray()
  • toBitmap()
  • toBool()
  • toBrush()
  • toByteArray()
  • toCString()
  • toColor()
  • toColorGroup()
  • toCursor()
  • toDate()
  • toDateTime()
  • toDouble()
  • toFont()
  • toIconSet()
  • toImage()
  • toInt()
  • toKeySequence()
  • toList()
  • toMap()
  • toPalette()
  • toPixmap()
  • toPoint()
  • toPointArray()
  • toRect()
  • toRegion()
  • toSize()
  • toSizePolicy()
  • toString()
  • toStringList()
  • toTime()
  • toUInt()
  • type()
  • typeName()
  • typeToName()


QVBox Class

QVBox Class Reference

The QVBox widget provides vertical geometry management of its child widgets. More...

#include <qvbox.h>

Inherits QHBox.

List of all member functions.

Public Members

  • QVBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Detailed Description

The QVBox widget provides vertical geometry management of its child widgets.

All its child widgets will be placed vertically and sized according to their sizeHint()s.

See also QHBox, Widget Appearance and Style, Layout Management and Organizers.

Member Function Documentation

QVBox::QVBox ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

Constructs a vbox widget called name with parent parent and widget flags f.

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


qvbox.h Include File

qvbox.h

This is the verbatim text of the qvbox.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qvbox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of vertical box layout widget class
**
** Created : 990124
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVBOX_H
#define QVBOX_H

#ifndef QT_H
#include "qhbox.h"
#endif // QT_H

#ifndef QT_NO_VBOX

class Q_EXPORT QVBox : public QHBox
{
    Q_OBJECT
public:
    QVBox( QWidget* parent=0, const char* name=0, WFlags f=0 );

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QVBox( const QVBox & );
    QVBox& operator=( const QVBox & );
#endif
};

#endif // QT_NO_VBOX

#endif // QVBOX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QVBox Member List

Complete Member List for QVBox

This is the complete list of member functions for QVBox, including inherited members.

  • QVBox()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setSpacing()
  • setStretchFactor()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()


QVBoxLayout Class

QVBoxLayout Class Reference

The QVBoxLayout class lines up widgets vertically. More...

#include <qlayout.h>

Inherits QBoxLayout.

List of all member functions.

Public Members

  • QVBoxLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )
  • QVBoxLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )
  • QVBoxLayout ( int spacing = -1, const char * name = 0 )
  • ~QVBoxLayout ()

Detailed Description

The QVBoxLayout class lines up widgets vertically.

This class is used to construct vertical box layout objects. See QBoxLayout for more details.

The simplest use of the class is like this:

        QBoxLayout * l = new QVBoxLayout( widget );
        l->addWidget( aWidget );
        l->addWidget( anotherWidget );

See also QHBoxLayout, QGridLayout, the Layout overview, Widget Appearance and Style and Layout Management.

Member Function Documentation

QVBoxLayout::QVBoxLayout ( QWidget * parent, int margin = 0, int spacing = -1, const char * name = 0 )

Constructs a new top-level vertical box called name, with parent parent.

The margin is the number of pixels between the edge of the widget and its managed children. The spacing is the default number of pixels between neighboring children. If spacing is -1 the value of margin is used for spacing.

QVBoxLayout::QVBoxLayout ( QLayout * parentLayout, int spacing = -1, const char * name = 0 )

Constructs a new vertical box called name name and adds it to parentLayout.

The spacing is the default number of pixels between neighboring children. If spacing is -1, this QVBoxLayout will inherit its parent's spacing().

QVBoxLayout::QVBoxLayout ( int spacing = -1, const char * name = 0 )

Constructs a new vertical box called name name. You must add it to another layout.

The spacing is the default number of pixels between neighboring children. If spacing is -1, this QVBoxLayout will inherit its parent's spacing().

QVBoxLayout::~QVBoxLayout ()

Destroys this box layout.

The layout's widgets are not destroyed.

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


QVBoxLayout Member List

Complete Member List for QVBoxLayout

This is the complete list of member functions for QVBoxLayout, including inherited members.

  • QVBoxLayout()
  • ~QVBoxLayout()
  • activate()
  • add()
  • addChildLayout()
  • addItem()
  • addLayout()
  • addSpacing()
  • addStretch()
  • addStrut()
  • addWidget()
  • alignment()
  • alignmentRect()
  • autoAdd()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteAllItems()
  • deleteLater()
  • destroyed()
  • direction()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • expanding()
  • findWidget()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • highPriority()
  • inherits()
  • insertChild()
  • insertItem()
  • insertLayout()
  • insertSpacing()
  • insertStretch()
  • insertWidget()
  • installEventFilter()
  • invalidate()
  • isA()
  • isEmpty()
  • isEnabled()
  • isTopLevel()
  • isWidgetType()
  • iterator()
  • killTimer()
  • killTimers()
  • layout()
  • mainWidget()
  • margin()
  • maximumSize()
  • menuBar()
  • metaObject()
  • minimumSize()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • resizeMode()
  • sender()
  • setAlignment()
  • setAutoAdd()
  • setDirection()
  • setEnabled()
  • setGeometry()
  • setMargin()
  • setMenuBar()
  • setName()
  • setProperty()
  • setResizeMode()
  • setSpacing()
  • setStretchFactor()
  • setSupportsMargin()
  • signalsBlocked()
  • sizeHint()
  • spacerItem()
  • spacing()
  • startTimer()
  • supportsMargin()
  • timerEvent()
  • tr()
  • trUtf8()
  • widget()


QVButtonGroup类

QVButtonGroup类参考

QVButtonGroup窗口部件把QButton窗口部件组织在一个垂直列中。 详情请见……

#include <qvbuttongroup.h>

继承了QButtonGroup。

所有成员函数的列表。

公有成员

  • QVButtonGroup ( QWidget * parent = 0, const char * name = 0 )
  • QVButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • ~QVButtonGroup ()

详细描述

QVButtonGroup窗口部件把QButton窗口部件组织在一个垂直列中。

QVButtonGroup是一个在QButtonGroup中提供了一个小布局的方便类。可以把它看作适提供了一个框架和标题的QVBox并且是特别为按钮设计的。

也可以参考QHButtonGroup、窗口部件外观和风格、布局管理和组织者.

成员函数文档

QVButtonGroup::QVButtonGroup ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的垂直按钮组。

parent和name参数被传递给QWidget构造函数。

QVButtonGroup::QVButtonGroup ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的垂直按钮组。

parent和name参数被传递给QWidget构造函数。

QVButtonGroup::~QVButtonGroup ()

销毁这个垂直按钮组，删除它的子窗口部件。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qvbuttongroup.h包含文件

qvbuttongroup.h

这里是qvbuttongroup.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qvbuttongroup.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QVButtonGroup class
**
** Created : 990602
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVBUTTONGROUP_H
#define QVBUTTONGROUP_H

#ifndef QT_H
#include "qbuttongroup.h"
#endif // QT_H

#ifndef QT_NO_VBUTTONGROUP

class Q_EXPORT QVButtonGroup : public QButtonGroup
{
    Q_OBJECT
public:
    QVButtonGroup( QWidget* parent=0, const char* name=0 );
    QVButtonGroup( const QString &title, QWidget* parent=0, const char* name=0 );

    ~QVButtonGroup();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QVButtonGroup( const QVButtonGroup & );
    QVButtonGroup &operator=( const QVButtonGroup & );
#endif
};

#endif // QT_NO_VBUTTONGROUP

#endif // QVBUTTONGROUP_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QVButtonGroup成员列表

完整的QVButtonGroup成员列表

这里是QVButtonGroup成员函数的完整列表，包括继承的成员。

  • QVButtonGroup()
  • ~QVButtonGroup()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • clicked()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • count()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • id()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insert()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExclusive()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isRadioButtonExclusive()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • moveFocus()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • pressed()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • released()
  • remove()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setButton()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExclusive()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setRadioButtonExclusive()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QVGroupBox类

QVGroupBox类参考

QVGroupBox窗口部件把一组窗口部件组织在一个垂直列中。 详情请见……

#include <qvgroupbox.h>

继承了QGroupBox。

所有成员函数的列表。

公有成员

  • QVGroupBox ( QWidget * parent = 0, const char * name = 0 )
  • QVGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )
  • ~QVGroupBox ()

详细描述

QVGroupBox窗口部件把一组窗口部件组织在一个垂直列中。

QVGroupBox是一个在QGroupBox中提供了一个小布局的方便类。可以把它看作适提供了一个框架和标题的QVBox。

也可以参考QHGroupBox、窗口部件外观和风格、布局管理和组织者。

成员函数文档

QVGroupBox::QVGroupBox ( QWidget * parent = 0, const char * name = 0 )

构造一个没有标题的垂直组合框。

parent和name参数被传递给QWidget构造函数。

QVGroupBox::QVGroupBox ( const QString & title, QWidget * parent = 0, const char * name = 0 )

构造一个标题为title的垂直组合框。

parent和name参数被传递给QWidget构造函数。

QVGroupBox::~QVGroupBox ()

销毁这个垂直组合框，删除它的子窗口部件。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qvgroupbox.h包含文件

qvgroupbox.h

这里是qvgroupbox.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/**********************************************************************
** $Id:  qt/qvgroupbox.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QVGroupBox widget class
**
** Created : 990602
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QVGROUPBOX_H
#define QVGROUPBOX_H

#ifndef QT_H
#include "qgroupbox.h"
#endif // QT_H

#ifndef QT_NO_VGROUPBOX

class Q_EXPORT QVGroupBox : public QGroupBox
{
    Q_OBJECT
public:
    QVGroupBox( QWidget* parent=0, const char* name=0 );
    QVGroupBox( const QString &title, QWidget* parent=0, const char* name=0 );

    ~QVGroupBox();

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QVGroupBox( const QVGroupBox & );
    QVGroupBox &operator=( const QVGroupBox & );
#endif
};

#endif // QT_NO_VGROUPBOX

#endif // QVGROUPBOX_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QVGroupBox成员列表

完整的QVGroupBox成员列表

这里是QVGroupBox成员函数的完整列表，包括继承的成员。

  • QVGroupBox()
  • ~QVGroupBox()
  • acceptDrops()
  • addSpace()
  • adjustSize()
  • alignment()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • columns()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • insideMargin()
  • insideSpacing()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAlignment()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setColumnLayout()
  • setColumns()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setInsideMargin()
  • setInsideSpacing()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWaitCondition类

QWaitCondition类参考

QWaitCondition类是线程之间允许等待/唤醒的条件。 详情请见……

#include <qwaitcondition.h>

所有成员函数的列表。

公有成员

  • QWaitCondition ()
  • virtual ~QWaitCondition ()
  • bool wait ( unsigned long time = ULONG_MAX )
  • bool wait ( QMutex * mutex, unsigned long time = ULONG_MAX )
  • void wakeOne ()
  • void wakeAll ()

详细描述

QWaitCondition类是线程之间允许等待/唤醒的条件。

QWaitConditions允许一个线程告诉其它线程某种条件已经满足，一个或多个线程可以等待一个由wakeOne()或wakeAll()设定的条件QWaitCondition。使用wakeOne()会唤醒一种随机选择的事件或者wakeAll()会把它们全部唤醒。比如，假定每次用户按下一个键，我们有三个任务要同时执行，每个任务都可以放到一个线程中，每个线程的run()都应该是这样：

  QWaitCondition key_pressed;

  for (;;) {
     key_pressed.wait(); // 这是一个QWaitCondition全局变量
     // 键被按下，做一些有趣的事
     do_something();
  }

第四个线程回去读键按下并且每当它接收到一个的时候唤醒其它三个线程，就像这样：

  QWaitCondition key_pressed;

  for (;;) {
     getchar();
     // 在key_pressed中导致引起任何一个线程。wait()将会从这个方法中返回并继续执行
     key_pressed.wakeAll();
  }

注意这三个线程被唤醒的顺序是未定义的，并且当键被按下时，这些线程中的一个或多个还在do_something()，它们将不会被唤醒（因为它们现在没有等待条件变量）并且这个任务也就不会针对这次按键执行操作。这种情况是可以避免得，比如，就像下面这样做：

  QMutex mymutex;
  QWaitCondition key_pressed;
  int mycount=0;

  // 工人线程代码
  for (;;) {
     key_pressed.wait(); // 这是一个QWaitCondition全局变量
     mymutex.lock();
     mycount++;
     mymutex.unlock();
     do_something();
     mymutex.lock();
     mycount--;
     mymutex.unlock();
  }

  // 读取按键线程代码
  for (;;) {
     getchar();
     mymutex.lock();
     // 睡眠，直到没有忙碌的工作线程才醒来。
     while( count > 0 ) {
       mymutex.unlock();
       sleep( 1 );
       mymutex.lock();
     }
     mymutex.unlock();
     key_pressed.wakeAll();
  }

互斥量是必须的，因为两个线程试图同时对同一个变量进行修改的结果是不可预知的。

也可以参考环境类和线程类。

成员函数文档

QWaitCondition::QWaitCondition ()

构造一个新的事件信号传输，比如，等待条件，对象。

QWaitCondition::~QWaitCondition () [虚]

删除这个事件信号传输，比如，等待条件，对象。

bool QWaitCondition::wait ( unsigned long time = ULONG_MAX )

在线程事件对象上等待。调用这个的线程将会阻塞，直到下列条件之一满足时才醒来：
  • 另一个线程使用wakeOne()或wakeAll()传输信号给它。在这种情况下，这个函数将返回真。
  • time毫秒过去了。如果time为ULONG_MAX（默认值），那么这个等待将永远不会超时（这个事件必须被传输）。如果等待的事件超时，这个函数将会返回假。

也可以参考wakeOne()和wakeAll()。

bool QWaitCondition::wait ( QMutex * mutex, unsigned long time = ULONG_MAX )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

释放锁定的mutex并且在线程事件对象上等待。mutex必须由调用线程初始锁定的。如果mutex没有在锁定状态，这个函数立即返回。如果mutex是一个递归互斥量，这个函数立即返回。mutex将被解锁，并且调用线程将会阻塞，直到下列条件之一满足时才醒来：

  • 另一个线程使用wakeOne()或wakeAll()传输信号给它。在这种情况下，这个函数将返回真。
  • time毫秒过去了。如果time为ULONG_MAX（默认值），那么这个等待将永远不会超时（这个事件必须被传输）。如果等待的事件超时，这个函数将会返回假。

互斥量将以同样的锁定状态返回。这个函数提供的是允许从锁定状态到等待状态的原子转换。

也可以参考wakeOne()和wakeAll()。

void QWaitCondition::wakeAll ()

这将会唤醒所有等待QWaitCondition的线程。这些线程被唤醒的顺序依赖于操组系统的调度策略，并且不能被控制或预知。

也可以参考wakeOne()。

void QWaitCondition::wakeOne ()

这将会唤醒所有等待QWaitCondition的线程中的一个线程。这个被唤醒的线程依赖于操组系统的调度策略，并且不能被控制或预知。

也可以参考wakeAll()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qwaitcondition.h包含文件

qwaitcondition.h

这里是qwaitcondition.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id$
**
** Definition of QWaitCondition class
**
** Created : 931107
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the tools module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWAITCONDITION_H
#define QWAITCONDITION_H

#ifndef QT_H
#include "qglobal.h"
#endif // QT_H

#if defined(QT_THREAD_SUPPORT)

#include <limits.h>

class QWaitConditionPrivate;
class QMutex;

class Q_EXPORT QWaitCondition
{
public:
    QWaitCondition();
    virtual ~QWaitCondition();

    // default argument causes thread to block indefinately
    bool wait( unsigned long time = ULONG_MAX );
    bool wait( QMutex *mutex, unsigned long time = ULONG_MAX );

    void wakeOne();
    void wakeAll();

private:
    QWaitConditionPrivate * d;

#if defined(Q_DISABLE_COPY)
    QWaitCondition( const QWaitCondition & );
    QWaitCondition &operator=( const QWaitCondition & );
#endif
};

#endif

#endif

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWaitCondition成员列表

完整的QWaitCondition成员列表

这里是QWaitCondition成员函数的完整列表，包括继承的成员。

  • QWaitCondition()
  • ~QWaitCondition()
  • wait()
  • wakeAll()
  • wakeOne()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Simple HTML Browser

Header file:

/****************************************************************************
** $Id:  qt/qwerty.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef QWERTY_H
#define QWERTY_H

#include <qwidget.h>
#include <qmenubar.h>
#include <qmultilineedit.h>
#include <qprinter.h>

class Editor : public QWidget
{
    Q_OBJECT
public:
    Editor( QWidget *parent=0, const char *name="qwerty" );
   ~Editor();

    void load( const QString& fileName, int code=-1 );

public slots:
    void newDoc();
    void load();
    bool save();
    void print();
    void addEncoding();
    void toUpper();
    void toLower();
    void font();
protected:
    void resizeEvent( QResizeEvent * );
    void closeEvent( QCloseEvent * );

private slots:
    void saveAsEncoding( int );
    void openAsEncoding( int );
    void textChanged();

private:
    bool saveAs( const QString& fileName, int code=-1 );
    void rebuildCodecList();
    QMenuBar       *m;
    QMultiLineEdit *e;
#ifndef QT_NO_PRINTER
    QPrinter        printer;
#endif
    QPopupMenu     *save_as;
    QPopupMenu     *open_as;
    bool changed;
};

#endif // QWERTY_H

Implementation:

/****************************************************************************
** $Id:  qt/qwerty.cpp   3.0.5   edited Jan 29 13:47 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "qwerty.h"
#include <qapplication.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qpopupmenu.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qmessagebox.h>
#include <qpaintdevicemetrics.h>
#include <qptrlist.h>
#include <qfontdialog.h>

#include <qtextcodec.h>

const bool no_writing = FALSE;

static QPtrList<QTextCodec> *codecList = 0;

enum { Uni = 0, MBug = 1, Lat1 = 2, Local = 3, Guess = 4, Codec = 5 };

Editor::Editor( QWidget * parent , const char * name )
    : QWidget( parent, name, WDestructiveClose )
{
    m = new QMenuBar( this, "menu" );

    QPopupMenu * file = new QPopupMenu();
    Q_CHECK_PTR( file );
    m->insertItem( "&File", file );

    file->insertItem( "&New",   this, SLOT(newDoc()),   ALT+Key_N );
    file->insertItem( "&Open...",  this, SLOT(load()),     ALT+Key_O );
    file->insertItem( "&Save...",  this, SLOT(save()),     ALT+Key_S );
    file->insertSeparator();
    open_as = new QPopupMenu();
    file->insertItem( "Open &As",  open_as );
    save_as = new QPopupMenu();
    file->insertItem( "Sa&ve As",  save_as );
    file->insertItem( "Add &Encoding", this, SLOT(addEncoding()) );
#ifndef QT_NO_PRINTER
    file->insertSeparator();
    file->insertItem( "&Print...", this, SLOT(print()),    ALT+Key_P );
#endif
    file->insertSeparator();
    file->insertItem( "&Close", this, SLOT(close()),ALT+Key_W );
    file->insertItem( "&Quit",  qApp, SLOT(closeAllWindows()),     ALT+Key_Q );

    connect( save_as, SIGNAL(activated(int)), this, SLOT(saveAsEncoding(int)) );
    connect( open_as, SIGNAL(activated(int)), this, SLOT(openAsEncoding(int)) );
    rebuildCodecList();

    QPopupMenu * edit = new QPopupMenu();
    Q_CHECK_PTR( edit );
    m->insertItem( "&Edit", edit );

    edit->insertItem( "To &Uppercase",   this, SLOT(toUpper()),   ALT+Key_U );
    edit->insertItem( "To &Lowercase",   this, SLOT(toLower()),   ALT+Key_L );
#ifndef QT_NO_FONTDIALOG
    edit->insertSeparator();
    edit->insertItem( "&Select Font" ,   this, SLOT(font()),     ALT+Key_T );
#endif
    changed = FALSE;
    e = new QMultiLineEdit( this, "editor" );
    connect( e, SIGNAL( textChanged() ), this, SLOT( textChanged() ) );

    // We use Unifont - if you have it installed you'll see all
    // Unicode character glyphs.
    //
    // Unifont only comes in one pixel size, so we cannot let
    // it change pixel size as the display DPI changes.
    //
    QFont unifont("unifont",16,50); unifont.setPixelSize(16);
    e->setFont( unifont );

    e->setFocus();
}

Editor::~Editor()
{
}

void Editor::font()
{
#ifndef QT_NO_FONTDIALOG
    bool ok;
    QFont f = QFontDialog::getFont( &ok, e->font() );
    if ( ok ) {
        e->setFont( f );
    }
#endif
}

void Editor::rebuildCodecList()
{
    delete codecList;
    codecList = new QPtrList<QTextCodec>;
    QTextCodec *codec;
    int i;
    for (i = 0; (codec = QTextCodec::codecForIndex(i)); i++)
        codecList->append( codec );
    int n = codecList->count();
    for (int pm=0; pm<2; pm++) {
        QPopupMenu* menu = pm ? open_as : save_as;
        menu->clear();
        QString local = "Local (";
        local += QTextCodec::codecForLocale()->name();
        local += ")";
        menu->insertItem( local, Local );
        menu->insertItem( "Unicode", Uni );
        menu->insertItem( "Latin1", Lat1 );
        menu->insertItem( "Microsoft Unicode", MBug );
        if ( pm )
            menu->insertItem( "[guess]", Guess );
        for ( i = 0; i < n; i++ )
            menu->insertItem( codecList->at(i)->name(), Codec + i );
    }
}

void Editor::newDoc()
{
    Editor *ed = new Editor;
    if ( qApp->desktop()->size().width() < 450
         || qApp->desktop()->size().height() < 450 ) {
        ed->showMaximized();
    } else {
        ed->resize( 400, 400 );
        ed->show();
    }
}

void Editor::load()
{
#ifndef QT_NO_FILEDIALOG
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() )
        load( fn, -1 );
#endif
}

void Editor::load( const QString& fileName, int code )
{
    QFile f( fileName );
    if ( !f.open( IO_ReadOnly ) )
        return;

    e->setAutoUpdate( FALSE );

    QTextStream t(&f);
    if ( code >= Codec )
        t.setCodec( codecList->at(code-Codec) );
    else if ( code == Uni )
        t.setEncoding( QTextStream::Unicode );
    else if ( code == MBug )
        t.setEncoding( QTextStream::UnicodeReverse );
    else if ( code == Lat1 )
        t.setEncoding( QTextStream::Latin1 );
    else if ( code == Guess ) {
        QFile f(fileName);
        f.open(IO_ReadOnly);
        char buffer[256];
        int l = 256;
        l=f.readBlock(buffer,l);
        QTextCodec* codec = QTextCodec::codecForContent(buffer, l);
        if ( codec ) {
            QMessageBox::information(this,"Encoding",QString("Codec: ")+codec->name());
            t.setCodec( codec );
        }
    }
    e->setText( t.read() );
    f.close();

    e->setAutoUpdate( TRUE );
    e->repaint();
    setCaption( fileName );

    changed = FALSE;
}

void Editor::openAsEncoding( int code )
{
#ifndef QT_NO_FILEDIALOG
    //storing filename (proper save) is left as an exercise...
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() )
        (void) load( fn, code );
#endif
}

bool Editor::save()
{
#ifndef QT_NO_FILEDIALOG
    //storing filename (proper save) is left as an exercise...
    QString fn = QFileDialog::getSaveFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() )
        return saveAs( fn );
    return FALSE;
#endif
}

void Editor::saveAsEncoding( int code )
{
#ifndef QT_NO_FILEDIALOG
    //storing filename (proper save) is left as an exercise...
    QString fn = QFileDialog::getSaveFileName( QString::null, QString::null, this );
    if ( !fn.isEmpty() )
        (void) saveAs( fn, code );
#endif
}

void Editor::addEncoding()
{
#ifndef QT_NO_FILEDIALOG
    QString fn = QFileDialog::getOpenFileName( QString::null, "*.map", this );
    if ( !fn.isEmpty() ) {
        QFile f(fn);
        if (f.open(IO_ReadOnly)) {
            if (QTextCodec::loadCharmap(&f)) {
                rebuildCodecList();
            } else {
                QMessageBox::warning(0,"Charmap error",
                    "The file did not contain a valid charmap.\n\n"
                    "A charmap file should look like this:\n"
                       "  <code_set_name> thename\n"
                       "  <escape_char> /\n"
                       "  % alias thealias\n"
                       "  CHARMAP\n"
                       "  <tokenname> /x12 <U3456>\n"
                       "  <tokenname> /xAB/x12 <U0023>\n"
                       "  ...\n"
                       "  END CHARMAP\n"
                );
            }
        }
    }
#endif
}

bool Editor::saveAs( const QString& fileName, int code )
{
    QFile f( fileName );
    if ( no_writing || !f.open( IO_WriteOnly ) ) {
        QMessageBox::warning(this,"I/O Error",
                    QString("The file could not be opened.\n\n")
                        +fileName);
        return FALSE;
    }
    QTextStream t(&f);
    if ( code >= Codec )
        t.setCodec( codecList->at(code-Codec) );
    else if ( code == Uni )
        t.setEncoding( QTextStream::Unicode );
    else if ( code == MBug )
        t.setEncoding( QTextStream::UnicodeReverse );
    else if ( code == Lat1 )
        t.setEncoding( QTextStream::Latin1 );
    t << e->text();
    f.close();
    setCaption( fileName );
    changed = FALSE;
    return TRUE;
}

void Editor::print()
{
#ifndef QT_NO_PRINTER
    if ( printer.setup(this) ) {                // opens printer dialog
        printer.setFullPage(TRUE);              // we'll set our own margins
        QPainter p;
        p.begin( &printer );                    // paint on printer
        p.setFont( e->font() );
        QFontMetrics fm = p.fontMetrics();
        QPaintDeviceMetrics metrics( &printer ); // need width/height
                                                 // of printer surface
        const int MARGIN = metrics.logicalDpiX() / 2; // half-inch margin
        int yPos        = MARGIN;               // y position for each line

        for( int i = 0 ; i < e->numLines() ; i++ ) {
            if ( printer.aborted() )
                break;
            if ( yPos + fm.lineSpacing() > metrics.height() - MARGIN ) {
                // no more room on this page
                if ( !printer.newPage() )          // start new page
                    break;                           // some error
                yPos = MARGIN;                   // back to top of page
            }
            p.drawText( MARGIN, yPos, metrics.width() - 2*MARGIN,
                        fm.lineSpacing(), ExpandTabs, e->textLine( i ) );
            yPos += fm.lineSpacing();
        }
        p.end();                                // send job to printer
    }
#endif
}

void Editor::resizeEvent( QResizeEvent * )
{
    if ( e && m )
        e->setGeometry( 0, m->height(), width(), height() - m->height() );
}

void Editor::closeEvent( QCloseEvent *event )
{
    event->accept();

    if ( changed ) { // the text has been changed
        switch ( QMessageBox::warning( this, "Qwerty",
                                        "Save changes to Document?",
                                        tr("&Yes"),
                                        tr("&No"),
                                        tr("Cancel"),
                                        0, 2) ) {
        case 0: // yes
            if ( save() )
                event->accept();
            else
                event->ignore();
            break;
        case 1: // no
            event->accept();
            break;
        default: // cancel
            event->ignore();
            break;
        }
    }
}

void Editor::toUpper()
{
    e->setText(e->text().upper());
}

void Editor::toLower()
{
    e->setText(e->text().lower());
}

void Editor::textChanged()
{
    changed = TRUE;
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "qwerty.h"

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

    bool isSmall =  qApp->desktop()->size().width() < 450
                  || qApp->desktop()->size().height() < 450;

    int i;
    for ( i= argc <= 1 ? 0 : 1; i<argc; i++ ) {
        Editor *e = new Editor;
        e->setCaption("Qt Example - QWERTY");
        if ( i > 0 )
            e->load( argv[i] );
        if ( isSmall ) {
            e->showMaximized();
        } else {
            e->resize( 400, 400 );
            e->show();
        }
    }
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    return a.exec();
}

See also Examples.


QWhatsThis类

QWhatsThis类参考

QWhatsThis类提供了任何一个窗口部件的简单描述，比如，回答“这是什么？”的问题。 详情请见……

#include <qwhatsthis.h>

继承了Qt。

所有成员函数的列表。

公有成员

  • QWhatsThis ( QWidget * widget )
  • virtual ~QWhatsThis ()
  • virtual QString text ( const QPoint & )
  • virtual bool clicked ( const QString & href )

静态公有成员

  • void add ( QWidget * widget, const QString & text )
  • void remove ( QWidget * widget )
  • QString textFor ( QWidget * w, const QPoint & pos = QPoint ( ), bool includeParents = FALSE )
  • QToolButton * whatsThisButton ( QWidget * parent )
  • void enterWhatsThisMode ()
  • bool inWhatsThisMode ()
  • void leaveWhatsThisMode ( const QString & text = QString::null, const QPoint & pos = QCursor::pos ( ), QWidget * w = 0 )
  • void display ( const QString & text, const QPoint & pos = QCursor::pos ( ), QWidget * w = 0 )

详细描述

QWhatsThis类提供了任何一个窗口部件的简单描述，比如，回答“这是什么？”的问题。

“这是什么？”帮助是提供给用户关于功能、用法、背景等等不同水平的从短的工具指南到完全的文本浏览帮助窗口的应用程序的在线帮助系统的一部分。

QWhatsThis是当用户询问“这是什么？”时提供的弹出的具有说明性文本的一个单一窗口。这样做的默认方法是把焦点移动到相关窗口部件并且按下Shift+F1。帮助文本就会立即出现，一旦用户做了其它什么事情，它就消失了。

（注意如果其它地方的快捷键是Shift+F1的话，这个机制就不能工作了。）

为了给一个窗口部件添加“这是什么？”文本，你只要对它简单地调用QWhatsThis::add()就可以了。比如，给一个菜单项分配文本，调用QMenuData::setWhatsThis()，对于一个全局快捷键，调用QAccel::setWhatsThis()并且如果你正在使用操作，使用QAction::setWhatsThis()。

这个文本可以是纯文本，也可以是多信息文本。如果你指定了一个多信息文本格式的字符串，它将被使用默认的样式表来显示。这样还可以使用嵌入的图片。详细情况请参考QStyleSheet::defaultSheet()。

        const char * fileOpenText = "<p><img source=\"fileopen\"> "
                         "Click this button to open a <em>new file</em>. <br>"
                         "You can also select the <b>Open</b> command "
                         "from the <b>File</b> menu.</p>";
        QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen",
                              fileOpenAction->iconSet().pixmap() );
        fileOpenAction->setWhatsThis( fileOpenText );

（对于上面的代码更详细的解释请参考具有QAction特征的简单应用程序的排演。）

另一个进入“这是什么？”模式的方法是使用已经由QWhatsThis::whatsThisButton()做好的工具条按钮。通过调用这个上下文帮助按钮（在下面图片中右面的第一个），用户切换到“这是什么？”模式。如果现在你在窗口部件上点击，适当的帮助文本就会被显示。当帮助被给出或者用户按下Esc时，这个模式就离开了。

如果你正在使用QMainWindow，你也可以使用QMainWindow::whatsThis()槽来从菜单项中调用这个模式。

为了更多的控制，你可以为一个特定窗口部件创建一个专用的QWhatsThis对象。通过继承和重新实现QWhatsThis::text()，它可能具有不同的帮助文本，依赖于鼠标点击的位置。通过重新实现QWhatsThis::clicked()，在帮助文本中使用超链接也是可能的。

如果你想手工地控制窗口部件的“这是什么？”的行为，请参考QWidget::customWhatsThis()。

使用QWhatsThis::remove()可以移除这是什么对象，尽管这很少需要，因为当窗口部件被销毁时它会被自动地移除。

也可以参考QToolTip和帮助系统。

成员函数文档

QWhatsThis::QWhatsThis ( QWidget * widget )

为widget构造一个动态的“这是什么？”对象。当被传递的窗口部件被销毁时，这个对象被删除。

当这个窗口部件被用户查询时，这个QWhatsThis的text()函数将会被调用来提供适当的文本，而不是使用由add()提供的文本。

QWhatsThis::~QWhatsThis () [虚]

销毁这个对象并释放任何被分配的资源。

void QWhatsThis::add ( QWidget * widget, const QString & text ) [静态]

为widget添加text作为“这是什么？”帮助。如果这个文本是多信息文本格式（比如，它包含标高），它将被使用默认的样式表QStyleSheet::defaultSheet()来显示。

如果这个窗口部件后来被销毁，这个文本也被销毁，所以它不需要被明显地移除。

也可以参考remove()。

实例：application/application.cpp和mdi/application.cpp。

bool QWhatsThis::clicked ( const QString & href ) [虚]

当用户在“这是什么？”窗口中点击鼠标时，这个虚函数被调用。href是用户所点击的连接，如果没有连接，就是QString::null。

如果函数返回真（默认），“这是什么？”窗口被关闭，否则它仍保留可视。

默认实现是忽略href并且返回真。

void QWhatsThis::display ( const QString & text, const QPoint & pos = QCursor::pos ( ), QWidget * w = 0 ) [静态]

在全局屏幕的帮助窗口中位置pos显示text。

如果窗口部件w不为零并且已经有了自己专有的QWhatsThis对象，当用户在帮助文本的超链接上点击时，这个对象将会接收clicked()消息。

也可以参考QWhatsThis::clicked()。

void QWhatsThis::enterWhatsThisMode () [静态]

进入“这是什么？”模式并且立即返回。

Qt将会安装一个特定的光标并且取代鼠标输入直到用户在某处点击为止。然后它显示任何可以提供的帮助并且切换出“这是什么？”模式。最后，Qt在鼠标左键不再点击的点移除特定光标和帮助窗口，然后回复通常的事件处理。

用户也可以使用Esc键离开“这是什么？”模式。

也可以参考inWhatsThisMode()和leaveWhatsThisMode()。

bool QWhatsThis::inWhatsThisMode () [静态]

如果应用程序在“这是什么？”模式中，返回真，否则返回假。

也可以参考enterWhatsThisMode()和leaveWhatsThisMode()。

void QWhatsThis::leaveWhatsThisMode ( const QString & text = QString::null, const QPoint & pos = QCursor::pos ( ), QWidget * w = 0 ) [静态]

离开“这是什么？”问题模式。

这个函数被支持QWidget::customWhatsThis()的窗口部件内部使用，应用程序通常不会调用它。有一个QPopupMenu这样的窗口部件的实例：菜单还在“这是什么？”模式正常工作，但也为个别的菜单项提供帮助文本。

如果text不是一个零字符串，“这是什么？”帮助窗口将在全局屏幕的位置pos处被显示。如果窗口部件w非零并且它有自己专有的QWhatsThis对象，当用户点击帮助文本中的超链接时，这个对象将收到clicked()消息。

也可以参考inWhatsThisMode()、enterWhatsThisMode()和QWhatsThis::clicked()。

void QWhatsThis::remove ( QWidget * widget ) [静态]

移除和widget相关的“这是什么？”帮助。如果这个窗口部件被销毁，这也会自动发生。

也可以参考add()。

QString QWhatsThis::text ( const QPoint & ) [虚]

虚函数返回这个“这是什么？”对象文档的窗口部件在位置p的文本。如果在这个位置没有“这是什么？”文本，QString::null被返回。

默认实现是返回QString::null。

QString QWhatsThis::textFor ( QWidget * w, const QPoint & pos = QPoint ( ), bool includeParents = FALSE ) [静态]

为窗口部件w返回这是什么的文本，或者如果对于这个窗口部件没有任何“这是什么？”帮助，返回一个零字符串。pos包含鼠标位置，这很有用，例如，如果你已经继承来使文本根据这个位置进行显示。

如果includeParents为真，父窗口部件将也被考虑进去。

也可以参考add()。

QToolButton * QWhatsThis::whatsThisButton ( QWidget * parent ) [静态]

当点击时，创建一个预定义进入“这是什么？”模式的QToolButton。你通常可以使用菜单条作为它的parent。
     (void) QWhatsThis::whatsThisButton( my_help_tool_bar );

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qwhatsthis.h包含文件

qwhatsthis.h

这里是qwhatsthis.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qwhatsthis.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QWhatsThis class
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWHATSTHIS_H
#define QWHATSTHIS_H

#ifndef QT_H
#include "qobject.h"
#endif // QT_H

#ifndef QT_NO_WHATSTHIS

#include "qcursor.h"

class QToolButton;
class QPopupMenu;
class QStyleSheet;

class Q_EXPORT QWhatsThis: public Qt
{
public:
    QWhatsThis( QWidget *);
    virtual ~QWhatsThis();

    virtual QString text( const QPoint & );
    virtual bool clicked( const QString& href );

    // the common static functions
    static void add( QWidget *, const QString &);
    static void remove( QWidget * );
    static QString textFor( QWidget *, const QPoint & pos = QPoint(), bool includeParents = FALSE );

    static QToolButton * whatsThisButton( QWidget * parent );

    static void enterWhatsThisMode();
    static bool inWhatsThisMode();
    static void leaveWhatsThisMode( const QString& = QString::null, const QPoint& pos = QCursor::pos(), QWidget* w = 0 );

    static void display( const QString& text, const QPoint& pos = QCursor::pos(), QWidget* w = 0 );
};

#endif // QT_NO_WHATSTHIS

#endif // QWHATSTHIS_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWhatsThis成员列表

完整的QWhatsThis成员列表

这里是QWhatsThis成员函数的完整列表，包括继承的成员。

  • QWhatsThis()
  • ~QWhatsThis()
  • add()
  • clicked()
  • display()
  • enterWhatsThisMode()
  • inWhatsThisMode()
  • leaveWhatsThisMode()
  • remove()
  • text()
  • textFor()
  • whatsThisButton()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWheelEvent Class

QWheelEvent Class Reference

The QWheelEvent class contains parameters that describe a wheel event. More...

#include <qevent.h>

Inherits QEvent.

List of all member functions.

Public Members

  • QWheelEvent ( const QPoint & pos, int delta, int state, Orientation orient = Vertical )
  • QWheelEvent ( const QPoint & pos, const QPoint & globalPos, int delta, int state, Orientation orient = Vertical )
  • int delta () const
  • const QPoint & pos () const
  • const QPoint & globalPos () const
  • int x () const
  • int y () const
  • int globalX () const
  • int globalY () const
  • ButtonState state () const
  • Orientation orientation () const
  • bool isAccepted () const
  • void accept ()
  • void ignore ()

Detailed Description

The QWheelEvent class contains parameters that describe a wheel event.

Wheel events occur when a mouse wheel is turned while the widget has focus. The rotation distance is provided by delta(). The functions pos() and globalPos() return the mouse pointer location at the time of the event.

A wheel event contains a special accept flag that indicates whether the receiver wants the event. You should call QWheelEvent::accept() if you handle the wheel event; otherwise it will be sent to the parent widget.

The QWidget::setEnable() function can be used to enable or disable mouse and keyboard events for a widget.

The event handler QWidget::wheelEvent() receives wheel events.

See also QMouseEvent, QWidget::grabMouse() and Event Classes.

Member Function Documentation

QWheelEvent::QWheelEvent ( const QPoint & pos, int delta, int state, Orientation orient = Vertical )

Constructs a wheel event object.

The globalPos() is initialized to QCursor::pos(), i.e. pos, which is usually (but not always) right. Use the other constructor if you need to specify the global position explicitly. delta contains the rotation distance, state holds the keyboard modifier flags at the time of the event and orient holds the wheel's orientation.

See also pos(), delta() and state().

QWheelEvent::QWheelEvent ( const QPoint & pos, const QPoint & globalPos, int delta, int state, Orientation orient = Vertical )

Constructs a wheel event object. The position when the event occurred is given in pos and globalPos. delta contains the rotation distance, state holds the keyboard modifier flags at the time of the event and orient holds the wheel's orientation.

See also pos(), globalPos(), delta() and state().

void QWheelEvent::accept ()

Sets the accept flag of the wheel event object.

Setting the accept parameter indicates that the receiver of the event wants the wheel event. Unwanted wheel events are sent to the parent widget.

The accept flag is set by default.

See also ignore().

int QWheelEvent::delta () const

Returns the distance that the wheel is rotated expressed in multiples or divisions of WHEEL_DELTA, which is currently set at 120. A positive value indicates that the wheel was rotated forwards away from the user; a negative value indicates that the wheel was rotated backwards toward the user.

The WHEEL_DELTA constant was set to 120 by the wheel mouse vendors to allow building finer-resolution wheels in the future, including perhaps a freely rotating wheel with no notches. The expectation is that such a device would send more messages per rotation but with a smaller value in each message.

const QPoint & QWheelEvent::globalPos () const

Returns the global position of the mouse pointer at the time of the event. This is important on asynchronous window systems such as X11; whenever you move your widgets around in response to mouse events, globalPos() can differ a lot from the current pointer position QCursor::pos().

See also globalX() and globalY().

int QWheelEvent::globalX () const

Returns the global x-position of the mouse pointer at the time of the event.

See also globalY() and globalPos().

int QWheelEvent::globalY () const

Returns the global y-position of the mouse pointer at the time of the event.

See also globalX() and globalPos().

void QWheelEvent::ignore ()

Clears the accept flag parameter of the wheel event object.

Clearing the accept parameter indicates that the event receiver does not want the wheel event. Unwanted wheel events are sent to the parent widget. The accept flag is set by default.

See also accept().

bool QWheelEvent::isAccepted () const

Returns TRUE if the receiver of the event handles the wheel event; otherwise returns FALSE.

Orientation QWheelEvent::orientation () const

Returns the wheel's orientation.

const QPoint & QWheelEvent::pos () const

Returns the position of the mouse pointer, relative to the widget that received the event.

If you move your widgets around in response to mouse events, use globalPos() instead of this function.

See also x(), y() and globalPos().

ButtonState QWheelEvent::state () const

Returns the keyboard modifier flags of the event.

The returned value is ShiftButton, ControlButton, and AltButton OR'ed together.

int QWheelEvent::x () const

Returns the x-position of the mouse pointer, relative to the widget that received the event.

See also y() and pos().

int QWheelEvent::y () const

Returns the y-position of the mouse pointer, relative to the widget that received the event.

See also x() and pos().

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


QWheelEvent Member List

Complete Member List for QWheelEvent

This is the complete list of member functions for QWheelEvent, including inherited members.

  • QWheelEvent()
  • accept()
  • delta()
  • globalPos()
  • globalX()
  • globalY()
  • ignore()
  • isAccepted()
  • orientation()
  • pos()
  • spontaneous()
  • state()
  • type()
  • x()
  • y()


QWidget类

QWidget类参考

QWidget类是所有用户界面对象的基类。 详情请见……

#include <qwidget.h>

继承QObject和QPaintDevice。

被QButton、QFrame、QDialog、QComboBox、QDataBrowser、QDataView、QDateTimeEdit、QDesktopWidget、QDial、QDockArea、QGLWidget、QHeader、QMainWindow、QNPWidget、QScrollBar、QSizeGrip、QSlider、QSpinBox、QStatusBar、QTabBar、QTabWidget、QWorkspace和QXtWidget继承。

所有成员函数的列表。

公有成员

  • QWidget ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )
  • ~QWidget ()
  • WId winId () const
  • QStyle & style () const
  • void setStyle ( QStyle * style )
  • QStyle * setStyle ( const QString & style )
  • bool isTopLevel () const
  • bool isDialog () const
  • bool isPopup () const
  • bool isDesktop () const
  • bool isModal () const
  • bool isEnabled () const
  • bool isEnabledTo ( QWidget * ancestor ) const
  • bool isEnabledToTLW () const (obsolete)
  • QRect frameGeometry () const
  • const QRect & geometry () const
  • int x () const
  • int y () const
  • QPoint pos () const
  • QSize frameSize () const
  • QSize size () const
  • int width () const
  • int height () const
  • QRect rect () const
  • QRect childrenRect () const
  • QRegion childrenRegion () const
  • QSize minimumSize () const
  • QSize maximumSize () const
  • int minimumWidth () const
  • int minimumHeight () const
  • int maximumWidth () const
  • int maximumHeight () const
  • void setMinimumSize ( const QSize & )
  • virtual void setMinimumSize ( int minw, int minh )
  • void setMaximumSize ( const QSize & )
  • virtual void setMaximumSize ( int maxw, int maxh )
  • void setMinimumWidth ( int minw )
  • void setMinimumHeight ( int minh )
  • void setMaximumWidth ( int maxw )
  • void setMaximumHeight ( int maxh )
  • QSize sizeIncrement () const
  • void setSizeIncrement ( const QSize & )
  • virtual void setSizeIncrement ( int w, int h )
  • QSize baseSize () const
  • void setBaseSize ( const QSize & )
  • void setBaseSize ( int basew, int baseh )
  • void setFixedSize ( const QSize & s )
  • void setFixedSize ( int w, int h )
  • void setFixedWidth ( int w )
  • void setFixedHeight ( int h )
  • QPoint mapToGlobal ( const QPoint & pos ) const
  • QPoint mapFromGlobal ( const QPoint & pos ) const
  • QPoint mapToParent ( const QPoint & pos ) const
  • QPoint mapFromParent ( const QPoint & pos ) const
  • QPoint mapTo ( QWidget * parent, const QPoint & pos ) const
  • QPoint mapFrom ( QWidget * parent, const QPoint & pos ) const
  • QWidget * topLevelWidget () const
  • BackgroundMode backgroundMode () const
  • virtual void setBackgroundMode ( BackgroundMode )
  • void setBackgroundMode ( BackgroundMode m, BackgroundMode visual )
  • const QColor & foregroundColor () const
  • const QColor & eraseColor () const
  • virtual void setEraseColor ( const QColor & color )
  • const QPixmap * erasePixmap () const
  • virtual void setErasePixmap ( const QPixmap & pixmap )
  • const QColorGroup & colorGroup () const
  • const QPalette & palette () const
  • bool ownPalette () const
  • virtual void setPalette ( const QPalette & )
  • void unsetPalette ()
  • const QColor & paletteForegroundColor () const
  • void setPaletteForegroundColor ( const QColor & )
  • const QColor & paletteBackgroundColor () const
  • virtual void setPaletteBackgroundColor ( const QColor & )
  • const QPixmap * paletteBackgroundPixmap () const
  • virtual void setPaletteBackgroundPixmap ( const QPixmap & )
  • const QBrush & backgroundBrush () const
  • QFont font () const
  • bool ownFont () const
  • virtual void setFont ( const QFont & )
  • void unsetFont ()
  • QFontMetrics fontMetrics () const
  • QFontInfo fontInfo () const
  • const QCursor & cursor () const
  • bool ownCursor () const
  • virtual void setCursor ( const QCursor & )
  • virtual void unsetCursor ()
  • QString caption () const
  • const QPixmap * icon () const
  • QString iconText () const
  • bool hasMouseTracking () const
  • bool hasMouse () const
  • virtual void setMask ( const QBitmap & bitmap )
  • virtual void setMask ( const QRegion & region )
  • void clearMask ()
  • const QColor & backgroundColor () const (obsolete)
  • virtual void setBackgroundColor ( const QColor & c ) (obsolete)
  • const QPixmap * backgroundPixmap () const (obsolete)
  • virtual void setBackgroundPixmap ( const QPixmap & pm ) (obsolete)
  • enum FocusPolicy { NoFocus = 0, TabFocus = 0x1, ClickFocus = 0x2, StrongFocus = 0x3, WheelFocus = 0x7 }
  • bool isActiveWindow () const
  • virtual void setActiveWindow ()
  • bool isFocusEnabled () const
  • FocusPolicy focusPolicy () const
  • virtual void setFocusPolicy ( FocusPolicy )
  • bool hasFocus () const
  • virtual void setFocusProxy ( QWidget * w )
  • QWidget * focusProxy () const
  • void grabMouse ()
  • void grabMouse ( const QCursor & cursor )
  • void releaseMouse ()
  • void grabKeyboard ()
  • void releaseKeyboard ()
  • bool isUpdatesEnabled () const
  • virtual bool close ( bool alsoDelete )
  • bool isVisible () const
  • bool isVisibleTo ( QWidget * ancestor ) const
  • bool isVisibleToTLW () const (obsolete)
  • QRect visibleRect () const
  • bool isHidden () const
  • bool isMinimized () const
  • bool isMaximized () const
  • virtual QSize sizeHint () const
  • virtual QSize minimumSizeHint () const
  • virtual QSizePolicy sizePolicy () const
  • virtual void setSizePolicy ( QSizePolicy )
  • virtual int heightForWidth ( int w ) const
  • virtual void adjustSize ()
  • QLayout * layout () const
  • void updateGeometry ()
  • virtual void reparent ( QWidget * parent, WFlags f, const QPoint & p, bool showIt = FALSE )
  • void reparent ( QWidget * parent, const QPoint & p, bool showIt = FALSE )
  • void recreate ( QWidget * parent, WFlags f, const QPoint & p, bool showIt = FALSE ) (obsolete)
  • void erase ()
  • void erase ( int x, int y, int w, int h )
  • void erase ( const QRect & r )
  • void erase ( const QRegion & reg )
  • void scroll ( int dx, int dy )
  • void scroll ( int dx, int dy, const QRect & r )
  • void drawText ( int x, int y, const QString & str )
  • void drawText ( const QPoint & pos, const QString & str )
  • QWidget * focusWidget () const
  • QRect microFocusHint () const
  • bool acceptDrops () const
  • virtual void setAcceptDrops ( bool on )
  • virtual void setAutoMask ( bool )
  • bool autoMask () const
  • enum BackgroundOrigin { WidgetOrigin, ParentOrigin, WindowOrigin }
  • virtual void setBackgroundOrigin ( BackgroundOrigin )
  • BackgroundOrigin backgroundOrigin () const
  • virtual bool customWhatsThis () const
  • QWidget * parentWidget ( bool sameWindow = FALSE ) const
  • WFlags testWFlags ( WFlags f ) const
  • QWidget * childAt ( int x, int y, bool includeThis = FALSE ) const
  • QWidget * childAt ( const QPoint & p, bool includeThis = FALSE ) const
  • void setPalette ( const QPalette & p, bool ) (obsolete)
  • void setFont ( const QFont & f, bool ) (obsolete)

公有槽

  • virtual void setEnabled ( bool )
  • void setDisabled ( bool disable )
  • virtual void setCaption ( const QString & )
  • virtual void setIcon ( const QPixmap & )
  • virtual void setIconText ( const QString & )
  • virtual void setMouseTracking ( bool enable )
  • virtual void setFocus ()
  • void clearFocus ()
  • virtual void setUpdatesEnabled ( bool enable )
  • void update ()
  • void update ( int x, int y, int w, int h )
  • void update ( const QRect & r )
  • void repaint ()
  • void repaint ( bool erase )
  • void repaint ( int x, int y, int w, int h, bool erase = TRUE )
  • void repaint ( const QRect & r, bool erase = TRUE )
  • void repaint ( const QRegion & reg, bool erase = TRUE )
  • virtual void show ()
  • virtual void hide ()
  • void iconify () (obsolete)
  • virtual void showMinimized ()
  • virtual void showMaximized ()
  • void showFullScreen ()
  • virtual void showNormal ()
  • virtual void polish ()
  • void constPolish () const
  • bool close ()
  • void raise ()
  • void lower ()
  • void stackUnder ( QWidget * w )
  • virtual void move ( int x, int y )
  • void move ( const QPoint & )
  • virtual void resize ( int w, int h )
  • void resize ( const QSize & )
  • virtual void setGeometry ( int x, int y, int w, int h )
  • virtual void setGeometry ( const QRect & )

静态公有成员

  • void setTabOrder ( QWidget * first, QWidget * second )
  • QWidget * mouseGrabber ()
  • QWidget * keyboardGrabber ()
  • QWidget * find ( WId id )

属性

  • bool acceptDrops - 窗口部件中放下事件是否有效
  • bool autoMask - 窗口部件中自动面具特征是否有效
  • QBrush backgroundBrush - 窗口部件的背景画刷 （只读）
  • BackgroundMode backgroundMode - 绘制窗口部件背景所使用的颜色模式
  • BackgroundOrigin backgroundOrigin - 窗口部件的背景的原点
  • QSize baseSize - 窗口部件的基础大小
  • QString caption - 窗口标题
  • QRect childrenRect - 窗口部件的子对象的边界矩形 （只读）
  • QRegion childrenRegion - 窗口部件的子对象所占用的组合区域 （只读）
  • QColorGroup colorGroup - 窗口部件调色板的当前颜色组 （只读）
  • QCursor cursor - 窗口部件的光标外形
  • bool customWhatsThis - 窗口部件是否手动处理“这是什么”的帮助 （只读）
  • bool enabled - 窗口部件是否有效
  • bool focus - 窗口部件（或者它的焦点代理）是否得到键盘输入焦点 （只读）
  • bool focusEnabled - 窗口部件是否接收键盘焦点 （只读）
  • FocusPolicy focusPolicy - 窗口部件接收键盘焦点的策略
  • QFont font - 窗口部件当前的字体集
  • QRect frameGeometry - 相对于它的父对象包含任何窗口框架的窗口部件的几何形状 （只读）
  • QSize frameSize - 包含任何窗口框架的窗口部件的大小 （只读）
  • QRect geometry - 相对于它的父对象不包括窗口框架的窗口部件的几何形状
  • int height - 不包括窗口框架的窗口部件的高度 （只读）
  • bool hidden - 窗口部件是否明确地隐藏 （只读）
  • QPixmap icon - 窗口部件图标像素映射
  • QString iconText - 窗口部件图标文本
  • bool isActiveWindow - 窗口部件或者它的一个子对象是否是活动窗口 （只读）
  • bool isDesktop - 窗口部件是否是桌面窗口部件，比如，代表桌面 （只读）
  • bool isDialog - 窗口部件是否是对话框窗口部件 （只读）
  • bool isModal - 窗口部件是否是模式窗口部件 （只读）
  • bool isPopup - 窗口部件是否是弹出窗口部件 （只读）
  • bool isTopLevel - 窗口部件是否是顶级窗口部件 （只读）
  • int maximumHeight - 窗口部件的最大高度
  • QSize maximumSize - 窗口部件的最大大小
  • int maximumWidth - 窗口部件的最大宽度
  • QRect microFocusHint - 窗口部件的当前设置的微焦点提示 （只读）
  • bool minimized - 窗口部件是否是最小化的（变为图标了） （只读）
  • int minimumHeight - 窗口部件的最小高度
  • QSize minimumSize - 窗口部件的最小大小
  • QSize minimumSizeHint - 建议的窗口部件最小大小 （只读）
  • int minimumWidth - 窗口部件的最小宽度
  • bool mouseTracking - 窗口部件跟踪鼠标是否生效
  • bool ownCursor - 窗口部件是否使用它自己的光标 （只读）
  • bool ownFont - 窗口部件是否使用它自己的字体 （只读）
  • bool ownPalette - 窗口部件是否使用它自己的调色板 （只读）
  • QPalette palette - 窗口部件的调色板
  • QColor paletteBackgroundColor - 窗口部件的背景色
  • QPixmap paletteBackgroundPixmap - 窗口部件的背景像素映射
  • QColor paletteForegroundColor - 窗口部件的前景色
  • QPoint pos - 窗口部件在它的父窗口部件中的位置
  • QRect rect - 不包含任何窗口框架的窗口部件的内部几何形状 （只读）
  • QSize size - 不包含任何窗口框架的窗口部件的大小
  • QSize sizeHint - 建议的窗口部件大小 （只读）
  • QSize sizeIncrement - 窗口部件的大小增量
  • QSizePolicy sizePolicy - 窗口部件的默认布局行为
  • bool underMouse - 窗口部件是否在鼠标光标下 （只读）
  • bool updatesEnabled - 更新是否生效
  • bool visible - 窗口部件是否可视 （只读）
  • QRect visibleRect - 窗口部件的当前可视矩形 （只读）
  • int width - 不包含任何窗口框架的窗口部件宽度 （只读）
  • int x - 相对于它的父对象包含任何窗口框架的窗口部件的x坐标 （只读）
  • int y - 相对于它的父对象包含任何窗口框架的窗口部件的y坐标 （只读）

保护成员

  • virtual bool event ( QEvent * e )
  • virtual void mousePressEvent ( QMouseEvent * e )
  • virtual void mouseReleaseEvent ( QMouseEvent * e )
  • virtual void mouseDoubleClickEvent ( QMouseEvent * e )
  • virtual void mouseMoveEvent ( QMouseEvent * e )
  • virtual void wheelEvent ( QWheelEvent * e )
  • virtual void keyPressEvent ( QKeyEvent * e )
  • virtual void keyReleaseEvent ( QKeyEvent * e )
  • virtual void focusInEvent ( QFocusEvent * )
  • virtual void focusOutEvent ( QFocusEvent * )
  • virtual void enterEvent ( QEvent * )
  • virtual void leaveEvent ( QEvent * )
  • virtual void paintEvent ( QPaintEvent * )
  • virtual void moveEvent ( QMoveEvent * )
  • virtual void resizeEvent ( QResizeEvent * )
  • virtual void closeEvent ( QCloseEvent * e )
  • virtual void contextMenuEvent ( QContextMenuEvent * e )
  • virtual void imStartEvent ( QIMEvent * e )
  • virtual void imComposeEvent ( QIMEvent * e )
  • virtual void imEndEvent ( QIMEvent * e )
  • virtual void tabletEvent ( QTabletEvent * e )
  • virtual void dragEnterEvent ( QDragEnterEvent * )
  • virtual void dragMoveEvent ( QDragMoveEvent * )
  • virtual void dragLeaveEvent ( QDragLeaveEvent * )
  • virtual void dropEvent ( QDropEvent * )
  • virtual void showEvent ( QShowEvent * )
  • virtual void hideEvent ( QHideEvent * )
  • virtual bool macEvent ( MSG * )
  • virtual bool winEvent ( MSG * )
  • virtual bool x11Event ( XEvent * )
  • virtual bool qwsEvent ( QWSEvent * )
  • virtual void updateMask ()
  • virtual void styleChange ( QStyle & oldStyle )
  • virtual void enabledChange ( bool oldEnabled )
  • virtual void paletteChange ( const QPalette & oldPalette )
  • virtual void fontChange ( const QFont & oldFont )
  • virtual void windowActivationChange ( bool oldActive )
  • virtual int metric ( int m ) const
  • void resetInputContext ()
  • virtual void create ( WId window = 0, bool initializeWindow = TRUE, bool destroyOldWindow = TRUE )
  • virtual void destroy ( bool destroyWindow = TRUE, bool destroySubWindows = TRUE )
  • WFlags getWFlags () const
  • virtual void setWFlags ( WFlags f )
  • void clearWFlags ( WFlags f )
  • virtual bool focusNextPrevChild ( bool next )
  • QFocusData * focusData ()
  • virtual void setKeyCompression ( bool compress )
  • virtual void setMicroFocusHint ( int x, int y, int width, int height, bool text = TRUE, QFont * f = 0 )

详细描述

QWidget类是所有用户界面对象的基类。

窗口部件是用户界面的一个原子：它从窗口系统接收鼠标、键盘和其它事件，并且在屏幕上绘制自己的表现。每一个窗口部件都是矩形，并且它们按Z轴顺序排列的。一个窗口部件可以被它的父窗口部件或者它前面的窗口部件盖住一部分。

QDialog是最普通的顶级窗口。不被嵌入到一个父窗口部件的窗口部件被叫做顶级窗口部件。通常情况下，顶级窗口部件是有框架和标题栏的窗口（尽管如果使用了一定的窗口部件标记，创建顶级窗口部件时也可能没有这些装饰。）在Qt中，QMainWindow和和不同的QDialog的子类是最普通的顶级窗口。

一个没有父窗口部件的窗口部件一直是顶级窗口部件。

非顶级窗口部件是子窗口部件。它们是它们的父窗口部件中的子窗口。你通常不能在视觉角度从它们的父窗口部件中辨别一个子窗口部件。在Qt中的绝大多数其它窗口部件仅仅作为子窗口部件才是有用的。（当然把一个按钮作为或者叫做顶级窗口部件也是可能的，但绝大多数人喜欢把他们的按钮放到其它按钮当中，比如QDialog。）

QWidget有很多成员函数，但是它们中的一些有少量的直接功能：例如，QWidget有一个字体属性，但是它自己从来不用。有很多继承它的子类提供了实际的功能，比如QPushButton、QListBox和QTabDialog等等。

函数分组：

上下文 | 函数
窗口函数 | show()、hide()、raise()、lower()、close()。
顶级窗口 | caption()、setCaption()、icon()、setIcon()、iconText()、setIconText()、isActiveWindow()、setActiveWindow()、showMinimized()、showMaximized()、showFullScreen()、showNormal()。
窗口内容 | update()、repaint()、erase()、scroll()、updateMask()。
几何形状 | pos()、size()、rect()、x()、y()、width()、height()、sizePolicy()、setSizePolicy()、sizeHint()、updateGeometry()、layout()、move()、resize()、setGeometry()、frameGeometry()、geometry()、childrenRect()、adjustSize()、mapFromGlobal()、mapFromParent()、mapToGlobal()、mapToParent()、maximumSize()、minimumSize()、sizeIncrement()、setMaximumSize()、setMinimumSize()、setSizeIncrement()、setBaseSize()、setFixedSize()。
模式 | isVisible()、isVisibleTo()、visibleRect()、isMinimized()、isDesktop()、isEnabled()、isEnabledTo()、isModal()、isPopup()、isTopLevel()、setEnabled()、hasMouseTracking()、setMouseTracking()、isUpdatesEnabled()、setUpdatesEnabled()。
观感 | style()、setStyle()、cursor()、setCursor()、font()、setFont()、palette()、setPalette()、backgroundMode()、setBackgroundMode()、colorGroup()、fontMetrics()、fontInfo()。
键盘焦点函数 | isFocusEnabled()、setFocusPolicy()、focusPolicy()、hasFocus()、setFocus()、clearFocus()、setTabOrder()、setFocusProxy()。
鼠标和键盘捕获 | grabMouse()、releaseMouse()、grabKeyboard()、releaseKeyboard()、mouseGrabber()、keyboardGrabber()。
事件处理器 | event()、mousePressEvent()、mouseReleaseEvent()、mouseDoubleClickEvent()、mouseMoveEvent()、keyPressEvent()、keyReleaseEvent()、focusInEvent()、focusOutEvent()、wheelEvent()、enterEvent()、leaveEvent()、paintEvent()、moveEvent()、resizeEvent()、closeEvent()、dragEnterEvent()、dragMoveEvent()、dragLeaveEvent()、dropEvent()、childEvent()、showEvent()、hideEvent()、customEvent()。
变化处理器 | enabledChange()、fontChange()、paletteChange()、styleChange()、windowActivationChange()。
系统函数 | parentWidget()、topLevelWidget()、reparent()、polish()、winId()、find()、metric()。
这是什么的帮助 | customWhatsThis()。
内部核心函数 | focusNextPrevChild()、wmapper()、clearWFlags()、getWFlags()、setWFlags()、testWFlags()。

每一个窗口部件构造函数接受两个或三个标准参数：

  1. QWidget *parent = 0是新窗口部件的父窗口部件。如果为0（默认），新的窗口部件将是一个顶级窗口部件。如果不是，它将会使parent的一个孩子，并且被parent的几何形状所强迫（除非你指定WType_TopLevel作为窗口部件标记）。
  2. const char *name = 0是新窗口部件的窗口部件名称。你可以使用name()来访问它。窗口部件名称很少被程序员用到，但是对于图形用户界面构造程序，比如Qt设计器，是相当重要的（你可以在Qt设计器中命名一个窗口部件，并且在你的代码中使用这个名字来连接它）。dumpObjectTree()调试函数也使用它。
  3. WFlags f = 0（在可用的情况下）设置窗口部件标记，默认设置对于几乎所有窗口部件都是适用的，但是，举例来说，一个没有窗口系统框架的顶级窗口部件，你必须使用特定的标记。

tictac/tictac.cpp实例程序是一个简单窗口部件的好实例。它包含了一些的事件处理器（就像所有窗口部件所必须的那样）、一些被指定给它的定制处理（就像所有有用的窗口部件做的那样）并且还有一些孩子和联机。它所做的每一件事都响应对应的一个事件：这是到目前为止设计图形用户界面的最普通的方式。

你自己将需要为你的窗口部件提供内容，但是这里是一些简要的运行事件，从最普通的开始：

  • paintEvent() - 只要窗口部件需要被重绘就被调用。每个要显示输出的窗口部件必须实现它并且不在paintEvent()之外在屏幕上绘制是明智的。

  • resizeEvent() - 当窗口部件被重新定义大小时被调用。

  • mousePressEvent() - 当鼠标键被按下时被调用。有六个鼠标相关事件，但是鼠标按下和鼠标释放事件是到目前为止最重要的。当鼠标在窗口部件内或者当它使用grabMouse()来捕获鼠标时，它接收鼠标按下事件。

  • mouseReleaseEvent() - 当鼠标键被释放时被调用。当窗口部件已经接收相应的鼠标按下事件时，它接收鼠标释放事件。这也就是说如果用户在你的窗口部件内按下鼠标，然后拖着鼠标到其它某个地方，然后释放，你的窗口部件接收这个释放事件。这里有一个例外：如果出现在弹出菜单中，当鼠标键被按下时，这个弹出菜单立即会偷掉这个鼠标事件。

  • mouseDoubleClickEvent() - 和它看起来也许不太一样。如果用户双击，窗口部件接收一个鼠标按下事件（如果他们没有拿牢鼠标，也许会出现一个或两个鼠标移动事件）、一个鼠标释放事件并且最终是这个事件。直到你看到第二次点击是否到来之前，不能从一个双击中辨别一个点击。（这是为什么绝大多数图形用户界面图书建议双击是单击的一个扩展，而不是一个不同行为的触发的一个原因。）

如果你的窗口部件仅仅包含子窗口部件，你也许不需要实现任何一个事件处理器。如果你想检测在子窗口部件中的鼠标点击，请在父窗口部件的mousePressEvent()中调用子窗口部件的hasMouse()函数。

接收键盘的窗口部件需要重新实现一些更多的事件处理器：

  • keyPressEvent() - 只要键被按下和当键已经被按下足够长的时间可以自动重复了就被调用。注意如果Tab和Shift+Tab键被用在焦点变换机制中，它们仅仅被传递给窗口部件。为了强迫那些键被你的窗口部件处理，你必须重新实现QWidget::event()。

  • focusInEvent() - 当窗口部件获得键盘焦点（假设你已经调用setFocusPolicy()）时被调用。写得好的窗口部件意味着它们能按照一种清晰但谨慎的方式来获得键盘焦点。

  • focusOutEvent() - 当窗口部件失去键盘焦点时被调用。

一些窗口部件也许需要实现一些不太普通的事件处理器：

  • mouseMoveEvent() - 只要当鼠标键被按下时鼠标移动就会被调用。举例来说，对于拖动，这个很有用。如果你调用setMouseTracking(TRUE)，尽管没有鼠标键被按下，你也会获得鼠标移动事件。（注意这个使用鼠标跟踪的应用程序在低下的X连接下不是很有用。）（也可以参考拖放信息。）

  • keyReleaseEvent() - 只要键被释放和当如果这个键是自动重复的并且被按下一段时间时就被调用。在这种情况下窗口部件接收一个键释放事件并且对于每一个重复立即有一个键按下事件。注意如果Tab和Shift+Tab键被用在焦点变换机制中，它们仅仅被传递给窗口部件。为了强迫那些键被你的窗口部件处理，你必须重新实现QWidget::event()。

  • wheelEvent() -- 当窗口部件拥有焦点时，只要用户转动鼠标滚轮就被调用。

  • enterEvent() - 当鼠标进入这个窗口部件屏幕空间时被调用。（这不包括被这个窗口部件的子窗口部件所拥有的屏幕空间。）

  • leaveEvent() - 当鼠标离开这个窗口部件的屏幕空间时被调用。

  • moveEvent() - 当窗口部件相对于它的父窗口部件已经被移动时被调用。

  • closeEvent() - 当用户关闭窗口部件时（或这当close()被调用时）被调用。

这里还有一些不太明显的事件。它们在qevent.h中被列出并且你需要重新实现event()来处理它们。event()的默认实现处理Tab和Shift+Tab（移动键盘焦点）并且其它绝大多数事件给上面提到的一个或更多的特定处理器。

当实现一个窗口部件时，还有一些更多的事情要考虑。

  • 在构造函数中，在你可能收到一个事件的任何机会之前，请确认尽早地设置你的成员变量。

  • 重新实现sizeHint()在绝大多数情况下都是很有用的并且使用setSizePolicy(),来设置正确的大小策略，这样你的同事可以更容易地设置布局管理器。一个大小策略可以让你为布局管理器提供好的默认情况，这样其它窗口部件可以很容易地包含和管理你的窗口部件。sizeHint()为这个窗口部件说明一个“好的”大小。

  • 如果你的窗口部件是一个顶级窗口部件，setCaption()和setIcon()分别设置标题栏和图标。

也可以参考QEvent、QPainter、QGridLayout、QBoxLayout和抽象窗口部件类。

成员类型文档

QWidget::BackgroundOrigin

这个枚举变量定义了用于绘制窗口部件背景像素映射的原点。

被绘制的像素映射使用：

  • QWidget::WidgetOrigin - 窗口部件的坐标系统。
  • QWidget::ParentOrigin - 父窗口部件的坐标系统。
  • QWidget::WindowOrigin - 顶级窗口的坐标系统。

QWidget::FocusPolicy

这个枚举变量定义了一个窗口部件获得键盘焦点所依据的不同策略。

policy可以是：

  • QWidget::TabFocus - 窗口部件通过Tab获得焦点。
  • QWidget::ClickFocus - 窗口部件通过点击获得焦点。
  • QWidget::StrongFocus - 窗口部件通过Tab和点击获得焦点。
  • QWidget::WheelFocus - 像StrongFocus那样加上窗口部件通过使用鼠标滚轮获得焦点。
  • QWidget::NoFocus - 窗口部件不接收焦点。

成员函数文档

QWidget::QWidget ( QWidget * parent = 0, const char * name = 0, WFlags f = 0 )

构造一个是parent的孩子、名称为name并且窗口部件标记为f的窗口部件。

如果parent为0，新的窗口部件变为顶级窗口。如果parent是另一个窗口部件，这个窗口部件变为parent中的一个子窗口。当它的parent被删除时，新的窗口部件被删除。

name被发送给QObject的构造函数。

窗口部件标记参数f通常为0，但它可以为顶级窗口部件设置自定义的窗口框架（比如，parent必须为0）。为了自定义框架，设置WStyle_Customize标记和任何一个Qt::WidgetFlags进行或运算。

如果你向一个已经可见的窗口部件中添加一个子窗口部件，你必须明显地显示这个孩子来使它可视。

注意Qt的X11版本也许不能在所有的系统上传递风格标记得所有组合。这是因为在X11上，Qt只能询问窗口管理器，并且窗口管理器会覆盖应用程序的设置。在Windows上，Qt可以是指你想要的任何标记。

实例：

    QLabel *splashScreen = new QLabel( 0, "mySplashScreen",
                                WStyle_Customize | WStyle_NoBorder |
                                WStyle_Tool );

QWidget::~QWidget ()

销毁这个窗口部件。

首先这个窗口部件的孩子都被删除。如果这个窗口部件是主窗口部件，应用程序退出。

bool QWidget::acceptDrops () const

如果对于这个窗口部件放下事件生效，返回真，否则返回假。详细情况请参考“acceptDrops”属性。

void QWidget::adjustSize () [虚]

调整窗口部件的大小来适合它的内容。

如果sizeHint()有效（比如，如果大小提示的宽和高都大于等于0）就是用它，否则设置大小为子对象所占用的矩形（所有子窗口部件几何形状的合集）。

也可以参考sizeHint和childrenRect。

实例：xform/xform.cpp。

在QMessageBox中被重新实现。

bool QWidget::autoMask () const

如果对于这个窗口部件自动面具特征生效，返回真，否则返回假。详细情况请参考“autoMask”属性。

const QBrush & QWidget::backgroundBrush () const

返回这个窗口部件的背景画刷。详细情况请参考“backgroundBrush”属性。

const QColor & QWidget::backgroundColor () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

作为替代请使用paletteBackgroundColor()或eraseColor()。

BackgroundMode QWidget::backgroundMode () const

返回绘制窗口部件的背景所使用的颜色功能。详细情况请参考“backgroundMode”属性。

BackgroundOrigin QWidget::backgroundOrigin () const

返回窗口部件的背景的原点。详细情况请参考“backgroundOrigin”属性。

const QPixmap * QWidget::backgroundPixmap () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

作为替代请使用paletteBackgroundPixmap()或者erasePixmap()。

实例：themes/metal.cpp和themes/wood.cpp。

QSize QWidget::baseSize () const

返回窗口部件的继承大小。详细情况请参考“baseSize”属性。

QString QWidget::caption () const

返回窗口标题。详细情况请参考“caption”属性。

QWidget * QWidget::childAt ( int x, int y, bool includeThis = FALSE ) const

返回在窗口部件自己的坐标系统中像素位置(x, y)处的可视的子窗口部件。

如果includeThis为真，并且在(x, y)没有可视的孩子，那么这个窗口部件本身被返回。

QWidget * QWidget::childAt ( const QPoint & p, bool includeThis = FALSE ) const

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

返回在窗口部件自己的坐标系统中点p处的可视的子窗口部件。

如果includeThis为真，并且在p没有可视的孩子，那么这个窗口部件本身被返回。

QRect QWidget::childrenRect () const

返回这个窗口部件的孩子的边界矩形。详细情况请参考“childrenRect”属性。

QRegion QWidget::childrenRegion () const

返回这个窗口部件的孩子所占用的组合区域。详细情况请参考“childrenRegion”属性。

void QWidget::clearFocus () [槽]

从窗口部件中拿走键盘输入焦点。

如果这个窗口部件有激活的焦点，焦点移出事件被发送给这个窗口部件告诉它关于它失去了焦点。

这个窗口部件必须已经为了获得键盘输入焦点使焦点设置生效，比如，它必须调用setFocusPolicy()。

也可以参考focus、setFocus()、focusInEvent()、focusOutEvent()、focusPolicy和QApplication::focusWidget()。

void QWidget::clearMask ()

通过setMask()移除任何面具设置。

也可以参考setMask()。

void QWidget::clearWFlags ( WFlags f ) [保护]

清空窗口部件标记f。

窗口部件标记是Qt::WidgetFlags的组合。

也可以参考testWFlags()、getWFlags()和setWFlags()。

bool QWidget::close () [槽]

关闭这个窗口部件。如果窗口部件被关闭，返回真，否则返回假。

首先它发送给这个窗口部件一个QCloseEvent。如果它接收这个关闭事件，它就被隐藏了。QWidget::closeEvent()的默认实现是接收这个关闭事件。

当最后一个可视的顶级窗口部件被关闭，QApplication::lastWindowClosed()信号被发射。

实例：mdi/application.cpp和popup/popup.cpp。

bool QWidget::close ( bool alsoDelete ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

关闭这个窗口部件。如果窗口部件被关闭，返回真，否则返回假。

如果alsoDelete为真或者这个窗口部件有WDestructiveClose窗口部件标记，这个窗口部件也被删除。这个窗口部件自己可以通过抵制它所收到的QCloseEvent来防止被关闭。

当最后一个可视的顶级窗口部件被关闭，QApplication::lastWindowClosed()信号被发射。

注意关闭QApplication::mainWidget()会终止应用程序。

也可以参考closeEvent()、QCloseEvent、hide()、QApplication::quit()、QApplication::setMainWidget()和QApplication::lastWindowClosed()。

void QWidget::closeEvent ( QCloseEvent * e ) [虚 保护]

这个对于事件e的事件处理器可以在子类中被重新实现来接收窗口部件关闭事件。

默认实现是调用e->accept()，它隐藏这个窗口部件。详细情况请参考QCloseEvent文档。

也可以参考event()、hide(), close()和QCloseEvent。

实例：action/application.cpp、application/application.cpp、i18n/mywidget.cpp、popup/popup.cpp和qwerty/qwerty.cpp。

const QColorGroup & QWidget::colorGroup () const

返回这个窗口部件调色板的当前颜色组。详细情况请参考“colorGroup”属性。

void QWidget::constPolish () const [槽]

确认这个窗口部件通过调用polish()被适当地初始化了。

从像sizeHint()这样依赖于这个窗口部件被初始化的函数中调用constPolish()，并且也可以在show()之前被调用。

警告：不要在窗口部件的构造函数中调用constPolish()。

也可以参考polish()。

void QWidget::contextMenuEvent ( QContextMenuEvent * e ) [虚 保护]

这个对于事件e的事件处理器可以在子类中被重新实现来接收窗口部件上下文菜单事件。

默认实现是调用e->accept()，它拒绝这个上下文事件。详细情况请参考QContextMenuEvent文档。

也可以参考event()和QContextMenuEvent。

void QWidget::create ( WId window = 0, bool initializeWindow = TRUE, bool destroyOldWindow = TRUE ) [虚 保护]

如果window为零，创一个新的窗口部件窗口，否则设置窗口部件参考为window。

如果initializeWindow为真，初始化窗口（设置几何形状等等）。如果initializeWindow为假，没有初始化被执行。这个参数只有在window是有效窗口时才有效。

如果destroyOldWindow为真，销毁就的窗口。如果destroyOldWindow为假，你有责任自己销毁这个窗口（使用平台本地代码）。

QWidget构造函数调用create(0,TRUE,TRUE)来为这个窗口部件创建窗口。

const QCursor & QWidget::cursor () const

返回这个窗口部件的光标外形。详细情况请参考“cursor”属性。

bool QWidget::customWhatsThis () const [虚]

如果这个窗口部件想手工地处理这是什么的帮助，返回真，否则返回假。详细情况请参考“customWhatsThis”属性。

void QWidget::destroy ( bool destroyWindow = TRUE, bool destroySubWindows = TRUE ) [虚 保护]

释放窗口系统资源。如果destroyWindow为真，销毁这个窗口部件窗口。

对于所有的子窗口部件，destroy()循环地调用自己，传递给destroySubWindows一个destroyWindow参数。为了对子窗口部件地销毁进行控制，首先有选择地销毁子窗口部件。

这个函数通常被QWidget析构函数调用。

void QWidget::dragEnterEvent ( QDragEnterEvent * ) [虚 保护]

当一个拖动正在进行并且鼠标进入这个窗口部件，这个事件处理器被调用。

对于在你的应用程序中如何提供拖放的概述请参考拖放文档。

也可以参考QTextDrag、QImageDrag和QDragEnterEvent。

实例：iconview/simple_dd/main.cpp。

void QWidget::dragLeaveEvent ( QDragLeaveEvent * ) [虚 保护]

当一个拖动正在进行并且鼠标离开这个窗口部件，这个事件处理器被调用。

对于在你的应用程序中如何提供拖放的概述请参考拖放文档。

也可以参考QTextDrag、QImageDrag和QDragLeaveEvent。

void QWidget::dragMoveEvent ( QDragMoveEvent * ) [虚 保护]

当一个拖动正在进行并且鼠标进入这个窗口部件，并且只要它在这个窗口部件中移动，这个事件处理器被调用。

对于在你的应用程序中如何提供拖放的概述请参考拖放文档。

也可以参考QTextDrag、QImageDrag和QDragMoveEvent。

void QWidget::drawText ( int x, int y, const QString & str )

在位置(x, y)绘制字符串str。

y位置是文本的基线位置。使用默认字体和默认前景色绘制文本。

这个函数的提供是为了方便。你使用painter替代它一般将会获得更灵活的结果和更快的速度。

也可以参考font、foregroundColor()和QPainter::drawText()。

void QWidget::drawText ( const QPoint & pos, const QString & str )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在位置pos绘制字符串str。

void QWidget::dropEvent ( QDropEvent * ) [虚 保护]

当拖动在这个窗口部件上被放下，这个事件处理器被调用。

对于在你的应用程序中如何提供拖放的概述请参考拖放文档。

也可以参考QTextDrag、QImageDrag和QDropEvent。

实例：iconview/simple_dd/main.cpp。

void QWidget::enabledChange ( bool oldEnabled ) [虚 保护]

isEnabled(). 这个虚函数被setEnabled()调用。oldEnabled是以前的设置，你可以从isEnabled()中得到新的设置。

如果你的窗口部件需要知道什么时候它变为有效或无效，请重新实现这个函数。你将几乎必然要使用update()来更新这个窗口部件。

默认实现是重新绘制窗口部件的可见部分。

也可以参考enabled、enabled、repaint()、update()和visibleRect。

void QWidget::enterEvent ( QEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收窗口部件进入事件。

当鼠标光标进入窗口部件，这个事件被发送给窗口部件。

也可以参考leaveEvent()、mouseMoveEvent()和event()。

void QWidget::erase ( int x, int y, int w, int h )

在窗口部件中擦除指定区域(x, y, w, h)，并不产生绘制事件。

如果w为负数，它被width()-x替换。如果h为负数，它被height()-y替换。

子窗口部件不被影响。

也可以参考repaint()。

void QWidget::erase ()

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本擦除整个窗口部件。

void QWidget::erase ( const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在窗口部件中擦除指定区域r，并不产生绘制事件。

void QWidget::erase ( const QRegion & reg )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在窗口部件中擦除reg定义的区域，并不产生绘制事件。

子窗口部件不被影响。

const QColor & QWidget::eraseColor () const

返回这个窗口部件的擦除色。

也可以参考setEraseColor()、setErasePixmap()和backgroundColor()。

const QPixmap * QWidget::erasePixmap () const

返回这个窗口部件的擦除像素映射。

也可以参考setErasePixmap()和eraseColor()。

bool QWidget::event ( QEvent * e ) [虚 保护]

这是主事件处理器，它处理事件e。你可以在子类中被重新实现整个函数，但是我们建议你使用一个特定的事件处理器来替代它。

主事件首先把事件传递给所有已经被安装的事件过滤器。如果没有过滤器中途截取这个事件，它调用一个特定的事件处理器。

键按下和释放事件被处理得和其它事件不同。event()检查Tab和Shift+Tab并且试图适当地移动焦点。如果没有窗口部件被焦点移入（或者键按下不是Tab或Shift+Tab），event()调用keyPressEvent()。

如果它能够把一个事件传递给没个东西，这个函数就返回真，否则如果没有任何东西想要这个事件，返回假。

也可以参考closeEvent()、focusInEvent()、focusOutEvent()、enterEvent()、keyPressEvent()、keyReleaseEvent()、leaveEvent()、mouseDoubleClickEvent()、mouseMoveEvent()、mousePressEvent()、 mouseReleaseEvent()、moveEvent()、paintEvent()、resizeEvent()、QObject::event()和QObject::timerEvent()。

从QObject中被重新实现。

QWidget * QWidget::find ( WId id ) [静态]

返回窗口标识符/句柄为id的窗口部件指针。

窗口标识符类型依赖于底下的窗口系统，实际定义请参考qwindowdefs.h。如果没有具有这样的标识符的窗口部件，0被返回。

QFocusData * QWidget::focusData () [保护]

返回这个窗口部件的顶级窗口部件的焦点数据的指针。

焦点数据总是属于顶级窗口部件。焦点数据列表包含这个可以接收焦点的顶级窗口部件中所有的窗口部件，按Tab顺序。一个迭代器指向当前焦点窗口部件（focusWidget()返回这个窗口部件的指针）。

这个信息对于重新实现更先进版本的focusNextPrevChild()很有用。

void QWidget::focusInEvent ( QFocusEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收这个窗口部件的键盘焦点事件（焦点进入）。

一个窗口部件通常必须使用setFocusPolicy()来接收焦点事件，除了NoFocus的。（注意应用程序的程序员可以在任何一个窗口部件中调用setFocus()，即使是那些通常不接收焦点的。）

如果它接收了焦点，默认实现是更新这个窗口部件（请参考focusPolicy()）。它也调用setMicroFocusHint()，提示任何系统指定的输入工具关于用户注意的焦点。

也可以参考focusOutEvent(), focusPolicy、keyPressEvent()、keyReleaseEvent()、event()和QFocusEvent。

在QtMultiLineEdit中被重新实现。

bool QWidget::focusNextPrevChild ( bool next ) [虚 保护]

找到一个新的窗口部件并且把键盘焦点给它，适用于Tab和Shift+Tab，并且如果它能找到新的窗口部件就返回真，并且如果不能就返回假。

如果next为真，这个函数就“向前”搜索，如果next为假，它就“向后”搜索。

有时，你想重新实现这个函数。例如，一个网页浏览器也许会重新实现它用来向前或向后移动“当前激活链接”，并且只有到达“页面”的最后一个或第一个链接时调用QWidget::focusNextPrevChild()。

子窗口部件在它们的父窗口部件上调用focusNextPrevChild()，但是只有顶级窗口部件可以重定向焦点。通过重载一个对象中的这个方法，你可以获得能够遍历所有子窗口部件的焦点控制。

也可以参考focusData()。

void QWidget::focusOutEvent ( QFocusEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收这个窗口部件的键盘焦点事件（焦点丢失）。

一个窗口部件通常必须使用setFocusPolicy()来接收焦点事件，除了NoFocus的。（注意应用程序的程序员可以在任何一个窗口部件中调用setFocus()，即使是那些通常不接收焦点的。）

默认实现是调用repaint()，因为窗口部件的colorGroup()从激活变为通常，所以这个窗口部件也许需要重新绘制。它也调用setMicroFocusHint()，提示任何系统指定的输入工具关于用户注意的焦点。

也可以参考focusInEvent()、focusPolicy、keyPressEvent()、keyReleaseEvent()、event()和QFocusEvent.

实例：qmag/qmag.cpp。

FocusPolicy QWidget::focusPolicy () const

返回窗口部件接收键盘焦点的方式。详细情况请参考“focusPolicy”属性。

QWidget * QWidget::focusProxy () const

返回焦点代理的指针，或者如果没有焦点代理就返回0。

也可以参考setFocusProxy()。

QWidget * QWidget::focusWidget () const

返回这个窗口部件窗口中的焦点窗口部件。这个和QApplication::focusWidget()是不一样的，后者返回当前激活窗口中的焦点窗口部件。

QFont QWidget::font () const

返回这个窗口部件的字体当前设置。详细情况请参考“font”属性。

void QWidget::fontChange ( const QFont & oldFont ) [虚 保护]

这个虚函数是从setFont()中被调用的。oldFont是以前的字体，你可以通过font()获得新的字体。

如果你的窗口部件需要直到什么时候它的字体改变了，就重新实现这个函数。你将几乎毫无疑问的需要使用update()更新这个窗口部件。

默认实现是更新包括它的几何形状的窗口部件。

也可以参考font、font、update()和updateGeometry()。

QFontInfo QWidget::fontInfo () const

返回这个窗口部件当前字体的字体信息。等于QFontInto(widget->font())。

也可以参考font、fontMetrics()和font。

QFontMetrics QWidget::fontMetrics () const

返回这个窗口部件的当前字体的字体规格。等于 QFontMetrics(widget->font())。

也可以参考font、fontInfo()和font。

实例：drawdemo/drawdemo.cpp和qmag/qmag.cpp。

const QColor & QWidget::foregroundColor () const

和paletteForegroundColor()相同。

QRect QWidget::frameGeometry () const

返回相对于它的父对象包含任何窗口框架的窗口部件的几何形状。详细情况请参考“frameGeometry”属性。

QSize QWidget::frameSize () const

返回包含任何窗口框架的窗口部件的大小。详细情况请参考“frameSize”属性。

const QRect & QWidget::geometry () const

返回相对于它的父对象不包括窗口框架的窗口部件的几何形状。详细情况请参考“geometry”属性。

WFlags QWidget::getWFlags () const [保护]

返回这个窗口部件的窗口部件标记。

窗口部件就是Qt::WidgetFlags的一个组合。

也可以参考testWFlags(), setWFlags()和clearWFlags()。

void QWidget::grabKeyboard ()

捕获键盘输入。

这个窗口部件接收所有的键盘事件并且其它窗口部件将不会得到直到releaseKeyboard()被调用。鼠标事件不受影响。如果你想捕获鼠标事件，请使用grabMouse()。

焦点窗口部件不受影响，除非它不接收任何键盘事件。setFocus()像平常那样移动焦点，但是只有在releaseKeyboard()被调用之后，新的焦点窗口部件才能接收键盘事件。

如果一个不同的窗口部件当前正在捕获键盘焦点，那么那个窗口部件的捕获首先被释放。

也可以参考releaseKeyboard()、grabMouse()、releaseMouse()和focusWidget()。

void QWidget::grabMouse ()

捕获鼠标输入。

这个窗口部件接收所有的鼠标事件并且其它窗口部件将不会得到直到releaseMouse()被调用。键盘事件不受影响。如果你想捕获键盘事件，请使用grabKeyboard()。

警告：捕获鼠标的应用程序的bug经常会锁定终端。请特别仔细地使用这个函数，并且在调试的时候考虑使用-nograb命令行参数。

在使用Qt的时候，几乎不需要捕获鼠标，因为Qt非常聪明地捕获它、释放它。在特殊情况下，当鼠标按键被按下并且保持这种状态直到最后一个按键被释放时，Qt捕获鼠标。

注意只有可视的窗口部件可以捕获鼠标输入。如果一个窗口部件的isVisible()返回假，这个窗口部件不能调用grabMouse()。

也可以参考releaseMouse()、grabKeyboard()、releaseKeyboard()、grabKeyboard()和focusWidget()。

void QWidget::grabMouse ( const QCursor & cursor )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

捕获鼠标输入并且改变光标形状。

光标将被赋值为形状cursor（只要在鼠标焦点被捕获）并且这个窗口部件将变为唯一接收鼠标事件的窗口部件直到releaseMouse()被调用。

警告：不过鼠标也许会锁定终端。

也可以参考releaseMouse()、grabKeyboard()、releaseKeyboard()和cursor。

bool QWidget::hasFocus () const

如果这个窗口部件（或者它的焦点代理）拥有键盘输入焦点，返回真，否则返回假。详细情况请参考“focus”属性。

bool QWidget::hasMouse () const

如果窗口部件在鼠标光标之下，返回真，否则返回假。详细情况请参考“underMouse”属性。

bool QWidget::hasMouseTracking () const

如果这个窗口部件中鼠标跟踪生效，返回真，否则返回假。详细情况请参考“mouseTracking”属性。

int QWidget::height () const

返回不包括窗口框架的窗口部件的高度。详细情况请参考“height”属性。

int QWidget::heightForWidth ( int w ) const [虚]

返回对于给定宽度w这个窗口部件的最佳高度。默认实现是返回0，表明最佳高度不依赖于宽度。

警告：不要考虑窗口部件的布局。

在QMenuBar和QTextEdit中被重新实现。

void QWidget::hide () [虚 槽]

隐藏窗口部件。

你几乎不需要重新实现这个函数。如果你需要在一个窗口部件被隐藏之后做些什么，请使用hideEvent()替代。

也可以参考hideEvent()、hidden、show()、showMinimized()、visible和close()。

实例：mdi/application.cpp、network/ftpclient/ftpmainwindow.cpp、popup/popup.cpp、 progress/progress.cpp、scrollview/scrollview.cpp和xform/xform.cpp。

在QMenuBar中被重新实现。

void QWidget::hideEvent ( QHideEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收窗口部件隐藏事件。

在窗口部件被隐藏之后，隐藏事件被立即发送给窗口部件。

也可以参考event()和QHideEvent。

在QScrollBar中被重新实现。

const QPixmap * QWidget::icon () const

返回窗口部件图标像素映射。详细情况请参考“icon”属性。

QString QWidget::iconText () const

返回窗口部件图标文本。详细情况请参考“iconText”属性。

void QWidget::iconify () [槽]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

void QWidget::imComposeEvent ( QIMEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收输入法写作事件。当用户通过输入法输入某些文本时，这个处理器将被调用。

默认实现是调用e->ignore()，它拒绝输入法事件。详细情况请参考QIMEvent文档。

也可以参考event()和QIMEvent。

void QWidget::imEndEvent ( QIMEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收输入法写作事件。当用户已经完成通过输入法输入某些文本时，这个处理器将被调用。

默认实现是调用e->ignore()，它拒绝输入法事件。详细情况请参考QIMEvent文档。

也可以参考event()和QIMEvent。

void QWidget::imStartEvent ( QIMEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收输入法写作事件。当用户开始通过输入法输入某些文本时，这个处理器将被调用。

默认实现是调用e->ignore()，它拒绝输入法事件。详细情况请参考QIMEvent文档。

也可以参考event()和QIMEvent。

bool QWidget::isActiveWindow () const

如果这个窗口部件是激活窗口或者它的一个孩子，返回真，否则返回假。详细情况请参考“isActiveWindow”属性。

bool QWidget::isDesktop () const

如果这个窗口部件是一个桌面窗口部件，比如，它代表着桌面，返回真，否则返回假。详细情况请参考“isDesktop”属性。

bool QWidget::isDialog () const

如果这个窗口部件是一个对话框窗口部件，返回真，否则返回假。详细情况请参考“isDialog”属性。

bool QWidget::isEnabled () const

如果这个窗口部件是生效的，返回真，否则返回假。详细情况请参考“enabled”属性。

bool QWidget::isEnabledTo ( QWidget * ancestor ) const

如果ancestor生效，这个窗口部件能够变为生效的，返回真，否则返回假。

如果这个窗口部件自身或者它的每一个祖先，但是除了ancestor以外，已经被明确地指定为失效的时候，才是这样的情况。

isEnabledTo(0)等于isEnabled()。

也可以参考enabled和enabled。

bool QWidget::isEnabledToTLW () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数是被反对的。它等于isEnabled()。

bool QWidget::isFocusEnabled () const

如果这个窗口部件接收键盘焦点，返回真，否则返回假。详细情况请参考“focusEnabled”属性。

bool QWidget::isHidden () const

如果这个窗口部件被明确地隐藏，返回真，否则返回假。详细情况请参考“hidden”属性。

bool QWidget::isMaximized () const

如果窗口部件是被最大化的顶级窗口部件，返回真，否则返回假。

注意因为一些窗口系统的一些限制，这样做并不是总能得到所期望的结果（比如，如果在X11上的用户通过窗口管理器最大化这个窗口，Qt并不能把它与其它重定义大小区分开）。这有待于窗口管理器协议的进一步改进。

也可以参考showMaximized()。

bool QWidget::isMinimized () const

如果这个窗口部件最小化（变为图标了），返回真，否则返回假。详细情况请参考“minimized”属性。

bool QWidget::isModal () const

如果这个窗口部件是模式窗口部件，返回真，否则返回假。详细情况请参考“isModal”属性。

bool QWidget::isPopup () const

如果这个窗口部件是弹出窗口部件，返回真，否则返回假。详细情况请参考“isPopup”属性。

bool QWidget::isTopLevel () const

如果这个窗口部件是顶级窗口部件，返回真，否则返回假。详细情况请参考“isTopLevel”属性。

bool QWidget::isUpdatesEnabled () const

如果更新是生效的，返回真，否则返回假。详细情况请参考“updatesEnabled”属性。

bool QWidget::isVisible () const

如果这个窗口部件是可视的，返回真，否则返回假。详细情况请参考“visible”属性。

bool QWidget::isVisibleTo ( QWidget * ancestor ) const

如果ancestor被显示，这个窗口部件可以变为可视，返回真，否则返回假。

如果这个窗口部件自身或者它的每一个祖先，但是除了ancestor以外，已经被明确地指定为隐藏的时候，才是这样的情况。

如果这个窗口部件被屏幕上其它窗口弄得变暗，这个函数仍会返回真，但是如果它或者它们被移动了，它将被变为物理可视的。

isVisibleTo(0)和isVisible()很相似，除了它变为图标的情况或者这个窗口存在与其它虚拟桌面的情况。

也可以参考show()、hide()和visible。

bool QWidget::isVisibleToTLW () const

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数是被反对的。它等于isVisible()。

void QWidget::keyPressEvent ( QKeyEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收这个窗口部件的键盘按下事件。

窗口部件最初必须调用setFocusPolicy()来接收焦点并且得到焦点用来接收键盘释放事件。

如果你重新实现这个处理器，如果你不能理解这个事件，你就忽略（ignore()）这个事件，这是很重要的，这样这个窗口部件的父对象就可以说明它。

默认实现是如果用户按下Esc就关闭弹出窗口部件。否则这个事件就被忽略。

也可以参考keyReleaseEvent()、QKeyEvent::ignore()、focusPolicy, focusInEvent()、focusOutEvent()、event()和QKeyEvent。

实例：picture/picture.cpp。

在QLineEdit、QTextEdit和QtMultiLineEdit中被重新实现。

void QWidget::keyReleaseEvent ( QKeyEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现用来接收这个窗口部件的键盘释放事件。

窗口部件最初必须调用setFocusPolicy()来接收焦点并且得到焦点用来接收键盘释放事件。

如果你重新实现这个处理器，如果你不能理解这个事件，你就忽略（ignore()）这个事件，这是很重要的，这样这个窗口部件的父对象就可以说明它。

默认实现就是忽略这个事件。

也可以参考keyPressEvent()、QKeyEvent::ignore()、focusPolicy、focusInEvent()、focusOutEvent()、event()和QKeyEvent。

QWidget * QWidget::keyboardGrabber () [静态]

返回当前正在捕获键盘输入的窗口部件的指针。

如果在这个应用程序中当前没有正在捕获键盘的窗口部件，0被返回。

也可以参考grabMouse()和mouseGrabber()。

QLayout * QWidget::layout () const

返回管理窗口部件孩子的几何形状的布局引擎的指针。

如果这个窗口部件没有布局，layout()返回一个零指针。

也可以参考sizePolicy。

实例：chart/optionsform.cpp和fonts/simple-qfont-demo/viewer.cpp。

void QWidget::leaveEvent ( QEvent * ) [虚 保护]

这个事件管理器可以在子类中被重新实现来接收窗口部件离开事件。

当鼠标光标离开这个窗口部件时，离开事件被发送给这个窗口部件。

也可以参考enterEvent()、mouseMoveEvent()和event()。

void QWidget::lower () [槽]

把这个窗口部件降低到它的父窗口部件的栈的底部。

如果在屏幕上有与这个窗口部件重叠的兄弟，这个窗口部件将被它后来的这些兄弟变暗。

也可以参考raise()和stackUnder()。

bool QWidget::macEvent ( MSG * ) [虚 保护]

这个特定的事件处理器可以在子类中被重新实现用来接收本地Macintosh事件。

在你重新实现的这个函数中，如果你想停止Qt对这个事件的处理，返回真。如果你返回假，这个本地事件被回传给Qt，它会把这个事件转换为一个Qt事件并且把它发送给这个窗口部件。

警告：这个函数是不可以移植的。

也可以参考QApplication::macEventFilter()。

QPoint QWidget::mapFrom ( QWidget * parent, const QPoint & pos ) const

把parent的坐标系统中的这个窗口部件的坐标pos转换到这个窗口部件的坐标系统中。parent必须不能为0并且必须是这个调用窗口部件的父对象。

也可以参考mapTo()、mapFromParent()、mapFromGlobal()和underMouse。

QPoint QWidget::mapFromGlobal ( const QPoint & pos ) const

把全局屏幕坐标pos转换为窗口部件坐标。

也可以参考mapToGlobal()、mapFrom()和mapFromParent()。

QPoint QWidget::mapFromParent ( const QPoint & pos ) const

把父窗口部件坐标pos转换为窗口部件坐标。

如果窗口部件没有父对象，就和mapFromGlobal()一样。

也可以参考mapToParent()、mapFrom()、mapFromGlobal()和underMouse。

QPoint QWidget::mapTo ( QWidget * parent, const QPoint & pos ) const

把窗口部件坐标pos转换到parent坐标系统。parent必须不能为0并且必须是这个调用窗口部件的父对象。

也可以参考mapFrom()、mapToParent()、mapToGlobal()和underMouse。

QPoint QWidget::mapToGlobal ( const QPoint & pos ) const

把窗口部件坐标pos转换为全局屏幕坐标。例如，
mapToGlobal(QPoint(0,0))
将会给出这个窗口部件的左上角像素的全局坐标。

也可以参考mapFromGlobal()、mapTo()和mapToParent()。

实例：scribble/scribble.cpp。

QPoint QWidget::mapToParent ( const QPoint & pos ) const

把窗口部件坐标pos转换为父窗口部件中的一个坐标。

如果窗口部件没有父对象，就和mapToGlobal()一样。

也可以参考mapFromParent()、mapTo()、mapToGlobal()和underMouse。

int QWidget::maximumHeight () const

返回这个窗口部件的最大高度。详细情况请参考“maximumHeight”属性。

QSize QWidget::maximumSize () const

返回这个窗口部件的最大大小。详细情况请参考“maximumSize”属性。

int QWidget::maximumWidth () const

返回这个窗口部件的最大宽度。详细情况请参考“maximumWidth”属性。

int QWidget::metric ( int m ) const [虚 保护]

虚函数QPaintDevice::metric()的内部实现。

使用QPaintDeviceMetrics来替代它。

m是要获得的规格。

QRect QWidget::microFocusHint () const

返回这个窗口部件的当前设置的微焦点提示的当前设置。详细情况请参考“microFocusHint”属性。

int QWidget::minimumHeight () const

返回这个窗口部件的最小高度。详细情况请参考“minimumHeight”属性。

QSize QWidget::minimumSize () const

返回这个窗口部件的最小大小。详细情况请参考“minimumSize”属性。

QSize QWidget::minimumSizeHint () const [虚]

返回这个窗口部件的建议最小大小。详细情况请参考“minimumSizeHint”属性。

在QLineEdit和QtMultiLineEdit中被重新实现。

int QWidget::minimumWidth () const

返回这个窗口部件的最小宽度。详细情况请参考“minimumWidth”属性。

void QWidget::mouseDoubleClickEvent ( QMouseEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收这个窗口部件的鼠标双击事件。

默认实现产生一个普通的鼠标点击事件。

注意在窗口部件得到mouseDoubleClickEvent()之前，它得到一个mousePressEvent()和一个mouseReleaseEvent()。

也可以参考mousePressEvent()、mouseReleaseEvent()、 mouseMoveEvent()、event()和QMouseEvent。

QWidget * QWidget::mouseGrabber () [静态]

返回当前捕获鼠标输入的窗口部件的指针。

如果这个应用程序中当前没有捕获鼠标的窗口部件，0被返回。

也可以参考grabMouse()和keyboardGrabber()。

void QWidget::mouseMoveEvent ( QMouseEvent * e ) [虚 保护]

这个窗口部件可以在子类中被重新实现来接收这个窗口部件中的鼠标移动事件。

如果鼠标跟踪被切换为关闭，只有在鼠标被按下后移动的情况下，才会发生鼠标移动事件。如果鼠标跟踪被切换为开，即使鼠标没有被按下，只要移动就会发生鼠标移动事件。

QMouseEvent::pos()报告鼠标光标相对于这个窗口部件的位置。对于按下和释放事件，这个位置通常和最后一次鼠标移动事件的位置相同，但是如果鼠标非常快地移动和按下，这也许是不同的。这依赖于底层的窗口系统，而不是Qt。

也可以参考mouseTracking、mousePressEvent()、 mouseReleaseEvent()、mouseDoubleClickEvent()、event()和QMouseEvent。

实例：aclock/aclock.cpp、drawlines/connect.cpp、iconview/simple_dd/main.cpp、life/life.cpp、popup/popup.cpp、qmag/qmag.cpp和scribble/scribble.cpp。

在QSizeGrip中被重新实现。

void QWidget::mousePressEvent ( QMouseEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收这个窗口部件中的鼠标按下事件。

如果你在mousePressEvent()中创建新的窗口部件，mouseReleaseEvent()也许不会像你所期待的那样结束，这依赖于底层的窗口系统（或X11窗口管理器）、这个窗口部件的位置并且也许更多。

当你再窗口外点击时，默认实现是关闭弹出窗口。对于其它窗口部件类型，它什么都不做。

也可以参考mouseReleaseEvent()、mouseDoubleClickEvent()、mouseMoveEvent()、event()和QMouseEvent。

实例：biff/biff.cpp、drawlines/connect.cpp、iconview/simple_dd/main.cpp, life/life.cpp, qmag/qmag.cpp、scribble/scribble.cpp和tooltip/tooltip.cpp。

在QSizeGrip中被重新实现。

void QWidget::mouseReleaseEvent ( QMouseEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收鼠标释放事件。

也可以参考mouseDoubleClickEvent()、mouseMoveEvent()、event()和QMouseEvent。

实例：drawlines/connect.cpp、hello/hello.cpp、popup/popup.cpp、qmag/qmag.cpp、scribble/scribble.cpp、showimg/showimg.cpp和t14/cannon.cpp。

void QWidget::move ( const QPoint & ) [槽]

设置窗口部件在它的父窗口部件中的位置。详细情况请参考“pos”属性。

void QWidget::move ( int x, int y ) [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个和move( QSize(x, y) )一致。

void QWidget::moveEvent ( QMoveEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收窗口部件移动事件。当窗口部件接收到这个事件时，它已经在新的位置上了。

旧的位置可以通过QMoveEvent::oldPos()来访问。

也可以参考resizeEvent()、event()、pos和QMoveEvent。

bool QWidget::ownCursor () const

如果这个窗口部件使用它自己的光标，返回真，否则返回假。详细情况请参考“ownCursor”属性。

bool QWidget::ownFont () const

如果这个窗口部件使用它自己的字体，返回真，否则返回假。详细情况请参考“ownFont”属性。

bool QWidget::ownPalette () const

如果这个窗口部件使用它自己的调色板，返回真，否则返回假。详细情况请参考“ownPalette”属性。

void QWidget::paintEvent ( QPaintEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收绘制事件。

绘制事件就是重新绘制这个窗口部件的所有部分的一个请求。它可以是repaint()或update()的结果，或者因为这个窗口部件原来被变暗并且现在已经不再被覆盖了，或者其它很多原因。

很多窗口部件在当它们被请求时，它们很简单地重新绘制整个界面，但是一些比较慢的窗口部件需要通过仅仅绘制被请求的区域QPaintEvent::region()进行优化。这个速度优化不会改变结果，在事件处理过程中，绘制仅仅发生在被改变的区域中。例如，QListView和QCanvas就是这样做的。

Qt也试图通过把多个绘制事件合并为一个来加快绘制速度。当update()被调用几次或者窗口系统发送几次绘制事件，Qt把它们合并为一个比较大区域（请参考QRegion::unite()）的一个事件中。repaint()不允许这样优化，所以只要可能我们建议使用update()。

当绘制事件发生，更新区域通常被擦除，所以你正在这个窗口部件的背景上绘制。这里有一些例外并且QPaintEvent::erased()告诉你这个窗口部件是否被擦除。

背景可以通过使用setBackgroundMode()、setPaletteBackgroundColor()或setBackgroundPixmap()来设置。setBackgroundMode()的文档详细描述了背景，我们建议你去读一下。

也可以参考event()、repaint()、update()、QPainter、QPixmap和QPaintEvent。

实例：drawdemo/drawdemo.cpp、drawlines/connect.cpp、qmag/qmag.cpp、scribble/scribble.cpp、splitter/splitter.cpp、t8/cannon.cpp和t9/cannon.cpp。

在QButton、QFrame、QGLWidget、QSizeGrip、QStatusBar和QTabBar中被重新实现。

const QPalette & QWidget::palette () const

返回这个窗口部件的调色板。详细情况请参考“palette”属性。

const QColor & QWidget::paletteBackgroundColor () const

返回这个窗口部件的背景色。详细情况请参考“paletteBackgroundColor”属性。

const QPixmap * QWidget::paletteBackgroundPixmap () const

返回这个窗口部件的背景像素映射。详细情况请参考“paletteBackgroundPixmap”属性。

void QWidget::paletteChange ( const QPalette & oldPalette ) [虚 保护]

这个虚函数是从setPalette()中被调用的。oldPalette是原来的调色板，你可以通过palette()得到新的调色板。

如果你的窗口部件需要知道什么时候调色板发生变化了，请重新实现这个函数。

也可以参考palette和palette。

const QColor & QWidget::paletteForegroundColor () const

返回这个窗口部件的前景色。详细情况请参考“paletteForegroundColor”属性。

QWidget * QWidget::parentWidget ( bool sameWindow = FALSE ) const

返回这个窗口部件的父窗口部件的指针，如果它没有，就返回零指针。如果sameWindow为真并且这个窗口部件是顶级的，就返回0，否则返回它的父窗口部件。

实例：mdi/application.cpp。

void QWidget::polish () [虚 槽]

延时窗口部件的初始化。

这个函数将在窗口部件完全创建完毕之后并且在它每一次被显示之前被调用。

抛光对于依赖一个特定窗口部件的最终初始化是很有用的。有一些事情构造函数不能够决定，因为子类的初始化也许没有完成。

在这个函数之后，窗口部件就有一个适当的字体和调色板并且QApplication::polish()已经被调用。

当重新实现这个函数的时候，记得调用QWidget的实现。

也可以参考constPolish()和QApplication::polish()。

实例：menu/menu.cpp。

QPoint QWidget::pos () const

返回这个窗口部件在它父窗口部件中的位置。详细情况请参考“pos”属性。

bool QWidget::qwsEvent ( QWSEvent * ) [虚 保护]

这个特定的事件处理器可以在子类中被重新实现来接收本地的Qt/Embedded事件。

在你重新实现的这个函数中，如果你想停止Qt对这个事件的处理，返回真。如果你返回假，这个本地事件被回传给Qt，它会把这个事件转换为一个Qt事件并且把它发送给这个窗口部件。

警告：这个函数是不可以移植的。

也可以参考QApplication::qwsEventFilter()。

void QWidget::raise () [槽]

把这个窗口部件升高到它的父窗口部件的栈的顶部。

如果在屏幕上有与这个窗口部件重叠的兄弟，这个窗口部件将在它后来的这些兄弟之前变的可视了。

也可以参考lower()和stackUnder()。

实例：showimg/showimg.cpp。

void QWidget::recreate ( QWidget * parent, WFlags f, const QPoint & p, bool showIt = FALSE )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

这个函数的提供是为了从Qt 1.0移植到2.0。在Qt 2.0中它已经被重新命名为reparent()。

QRect QWidget::rect () const

返回不包含任何窗口框架的窗口部件的内部几何形状。详细情况请参考“rect”属性。

void QWidget::releaseKeyboard ()

释放键盘捕获。

也可以参考grabKeyboard()、grabMouse()和releaseMouse()。

void QWidget::releaseMouse ()

释放鼠标捕获。

也可以参考grabMouse()、grabKeyboard()和releaseKeyboard()。

void QWidget::repaint ( int x, int y, int w, int h, bool erase = TRUE ) [槽]

通过立即调用paintEvent()来直接重新绘制窗口部件，除非更新是失效的或者窗口部件被隐藏。

如果erase为真，Qt在paintEvent()调用之前擦除区域(x,y,w,h)。

如果w是负数，它被width()-x替换，并且如果h是负数，它被height()-y替换。

如果你需要立即重新绘制，我们建议使用repaint()，比如在动画期间。在绝大多数情况下，update()更好，因为它允许Qt来优化速度并且防止闪烁。

警告：如果你在一个函数中调用repaint()，而它自己又被paintEvent()调用，你也许会看到无线循环。update()函数从来不会产生循环。

也可以参考update()、paintEvent()、updatesEnabled和erase()。

实例：qwerty/qwerty.cpp。

void QWidget::repaint () [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本擦除并且重新绘制整个窗口部件。

void QWidget::repaint ( bool erase ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本重新绘制整个窗口部件。

void QWidget::repaint ( const QRect & r, bool erase = TRUE ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

通过立即调用paintEvent()来直接重新绘制窗口部件，除非更新是失效的或者窗口部件被隐藏。

如果erase为真，擦除窗口部件区域r。

void QWidget::repaint ( const QRegion & reg, bool erase = TRUE ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

通过立即调用paintEvent()来直接重新绘制窗口部件，除非更新是失效的或者窗口部件被隐藏。

如果erase为真，擦除窗口部件区域reg。

如果你需要立即重新绘制，我们建议使用repaint()，比如在动画期间。一连串的多次调用update()将产生一个单一的绘制事件。

警告：如果你在一个函数中调用repaint()，而它自己又被paintEvent()调用，你也许会看到无线循环。update()函数从来不会产生循环。

也可以参考update()、paintEvent()、updatesEnabled和erase()。

void QWidget::reparent ( QWidget * parent, WFlags f, const QPoint & p, bool showIt = FALSE ) [虚]

重新定义这个窗口部件的父对象。这个窗口部件得到新的parent，新的窗口部件标记（f，但通常使用0）和在新的父对象中的新位置（p）。

如果showIt为真，一旦窗口部件被重新定义父对象，show()就被调用。

如果新的父窗口部件在一个不同的顶级窗口部件中，被重新定义父对象的窗口部件和它的孩子们将被添加到新窗口部件的tab链的最后。如果被移动的窗口部件之一拥有键盘焦点，reparent()为这个窗口部件调用clearFocus()。

如果新的父窗口部件和原来的父对象在同一个顶级窗口部件中，reparent()不会改变tab顺序或者键盘焦点。

警告：你对这个函数的需要是绝对不必要的。如果你有一个窗口部件动态的改变它的内容，使用QWidgetStack或QWizard会更容易的多。

也可以参考getWFlags()。

void QWidget::reparent ( QWidget * parent, const QPoint & p, bool showIt = FALSE )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

一个方便的重新定义这个窗口部件的父对象的版本没有把窗口部件标记作为参数。

调用reparent(parent, getWFlags() & ~WType_Mask, p, showIt)。

void QWidget::resetInputContext () [保护]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。比如，改变焦点到另一个窗口部件，移动光标，等等。

void QWidget::resize ( const QSize & ) [槽]

设置不包含任何窗口框架的窗口部件的大小。详细情况请参考“size”属性。

void QWidget::resize ( int w, int h ) [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个和resize( QSize(w, h) )一致。

void QWidget::resizeEvent ( QResizeEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收窗口部件重定义大小事件。当resizeEvent()被调用时，这个窗口部件已经有了新的几何形状。原来的大小可以通过QResizeEvent::oldSize()访问。

这个窗口部件竟被擦除并且在处理重定义大小事件之后立即接收到一个绘制事件。在这个处理器中不需要（或者必须）绘制。

由WResizeNoErase创建的窗口部件将不会被擦除。不过，它们也将收到一个对于整个区域的绘制事件。再一次的，在这个处理器中不需要（或者必须）绘制。

如果窗口部件的自动面具生效，默认实现调用updateMask()。

也可以参考moveEvent()、event()、size、QResizeEvent和paintEvent()。

实例：drawdemo/drawdemo.cpp、mainlyQt/editor.cpp、mainlyXt/editor.cpp 、menu/menu.cpp、qmag/qmag.cpp、scribble/scribble.cpp和tooltip/tooltip.cpp。

在QFrame和QGLWidget中被重新实现。

void QWidget::scroll ( int dx, int dy )

卷动包括它的孩子的窗口部件，向右dx像素并且向下dy像素。dx和dy都可以为负。

在卷动后，scroll()发送绘制事件，只为了读的部分，但不写。例如，当向右卷动10像素，窗口部件的最左面10像素需要重新绘制。绘制事件也许立即或者稍后被交付，依赖于一些启发式。

也可以参考QScrollView、erase()和bitBlt()。

void QWidget::scroll ( int dx, int dy, const QRect & r )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个版本仅卷动r并且不移动窗口部件的孩子。

如果r为空或者无效，结果是未定义的。

也可以参考QScrollView、erase()和bitBlt()。

void QWidget::setAcceptDrops ( bool on ) [虚]

设置对于这个窗口部件放下事件是否生效为on。详细情况请参考“acceptDrops”属性。

void QWidget::setActiveWindow () [虚]

设置包含这个窗口部件的顶级窗口部件为激活窗口。

激活窗口就是拥有键盘输入焦点的可视的顶级窗口。

这个函数执行的操作和在一个顶级窗口的标题栏点击鼠标是一样的。在X11上，结果依赖于窗口管理器。如果你想确认窗口也被堆在顶部，请另外调用raise()。注意这个窗口已经被变为可视，除非setActiveWindow()没有效果。

在Windows上，如果当应用程序不是当前激活的应用程序，如果你调用这个函数，然后它不会使它变为激活窗口。它将会在标题栏条目上闪烁蓝色标明这个窗口已经做了些什么。这是由于Microsoft不允许一个应用程序打断用户当前在另一个应用程序上所做的事情。

也可以参考isActiveWindow、topLevelWidget()和show()。

在QXtWidget中被重新实现。

void QWidget::setAutoMask ( bool ) [虚]

设置这个窗口部件自动面具特征是否生效。详细情况请参考“autoMask”属性。

void QWidget::setBackgroundColor ( const QColor & c ) [虚]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。使用setPaletteBackgroundColor()或setEraseColor()替代它。

实例：customlayout/main.cpp、desktop/desktop.cpp、hello/main.cpp、movies/main.cpp和splitter/splitter.cpp。

void QWidget::setBackgroundMode ( BackgroundMode ) [虚]

设置绘制窗口部件背景所使用的颜色模式。详细情况请参考“backgroundMode”属性。

void QWidget::setBackgroundMode ( BackgroundMode m, BackgroundMode visual )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置这个窗口部件自己的背景模式为m并且可视背景模式为visual。可视背景模式和可设计的属性backgroundColor、foregroundColor和backgroundPixmap一起使用。

对于复杂的控制，合理的背景模式有时和窗口部件自己的背景模式不同。例如，微调框把PaletteBackground作为背景模式（通常是暗灰色），当它被嵌入到行编辑控件中使用PaletteBase（通常是白色）。因为行编辑控件覆盖微调框的绝大部分可视区域，它定义了PaletteBase为它的可视背景模式。改变backgroundColor属性会改变行编辑控件的背景，这正是用户在Qt设计器中所期待的。

void QWidget::setBackgroundOrigin ( BackgroundOrigin ) [虚]

设置这个窗口部件背景的原点。详细情况请参考“backgroundOrigin”属性。

void QWidget::setBackgroundPixmap ( const QPixmap & pm ) [虚]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。使用setPaletteBackgroundPixmap()或setErasePixmap()替代它。

实例：desktop/desktop.cpp。

void QWidget::setBaseSize ( const QSize & )

设置这个窗口部件的基础大小。详细情况请参考“baseSize”属性。

void QWidget::setBaseSize ( int basew, int baseh )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个和setBaseSize( QSize(basew, baseh) )一致。设置窗口部件基础大小的宽为basew，高为baseh。

void QWidget::setCaption ( const QString & ) [虚 槽]

设置窗口标题。详细情况请参考“caption”属性。

void QWidget::setCursor ( const QCursor & ) [虚]

设置这个窗口部件的光标形状。详细情况请参考“cursor”属性。

void QWidget::setDisabled ( bool disable ) [槽]

如果disable为真，使窗口部件输入事件失效，否则使输入事件生效。

更多信息请参考enabled文档。

也可以参考isEnabledTo()、QKeyEvent、QMouseEvent和enabledChange()。

void QWidget::setEnabled ( bool ) [虚 槽]

设置这个窗口部件是否生效。详细情况请参考“enabled”属性。

void QWidget::setEraseColor ( const QColor & color ) [虚]

设置这个窗口部件的擦除颜色为color。

擦除颜色就是在paintEvent()被调用之前这个窗口部件被清空的颜色。如果有擦除像素映射（使用setErasePixmap()设置），然后这个属性就会有不确定的值。

也可以参考erasePixmap()、backgroundColor()、backgroundMode和palette。

void QWidget::setErasePixmap ( const QPixmap & pixmap ) [虚]

设置这个窗口部件的擦除像素映射为pixmap。

这个像素映射就是在paintEvent()被调用之前用来清空这个窗口部件的。

void QWidget::setFixedHeight ( int h )

设置这个窗口部件的最小高度和最大高度都为h，而不改变宽度。为了方便而提供。

也可以参考sizeHint、minimumSize、maximumSize和setFixedSize()。

实例：fonts/simple-qfont-demo/viewer.cpp、layout/layout.cpp、qdir/qdir.cpp和showimg/showimg.cpp。

void QWidget::setFixedSize ( const QSize & s )

设置这个窗口部件的最小大小和最大大小都为s，这样就可以防止它变大或者变小。

也可以参考maximumSize和minimumSize。

void QWidget::setFixedSize ( int w, int h )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置窗口部件的宽度为w，高度为h。

void QWidget::setFixedWidth ( int w )

设置这个窗口部件的最小宽度和最大宽度都为h，而不改变高度。为了方便而提供。

也可以参考sizeHint、minimumSize、maximumSize和setFixedSize()。

实例：network/ftpclient/ftpmainwindow.cpp、progressbar/progressbar.cpp和qdir/qdir.cpp。

void QWidget::setFocus () [虚 槽]

把键盘输入焦点给这个窗口部件（或者它的焦点代理）。

首先，一个焦点移出事件会被发送给焦点窗口部件（如果有的话）告诉它关于失去焦点的事情。然后一个焦点进入事件被发送给这个窗口部件告诉它刚刚接收到焦点。（如果焦点移出和进入的窗口部件是同一个的话，就什么都没有发生。）

setFocus()会把焦点给一个窗口部件，而不管它的焦点策略，但是不会清空任何键盘捕获（请参考grabKeyboard()）。

请注意如果窗口部件是被隐藏的，它将不接收焦点。

警告：如果你在一个函数中调用setFocus()，而这个函数自己被focusOutEvent()或focusInEvent()调用，你也许会体验到无限循环。

也可以参考focus、clearFocus()、focusInEvent()、focusOutEvent()、focusPolicy、QApplication::focusWidget()、grabKeyboard()和grabMouse()。

实例：addressbook/centralwidget.cpp、lineedits/lineedits.cpp、mdi/application.cpp、popup/popup.cpp、rot13/rot13.cpp、t8/main.cpp和wizard/wizard.cpp。

void QWidget::setFocusPolicy ( FocusPolicy ) [虚]

设置这个窗口部件接收键盘焦点的方式。详细情况请参考“focusPolicy”属性。

void QWidget::setFocusProxy ( QWidget * w ) [虚]

设置这个窗口部件的焦点代理为窗口部件w。如果w为0，这个函数重置这个窗口部件没有焦点代理。

一些窗口部件，比如QComboBox，能够“拥有焦点”，但创建一个子窗口部件来实际处理这个焦点。例如，QComboBox创建了一个QLineEdit来处理焦点。

当“这个窗口部件”获得焦点时，setFocusProxy()设置这个窗口部件实际获得焦点。如果有了一个焦点代理，focusPolicy()、setFocusPolicy()、setFocus()和hasFocus()都在这个焦点代理上操作。

也可以参考focusProxy()。

void QWidget::setFont ( const QFont & ) [虚]

设置这个窗口部件的字体当前设置。详细情况请参考“font”属性。

在QComboBox、QLabel和QTabDialog中被重新实现。

void QWidget::setFont ( const QFont & f, bool )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用setFont(const QFont& font)替代它。

void QWidget::setGeometry ( const QRect & ) [虚 槽]

设置相对于它的父对象不包括窗口框架的窗口部件的几何形状。详细情况请参考“geometry”属性。

void QWidget::setGeometry ( int x, int y, int w, int h ) [虚 槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这相当于setGeometry( QRect(x, y, w, h) )。

void QWidget::setIcon ( const QPixmap & ) [虚 槽]

设置这个窗口部件图标像素映射。详细情况请参考“icon”属性。

void QWidget::setIconText ( const QString & ) [虚 槽]

设置这个窗口部件图标文本。详细情况请参考“iconText”属性。

void QWidget::setKeyCompression ( bool compress ) [虚 保护]

如果compress为真，使键盘事件压缩生效，并且如果compress为假，使键盘事件压缩失效。

默认情况下，键盘压缩是关闭的，所以窗口部件对于每一个键盘按下（或者更多，因为自动重复通常是打开的）都接收到一个键盘按下事件。如果你把它打开并且你的应用程序更不上键盘输入，Qt也许会试图压缩键盘事件，这样每一个事件中就会处理多于一个字符的情况。

例如，如果布局重新运算占用太长时间的CPU，一个字处理器窗口部件接收每一个QKeyEvent::text()中的2个、3个或更多字符。

如果窗口部件支持多字符unicode输入，它对于这种压缩打开总是安全的。

Qt只对可打印的字符执行键盘事件压缩。修正键、光标移动键、功能键和其它操作键（比如，Escape、Return、Backspace、PrintScreen）将会停止键盘事件压缩，即使如果可以更多可压缩的键盘事件。

并不是所有的平台都支持这种压缩，在这种情况下如果把这个选项打开将不会有任何效果。

也可以参考QKeyEvent::text().

void QWidget::setMask ( const QBitmap & bitmap ) [虚]

导致只有和bitmap中为1的位对应的窗口部件的像素是可视的。如果包含像素的区域在窗口部件的rect()之外，在那个区域的窗口系统控制允许可视，也许不可视，依赖于平台。

注意如果区域相当复杂，这种效果会很慢。

也可以参考clearMask()。

void QWidget::setMask ( const QRegion & region ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

导致只有和region重合的窗口部件的部分是可视的。如果包含像素的区域在窗口部件的rect()之外，在那个区域的窗口系统控制允许可视，也许不可视，依赖于平台。

注意如果区域相当复杂，这种效果会很慢。

也可以参考clearMask()。

void QWidget::setMaximumHeight ( int maxh )

设置这个窗口部件的最大高度为maxh。详细情况请参考“maximumHeight”属性。

void QWidget::setMaximumSize ( const QSize & )

设置这个窗口部件的最大大小。详细情况请参考“maximumSize”属性。

void QWidget::setMaximumSize ( int maxw, int maxh ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数相当于setMaximumSize( QSize(maxw, maxh) )。设置最大宽度为maxw，最大高度为maxh。

void QWidget::setMaximumWidth ( int maxw )

设置这个窗口部件的最大宽度为maxw。详细情况请参考“maximumWidth”属性。

void QWidget::setMicroFocusHint ( int x, int y, int width, int height, bool text = TRUE, QFont * f = 0 ) [虚 保护]

当窗口部件得到焦点，它应该为合适的大小和位置——x、y和width与em>height，调用setMicroFocusHint。这没有可视效果，它仅仅为任意系统指定的输入处理工具提供提示。

如果这是一个文本输入位置，text参数应该为真。

在Windows版本的Qt中，这个方法设置系统插入符号，这用户用户可访问的焦点处理。如果text为真，在远东亚洲语言输入系统中，它也会设置输入法的。

在X11版本的Qt中，如果text为真，这个方法为复杂语言输入处理设置XIM“spot”点。

字体参数f现在不使用了。

也可以参考microFocusHint。

void QWidget::setMinimumHeight ( int minh )

设置这个窗口部件的最小高度为minh。详细情况请参考“minimumHeight”属性。

void QWidget::setMinimumSize ( const QSize & )

设置这个窗口部件的最小大小。详细情况请参考“minimumSize”属性。

void QWidget::setMinimumSize ( int minw, int minh ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

这个函数相当于setMinimumSize( QSize(minw, minh) )。设置最小宽度为minw，最小高度为minh。

void QWidget::setMinimumWidth ( int minw )

设置这个窗口部件的最小宽度为minw。详细情况请参考“minimumWidth”属性。

void QWidget::setMouseTracking ( bool enable ) [虚 槽]

设置对于这个窗口部件鼠标跟踪是否生效为enable。详细情况请参考“mouseTracking”属性。

void QWidget::setPalette ( const QPalette & ) [虚]

设置这个窗口部件的调色板。详细情况请参考“palette”属性。

在QComboBox、QScrollBar和QSlider中被重新实现。

void QWidget::setPalette ( const QPalette & p, bool )

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用setPalette( const QPalette& p )替代它。

void QWidget::setPaletteBackgroundColor ( const QColor & ) [虚]

设置这个窗口部件的背景色。详细情况请参考“paletteBackgroundColor”属性。

void QWidget::setPaletteBackgroundPixmap ( const QPixmap & ) [虚]

设置这个窗口部件的背景像素映射。详细情况请参考“paletteBackgroundPixmap”属性。

void QWidget::setPaletteForegroundColor ( const QColor & )

设置这个窗口部件的前景色。详细情况请参考“paletteForegroundColor”属性。

void QWidget::setSizeIncrement ( const QSize & )

设置这个窗口部件的大小增量。详细情况请参考“sizeIncrement”属性。

void QWidget::setSizeIncrement ( int w, int h ) [虚]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

设置x（宽度）大小增量为w，y（高度）大小增量为h。

void QWidget::setSizePolicy ( QSizePolicy ) [虚]

设置这个窗口部件的默认布局方式。详细情况请参考“sizePolicy”属性。

void QWidget::setStyle ( QStyle * style )

设置这个窗口部件的图形用户界面风格为style。风格对象的所有权不能被转让。

如果没有风格被设置，这个窗口部件使用应用程序的风格QApplication::style()替代它。

设置窗口部件的风格对于已经存在或未来的子窗口部件没有效果。

警告：当你想显示Qt的风格的能力时，这个函数对于演示目的很有用。真正的应用程序应该避免它并且使用一个一致的图形用户界面风格来替代它。

也可以参考style()、QStyle、QApplication::style()和QApplication::setStyle()。

实例：grapher/grapher.cpp和progressbar/progressbar.cpp。

QStyle * QWidget::setStyle ( const QString & style )

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

使用QStyleFactory设置这个窗口部件的图形用户界面风格为style。

void QWidget::setTabOrder ( QWidget * first, QWidget * second ) [静态]

在焦点窗口部件的环中移动second窗口部件，这样当Tab被按下时，键盘焦点从first窗口部件移动到second窗口部件。

注意因为second窗口部件的tab顺序被改变，你应该用链的方式安排顺序：

    setTabOrder( a, b ); // a到b
    setTabOrder( b, c ); // a到b到c
    setTabOrder( c, d ); // a到b到c到d

不能像这样：

    setTabOrder( c, d ); // c到d，错误
    setTabOrder( a, b ); // a到b并且c到d
    setTabOrder( b, c ); // a到b到c，而不是c到d

如果first或second有焦点代理，setTabOrder()替代它/它们的代理。

也可以参考focusPolicy和setFocusProxy()。

实例：customlayout/main.cpp.

void QWidget::setUpdatesEnabled ( bool enable ) [虚 槽]

设置更新是否生效为enable。详细情况请参考“updatesEnabled”属性。

void QWidget::setWFlags ( WFlags f ) [虚 保护]

设置窗口部件标记为f。

窗口部件标记为Qt::WidgetFlags的组合。

也可以参考testWFlags()、getWFlags()和clearWFlags()。

void QWidget::show () [虚 槽]

显示这个窗口部件和它的子窗口部件。

如果它的大小或位置已经发生改变，Qt保证窗口部件正好在被显示之前得到移动和重定义大小事件。

你几乎不用重新实现这个函数。如果你需要在一个窗口部件被显示之前改变一些东西，请使用showEvent()替代它。如果你需要对初始化延时，请使用polish()。

也可以参考showEvent()、hide()、showMinimized()、showMaximized()、showNormal()、visible和polish()。

实例：canvas/main.cpp、fonts/simple-qfont-demo/simple-qfont-demo.cpp、life/main.cpp、popup/popup.cpp、t1/main.cpp、t3/main.cpp和t4/main.cpp。

在QDialog和QMenuBar中被重新实现。

void QWidget::showEvent ( QShowEvent * ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收窗口部件显示事件。

在窗口部件被显示之前，非自发显示事件立即被发送给窗口部件。顶级窗口部件的自发显示事件在这之后被交付。

也可以参考event()和QShowEvent。

实例：qdir/qdir.cpp。

void QWidget::showFullScreen () [槽]

用全屏模式显示这个窗口部件。

调用这个函数只有对顶级窗口部件有效。

为了从全屏模式返回，请调用showNormal()。

全屏模式在Windows下工作的非常好，但是在X下却有些问题。这些问题是由于指定X11客户端和窗口管理器之间通讯的ICCCM协议的限制。ICCCM很简单地不能理解无装饰的全屏模式窗口这一概念。因此，我们所能做的最好方式是请求一个无边框窗口并且放置和重定以它的大小为整个屏幕。依赖窗口管理器，这也许能工作，也许不能。无边框窗口使用MOTIF提示被请求，至少可以被实际存在地所有现代窗口管理器能够部分支持。

另一个方法是绕过整个窗口管理器并且使用WX11BypassWM标记创建一个窗口。尽管这样还会有其它一些问题，比如完全地破坏键盘焦点和当桌面变化时或用户升起其它窗口时会有非常奇怪的效果。

遵循现代的后ICCCM规范的未来X11窗口管理器也许能够完全地支持全屏模式。

也可以参考showNormal()、showMaximized()、show()、hide()和visible。

void QWidget::showMaximized () [虚 槽]

最大化显示这个窗口部件。

对不是顶级窗口部件的，调用这个函数没有任何效果。

在X11下，这个函数在特定窗口管理器下允许不能正常工作。关于为什么的详细情况请参考窗口几何形状文档。

也可以参考showNormal()、showMinimized()、show()、hide()和visible。

实例：canvas/main.cpp、helpviewer/main.cpp、mdi/application.cpp、qwerty/main.cpp、qwerty/qwerty.cpp和scribble/main.cpp。

void QWidget::showMinimized () [虚 槽]

最小化显示这个窗口为一个图标。

对不是顶级窗口部件的，调用这个函数没有任何效果。

也可以参考showNormal()、showMaximized()、show()、hide(), visible和minimized。

void QWidget::showNormal () [虚 槽]

在窗口部件被最大化或最小化之后，恢复它。

对不是顶级窗口部件的，调用这个函数没有任何效果。

也可以参考showMinimized()、showMaximized()、show()、hide()和visible。

实例：mdi/application.cpp。

QSize QWidget::size () const

返回不包含任何窗口框架的窗口部件的大小。详细情况请参考“size”属性。

QSize QWidget::sizeHint () const [虚]

返回建议的窗口部件大小。详细情况请参考“sizeHint”属性。

在QSizeGrip中被重新实现。

QSize QWidget::sizeIncrement () const

返回窗口部件的大小增量。详细情况请参考“sizeIncrement”属性。

QSizePolicy QWidget::sizePolicy () const [虚]

返回窗口部件的默认布局行为。详细情况请参考“sizePolicy”属性。

void QWidget::stackUnder ( QWidget * w ) [槽]

把窗口部件放在父窗口部件栈中w的下面。

为了保证这个能工作，这个窗口部件自己和w必须是兄弟。

也可以参考raise()和lower()。

QStyle & QWidget::style () const

返回这个窗口部件的图形用户界面的风格。

也可以参考QWidget::setStyle()、QApplication::setStyle()和QApplication::style()。

void QWidget::styleChange ( QStyle & oldStyle ) [虚 保护]

当窗口部件的风格发生变化时，这个虚函数被调用。oldStyle是原来的图形用户界面风格，你可以通过style()得到新的风格。

如果你的窗口部件需要知道什么时候它的图形用户界面发生变化，请重新实现这个函数。你几乎必然需要使用update()来更新窗口部件。

默认实现是更新包括几何形状的窗口部件。

也可以参考QApplication::setStyle()、style()、update()和updateGeometry()。

void QWidget::tabletEvent ( QTabletEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收这个窗口部件的写字板事件。

如果你重新实现这个处理器，如果你不处理它的话，你忽略（ignore()）这个事件是非常重要的，这样这个窗口部件的父对象就可以解释它。

默认实现是忽略这个事件。

也可以参考QTabletEvent::ignore()、QTabletEvent::accept()、event()和QTabletEvent。

WFlags QWidget::testWFlags ( WFlags f ) const

返回这个窗口部件的标记和f的位与（AND）运算结果。

窗口部件标记是Qt::WidgetFlags的组合。

也可以参考getWFlags()、setWFlags()和clearWFlags()。

QWidget * QWidget::topLevelWidget () const

返回这个窗口部件的顶级窗口部件，比如，有（或者能够有）窗口系统框架的上一级祖先。

如果这个窗口部件是顶级的，它自己被返回。

通常的使用方法是改变窗口标题：

        aWidget->topLevelWidget()->setCaption( "New Caption" );

也可以参考isTopLevel。

void QWidget::unsetCursor () [虚]

重置这个窗口部件的光标形状。详细情况请参考“cursor”属性。

void QWidget::unsetFont ()

重置这个窗口部件的字体当前设置。详细情况请参考“font”属性。

void QWidget::unsetPalette ()

重置这个窗口部件的调色板。详细情况请参考“palette”属性。

void QWidget::update () [槽]

更新窗口部件，除非更新已经失效或者窗口部件被隐藏。

这个函数不会导致一个立刻的重新绘制——更正确的是，当Qt回到主事件回路中时，它规划了所要处理的绘制事件。这样允许Qt来优化得到比调用repaint()更快的速度和更少的闪烁。

几次调用update()的结果通常仅仅是一次paintEvent()调用。

Qt通常在paintEvent()调用之前擦除这个窗口部件的区域。仅仅只有在WRepaintNoErase窗口部件标记被设置的时候，窗口部件本身对绘制它所有的像素负有责任。

也可以参考repaint()、paintEvent()、updatesEnabled、erase()和setWFlags()。

实例：desktop/desktop.cpp和scrollview/scrollview.cpp。

void QWidget::update ( int x, int y, int w, int h ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

更新窗口部件中的矩形(x, y, w, h)，除非更新已经失效或者窗口部件被隐藏。

这个函数不会导致一个立刻的重新绘制——更正确的是，当Qt回到主事件回路中时，它规划了所要处理的绘制事件。这样允许Qt来优化得到比调用repaint()更快的速度和更少的闪烁。

几次调用update()的结果通常仅仅是一次paintEvent()调用。

如果w为负数，它被width()-x替换。如果h为负数，它被height()-y替换。

Qt通常在paintEvent()调用之前擦除这个窗口部件的区域。仅仅只有在WRepaintNoErase窗口部件标记被设置的时候，窗口部件本身对绘制它所有的像素负有责任。

也可以参考repaint(), paintEvent(), updatesEnabled and erase().

void QWidget::update ( const QRect & r ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

更新窗口部件中的矩形r，除非更新已经失效或者窗口部件被隐藏。

这个函数不会导致一个立刻的重新绘制——更正确的是，当Qt回到主事件回路中时，它规划了所要处理的绘制事件。这样允许Qt来优化得到比调用repaint()更快的速度和更少的闪烁。

几次调用update()的结果通常仅仅是一次paintEvent()调用。

void QWidget::updateGeometry ()

把这个窗口部件已经改变并且也许需要改变几何形状通告给布局系统。

如果sizeHint()或sizePolicy()已经发生变化，请调用这个函数。

对于明确隐藏的窗口部件，updateGeometry()是没有操作的。只要这个窗口部件一显示出来，布局系统就将被通告。

void QWidget::updateMask () [虚 保护]

这个函数可以在子类中被重新实现来支持透明窗口部件。只要窗口部件改变状态，形状面具不得不被重新计算，它就会被调用。

也可以参考autoMask、setMask()和clearMask()。

QRect QWidget::visibleRect () const

返回窗口部件的当前可见矩形。详细情况请参考“visibleRect”属性。

void QWidget::wheelEvent ( QWheelEvent * e ) [虚 保护]

这个事件处理器可以在子类中被重新实现来接收这个窗口部件的滚轮事件。

如果你重新实现这个处理器，如果你不处理它的话，你忽略（ignore()）这个事件是非常重要的，这样这个窗口部件的父对象就可以解释它。

默认实现是忽略这个事件。

也可以参考QWheelEvent::ignore()、QWheelEvent::accept()、event()和QWheelEvent。

int QWidget::width () const

返回不包含任何窗口框架的窗口部件宽度。详细情况请参考“width”属性。

bool QWidget::winEvent ( MSG * ) [虚 保护]

这个特定事件处理器可以在子类中被重新实现来接收本地Windows事件。

在重新实现的这个函数中，如果你想停止Qt对这个事件的处理，请返回真。如果你返回假，这个本地事件被回传给Qt，它会把这个事件转化为一个Qt事件并且把它发送给这个窗口部件。

警告：这个函数不能移植。

也可以参考QApplication::winEventFilter()。

WId QWidget::winId () const

返回窗口部件的窗口系统标识符。

原则上是可以移植的，但是如果使用了它，一定是做了一些不可移植的事情。请留心。

也可以参考find()。

实例：mainlyXt/editor.cpp.

void QWidget::windowActivationChange ( bool oldActive ) [虚 保护]

当窗口部件的窗口被窗口系统激活或者停用，这个虚函数被调用。oldActive是原来的状态，你可以通过isActiveWindow()得到新的设置。

如果你的窗口部件需要知道什么时候它的窗口变为激活或停用，请重新实现这个函数。

如果停止和激活颜色组不同与高亮和连接颜色，默认实现更新这个窗口部件的可视部分。

也可以参考setActiveWindow()、isActiveWindow、update()和palette。

int QWidget::x () const

返回包括任何窗口框架的相对于它的父窗口部件的这个窗口部件的x坐标。详细情况请参考“x”属性。

bool QWidget::x11Event ( XEvent * ) [虚 保护]

这个特定事件处理器可以在子类中被重新实现来接收本地X11事件。

在重新实现的这个函数中，如果你想停止Qt对这个事件的处理，请返回真。如果你返回假，这个本地事件被回传给Qt，它会把这个事件转化为一个Qt事件并且把它发送给这个窗口部件。

警告：这个函数不能移植。

也可以参考QApplication::x11EventFilter()。

在QXtWidget中被重新实现。

int QWidget::y () const

返回包括任何窗口框架的相对于它的父窗口部件的这个窗口部件的y坐标。详细情况请参考“y”属性。

属性文档

bool acceptDrops

这个属性保存的是窗口部件中放下事件是否有效。

设置这个属性为真告诉系统这个窗口部件可以能够接收放下事件。

如果窗口部件是桌面（QWidget::isDesktop()），如果其它应用程序正在使用桌面，这也许会失败，你可以调用acceptDrops()来测试这种情况是否发生。

通过setAcceptDrops()可以设置属性值并且通过acceptDrops()来获得属性值。

bool autoMask

这个属性保存的是窗口部件中自动面具特征是否有效。

透明窗口部件使用面具来定义它们的可视区域。QWidget有一些内置的支持可以使重新计算面具的任务更容易。当设置自动面具为真，只要窗口部件改变大小或者改变它的焦点状态updateMask()就将会被调用。注意你必须重新实现updateMask()（其中应该包含一个setMask()的调用）或者什么都不会发生。

注意：当你在你的自定义窗口部件中被重新实现resizeEvent()、focusInEvent()或focusOutEvent()时并且还想确认自动面具计算工作，你应该在你的事件处理函数的后面添加：

    if ( autoMask() )
        updateMask();

对于所有改变窗口部件的外观，都需要一个重新计算的面具，这都是真的。

虽然面具是一个技术上很吸引人的概念，但是他有一个很大的缺点：当使用复杂的不能被很容易地使用相对简单的区域表达的面具时，它们在一些窗口系统中很慢。经典的实例就是透明的标签。它的内容的复杂形状使它需要用一个位图重新描述它的面具，这将会消耗内存和事件。如果你想让几个临近的窗口部件的背景没有缝隙的融合在一起，你也许想使用的是setBackgroundOrigin()，而不是面具。

也可以参考updateMask()、setMask()、clearMask()和backgroundOrigin。

通过setAutoMask()可以设置属性值并且通过autoMask()来获得属性值。

QBrush backgroundBrush

这个属性保存的是窗口部件的背景画刷。

背景画刷依赖于窗口部件的调色板和它的背景模式。

也可以参考backgroundColor()、backgroundPixmap()、eraseColor()、palette和QApplication::setPalette()。

通过backgroundBrush()来获得属性值。

BackgroundMode backgroundMode

这个属性保存的是绘制窗口部件背景所使用的颜色模式。

setPaletteBackgroundColor()读取这个属性来决定palette中的哪一个被设置。

对于绝大多数出口部，默认的就足够了（PaletteBackground，通常是灰色），但是一些需要使用PaletteBase（文本输出的背景，通常是白色）或者其它模式。

凹陷的QListBox并且为了和它的环境形成对照使用基本色，在构造函数中这样做：

    setBackgroundMode( PaletteBase );

对于Qt内置的窗口部件，你永远都不需要为它们设置背景模式，但是你也许需要在你的自定义窗口部件中考虑设置一下，这样setPaletteBackgroundColor()就可以像被期待地那样工作。

注意对于setBackgroundMode()中的两个背景模式值，名为FixedPixmap何FixedColor，没有什么意义。你必须调用setBackgroundPixmap()和setPaletteBackgroundColor()来替代。

通过setBackgroundMode()可以设置属性值并且通过backgroundMode()来获得属性值。

BackgroundOrigin backgroundOrigin

这个属性保存的是窗口部件的背景的原点。

这个原点是WidgetOrigin（默认）、ParentOrigin和WindowOrigin其中之一。

只有在窗口部件有一个背景像素映射，对于定位有所不同。使用WindowOrigin，临近的几个窗口部件的背景会融合的很好好像没有缝隙一样。

也可以参考backgroundPixmap()和backgroundMode。

通过setBackgroundOrigin()设置属性值并且通过backgroundOrigin()来获得属性值。

QSize baseSize

这个属性保存的是窗口部件的基础大小。

如果窗口部件定义了sizeIncrement()，基础大小就被用来计算一个确切的窗口部件大小。

也可以参考sizeIncrement。

通过setBaseSize()设置属性值并且通过baseSize()来获得属性值。

QString caption

This property holds the window caption (title). 这个属性保存的是窗口标题。

这个属性只对顶级窗口部件有用。如果没有标题被设置，标题就为QString::null。

也可以参考icon and iconText。

通过setCaption()可以设置属性值并且通过caption()来获得属性值。

QRect childrenRect

这个属性保存的是窗口部件的子对象的边界矩形。

隐藏的子对象除外。

也可以参考childrenRegion和geometry。

通过childrenRect()来获得属性值。

QRegion childrenRegion

这个属性保存的是窗口部件的子对象所占用的组合区域。

隐藏的子对象除外。

也可以参考childrenRect和geometry。

通过childrenRegion()来获得属性值。

QColorGroup colorGroup

This property holds the current color group of the widget palette. 这个属性保存的是窗口部件调色板的当前颜色组。

颜色组由窗口部件的状态决定。一个失效的窗口部件是QPalette::disabled()颜色组，一个有键盘焦点的窗口部件是QPalette::active()颜色组，一个停止的窗口部件是QPalette::inactive()颜色组。

也可以参考palette。

通过colorGroup()来获得属性值。

QCursor cursor

这个属性保存的是窗口部件的光标外形。

当鼠标在窗口部件之上时，鼠标光标将采用这个外形。对于可以使用的外形的范围请参考预定义的光标对象列表。

一个编辑器窗口部件也许使用I形光标：

        setCursor( IbeamCursor );

如果没有光标被设置，或者在调用unsetCursor()之后，父对象的光标被使用。函数unsetCursor()对于顶级窗口部件没有效果。

也可以参考QApplication::setOverrideCursor()。

通过setCursor()设置属性值，通过cursor()来获得属性值并且通过unsetCursor()重置属性值。

bool customWhatsThis

这个属性保存的是窗口部件是否手动处理“这是什么”的帮助。

customWhatsThis()的默认实现返回假，这也就是说窗口部件在“这是什么”状态将不接受任何事件。

通过调用QWhatsThis::leaveWhatsThisMode()，不管有没有任何实际显示的帮助文本，窗口部件会离开“这是什么”模式。

如果你的窗口部件是一个“被动的内部行动者”，假设在所有环境下工作时，你也许要重新实现customWhatsThis()。

也可以参考QWhatsThis::inWhatsThisMode()和QWhatsThis::leaveWhatsThisMode()。

通过customWhatsThis()来获得属性值。

bool enabled

这个属性保存的是窗口部件是否有效。

一个有效的窗口部件接收键盘和鼠标事件，一个失效的窗口部件不能。实际上，有效的窗口部件只有在它处于焦点时才接收键盘事件。

一些窗口部件当它们被失效的时候，显示得不同。例如，一个按钮也许把它的标签变灰。如果你的窗口部件需要知道它什么时候生效或失效，你可以重新实现enabledChange()函数。

使一个窗口部件失效就隐含地使它所有的子对象失效。使一个窗口部件生效就会逐个把它的子窗口部件生效，除非它们被明确地失效。

也可以参考enabled、isEnabledTo()、QKeyEvent、QMouseEvent和enabledChange()。

通过setEnabled()设置属性值并且通过isEnabled()来获得属性值。

bool focus

这个属性保存的是窗口部件（或者它的焦点代理）是否得到键盘输入焦点。

实际上等价于qApp->focusWidget() == this。

也可以参考setFocus()、a href="#clearFocus">clearFocus()、focusPolicy和QApplication::focusWidget()。

通过hasFocus()来获得属性值。

bool focusEnabled

这个属性保存的是窗口部件是否接收键盘焦点。

键盘焦点初始状态是失效的（比如，focusPolicy() == QWidget::NoFocus）。

如果一个窗口部件处理键盘事件，你必须为它使键盘焦点生效。这通常在窗口部件的构造函数中完成。例如，QLineEdit的构造函数调用setFocusPolicy(QWidget::StrongFocus)。

也可以参考focusPolicy、focusInEvent()、focusOutEvent()、keyPressEvent()、keyReleaseEvent()和enabled。

通过isFocusEnabled()来获得属性值。

FocusPolicy focusPolicy

这个属性保存的是窗口部件接收键盘焦点的策略。

如果窗口部件通过tab来接收键盘焦点，这个策略就是QWidget::TabFocus；如果窗口部件通过点击来接收键盘焦点，这个策略就是QWidget::ClickFocus；如果窗口部件上述两种方式都使用，是QWidget::StrongFocus；并且如果它不接收焦点（QWidget的默认值），是QWidget::NoFocus。

如果一个窗口部件处理键盘事件，你必须为它使键盘焦点生效。这通常在窗口部件的构造函数中完成。例如，QLineEdit的构造函数调用setFocusPolicy(QWidget::StrongFocus)。

也可以参考focusEnabled、focusInEvent()、focusOutEvent()、keyPressEvent()、keyReleaseEvent()和enabled。

通过setFocusPolicy()设置属性值并且通过focusPolicy()来获得属性值。

QFont font

这个属性保存的是窗口部件当前的字体集。

fontInfo()函数报告这个窗口部件所用的实际字体。

只要没有特定字体被设置，或者在unsetFont()被调用之后，那么这个窗口部件类使用父窗口部件的字体或者（如果这个窗口部件是顶级窗口部件）使用默认应用程序字体。

这段代码设置12点的helvetica粗字体：

    QFont f( "Helvetica", 12, QFont::Bold );
    setFont( f );

另外设置字体时，setFont()通知所有子对象关于这个变化。

也可以参考fontChange()、fontInfo()、fontMetrics()和ownFont。

通过setFont()设置属性值，通过font()来获得属性值并且通过unsetFont()重置属性值。

QRect frameGeometry

这个属性保存的是相对于它的父对象包含任何窗口框架的窗口部件的几何形状。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考geometry、x、a href="#y-prop">y和pos。

通过frameGeometry()来获得属性值。

QSize frameSize

这个属性保存的是包含任何窗口框架的窗口部件的大小。

通过frameSize()来获得属性值。

QRect geometry

这个属性保存的是相对于它的父对象不包括窗口框架的窗口部件的几何形状。

当窗口部件改变几何形状时，如果它是可视的，它立即接收到一个移动事件（moveEvent()）和/或一个重定义大小（resizeEvent()）。如果它当前不是可视的，它被保证会在被显示之前接收到适当的事件。

如果它在由minimumSize()和maximumSize()定义的范围之外，大小组件被调整。

setGeometry()是虚的，并且所有Qt中其它重载setGeometry()的重新实现调用它。

警告：在resizeEvent()或moveEvent()中调用setGeometry()会导致无限循环。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考frameGeometry、rect、pos、size、moveEvent()、resizeEvent()、minimumSize和maximumSize。

通过setGeometry()设置属性值并且通过geometry()来获得属性值。

int height

这个属性保存的是不包括窗口框架的窗口部件的高度。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考geometry、width和size。

通过height()来获得属性值。

bool hidden

这个属性保存的是窗口部件是否明确地隐藏。

如果为假，这个窗口部件是可视的或者如果它的所有祖先变为可视，它将变为可视的。

也可以参考hide()、show()、visible和isVisibleTo()。

通过isHidden()来获得属性值。

QPixmap icon

这个属性保存的是窗口部件图标像素映射。

这个属性只对顶级窗口部件有效。如果没有图标被设置，icon()返回0。

也可以参考iconText、caption和设置应用程序图标。

通过setIcon()设置属性值并且通过icon()来获得属性值。

QString iconText

这个属性保存的是窗口部件图标文本。

这个属性只对顶级窗口部件有效。如果没有图标文本被设置，这个函数返回QString::null。

也可以参考icon和caption。

通过setIconText()设置属性值并且通过iconText()来获得属性值。

bool isActiveWindow

这个属性保存的是窗口部件或者它的一个子对象是否是活动窗口。

活动窗口是有键盘焦点的窗口

当弹出窗口是可视的，这个属性对于活动窗口和这个弹出窗口都是真。

也可以参考setActiveWindow()和QApplication::activeWindow()。

通过isActiveWindow()来获得属性值。

bool isDesktop

这个属性保存的是窗口部件是否是桌面窗口部件，比如，代表桌面。

一个桌面窗口部件也是顶级窗口部件。

也可以参考isTopLevel和QApplication::desktop()。

通过isDesktop()来获得属性值。

bool isDialog

这个属性保存的是窗口部件是否是对话框窗口部件。

对话框窗口部件是次要的顶级窗口部件，比如一个有父对象的顶级窗口部件。

也可以参考isTopLevel和QDialog。

通过isDialog()来获得属性值。

bool isModal

这个属性保存的是窗口部件是否是模式窗口部件。

这个属性只对顶级窗口部件有效。一个模式窗口部件防止对其它所有顶级窗口部件得到任何输入。

也可以参考isTopLevel、isDialog和QDialog。

通过isModal()来获得属性值。

bool isPopup

这个属性保存的是窗口部件是否是弹出窗口部件。

一个弹出窗口部件是在窗口部件的构造函数中使用窗口部件标记 WType_Popup创建的。一个弹出窗口部件也是一个顶级窗口部件。

也可以参考isTopLevel。

通过isPopup()来获得属性值。

bool isTopLevel

This property holds whether the widget is a top-level widget. 这个属性保存的是窗口部件是否是顶级窗口部件。

顶级窗口部件通常有框架和标题。弹出和桌面窗口部件也是顶级窗口部件。

顶级窗口部件可以有父窗口部件。然后它和它的父窗口部件就形成一个组并且当它的父对象被删除或最小化等等时，它也被删除或最小化等等。如果被窗口部件支持的话，它和它的父对象一样也有一个普通任务栏条目。

QDialog和QMainWindow窗口部件默认是顶级的，尽管在构造函数中被指定一个父窗口部件。这个行为是由WType_TopLevel窗口部件标记指定的。

也可以参考topLevelWidget()、isDialog、isModal、isPopup、isDesktop和parentWidget()。

通过isTopLevel()来获得属性值。

int maximumHeight

这个属性保存的是窗口部件的最大高度。

这个属性和maximumSize().height()一致。

也可以参考maximumSize和maximumWidth。

通过setMaximumHeight()设置属性值并且通过maximumHeight().来获得属性值。

QSize maximumSize

这个属性保存的是窗口部件的最大大小。

这个窗口部件不能被重定义为比这个最大大小更大的大小了。

也可以参考maximumWidth、maximumHeight、maximumSize、minimumSize和sizeIncrement。

通过setMaximumSize()设置属性值并且通过maximumSize()来获得属性值。

int maximumWidth

这个属性保存的是窗口部件的最大宽度。

这个属性和maximumSize().width()一致。

也可以参考maximumSize和maximumHeight。

通过setMaximumWidth()设置属性值并且通过maximumWidth()来获得属性值。

QRect microFocusHint

这个属性保存的是窗口部件的当前设置的微焦点提示。

更多信息请参考setMicroFocusHint()的文档。

通过microFocusHint()来获得属性值。

bool minimized

这个属性保存的是窗口部件是否是最小化的（变为图标了）。

这个属性和顶级窗口部件相关。

也可以参考showMinimized()、visible、show()、hide()和showNormal()。

通过isMinimized()来获得属性值。

int minimumHeight

这个属性保存的是窗口部件的最小高度。

这个属性和minimumSize().height()一致。

也可以参考minimumSize和minimumWidth。

通过setMinimumHeight()设置属性值并且通过minimumHeight()来获得属性值。

QSize minimumSize

这个属性保存的是窗口部件的最小大小。

这个窗口部件不能被重定义比这个最小大小更小的大笑了。如果当前大小更小的话，窗口部件的大小被强制为最小大小。

如果你在这个窗口部件中使用了布局，最小大小将会被这个布局设置，而不是setMinimumSize()，除非你设置布局的重定义大小模式为QLayout::FreeResize。

也可以参考minimumWidth、minimumHeight、maximumSize、sizeIncrement和QLayout::resizeMode。

通过setMinimumSize()设置属性值并且通过minimumSize()来获得属性值。

QSize minimumSizeHint

这个属性保存的是建议的窗口部件最小大小。

如果这个属性值是无效的大小，那么就没有被建议的最小大小了。

如果这个窗口部件中没有布局，minimumSizeHint()默认实现返回无效大小并且否则的话返回布局的最小大小。绝大多数内置窗口部件重新实现了minimumSizeHint()。

QLayout从来不会重定义窗口部件大小小于minimumSizeHint。

也可以参考QSize::isValid()、size、minimumSize和sizePolicy。

通过minimumSizeHint()来获得属性值。

int minimumWidth

这个属性保存的是窗口部件的最小宽度。

这个属性和minimumSize().width()一致。

也可以参考minimumSize和minimumHeight。

通过setMinimumWidth()设置属性值并且通过minimumWidth()来得到属性值。

bool mouseTracking

这个属性保存的是窗口部件跟踪鼠标是否生效。

如果鼠标跟踪失效（默认），当鼠标被移动的时候只有在至少一个鼠标按键被按下时，这个窗口部件才会接收鼠标移动事件。

如果鼠标跟踪生效，如果没有按键被按下，这个窗口部件也会接收鼠标移动事件。

也可以参考mouseMoveEvent()和QApplication::setGlobalMouseTracking()。

通过setMouseTracking()设置属性值并且通过hasMouseTracking()来获得属性值。

bool ownCursor

这个属性保存的是窗口部件是否使用它自己的光标。

如果为假，这个窗口部件使用它父窗口部件的光标。

也可以参考cursor。

通过ownCursor()来获得属性值。

bool ownFont

这个属性保存的是窗口部件是否使用它自己的字体。

如果为假，这个窗口部件使用它父窗口部件的字体。

也可以参考font。

通过ownFont()来获得属性值。

bool ownPalette

这个属性保存的是窗口部件是否使用它自己的调色板。

如果为假，这个窗口部件使用它父窗口部件的调色板。

也可以参考palette。

通过ownPalette()来获得属性值。

QPalette palette

这个属性保存的是窗口部件的调色板。

只要没有特定的调色板被设置，或者在unsetPalette()被调用之后，这个窗口部件的特定调色板就是父窗口部件的调色板或者（如果这个窗口部件是顶级窗口部件）默认的应用程序调色板。

可以替代定义整个新的调色板的，你也可以使用paletteBackgroundColor、paletteBackgroundPixmap和paletteForegroundColor方便的属性来只改变窗口部件的背景和前景外观。

也可以参考ownPalette、colorGroup和QApplication::palette()。

通过setPalette()设置属性值，通过palette()来获得属性值并且通过unsetPalette()重置属性值。

QColor paletteBackgroundColor

这个属性保存的是窗口部件的背景色。

这个调色板背景色通常被setBackgroundMode()隐含地设置，尽管它也可以由setPaletteBackgroundColor()明显地设置。setPaletteBackgroundColor()是一个创建和设置通过setPalette()修改过的QPalette方便函数。这个调色板根据窗口部件的背景模式被修改。例如，如果背景模式是PaletteButton，调色板的QColorGroup::Button颜色条目所用的颜色被设置。

如果有一个背景像素映射（使用setPaletteBackgroundPixmap()设置的），那么这个函数的返回值是不确定的。

也可以参考paletteBackgroundPixmap、paletteForegroundColor、palette和colorGroup。

通过setPaletteBackgroundColor()设置属性值，通过paletteBackgroundColor()来获得属性值并且通过unsetPalette()重置属性值。

QPixmap paletteBackgroundPixmap

这个属性保存的是窗口部件的背景像素映射。

这个调色板背景像素映射通常被setBackgroundMode()隐含地设置，尽管它也可以由setPaletteBackgroundPixmap()明显地设置。setPaletteBackgroundPixmap()是一个创建和设置通过setPalette()修改过的QPalette方便函数。这个调色板根据窗口部件的背景模式被修改。例如，如果背景模式是PaletteButton，调色板的QColorGroup::Button颜色条目所用的像素映射被设置。

如果有一个简单的背景颜色（使用setPaletteBackgroundColor()设置的），那么这个函数返回0。

也可以参考paletteBackgroundColor、paletteForegroundColor、palette和colorGroup。

通过setPaletteBackgroundPixmap()设置属性值，通过paletteBackgroundPixmap()来获得属性值并且通过unsetPalette()重置属性值。

QColor paletteForegroundColor

这个属性保存的是窗口部件的前景色。

setPaletteForegroundColor()是一个创建和设置通过setPalette()修改过的QPalette方便函数。这个调色板根据窗口部件的背景模式被修改。例如，如果背景模式是PaletteButton，调色板的QColorGroup::ButtonText颜色条目所用的颜色被设置。

也可以参考palette、QApplication::setPalette()、backgroundMode、foregroundColor()、backgroundMode和setEraseColor()。

通过setPaletteForegroundColor()设置属性值，通过paletteForegroundColor()来获得属性值并且通过unsetPalette().重置属性值。

QPoint pos

这个属性保存的是窗口部件在它的父窗口部件中的位置。

如果这个窗口部件是顶级窗口部件，那它的位置就是在桌面上包括它的框架的窗口部件的位置。

当改变位置时，这个窗口部件如果可视，会立即接收一个移动事件（moveEvent()）。如果这个窗口部件当前不是可视的，它被保证会在它被显示之前收到这个事件。

move()是虚函数，并且Qt中所有其它重载move()的重新实现都调用它。

警告：在moveEvent()调用move()或setGeometry()会导致无限循环。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考frameGeometry、size、x和y。

通过move()设置属性值并且通过pos()来获得属性值。

QRect rect

这个属性保存的是不包含任何窗口框架的窗口部件的内部几何形状。

这个矩形属性等于QRect(0, 0, width(), height())。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考size。

通过rect()来获得属性值。

QSize size

这个属性保存的是不包含任何窗口框架的窗口部件的大小。

当重新定义大小时，这个窗口部件如果可视，会立即收到一个重新定义大小事件（resizeEvent()）。如果这个窗口部件当前不是可视的，它被保证会在它被显示之前收到这个事件。

如果这个大小在minimumSize()和a href="#maximumSize">maximumSize()定义的范围之外，它被调整。此外，这个大小总是至少为QSize(1, 1)。

resize()是虚函数，并且Qt中所有其它重载resize()的重新实现都调用它。

警告：在resizeEvent()调用resize()或setGeometry()会导致无限循环。

也可以参考pos、geometry、minimumSize、maximumSize和resizeEvent()。

通过resize()设置属性值并且通过size()来获得属性值。

QSize sizeHint

这个属性保存的是建议的窗口部件大小。

如果这个属性值是无效的大小，那么就没有大小被建议。

如果这个窗口部件没有布局，sizeHint()的默认实现返回一个无效大小，并且否则的话就返回布局的首选大小。

也可以参考QSize::isValid()、minimumSizeHint、sizePolicy、minimumSize和updateGeometry()。

通过sizeHint()来获得属性值。

QSize sizeIncrement

这个属性保存的是窗口部件的大小增量。

当用户重新定义窗口的大小时，大小会在水平方向上按sizeIncrement().width()像素和垂直方向上按sizeIncrement.height()像素来逐步变化，基础大小为baseSize() 。首选的窗口部件大小为非负整数i和j：

        width = baseSize().width() + i * sizeIncrement().width();
        height = baseSize().height() + j * sizeIncrement().height();

注意，当你为所有的窗口部件设置大小增量时，它只对顶级窗口部件有效。

警告：大小增量在Windows下没有效果，并且也许会被X上的窗口管理器忽视。

也可以参考size、minimumSize和maximumSize。

通过setSizeIncrement()设置属性值并且通过sizeIncrement()来获得属性值。

QSizePolicy sizePolicy

这个属性保存的是窗口部件的默认布局行为。

如果有一个QLayout管理这个窗口部件的子对象，这个大小策略由布局使用的大小策略指定。如果没有这样的QLayout，那么这个函数的结果被使用。

默认策略是首选/首选，也就是说窗口部件可以被自由地重新定义大小，但是首选的是sizeHint()返回的大小。具有按钮特征的窗口部件设置它们的大小策略为水平方向可以伸展，但垂直方向固定。这同样适用于行编辑控件（比如QLineEdit、QSpinBox或可编辑的QComboBox）和其它水平方向的窗口部件（比如QProgressBar）。QToolButton的大小策略通常是允许两个方向都可以变化。支持不同方向的窗口部件（比如QSlider、QScrollBar或QHeader）仅仅按被指定的方向变化。可以提供滚动条的窗口部件（通常是QScrollView的子类）趋向于指定它们可以使用额外的空间，并且它们可以在小于sizeHint()时正常工作。

也可以参考sizeHint、QLayout、QSizePolicy和updateGeometry()。

通过setSizePolicy()设置属性值并且通过sizePolicy()来获得属性值。

bool underMouse

这个属性保存的是窗口部件是否在鼠标光标下。

这个值在拖放操作期间不会被完全地更新。

也可以参考QEvent::Enter和QEvent::Leave。

通过hasMouse()来获得属性值。

bool updatesEnabled

这个属性保存的是更新是否生效。

如果更新失效，调用update()和repaint()是没有效果的。如果更新失效，来自窗口系统的绘制事件会被正常处理。

setUpdatesEnabled()通常被用于在一小段事件内使更新失效，例如为了避免在大的变化期间发生屏幕闪烁。

实例：

    setUpdatesEnabled( FALSE );
    bigVisualChanges();
    setUpdatesEnabled( TRUE );
    repaint();

也可以参考update()、repaint()和paintEvent()。

通过setUpdatesEnabled()设置属性值并且通过isUpdatesEnabled()来获得属性值。

bool visible

这个属性保存的是窗口部件是否可视。

如果窗口部件的父窗口部件直到顶级窗口部件是可视的，调用show()设置它为可视的。如果有一个祖先是不可视的，直到它的所有祖先被显示时，这个窗口部件才会变为可视。

调用hide()明显地隐藏一个窗口部件。一个明显地被隐藏的窗口部件永远不会被变为可视，尽管它的所有祖先都变为可视，除非你显示它。

图标化的顶级窗口部件也处在隐藏状态，也就是isMinimized()返回真。存在于另一个虚拟桌面上的窗口（在一些支持这个概念的平台上）也处在隐藏状态。

一个窗口部件会因为屏幕上其它可视的窗口部件而变暗。

当窗口部件的可视状态发生变化时，它接收显示和隐藏事件。隐藏和显示事件都不需要浪费CPU在准备或显示信息给用户。例如，一个视频应用程序也许只是简单地停止产生新的帧。

也可以参考show(), hide()、hidden、isVisibleTo()、minimized、showEvent()和hideEvent()。

通过isVisible()来获得属性值。

QRect visibleRect

这个属性保存的是窗口部件的当前可视矩形。

这个属性对于优化窗口部件的立即重新绘制很有用。典型用法是：

    repaint( w->visibleRect() );
或
    repaint( w->visibleRect(), FALSE );

如果没有什么是可视的，这个返回的矩形为空。

通过visibleRect()来获得属性值。

int width

这个属性保存的是不包含任何窗口框架的窗口部件宽度。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考geometry、height和size。

通过width()来获得属性值。

int x

这个属性保存的是相对于它的父对象包含任何窗口框架的窗口部件的x坐标。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考frameGeometry、y和pos。

通过x()来获得属性值。

int y

这个属性保存的是相对于它的父对象包含任何窗口框架的窗口部件的y坐标。

对于顶级窗口部件的几何形状的概述请参考窗口几何形状文档。

也可以参考frameGeometry、x和pos。

通过y()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002


qwidget.h包含文件

qwidget.h

这里是qwidget.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qwidget.h   3.0.5   edited Apr 30 21:58 $
**
** Definition of QWidget class
**
** Created : 931029
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWIDGET_H
#define QWIDGET_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qobject.h"
#include "qpaintdevice.h"
#include "qpalette.h"
#include "qfont.h"
#include "qfontmetrics.h"
#include "qfontinfo.h"
#include "qsizepolicy.h"
#endif // QT_H

class QLayout;
struct QWExtra;
struct QTLWExtra;
class QFocusData;
class QCursor;
class QWSRegionManager;
class QStyle;

class Q_EXPORT QWidget : public QObject, public QPaintDevice
{
    Q_OBJECT
    Q_ENUMS( BackgroundMode FocusPolicy BackgroundOrigin )
    Q_PROPERTY( bool isTopLevel READ isTopLevel )
    Q_PROPERTY( bool isDialog READ isDialog )
    Q_PROPERTY( bool isModal READ isModal )
    Q_PROPERTY( bool isPopup READ isPopup )
    Q_PROPERTY( bool isDesktop READ isDesktop )
    Q_PROPERTY( bool enabled READ isEnabled WRITE setEnabled )
    Q_PROPERTY( QRect geometry READ geometry WRITE setGeometry )
    Q_PROPERTY( QRect frameGeometry READ frameGeometry )
    Q_PROPERTY( int x READ x )
    Q_PROPERTY( int y READ y )
    Q_PROPERTY( QPoint pos READ pos WRITE move DESIGNABLE false STORED false )
    Q_PROPERTY( QSize frameSize READ frameSize )
    Q_PROPERTY( QSize size READ size WRITE resize DESIGNABLE false STORED false )
    Q_PROPERTY( int width READ width )
    Q_PROPERTY( int height READ height )
    Q_PROPERTY( QRect rect READ rect )
    Q_PROPERTY( QRect childrenRect READ childrenRect )
    Q_PROPERTY( QRegion childrenRegion READ childrenRegion )
    Q_PROPERTY( QSizePolicy sizePolicy READ sizePolicy WRITE setSizePolicy )
    Q_PROPERTY( QSize minimumSize READ minimumSize WRITE setMinimumSize )
    Q_PROPERTY( QSize maximumSize READ maximumSize WRITE setMaximumSize )
    Q_PROPERTY( int minimumWidth READ minimumWidth WRITE setMinimumWidth STORED false DESIGNABLE false )
    Q_PROPERTY( int minimumHeight READ minimumHeight WRITE setMinimumHeight STORED false DESIGNABLE false )
    Q_PROPERTY( int maximumWidth READ maximumWidth WRITE setMaximumWidth STORED false DESIGNABLE false )
    Q_PROPERTY( int maximumHeight READ maximumHeight WRITE setMaximumHeight STORED false DESIGNABLE false )
    Q_PROPERTY( QSize sizeIncrement READ sizeIncrement WRITE setSizeIncrement )
    Q_PROPERTY( QSize baseSize READ baseSize WRITE setBaseSize )
    Q_PROPERTY( BackgroundMode backgroundMode READ backgroundMode WRITE setBackgroundMode DESIGNABLE false )
    Q_PROPERTY( QColor paletteForegroundColor READ paletteForegroundColor WRITE setPaletteForegroundColor RESET unsetPalette )
    Q_PROPERTY( QColor paletteBackgroundColor READ paletteBackgroundColor WRITE setPaletteBackgroundColor RESET unsetPalette )
    Q_PROPERTY( QPixmap paletteBackgroundPixmap READ paletteBackgroundPixmap WRITE setPaletteBackgroundPixmap RESET unsetPalette )
    Q_PROPERTY( QBrush backgroundBrush READ backgroundBrush )
    Q_PROPERTY( QColorGroup colorGroup READ colorGroup )
    Q_PROPERTY( QPalette palette READ palette WRITE setPalette RESET unsetPalette  STORED ownPalette )
    Q_PROPERTY( BackgroundOrigin backgroundOrigin READ backgroundOrigin WRITE setBackgroundOrigin )
    Q_PROPERTY( bool ownPalette READ ownPalette )
    Q_PROPERTY( QFont font READ font WRITE setFont RESET unsetFont STORED ownFont )
    Q_PROPERTY( bool ownFont READ ownFont )
#ifndef QT_NO_CURSOR
    Q_PROPERTY( QCursor cursor READ cursor WRITE setCursor RESET unsetCursor STORED ownCursor )
    Q_PROPERTY( bool ownCursor READ ownCursor )
#endif
#ifndef QT_NO_WIDGET_TOPEXTRA
    Q_PROPERTY( QString caption READ caption WRITE setCaption )
    Q_PROPERTY( QPixmap icon READ icon WRITE setIcon )
    Q_PROPERTY( QString iconText READ iconText WRITE setIconText )
#endif
    Q_PROPERTY( bool mouseTracking READ hasMouseTracking WRITE setMouseTracking )
    Q_PROPERTY( bool underMouse READ hasMouse )
    Q_PROPERTY( bool isActiveWindow READ isActiveWindow )
    Q_PROPERTY( bool focusEnabled READ isFocusEnabled )
    Q_PROPERTY( FocusPolicy focusPolicy READ focusPolicy WRITE setFocusPolicy )
    Q_PROPERTY( bool focus READ hasFocus )
    Q_PROPERTY( bool updatesEnabled READ isUpdatesEnabled WRITE setUpdatesEnabled DESIGNABLE false )
    Q_PROPERTY( bool visible READ isVisible )
    Q_PROPERTY( QRect visibleRect READ visibleRect )
    Q_PROPERTY( bool hidden READ isHidden )
    Q_PROPERTY( bool minimized READ isMinimized )
    Q_PROPERTY( QSize sizeHint READ sizeHint )
    Q_PROPERTY( QSize minimumSizeHint READ minimumSizeHint )
    Q_PROPERTY( QRect microFocusHint READ microFocusHint )
    Q_PROPERTY( bool acceptDrops READ acceptDrops WRITE setAcceptDrops )
    Q_PROPERTY( bool autoMask READ autoMask WRITE setAutoMask DESIGNABLE false SCRIPTABLE false )
    Q_PROPERTY( bool customWhatsThis READ customWhatsThis )

public:
    QWidget( QWidget* parent=0, const char* name=0, WFlags f=0 );
    ~QWidget();

    WId		 winId() const;
    void	 setName( const char *name );
#ifndef QT_NO_STYLE
    // GUI style setting

    QStyle     &style() const;
    void        setStyle( QStyle * );
    QStyle*	setStyle( const QString& );
#endif
    // Widget types and states

    bool	 isTopLevel()	const;
    bool	 isDialog()	const;
    bool	 isPopup()	const;
    bool	 isDesktop()	const;
    bool	 isModal()	const;

    bool	 isEnabled()	const;
    bool	 isEnabledTo(QWidget*) const;
    bool	 isEnabledToTLW() const;

public slots:
    virtual void setEnabled( bool );
    void setDisabled( bool );

    // Widget coordinates

public:
    QRect	 frameGeometry() const;
    const QRect &geometry()	const;
    int		 x()		const;
    int		 y()		const;
    QPoint	 pos()		const;
    QSize	 frameSize()    const;
    QSize	 size()		const;
    int		 width()	const;
    int		 height()	const;
    QRect	 rect()		const;
    QRect	 childrenRect() const;
    QRegion	 childrenRegion() const;

    QSize	 minimumSize()	 const;
    QSize	 maximumSize()	 const;
    int		 minimumWidth()	 const;
    int		 minimumHeight() const;
    int		 maximumWidth()	 const;
    int		 maximumHeight() const;
    void	 setMinimumSize( const QSize & );
    virtual void setMinimumSize( int minw, int minh );
    void	 setMaximumSize( const QSize & );
    virtual void setMaximumSize( int maxw, int maxh );
    void	 setMinimumWidth( int minw );
    void	 setMinimumHeight( int minh );
    void	 setMaximumWidth( int maxw );
    void	 setMaximumHeight( int maxh );

    QSize	 sizeIncrement() const;
    void	 setSizeIncrement( const QSize & );
    virtual void setSizeIncrement( int w, int h );
    QSize	 baseSize() const;
    void	 setBaseSize( const QSize & );
    void	 setBaseSize( int basew, int baseh );

    void	setFixedSize( const QSize & );
    void	setFixedSize( int w, int h );
    void	setFixedWidth( int w );
    void	setFixedHeight( int h );

    // Widget coordinate mapping

    QPoint	 mapToGlobal( const QPoint & )	 const;
    QPoint	 mapFromGlobal( const QPoint & ) const;
    QPoint	 mapToParent( const QPoint & )	 const;
    QPoint	 mapFromParent( const QPoint & ) const;
    QPoint	 mapTo( QWidget *, const QPoint & ) const;
    QPoint	 mapFrom( QWidget *, const QPoint & ) const;

    QWidget	*topLevelWidget()   const;

    // Widget attribute functions

    BackgroundMode	backgroundMode() const;
    virtual void	setBackgroundMode( BackgroundMode );
    void 		setBackgroundMode( BackgroundMode, BackgroundMode );

    const QColor &	foregroundColor() const;

    const QColor &	eraseColor() const;
    virtual void	setEraseColor( const QColor & );

    const QPixmap *	erasePixmap() const;
    virtual void	setErasePixmap( const QPixmap & );

#ifndef QT_NO_PALETTE
    const QColorGroup & colorGroup() const;
    const QPalette &	palette()    const;
    bool		ownPalette() const;
    virtual void	setPalette( const QPalette & );
    void		unsetPalette();
#endif

    const QColor &	paletteForegroundColor() const;
    void		setPaletteForegroundColor( const QColor & );

    const QColor &	paletteBackgroundColor() const;
    virtual void	setPaletteBackgroundColor( const QColor & );

    const QPixmap *	paletteBackgroundPixmap() const;
    virtual void 	setPaletteBackgroundPixmap( const QPixmap & );

    const QBrush&	backgroundBrush() const;

    QFont		font() const;
    bool		ownFont() const;
    virtual void	setFont( const QFont & );
    void		unsetFont();
    QFontMetrics	fontMetrics() const;
    QFontInfo	 	fontInfo() const;

#ifndef QT_NO_CURSOR
    const QCursor      &cursor() const;
    bool		ownCursor() const;
    virtual void	setCursor( const QCursor & );
    virtual void	unsetCursor();
#endif
#ifndef QT_NO_WIDGET_TOPEXTRA
    QString		caption() const;
    const QPixmap      *icon() const;
    QString		iconText() const;
#endif
    bool		hasMouseTracking() const;
    bool		hasMouse() const;

    virtual void	setMask( const QBitmap & );
    virtual void	setMask( const QRegion & );
    void		clearMask();

    const QColor &	backgroundColor() const; // obsolete, use eraseColor()
    virtual void	setBackgroundColor( const QColor & ); // obsolete, use setEraseColor()
    const QPixmap *	backgroundPixmap() const; // obsolete, use erasePixmap()
    virtual void	setBackgroundPixmap( const QPixmap & ); // obsolete, use setErasePixmap()

public slots:
#ifndef QT_NO_WIDGET_TOPEXTRA
    virtual void	setCaption( const QString &);
    virtual void	setIcon( const QPixmap & );
    virtual void	setIconText( const QString &);
#endif
    virtual void	setMouseTracking( bool enable );

    // Keyboard input focus functions

    virtual void	setFocus();
    void		clearFocus();

public:
    enum FocusPolicy {
    NoFocus = 0,
    TabFocus = 0x1,
    ClickFocus = 0x2,
    StrongFocus = 0x3,
    WheelFocus = 0x7
    };

    bool		isActiveWindow() const;
    virtual void	setActiveWindow();
    bool		isFocusEnabled() const;

    FocusPolicy		focusPolicy() const;
    virtual void	setFocusPolicy( FocusPolicy );
    bool		hasFocus() const;
    static void		setTabOrder( QWidget *, QWidget * );
    virtual void	setFocusProxy( QWidget * );
    QWidget *		focusProxy() const;

    // Grab functions

    void		grabMouse();
#ifndef QT_NO_CURSOR
    void		grabMouse( const QCursor & );
#endif
    void		releaseMouse();
    void		grabKeyboard();
    void		releaseKeyboard();
    static QWidget *	mouseGrabber();
    static QWidget *	keyboardGrabber();

    // Update/refresh functions

    bool	 	isUpdatesEnabled() const;

#if 0 //def Q_WS_QWS
    void		repaintUnclipped( const QRegion &, bool erase = TRUE );
#endif
public slots:
    virtual void	setUpdatesEnabled( bool enable );
    void		update();
    void		update( int x, int y, int w, int h );
    void		update( const QRect& );
    void		repaint();
    void		repaint( bool erase );
    void		repaint( int x, int y, int w, int h, bool erase=TRUE );
    void		repaint( const QRect &, bool erase = TRUE );
    void		repaint( const QRegion &, bool erase = TRUE );

    // Widget management functions

    virtual void	show();
    virtual void	hide();
#ifndef QT_NO_COMPAT
    void		iconify()	{ showMinimized(); }
#endif
    virtual void	showMinimized();
    virtual void	showMaximized();
    void		showFullScreen(); // virtual 3.0
    virtual void	showNormal();
    virtual void	polish();
    void 		constPolish() const;
    bool		close();

    void		raise();
    void		lower();
    void		stackUnder( QWidget* );
    virtual void	move( int x, int y );
    void		move( const QPoint & );
    virtual void	resize( int w, int h );
    void		resize( const QSize & );
    virtual void	setGeometry( int x, int y, int w, int h );
    virtual void	setGeometry( const QRect & );

public:
    virtual bool	close( bool alsoDelete );
    bool		isVisible()	const;
    bool		isVisibleTo(QWidget*) const;
    bool		isVisibleToTLW() const; // obsolete
    QRect		visibleRect() const;
    bool 		isHidden() const;
    bool		isMinimized() const;
    bool		isMaximized() const;

    virtual QSize	sizeHint() const;
    virtual QSize	minimumSizeHint() const;
    virtual QSizePolicy	sizePolicy() const;
    virtual void		setSizePolicy( QSizePolicy );
    virtual int heightForWidth(int) const;

    virtual void  	adjustSize();
#ifndef QT_NO_LAYOUT
    QLayout *		layout() const { return lay_out; }
#endif
    void		updateGeometry();
    virtual void 	reparent( QWidget *parent, WFlags, const QPoint &,
                  bool showIt=FALSE );
    void		reparent( QWidget *parent, const QPoint &,
                  bool showIt=FALSE );
#ifndef QT_NO_COMPAT
    void		recreate( QWidget *parent, WFlags f, const QPoint & p,
                  bool showIt=FALSE ) { reparent(parent,f,p,showIt); }
#endif

    void		erase();
    void		erase( int x, int y, int w, int h );
    void		erase( const QRect & );
    void		erase( const QRegion & );
    void		scroll( int dx, int dy );
    void		scroll( int dx, int dy, const QRect& );

    void		drawText( int x, int y, const QString &);
    void		drawText( const QPoint &, const QString &);

    // Misc. functions

    QWidget *		focusWidget() const;
    QRect               microFocusHint() const;

    // drag and drop

    bool		acceptDrops() const;
    virtual void	setAcceptDrops( bool on );

    // transparency and pseudo transparency

    virtual void	setAutoMask(bool);
    bool		autoMask() const;

    enum BackgroundOrigin { WidgetOrigin, ParentOrigin, WindowOrigin };

    virtual void setBackgroundOrigin( BackgroundOrigin );
    BackgroundOrigin backgroundOrigin() const;

    // whats this help
    virtual bool customWhatsThis() const;

    QWidget *		parentWidget( bool sameWindow = FALSE ) const;
    WState		testWState( WState s ) const;
    WFlags		testWFlags( WFlags f ) const;
    static QWidget *	find( WId );
    static QWidgetMapper *wmapper();

    QWidget  *childAt( int x, int y, bool includeThis = FALSE ) const;
    QWidget  *childAt( const QPoint &, bool includeThis = FALSE ) const;

#if defined(Q_WS_QWS)
    virtual QGfx * graphicsContext(bool clip_children=TRUE) const;
#endif
#if defined(Q_WS_MAC)
    QRegion clippedRegion(bool do_children=TRUE);
    uint clippedSerial(bool do_children=TRUE);
#ifndef QMAC_NO_QUARTZ
    CGContextRef macCGContext(bool clipped=TRUE) const;
#endif
#endif

protected:
    // Event handlers
    bool	 event( QEvent * );
    virtual void mousePressEvent( QMouseEvent * );
    virtual void mouseReleaseEvent( QMouseEvent * );
    virtual void mouseDoubleClickEvent( QMouseEvent * );
    virtual void mouseMoveEvent( QMouseEvent * );
#ifndef QT_NO_WHEELEVENT
    virtual void wheelEvent( QWheelEvent * );
#endif
    virtual void keyPressEvent( QKeyEvent * );
    virtual void keyReleaseEvent( QKeyEvent * );
    virtual void focusInEvent( QFocusEvent * );
    virtual void focusOutEvent( QFocusEvent * );
    virtual void enterEvent( QEvent * );
    virtual void leaveEvent( QEvent * );
    virtual void paintEvent( QPaintEvent * );
    virtual void moveEvent( QMoveEvent * );
    virtual void resizeEvent( QResizeEvent * );
    virtual void closeEvent( QCloseEvent * );
    virtual void contextMenuEvent( QContextMenuEvent * );
    virtual void imStartEvent( QIMEvent * );
    virtual void imComposeEvent( QIMEvent * );
    virtual void imEndEvent( QIMEvent * );
    virtual void tabletEvent( QTabletEvent * );

#ifndef QT_NO_DRAGANDDROP
    virtual void dragEnterEvent( QDragEnterEvent * );
    virtual void dragMoveEvent( QDragMoveEvent * );
    virtual void dragLeaveEvent( QDragLeaveEvent * );
    virtual void dropEvent( QDropEvent * );
#endif

    virtual void showEvent( QShowEvent * );
    virtual void hideEvent( QHideEvent * );

#if defined(Q_WS_MAC)
    virtual bool macEvent( MSG * );
#endif
#if defined(Q_WS_WIN)
    virtual bool winEvent( MSG * );
#endif
#if defined(Q_WS_X11)
    virtual bool x11Event( XEvent * );
#endif
#if defined(Q_WS_QWS)
    virtual bool qwsEvent( QWSEvent * );
    virtual unsigned char *scanLine( int ) const;
    virtual int bytesPerLine() const;
#endif

    virtual void updateMask();

    // Misc. protected functions

#ifndef QT_NO_STYLE
    virtual void styleChange( QStyle& );
#endif
    virtual void enabledChange( bool oldEnabled );
#ifndef QT_NO_PALETTE
    virtual void paletteChange( const QPalette & );
#endif
    virtual void fontChange( const QFont & );
    virtual void windowActivationChange( bool oldActive );

    int		 metric( int )	const;

    void	 resetInputContext();

    virtual void create( WId = 0, bool initializeWindow = TRUE,
             bool destroyOldWindow = TRUE );
    virtual void destroy( bool destroyWindow = TRUE,
              bool destroySubWindows = TRUE );
    uint	 getWState() const;
    virtual void setWState( uint );
    void	 clearWState( uint n );
    WFlags	 getWFlags() const;
    virtual void setWFlags( WFlags );
    void	 clearWFlags( WFlags n );

    virtual bool focusNextPrevChild( bool next );

    QWExtra	*extraData();
    QTLWExtra	*topData();
    QFocusData	*focusData();

    virtual void setKeyCompression(bool);
    virtual void setMicroFocusHint(int x, int y, int w, int h, bool text=TRUE, QFont *f = 0);

#if defined(Q_WS_MAC)
    void dirtyClippedRegion(bool);
    bool isClippedRegionDirty();
#endif

private slots:
    void	 focusProxyDestroyed();

private:
    void	 setFontSys( QFont *f = 0 );
#if defined(Q_WS_X11)
    void	 createInputContext();
    void	 destroyInputContext();
    void	 focusInputContext();
    void	 checkChildrenDnd();
#elif defined(Q_WS_MAC)
    uint    own_id : 1, macDropEnabled : 1;
    EventHandlerRef window_event;
    //mac event functions
    void    propagateUpdates();
    void    update( const QRegion& );
    //friends, way too many - fix this immediatly!
    friend void qt_clean_root_win();
    friend bool qt_recreate_root_win();
    friend QPoint posInWindow(QWidget *);
    friend QWidget *qt_recursive_match(QWidget *widg, int x, int y);
    friend void qt_paint_children(QWidget *,QRegion &, uchar ops);
    friend void qt_event_request_updates(QWidget *, QRegion &);
    friend bool qt_window_rgn(WId, short, RgnHandle, bool);
    friend class QDragManager;
#endif

#ifndef QT_NO_LAYOUT
    void 	 setLayout( QLayout *l );
#endif
    void	 setWinId( WId );
    void	 showWindow();
    void	 hideWindow();
    void	 sendShowEventsToChildren( bool spontaneous );
    void	 sendHideEventsToChildren( bool spontaneous );
    void	 reparentSys( QWidget *parent, WFlags, const QPoint &,  bool showIt);
    void	 createTLExtra();
    void	 createExtra();
    void	 deleteExtra();
    void	 createSysExtra();
    void	 deleteSysExtra();
    void	 createTLSysExtra();
    void	 deleteTLSysExtra();
    void	 deactivateWidgetCleanup();
    void	 internalSetGeometry( int, int, int, int, bool );
    void	 reparentFocusWidgets( QWidget * );
    QFocusData	*focusData( bool create );
    void         setBackgroundFromMode();
    void         setBackgroundColorDirect( const QColor & );
    void   	 setBackgroundPixmapDirect( const QPixmap & );
    void         setBackgroundModeDirect( BackgroundMode );
    void         setBackgroundEmpty();
    void	 updateFrameStrut() const;
#if defined(Q_WS_X11)
    void         setBackgroundX11Relative();
#endif

    WId		 winid;
    uint	 widget_state;
    uint	 widget_flags;
    uint	 focus_policy : 4;
    uint 	 own_font :1;
    uint 	 own_palette :1;
    uint 	 sizehint_forced :1;
    uint 	 is_closing :1;
    uint 	 in_show : 1;
    uint 	 in_show_maximized : 1;
    uint	 fstrut_dirty : 1;
    QRect	 crect;
    QColor	 bg_col;
#ifndef QT_NO_PALETTE
    QPalette	 pal;
#endif
    QFont	 fnt;
#ifndef QT_NO_LAYOUT
    QLayout 	*lay_out;
#endif
    QWExtra	*extra;
#if defined(Q_WS_QWS)
    QRegion	 req_region;			// Requested region
    mutable QRegion	 paintable_region;	// Paintable region
    mutable bool         paintable_region_dirty;// needs to be recalculated
    mutable QRegion      alloc_region;          // Allocated region
    mutable bool         alloc_region_dirty;    // needs to be recalculated
    mutable int          overlapping_children;  // Handle overlapping children

    int		 alloc_region_index;
    int		 alloc_region_revision;

    void updateOverlappingChildren() const;
    void setChildrenAllocatedDirty();
    bool isAllocatedRegionDirty() const;
    QRegion requestedRegion() const;
    QRegion allocatedRegion() const;
    QRegion paintableRegion() const;

    // used to accumulate dirty region when children moved/resized.
    QRegion dirtyChildren;
    bool isSettingGeometry;
    friend class QWSManager;
#endif

    static void	 createMapper();
    static void	 destroyMapper();
    static QWidgetList	 *wList();
    static QWidgetList	 *tlwList();
    static QWidgetMapper *mapper;
    friend class QApplication;
    friend class QBaseApplication;
    friend class QPainter;
    friend class QFontMetrics;
    friend class QFontInfo;
    friend class QETWidget;
    friend class QLayout;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QWidget( const QWidget & );
    QWidget &operator=( const QWidget & );
#endif

public: // obsolete functions to dissappear or to become inline in 3.0
#ifndef QT_NO_PALETTE
    void setPalette( const QPalette &p, bool ) { setPalette( p ); }
#endif
    void setFont( const QFont &f, bool ) { setFont( f ); }
};

inline Qt::WState QWidget::testWState( WState s ) const
{ return (widget_state & s); }

inline Qt::WFlags QWidget::testWFlags( WFlags f ) const
{ return (widget_flags & f); }

inline WId QWidget::winId() const
{ return winid; }

inline bool QWidget::isTopLevel() const
{ return testWFlags(WType_TopLevel); }

inline bool QWidget::isDialog() const
{ return testWFlags(WType_Dialog); }

inline bool QWidget::isPopup() const
{ return testWFlags(WType_Popup); }

inline bool QWidget::isDesktop() const
{ return testWFlags(WType_Desktop); }

inline bool QWidget::isEnabled() const
{ return !testWState(WState_Disabled); }

inline bool QWidget::isModal() const
{ return testWFlags(WShowModal); }

inline bool QWidget::isEnabledToTLW() const
{ return isEnabled(); }

inline const QRect &QWidget::geometry() const
{ return crect; }

inline QSize QWidget::size() const
{ return crect.size(); }

inline int QWidget::width() const
{ return crect.width(); }

inline int QWidget::height() const
{ return crect.height(); }

inline QRect QWidget::rect() const
{ return QRect(0,0,crect.width(),crect.height()); }

inline int QWidget::minimumWidth() const
{ return minimumSize().width(); }

inline int QWidget::minimumHeight() const
{ return minimumSize().height(); }

inline int QWidget::maximumWidth() const
{ return maximumSize().width(); }

inline int QWidget::maximumHeight() const
{ return maximumSize().height(); }

inline void QWidget::setMinimumSize( const QSize &s )
{ setMinimumSize(s.width(),s.height()); }

inline void QWidget::setMaximumSize( const QSize &s )
{ setMaximumSize(s.width(),s.height()); }

inline void QWidget::setSizeIncrement( const QSize &s )
{ setSizeIncrement(s.width(),s.height()); }

inline void QWidget::setBaseSize( const QSize &s )
{ setBaseSize(s.width(),s.height()); }

inline const QColor &QWidget::eraseColor() const
{ return bg_col; }

#ifndef QT_NO_PALETTE
inline const QPalette &QWidget::palette() const
{ return pal; }
#endif

inline QFont QWidget::font() const
{ return fnt; }

inline QFontMetrics QWidget::fontMetrics() const
{ return QFontMetrics(font()); }

inline QFontInfo QWidget::fontInfo() const
{ return QFontInfo(font()); }

inline bool QWidget::hasMouseTracking() const
{ return testWState(WState_MouseTracking); }

inline bool QWidget::hasMouse() const
{ return testWState(WState_HasMouse); }

inline bool  QWidget::isFocusEnabled() const
{ return (FocusPolicy)focus_policy != NoFocus; }

inline QWidget::FocusPolicy QWidget::focusPolicy() const
{ return (FocusPolicy)focus_policy; }

inline bool QWidget::isUpdatesEnabled() const
{ return !testWState(WState_BlockUpdates); }

inline void QWidget::update( const QRect &r )
{ update( r.x(), r.y(), r.width(), r.height() ); }

inline void QWidget::repaint()
{ repaint( 0, 0, crect.width(), crect.height(), TRUE ); }

inline void QWidget::repaint( bool erase )
{ repaint( 0, 0, crect.width(), crect.height(), erase ); }

inline void QWidget::repaint( const QRect &r, bool erase )
{ repaint( r.x(), r.y(), r.width(), r.height(), erase ); }

inline void QWidget::erase()
{ erase( 0, 0, crect.width(), crect.height() ); }

inline void QWidget::erase( const QRect &r )
{ erase( r.x(), r.y(), r.width(), r.height() ); }

inline bool QWidget::close()
{ return close( FALSE ); }

inline bool QWidget::isVisible() const
{ return testWState(WState_Visible); }

inline bool QWidget::isVisibleToTLW() const // obsolete
{ return isVisible(); }

inline bool QWidget::isHidden() const
{ return testWState(WState_ForceHide); }

inline void QWidget::move( const QPoint &p )
{ move( p.x(), p.y() ); }

inline void QWidget::resize( const QSize &s )
{ resize( s.width(), s.height()); }

inline void QWidget::setGeometry( const QRect &r )
{ setGeometry( r.left(), r.top(), r.width(), r.height() ); }

inline void QWidget::drawText( const QPoint &p, const QString &s )
{ drawText( p.x(), p.y(), s ); }

inline QWidget *QWidget::parentWidget( bool sameWindow ) const
{
    if ( sameWindow )
    return isTopLevel() ? 0 : (QWidget *)QObject::parent();
    return (QWidget *)QObject::parent();
}

inline QWidgetMapper *QWidget::wmapper()
{ return mapper; }

inline uint QWidget::getWState() const
{ return widget_state; }

inline void QWidget::setWState( uint f )
{ widget_state |= f; }

inline void QWidget::clearWState( uint f )
{ widget_state &= ~f; }

inline Qt::WFlags QWidget::getWFlags() const
{ return widget_flags; }

inline void QWidget::setWFlags( WFlags f )
{ widget_flags |= f; }

inline void QWidget::clearWFlags( WFlags f )
{ widget_flags &= ~f; }

inline void QWidget::constPolish() const
{
    if ( !testWState(WState_Polished) ) {
    QWidget* that = (QWidget*) this;
    that->polish();
        that->setWState(WState_Polished); // be on the safe side...
    }
}
#ifndef QT_NO_CURSOR
inline bool QWidget::ownCursor() const
{
    return testWState( WState_OwnCursor );
}
#endif
inline bool QWidget::ownFont() const
{
    return own_font;
}
#ifndef QT_NO_PALETTE
inline bool QWidget::ownPalette() const
{
    return own_palette;
}
#endif

// Extra QWidget data
//  - to minimize memory usage for members that are seldom used.
//  - top-level widgets have extra extra data to reduce cost further

class QFocusData;
class QWSManager;
#if defined(Q_WS_WIN)
class QOleDropTarget;
#endif
#if defined(Q_WS_MAC)
class QMacDndExtra;
#endif

struct Q_EXPORT QTLWExtra {
#ifndef QT_NO_WIDGET_TOPEXTRA
    QString  caption;				// widget caption
    QString  iconText;				// widget icon text
    QPixmap *icon;				// widget icon
#endif
    QFocusData *focusData;			// focus data (for TLW)
    short    incw, inch;			// size increments
    // frame strut
    ulong    fleft, fright, ftop, fbottom;
    uint     iconic: 1;				// iconified [cur. win32 only]
    uint     fullscreen : 1;			// full-screen mode
    uint     showMode: 2;			// 0 normal, 1 minimized, 2 maximized, 3 reset
    short    basew, baseh;			// base sizes
#if defined(Q_WS_X11)
    WId  parentWinId;			// parent window Id (valid after reparenting)
    uint     embedded : 1;			// window is embedded in another Qt application
    uint     reserved: 2;			// reserved
    uint     dnd : 1; 				// DND properties installed
    uint     uspos : 1;                         // User defined position
    uint     ussize : 1;                        // User defined size
    void    *xic;				// XIM Input Context
#endif
#if defined(Q_WS_MAC)
    WindowGroupRef group;
#endif
#if defined(Q_WS_QWS) && !defined ( QT_NO_QWS_MANAGER )
    QRegion decor_allocated_region;		// decoration allocated region
    QWSManager *qwsManager;
#endif
#if defined(Q_WS_WIN)
    HICON    winIcon;				// internal Windows icon
#endif
    QRect    normalGeometry;			// used by showMin/maximized/FullScreen
};

#define QWIDGETSIZE_MAX 32767

// dear user: you can see this struct, but it is internal. do not touch.

struct Q_EXPORT QWExtra {
    Q_INT16  minw, minh;			// minimum size
    Q_INT16  maxw, maxh;			// maximum size
    QPixmap *bg_pix;				// background pixmap
    QWidget *focus_proxy;
#ifndef QT_NO_CURSOR
    QCursor *curs;
#endif
    QTLWExtra *topextra;			// only useful for TLWs
#if defined(Q_WS_WIN)
    QOleDropTarget *dropTarget;			// drop target
#endif
#if defined(Q_WS_X11)
    WId xDndProxy;			// XDND forwarding to embedded windows
#endif
#if defined(Q_WS_MAC)
    QRegion clip_saved, clip_sibs, clip_children;
    QMacDndExtra *macDndExtra;
    QRegion dirty_area;
    uint clip_dirty : 1, clip_serial : 15;
    uint child_dirty : 1, child_serial : 15;
#ifndef QMAC_NO_QUARTZ
    uint ctx_children_clipped:1;
#endif
    uint has_dirty_area:1;
#endif
    uint bg_origin : 2;
#if defined(Q_WS_X11)
    uint children_use_dnd : 1;
#endif
#if defined(Q_WS_QWS) || defined(Q_WS_MAC)
    QRegion mask;				// widget mask
#endif
    char     bg_mode;				// background mode
    char     bg_mode_visual;				// visual background mode
#ifndef QT_NO_STYLE
    QStyle* style;
#endif
    QRect micro_focus_hint;                     // micro focus hint
    QSizePolicy size_policy;
};

#endif // QWIDGET_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWidget成员列表

完整的QWidget成员列表

这里是QWidget成员函数的完整列表，包括继承的成员。

  • QWidget()
  • ~QWidget()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWidgetFactory Class

QWidgetFactory Class Reference

The QWidgetFactory class provides for the dynamic creation of widgets from Qt Designer .ui files. More...

#include <qwidgetfactory.h>

List of all member functions.

Public Members

  • QWidgetFactory ()
  • virtual ~QWidgetFactory ()
  • virtual QWidget * createWidget ( const QString & className, QWidget * parent, const char * name ) const

Static Public Members

  • QWidget * create ( const QString & uiFile, QObject * connector = 0, QWidget * parent = 0, const char * name = 0 )
  • QWidget * create ( QIODevice * dev, QObject * connector = 0, QWidget * parent = 0, const char * name = 0 )
  • void addWidgetFactory ( QWidgetFactory * factory )
  • void loadImages ( const QString & dir )

Detailed Description

The QWidgetFactory class provides for the dynamic creation of widgets from Qt Designer .ui files.

This class basically offers two things:

  • Dynamically creating widgets from Qt Designer Qt Designer user interface description files. You can do this using the static function QWidgetFactory::create(). This function also performs signal and slot connections, tab ordering, etc., as defined in the .ui file, and returns the top-level widget in the .ui file. After creating the widget you can use QObject::child() and QObject::queryList() to access child widgets of this returned widget.

  • Adding additional widget factories to be able to create custom widgets. See createWidget() for details.

This class is not included in the Qt library itself. To use it you must link against libqui.so (Unix) or qui.lib (Windows), which is built into $(QTDIR)/lib if you built Qt Designer.

See the "Creating Dynamic Dialogs from .ui Files" section of the Qt Designer manual for an example. See also the QWidgetPlugin class and the Plugins documentation.

Member Function Documentation

QWidgetFactory::QWidgetFactory ()

Constructs a QWidgetFactory.

QWidgetFactory::~QWidgetFactory () [virtual]

Destructor.

void QWidgetFactory::addWidgetFactory ( QWidgetFactory * factory ) [static]

Installs a widget factory factory, which normally contains additional widgets that can then be created using a QWidgetFactory. See createWidget() for further details.

QWidget * QWidgetFactory::create ( const QString & uiFile, QObject * connector = 0, QWidget * parent = 0, const char * name = 0 ) [static]

Loads the Qt Designer user interface description file uiFile and returns the top-level widget in that description. parent and name are passed to the constructor of the top-level widget.

This function also performs signal and slot connections, tab ordering, etc., as described in the .ui file. In Qt Designer it is possible to add custom slots to a form and connect to them. If you want these connections to be made, you must create a class derived from QObject, which implements all these slots. Then pass an instance of the object as connector to this function. If you do this, the connections to the custom slots will be done using the connector as slot.

If something fails, 0 is returned.

The ownership of the returned widget is passed to the caller.

QWidget * QWidgetFactory::create ( QIODevice * dev, QObject * connector = 0, QWidget * parent = 0, const char * name = 0 ) [static]

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

Loads the user interface description from device dev.

QWidget * QWidgetFactory::createWidget ( const QString & className, QWidget * parent, const char * name ) const [virtual]

Creates a widget of the type className passing parent and name to its constructor.

If className is a widget in the Qt library, it is directly created by this function. If the widget isn't in the Qt library, each of the installed widget plugins is asked, in turn, to create the widget. As soon as a plugin says it can create the widget it is asked to do so. It may occur that none of the plugins can create the widget, in which case each installed widget factory is asked to create the widget (see addWidgetFactory()). If the widget cannot be created by any of these means, 0 is returned.

If you have a custom widget, and want it to be created using the widget factory, there are two approaches you can use:

  1. Write a widget plugin. This allows you to use the widget in Qt Designer and in this QWidgetFactory. See the widget plugin documentation for further details. (See the "Creating Custom Widgets with Plugins" section of the Qt Designer manual for an example.

  2. Subclass QWidgetFactory. Then reimplement this function to create and return an instance of your custom widget if className equals the name of your widget, otherwise return 0. Then at the beginning of your program where you want to use the widget factory to create widgets do a:
        QWidgetFactory::addWidgetFactory( new MyWidgetFactory );
    where MyWidgetFactory is your QWidgetFactory subclass.

void QWidgetFactory::loadImages ( const QString & dir ) [static]

If you use a pixmap collection (which is the default for new projects) rather than saving the pixmaps within the .ui XML file, you must load the pixmap collection. QWidgetFactory looks in the default QMimeSourceFactory for the pixmaps. Either add it there manually, or call this function and specify the directory where the images can be found, as dir. This is normally the directory called images in the project's directory.

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


qwidgetfactory.h Include File

qwidgetfactory.h

This is the verbatim text of the qwidgetfactory.h include file. It is provided only for illustration; the copyright remains with Trolltech.

 /**********************************************************************
** Copyright (C) 2000 Trolltech AS.  All rights reserved.
**
** This file is part of Qt Designer.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWIDGETFACTORY_H
#define QWIDGETFACTORY_H

#ifndef QT_H
#include <qstring.h>
#include <qptrlist.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qvaluelist.h>
#include <qmap.h>
#include <qaction.h>
#endif // QT_H

class QWidget;
class QLayout;
class QDomElement;
class QListViewItem;
class QTable;

class QWidgetFactory
{
public:
    QWidgetFactory();
    virtual ~QWidgetFactory();

    static QWidget *create( const QString &uiFile, QObject *connector = 0, QWidget *parent = 0, const char *name = 0 );
    static QWidget *create( QIODevice *dev, QObject *connector = 0, QWidget *parent = 0, const char *name = 0 );
    static void addWidgetFactory( QWidgetFactory *factory );
    static void loadImages( const QString &dir );

    virtual QWidget *createWidget( const QString &className, QWidget *parent, const char *name ) const;

private:
    enum LayoutType { HBox, VBox, Grid, NoLayout };
    void loadImageCollection( const QDomElement &e );
    void loadConnections( const QDomElement &e, QObject *connector );
    void loadTabOrder( const QDomElement &e );
    QWidget *createWidgetInternal( const QDomElement &e, QWidget *parent, QLayout* layout, const QString &classNameArg );
    QLayout *createLayout( QWidget *widget, QLayout*  layout, LayoutType type );
    LayoutType layoutType( QLayout *l ) const;
    void setProperty( QObject* widget, const QString &prop, const QDomElement &e );
    void createSpacer( const QDomElement &e, QLayout *layout );
    QImage loadFromCollection( const QString &name );
    QPixmap loadPixmap( const QDomElement &e );
    QColorGroup loadColorGroup( const QDomElement &e );
    void createColumn( const QDomElement &e, QWidget *widget );
    void loadItem( const QDomElement &e, QPixmap &pix, QString &txt, bool &hasPixmap );
    void createItem( const QDomElement &e, QWidget *widget, QListViewItem *i = 0 );
    void loadChildAction( QObject *parent, const QDomElement &e );
    void loadActions( const QDomElement &e );
    void loadToolBars( const QDomElement &e );
    void loadMenuBar( const QDomElement &e );
    void loadFunctions( const QDomElement &e );
    QAction *findAction( const QString &name );
    void loadExtraSource();
    QString translate( const QString& sourceText, const QString& comment = "" );

private:
    struct Image {
    QImage img;
    QString name;
    bool operator==(  const Image &i ) const {
        return ( i.name == name &&
             i.img == img );
    }
    };

    struct Field
    {
    Field() {}
    Field( const QString &s1, const QPixmap &p, const QString &s2 ) : name( s1 ), pix( p ), field( s2 ) {}
    QString name;
    QPixmap pix;
    QString field;
#if defined(Q_FULL_TEMPLATE_INSTANTIATION)
    bool operator==( const Field& ) const { return FALSE; }
#endif
    };

    struct EventFunction
    {
    EventFunction() {}
    EventFunction( const QString &e, const QStringList &f )
        : events( e ) { functions.append( f ); }
    QStringList events;
    QValueList<QStringList> functions;
    };

    struct SqlWidgetConnection
    {
    SqlWidgetConnection() {}
    SqlWidgetConnection( const QString &c, const QString &t )
        : conn( c ), table( t ), dbControls( new QMap<QString, QString>() ) {}
    QString conn;
    QString table;
    QMap<QString, QString> *dbControls;
    };

    struct Functions
    {
    QString functions;
    };

    QValueList<Image> images;
    QWidget *toplevel;
    QListViewItem *lastItem;
    QMap<QString, QString> *dbControls;
    QMap<QString, QStringList> dbTables;
    QMap<QWidget*, SqlWidgetConnection> sqlWidgetConnections;
    QMap<QString, QString> buddies;
    QMap<QTable*, QValueList<Field> > fieldMaps;
    QPtrList<QAction> actionList;
    QMap<QObject *, EventFunction> eventMap;
    QMap<QString, QString> languageSlots;
    QMap<QString, Functions*> languageFunctions;
    QStringList variables;
    QStringList noDatabaseWidgets;
    bool usePixmapCollection;
    int defMargin, defSpacing;

};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWidgetFactory Member List

Complete Member List for QWidgetFactory

This is the complete list of member functions for QWidgetFactory, including inherited members.

  • QWidgetFactory()
  • ~QWidgetFactory()
  • addWidgetFactory()
  • create()
  • createWidget()
  • loadImages()


QWidgetItem Class

QWidgetItem Class Reference

The QWidgetItem class is a layout item that represents a widget. More...

#include <qlayout.h>

Inherits QLayoutItem.

List of all member functions.

Public Members

  • QWidgetItem ( QWidget * w )
  • virtual QSize sizeHint () const
  • virtual QSize minimumSize () const
  • virtual QSize maximumSize () const
  • virtual QSizePolicy::ExpandData expanding () const
  • virtual bool isEmpty () const
  • virtual void setGeometry ( const QRect & r )
  • virtual QWidget * widget ()

Detailed Description

The QWidgetItem class is a layout item that represents a widget.

This is used by custom layouts.

See also QLayout, QLayout::widget(), Widget Appearance and Style and Layout Management.

Member Function Documentation

QWidgetItem::QWidgetItem ( QWidget * w )

Creates an item containing widget w.

QSizePolicy::ExpandData QWidgetItem::expanding () const [virtual]

Returns TRUE if this item's widget is expanding; otherwise returns FALSE.

Reimplemented from QLayoutItem.

bool QWidgetItem::isEmpty () const [virtual]

Returns TRUE if the widget has been hidden; otherwise returns FALSE.

Reimplemented from QLayoutItem.

QSize QWidgetItem::maximumSize () const [virtual]

Returns the maximum size of this item.

Reimplemented from QLayoutItem.

QSize QWidgetItem::minimumSize () const [virtual]

Returns the minimum size of this item.

Reimplemented from QLayoutItem.

void QWidgetItem::setGeometry ( const QRect & r ) [virtual]

Sets the geometry of this item's widget to be contained within rect r, taking alignment and maximum size into account.

Reimplemented from QLayoutItem.

QSize QWidgetItem::sizeHint () const [virtual]

Returns the preferred size of this item.

Reimplemented from QLayoutItem.

QWidget * QWidgetItem::widget () [virtual]

Returns the widget managed by this item.

Reimplemented from QLayoutItem.

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


QWidgetItem Member List

Complete Member List for QWidgetItem

This is the complete list of member functions for QWidgetItem, including inherited members.

  • QWidgetItem()
  • alignment()
  • expanding()
  • geometry()
  • hasHeightForWidth()
  • heightForWidth()
  • invalidate()
  • isEmpty()
  • iterator()
  • layout()
  • maximumSize()
  • minimumSize()
  • setAlignment()
  • setGeometry()
  • sizeHint()
  • spacerItem()
  • widget()


QWidgetPlugin Class

QWidgetPlugin Class Reference

The QWidgetPlugin class provides an abstract base for custom QWidget plugins. More...

#include <qwidgetplugin.h>

List of all member functions.

Public Members

  • QWidgetPlugin ()
  • ~QWidgetPlugin ()
  • virtual QStringList keys () const = 0
  • virtual QWidget * create ( const QString & key, QWidget * parent = 0, const char * name = 0 ) = 0
  • virtual QString group ( const QString & key ) const
  • virtual QIconSet iconSet ( const QString & key ) const
  • virtual QString includeFile ( const QString & key ) const
  • virtual QString toolTip ( const QString & key ) const
  • virtual QString whatsThis ( const QString & key ) const
  • virtual bool isContainer ( const QString & key ) const

Detailed Description

The QWidgetPlugin class provides an abstract base for custom QWidget plugins.

The widget plugin is a simple plugin interface that makes it easy to create custom widgets that can be included in forms using Qt Designer and used by applications.

Writing a widget plugin is achieved by subclassing this base class, reimplementing the pure virtual functions keys(), create(), group(), iconSet(), includeFile(), toolTip(), whatsThis() and isContainer(), and exporting the class with the Q_EXPORT_PLUGIN macro.

See the Qt Designer manual's, 'Creating Custom Widgets' section in the 'Creating Custom Widgets' chapter, for a complete example of a QWidgetPlugin.

See also the Plugins documentation and the QWidgetFactory class that is supplied with Qt Designer.

See also Plugins.

Member Function Documentation

QWidgetPlugin::QWidgetPlugin ()

Constructs a widget plugin. This is invoked automatically by the Q_EXPORT_PLUGIN macro.

QWidgetPlugin::~QWidgetPlugin ()

Destroys the widget plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

QWidget * QWidgetPlugin::create ( const QString & key, QWidget * parent = 0, const char * name = 0 ) [pure virtual]

Creates and returns a QWidget object for the widget key key. The widget key is the class name of the required widget. The name and parent arguments are passed to the custom widget's constructor.

See also keys().

QString QWidgetPlugin::group ( const QString & key ) const [virtual]

Returns the group (toolbar name) that the custom widget of class key should be part of when Qt Designer loads it.

The default implementation returns a null string.

QIconSet QWidgetPlugin::iconSet ( const QString & key ) const [virtual]

Returns the iconset that Qt Designer should use to represent the custom widget of class key in the toolbar.

The default implementation returns an null iconset.

QString QWidgetPlugin::includeFile ( const QString & key ) const [virtual]

Returns the name of the include file that Qt Designer and uic should use to include the custom widget of class key in generated code.

The default implementation returns a null string.

bool QWidgetPlugin::isContainer ( const QString & key ) const [virtual]

Returns TRUE if the custom widget of class key can contain other widgets, e.g. like QFrame; otherwise returns FALSE.

The default implementation returns FALSE.

QStringList QWidgetPlugin::keys () const [pure virtual]

Returns the list of widget keys this plugin supports.

These keys must be the class names of the custom widgets that are implemented in the plugin.

See also create().

QString QWidgetPlugin::toolTip ( const QString & key ) const [virtual]

Returns the text of the tooltip that Qt Designer should use for the custom widget of class key's toolbar button.

The default implementation returns a null string.

QString QWidgetPlugin::whatsThis ( const QString & key ) const [virtual]

Returns the text of the whatsThis text that Qt Designer should use when the user requests whatsThis help for the custom widget of class key.

The default implementation returns a null string.

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


qwidgetplugin.h Include File

qwidgetplugin.h

This is the verbatim text of the qwidgetplugin.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qwidgetplugin.h   3.0.5   edited Mar 12 15:48 $
**
** Definition of QWidgetPlugin class
**
** Created : 010920
**
** Copyright (C) 2001 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWIDGETPLUGIN_H
#define QWIDGETPLUGIN_H

#ifndef QT_H
#include "qgplugin.h"
#include "qstringlist.h"
#include "qiconset.h"
#endif // QT_H
#ifndef QT_NO_WIDGETPLUGIN

#ifdef Q_WS_WIN
#ifdef QT_PLUGIN
#define QT_WIDGET_PLUGIN_EXPORT __declspec(dllexport)
#else
#define QT_WIDGET_PLUGIN_EXPORT __declspec(dllimport)
#endif
#else
#define QT_WIDGET_PLUGIN_EXPORT
#endif

class QWidgetPluginPrivate;
class QWidget;

class Q_EXPORT QWidgetPlugin : public QGPlugin
{
    Q_OBJECT
public:
    QWidgetPlugin();
    ~QWidgetPlugin();

    virtual QStringList keys() const = 0;
    virtual QWidget *create( const QString &key, QWidget *parent = 0, const char *name = 0 ) = 0;

    virtual QString group( const QString &key ) const;
    virtual QIconSet iconSet( const QString &key ) const;
    virtual QString includeFile( const QString &key ) const;
    virtual QString toolTip( const QString &key ) const;
    virtual QString whatsThis( const QString &key ) const;
    virtual bool isContainer( const QString &key ) const;

private:
    QWidgetPluginPrivate *d;
};

#endif // QT_NO_WIDGETPLUGIN
#endif // QWIDGETPLUGIN_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWidgetPlugin Member List

Complete Member List for QWidgetPlugin

This is the complete list of member functions for QWidgetPlugin, including inherited members.

  • QWidgetPlugin()
  • ~QWidgetPlugin()
  • create()
  • group()
  • iconSet()
  • includeFile()
  • isContainer()
  • keys()
  • toolTip()
  • whatsThis()


QWidgetStack类

QWidgetStack类参考

QWidgetStack类提供了一个只有最上面的窗口部件是用户可视的窗口部件的栈。 详情请见……

#include <qwidgetstack.h>

继承了QFrame。

所有成员函数的列表。

公有成员

  • QWidgetStack ( QWidget * parent = 0, const char * name = 0 )
  • ~QWidgetStack ()
  • int addWidget ( QWidget * w, int id = -1 )
  • void removeWidget ( QWidget * w )
  • QWidget * widget ( int id ) const
  • int id ( QWidget * widget ) const
  • QWidget * visibleWidget () const

公有槽

  • void raiseWidget ( int id )
  • void raiseWidget ( QWidget * w )

信号

  • void aboutToShow ( int )
  • void aboutToShow ( QWidget * )

保护成员

  • virtual void setChildGeometries ()

详细描述n

QWidgetStack类提供了一个只有最上面的窗口部件是用户可视的窗口部件的栈。

应用程序程序员可以在任何时候使用raiseWidget()把任何一个窗口部件移到栈顶，并且使用addWidget()和removeWidget()来添加或者移除窗口部件。

visibleWidget()是raiseWidget()的获取对应函数，它返回当前在栈顶的窗口部件的指针。

QWidgetStack也提供了通过应用程序指定的整数标识来维护这些窗口部件。你也可以使用id()来从窗口部件指针转换到标识并且使用widget()来从标识转换到窗口部件指针。这些数字标识是唯一的（每一个QWidgetStack，而不是全局的），但是QWidgetStack不会给它们添加额外的东西。

默认窗口部件栈是没有框架的，但是你可以使用通常的QFrame函数（比如setFrameStyle()）来添加一个框架。

QWidgetStack提供一个信号aboutToShow()，在一个被管理的窗口部件被显示之前，这个信号被发射。

也可以参考QTabDialog、QTabBar、QFrame和组织者。

成员函数文档

QWidgetStack::QWidgetStack ( QWidget * parent = 0, const char * name = 0 )

构造一个父对象为parent、名称为name的空窗口部件栈。

QWidgetStack::~QWidgetStack ()

销毁这个对象并且释放所有已分配的资源。

void QWidgetStack::aboutToShow ( int ) [信号]

如果一个被管理的窗口部件的标识不等于-1，在它被显示之前，这个信号被发射。那个参数是窗口部件的数字标识。

void QWidgetStack::aboutToShow ( QWidget * ) [信号]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

在一个被管理的窗口部件被显示之前，这个信号被发射。那个参数是窗口部件的指针。

int QWidgetStack::addWidget ( QWidget * w, int id = -1 )

把窗口部件w添加到这个窗口部件栈中，标识为id。

如果你传递一个id >= 0，这个标识就被使用。如果你传递一个-1的标识（默认），这个窗口部件将会被自动标识。如果你传递一个-1，一个负整数将被生成。没有窗口部件有-1的标识。

如果w不是这个QWidgetStack的子对象，QWidgetStack会使用reparent()来移动它。

实例：xform/xform.cpp。

int QWidgetStack::id ( QWidget * widget ) const

返回widget的标识，如果widget为0或者不被这个窗口部件栈管理，这个函数返回-1。

也可以参考widget()和addWidget()。

void QWidgetStack::raiseWidget ( int id ) [槽]

升起标识为id的窗口部件到这个窗口部件栈的栈顶。

也可以参考visibleWidget()。

实例：xform/xform.cpp。

void QWidgetStack::raiseWidget ( QWidget * w ) [槽]

这是一个重载成员函数，提供了方便。它的行为基本上和上面的函数相同。

升起窗口部件w到这个窗口部件栈的栈顶。

void QWidgetStack::removeWidget ( QWidget * w )

从窗口部件栈中移除窗口部件w。不删除w。如果w为当前可视窗口部件，没有其它窗口部件会替代的。

也可以参考visibleWidget()和raiseWidget()。

void QWidgetStack::setChildGeometries () [虚 保护]

安排子窗口的几何形状。

QWidget * QWidgetStack::visibleWidget () const

返回当前可视窗口部件的指针（栈顶的那一个），或者如果当前没有被显示的，返回0。

也可以参考aboutToShow()、id()和raiseWidget()。

QWidget * QWidgetStack::widget ( int id ) const

返回标识为id的窗口部件。如果这个窗口部件栈不管理标识为id的窗口部件，这个函数返回0。

也可以参考id()和addWidget()。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qwidgetstack.h包含文件

qwidgetstack.h

这里是qwidgetstack.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qwidgetstack.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QWidgetStack class
**
** Created : 980306
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWIDGETSTACK_H
#define QWIDGETSTACK_H

#ifndef QT_H
#include "qframe.h"
#include "qintdict.h"
#include "qptrdict.h"
#endif // QT_H

#ifndef QT_NO_WIDGETSTACK

class QWidgetStackPrivate;

class Q_EXPORT QWidgetStack: public QFrame
{
    Q_OBJECT
public:
    QWidgetStack( QWidget* parent=0, const char* name=0 );

    ~QWidgetStack();

    int addWidget( QWidget *, int = -1 );
    void removeWidget( QWidget * );

    QSize sizeHint() const;
    QSize minimumSizeHint() const;
    void show();

    QWidget * widget( int ) const;
    int id( QWidget * ) const;

    QWidget * visibleWidget() const;

    void setFrameRect( const QRect & );

signals:
    void aboutToShow( int );
    void aboutToShow( QWidget * );

public slots:
    void raiseWidget( int );
    void raiseWidget( QWidget * );

protected:
    void frameChanged();
    void resizeEvent( QResizeEvent * );

    virtual void setChildGeometries();
    void childEvent( QChildEvent * );

private:
    bool isMyChild( QWidget * );

    QWidgetStackPrivate * d;
    QIntDict<QWidget> * dict;
    QPtrDict<QWidget> * focusWidgets;
    QWidget * topWidget;
    QWidget * invisible;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QWidgetStack( const QWidgetStack & );
    QWidgetStack& operator=( const QWidgetStack & );
#endif
};

#endif // QT_NO_WIDGETSTACK

#endif // QWIDGETSTACK_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWidgetStack成员列表

完整的QWidgetStack成员列表

这里是QWidgetStack成员函数的完整列表，包括继承的成员。

  • QWidgetStack()
  • ~QWidgetStack()
  • aboutToShow()
  • acceptDrops()
  • addWidget()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contentsRect()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawContents()
  • drawFrame()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameChanged()
  • frameGeometry()
  • frameRect()
  • frameShadow()
  • frameShape()
  • frameSize()
  • frameStyle()
  • frameWidth()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • id()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lineWidth()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • margin()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • midLineWidth()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • raiseWidget()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removeWidget()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setChildGeometries()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setFrameRect()
  • setFrameShadow()
  • setFrameShape()
  • setFrameStyle()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setLineWidth()
  • setMargin()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMidLineWidth()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • visibleWidget()
  • wheelEvent()
  • widget()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qwindowdefs.h Include File

qwindowdefs.h

This is the verbatim text of the qwindowdefs.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of general window system dependent functions, types and
** constants
**
** Created : 931029
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWINDOWDEFS_H
#define QWINDOWDEFS_H

#ifndef QT_H
#include "qobjectdefs.h"
#include "qstring.h"
#include "qnamespace.h"
#endif // QT_H

#include <limits.h>

// Class forward definitions

class QPaintDevice;
class QPaintDeviceMetrics;
class QWidget;
class QWidgetMapper;
class QDialog;
class QColor;
class QColorGroup;
class QPalette;
class QCursor;
class QPoint;
class QSize;
class QRect;
class QPointArray;
class QPainter;
class QRegion;
class QFont;
class QFontMetrics;
class QFontInfo;
class QPen;
class QBrush;
class QWMatrix;
class QPixmap;
class QBitmap;
class QMovie;
class QImage;
class QImageIO;
class QPicture;
class QPrinter;
class QAccel;
class QTimer;
class QTime;
class QClipboard;

// Widget list (defined in qwidgetlist.h)

class QWidgetList;
class QWidgetListIt;

// Window system dependent definitions

#if defined(Q_WS_MAC)

#ifndef QMAC_NO_QUARTZ
typedef struct CGContext *CGContextRef;
#endif
typedef struct OpaqueControlRef *ControlRef;
typedef struct OpaqueWindowGroupRef *WindowGroupRef;
typedef struct OpaqueGrafPtr *CGrafPtr;
typedef struct OpaqueMenuHandle *MenuRef;
typedef struct OpaquePMPrintSession *PMPrintSession;
typedef struct OpaquePMPrintSettings *PMPrintSettings;
typedef struct OpaquePMPageFormat *PMPageFormat;
typedef struct Point Point;
typedef struct FSSpec FSSpec;
typedef struct OpaqueEventHandlerRef*   EventHandlerRef;
typedef struct OpaqueEventHandlerCallRef*  EventHandlerCallRef;
#ifdef MACOSX_102
typedef struct __EventLoopTimer*        EventLoopTimerRef;
#else
typedef struct OpaqueEventLoopTimerRef* EventLoopTimerRef;
#endif
typedef struct OpaqueEventRef*          EventRef;
typedef long int OSStatus;
typedef struct OpaqueScrapRef *ScrapRef;
typedef struct OpaqueRgnHandle *RgnHandle;
typedef struct OpaqueWindowPtr *WindowPtr;
typedef WindowPtr WindowRef;
typedef struct OpaqueGrafPtr *GWorldPtr;
typedef GWorldPtr GrafPtr;
typedef struct GDevice **GDHandle;
typedef struct ColorTable ColorTable;
typedef struct BitMap BitMap;
typedef struct EventRecord EventRecord;
typedef void * MSG;
typedef int WId;

#endif

#if defined(Q_WS_WIN)
#include "qwindowdefs_win.h"
#endif // Q_WS_WIN

#if defined(Q_WS_X11)

typedef struct _XDisplay Display;
typedef union  _XEvent XEvent;
typedef struct _XGC *GC;
typedef struct _XRegion *Region;
typedef unsigned long  WId;

Q_EXPORT Display *qt_xdisplay();
Q_EXPORT int	 qt_xscreen();
Q_EXPORT WId	 qt_xrootwin();
Q_EXPORT GC	 qt_xget_readonly_gc( int scrn, bool monochrome );
Q_EXPORT GC	 qt_xget_temp_gc( int scrn, bool monochrome );

#endif // Q_WS_X11

#if defined(Q_WS_QWS)

typedef unsigned long  WId;
struct QWSEvent;
class QGfx;

#endif // Q_WS_QWS

class QApplication;

#if defined(NEEDS_QMAIN)
#define main qMain
#endif

// Global platform-independent types and functions

typedef Q_INT32 QCOORD;				// coordinate type
const QCOORD QCOORD_MAX =  2147483647;
const QCOORD QCOORD_MIN = -QCOORD_MAX - 1;

typedef unsigned int QRgb;			// RGB triplet

Q_EXPORT const char *qAppName();		// get application name

// Misc functions

typedef void (*QtCleanUpFunction)();
Q_EXPORT void qAddPostRoutine( QtCleanUpFunction );
Q_EXPORT void qRemovePostRoutine( QtCleanUpFunction );

#if !defined(QT_CLEAN_NAMESPACE)
// source compatibility with Qt 2.x
typedef QtCleanUpFunction Q_CleanUpFunction;
#endif

// ### remove 3.0
Q_EXPORT void *qt_find_obj_child( QObject *, const char *, const char * );
#define Q_CHILD(parent,type,name) \
    ((type*)qt_find_obj_child(parent,#type,name))

#endif // QWINDOWDEFS_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWindowsMime Class

QWindowsMime Class Reference

The QWindowsMime class maps open-standard MIME to Window Clipboard formats. More...

#include <qmime.h>

List of all member functions.

Public Members

  • QWindowsMime ()
  • virtual ~QWindowsMime ()
  • virtual const char * convertorName () = 0
  • virtual int countCf () = 0
  • virtual int cf ( int index ) = 0
  • virtual bool canConvert ( const char * mime, int cf ) = 0
  • virtual const char * mimeFor ( int cf ) = 0
  • virtual int cfFor ( const char * mime ) = 0
  • virtual QByteArray convertToMime ( QByteArray data, const char * mime, int cf ) = 0
  • virtual QByteArray convertFromMime ( QByteArray data, const char * mime, int cf ) = 0

Static Public Members

  • void initialize ()
  • QPtrList<QWindowsMime> all ()
  • QWindowsMime * convertor ( const char * mime, int cf )
  • const char * cfToMime ( int cf )

Detailed Description

The QWindowsMime class maps open-standard MIME to Window Clipboard formats.

Qt's drag-and-drop and clipboard facilities use the MIME standard. On X11, this maps trivially to the Xdnd protocol, but on Windows although some applications use MIME types to describe clipboard formats, others use arbitrary non-standardized naming conventions, or unnamed built-in formats of Windows.

By instantiating subclasses of QWindowsMime that provide conversions between Windows Clipboard and MIME formats, you can convert proprietary clipboard formats to MIME formats.

Qt has predefined support for the following Windows Clipboard formats:

  • CF_UNICODETEXT - converted to "text/plain;charset=ISO-10646-UCS-2" and supported by QTextDrag.
  • CF_TEXT - converted to "text/plain;charset=system" or "text/plain" and supported by QTextDrag.
  • CF_DIB - converted to "image/*", where * is a Qt image format, and supported by QImageDrag.
  • CF_HDROP - converted to "text/uri-list", and supported by QUriDrag.

An example use of this class would be to map the Windows Metafile clipboard format (CF_METAFILEPICT) to and from the MIME type "image/x-wmf". This conversion might simply be adding or removing a header, or even just passing on the data. See the Drag-and-Drop documentation for more information on choosing and definition MIME types.

You can check if a MIME type is convertible using canConvert() and can perform conversions with convertToMime() and convertFromMime().

See also Drag And Drop Classes, Input/Output and Networking and Miscellaneous Classes.

Member Function Documentation

QWindowsMime::QWindowsMime ()

Constructs a new conversion object, adding it to the globally accessed list of available convertors.

QWindowsMime::~QWindowsMime () [virtual]

Destroys a conversion object, removing it from the global list of available convertors.

QPtrList<QWindowsMime> QWindowsMime::all () [static]

Returns a list of all currently defined QWindowsMime objects.

bool QWindowsMime::canConvert ( const char * mime, int cf ) [pure virtual]

Returns TRUE if the convertor can convert (both ways) between mime and cf; otherwise returns FALSE.

All subclasses must reimplement this pure virtual function.

int QWindowsMime::cf ( int index ) [pure virtual]

Returns the Windows Clipboard format supported by this convertor that is ordinarily at position index. This means that cf(0) returns the first Windows Clipboard format supported, and cf(countCf()-1) returns the last. If index is out of range the return value is undefined.

All subclasses must reimplement this pure virtual function.

int QWindowsMime::cfFor ( const char * mime ) [pure virtual]

Returns the Windows Clipboard type used for MIME type mime, or 0 if this convertor does not support mime.

All subclasses must reimplement this pure virtual function.

const char * QWindowsMime::cfToMime ( int cf ) [static]

Returns a MIME type for cf, or 0 if none exists.

QByteArray QWindowsMime::convertFromMime ( QByteArray data, const char * mime, int cf ) [pure virtual]

Returns data converted from MIME type mime to Windows Clipboard format cf.

Note that Windows Clipboard formats must all be self-terminating. The return value may contain trailing data.

All subclasses must reimplement this pure virtual function.

QByteArray QWindowsMime::convertToMime ( QByteArray data, const char * mime, int cf ) [pure virtual]

Returns data converted from Windows Clipboard format cf to MIME type mime.

Note that Windows Clipboard formats must all be self-terminating. The input data may contain trailing data.

All subclasses must reimplement this pure virtual function.

QWindowsMime * QWindowsMime::convertor ( const char * mime, int cf ) [static]

Returns the most-recently created QWindowsMime that can convert between the mime and cf formats. Returns 0 if no such convertor exists.

const char * QWindowsMime::convertorName () [pure virtual]

Returns a name for the convertor.

All subclasses must reimplement this pure virtual function.

int QWindowsMime::countCf () [pure virtual]

Returns the number of Windows Clipboard formats supported by this convertor.

All subclasses must reimplement this pure virtual function.

void QWindowsMime::initialize () [static]

This is an internal function.

const char * QWindowsMime::mimeFor ( int cf ) [pure virtual]

Returns the MIME type used for Windows Clipboard format cf, or 0 if this convertor does not support cf.

All subclasses must reimplement this pure virtual function.

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


QWindowsMime Member List

Complete Member List for QWindowsMime

This is the complete list of member functions for QWindowsMime, including inherited members.

  • QWindowsMime()
  • ~QWindowsMime()
  • all()
  • canConvert()
  • cf()
  • cfFor()
  • cfToMime()
  • convertFromMime()
  • convertToMime()
  • convertor()
  • convertorName()
  • countCf()
  • initialize()
  • mimeFor()


QWindowsStyle Class

QWindowsStyle Class Reference

The QWindowsStyle class provides a Microsoft Windows-like look and feel. More...

#include <qwindowsstyle.h>

Inherits QCommonStyle.

Inherited by QPlatinumStyle.

List of all member functions.

Public Members

  • QWindowsStyle ()

Detailed Description

The QWindowsStyle class provides a Microsoft Windows-like look and feel.

This style is Qt's default GUI style on Windows.

See also Widget Appearance and Style.

Member Function Documentation

QWindowsStyle::QWindowsStyle ()

Constructs a QWindowsStyle

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


qwindowsstyle.h Include File

qwindowsstyle.h

This is the verbatim text of the qwindowsstyle.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qwindowsstyle.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Windows-like style class
**
** Created : 981231
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWINDOWSSTYLE_H
#define QWINDOWSSTYLE_H

#ifndef QT_H
#include "qcommonstyle.h"
#endif // QT_H

#ifndef QT_NO_STYLE_WINDOWS

#if defined(QT_PLUGIN)
#define Q_EXPORT_STYLE_WINDOWS
#else
#define Q_EXPORT_STYLE_WINDOWS Q_EXPORT
#endif

class Q_EXPORT_STYLE_WINDOWS QWindowsStyle : public QCommonStyle
{
    Q_OBJECT
public:
    QWindowsStyle();
    ~QWindowsStyle();

    virtual void polishPopupMenu( QPopupMenu* );

    // new stuff
    void drawPrimitive( PrimitiveElement pe,
            QPainter *p,
            const QRect &r,
            const QColorGroup &cg,
            SFlags flags = Style_Default,
            const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
              QPainter *p,
              const QWidget *widget,
              const QRect &r,
              const QColorGroup &cg,
              SFlags flags = Style_Default,
              const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl control,
                 QPainter* p,
                 const QWidget* widget,
                 const QRect& r,
                 const QColorGroup& cg,
                 SFlags flags = Style_Default,
                 SCFlags sub = SC_All,
                 SCFlags subActive = SC_None,
                 const QStyleOption& = QStyleOption::Default ) const;

    int pixelMetric( PixelMetric metric,
             const QWidget *widget = 0 ) const;

    QSize sizeFromContents( ContentsType contents,
                const QWidget *widget,
                const QSize &contentsSize,
                const QStyleOption& = QStyleOption::Default ) const;

    int styleHint(StyleHint sh, const QWidget *, const QStyleOption & = QStyleOption::Default,
          QStyleHintReturn* = 0) const;

    QPixmap stylePixmap( StylePixmap stylepixmap,
             const QWidget *widget = 0,
             const QStyleOption& = QStyleOption::Default ) const;

private:
    // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QWindowsStyle( const QWindowsStyle & );
    QWindowsStyle& operator=( const QWindowsStyle & );
#endif
};

#endif // QT_NO_STYLE_WINDOWS

#endif // QWINDOWSSTYLE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWindowsStyle Member List

Complete Member List for QWindowsStyle

This is the complete list of member functions for QWindowsStyle, including inherited members.

  • QWindowsStyle()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • defaultFrameWidth()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • drawComplexControl()
  • drawComplexControlMask()
  • drawControl()
  • drawControlMask()
  • drawItem()
  • drawPrimitive()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • itemRect()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • pixelMetric()
  • polish()
  • polishPopupMenu()
  • property()
  • queryList()
  • querySubControl()
  • querySubControlMetrics()
  • removeChild()
  • removeEventFilter()
  • scrollBarExtent()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • sizeFromContents()
  • startTimer()
  • styleHint()
  • stylePixmap()
  • subRect()
  • tabbarMetrics()
  • timerEvent()
  • tr()
  • trUtf8()
  • unPolish()
  • visualRect()


qwindowsystem_qws.h Include File

qwindowsystem_qws.h

This is the verbatim text of the qwindowsystem_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of Qt/FB central server classes
**
** Created : 991025
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QTFB_H
#define QTFB_H

#ifndef QT_H
#include <qwssocket_qws.h>
#include <qmap.h>
#include <qdatetime.h>
#include <qptrlist.h>
#include <qimage.h>

#include "qwsproperty_qws.h"
#include "qwscommand_qws.h"
#include "qwsevent_qws.h"
#include "qkeyboard_qws.h"
#endif // QT_H

struct SWCursorData;
class QWSCursor;
class QWSClient;
class QWSRegionManager;
class QGfx;
class QWSServerData;

class QWSInternalWindowInfo
{

public:

    int winid;
    unsigned int clientid;
    QString name;   // Corresponds to QObject name of top-level widget

};

struct QWSWindowData;

class QWSScreenSaver
{
public:
    virtual ~QWSScreenSaver();
    virtual void restore()=0;
    virtual bool save(int level)=0;
};

class QWSWindow
{
    friend class QWSServer;
public:
    QWSWindow(int i, QWSClient* client);
    ~QWSWindow();

    int winId() const { return id; }
    const QString &name() const { return rgnName; }
    const QString &caption() const { return rgnCaption; }
    QWSClient* client() const { return c; }
    QRegion requested() const { return requested_region; }
    QRegion allocation() const { return allocated_region; }
    bool isVisible() const { return !requested_region.isEmpty(); }
    bool isPartiallyObscured() const { return requested_region!=allocated_region; }
    bool isFullyObscured() const { return allocated_region.isEmpty(); }

    void raise();
    void lower();
    void show();
    void hide();
    void setActiveWindow();

private:
    bool hidden() const { return requested_region.isEmpty(); }
    bool forClient(const QWSClient* cl) const { return cl==c; }

    void setName( const QString &n );
    void setCaption( const QString &c );

    void addAllocation( QWSRegionManager *, QRegion );
    void removeAllocation( QWSRegionManager *, QRegion );

    int  allocationIndex() const { return alloc_region_idx; }
    void setAllocationIndex( int i ) { alloc_region_idx = i; modified = TRUE; }
    void updateAllocation();

    void setNeedAck( bool n ) { needAck = n; }

    void focus(bool get);
    int focusPriority() const { return last_focus_time; }
    void operation( QWSWindowOperationEvent::Operation o );
    void shuttingDown() { last_focus_time=0; }

private:
    int id;
    QString rgnName;
    QString rgnCaption;
    int alloc_region_idx;
    bool modified;
    bool needAck;
    bool onTop;
    QWSClient* c;
    QRegion requested_region;
    QRegion allocated_region;
    QRegion exposed;
    int last_focus_time;
    QWSWindowData *d;
};

#ifndef QT_NO_SOUND
class QWSSoundServer;
#ifdef QT_USE_OLD_QWS_SOUND
class QWSSoundServerData;

class QWSSoundServer : public QObject {
    Q_OBJECT
public:
    QWSSoundServer(QObject* parent);
    ~QWSSoundServer();
    void playFile(const QString& filename);
private slots:
    void feedDevice(int fd);
private:
    QWSSoundServerData* d;
};
#endif
#endif

/*********************************************************************
 *
 * Class: QWSServer
 *
 *********************************************************************/

class QWSMouseHandler;
struct QWSCommandStruct;

#ifndef QT_NO_QWS_MULTIPROCESS
class QWSServer : public QWSServerSocket
#else
class QWSServer : public QObject
#endif
{
    friend class QCopChannel;
    friend class QWSMouseHandler;
    friend class QWSWindow;
    friend class QWSDisplay;
    Q_OBJECT

public:
    QWSServer( int flags = 0, QObject *parent=0, const char *name=0 );
    ~QWSServer();
    enum ServerFlags { DisableKeyboard = 0x01,
               DisableMouse = 0x02 };

    enum GUIMode { NoGui = FALSE, NormalGUI = TRUE, Server };

    static void sendKeyEvent(int unicode, int keycode, int modifiers, bool isPress,
                 bool autoRepeat);
    static void processKeyEvent(int unicode, int keycode, int modifiers, bool isPress,
                bool autoRepeat);
#ifndef QT_NO_QWS_KEYBOARD
    typedef struct KeyMap {
    ushort key_code;
    ushort unicode;
    ushort shift_unicode;
    ushort ctrl_unicode;
    };

    static const KeyMap *keyMap();

    class KeyboardFilter
    {
    public:
    virtual bool filter(int unicode, int keycode, int modifiers, bool isPress,
              bool autoRepeat)=0;
    };

    static void setKeyboardFilter( KeyboardFilter *f );
#endif
    static void setDefaultMouse( const char * );
    static void setDefaultKeyboard( const char * );
    static void setMaxWindowRect(const QRect&);
    static void sendMouseEvent(const QPoint& pos, int state);

    static void setDesktopBackground( const QImage &img );
    static void setDesktopBackground( const QColor & );
    static QWSMouseHandler *mouseHandler();
    static void setMouseHandler(QWSMouseHandler*);
#ifndef QT_NO_QWS_KEYBOARD
    static QWSKeyboardHandler* keyboardHandler();
    static void setKeyboardHandler(QWSKeyboardHandler* kh);
#endif
    QWSWindow *windowAt( const QPoint& pos );

    // For debugging only at this time
    const QPtrList<QWSWindow> &clientWindows() { return windows; }

    void openMouse();
    void closeMouse();
#ifndef QT_NO_QWS_KEYBOARD
    void openKeyboard();
    void closeKeyboard();
#endif

    static void setScreenSaver(QWSScreenSaver*);
    static void setScreenSaverIntervals(int* ms);
    static void setScreenSaverInterval(int);
    static bool screenSaverActive();
    static void screenSaverActivate(bool);

    // the following are internal.
    void refresh();
#ifndef QT_NO_QWS_REPEATER
    void refresh(QRegion &);
#endif

    void enablePainting(bool);
    static void processEventQueue();
    static QPtrList<QWSInternalWindowInfo> * windowList();

    void sendPropertyNotifyEvent( int property, int state );
#ifndef QT_NO_QWS_PROPERTIES
    QWSPropertyManager *manager() {
    return &propertyManager;
    }
#endif

    static QPoint mousePosition;

    static void startup( int flags );
    static void closedown();

    enum WindowEvent { Create=0x01, Destroy=0x02, Hide=0x04, Show=0x08,
               Raise=0x10, Lower=0x20, Geometry=0x40 };

signals:
    void windowEvent( QWSWindow *w, QWSServer::WindowEvent e );

#ifndef QT_NO_COP
    void newChannel( const QString& );
#endif

private:
#ifndef QT_NO_COP
    static void sendQCopEvent( QWSClient *c, const QCString &ch,
                   const QCString &msg, const QByteArray &data,
                   bool response = FALSE );
#endif
    void move_region( const QWSRegionMoveCommand * );
    void set_altitude( const QWSChangeAltitudeCommand * );
    void request_focus( const QWSRequestFocusCommand * );
    void request_region( int, QRegion );
    void destroy_region( const QWSRegionDestroyCommand * );
    void name_region( const QWSRegionNameCommand * );

    static void emergency_cleanup();

    static QColor *bgColor;
    static QImage *bgImage;

    void sendMaxWindowRectEvents();
#ifndef QT_NO_QWS_MULTIPROCESS
    void newConnection( int socket );
#endif
    void invokeIdentify( QWSIdentifyCommand *cmd, QWSClient *client );
    void invokeCreate( QWSCreateCommand *cmd, QWSClient *client );
    void invokeRegionName( const QWSRegionNameCommand *cmd, QWSClient *client );
    void invokeRegion( QWSRegionCommand *cmd, QWSClient *client );
    void invokeRegionMove( const QWSRegionMoveCommand *cmd, QWSClient *client );
    void invokeRegionDestroy( const QWSRegionDestroyCommand *cmd, QWSClient *client );
    void invokeSetAltitude( const QWSChangeAltitudeCommand *cmd, QWSClient *client );
#ifndef QT_NO_QWS_PROPERTIES
    void invokeAddProperty( QWSAddPropertyCommand *cmd );
    void invokeSetProperty( QWSSetPropertyCommand *cmd );
    void invokeRemoveProperty( QWSRemovePropertyCommand *cmd );
    void invokeGetProperty( QWSGetPropertyCommand *cmd, QWSClient *client );
#endif //QT_NO_QWS_PROPERTIES
    void invokeSetSelectionOwner( QWSSetSelectionOwnerCommand *cmd );
    void invokeConvertSelection( QWSConvertSelectionCommand *cmd );
    void invokeSetFocus( const QWSRequestFocusCommand *cmd, QWSClient *client );

    void initIO();
    void setFocus( QWSWindow*, bool gain );
#ifndef QT_NO_QWS_CURSOR
    void invokeDefineCursor( QWSDefineCursorCommand *cmd, QWSClient *client );
    void invokeSelectCursor( QWSSelectCursorCommand *cmd, QWSClient *client );
#endif
    void invokeGrabMouse( QWSGrabMouseCommand *cmd, QWSClient *client );
    void invokeGrabKeyboard( QWSGrabKeyboardCommand *cmd, QWSClient *client );
#ifndef QT_NO_SOUND
    void invokePlaySound( QWSPlaySoundCommand *cmd, QWSClient *client );
#endif
#ifndef QT_NO_COP
    void invokeRegisterChannel( QWSQCopRegisterChannelCommand *cmd,
                QWSClient *client );
    void invokeQCopSend( QWSQCopSendCommand *cmd, QWSClient *client );
#endif
#ifndef QT_NO_QWS_REPEATER
    void invokeRepaintRegion( QWSRepaintRegionCommand *cmd,
                  QWSClient *client );
#endif

    QWSMouseHandler* newMouseHandler(const QString& spec);
#ifndef QT_NO_QWS_KEYBOARD
    QWSKeyboardHandler* newKeyboardHandler(const QString& spec);
#endif
    void openDisplay();
    void closeDisplay();

    void showCursor();
    void hideCursor();
    void initializeCursor();
    void paintServerRegion();
    void paintBackground( QRegion );
    void clearRegion( const QRegion &r, const QColor &c );
    void refreshBackground();

private slots:
#ifndef QT_NO_QWS_MULTIPROCESS
    void clientClosed();
    void doClient();
#endif

    void screenSaverWake();
    void screenSaverSleep();
    void screenSaverTimeout();

private:
    void screenSave(int level);
    void doClient( QWSClient * );
    typedef QMapIterator<int,QWSClient*> ClientIterator;
    typedef QMap<int,QWSClient*> ClientMap;
    void releaseMouse(QWSWindow* w);
    void releaseKeyboard(QWSWindow* w);

    uchar* sharedram;
    int ramlen;

    QGfx *gfx;

    ClientMap client;
#ifndef QT_NO_QWS_PROPERTIES
    QWSPropertyManager propertyManager;
#endif
    struct SelectionOwner {
    int windowid;
    struct Time {
        void set( int h, int m, int s, int s2 ) {
        hour = h; minute = m; sec = s; ms = s2;
        }
        int hour, minute, sec, ms;
    } time;
    } selectionOwner;
    QTime timer;
    QWSServerData* d;
    int* screensaverinterval;

    QWSWindow *focusw;
    QWSWindow *mouseGrabber;
    bool mouseGrabbing;
    int swidth, sheight, sdepth;
#ifndef QT_NO_QWS_CURSOR
    bool cursorNeedsUpdate;
    QWSCursor *cursor;	    // cursor currently shown
    QWSCursor *nextCursor;  // cursor to show once grabbing is off
#endif
    QRegion screenRegion;   // the entire display region
    QRegion serverRegion;
    QRegion dirtyBackground;
    bool disablePainting;
    QPtrList<QWSMouseHandler> mousehandlers;
#ifndef QT_NO_QWS_KEYBOARD
    QPtrList<QWSKeyboardHandler> keyboardhandlers;
#endif

    QPtrList<QWSCommandStruct> commandQueue;
    QWSRegionManager *rgnMan;

    // Window management
    QPtrList<QWSWindow> windows; // first=topmost
    QWSWindow* newWindow(int id, QWSClient* client);
    QWSWindow* findWindow(int windowid, QWSClient* client);
    void moveWindowRegion(QWSWindow*, int dx, int dy );
    QRegion setWindowRegion(QWSWindow*, QRegion r );
    void raiseWindow( QWSWindow *, int = 0);
    void lowerWindow( QWSWindow *, int = -1);
    void exposeRegion( QRegion , int index = 0 );
    void notifyModified( QWSWindow *active = 0 );
    void syncRegions( QWSWindow *active = 0 );

    void setCursor(QWSCursor *curs);

    // multimedia
#ifndef QT_NO_SOUND
    QWSSoundServer *soundserver;
#endif
#ifndef QT_NO_COP
    QMap<QString, QPtrList<QWSClient> > channels;
#endif
};

extern QWSServer *qwsServer; //there can be only one

/*********************************************************************
 *
 * Class: QWSClient
 *
 *********************************************************************/

struct QWSMouseEvent;

typedef QMap<int, QWSCursor*> QWSCursorMap;

class QWSClient : public QObject
{
    Q_OBJECT
public:
    QWSClient( QObject* parent, int socket );
    ~QWSClient();

    int socket() const;

    void setIdentity(const QString&);
    QString identity() const { return id; }

    void sendEvent( QWSEvent* event );
    void sendConnectedEvent( const char *display_spec );
    void sendMaxWindowRectEvent();
    void sendRegionModifyEvent( int winid, QRegion exposed, bool ack );
    void sendFocusEvent( int winid, bool get );
    void sendPropertyNotifyEvent( int property, int state );
    void sendPropertyReplyEvent( int property, int len, char *data );
    void sendSelectionClearEvent( int windowid );
    void sendSelectionRequestEvent( QWSConvertSelectionCommand *cmd, int windowid );
    QWSCommand* readMoreCommand();

    QWSCursorMap cursors;	// cursors defined by this client
signals:
    void connectionClosed();
    void readyRead();
private slots:
    void closeHandler();
    void errorHandler( int );
private:
    int s; // XXX csocket->d->socket->socket() is this value
#ifndef QT_NO_QWS_MULTIPROCESS
    QWSSocket *csocket;
#endif
    QWSCommand* command;
    uint isClosed : 1;
    QString id;
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWizard类

QWizard类参考

QWizard类提供了一个向导对话框的框架。 详情请见……

#include <qwizard.h>

继承了QDialog。

所有成员函数的列表。

公有成员

  • QWizard ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )
  • ~QWizard ()
  • virtual void addPage ( QWidget * page, const QString & title )
  • virtual void insertPage ( QWidget * page, const QString & title, int index )
  • virtual void removePage ( QWidget * page )
  • QString title ( QWidget * page ) const
  • void setTitle ( QWidget * page, const QString & title )
  • QFont titleFont () const
  • void setTitleFont ( const QFont & )
  • virtual void showPage ( QWidget * page )
  • QWidget * currentPage () const
  • QWidget * page ( int index ) const
  • int pageCount () const
  • int indexOf ( QWidget * page ) const
  • virtual bool appropriate ( QWidget * page ) const
  • virtual void setAppropriate ( QWidget * page, bool appropriate )
  • QPushButton * backButton () const
  • QPushButton * nextButton () const
  • QPushButton * finishButton () const
  • QPushButton * cancelButton () const
  • QPushButton * helpButton () const

公有槽

  • virtual void setBackEnabled ( QWidget * page, bool enable )
  • virtual void setNextEnabled ( QWidget * page, bool enable )
  • virtual void setFinishEnabled ( QWidget * page, bool enable )
  • virtual void setHelpEnabled ( QWidget * page, bool enable )
  • virtual void setFinish ( QWidget *, bool ) （废弃）

信号

  • void helpClicked ()
  • void selected ( const QString & )

属性

  • QFont titleFont - 页标题使用的字体

保护成员

  • virtual void layOutButtonRow ( QHBoxLayout * layout )
  • virtual void layOutTitleRow ( QHBoxLayout * layout, const QString & title )

保护槽

  • virtual void back ()
  • virtual void next ()
  • virtual void help ()

详细描述

QWizard类提供了一个向导对话框的框架。

向导就是包含一组顺序的对话框页面的特定类型的输入对话框。向导的目的是让用户一步一步地完成一个过程。向导对于复杂或者偶尔发生的并且人们发现它很难学会或者执行的任务很有用处。

QWizard会根据当前页在顺序中的位置提供页面标题和显示Next、Back、Finish、Cancel和Help推动按钮。

创建并且组装继承于QWidget的对话框页面并且使用addPage()把它们添加到这个向导中。使用insertPage()可以把一个对话框页添加到页顺序的特定位置中。使用removePage()可以移除页顺序中的一页。

使用currentPage()来得到当前显示页的指针。page()返回在页顺序中特定位置的页的指针。

使用pageCount()可以得到页顺序中的页的总量。indexOf()将会返回一个页在页顺序中的索引。

QWizard根据（或者没有）setAppropriate()的当前上下文来提供标记页面的功能。这个思想就是根据用户在前面的页面输入的内容，一个页面也许是无关的并且应该被忽略。

使用比较多的有较少选项的简单页面比使用比较少的复杂页面更是一个好的设计所要考虑的。

这里是可用的实例代码：wizard/wizard.cpp、wizard/wizard.h。

A QWizard page

一个QWizard页

也可以参考抽象窗口部件类、对话框类和组织者。

成员函数文档

QWizard::QWizard ( QWidget * parent = 0, const char * name = 0, bool modal = FALSE, WFlags f = 0 )

构造一个空的向导对话框。parent、name、modal和f参数被传递给QDialog构造函数。

QWizard::~QWizard ()

销毁这个对象并且释放任何已经分配的资源，包括所有的页和控制器。

void QWizard::addPage ( QWidget * page, const QString & title ) [虚]

把page添加到页顺序的末尾，标题为title。

bool QWizard::appropriate ( QWidget * page ) const [虚]

当Next按钮被点击时被调用的，如果page和当前上下文中显示的是相关的，这个虚函数返回真，否则它就会被QWizard忽略并返回假。默认实现是返回使用setAppropriate()设置的值。最终默认值为真。

警告： 如果没有页面和当前上下文相关，向导中的最后一页会被显示。

void QWizard::back () [虚 保护 槽]

当用户点击Back按钮时被调用，这个函数显示在顺序中前面的相关页面。

也可以参考appropriate()。

QPushButton * QWizard::backButton () const

返回对话框Back按钮的指针。

默认情况下，这个按钮会被连接到back()槽，它是虚的，这样你可以在QWizard的子类中重新实现它。

QPushButton * QWizard::cancelButton () const

返回对话框的Cancel按钮的指针。

默认情况下，这个按钮会被连接到QDialog::reject()槽，它是虚的，这样你可以在QWizard的子类中重新实现它。

QWidget * QWizard::currentPage () const

返回在页顺序中当前页的指针。尽管向导会尽全力确保这个值不会为0，但如果你也足够尽力的话，它就有可能是了。

QPushButton * QWizard::finishButton () const

返回对话框的Finish按钮的指针。

默认情况下，这个按钮会被连接到QDialog::accept()槽，它是虚的，这样你可以在QWizard的子类中重新实现它。

void QWizard::help () [虚 保护 槽]

当用户点击Help按钮时被调用，这个函数发射helpClicked()信号。

QPushButton * QWizard::helpButton () const

返回对话框的Help按钮的指针。

默认情况下，这个按钮会被连接到help()槽，它是虚的，这样你可以在QWizard的子类中重新实现它。

void QWizard::helpClicked () [信号]

当用户点击Help按钮时，这个信号被发射。

int QWizard::indexOf ( QWidget * page ) const

返回页page的位置。如果这个页不是向导的一部分，-1被返回。

void QWizard::insertPage ( QWidget * page, const QString & title, int index ) [虚]

把page插入到页顺序的index位置，标题为title。如果index为-1，这个页会被添加到向导的页顺序的末尾。

void QWizard::layOutButtonRow ( QHBoxLayout * layout ) [虚 保护]

这个虚函数是负责添加底部的分割器和下面的按钮。

layout是整个向导的垂直布局。

void QWizard::layOutTitleRow ( QHBoxLayout * layout, const QString & title ) [虚 保护]

这个虚函数是负责布局上面的标题行并且在标题和向导页之间添加垂直分割器的。layout是向导的垂直布局，并且title是这页的标题。每次title改变时，这个函数都被调用。

void QWizard::next () [虚 保护 槽]

当用户点击Next按钮，这个函数显示在页顺序中后面的相关页。

也可以参考appropriate()。

QPushButton * QWizard::nextButton () const

返回对话框的Next按钮的指针。

默认情况下，这个按钮会被连接到next()槽，它是虚的，这样你可以在QWizard的子类中重新实现它。

QWidget * QWizard::page ( int index ) const

返回在页顺序中index位置的页的指针，或者如果index超出范围，返回0。第一页的索引是0。

int QWizard::pageCount () const

返回向导中的页数。

void QWizard::removePage ( QWidget * page ) [虚]

从页顺序中移除page但不删除它。如果page当前正被显示，QWizard将会显示它前面的一页，或者如果它是第一页就显示第一页。

void QWizard::selected ( const QString & ) [信号]

当当前页发生变化，这个信号被发射。参数包含被选择页的标题。

void QWizard::setAppropriate ( QWidget * page, bool appropriate ) [虚]

如果appropriate为真，那么页page别考虑为和当前上下文相关的并且应该在页顺序中被显示，否则page就不会在页顺序中被显示。

也可以参考appropriate()。

void QWizard::setBackEnabled ( QWidget * page, bool enable ) [虚 槽]

如果enable为真，页page有一个Back按钮，否则page就没有Back按钮。默认所有页都有这个按钮。

void QWizard::setFinish ( QWidget *, bool ) [虚 槽]

这个函数是废弃的。它的提供只是为了保证旧代码能够工作。我们强烈建议在新代码中不要使用它。

使用setFinishEnabled替代。

void QWizard::setFinishEnabled ( QWidget * page, bool enable ) [虚 槽]

如果enable为真，页page有一个Finish按钮，否则page就没有Finish按钮。默认所有页都没有这个按钮。

void QWizard::setHelpEnabled ( QWidget * page, bool enable ) [虚 槽]

如果enable为真，页page有一个Help按钮，否则page就没有Help按钮。默认所有页都有这个按钮。

void QWizard::setNextEnabled ( QWidget * page, bool enable ) [虚 槽]

如果enable为真，页page有一个Next按钮，否则Next就没有Help按钮。默认所有页都有这个按钮。

void QWizard::setTitle ( QWidget * page, const QString & title )

设置页page的标题为title。

void QWizard::setTitleFont ( const QFont & )

设置页标题所用的字体。详细情况请参考“titleFont”属性。

void QWizard::showPage ( QWidget * page ) [虚]

让page为当前页并且发射selected()信号。

实例：wizard/wizard.cpp。

QString QWizard::title ( QWidget * page ) const

返回页page的标题。

QFont QWizard::titleFont () const

返回页标题所有的字体。详细情况请参考“titleFont”属性。

属性文档

QFont titleFont

这个属性保存的是页标题使用的字体。

默认是QApplication::font()。

通过setTitleFont()设置属性值并且通过titleFont()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qwizard.h包含文件

qwizard.h

这里是qwizard.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qwizard.h   3.0.5   edited Oct 12 2001 $
**
** Definition of the QWizard class.
**
** Created : 990101
**
** Copyright (C) 1999 by Trolltech AS.  All rights reserved.
**
** This file is part of the dialogs module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWIZARDDIALOG_H
#define QWIZARDDIALOG_H

#ifndef QT_H
#include "qdialog.h"
#endif // QT_H

#ifndef QT_NO_WIZARD

class QHBoxLayout;
class QWizardPrivate;

class Q_EXPORT QWizard : public QDialog
{
    Q_OBJECT
    Q_PROPERTY( QFont titleFont READ titleFont WRITE setTitleFont )

public:
    QWizard( QWidget* parent=0, const char* name=0, bool modal=FALSE,
         WFlags f=0 );
    ~QWizard();

    void show();

    void setFont( const QFont & font );

    virtual void addPage( QWidget *, const QString & );
    virtual void insertPage( QWidget*, const QString&, int );
    virtual void removePage( QWidget * );

    QString title( QWidget * ) const;
    void setTitle( QWidget *, const QString & );
    QFont titleFont() const;
    void setTitleFont( const QFont & );

    virtual void showPage( QWidget * );

    QWidget * currentPage() const;

    QWidget* page( int ) const;
    int pageCount() const;
    int indexOf( QWidget* ) const;

    virtual bool appropriate( QWidget * ) const;
    virtual void setAppropriate( QWidget *, bool );

    QPushButton * backButton() const;
    QPushButton * nextButton() const;
    QPushButton * finishButton() const;
    QPushButton * cancelButton() const;
    QPushButton * helpButton() const;

    bool eventFilter( QObject *, QEvent * );

public slots:
    virtual void setBackEnabled( QWidget *, bool );
    virtual void setNextEnabled( QWidget *, bool );
    virtual void setFinishEnabled( QWidget *, bool );

    virtual void setHelpEnabled( QWidget *, bool );

    // obsolete
    virtual void setFinish(  QWidget *, bool ) {}

protected slots:
    virtual void back();
    virtual void next();
    virtual void help();

signals:
    void helpClicked();
    void selected( const QString& );

protected:
    virtual void layOutButtonRow( QHBoxLayout * );
    virtual void layOutTitleRow( QHBoxLayout *, const QString & );

private:
    void setBackEnabled( bool );
    void setNextEnabled( bool );

    void setHelpEnabled( bool );

    void setNextPage( QWidget * );

    void updateButtons();

    void layOut();

    QWizardPrivate *d;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QWizard( const QWizard & );
    QWizard& operator=( const QWizard & );
#endif
};

#endif // QT_NO_WIZARD

#endif // QWIZARD_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWizard成员列表

完整的QWizard成员列表

这里是QWizard成员函数的完整列表，包括继承的成员。

  • QWizard()
  • ~QWizard()
  • accept()
  • acceptDrops()
  • addPage()
  • adjustSize()
  • appropriate()
  • autoMask()
  • back()
  • backButton()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • cancelButton()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • currentPage()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • done()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • exec()
  • extension()
  • find()
  • finishButton()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • help()
  • helpButton()
  • helpClicked()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • indexOf()
  • inherits()
  • insertChild()
  • insertPage()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isSizeGripEnabled()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layOutButtonRow()
  • layOutTitleRow()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • next()
  • nextButton()
  • normalizeSignalSlot()
  • objectTrees()
  • orientation()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • page()
  • pageCount()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • reject()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • removePage()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • result()
  • scroll()
  • selected()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAppropriate()
  • setAutoMask()
  • setBackEnabled()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setExtension()
  • setFinish()
  • setFinishEnabled()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setHelpEnabled()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setNextEnabled()
  • setOrientation()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setResult()
  • setSizeGripEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setTitle()
  • setTitleFont()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showExtension()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • showPage()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • title()
  • titleFont()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWMatrix Class

QWMatrix Class Reference

The QWMatrix class specifies 2D transformations of a coordinate system. More...

#include <qwmatrix.h>

List of all member functions.

Public Members

  • QWMatrix ()
  • QWMatrix ( double m11, double m12, double m21, double m22, double dx, double dy )
  • void setMatrix ( double m11, double m12, double m21, double m22, double dx, double dy )
  • double m11 () const
  • double m12 () const
  • double m21 () const
  • double m22 () const
  • double dx () const
  • double dy () const
  • void map ( int x, int y, int * tx, int * ty ) const
  • void map ( double x, double y, double * tx, double * ty ) const
  • QRect mapRect ( const QRect & rect ) const
  • QPoint map ( const QPoint & p ) const (obsolete)
  • QRect map ( const QRect & r ) const (obsolete)
  • QPointArray map ( const QPointArray & a ) const (obsolete)
  • void reset ()
  • bool isIdentity () const
  • QWMatrix & translate ( double dx, double dy )
  • QWMatrix & scale ( double sx, double sy )
  • QWMatrix & shear ( double sh, double sv )
  • QWMatrix & rotate ( double a )
  • bool isInvertible () const
  • QWMatrix invert ( bool * invertible = 0 ) const
  • bool operator== ( const QWMatrix & m ) const
  • bool operator!= ( const QWMatrix & m ) const
  • QWMatrix & operator*= ( const QWMatrix & m )
  • QPoint operator* ( const QPoint & p ) const
  • QRegion operator* ( const QRect & r ) const
  • QRegion operator* ( const QRegion & r ) const
  • QPointArray operator* ( const QPointArray & a ) const

Related Functions

  • QWMatrix operator* ( const QWMatrix & m1, const QWMatrix & m2 )
  • QDataStream & operator<< ( QDataStream & s, const QWMatrix & m )
  • QDataStream & operator>> ( QDataStream & s, QWMatrix & m )

Detailed Description

The QWMatrix class specifies 2D transformations of a coordinate system.

The standard coordinate system of a paint device has the origin located at the top-left position. X values increase to the right; Y values increase downward.

This coordinate system is default for the QPainter, which renders graphics in a paint device. A user-defined coordinate system can be specified by setting a QWMatrix for the painter.

Example:

    MyWidget::paintEvent( QPaintEvent * )
    {
      QPainter p;                       // our painter
      QWMatrix m;                       // our transformation matrix
      m.rotate( 22.5 );                 // rotated coordinate system
      p.begin( this );                  // start painting
      p.setWorldMatrix( m );            // use rotated coordinate system
      p.drawText( 30,20, "detator" );   // draw rotated text at 30,20
      p.end();                          // painting done
    }

A matrix specifies how to translate, scale, shear or rotate the graphics; the actual transformation is performed by the drawing routines in QPainter and by QPixmap::xForm().

The QWMatrix class contains a 3*3 matrix of the form:

    m11  m12  0
    m21  m22  0
    dx   dy   1

A matrix transforms a point in the plane to another point:

    x' = m11*x + m21*y + dx
    y' = m22*y + m12*x + dy

The point (x, y) is the original point, and (x', y') is the transformed point. (x', y') can be transformed back to (x, y) by performing the same operation on the inverted matrix.

The elements dx and dy specify horizontal and vertical translation. The elements m11 and m22 specify horizontal and vertical scaling. The elements m12 and m21 specify horizontal and vertical shearing.

The identity matrix has m11 and m22 set to 1; all others are set to 0. This matrix maps a point to itself.

Translation is the simplest transformation. Setting dx and dy will move the coordinate system dx units along the X axis and dy units along the Y axis.

Scaling can be done by setting m11 and m22. For example, setting m11 to 2 and m22 to 1.5 will double the height and increase the width by 50%.

Shearing is controlled by m12 and m21. Setting these elements to values different from zero will twist the coordinate system.

Rotation is achieved by carefully setting both the shearing factors and the scaling factors. The QWMatrix has a function that sets rotation directly.

QWMatrix lets you combine transformations like this:

    QWMatrix m;           // identity matrix
    m.translate(10, -20); // first translate (10,-20)
    m.rotate(25);         // then rotate 25 degrees
    m.scale(1.2, 0.7);    // finally scale it

Here's the same example using basic matrix operations:

    double a    = pi/180 * 25;         // convert 25 to radians
    double sina = sin(a);
    double cosa = cos(a);
    QWMatrix m1(0, 0, 0, 0, 10, -20);  // translation matrix
    QWMatrix m2( cosa, sina,           // rotation matrix
                 -sina, cosa, 0, 0 );
    QWMatrix m3(1.2, 0, 0, 0.7, 0, 0); // scaling matrix
    QWMatrix m;
    m = m3 * m2 * m1;                  // combine all transformations

QPainter has functions to translate, scale, shear and rotate the coordinate system without using a QWMatrix. Although these functions are very convenient, it can be more efficient to build a QWMatrix and call QPainter::setWorldMatrix() if you want to perform more than a single transform operation.

See also QPainter::setWorldMatrix(), QPixmap::xForm(), Graphics Classes and Image Processing Classes.

Member Function Documentation

QWMatrix::QWMatrix ()

Constructs an identity matrix. All elements are set to zero except m11 and m22 (scaling), which are set to 1.

QWMatrix::QWMatrix ( double m11, double m12, double m21, double m22, double dx, double dy )

Constructs a matrix with the elements, m11, m12, m21, m22, dx and dy.

double QWMatrix::dx () const

Returns the horizontal translation.

double QWMatrix::dy () const

Returns the vertical translation.

QWMatrix QWMatrix::invert ( bool * invertible = 0 ) const

Returns the inverted matrix.

If the matrix is singular (not invertible), the identity matrix is returned.

If invertible is not null, the value of *invertible is set to TRUE if the matrix is invertible or to FALSE if the matrix is not invertible.

See also isInvertible().

Example: t14/cannon.cpp.

bool QWMatrix::isIdentity () const

Returns TRUE if the matrix is the identity matrix; otherwise returns FALSE.

See also reset().

bool QWMatrix::isInvertible () const

Returns TRUE if the matrix is invertible; otherwise returns FALSE.

See also invert().

double QWMatrix::m11 () const

Returns the X scaling factor.

double QWMatrix::m12 () const

Returns the vertical shearing factor.

double QWMatrix::m21 () const

Returns the horizontal shearing factor.

double QWMatrix::m22 () const

Returns the Y scaling factor.

void QWMatrix::map ( int x, int y, int * tx, int * ty ) const

Transforms ( x, y ) to ( *tx, *ty ) using the formulae:

    *tx = m11*x + m21*y + dx  (rounded to the nearest integer)
    *ty = m22*y + m12*x + dy  (rounded to the nearest integer)

Examples: t14/cannon.cpp and xform/xform.cpp.

void QWMatrix::map ( double x, double y, double * tx, double * ty ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Transforms ( x, y ) to ( *tx, *ty ) using the following formulae:

    *tx = m11*x + m21*y + dx
    *ty = m22*y + m12*x + dy

QPoint QWMatrix::map ( const QPoint & p ) const

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Does the same as operator *( const QPoint &)

QRect QWMatrix::map ( const QRect & r ) const

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Please use QWMatrix::mapRect() instead.

Note that this method does return the bounding rectangle of the r, when shearing or rotations are used.

QPointArray QWMatrix::map ( const QPointArray & a ) const

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Does the same as operator *( const QPointArray &)

QRect QWMatrix::mapRect ( const QRect & rect ) const

Returns the transformed rectangle rect.

The bounding rectangle is returned if rotation or shearing has been specified.

If you need to know the exact region rect maps to use operator*().

See also operator*().

bool QWMatrix::operator!= ( const QWMatrix & m ) const

Returns TRUE if this matrix is not equal to m; otherwise returns FALSE.

QPoint QWMatrix::operator* ( const QPoint & p ) const

Transforms p to using the formulae:

    retx = m11*px + m21*py + dx  (rounded to the nearest integer)
    rety = m22*py + m12*px + dy  (rounded to the nearest integer)

QRegion QWMatrix::operator* ( const QRect & r ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Transforms the rectangle r.

Rotation and shearing a rectangle results in a more general region, which is returned here.

Calling this method can be rather expensive, if rotations or shearing are used. If you just need to know the bounding rectangle of the returned region, use mapRect() which is a lot faster than this function.

See also QWMatrix::mapRect().

QRegion QWMatrix::operator* ( const QRegion & r ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Transforms the region r.

Calling this method can be rather expensive, if rotations or shearing are used.

QPointArray QWMatrix::operator* ( const QPointArray & a ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the point array a transformed by calling map for each point.

QWMatrix & QWMatrix::operator*= ( const QWMatrix & m )

Returns the result of multiplying this matrix with matrix m.

bool QWMatrix::operator== ( const QWMatrix & m ) const

Returns TRUE if this matrix is equal to m; otherwise returns FALSE.

void QWMatrix::reset ()

Resets the matrix to an identity matrix.

All elements are set to zero, except m11 and m22 (scaling) that are set to 1.

See also isIdentity().

QWMatrix & QWMatrix::rotate ( double a )

Rotates the coordinate system a degrees counterclockwise.

Returns a reference to the matrix.

See also translate(), scale() and shear().

Examples: canvas/canvas.cpp, desktop/desktop.cpp, drawdemo/drawdemo.cpp, t14/cannon.cpp and xform/xform.cpp.

QWMatrix & QWMatrix::scale ( double sx, double sy )

Scales the coordinate system unit by sx horizontally and sy vertically.

Returns a reference to the matrix.

See also translate(), shear() and rotate().

Examples: canvas/canvas.cpp, fileiconview/qfileiconview.cpp, movies/main.cpp, qmag/qmag.cpp, qtimage/qtimage.cpp, showimg/showimg.cpp and xform/xform.cpp.

void QWMatrix::setMatrix ( double m11, double m12, double m21, double m22, double dx, double dy )

Sets the matrix elements to the specified values, m11, m12, m21, m22, dx and dy.

QWMatrix & QWMatrix::shear ( double sh, double sv )

Shears the coordinate system by sh horizontally and sv vertically.

Returns a reference to the matrix.

See also translate(), scale() and rotate().

Examples: drawdemo/drawdemo.cpp and xform/xform.cpp.

QWMatrix & QWMatrix::translate ( double dx, double dy )

Moves the coordinate system dx along the X-axis and dy along the Y-axis.

Returns a reference to the matrix.

See also scale(), shear() and rotate().

Examples: canvas/canvas.cpp, drawdemo/drawdemo.cpp, t14/cannon.cpp and xform/xform.cpp.

Related Functions

QWMatrix operator* ( const QWMatrix & m1, const QWMatrix & m2 )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the product of m1 * m2.

Note that matrix multiplication is not commutative, i.e. a*b != b*a.

QDataStream & operator<< ( QDataStream & s, const QWMatrix & m )

Writes the matrix m to the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

QDataStream & operator>> ( QDataStream & s, QWMatrix & m )

Reads the matrix m from the stream s and returns a reference to the stream.

See also Format of the QDataStream operators.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


qwmatrix.h Include File

qwmatrix.h

This is the verbatim text of the qwmatrix.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qwmatrix.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QWMatrix class
**
** Created : 941020
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWMATRIX_H
#define QWMATRIX_H

#ifndef QT_H
#include "qwindowdefs.h"
#include "qpointarray.h"
#include "qrect.h"
#endif // QT_H

#ifndef QT_NO_WMATRIX

class Q_EXPORT QWMatrix					// 2D transform matrix
{
public:
    QWMatrix();
    QWMatrix( double m11, double m12, double m21, double m22,
          double dx, double dy );

    void	setMatrix( double m11, double m12, double m21, double m22,
               double dx,  double dy );

    double	m11() const { return _m11; }
    double	m12() const { return _m12; }
    double	m21() const { return _m21; }
    double	m22() const { return _m22; }
    double	dx()  const { return _dx; }
    double	dy()  const { return _dy; }

    void	map( int x, int y, int *tx, int *ty )	      const;
    void	map( double x, double y, double *tx, double *ty ) const;
    QRect	mapRect( const QRect & )	const;

    QPoint	map( const QPoint &p )	const { return operator *( p ); }
    QRect	map( const QRect &r )	const { return mapRect ( r ); }
    QPointArray map( const QPointArray &a ) const { return operator * ( a ); }

    void	reset();
    bool	isIdentity() const;

    QWMatrix   &translate( double dx, double dy );
    QWMatrix   &scale( double sx, double sy );
    QWMatrix   &shear( double sh, double sv );
    QWMatrix   &rotate( double a );

    bool isInvertible() const { return (_m11*_m22 - _m12*_m21) != 0; }
    QWMatrix	invert( bool * = 0 ) const;

    bool	operator==( const QWMatrix & ) const;
    bool	operator!=( const QWMatrix & ) const;
    QWMatrix   &operator*=( const QWMatrix & );

    /* we use matrix multiplication semantics here */
    QPoint operator * (const QPoint & ) const;
    QRegion operator * (const QRect & ) const;
    QRegion operator * (const QRegion & ) const;
    QPointArray operator *  ( const QPointArray &a ) const;

private:
    QWMatrix   &bmul( const QWMatrix & );
    double	_m11, _m12;
    double	_m21, _m22;
    double	_dx,  _dy;
};

Q_EXPORT QWMatrix operator*( const QWMatrix &, const QWMatrix & );

/*****************************************************************************
  QWMatrix stream functions
 *****************************************************************************/

Q_EXPORT QDataStream &operator<<( QDataStream &, const QWMatrix & );
Q_EXPORT QDataStream &operator>>( QDataStream &, QWMatrix & );

#endif // QT_NO_WMATRIX

#endif // QWMATRIX_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWMatrix Member List

Complete Member List for QWMatrix

This is the complete list of member functions for QWMatrix, including inherited members.

  • QWMatrix()
  • dx()
  • dy()
  • invert()
  • isIdentity()
  • isInvertible()
  • m11()
  • m12()
  • m21()
  • m22()
  • map()
  • mapRect()
  • operator!=()
  • operator*()
  • operator*=()
  • operator==()
  • reset()
  • rotate()
  • scale()
  • setMatrix()
  • shear()
  • translate()


QWorkspace类

QWorkspace类参考

QWorkspace窗口部件提供了可以包含内部窗口（例如，多文档界面）的工作区窗口。 详情请见……

#include <qworkspace.h>

继承了QWidget。

所有成员函数的列表。

公有成员

  • QWorkspace ( QWidget * parent = 0, const char * name = 0 )
  • ~QWorkspace ()
  • QWidget * activeWindow () const
  • QWidgetList windowList () const
  • bool scrollBarsEnabled () const
  • void setScrollBarsEnabled ( bool enable )

公有槽

  • void cascade ()
  • void tile ()

信号

  • void windowActivated ( QWidget * w )

属性

  • bool scrollBarsEnabled - 工作区是否提供滚动条

详细描述

QWorkspace窗口部件提供了可以包含内部窗口（例如，多文档界面）的工作区窗口。

一个多文档界面（MDI）应用程序有一个带菜单条的主窗口。这个窗口的中央窗口部件就是一个工作区。工作区自己包含零个、一个或多个文档窗口，每个窗口显示一个文档。

工作区自己是一个普通Qt窗口部件。它有一个带父窗口部件和对象名称的标准构造函数。父对象通常使用QMainWindow，但也可以不是。

文档窗口（也就是多文档界面窗口）也是普通的Qt窗口部件，它们有一个工作区作为父窗口部件。当你在一个文档窗口上调用show()、hide()、showMaximized()、setCaption()等等，它被按你所期望的有一个框架、标题、图标和图标文本来显示、隐藏等等。你可以提供窗口部件标记来用于修饰的布局或者窗口部件自身的行为。

为了改变多文档窗口的几何形状，让这个函数调用这个窗口部件的parentWidget()是需要的，因为它将会移动或者重新定义内部窗口的大小。

当一个文档窗口获得键盘焦点时，它被激活了。你可以使用setFocus()来激活它，并且用户可以用普通的移动焦点的方式来激活它。当工作区检测到激活变化时，它发射一个windowActivated()信号，并且activeWindow()函数总是返回活动的文档窗口的指针。

方便的windowList()函数返回所有的文档窗口的列表。例如，这对于在空中创建一个弹出菜单“Windows”是很有用的。

QWorkspace提供了两个内置的对子窗口的布局策略：cascade()和tile()。这两个都是槽，这样你就可以很容易地把菜单项和它们连接起来了。

如果你想让用户能够把工作的文档窗口设置的比实际工作区还大，请把scrollBarsEnabled属性设置为真。

如果顶级窗口包含一个菜单条和一个最大化的文档窗口，QWorkspace会把文档窗口的最小化、恢复和关闭按钮从文档窗口的框架上移到工作区窗口的菜单条中。然后它会在菜单条的最左面插入一个窗口操作菜单。

也可以参考主窗口和相关类和组织者。

成员函数文档

QWorkspace::QWorkspace ( QWidget * parent = 0, const char * name = 0 )

构造一个父对象为parent、名称为name的工作区。

QWorkspace::~QWorkspace ()

销毁这个工作区并且释放所有已分配的资源。

QWidget * QWorkspace::activeWindow () const

返回活动窗口，或者如果没有窗口是活动的，返回0。

实例：mdi/application.cpp。

void QWorkspace::cascade () [槽]

层叠模式排列所有子窗口。

也可以参考tile()。

实例：mdi/application.cpp。

bool QWorkspace::scrollBarsEnabled () const

如果工作区提供滚动条，返回真，否则返回假。详细情况请参考“scrollBarsEnabled”属性。

void QWorkspace::setScrollBarsEnabled ( bool enable )

设置工作区是否提供滚动条为enable。详细情况请参考“scrollBarsEnabled”属性。

void QWorkspace::tile () [槽]

平铺模式排列所有子窗口。

也可以参考cascade()。

实例：mdi/application.cpp。

void QWorkspace::windowActivated ( QWidget * w ) [信号]

当窗口部件w变为活动时，这个信号被发射。注意w可以为零，并且对于一个激活事件可能有超过一个的信号被发射。

也可以参考activeWindow()和windowList()。

QWidgetList QWorkspace::windowList () const

返回所有窗口的列表。

实例：mdi/application.cpp。

属性文档

bool scrollBarsEnabled

This property holds whether the workspace provides scrollbars. 这个属性保存的是工作区是否提供滚动条。

如果这个属性被设置为真，那么重定义子窗口的大小超过工作区的可视区域的右或下边缘是可能的。工作区显示这些滚动条使用户能够访问这些窗口。如果这个属性被设置为假（默认），定义子窗口的大小超过工作区的可视区域的右或下边缘是不被允许的。

通过setScrollBarsEnabled()设置属性值并且通过scrollBarsEnabled()来获得属性值。

这个文件是Qt工具包一部分。 版权所有 © 1995-2002 Trolltech。保留所有权利。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


qworkspace.h包含文件

qworkspace.h

这里是qworkspace.h包含文件的所有文本，一字不差。它仅仅用来说明，版权由Trolltech保留。

/****************************************************************************
** $Id:  qt/qworkspace.h   3.0.5   edited Nov 9 2001 $
**
** Definition of the QWorkspace class
**
** Created : 990210
**
** Copyright (C) 1999-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the workspace module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWORKSPACE_H
#define QWORKSPACE_H

#ifndef QT_H
#include <qwidget.h>
#include <qwidgetlist.h>
#endif // QT_H

#ifndef QT_NO_WORKSPACE

#if !defined( QT_MODULE_WORKSPACE ) || defined( QT_INTERNAL_WORKSPACE )
#define QM_EXPORT_WORKSPACE
#else
#define QM_EXPORT_WORKSPACE Q_EXPORT
#endif

class QWorkspaceChild;
class QShowEvent;
class QWorkspacePrivate;
class QPopupMenu;

class QM_EXPORT_WORKSPACE QWorkspace : public QWidget
{
    Q_OBJECT
    Q_PROPERTY( bool scrollBarsEnabled READ scrollBarsEnabled WRITE setScrollBarsEnabled )
public:
    QWorkspace( QWidget* parent=0, const char* name=0 );
    ~QWorkspace();

    QWidget* activeWindow() const;
    QWidgetList windowList() const;

    QSize sizeHint() const;

    bool scrollBarsEnabled() const;
    void setScrollBarsEnabled( bool enable );

    void setPaletteBackgroundColor( const QColor & );
    void setPaletteBackgroundPixmap( const QPixmap & );

signals:
    void windowActivated( QWidget* w);

public slots:
    void cascade();
    void tile();

protected:
#ifndef QT_NO_STYLE
    void styleChange( QStyle& );
#endif
    void childEvent( QChildEvent * );
    void resizeEvent( QResizeEvent * );
    bool eventFilter( QObject *, QEvent * );
    void showEvent( QShowEvent *e );
    void hideEvent( QHideEvent *e );
#ifndef QT_NO_WHEELEVENT
    void wheelEvent( QWheelEvent *e );
#endif

private slots:
    void closeActiveWindow();
    void closeAllWindows();
    void normalizeActiveWindow();
    void minimizeActiveWindow();
    void showOperationMenu();
    void popupOperationMenu( const QPoint& );
    void operationMenuActivated( int );
    void operationMenuAboutToShow();
    void toolMenuAboutToShow();
    void activateNextWindow();
    void activatePreviousWindow();
    void scrollBarChanged();

private:
    void insertIcon( QWidget* w);
    void removeIcon( QWidget* w);
    void place( QWidget* );

    QWorkspaceChild* findChild( QWidget* w);
    void showMaximizeControls();
    void hideMaximizeControls();
    void activateWindow( QWidget* w, bool change_focus = TRUE );
    void showWindow( QWidget* w);
    void maximizeWindow( QWidget* w);
    void minimizeWindow( QWidget* w);
    void normalizeWindow( QWidget* w);

    QRect updateWorkspace();

    QPopupMenu* popup;
    QWorkspacePrivate* d;

    friend class QWorkspaceChild;

private:	// Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
    QWorkspace( const QWorkspace & );
    QWorkspace& operator=( const QWorkspace & );
#endif
};

#endif // QT_NO_WORKSPACE

#endif // QWORKSPACE_H

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


QWorkspace成员列表

完整的QWorkspace成员列表

这里是QWorkspace成员函数的完整列表，包括继承的成员。

  • QWorkspace()
  • ~QWorkspace()
  • acceptDrops()
  • activeWindow()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • cascade()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • scrollBarsEnabled()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setScrollBarsEnabled()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • tile()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivated()
  • windowActivationChange()
  • windowList()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • y()

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt/Embedded

These classes are relevant to Qt/Embedded users.

QFontManager | Implements font management in Qt/Embedded
QLock | Wrapper for a System V shared semaphore
QScreen | And its descendants manage the framebuffer and palette
QWSDecoration | Allows the appearance of the Qt/Embedded Window Manager to be customized
QWSKeyboardHandler | Implements the keyboard driver/handler for Qt/Embedded
QWSMouseHandler | Mouse driver/handler for Qt/Embedded
QWSServer | Server-specific functionality in Qt/Embedded
QWSWindow | Server-specific functionality in Qt/Embedded


QWSDecoration Class

QWSDecoration Class Reference

The QWSDecoration class allows the appearance of the Qt/Embedded Window Manager to be customized. More...

#include <qwsdecoration_qws.h>

List of all member functions.

Public Members

  • QWSDecoration ()
  • virtual ~QWSDecoration ()
  • enum Region { None = 0, All = 1, Title = 2, Top = 3, Bottom = 4, Left = 5, Right = 6, TopLeft = 7, TopRight = 8, BottomLeft = 9, BottomRight = 10, Close = 11, Minimize = 12, Maximize = 13, Normalize = 14, Menu = 15, LastRegion = Menu }
  • virtual QRegion region ( const QWidget * widget, const QRect & rect, Region type = All ) = 0
  • virtual void close ( QWidget * widget )
  • virtual void minimize ( QWidget * widget )
  • virtual void maximize ( QWidget * widget )
  • virtual QPopupMenu * menu ( const QWidget *, const QPoint & )
  • virtual void paint ( QPainter * painter, const QWidget * widget ) = 0
  • virtual void paintButton ( QPainter * painter, const QWidget * widget, Region type, int state ) = 0

Detailed Description

The QWSDecoration class allows the appearance of the Qt/Embedded Window Manager to be customized.

Qt/Embedded provides window management to top level windows. The appearance of the borders and buttons (the decoration) around the managed windows can be customized by creating your own class derived from QWSDecoration and overriding a few methods.

This class is non-portable. It is available only in Qt/Embedded.

See also QApplication::qwsSetDecoration() and Qt/Embedded.

Member Type Documentation

QWSDecoration::Region

This enum describes the regions in the window decorations.

  • QWSDecoration::None - used internally.
  • QWSDecoration::All - the entire region used by the window decoration.
  • QWSDecoration::Title - Displays the window title and allows the window to be moved by dragging.
  • QWSDecoration::Top - allows the top of the window to be resized.
  • QWSDecoration::Bottom - allows the bottom of the window to be resized.
  • QWSDecoration::Left - allows the left edge of the window to be resized.
  • QWSDecoration::Right - allows the right edge of the window to be resized.
  • QWSDecoration::TopLeft - allows the top-left of the window to be resized.
  • QWSDecoration::TopRight - allows the top-right of the window to be resized.
  • QWSDecoration::BottomLeft - allows the bottom-left of the window to be resized.
  • QWSDecoration::BottomRight - allows the bottom-right of the window to be resized.
  • QWSDecoration::Close - clicking in this region closes the window.
  • QWSDecoration::Minimize - clicking in this region minimizes the window.
  • QWSDecoration::Maximize - clicking in this region maximizes the window.
  • QWSDecoration::Normalize - returns a maximized window to previous size.
  • QWSDecoration::Menu - clicking in this region opens the window operations menu.

Member Function Documentation

QWSDecoration::QWSDecoration ()

Constructs a decorator.

QWSDecoration::~QWSDecoration () [virtual]

Destroys a decorator.

void QWSDecoration::close ( QWidget * widget ) [virtual]

Called when the user clicks in the Close region.

widget is the QWidget to be closed.

The default behaviour is to close the widget.

void QWSDecoration::maximize ( QWidget * widget ) [virtual]

Called when the user clicks in the Maximize region.

widget is the QWidget to be maximized.

The default behaviour is to resize the widget to be full-screen. This method can be overridden to, e.g. avoid launch panels.

QPopupMenu * QWSDecoration::menu ( const QWidget *, const QPoint & ) [virtual]

Called to create a QPopupMenu containing the valid menu operations.

The default implementation adds all possible window operations.

void QWSDecoration::minimize ( QWidget * widget ) [virtual]

Called when the user clicks in the Minimize region.

widget is the QWidget to be minimized.

The default behaviour is to ignore this action.

void QWSDecoration::paint ( QPainter * painter, const QWidget * widget ) [pure virtual]

Override to paint the border and title decoration around widget using painter.

void QWSDecoration::paintButton ( QPainter * painter, const QWidget * widget, Region type, int state ) [pure virtual]

Override to paint a button type using painter.

widget is the widget whose button is to be drawn. state is the state of the button. It can be a combination of the following ORed together:

  • QWSButton::MouseOver
  • QWSButton::Clicked
  • QWSButton::On

QRegion QWSDecoration::region ( const QWidget * widget, const QRect & rect, Region type = All ) [pure virtual]

Returns the requested region type which will contain widget with geometry rect.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QWSDecoration Member List

Complete Member List for QWSDecoration

This is the complete list of member functions for QWSDecoration, including inherited members.

  • QWSDecoration()
  • ~QWSDecoration()
  • close()
  • maximize()
  • menu()
  • minimize()
  • paint()
  • paintButton()
  • region()


qwsdecoration_qws.h Include File

qwsdecoration_qws.h

This is the verbatim text of the qwsdecoration_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qwsdecoration_qws.h   3.0.5   edited Oct 12 2001 $
**
** Definition of QWSDecoration class.
**
** Created : 20000308
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QWSDECORATION_H
#define QWSDECORATION_H

#ifndef QT_H
#include "qregion.h"
#endif // QT_H

class QPopupMenu;

/*
 Implements decoration styles
*/
class QWSDecoration
{
public:
    QWSDecoration() {}
    virtual ~QWSDecoration() {}

    enum Region { None=0, All=1, Title=2, Top=3, Bottom=4, Left=5, Right=6,
        TopLeft=7, TopRight=8, BottomLeft=9, BottomRight=10,
        Close=11, Minimize=12, Maximize=13, Normalize=14,
        Menu=15, LastRegion=Menu };

    virtual QRegion region(const QWidget *, const QRect &rect, Region r=All) = 0;
    virtual void close( QWidget * );
    virtual void minimize( QWidget * );
    virtual void maximize( QWidget * );
#ifndef QT_NO_POPUPMENU
    virtual QPopupMenu *menu(const QWidget *, const QPoint &);
#endif
    virtual void paint(QPainter *, const QWidget *) = 0;
    virtual void paintButton(QPainter *, const QWidget *, Region, int state) = 0;
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWSKeyboardHandler Class

QWSKeyboardHandler Class Reference

The QWSKeyboardHandler class implements the keyboard driver/handler for Qt/Embedded. More...

#include <qkeyboard_qws.h>

Inherits QObject.

List of all member functions.

Public Members

  • QWSKeyboardHandler ()
  • virtual ~QWSKeyboardHandler ()

Protected Members

  • virtual void processKeyEvent ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat )

Detailed Description

The QWSKeyboardHandler class implements the keyboard driver/handler for Qt/Embedded.

The keyboard handler (driver) handles events from system devices and generates key events.

A QWSKeyboardHandler will usually open some system device in its constructor, create a QSocketNotifier on that opened device and when it receives data, it will call processKeyEvent() to send the event to Qt/Embedded for relaying to clients.

See also Qt/Embedded.

Member Function Documentation

QWSKeyboardHandler::QWSKeyboardHandler ()

Constructs a keyboard handler. The handler may be passed to the system for later destruction with QWSServer::setKeyboardHandler(), although even without doing this, the handler can function, calling processKeyEvent() to emit events.

QWSKeyboardHandler::~QWSKeyboardHandler () [virtual]

Destroys a keyboard handler. Note that if you have called QWSServer::setKeyboardHandler(), you may not delete the handler.

void QWSKeyboardHandler::processKeyEvent ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ) [virtual protected]

Subclasses call this function to send a key event. The server may additionally filter the event before sending it on to applications.

  • unicode is the Unicode value for the key, or 0xFFFF is none is appropriate.
  • keycode is the Qt keycode for the key (see Qt::Key). for the list of codes).
  • modifiers is the set of modifier keys (see Qt::Modifier).
  • isPress says whether this is a press or a release.
  • autoRepeat says whether this event was generated by an auto-repeat mechanism, or an actual key press.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QWSKeyboardHandler Member List

Complete Member List for QWSKeyboardHandler

This is the complete list of member functions for QWSKeyboardHandler, including inherited members.

  • QWSKeyboardHandler()
  • ~QWSKeyboardHandler()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • processKeyEvent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


qwsmouse_qws.h Include File

qwsmouse_qws.h

This is the verbatim text of the qwsmouse_qws.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qwsmouse_qws.h   3.0.5   edited Oct 31 2001 $
**
** Definition of Qt/FB central server classes
**
** Created : 991025
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QWSMOUSE_H
#define QWSMOUSE_H

#ifndef QT_H
#include <qobject.h>
#include <qpointarray.h>
#include <qptrlist.h>
#include "qsocketnotifier.h"
#endif // QT_H

class QWSPointerCalibrationData
{
public:
    enum Location { TopLeft = 0, BottomLeft = 1, BottomRight = 2, TopRight = 3,
            Center = 4, LastLocation = Center };
    QPoint devPoints[5];
    QPoint screenPoints[5];
};

class QWSMouseHandler : public QObject {
    Q_OBJECT
public:
    QWSMouseHandler();
    virtual ~QWSMouseHandler();

    virtual void clearCalibration() {}
    virtual void calibrate( QWSPointerCalibrationData * ) {}
    virtual void getCalibration( QWSPointerCalibrationData * ) {}

protected:
    enum {mouseBufSize = 128};

    void mouseChanged(const QPoint& pos, int bstate);
};

#if !defined(QT_QWS_IPAQ) && !defined(QT_QWS_CASSIOPEIA)
# define QT_NO_QWS_MOUSE_CALIBRATED
#endif

#ifndef QT_NO_QWS_MOUSE_CALIBRATED
class QCalibratedMouseHandler : public QWSMouseHandler
{
    Q_OBJECT
public:
    QCalibratedMouseHandler();

    virtual void clearCalibration();
    virtual void calibrate( QWSPointerCalibrationData * );
    virtual void getCalibration( QWSPointerCalibrationData * );

protected:
    void readCalibration();
    void writeCalibration();
    QPoint transform( const QPoint & );
    bool sendFiltered( const QPoint &, int button );
    void setFilterSize( int );

private:
    int a, b, c;
    int d, e, f;
    int s;
    QPointArray samples;
    unsigned int currSample;
    unsigned int numSamples;
};
#endif

/********************* PRIVATE CLASSES FOLLOW *******************************/

enum MouseProtocol { Unknown = -1, Auto = 0,
             MouseMan, IntelliMouse, Microsoft,
             QVFBMouse, TPanel, BusMouse,
             FirstAuto = MouseMan,
             LastAuto = Microsoft };

#ifndef QT_NO_QWS_MOUSE_AUTO
class QAutoMouseSubHandler;
class QAutoMouseHandlerPrivate : public QWSMouseHandler {
    Q_OBJECT
public:
    QAutoMouseHandlerPrivate();
    ~QAutoMouseHandlerPrivate();

private:
    enum { max_dev=32 };
    QAutoMouseSubHandler *sub[max_dev];
    QPtrList<QSocketNotifier> notifiers;
    int nsub;
    int retries;

private slots:
    void readMouseData(int);

private:
    void openDevices();
    void closeDevices();
    void notify(int fd);
    bool sendEvent(QAutoMouseSubHandler& h);

};
#endif

#ifndef QT_NO_QWS_MOUSE_MANUAL
class QWSMouseHandlerPrivate : public QWSMouseHandler {
    Q_OBJECT
public:
    QWSMouseHandlerPrivate( MouseProtocol protocol, QString mouseDev );
    ~QWSMouseHandlerPrivate();

private:
    int mouseFD;
    int mouseIdx;
    uchar mouseBuf[mouseBufSize];
    MouseProtocol mouseProtocol;
    void handleMouseData();

private slots:
    void readMouseData();

private:
    int obstate;
    QTimer *rtimer;
};
#endif

#ifdef QT_QWS_CASSIOPEIA
/*
 * Handler for /dev/tpanel Linux kernel driver
 */

class QVrTPanelHandlerPrivate : public QCalibratedMouseHandler {
    Q_OBJECT
public:
    QVrTPanelHandlerPrivate(MouseProtocol, QString dev);
    ~QVrTPanelHandlerPrivate();

private:
    int mouseFD;
    MouseProtocol mouseProtocol;
private slots:
    void sendRelease();
    void readMouseData();
private:
    QTimer *rtimer;
    int mouseIdx;
    uchar mouseBuf[mouseBufSize];
};
#endif

#if defined(QT_QWS_IPAQ) || defined(QT_QWS_EBX)
class QTPanelHandlerPrivate : public QCalibratedMouseHandler
{
     Q_OBJECT
public:
    QTPanelHandlerPrivate(MouseProtocol, QString dev);
    ~QTPanelHandlerPrivate();

private:
    static const int mouseBufSize = 2048;
    int mouseFD;
    QPoint oldmouse;
    bool waspressed;
    QPointArray samples;
    unsigned int currSample;
    unsigned int numSamples;
    int mouseIdx;
    uchar mouseBuf[mouseBufSize];

private slots:
    void readMouseData();
};
#endif

#ifdef QT_QWS_YOPY
// YOPY touch panel support based on changes contributed by Ron Victorelli
// (victorrj at icubed.com) to Custom TP driver.
//
class QYopyTPanelHandlerPrivate : public QWSMouseHandler {
    Q_OBJECT
public:
    QYopyTPanelHandlerPrivate(MouseProtocol, QString dev);
    ~QYopyTPanelHandlerPrivate();

private:
    int mouseFD;
    int prevstate;
private slots:
    void readMouseData();

};
#endif

#ifdef QT_QWS_CUSTOMTOUCHPANEL
class QCustomTPanelHandlerPrivate : public QWSMouseHandler {
    Q_OBJECT
public:
    QCustomTPanelHandlerPrivate(MouseProtocol, QString dev);
    ~QCustomTPanelHandlerPrivate();

private:
    int mouseFD;
private slots:
    void readMouseData();
};
#endif

#ifndef QT_NO_QWS_VFB
class QVFbMouseHandlerPrivate : public QWSMouseHandler {
    Q_OBJECT
public:
    QVFbMouseHandlerPrivate(MouseProtocol, QString dev);
    ~QVFbMouseHandlerPrivate();

    bool isOpen() const { return mouseFD > 0; }

private:
    int mouseFD;
    int mouseIdx;
    uchar mouseBuf[mouseBufSize];
private slots:
    void readMouseData();
};
#endif

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QWSMouseHandler Class

QWSMouseHandler Class Reference

The QWSMouseHandler class is a mouse driver/handler for Qt/Embedded. More...

#include <qwsmouse_qws.h>

Inherits QObject.

List of all member functions.

Public Members

  • QWSMouseHandler ()
  • virtual ~QWSMouseHandler ()
  • virtual void clearCalibration ()
  • virtual void calibrate ( QWSPointerCalibrationData * )
  • virtual void getCalibration ( QWSPointerCalibrationData * )

Protected Members

  • void mouseChanged ( const QPoint & pos, int bstate )

Detailed Description

The QWSMouseHandler class is a mouse driver/handler for Qt/Embedded.

The mouse driver/handler handles events from system devices and generates mouse events.

A QWSMouseHandler will usually open some system device in its constructor, create a QSocketNotifier on that opened device and when it receives data, it will call mouseChanged() to send the event to Qt/Embedded for relaying to clients.

See also Qt/Embedded.

Member Function Documentation

QWSMouseHandler::QWSMouseHandler ()

Constructs a mouse handler. This becomes the primary mouse handler.

Note that once created, mouse handlers are controlled by the system and should not be deleted.

QWSMouseHandler::~QWSMouseHandler () [virtual]

Destroys the mouse handler. You should not call this directly.

void QWSMouseHandler::calibrate ( QWSPointerCalibrationData * ) [virtual]

This method is reimplemented in the calibrated mouse handler to set calibration information (from, for instance, the QPE calibration screen). This version does nothing.

void QWSMouseHandler::clearCalibration () [virtual]

This method is reimplemented in the calibrated mouse handler to clear calibration information. This version does nothing.

void QWSMouseHandler::mouseChanged ( const QPoint & pos, int bstate ) [protected]

When a mouse event occurs this function is called with the mouse's position in pos, and the state of its buttons in bstate.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QWSMouseHandler Member List

Complete Member List for QWSMouseHandler

This is the complete list of member functions for QWSMouseHandler, including inherited members.

  • QWSMouseHandler()
  • ~QWSMouseHandler()
  • blockSignals()
  • calibrate()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clearCalibration()
  • connect()
  • connectNotify()
  • customEvent()
  • deleteLater()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dumpObjectInfo()
  • dumpObjectTree()
  • event()
  • eventFilter()
  • highPriority()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • metaObject()
  • mouseChanged()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • parent()
  • property()
  • queryList()
  • removeChild()
  • removeEventFilter()
  • sender()
  • setName()
  • setProperty()
  • signalsBlocked()
  • startTimer()
  • timerEvent()
  • tr()
  • trUtf8()


QWSServer Class

QWSServer Class Reference

The QWSServer class provides server-specific functionality in Qt/Embedded. More...

#include <qwindowsystem_qws.h>

List of all member functions.

Public Members

  • QWSServer ( int flags = 0, QObject * parent = 0, const char * name = 0 )
  • ~QWSServer ()
  • enum ServerFlags { DisableKeyboard = 0x01, DisableMouse = 0x02 }
  • enum GUIMode { NoGui = FALSE, NormalGUI = TRUE, Server }
  • class KeyMap { }
  • class KeyboardFilter { }
  • QWSWindow * windowAt ( const QPoint & pos )
  • const QPtrList<QWSWindow> & clientWindows ()
  • void openMouse ()
  • void closeMouse ()
  • void openKeyboard ()
  • void closeKeyboard ()
  • void refresh ()
  • void refresh ( QRegion & r )
  • void enablePainting ( bool e )
  • QWSPropertyManager * manager ()
  • enum WindowEvent { Create = 0x01, Destroy = 0x02, Hide = 0x04, Show = 0x08, Raise = 0x10, Lower = 0x20, Geometry = 0x40 }

Signals

  • void windowEvent ( QWSWindow * w, QWSServer::WindowEvent e )
  • void newChannel ( const QString & )

Static Public Members

  • void sendKeyEvent ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat )
  • const KeyMap * keyMap ()
  • void setKeyboardFilter ( KeyboardFilter * f )
  • void setDefaultMouse ( const char * m )
  • void setDefaultKeyboard ( const char * k )
  • void setMaxWindowRect ( const QRect & r )
  • void setDesktopBackground ( const QImage & img )
  • void setDesktopBackground ( const QColor & c )
  • QWSMouseHandler * mouseHandler ()
  • QWSKeyboardHandler * keyboardHandler ()
  • void setKeyboardHandler ( QWSKeyboardHandler * kh )
  • void setScreenSaver ( QWSScreenSaver * ss )
  • void setScreenSaverIntervals ( int * ms )
  • void setScreenSaverInterval ( int ms )
  • bool screenSaverActive ()
  • void screenSaverActivate ( bool activate )

Detailed Description

The QWSServer class provides server-specific functionality in Qt/Embedded.

When you run a Qt/Embedded application, it either runs as a server or connects to an existing server. If it runs as a server, some additional operations are provided via the QWSServer class.

This class is instantiated by QApplication for Qt/Embedded server processes. You should never construct this class yourself.

A pointer to the QWSServer instance can be obtained via the global qwsServer variable.

The mouse and keyboard devices can be opened with openMouse() and openKeyboard(). (Close them with closeMouse() and closeKeyboard().)

The display is refreshed with refresh(), and painting can be enabled or disabled with enablePainting().

Obtain the list of client windows with clientWindows() and find out which window is at a particular point with windowAt().

Many static functions are provided, for example, setKeyboardFilter(), setKeyboardHandler(), setDefaultKeyboard() and setDefaultMouse().

The size of the window rectangle can be set with setMaxWindowRect(), and the desktop's background can be set with setDesktopBackground().

The screen saver is controlled with setScreenSaverInterval() and screenSaverActivate().

See also Qt/Embedded.

Member Type Documentation

QWSServer::GUIMode

This determines what sort of QWS server to create:
  • QWSServer::NoGui - This is used for non-graphical Qt applications.
  • QWSServer::NormalGUI - A normal Qt/Embedded application (not the server).
  • QWSServer::Server - A Qt/Embedded server (e.g. if -qws has been specified on the command line.

QWSServer::ServerFlags

This enum is used to pass various options to the window system server. Currently defined are:
  • QWSServer::DisableKeyboard - Ignore all keyboard input.
  • QWSServer::DisableMouse - Ignore all mouse input.

QWSServer::WindowEvent

This specifies what sort of event has occurred to a top level window:
  • QWSServer::Create - A new window has been created (QWidget constructor).
  • QWSServer::Destroy - The window has been closed and deleted (QWidget destructor).
  • QWSServer::Hide - The window has been hidden with QWidget::hide().
  • QWSServer::Show - The window has been shown with QWidget::show() or similar.
  • QWSServer::Raise - The window has been raised to the top of the desktop.
  • QWSServer::Lower - The window has been lowered.
  • QWSServer::Geometry - The window has changed size or position.

Member Function Documentation

QWSServer::QWSServer ( int flags = 0, QObject * parent = 0, const char * name = 0 )

Construct a QWSServer class with parent parent, called name and flags flags.

Warning: This class is instantiated by QApplication for Qt/Embedded server processes. You should never construct this class yourself.

QWSServer::~QWSServer ()

Destruct QWSServer

const QPtrList<QWSWindow> & QWSServer::clientWindows ()

Returns the list of top-level windows. This list will change as applications add and remove wigdets so it should not be stored for future use. The windows are sorted in stacking order from top-most to bottom-most.

void QWSServer::closeKeyboard ()

Closes keyboard device(s).

void QWSServer::closeMouse ()

Closes the pointer device(s).

void QWSServer::enablePainting ( bool e )

If e is TRUE, painting on the display is enabled; if e is FALSE, painting is disabled.

const KeyMap * QWSServer::keyMap () [static]

Returns the keyboard mapping table used to convert keyboard scancodes to Qt keycodes and unicode values. It's used by the keyboard driver in qkeyboard_qws.cpp.

QWSKeyboardHandler * QWSServer::keyboardHandler () [static]

Returns the primary keyboard handler.

QWSPropertyManager * QWSServer::manager ()

Returns the QWSPropertyManager, which is used for implementing X11-style window properties.

QWSMouseHandler * QWSServer::mouseHandler () [static]

Returns the primary mouse handler.

void QWSServer::openKeyboard ()

Opens the keyboard device(s).

void QWSServer::openMouse ()

Opens the mouse device(s).

void QWSServer::refresh ()

Refreshes the entire display.

void QWSServer::refresh ( QRegion & r )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Refreshes the region r.

void QWSServer::screenSaverActivate ( bool activate ) [static]

If activate is TRUE the screensaver is activated immediately; if activate is FALSE the screensaver is deactivated.

bool QWSServer::screenSaverActive () [static]

Returns TRUE if the screensaver is active (i.e. the screen is blanked); otherwise returns FALSE.

void QWSServer::sendKeyEvent ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ) [static]

Send a key event. You can use this to send key events generated by "virtual keyboards". unicode is the unicode value of the key to send, keycode the Qt keycode (e.g. Key_Left), modifiers indicates whether, Shift/Alt/Ctrl keys are pressed, isPress is TRUE if this is a key down event and FALSE if it's a key up event, and autoRepeat is TRUE if this is an autorepeat event (i.e. the user has held the key down and this is the second or subsequent key event being sent).

void QWSServer::setDefaultKeyboard ( const char * k ) [static]

Set the keyboard driver to k, e.g. if $QWS_KEYBOARD is not defined. The default is platform-dependant.

void QWSServer::setDefaultMouse ( const char * m ) [static]

Set the mouse driver m to use if $QWS_MOUSE_PROTO is not defined. The default is platform-dependent.

void QWSServer::setDesktopBackground ( const QImage & img ) [static]

Sets the image img to be used as the background in the absence of obscuring windows.

void QWSServer::setDesktopBackground ( const QColor & c ) [static]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Sets the color c to be used as the background in the absence of obscuring windows.

void QWSServer::setKeyboardFilter ( KeyboardFilter * f ) [static]

Sets a filter f to be invoked for all key events from physical keyboard drivers (events sent via processKeyEvent()). The filter is not invoked for keys generated by virtual keyboard drivers (events sent via sendKeyEvent()).

void QWSServer::setKeyboardHandler ( QWSKeyboardHandler * kh ) [static]

Sets the primary keyboard handler to kh.

void QWSServer::setMaxWindowRect ( const QRect & r ) [static]

Sets the area of the screen which Qt/Embedded applications will consider to be the maximum area to use for windows to r.

See also QWidget::showMaximized().

void QWSServer::setScreenSaver ( QWSScreenSaver * ss ) [static]

Replaces the existing screensave with the screensaver specified in ss.

void QWSServer::setScreenSaverInterval ( int ms ) [static]

Sets the timeout for the screensaver to ms milliseconds. A setting of zero turns off the screensaver.

void QWSServer::setScreenSaverIntervals ( int * ms ) [static]

Sets an array of timeouts for the screensaver to a list of ms milliseconds. A setting of zero turns off the screensaver. The array must be 0-terminated.

QWSWindow * QWSServer::windowAt ( const QPoint & pos )

Returns the window containing the point pos or 0 if there is no window under the point.

void QWSServer::windowEvent ( QWSWindow * w, QWSServer::WindowEvent e ) [signal]

This signal is emitted whenever something happens to a top level window (e.g. it's created or destroyed). w is the window to which the event of type e has occurred.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QWSServer Member List

Complete Member List for QWSServer

This is the complete list of member functions for QWSServer, including inherited members.

  • QWSServer()
  • ~QWSServer()
  • clientWindows()
  • closeKeyboard()
  • closeMouse()
  • enablePainting()
  • keyMap()
  • keyboardHandler()
  • manager()
  • mouseHandler()
  • openKeyboard()
  • openMouse()
  • refresh()
  • screenSaverActivate()
  • screenSaverActive()
  • sendKeyEvent()
  • setDefaultKeyboard()
  • setDefaultMouse()
  • setDesktopBackground()
  • setKeyboardFilter()
  • setKeyboardHandler()
  • setMaxWindowRect()
  • setScreenSaver()
  • setScreenSaverInterval()
  • setScreenSaverIntervals()
  • windowAt()
  • windowEvent()


QWSWindow Class

QWSWindow Class Reference

The QWSWindow class provides server-specific functionality in Qt/Embedded. More...

#include <qwindowsystem_qws.h>

List of all member functions.

Public Members

  • QWSWindow ( int i, QWSClient * client )
  • ~QWSWindow ()
  • int winId () const
  • const QString & name () const
  • const QString & caption () const
  • QWSClient * client () const
  • QRegion requested () const
  • QRegion allocation () const
  • bool isVisible () const
  • bool isPartiallyObscured () const
  • bool isFullyObscured () const
  • void raise ()
  • void lower ()
  • void show ()
  • void hide ()
  • void setActiveWindow ()

Detailed Description

The QWSWindow class provides server-specific functionality in Qt/Embedded.

When you run a Qt/Embedded application, it either runs as a server or connects to an existing server. If it runs as a server, some additional functionality is provided by the QWSServer class.

This class maintains information about each window and allows operations to be performed on the windows.

You can get the window's name(), caption() and winId(), along with the client() that owns the window.

The region the window wants to draw on is returned by requested(); the region that the window is allowed to draw on is returned by allocation().

The visibility of the window can be determined using isVisible(), isPartiallyObscured() and isFullyObscured(). Visibility can be changed using raise(), lower(), show(), hide() and setActiveWindow().

See also Qt/Embedded.

Member Function Documentation

QWSWindow::QWSWindow ( int i, QWSClient * client )

Constructs a new top-level window, associated with the client client and giving it the id i.

QWSWindow::~QWSWindow ()

Destructor.

QRegion QWSWindow::allocation () const

Returns the region that the window is allowed to draw onto including any window decorations but excluding regions covered by other windows.

See also requested().

const QString & QWSWindow::caption () const

Returns this window's caption.

QWSClient * QWSWindow::client () const

Returns the QWSClient that owns this window.

void QWSWindow::hide ()

Hides the window.

bool QWSWindow::isFullyObscured () const

Returns TRUE is the window is completely obsured by another window or by the bounds of the screen; otherwise returns FALSE.

bool QWSWindow::isPartiallyObscured () const

Returns TRUE is the window is partially obsured by another window or by the bounds of the screen; otherwise returns FALSE.

bool QWSWindow::isVisible () const

Returns TRUE if the window is visible; otherwise returns FALSE.

void QWSWindow::lower ()

Lowers the window below other windows.

const QString & QWSWindow::name () const

Returns the name of this window.

void QWSWindow::raise ()

Raises the window above all other windows except "Stay on top" windows.

QRegion QWSWindow::requested () const

Returns the region that the window has requested to draw onto including any window decorations.

See also allocation().

void QWSWindow::setActiveWindow ()

Make this the active window (i.e. sets the keyboard focus to this window).

void QWSWindow::show ()

Shows the window.

int QWSWindow::winId () const

Returns the Id of this window.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QWSWindow Member List

Complete Member List for QWSWindow

This is the complete list of member functions for QWSWindow, including inherited members.

  • QWSWindow()
  • ~QWSWindow()
  • allocation()
  • caption()
  • client()
  • hide()
  • isFullyObscured()
  • isPartiallyObscured()
  • isVisible()
  • lower()
  • name()
  • raise()
  • requested()
  • setActiveWindow()
  • show()
  • winId()


qxml.h Include File

qxml.h

This is the verbatim text of the qxml.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id$
**
** Definition of QXmlSimpleReader and related classes.
**
** Created : 000518
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the xml module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition licenses may use this
** file in accordance with the Qt Commercial License Agreement provided
** with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QXML_H
#define QXML_H

#ifndef QT_H
#include "qtextstream.h"
#include "qfile.h"
#include "qstring.h"
#include "qstringlist.h"
#endif // QT_H

#if !defined(QT_MODULE_XML) || defined( QT_LICENSE_PROFESSIONAL ) || defined( QT_INTERNAL_XML )
#define QM_EXPORT_XML
#else
#define QM_EXPORT_XML Q_EXPORT
#endif

#ifndef QT_NO_XML

class QXmlNamespaceSupport;
class QXmlAttributes;
class QXmlContentHandler;
class QXmlDefaultHandler;
class QXmlDTDHandler;
class QXmlEntityResolver;
class QXmlErrorHandler;
class QXmlLexicalHandler;
class QXmlDeclHandler;
class QXmlInputSource;
class QXmlLocator;
class QXmlNamespaceSupport;
class QXmlParseException;

class QXmlReader;
class QXmlSimpleReader;

class QXmlSimpleReaderPrivate;
class QXmlNamespaceSupportPrivate;
class QXmlAttributesPrivate;
class QXmlInputSourcePrivate;
class QXmlParseExceptionPrivate;
class QXmlLocatorPrivate;
class QXmlDefaultHandlerPrivate;

//
// SAX Namespace Support
//

class QM_EXPORT_XML QXmlNamespaceSupport
{
public:
    QXmlNamespaceSupport();
    ~QXmlNamespaceSupport();

    void setPrefix( const QString&, const QString& );

    QString prefix( const QString& ) const;
    QString uri( const QString& ) const;
    void splitName( const QString&, QString&, QString& ) const;
    void processName( const QString&, bool, QString&, QString& ) const;
    QStringList prefixes() const;
    QStringList prefixes( const QString& ) const;

    void pushContext();
    void popContext();
    void reset();

private:
    QXmlNamespaceSupportPrivate *d;
};

//
// SAX Attributes
//

class QM_EXPORT_XML QXmlAttributes
{
public:
    QXmlAttributes() {}
    virtual ~QXmlAttributes() {}

    int index( const QString& qName ) const;
    int index( const QString& uri, const QString& localPart ) const;
    int length() const;
    int count() const;
    QString localName( int index ) const;
    QString qName( int index ) const;
    QString uri( int index ) const;
    QString type( int index ) const;
    QString type( const QString& qName ) const;
    QString type( const QString& uri, const QString& localName ) const;
    QString value( int index ) const;
    QString value( const QString& qName ) const;
    QString value( const QString& uri, const QString& localName ) const;

    void clear();
    void append( const QString &qName, const QString &uri, const QString &localPart, const QString &value );

private:
    QStringList qnameList;
    QStringList uriList;
    QStringList localnameList;
    QStringList valueList;

    QXmlAttributesPrivate *d;
};

//
// SAX Input Source
//

class QM_EXPORT_XML QXmlInputSource
{
public:
    QXmlInputSource();
    QXmlInputSource( QIODevice *dev );
    QXmlInputSource( QFile& file ); // obsolete
    QXmlInputSource( QTextStream& stream ); // obsolete
    virtual ~QXmlInputSource();

    virtual void setData( const QString& dat );
    virtual void setData( const QByteArray& dat );
    virtual void fetchData();
    virtual QString data();
    virtual QChar next();
    virtual void reset();

    static const QChar EndOfData;
    static const QChar EndOfDocument;

protected:
    virtual QString fromRawData( const QByteArray &data, bool beginning = FALSE );

private:
    void init();

    QIODevice *inputDevice;
    QTextStream *inputStream;

    QString str;
    const QChar *unicode;
    int pos;
    int length;
    bool nextReturnedEndOfData;
    QTextDecoder *encMapper;

    QXmlInputSourcePrivate *d;
};

//
// SAX Exception Classes
//

class QM_EXPORT_XML QXmlParseException
{
public:
    QXmlParseException( const QString& name="", int c=-1, int l=-1, const QString& p="", const QString& s="" )
    : msg( name ), column( c ), line( l ), pub( p ), sys( s )
    { }

    int columnNumber() const;
    int lineNumber() const;
    QString publicId() const;
    QString systemId() const;
    QString message() const;

private:
    QString msg;
    int column;
    int line;
    QString pub;
    QString sys;

    QXmlParseExceptionPrivate *d;
};

//
// XML Reader
//

class QM_EXPORT_XML QXmlReader
{
public:
    virtual bool feature( const QString& name, bool *ok = 0 ) const = 0;
    virtual void setFeature( const QString& name, bool value ) = 0;
    virtual bool hasFeature( const QString& name ) const = 0;
    virtual void* property( const QString& name, bool *ok = 0 ) const = 0;
    virtual void setProperty( const QString& name, void* value ) = 0;
    virtual bool hasProperty( const QString& name ) const = 0;
    virtual void setEntityResolver( QXmlEntityResolver* handler ) = 0;
    virtual QXmlEntityResolver* entityResolver() const = 0;
    virtual void setDTDHandler( QXmlDTDHandler* handler ) = 0;
    virtual QXmlDTDHandler* DTDHandler() const = 0;
    virtual void setContentHandler( QXmlContentHandler* handler ) = 0;
    virtual QXmlContentHandler* contentHandler() const = 0;
    virtual void setErrorHandler( QXmlErrorHandler* handler ) = 0;
    virtual QXmlErrorHandler* errorHandler() const = 0;
    virtual void setLexicalHandler( QXmlLexicalHandler* handler ) = 0;
    virtual QXmlLexicalHandler* lexicalHandler() const = 0;
    virtual void setDeclHandler( QXmlDeclHandler* handler ) = 0;
    virtual QXmlDeclHandler* declHandler() const = 0;
    virtual bool parse( const QXmlInputSource& input ) = 0;
    virtual bool parse( const QXmlInputSource* input ) = 0;
};

class QM_EXPORT_XML QXmlSimpleReader : public QXmlReader
{
public:
    QXmlSimpleReader();
    virtual ~QXmlSimpleReader();

    bool feature( const QString& name, bool *ok = 0 ) const;
    void setFeature( const QString& name, bool value );
    bool hasFeature( const QString& name ) const;

    void* property( const QString& name, bool *ok = 0 ) const;
    void setProperty( const QString& name, void* value );
    bool hasProperty( const QString& name ) const;

    void setEntityResolver( QXmlEntityResolver* handler );
    QXmlEntityResolver* entityResolver() const;
    void setDTDHandler( QXmlDTDHandler* handler );
    QXmlDTDHandler* DTDHandler() const;
    void setContentHandler( QXmlContentHandler* handler );
    QXmlContentHandler* contentHandler() const;
    void setErrorHandler( QXmlErrorHandler* handler );
    QXmlErrorHandler* errorHandler() const;
    void setLexicalHandler( QXmlLexicalHandler* handler );
    QXmlLexicalHandler* lexicalHandler() const;
    void setDeclHandler( QXmlDeclHandler* handler );
    QXmlDeclHandler* declHandler() const;

    bool parse( const QXmlInputSource& input );
    bool parse( const QXmlInputSource* input );
    virtual bool parse( const QXmlInputSource* input, bool incremental );
    virtual bool parseContinue();

private:
    // variables
    QXmlContentHandler *contentHnd;
    QXmlErrorHandler   *errorHnd;
    QXmlDTDHandler     *dtdHnd;
    QXmlEntityResolver *entityRes;
    QXmlLexicalHandler *lexicalHnd;
    QXmlDeclHandler    *declHnd;

    QXmlInputSource *inputSource;

    QChar c; // the character at reading position
    int   lineNr; // number of line
    int   columnNr; // position in line

    int     namePos;
    QChar   nameArray[256]; // only used for names
    QString nameValue; // only used for names
    int     refPos;
    QChar   refArray[256]; // only used for references
    QString refValue; // only used for references
    int     stringPos;
    QChar   stringArray[256]; // used for any other strings that are parsed
    QString stringValue; // used for any other strings that are parsed

    QXmlSimpleReaderPrivate* d;

    // inlines
    bool is_S( const QChar& );
    bool is_NameBeginning( const QChar& );
    bool is_NameChar( const QChar& );

    QString& string();
    void stringClear();
    void stringAddC();
    void stringAddC(const QChar&);
    QString& name();
    void nameClear();
    void nameAddC();
    void nameAddC(const QChar&);
    QString& ref();
    void refClear();
    void refAddC();
    void refAddC(const QChar&);

    // used by parseReference() and parsePEReference()
    enum EntityRecognitionContext { InContent, InAttributeValue, InEntityValue, InDTD };

    // private functions
    bool eat_ws();
    bool next_eat_ws();

    void next();
    bool atEnd();

    void init( const QXmlInputSource* i );
    void initData();

    bool entityExist( const QString& ) const;

    bool parseBeginOrContinue( int state, bool incremental );

    bool parseProlog();
    bool parseElement();
    bool processElementEmptyTag();
    bool processElementETagBegin2();
    bool processElementAttribute();
    bool parseMisc();
    bool parseContent();

    bool parsePI();
    bool parseDoctype();
    bool parseComment();

    bool parseName();
    bool parseNmtoken();
    bool parseAttribute();
    bool parseReference();
    bool processReference();

    bool parseExternalID();
    bool parsePEReference();
    bool parseMarkupdecl();
    bool parseAttlistDecl();
    bool parseAttType();
    bool parseAttValue();
    bool parseElementDecl();
    bool parseNotationDecl();
    bool parseChoiceSeq();
    bool parseEntityDecl();
    bool parseEntityValue();

    bool parseString();

    bool insertXmlRef( const QString&, const QString&, bool );

    bool reportEndEntities();
    void reportParseError( const QString& error );

    typedef bool (QXmlSimpleReader::*ParseFunction) ();
    void unexpectedEof( ParseFunction where, int state );
    void parseFailed( ParseFunction where, int state );
    void pushParseState( ParseFunction function, int state );

    friend class QXmlSimpleReaderPrivate;
    friend class QXmlSimpleReaderLocator;
};

//
// SAX Locator
//

class QM_EXPORT_XML QXmlLocator
{
public:
    QXmlLocator();
    virtual ~QXmlLocator();

    virtual int columnNumber() = 0;
    virtual int lineNumber() = 0;
//    QString getPublicId()
//    QString getSystemId()
};

//
// SAX handler classes
//

class QM_EXPORT_XML QXmlContentHandler
{
public:
    virtual void setDocumentLocator( QXmlLocator* locator ) = 0;
    virtual bool startDocument() = 0;
    virtual bool endDocument() = 0;
    virtual bool startPrefixMapping( const QString& prefix, const QString& uri ) = 0;
    virtual bool endPrefixMapping( const QString& prefix ) = 0;
    virtual bool startElement( const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts ) = 0;
    virtual bool endElement( const QString& namespaceURI, const QString& localName, const QString& qName ) = 0;
    virtual bool characters( const QString& ch ) = 0;
    virtual bool ignorableWhitespace( const QString& ch ) = 0;
    virtual bool processingInstruction( const QString& target, const QString& data ) = 0;
    virtual bool skippedEntity( const QString& name ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlErrorHandler
{
public:
    virtual bool warning( const QXmlParseException& exception ) = 0;
    virtual bool error( const QXmlParseException& exception ) = 0;
    virtual bool fatalError( const QXmlParseException& exception ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlDTDHandler
{
public:
    virtual bool notationDecl( const QString& name, const QString& publicId, const QString& systemId ) = 0;
    virtual bool unparsedEntityDecl( const QString& name, const QString& publicId, const QString& systemId, const QString& notationName ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlEntityResolver
{
public:
    virtual bool resolveEntity( const QString& publicId, const QString& systemId, QXmlInputSource*& ret ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlLexicalHandler
{
public:
    virtual bool startDTD( const QString& name, const QString& publicId, const QString& systemId ) = 0;
    virtual bool endDTD() = 0;
    virtual bool startEntity( const QString& name ) = 0;
    virtual bool endEntity( const QString& name ) = 0;
    virtual bool startCDATA() = 0;
    virtual bool endCDATA() = 0;
    virtual bool comment( const QString& ch ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlDeclHandler
{
public:
    virtual bool attributeDecl( const QString& eName, const QString& aName, const QString& type, const QString& valueDefault, const QString& value ) = 0;
    virtual bool internalEntityDecl( const QString& name, const QString& value ) = 0;
    virtual bool externalEntityDecl( const QString& name, const QString& publicId, const QString& systemId ) = 0;
    virtual QString errorString() = 0;
};

class QM_EXPORT_XML QXmlDefaultHandler : public QXmlContentHandler, public QXmlErrorHandler, public QXmlDTDHandler, public QXmlEntityResolver, public QXmlLexicalHandler, public QXmlDeclHandler
{
public:
    QXmlDefaultHandler() { }
    virtual ~QXmlDefaultHandler() { }

    void setDocumentLocator( QXmlLocator* locator );
    bool startDocument();
    bool endDocument();
    bool startPrefixMapping( const QString& prefix, const QString& uri );
    bool endPrefixMapping( const QString& prefix );
    bool startElement( const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts );
    bool endElement( const QString& namespaceURI, const QString& localName, const QString& qName );
    bool characters( const QString& ch );
    bool ignorableWhitespace( const QString& ch );
    bool processingInstruction( const QString& target, const QString& data );
    bool skippedEntity( const QString& name );

    bool warning( const QXmlParseException& exception );
    bool error( const QXmlParseException& exception );
    bool fatalError( const QXmlParseException& exception );

    bool notationDecl( const QString& name, const QString& publicId, const QString& systemId );
    bool unparsedEntityDecl( const QString& name, const QString& publicId, const QString& systemId, const QString& notationName );

    bool resolveEntity( const QString& publicId, const QString& systemId, QXmlInputSource*& ret );

    bool startDTD( const QString& name, const QString& publicId, const QString& systemId );
    bool endDTD();
    bool startEntity( const QString& name );
    bool endEntity( const QString& name );
    bool startCDATA();
    bool endCDATA();
    bool comment( const QString& ch );

    bool attributeDecl( const QString& eName, const QString& aName, const QString& type, const QString& valueDefault, const QString& value );
    bool internalEntityDecl( const QString& name, const QString& value );
    bool externalEntityDecl( const QString& name, const QString& publicId, const QString& systemId );

    QString errorString();

private:
    QXmlDefaultHandlerPrivate *d;
};

//
// inlines
//

inline bool QXmlSimpleReader::is_S(const QChar& ch)
{
    return ch==' ' || ch=='\t' || ch=='\n' || ch=='\r';
}
inline bool QXmlSimpleReader::is_NameBeginning( const QChar& ch )
{
    return ch=='_' || ch==':' ||
    ch.isLetter() || // ### Category Lm is not allowed
    ch.category()==QChar::Number_Letter;
}
inline bool QXmlSimpleReader::is_NameChar( const QChar& ch )
{
    return ch=='.' || ch=='-' || ch=='_' || ch==':' ||
    ch.isLetterOrNumber() || // ### Category No is not allowed
    ch.isMark();
}

inline bool QXmlSimpleReader::atEnd()
{ return (c.unicode()|0x0001) == 0xffff; }

inline void QXmlSimpleReader::stringClear()
{ stringValue = ""; stringPos = 0; }
inline void QXmlSimpleReader::nameClear()
{ nameValue = ""; namePos = 0; }
inline void QXmlSimpleReader::refClear()
{ refValue = ""; refPos = 0; }

inline int QXmlAttributes::count() const
{ return length(); }

#endif //QT_NO_XML

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QXmlAttributes Class

QXmlAttributes Class Reference
[XML module]

The QXmlAttributes class provides XML attributes. More...

#include <qxml.h>

List of all member functions.

Public Members

  • QXmlAttributes ()
  • virtual ~QXmlAttributes ()
  • int index ( const QString & qName ) const
  • int index ( const QString & uri, const QString & localPart ) const
  • int length () const
  • int count () const
  • QString localName ( int index ) const
  • QString qName ( int index ) const
  • QString uri ( int index ) const
  • QString type ( int index ) const
  • QString type ( const QString & qName ) const
  • QString type ( const QString & uri, const QString & localName ) const
  • QString value ( int index ) const
  • QString value ( const QString & qName ) const
  • QString value ( const QString & uri, const QString & localName ) const
  • void clear ()
  • void append ( const QString & qName, const QString & uri, const QString & localPart, const QString & value )

Detailed Description

The QXmlAttributes class provides XML attributes.

If attributes are reported by QXmlContentHandler::startElement() this class is used to pass the attribute values.

Use index() to locate the position of an attribute in the list, count() to retrieve the number of attributes, and clear() to remove the attributes. New attributes can be added with append(). Use type() to get an attribute's type and value() to get its value. The attribute's name is available from localName() or qName(), and its namespace URI from uri().

See also XML.

Member Function Documentation

QXmlAttributes::QXmlAttributes ()

Constructs an empty attribute list.

QXmlAttributes::~QXmlAttributes () [virtual]

Destroys the attributes object.

void QXmlAttributes::append ( const QString & qName, const QString & uri, const QString & localPart, const QString & value )

Appends a new attribute entry to the list of attributes. The qualified name of the attribute is qName, the namespae URI is uri and the local name is localPart. The value of the attribute is value.

See also qName(), uri(), localName() and value().

void QXmlAttributes::clear ()

Clears the list of attributes.

See also append().

int QXmlAttributes::count () const

Returns the number of attributes in the list. This function is equivalent to length().

int QXmlAttributes::index ( const QString & qName ) const

Looks up the index of an attribute by the qualified name qName.

Returns the index of the attribute or -1 if it wasn't found.

See also the namespace description.

int QXmlAttributes::index ( const QString & uri, const QString & localPart ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Looks up the index of an attribute by a namespace name.

uri specifies the namespace URI, or an empty string if the name has no namespace URI. localPart specifies the attribute's local name.

Returns the index of the attribute -1 if it wasn't found.

See also the namespace description.

int QXmlAttributes::length () const

Returns the number of attributes in the list.

Example: xml/tagreader-with-features/structureparser.cpp.

QString QXmlAttributes::localName ( int index ) const

Looks up an attribute's local name for the attribute at position index. If no namespace processing is done, the local name is a null string.

See also the namespace description.

QString QXmlAttributes::qName ( int index ) const

Looks up an attribute's XML 1.0 qualified name for the attribute at position index.

See also the namespace description.

Example: xml/tagreader-with-features/structureparser.cpp.

QString QXmlAttributes::type ( int index ) const

Looks up an attribute's type for the attribute at position index.

Currently only "CDATA" is returned.

QString QXmlAttributes::type ( const QString & qName ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Looks up an attribute's type for the qualified name qName.

Currently only "CDATA" is returned.

QString QXmlAttributes::type ( const QString & uri, const QString & localName ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Looks up an attribute's type by namespace name.

uri specifies the namespace URI and localName specifies the local name. If the name has no namespace URI, use an empty string for uri.

Currently only "CDATA" is returned.

QString QXmlAttributes::uri ( int index ) const

Looks up an attribute's namespace URI for the attribute at position index. If no namespace processing is done or if the attribute has no namespace, the namespace URI is a null string.

See also the namespace description.

Example: xml/tagreader-with-features/structureparser.cpp.

QString QXmlAttributes::value ( int index ) const

Looks up an attribute's value for the attribute at position index.

QString QXmlAttributes::value ( const QString & qName ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Looks up an attribute's value for the qualified name qName.

See also the namespace description.

QString QXmlAttributes::value ( const QString & uri, const QString & localName ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Looks up an attribute's value by namespace name.

uri specifies the namespace URI, or an empty string if the name has no namespace URI. localName specifies the attribute's local name.

See also the namespace description.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlAttributes Member List

Complete Member List for QXmlAttributes

This is the complete list of member functions for QXmlAttributes, including inherited members.

  • QXmlAttributes()
  • ~QXmlAttributes()
  • append()
  • clear()
  • count()
  • index()
  • length()
  • localName()
  • qName()
  • type()
  • uri()
  • value()


QXmlContentHandler Class

QXmlContentHandler Class Reference
[XML module]

The QXmlContentHandler class provides an interface to report the logical content of XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual void setDocumentLocator ( QXmlLocator * locator ) = 0
  • virtual bool startDocument () = 0
  • virtual bool endDocument () = 0
  • virtual bool startPrefixMapping ( const QString & prefix, const QString & uri ) = 0
  • virtual bool endPrefixMapping ( const QString & prefix ) = 0
  • virtual bool startElement ( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes & atts ) = 0
  • virtual bool endElement ( const QString & namespaceURI, const QString & localName, const QString & qName ) = 0
  • virtual bool characters ( const QString & ch ) = 0
  • virtual bool ignorableWhitespace ( const QString & ch ) = 0
  • virtual bool processingInstruction ( const QString & target, const QString & data ) = 0
  • virtual bool skippedEntity ( const QString & name ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlContentHandler class provides an interface to report the logical content of XML data.

If the application needs to be informed of basic parsing events, it implements this interface and sets it with QXmlReader::setContentHandler(). The reader reports basic document-related events like the start and end of elements and character data through this interface.

The order of events in this interface is very important, and mirrors the order of information in the document itself. For example, all of an element's content (character data, processing instructions, and/or sub-elements) appears, in order, between the startElement() event and the corresponding endElement() event.

The class QXmlDefaultHandler provides a default implementation for this interface; subclassing from the QXmlDefaultHandler class is very convenient if you only want to be informed of some parsing events.

The startDocument() function is called at the start of the document, and endDocument() is called at the end. Before parsing begins setDocumentLocator() is called. For each element startElement() is called, with endElement() being called at the end of each element. The characters() function is called with chunks of character data; ignorableWhitespace() is called with chunks of whitespace and processingInstruction() is called with processing instructions. If an entity is skipped skippedEntity() is called. At the beginning of prefix-URI scopes startPrefixMapping() is called.

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlDeclHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler and XML.

Member Function Documentation

bool QXmlContentHandler::characters ( const QString & ch ) [pure virtual]

The reader calls this function when it has parsed a chunk of character data (either normal character data or character data inside a CDATA section; if you have to distinguish between those two types you must use QXmlLexicalHandler::startCDATA() and QXmlLexicalHandler::endCDATA()). The character data is reported in ch.

Some readers report whitespace in element content using the ignorableWhitespace() function rather than using this one.

A reader may report the character data of an element in more than one chunk; e.g. a reader might want to report "a<b" in three characters() events ("a ", "<" and " b").

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlContentHandler::endDocument () [pure virtual]

The reader calls this function after it has finished parsing. It is called just once, and is the last handler function called. It is called after the reader has read all input or has abandoned parsing because of a fatal error.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also startDocument().

bool QXmlContentHandler::endElement ( const QString & namespaceURI, const QString & localName, const QString & qName ) [pure virtual]

The reader calls this function when it has parsed an end element tag with the qualified name qName, the local name localName and the namespace URI namespaceURI.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also the namespace description.

See also startElement().

Example: xml/tagreader/structureparser.cpp.

bool QXmlContentHandler::endPrefixMapping ( const QString & prefix ) [pure virtual]

The reader calls this function to signal the end of a prefix mapping for the prefix prefix.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also the namespace description.

See also startPrefixMapping().

QString QXmlContentHandler::errorString () [pure virtual]

The reader calls this function to get an error string, e.g. if any of the handler functions returns FALSE.

bool QXmlContentHandler::ignorableWhitespace ( const QString & ch ) [pure virtual]

Some readers may use this function to report each chunk of whitespace in element content. The whitespace reported in ch.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlContentHandler::processingInstruction ( const QString & target, const QString & data ) [pure virtual]

The reader calls this function when it has parsed a processing instruction.

target is the target name of the processing instruction and data is the data in the processing instruction.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

void QXmlContentHandler::setDocumentLocator ( QXmlLocator * locator ) [pure virtual]

The reader calls this function before it starts parsing the document. The argument locator is a pointer to a QXmlLocator which allows the application to get the parsing position within the document.

Do not destroy the locator; it is destroyed when the reader is destroyed (do not use the locator after the reader is destroyed).

bool QXmlContentHandler::skippedEntity ( const QString & name ) [pure virtual]

Some readers may skip entities if they have not seen the declarations (e.g. because they are in an external DTD). If they do so they report that they skipped the entity called name by calling this function.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlContentHandler::startDocument () [pure virtual]

The reader calls this function when it starts parsing the document. The reader calls this function just once, after the call to setDocumentLocator(), and before any other functions in this class or in the QXmlDTDHandler class are called.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also endDocument().

Example: xml/tagreader/structureparser.cpp.

bool QXmlContentHandler::startElement ( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes & atts ) [pure virtual]

The reader calls this function when it has parsed a start element tag.

There is a corresponding endElement() call when the corresponding end element tag is read. The startElement() and endElement() calls are always nested correctly. Empty element tags (e.g. <x/>) cause a startElement() call immediately followed by an endElement() call.

The attribute list provided contains only attributes with explicit values. The attribute list contains attributes used for namespace declaration (i.e. attributes starting with xmlns) only if the namespace-prefix property of the reader is TRUE.

The argument namespaceURI is the namespace URI, or a null string if the element has no namespace URI or if no namespace processing is done. localName is the local name (without prefix), or a null string if no namespace processing is done, qName is the qualified name (with prefix) and atts are the attributes attached to the element. If there are no attributes, atts is an empty attributes object.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also the namespace description.

See also endElement().

Example: xml/tagreader/structureparser.cpp.

bool QXmlContentHandler::startPrefixMapping ( const QString & prefix, const QString & uri ) [pure virtual]

The reader calls this function to signal the begin of a prefix-URI namespace mapping scope. This information is not necessary for normal namespace processing since the reader automatically replaces prefixes for element and attribute names.

Note that startPrefixMapping() and endPrefixMapping() calls are not guaranteed to be properly nested relative to each other: all startPrefixMapping() events occur before the corresponding startElement() event, and all endPrefixMapping() events occur after the corresponding endElement() event, but their order is not otherwise guaranteed.

The argument prefix is the namespace prefix being declared and the argument uri is the namespace URI the prefix is mapped to.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also the namespace description.

See also endPrefixMapping().

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlContentHandler Member List

Complete Member List for QXmlContentHandler

This is the complete list of member functions for QXmlContentHandler, including inherited members.

  • characters()
  • endDocument()
  • endElement()
  • endPrefixMapping()
  • errorString()
  • ignorableWhitespace()
  • processingInstruction()
  • setDocumentLocator()
  • skippedEntity()
  • startDocument()
  • startElement()
  • startPrefixMapping()


QXmlDeclHandler Class

QXmlDeclHandler Class Reference
[XML module]

The QXmlDeclHandler class provides an interface to report declaration content of XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual bool attributeDecl ( const QString & eName, const QString & aName, const QString & type, const QString & valueDefault, const QString & value ) = 0
  • virtual bool internalEntityDecl ( const QString & name, const QString & value ) = 0
  • virtual bool externalEntityDecl ( const QString & name, const QString & publicId, const QString & systemId ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlDeclHandler class provides an interface to report declaration content of XML data.

You can set the declaration handler with QXmlReader::setDeclHandler().

This interface based upon the SAX2 extension DeclHandler.

The interface provides attributeDecl(), internalEntityDecl() and externalEntityDecl() functions.

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler and XML.

Member Function Documentation

bool QXmlDeclHandler::attributeDecl ( const QString & eName, const QString & aName, const QString & type, const QString & valueDefault, const QString & value ) [pure virtual]

The reader calls this function to report an attribute type declaration. Only the effective (first) declaration for an attribute is reported.

The reader passes the name of the associated element in eName and the name of the attribute in aName. It passes a string that represents the attribute type in type and a string that represents the attribute default in valueDefault. This string is one of "#IMPLIED", "#REQUIRED", "#FIXED" or null (if none of the others applies). The reader passes the attribute's default value in value. If no default value is specified in the XML file, value is QString::null.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

QString QXmlDeclHandler::errorString () [pure virtual]

The reader calls this function to get an error string if any of the handler functions returns FALSE.

bool QXmlDeclHandler::externalEntityDecl ( const QString & name, const QString & publicId, const QString & systemId ) [pure virtual]

The reader calls this function to report a parsed external entity declaration. Only the effective (first) declaration for each entity is reported.

The reader passes the name of the entity in name, the public identifier in publicId and the system identifier in systemId. If there is no public identifier specified, it passes QString::null in publicId.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlDeclHandler::internalEntityDecl ( const QString & name, const QString & value ) [pure virtual]

The reader calls this function to report an internal entity declaration. Only the effective (first) declaration is reported.

The reader passes the name of the entity in name and the value of the entity in value.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlDeclHandler Member List

Complete Member List for QXmlDeclHandler

This is the complete list of member functions for QXmlDeclHandler, including inherited members.

  • attributeDecl()
  • errorString()
  • externalEntityDecl()
  • internalEntityDecl()


QXmlDefaultHandler Class

QXmlDefaultHandler Class Reference
[XML module]

The QXmlDefaultHandler class provides a default implementation of all XML handler classes. More...

#include <qxml.h>

Inherits QXmlContentHandler, QXmlErrorHandler, QXmlDTDHandler, QXmlEntityResolver, QXmlLexicalHandler and QXmlDeclHandler.

List of all member functions.

Public Members

  • QXmlDefaultHandler ()
  • virtual ~QXmlDefaultHandler ()

Detailed Description

The QXmlDefaultHandler class provides a default implementation of all XML handler classes.

Very often you are only interested in parts of the things that that the reader reports to you. This class implements a default behaviour for the handler classes (i.e. most of the time do nothing). Usually this is the class you subclass for implementing your customized handler.

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler and XML.

Member Function Documentation

QXmlDefaultHandler::QXmlDefaultHandler ()

Constructor.

QXmlDefaultHandler::~QXmlDefaultHandler () [virtual]

Destructor.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlDefaultHandler Member List

Complete Member List for QXmlDefaultHandler

This is the complete list of member functions for QXmlDefaultHandler, including inherited members.

  • QXmlDefaultHandler()
  • ~QXmlDefaultHandler()
  • attributeDecl()
  • characters()
  • comment()
  • endCDATA()
  • endDTD()
  • endDocument()
  • endElement()
  • endEntity()
  • endPrefixMapping()
  • error()
  • errorString()
  • externalEntityDecl()
  • fatalError()
  • ignorableWhitespace()
  • internalEntityDecl()
  • notationDecl()
  • processingInstruction()
  • resolveEntity()
  • setDocumentLocator()
  • skippedEntity()
  • startCDATA()
  • startDTD()
  • startDocument()
  • startElement()
  • startEntity()
  • startPrefixMapping()
  • unparsedEntityDecl()
  • warning()


QXmlDTDHandler Class

QXmlDTDHandler Class Reference
[XML module]

The QXmlDTDHandler class provides an interface to report DTD content of XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual bool notationDecl ( const QString & name, const QString & publicId, const QString & systemId ) = 0
  • virtual bool unparsedEntityDecl ( const QString & name, const QString & publicId, const QString & systemId, const QString & notationName ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlDTDHandler class provides an interface to report DTD content of XML data.

If an application needs information about notations and unparsed entities, it can implement this interface and register an instance with QXmlReader::setDTDHandler().

Note that this interface includes only those DTD events that the XML recommendation requires processors to report, i.e. notation and unparsed entity declarations using notationDecl() and unparsedEntityDecl() respectively.

See also the Introduction to SAX2.

See also QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler, QXmlLexicalHandler and XML.

Member Function Documentation

QString QXmlDTDHandler::errorString () [pure virtual]

The reader calls this function to get an error string if any of the handler functions returns FALSE.

bool QXmlDTDHandler::notationDecl ( const QString & name, const QString & publicId, const QString & systemId ) [pure virtual]

The reader calls this function when it has parsed a notation declaration.

The argument name is the notation name, publicId is the notations's public identifier and systemId is the notations's system identifier.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlDTDHandler::unparsedEntityDecl ( const QString & name, const QString & publicId, const QString & systemId, const QString & notationName ) [pure virtual]

The reader calls this function when it finds an unparsed entity declaration.

The argument name is the unparsed entity's name, publicId is the entity's public identifier, systemId is the entity's system identifier and notationName is the name of the associated notation.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlDTDHandler Member List

Complete Member List for QXmlDTDHandler

This is the complete list of member functions for QXmlDTDHandler, including inherited members.

  • errorString()
  • notationDecl()
  • unparsedEntityDecl()


QXmlEntityResolver Class

QXmlEntityResolver Class Reference
[XML module]

The QXmlEntityResolver class provides an interface to resolve external entities contained in XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual bool resolveEntity ( const QString & publicId, const QString & systemId, QXmlInputSource *& ret ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlEntityResolver class provides an interface to resolve external entities contained in XML data.

If an application needs to implement customized handling for external entities, it must implement this interface, i.e. resolveEntity(), and register it with QXmlReader::setEntityResolver().

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlErrorHandler, QXmlLexicalHandler and XML.

Member Function Documentation

QString QXmlEntityResolver::errorString () [pure virtual]

The reader calls this function to get an error string if any of the handler functions returns FALSE.

bool QXmlEntityResolver::resolveEntity ( const QString & publicId, const QString & systemId, QXmlInputSource *& ret ) [pure virtual]

The reader calls this function before it opens any external entity, except the top-level document entity. The application may request the reader to resolve the entity itself (ret is 0) or to use an entirely different input source (ret points to the input source).

The reader deletes the input source ret when it no longer needs it, so you should allocate it on the heap with new.

The argument publicId is the public identifier of the external entity, systemId is the system identifier of the external entity and ret is the return value of this function. If ret is 0 the reader should resolve the entity itself, if it is non-zero it must point to an input source which the reader uses instead.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlEntityResolver Member List

Complete Member List for QXmlEntityResolver

This is the complete list of member functions for QXmlEntityResolver, including inherited members.

  • errorString()
  • resolveEntity()


QXmlErrorHandler Class

QXmlErrorHandler Class Reference
[XML module]

The QXmlErrorHandler class provides an interface to report errors in XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual bool warning ( const QXmlParseException & exception ) = 0
  • virtual bool error ( const QXmlParseException & exception ) = 0
  • virtual bool fatalError ( const QXmlParseException & exception ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlErrorHandler class provides an interface to report errors in XML data.

If the application is interested in reporting errors to the user or any other customized error handling, you should subclass this class.

You can set the error handler with QXmlReader::setErrorHandler().

Errors can be reported using warning(), error() and fataError(), with the error text being reported with errorString().

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlLexicalHandler and XML.

Member Function Documentation

bool QXmlErrorHandler::error ( const QXmlParseException & exception ) [pure virtual]

A reader might use this function to report a recoverable error. A recoverable error corresponds to the definiton of "error" in section 1.2 of the XML 1.0 specification. Details of the error are stored in exception.

The reader must continue to provide normal parsing events after invoking this function.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

QString QXmlErrorHandler::errorString () [pure virtual]

The reader calls this function to get an error string if any of the handler functions returns FALSE.

bool QXmlErrorHandler::fatalError ( const QXmlParseException & exception ) [pure virtual]

A reader must use this function to report a non-recoverable error. Details of the error are stored in exception.

If this function returns TRUE the reader might try to go on parsing and reporting further errors; but no regular parsing events are reported.

bool QXmlErrorHandler::warning ( const QXmlParseException & exception ) [pure virtual]

A reader might use this function to report a warning. Warnings are conditions that are not errors or fatal errors as defined by the XML 1.0 specification. Details of the warning are stored in exception.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlErrorHandler Member List

Complete Member List for QXmlErrorHandler

This is the complete list of member functions for QXmlErrorHandler, including inherited members.

  • error()
  • errorString()
  • fatalError()
  • warning()


QXmlInputSource Class

QXmlInputSource Class Reference
[XML module]

The QXmlInputSource class provides the input data for the QXmlReader subclasses. More...

#include <qxml.h>

List of all member functions.

Public Members

  • QXmlInputSource ()
  • QXmlInputSource ( QIODevice * dev )
  • QXmlInputSource ( QFile & file ) (obsolete)
  • QXmlInputSource ( QTextStream & stream ) (obsolete)
  • virtual ~QXmlInputSource ()
  • virtual void setData ( const QString & dat )
  • virtual void setData ( const QByteArray & dat )
  • virtual void fetchData ()
  • virtual QString data ()
  • virtual QChar next ()
  • virtual void reset ()

Protected Members

  • virtual QString fromRawData ( const QByteArray & data, bool beginning = FALSE )

Detailed Description

The QXmlInputSource class provides the input data for the QXmlReader subclasses.

All subclasses of QXmlReader read the input XML document from this class.

This class recognizes the encoding of the data by reading the encoding declaration in the XML file and if it finds one, reading the data using the corresponding encoding. If it does not find an encoding declaration, then it assumes that the data is either in UTF-8 or UTF-16, depending on whether it can find a byte-order mark.

There are two ways to populate the input source with data: you can construct it with a QIODevice* so that the input source reads the data from that device. Or you can set the data explicitly with one of the setData() functions.

Usually you either construct a QXmlInputSource that works on a QIODevice* or you construct an empty QXmlInputSource and set the data with setData(). There are only rare occasions where you want to mix both methods.

The subclasses of QXmlReader use the next() function to read the input character by character. If you want to start from the beginning again, you have to call reset() to change the position in the input source to the beginning.

The functions data() and fetchData() are useful if you want to do something with the data other than parsing, e.g. displaying the raw XML file. The benefit of using the QXmlInputClass in such cases is that it tries to use the correct encoding.

See also QXmlReader, QXmlSimpleReader and XML.

Member Function Documentation

QXmlInputSource::QXmlInputSource ()

Constructs an input source which contains no data.

See also setData().

QXmlInputSource::QXmlInputSource ( QIODevice * dev )

Constructs an input source and gets the data from device dev. If dev is not open, it is opened in read-only mode. If dev is a null pointer or it is not possible to read from the device, the input source will contain no data.

See also setData(), fetchData() and QIODevice.

QXmlInputSource::QXmlInputSource ( QFile & file )

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Constructs an input source and gets the data from the file file. If the file cannot be read the input source is empty.

QXmlInputSource::QXmlInputSource ( QTextStream & stream )

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

Constructs an input source and gets the data from the text stream stream.

QXmlInputSource::~QXmlInputSource () [virtual]

Destructor.

QString QXmlInputSource::data () [virtual]

Returns the data the input source contains or QString::null if the input source does not contain any data.

See also setData(), QXmlInputSource() and fetchData().

void QXmlInputSource::fetchData () [virtual]

This function reads more data from the device that was set during construction. If the input source already contained data, this function deletes that data first.

This object contains no data after a call to this function if the object was constructed without a device to read data from or if this function was not able to get more data from the device.

There are two occasions where a fetch is done implicitly by another function call: during construction (so the object starts out with some initial data where available), and during a call to next() (if the data had run out).

You normally don't need to use this function if you use next().

See also data(), next() and QXmlInputSource().

QString QXmlInputSource::fromRawData ( const QByteArray & data, bool beginning = FALSE ) [virtual protected]

This function reads the XML file from data and tries to recoginize the encoding. It converts the raw data data into a QString and returns it. It tries its best to get the correct encoding for the XML file.

If beginning is TRUE, this function assumes that the data starts at the beginning of a new XML document and looks for an encoding declaration. If beginning is FALSE, it converts the raw data using the encoding determined from prior calls.

QChar QXmlInputSource::next () [virtual]

Returns the next character of the input source. If this funciton reaches the end of available data, it returns QXmlInputSource::EndOfData. If you call next() after that, it tries to fetch more data by calling fetchData(). If the fetchData() call results in new data, this function returns the first character of that data; otherwise it returns QXmlInputSource::EndOfDocument.

See also reset(), fetchData(), QXmlSimpleReader::parse() and QXmlSimpleReader::parseContinue().

void QXmlInputSource::reset () [virtual]

This function sets the position used by next() to the beginning of the data returned by data(). This is useful if you want to use the input source for more than one parse.

See also next().

Example: xml/tagreader-with-features/tagreader.cpp.

void QXmlInputSource::setData ( const QString & dat ) [virtual]

Sets the data of the input source to dat.

If the input source already contains data, this function deletes that data first.

See also data().

void QXmlInputSource::setData ( const QByteArray & dat ) [virtual]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

The data dat is passed through the correct text-codec, before it is set.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlInputSource Member List

Complete Member List for QXmlInputSource

This is the complete list of member functions for QXmlInputSource, including inherited members.

  • QXmlInputSource()
  • ~QXmlInputSource()
  • data()
  • fetchData()
  • fromRawData()
  • next()
  • reset()
  • setData()


QXmlLexicalHandler Class

QXmlLexicalHandler Class Reference
[XML module]

The QXmlLexicalHandler class provides an interface to report the lexical content of XML data. More...

#include <qxml.h>

Inherited by QXmlDefaultHandler.

List of all member functions.

Public Members

  • virtual bool startDTD ( const QString & name, const QString & publicId, const QString & systemId ) = 0
  • virtual bool endDTD () = 0
  • virtual bool startEntity ( const QString & name ) = 0
  • virtual bool endEntity ( const QString & name ) = 0
  • virtual bool startCDATA () = 0
  • virtual bool endCDATA () = 0
  • virtual bool comment ( const QString & ch ) = 0
  • virtual QString errorString () = 0

Detailed Description

The QXmlLexicalHandler class provides an interface to report the lexical content of XML data.

The events in the lexical handler apply to the entire document, not just to the document element, and all lexical handler events appear between the content handler's startDocument and endDocument events.

You can set the lexical handler with QXmlReader::setLexicalHandler().

This interface's design is based on the the SAX2 extension LexicalHandler.

The interface provides startDTD(), endDTD(), startEntity(), endEntity(), startCDATA(), endCDATA() and comment() functions.

See also the Introduction to SAX2.

See also QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler and XML.

Member Function Documentation

bool QXmlLexicalHandler::comment ( const QString & ch ) [pure virtual]

The reader calls this function to report an XML comment anywhere in the document. It reports the text of the comment in ch.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

bool QXmlLexicalHandler::endCDATA () [pure virtual]

The reader calls this function to report the end of a CDATA section.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also startCDATA().

bool QXmlLexicalHandler::endDTD () [pure virtual]

The reader calls this function to report the end of a DTD declaration, if any.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also startDTD().

bool QXmlLexicalHandler::endEntity ( const QString & name ) [pure virtual]

The reader calls this function to report the end of an entity with the name name.

For every call of startEntity(), there is a corresponding call of endEntity(). The calls of startEntity() and endEntity() are properly nested.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also startEntity() and QXmlSimpleReader::setFeature().

QString QXmlLexicalHandler::errorString () [pure virtual]

The reader calls this function to get an error string if any of the handler functions returns FALSE.

bool QXmlLexicalHandler::startCDATA () [pure virtual]

The reader calls this function to report the start of a CDATA section. The content of the CDATA section is reported through the QXmlContentHandler::characters() function. This function is intended only to report the boundary.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also endCDATA().

bool QXmlLexicalHandler::startDTD ( const QString & name, const QString & publicId, const QString & systemId ) [pure virtual]

The reader calls this function to report the start of a DTD declaration, if any. It reports the name of the document type in name, the public identifier in publicId and the system identifier in systemId.

If the public identifier and the system identifier is missing, the reader sets the publicId and systemId to QString::null.

All declarations reported through QXmlDTDHandler or QXmlDeclHandler appear between the startDTD() and endDTD() calls.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also endDTD().

bool QXmlLexicalHandler::startEntity ( const QString & name ) [pure virtual]

The reader calls this function to report the start of an entity with the name name.

Note that if the entity is unknown, the reader reports it through QXmlContentHandler::skippedEntity() and not throught this function.

If this function returns FALSE the reader stops parsing and reports an error. The reader uses the function errorString() to get the error message.

See also endEntity() and QXmlSimpleReader::setFeature().

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlLexicalHandler Member List

Complete Member List for QXmlLexicalHandler

This is the complete list of member functions for QXmlLexicalHandler, including inherited members.

  • comment()
  • endCDATA()
  • endDTD()
  • endEntity()
  • errorString()
  • startCDATA()
  • startDTD()
  • startEntity()


QXmlLocator Class

QXmlLocator Class Reference
[XML module]

The QXmlLocator class provides the XML handler classes with information about the parsing position within a file. More...

#include <qxml.h>

List of all member functions.

Public Members

  • QXmlLocator ()
  • virtual ~QXmlLocator ()
  • virtual int columnNumber () = 0
  • virtual int lineNumber () = 0

Detailed Description

The QXmlLocator class provides the XML handler classes with information about the parsing position within a file.

The reader reports a QXmlLocator to the content handler before it starts to parse the document. This is done with the QXmlContentHandler::setDocumentLocator() function. The handler classes can now use this locator to get the position (lineNumber() and columnNumber()) that the reader has reached.

See also XML.

Member Function Documentation

QXmlLocator::QXmlLocator ()

Constructor.

QXmlLocator::~QXmlLocator () [virtual]

Destructor.

int QXmlLocator::columnNumber () [pure virtual]

Returns the column number (starting at 1) or -1 if there is no column number available.

int QXmlLocator::lineNumber () [pure virtual]

Returns the line number (starting at 1) or -1 if there is no line number available.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlLocator Member List

Complete Member List for QXmlLocator

This is the complete list of member functions for QXmlLocator, including inherited members.

  • QXmlLocator()
  • ~QXmlLocator()
  • columnNumber()
  • lineNumber()


QXmlNamespaceSupport Class

QXmlNamespaceSupport Class Reference
[XML module]

The QXmlNamespaceSupport class is a helper class for XML readers which want to include namespace support. More...

#include <qxml.h>

List of all member functions.

Public Members

  • QXmlNamespaceSupport ()
  • ~QXmlNamespaceSupport ()
  • void setPrefix ( const QString & pre, const QString & uri )
  • QString prefix ( const QString & uri ) const
  • QString uri ( const QString & prefix ) const
  • void splitName ( const QString & qname, QString & prefix, QString & localname ) const
  • void processName ( const QString & qname, bool isAttribute, QString & nsuri, QString & localname ) const
  • QStringList prefixes () const
  • QStringList prefixes ( const QString & uri ) const
  • void pushContext ()
  • void popContext ()
  • void reset ()

Detailed Description

The QXmlNamespaceSupport class is a helper class for XML readers which want to include namespace support.

You can set the prefix for the current namespace with setPrefix(), and get the list of current prefixes (or those for a given URI) with prefixes(). The namespace URI is available from uri(). Use pushContext() to start a new namespace context, and popContext() to return to the previous namespace context. Use splitName() or processName() to split a name into its prefix and local name.

See also the namespace description.

See also XML.

Member Function Documentation

QXmlNamespaceSupport::QXmlNamespaceSupport ()

Constructs a QXmlNamespaceSupport.

QXmlNamespaceSupport::~QXmlNamespaceSupport ()

Destroys a QXmlNamespaceSupport.

void QXmlNamespaceSupport::popContext ()

Reverts to the previous namespace context.

Normally, you should pop the context at the end of each XML element. After popping the context, all namespace prefix mappings that were previously in force are restored.

See also pushContext().

QString QXmlNamespaceSupport::prefix ( const QString & uri ) const

Returns one of the prefixes mapped to the namespace URI uri.

If more than one prefix is currently mapped to the same URI, this function makes an arbitrary selection; if you want all of the prefixes, use prefixes() instead.

Note: to check for a default prefix, use the uri() function with an argument of "".

QStringList QXmlNamespaceSupport::prefixes () const

Returns a list of all prefixes currently declared.

If there is a default prefix, this function does not return it in the list; check for the default prefix using uri() with an argument of "".

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myXmlNamespaceSupport.prefixes();
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

QStringList QXmlNamespaceSupport::prefixes ( const QString & uri ) const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a list of all prefixes currently declared for the namespace URI uri.

The "xml:" prefix is included. If you only want one prefix that is mapped to the namespace URI, and you don't care which one you get, use the prefix() function instead.

Note: the empty (default) prefix is never included in this list; to check for the presence of a default namespace, use uri() with an argument of "".

Note that if you want to iterate over the list, you should iterate over a copy, e.g.

    QStringList list = myXmlNamespaceSupport.prefixes( "" );
    QStringList::Iterator it = list.begin();
    while( it != list.end() ) {
        myProcessing( *it );
        ++it;
    }

void QXmlNamespaceSupport::processName ( const QString & qname, bool isAttribute, QString & nsuri, QString & localname ) const

Processes a raw XML 1.0 name in the current context by removing the prefix and looking it up among the prefixes currently declared.

qname is the raw XML 1.0 name to be processed. isAttribute is TRUE if the name is an attribute name.

This function stores the namespace URI in nsuri (which will get a null string if the raw name has an undeclared prefix), and stores the local name (without prefix) in localname (which will get a null string if no namespace is in use).

Note that attribute names are processed differently than element names: an unprefixed element name gets the default namespace (if any), while an unprefixed element name does not.

void QXmlNamespaceSupport::pushContext ()

Starts a new namespace context.

Normally, you should push a new context at the beginning of each XML element: the new context automatically inherits the declarations of its parent context, and it also keeps track of which declarations were made within this context.

See also popContext().

void QXmlNamespaceSupport::reset ()

Resets this namespace support object for reuse.

void QXmlNamespaceSupport::setPrefix ( const QString & pre, const QString & uri )

This function declares a prefix pre in the current namespace context to be the namespace URI uri. The prefix remains in force until this context is popped, unless it is shadowed in a descendant context.

Note that there is an asymmetry in this library. prefix() does not return the default "" prefix, even if you have declared one; to check for a default prefix, you must look it up explicitly using uri(). This asymmetry exists to make it easier to look up prefixes for attribute names, where the default prefix is not allowed.

void QXmlNamespaceSupport::splitName ( const QString & qname, QString & prefix, QString & localname ) const

Splits the name qname at the ':' and returns the prefix in prefix and the local name in localname.

See also processName().

QString QXmlNamespaceSupport::uri ( const QString & prefix ) const

Looks up the prefix prefix in the current context and returns the currently-mapped namespace URI. Use the empty string ("") for the default namespace.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlNamespaceSupport Member List

Complete Member List for QXmlNamespaceSupport

This is the complete list of member functions for QXmlNamespaceSupport, including inherited members.

  • QXmlNamespaceSupport()
  • ~QXmlNamespaceSupport()
  • popContext()
  • prefix()
  • prefixes()
  • processName()
  • pushContext()
  • reset()
  • setPrefix()
  • splitName()
  • uri()


QXmlParseException Class

QXmlParseException Class Reference
[XML module]

The QXmlParseException class is used to report errors with the QXmlErrorHandler interface. More...

#include <qxml.h>

List of all member functions.

Public Members

  • QXmlParseException ( const QString & name = "", int c = -1, int l = -1, const QString & p = "", const QString & s = "" )
  • int columnNumber () const
  • int lineNumber () const
  • QString publicId () const
  • QString systemId () const
  • QString message () const

Detailed Description

The QXmlParseException class is used to report errors with the QXmlErrorHandler interface.

The XML subsystem constructs an instance of this class when it detects an error. You can retrieve the place where the error occurred using systemId(), publicId(), lineNumber() and columnNumber(), along with the error message().

See also QXmlErrorHandler, QXmlReader and XML.

Member Function Documentation

QXmlParseException::QXmlParseException ( const QString & name = "", int c = -1, int l = -1, const QString & p = "", const QString & s = "" )

Constructs a parse exception with the error string name in the column c and line l for the public identifier p and the system identifier s.

int QXmlParseException::columnNumber () const

Returns the column number where the error occurred.

int QXmlParseException::lineNumber () const

Returns the line number where the error occurred.

QString QXmlParseException::message () const

Returns the error message.

QString QXmlParseException::publicId () const

Returns the public identifier where the error occurred.

QString QXmlParseException::systemId () const

Returns the system identifier where the error occurred.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlParseException Member List

Complete Member List for QXmlParseException

This is the complete list of member functions for QXmlParseException, including inherited members.

  • QXmlParseException()
  • columnNumber()
  • lineNumber()
  • message()
  • publicId()
  • systemId()


QXmlReader Class

QXmlReader Class Reference
[XML module]

The QXmlReader class provides an interface for XML readers (i.e. parsers). More...

#include <qxml.h>

Inherited by QXmlSimpleReader.

List of all member functions.

Public Members

  • virtual bool feature ( const QString & name, bool * ok = 0 ) const = 0
  • virtual void setFeature ( const QString & name, bool value ) = 0
  • virtual bool hasFeature ( const QString & name ) const = 0
  • virtual void * property ( const QString & name, bool * ok = 0 ) const = 0
  • virtual void setProperty ( const QString & name, void * value ) = 0
  • virtual bool hasProperty ( const QString & name ) const = 0
  • virtual void setEntityResolver ( QXmlEntityResolver * handler ) = 0
  • virtual QXmlEntityResolver * entityResolver () const = 0
  • virtual void setDTDHandler ( QXmlDTDHandler * handler ) = 0
  • virtual QXmlDTDHandler * DTDHandler () const = 0
  • virtual void setContentHandler ( QXmlContentHandler * handler ) = 0
  • virtual QXmlContentHandler * contentHandler () const = 0
  • virtual void setErrorHandler ( QXmlErrorHandler * handler ) = 0
  • virtual QXmlErrorHandler * errorHandler () const = 0
  • virtual void setLexicalHandler ( QXmlLexicalHandler * handler ) = 0
  • virtual QXmlLexicalHandler * lexicalHandler () const = 0
  • virtual void setDeclHandler ( QXmlDeclHandler * handler ) = 0
  • virtual QXmlDeclHandler * declHandler () const = 0
  • virtual bool parse ( const QXmlInputSource & input ) = 0 (obsolete)
  • virtual bool parse ( const QXmlInputSource * input ) = 0

Detailed Description

The QXmlReader class provides an interface for XML readers (i.e. parsers).

This abstract class provides an interface for all XML readers in Qt. At the moment there is only one implementation of a reader included in the XML module of Qt (QXmlSimpleReader). In future releases there might be more readers with different properties available (e.g. a validating parser).

The design of the XML classes follows the SAX2 java interface. It was adapted to fit the Qt naming conventions; so it should be very easy for anybody who has worked with SAX2 to get started with the Qt XML classes.

All readers use the class QXmlInputSource to read the input document. Since you are normally interested in particular content in the XML document, the reader reports the content through special handler classes (QXmlDTDHandler, QXmlDeclHandler, QXmlContentHandler, QXmlEntityResolver, QXmlErrorHandler and QXmlLexicalHandler), which you must subclass, if you want to process the contents..

Since the handler classes describe only interfaces you must implement all functions; there is a class (QXmlDefaultHandler) to make this easier; it implements a default behaviour (do nothing) for all functions.

Features and properties of the reader can be set with setFeature() and setProperty respectively. You can set the reader to use your own subclasses with setEntityResolver(), setDTDHandler(), setContentHandler(), setErrorHandler(), setLexicalHandler() and setDeclHandler(). The parse itself is started with a call to parse().

For getting started see also the tiny SAX2 parser walkthrough.

See also QXmlSimpleReader and XML.

Member Function Documentation

QXmlDTDHandler * QXmlReader::DTDHandler () const [pure virtual]

Returns the DTD handler or 0 if none was set.

See also setDTDHandler().

QXmlContentHandler * QXmlReader::contentHandler () const [pure virtual]

Returns the content handler or 0 if none was set.

See also setContentHandler().

QXmlDeclHandler * QXmlReader::declHandler () const [pure virtual]

Returns the declaration handler or 0 if none was set.

See also setDeclHandler().

QXmlEntityResolver * QXmlReader::entityResolver () const [pure virtual]

Returns the entity resolver or 0 if none was set.

See also setEntityResolver().

QXmlErrorHandler * QXmlReader::errorHandler () const [pure virtual]

Returns the error handler or 0 if none was set.

See also setErrorHandler().

bool QXmlReader::feature ( const QString & name, bool * ok = 0 ) const [pure virtual]

If the reader has the feature called name, the feature's value is returned. If no such feature exists the return value is undefined.

If ok is not 0, then *ok is set to TRUE if the reader has the feature called name; otherwise *ok is set to FALSE.

See also setFeature() and hasFeature().

bool QXmlReader::hasFeature ( const QString & name ) const [pure virtual]

Returns TRUE if the reader has the feature name; otherwise returns FALSE.

See also feature() and setFeature().

bool QXmlReader::hasProperty ( const QString & name ) const [pure virtual]

Returns TRUE if the reader has the property name; otherwise returns FALSE.

See also property() and setProperty().

QXmlLexicalHandler * QXmlReader::lexicalHandler () const [pure virtual]

Returns the lexical handler or 0 if none was set.

See also setLexicalHandler().

bool QXmlReader::parse ( const QXmlInputSource * input ) [pure virtual]

Reads an XML document from input and parses it. Returns TRUE if the parsing was successful; otherwise returns FALSE.

Example: xml/tagreader/tagreader.cpp.

bool QXmlReader::parse ( const QXmlInputSource & input ) [pure virtual]

This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code.

void * QXmlReader::property ( const QString & name, bool * ok = 0 ) const [pure virtual]

If the reader has the property name, this function returns the value of the property and sets *ok to TRUE; otherwise *ok is set to FALSE.

See also setProperty() and hasProperty().

void QXmlReader::setContentHandler ( QXmlContentHandler * handler ) [pure virtual]

Sets the content handler to handler.

See also contentHandler().

Example: xml/tagreader/tagreader.cpp.

void QXmlReader::setDTDHandler ( QXmlDTDHandler * handler ) [pure virtual]

Sets the DTD handler to handler.

See also DTDHandler().

void QXmlReader::setDeclHandler ( QXmlDeclHandler * handler ) [pure virtual]

Sets the declaration handler to handler.

See also declHandler().

void QXmlReader::setEntityResolver ( QXmlEntityResolver * handler ) [pure virtual]

Sets the entity resolver to handler.

See also entityResolver().

void QXmlReader::setErrorHandler ( QXmlErrorHandler * handler ) [pure virtual]

Sets the error handler to handler. Clears the error handler if handler is 0.

See also errorHandler().

void QXmlReader::setFeature ( const QString & name, bool value ) [pure virtual]

Sets the feature called name to the given value. If the reader doesn't have the feature nothing happens.

See also feature() and hasFeature().

void QXmlReader::setLexicalHandler ( QXmlLexicalHandler * handler ) [pure virtual]

Sets the lexical handler to handler.

See also lexicalHandler().

void QXmlReader::setProperty ( const QString & name, void * value ) [pure virtual]

Sets the property name to value. If the reader doesn't have the property nothing happens.

See also property() and hasProperty().

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlReader Member List

Complete Member List for QXmlReader

This is the complete list of member functions for QXmlReader, including inherited members.

  • DTDHandler()
  • contentHandler()
  • declHandler()
  • entityResolver()
  • errorHandler()
  • feature()
  • hasFeature()
  • hasProperty()
  • lexicalHandler()
  • parse()
  • property()
  • setContentHandler()
  • setDTDHandler()
  • setDeclHandler()
  • setEntityResolver()
  • setErrorHandler()
  • setFeature()
  • setLexicalHandler()
  • setProperty()


QXmlSimpleReader Class

QXmlSimpleReader Class Reference
[XML module]

The QXmlSimpleReader class provides an implementation of a simple XML reader (parser). More...

#include <qxml.h>

Inherits QXmlReader.

List of all member functions.

Public Members

  • QXmlSimpleReader ()
  • virtual ~QXmlSimpleReader ()
  • virtual bool parse ( const QXmlInputSource * input, bool incremental )
  • virtual bool parseContinue ()

Detailed Description

The QXmlSimpleReader class provides an implementation of a simple XML reader (parser).

This XML reader is sufficient for simple parsing tasks. The reader:

  • provides a well-formed parser;
  • does not parse any external entities;
  • can do namespace processing.

Documents are parsed with a call to parse().

See the tiny SAX2 parser walkthrough.

See also XML.

Member Function Documentation

QXmlSimpleReader::QXmlSimpleReader ()

Constructs a simple XML reader with the following feature settings:
  • http://xml.org/sax/features/namespaces TRUE
  • http://xml.org/sax/features/namespace-prefixes FALSE
  • http://trolltech.com/xml/features/report-whitespace-only-CharData TRUE
  • http://trolltech.com/xml/features/report-start-end-entity FALSE

More information about features can be found in the Qt SAX2 overview.

See also setFeature().

QXmlSimpleReader::~QXmlSimpleReader () [virtual]

Destroys the simple XML reader.

bool QXmlSimpleReader::parse ( const QXmlInputSource * input, bool incremental ) [virtual]

Reads an XML document from input and parses it. Returns FALSE if the parsing detects an error; otherwise returns TRUE.

If incremental is TRUE, the parser does not return FALSE when it reaches the end of the input without reaching the end of the XML file. Instead it stores the state of the parser so that parsing can be continued at a later stage when more data is available. You can use the function parseContinue() to continue with parsing. This class stores a pointer to the input source input and the parseContinue() tries to read from that input souce. This means you should not delete the input source input until you've finished your calls to parseContinue(). If you call this function with incremental TRUE whilst an incremental parse is in progress a new parsing session will be started and the previous session lost.

If incremental is FALSE, this function behaves like the normal parse function, i.e. it returns FALSE when the end of input is reached without reaching the end of the XML file and the parsing can't be continued.

See also parseContinue() and QSocket.

Examples: xml/tagreader-with-features/tagreader.cpp and xml/tagreader/tagreader.cpp.

bool QXmlSimpleReader::parseContinue () [virtual]

Continues incremental parsing; this function reads the input from the QXmlInputSource that was specified with the last parse() command. To use this function, you must have called parse() with the incremental argument set to TRUE.

Returns FALSE if a parsing error occurs; otherwise returns TRUE.

If the input source returns an empty string for the function QXmlInputSource::data(), then this means that the end of the XML file is reached; this is quite important, especially if you want to use the reader to parse more than one XML file.

The case that the end of the XML file is reached without having finished the parsing is not considered as an error -- you can continue parsing at a later stage by calling this function again when there is more data available to parse.

This function assumes that the end of the XML document is reached if the QXmlInputSource::next() function returns QXmlInputSource::EndOfDocument. If the parser has not finished parsing when it encounters this symbol, it is an error and FALSE is returned.

See also parse() and QXmlInputSource::next().

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXmlSimpleReader Member List

Complete Member List for QXmlSimpleReader

This is the complete list of member functions for QXmlSimpleReader, including inherited members.

  • QXmlSimpleReader()
  • ~QXmlSimpleReader()
  • DTDHandler()
  • contentHandler()
  • declHandler()
  • entityResolver()
  • errorHandler()
  • feature()
  • hasFeature()
  • hasProperty()
  • lexicalHandler()
  • parse()
  • parseContinue()
  • property()
  • setContentHandler()
  • setDTDHandler()
  • setDeclHandler()
  • setEntityResolver()
  • setErrorHandler()
  • setFeature()
  • setLexicalHandler()
  • setProperty()


qxt.h Include File

qxt.h

This is the verbatim text of the qxt.h include file. It is provided only for illustration; the copyright remains with Trolltech.

/****************************************************************************
** $Id:  qt/qxt.h   3.0.5   edited Oct 12 2001 $
**
** Definition of Qt extension classes for Xt/Motif support.
**
** Created : 980107
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
**   information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#ifndef QXT_H
#define QXT_H

#include <qapplication.h>
#include <qwidget.h>

#include <X11/Intrinsic.h>

#ifdef Bool
#undef Bool
#endif // Bool

class QXtApplication : public QApplication {
    Q_OBJECT
    void init();

public:
    QXtApplication(int& argc, char** argv,
    const char* appclass=0,
    XrmOptionDescRec *options=0, int num_options=0,
    const char** resources=0);
    QXtApplication(Display *, HANDLE = 0, HANDLE = 0);
    QXtApplication(Display *, int, char **, HANDLE = 0, HANDLE = 0);
    ~QXtApplication();
};

class QXtWidget : public QWidget {
    Q_OBJECT
    Widget xtw;
    Widget xtparent;
    bool   need_reroot;
    void init(const char* name, WidgetClass widget_class,
            Widget parent, QWidget* qparent,
            ArgList args, Cardinal num_args,
            bool managed);
    friend void qwidget_realize( Widget widget, XtValueMask* mask,
                 XSetWindowAttributes* attributes );

public:
    QXtWidget(const char* name, Widget parent, bool managed=FALSE);
    QXtWidget(const char* name, WidgetClass widget_class,
          QWidget *parent=0, ArgList args=0, Cardinal num_args=0,
          bool managed=FALSE);
    ~QXtWidget();

    Widget xtWidget() const { return xtw; }
    bool isActiveWindow() const;
    void setActiveWindow();

protected:
    void moveEvent( QMoveEvent* );
    void resizeEvent( QResizeEvent* );
    bool x11Event( XEvent * );
};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


QXtApplication Class

QXtApplication Class Reference

The QXtApplication class facilitates the mixing of Xt/Motif and Qt widgets.

This class is part of the Qt Xt/Motif Extension. More...

#include <qxt.h>

Inherits QApplication.

List of all member functions.

Public Members

  • QXtApplication ( int & argc, char ** argv, const char * appclass = 0, XrmOptionDescRec * options = 0, int num_options = 0, const char ** resources = 0 )
  • QXtApplication ( Display * display, HANDLE visual = 0, HANDLE colormap = 0 )
  • QXtApplication ( Display * display, int argc, char ** argv, HANDLE visual = 0, HANDLE colormap = 0 )
  • ~QXtApplication ()

Detailed Description

This class is defined in the Qt Xt/Motif Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QXtApplication class facilitates the mixing of Xt/Motif and Qt widgets.

The QXtApplication and QXtWidget classes allow old Xt or Motif widgets to be used in new Qt applications. They also allow Qt widgets to be used in primarily Xt/Motif applications. The facility is intended to aid migration from Xt/Motif to the more comfortable Qt system.

Member Function Documentation

QXtApplication::QXtApplication ( int & argc, char ** argv, const char * appclass = 0, XrmOptionDescRec * options = 0, int num_options = 0, const char ** resources = 0 )

Constructs a QApplication and initializes the Xt toolkit. The appclass, options, num_options, and resources arguments are passed on to XtAppSetFallbackResources and XtDisplayInitialize.

Use this constructor when writing a new Qt application which needs to use some existing Xt/Motif widgets.

The argc and argv arguments are passed to the QApplication constructor.

QXtApplication::QXtApplication ( Display * display, HANDLE visual = 0, HANDLE colormap = 0 )

Constructs a QApplication from the display of an already-initialized Xt application. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts.

Use this constructor when introducing Qt widgets into an existing Xt/Motif application.

QXtApplication::QXtApplication ( Display * display, int argc, char ** argv, HANDLE visual = 0, HANDLE colormap = 0 )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Constructs a QApplication from the display of an already-initialized Xt application. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts.

Use this constructor when introducing Qt widgets into an existing Xt/Motif application.

The argc and argv arguments are passed to the QApplication constructor.

QXtApplication::~QXtApplication ()

Destructs the application. Does not close the Xt toolkit.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXtApplication Member List

Complete Member List for QXtApplication

This is the complete list of member functions for QXtApplication, including inherited members.

  • QXtApplication()
  • ~QXtApplication()
  • aboutToQuit()
  • activeModalWidget()
  • activePopupWidget()
  • activeWindow()
  • addLibraryPath()
  • allWidgets()
  • argc()
  • argv()
  • beep()
  • blockSignals()
  • checkConnectArgs()
  • child()
  • childEvent()
  • children()
  • className()
  • clipboard()
  • closeAllWindows()
  • closingDown()
  • colorSpec()
  • commitData()
  • connect()
  • connectNotify()
  • cursorFlashTime()
  • customEvent()
  • defaultCodec()
  • deleteLater()
  • desktop()
  • desktopSettingsAware()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • doubleClickInterval()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enter_loop()
  • event()
  • eventFilter()
  • exec()
  • exit()
  • exit_loop()
  • flush()
  • flushX()
  • focusWidget()
  • font()
  • fontMetrics()
  • globalStrut()
  • guiThreadAwake()
  • hasGlobalMouseTracking()
  • hasPendingEvents()
  • highPriority()
  • horizontalAlignment()
  • inherits()
  • insertChild()
  • installEventFilter()
  • installTranslator()
  • isA()
  • isEffectEnabled()
  • isSessionRestored()
  • isWidgetType()
  • killTimer()
  • killTimers()
  • lastWindowClosed()
  • libraryPaths()
  • lock()
  • locked()
  • loopLevel()
  • macEventFilter()
  • mainWidget()
  • metaObject()
  • name()
  • normalizeSignalSlot()
  • notify()
  • objectTrees()
  • overrideCursor()
  • palette()
  • parent()
  • polish()
  • postEvent()
  • processEvents()
  • processOneEvent()
  • property()
  • queryList()
  • quit()
  • qwsDecoration()
  • qwsEventFilter()
  • qwsSetCustomColors()
  • qwsSetDecoration()
  • removeChild()
  • removeEventFilter()
  • removeLibraryPath()
  • removePostedEvents()
  • removeTranslator()
  • restoreOverrideCursor()
  • reverseLayout()
  • saveState()
  • sendEvent()
  • sendPostedEvents()
  • sender()
  • sessionId()
  • setColorSpec()
  • setCursorFlashTime()
  • setDefaultCodec()
  • setDesktopSettingsAware()
  • setDoubleClickInterval()
  • setEffectEnabled()
  • setFont()
  • setGlobalMouseTracking()
  • setGlobalStrut()
  • setLibraryPaths()
  • setMainWidget()
  • setName()
  • setOverrideCursor()
  • setPalette()
  • setProperty()
  • setReverseLayout()
  • setStartDragDistance()
  • setStartDragTime()
  • setStyle()
  • setWheelScrollLines()
  • setWinStyleHighlightColor()
  • signalsBlocked()
  • startDragDistance()
  • startDragTime()
  • startTimer()
  • startingUp()
  • style()
  • syncX()
  • timerEvent()
  • topLevelWidgets()
  • tr()
  • trUtf8()
  • translate()
  • tryLock()
  • type()
  • unlock()
  • wakeUpGuiThread()
  • wheelScrollLines()
  • widgetAt()
  • winEventFilter()
  • winFocus()
  • winStyleHighlightColor()
  • winVersion()
  • x11EventFilter()
  • x11ProcessEvent()


QXtWidget Class

QXtWidget Class Reference

The QXtWidget class allows mixing of Xt/Motif and Qt widgets.

This class is part of the Qt Xt/Motif Extension. More...

#include <qxt.h>

Inherits QWidget.

List of all member functions.

Public Members

  • QXtWidget ( const char * name, Widget parent, bool managed = FALSE )
  • QXtWidget ( const char * name, WidgetClass widget_class, QWidget * parent = 0, ArgList args = 0, Cardinal num_args = 0, bool managed = FALSE )
  • ~QXtWidget ()
  • Widget xtWidget () const
  • bool isActiveWindow () const
  • virtual void setActiveWindow ()

Protected Members

  • virtual bool x11Event ( XEvent * e )

Detailed Description

This class is defined in the Qt Xt/Motif Extension, which can be found in the qt/extensions directory. It is not included in the main Qt API.

The QXtWidget class allows mixing of Xt/Motif and Qt widgets.

QXtWidget acts as a bridge between Xt and Qt. For utilizing old Xt widgets, it can be a QWidget based on a Xt widget class. For including Qt widgets in an existing Xt/Motif application, it can be a special Xt widget class that is a QWidget. See the constructors for the different behaviors.

Member Function Documentation

QXtWidget::QXtWidget ( const char * name, Widget parent, bool managed = FALSE )

Constructs a QXtWidget of the special Xt widget class known as "QWidget" to the resource manager.

Use this constructor to utilize Qt widgets in an Xt/Motif application. The QXtWidget is a QWidget, so you can create subwidgets, layouts, etc. using Qt functionality.

The name is the object name passed to the QWidget constructor. The widget's parent is parent.

If the managed parameter is TRUE and parent in not null, XtManageChild it used to manage the child.

QXtWidget::QXtWidget ( const char * name, WidgetClass widget_class, QWidget * parent = 0, ArgList args = 0, Cardinal num_args = 0, bool managed = FALSE )

Constructs a QXtWidget of the given widget_class called name.

Use this constructor to utilize Xt or Motif widgets in a Qt application. The QXtWidget looks and behaves like the Xt class, but can be used like any QWidget.

Note that Xt requires that the most top level Xt widget is a shell. This means, if parent is a QXtWidget, the widget_class can be of any kind. If there isn't a parent or the parent is just a normal QWidget, widget_class should be something like topLevelShellWidgetClass.

The arguments, args, num_args are passed on to XtCreateWidget.

If the managed parameter is TRUE and parent in not null, XtManageChild it used to manage the child.

QXtWidget::~QXtWidget ()

Destructs the QXtWidget.

bool QXtWidget::isActiveWindow () const

Different from QWidget::isActiveWindow()

void QXtWidget::setActiveWindow () [virtual]

Implement a degree of focus handling for Xt widgets.

Reimplemented from QWidget.

bool QXtWidget::x11Event ( XEvent * e ) [virtual protected]

Reimplemented to produce the Xt effect of getting focus when the mouse enters the widget. The event is passed in e.

This function is under development and is subject to change.

Reimplemented from QWidget.

Widget QXtWidget::xtWidget () const

Returns the Xt widget equivalent for the Qt widget.

Examples: mainlyMotif/editor.cpp and mainlyXt/editor.cpp.

This file is part of the Qt toolkit. Copyright © 1995-2002 Trolltech. All Rights Reserved.


QXtWidget Member List

Complete Member List for QXtWidget

This is the complete list of member functions for QXtWidget, including inherited members.

  • QXtWidget()
  • ~QXtWidget()
  • acceptDrops()
  • adjustSize()
  • autoMask()
  • backgroundBrush()
  • backgroundColor()
  • backgroundMode()
  • backgroundOrigin()
  • backgroundPixmap()
  • baseSize()
  • blockSignals()
  • caption()
  • checkConnectArgs()
  • child()
  • childAt()
  • childEvent()
  • children()
  • childrenRect()
  • childrenRegion()
  • className()
  • clearFocus()
  • clearMask()
  • clearWFlags()
  • close()
  • closeEvent()
  • cmd()
  • colorGroup()
  • connect()
  • connectNotify()
  • constPolish()
  • contextMenuEvent()
  • create()
  • cursor()
  • customEvent()
  • customWhatsThis()
  • deleteLater()
  • destroy()
  • destroyed()
  • disconnect()
  • disconnectNotify()
  • dragEnterEvent()
  • dragLeaveEvent()
  • dragMoveEvent()
  • drawText()
  • dropEvent()
  • dumpObjectInfo()
  • dumpObjectTree()
  • enabledChange()
  • enterEvent()
  • erase()
  • eraseColor()
  • erasePixmap()
  • event()
  • eventFilter()
  • find()
  • focusData()
  • focusInEvent()
  • focusNextPrevChild()
  • focusOutEvent()
  • focusPolicy()
  • focusProxy()
  • focusWidget()
  • font()
  • fontChange()
  • fontInfo()
  • fontMetrics()
  • foregroundColor()
  • frameGeometry()
  • frameSize()
  • geometry()
  • getWFlags()
  • grabKeyboard()
  • grabMouse()
  • handle()
  • hasFocus()
  • hasMouse()
  • hasMouseTracking()
  • height()
  • heightForWidth()
  • hide()
  • hideEvent()
  • highPriority()
  • icon()
  • iconText()
  • iconify()
  • imComposeEvent()
  • imEndEvent()
  • imStartEvent()
  • inherits()
  • insertChild()
  • installEventFilter()
  • isA()
  • isActiveWindow()
  • isDesktop()
  • isDialog()
  • isEnabled()
  • isEnabledTo()
  • isEnabledToTLW()
  • isExtDev()
  • isFocusEnabled()
  • isHidden()
  • isMaximized()
  • isMinimized()
  • isModal()
  • isPopup()
  • isTopLevel()
  • isUpdatesEnabled()
  • isVisible()
  • isVisibleTo()
  • isVisibleToTLW()
  • isWidgetType()
  • keyPressEvent()
  • keyReleaseEvent()
  • keyboardGrabber()
  • killTimer()
  • killTimers()
  • layout()
  • leaveEvent()
  • lower()
  • macEvent()
  • mapFrom()
  • mapFromGlobal()
  • mapFromParent()
  • mapTo()
  • mapToGlobal()
  • mapToParent()
  • maximumHeight()
  • maximumSize()
  • maximumWidth()
  • metaObject()
  • metric()
  • microFocusHint()
  • minimumHeight()
  • minimumSize()
  • minimumSizeHint()
  • minimumWidth()
  • mouseDoubleClickEvent()
  • mouseGrabber()
  • mouseMoveEvent()
  • mousePressEvent()
  • mouseReleaseEvent()
  • move()
  • moveEvent()
  • name()
  • normalizeSignalSlot()
  • objectTrees()
  • ownCursor()
  • ownFont()
  • ownPalette()
  • paintEvent()
  • paintingActive()
  • palette()
  • paletteBackgroundColor()
  • paletteBackgroundPixmap()
  • paletteChange()
  • paletteForegroundColor()
  • parent()
  • parentWidget()
  • polish()
  • pos()
  • property()
  • queryList()
  • qwsEvent()
  • raise()
  • recreate()
  • rect()
  • releaseKeyboard()
  • releaseMouse()
  • removeChild()
  • removeEventFilter()
  • repaint()
  • reparent()
  • resetInputContext()
  • resize()
  • resizeEvent()
  • scroll()
  • sender()
  • setAcceptDrops()
  • setActiveWindow()
  • setAutoMask()
  • setBackgroundColor()
  • setBackgroundMode()
  • setBackgroundOrigin()
  • setBackgroundPixmap()
  • setBaseSize()
  • setCaption()
  • setCursor()
  • setDisabled()
  • setEnabled()
  • setEraseColor()
  • setErasePixmap()
  • setFixedHeight()
  • setFixedSize()
  • setFixedWidth()
  • setFocus()
  • setFocusPolicy()
  • setFocusProxy()
  • setFont()
  • setGeometry()
  • setIcon()
  • setIconText()
  • setKeyCompression()
  • setMask()
  • setMaximumHeight()
  • setMaximumSize()
  • setMaximumWidth()
  • setMicroFocusHint()
  • setMinimumHeight()
  • setMinimumSize()
  • setMinimumWidth()
  • setMouseTracking()
  • setName()
  • setPalette()
  • setPaletteBackgroundColor()
  • setPaletteBackgroundPixmap()
  • setPaletteForegroundColor()
  • setProperty()
  • setSizeIncrement()
  • setSizePolicy()
  • setStyle()
  • setTabOrder()
  • setUpdatesEnabled()
  • setWFlags()
  • show()
  • showEvent()
  • showFullScreen()
  • showMaximized()
  • showMinimized()
  • showNormal()
  • signalsBlocked()
  • size()
  • sizeHint()
  • sizeIncrement()
  • sizePolicy()
  • stackUnder()
  • startTimer()
  • style()
  • styleChange()
  • tabletEvent()
  • testWFlags()
  • timerEvent()
  • topLevelWidget()
  • tr()
  • trUtf8()
  • unsetCursor()
  • unsetFont()
  • unsetPalette()
  • update()
  • updateGeometry()
  • updateMask()
  • visibleRect()
  • wheelEvent()
  • width()
  • winEvent()
  • winId()
  • windowActivationChange()
  • x()
  • x11AppCells()
  • x11AppColormap()
  • x11AppDefaultColormap()
  • x11AppDefaultVisual()
  • x11AppDepth()
  • x11AppDisplay()
  • x11AppDpiX()
  • x11AppDpiY()
  • x11AppScreen()
  • x11AppVisual()
  • x11Cells()
  • x11Colormap()
  • x11DefaultColormap()
  • x11DefaultVisual()
  • x11Depth()
  • x11Display()
  • x11Event()
  • x11Screen()
  • x11SetAppDpiX()
  • x11SetAppDpiY()
  • x11Visual()
  • xtWidget()
  • y()


Range controls

This examples shows various types of range controls that are supported by Qt: dials, spin boxes and sliders.

Header file:

/****************************************************************************
** $Id:  qt/rangecontrols.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef RANGECONTROLS_H
#define RANGECONTROLS_H

#include <qvbox.h>

class QCheckBox;

class RangeControls : public QVBox
{
    Q_OBJECT

public:
    RangeControls( QWidget *parent = 0, const char *name = 0 );

private:
    QCheckBox *notches, *wrapping;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/rangecontrols.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "rangecontrols.h"

#include <qhbox.h>
#include <qlcdnumber.h>
#include <qspinbox.h>
#include <qlabel.h>
#include <qstring.h>
#include <qslider.h>
#include <qcheckbox.h>

#include <limits.h>

RangeControls::RangeControls( QWidget *parent, const char *name )
    : QVBox( parent, name )
{
    QHBox *row1 = new QHBox( this );

    QVBox *cell2 = new QVBox( row1 );
    cell2->setMargin( 10 );
    cell2->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );

    (void)new QWidget( cell2 );

    QLabel *label1 = new QLabel( QString( "Enter a value between\n%1 and %2:" ).arg( -INT_MAX ).arg( INT_MAX ), cell2 );
    label1->setMaximumHeight( label1->sizeHint().height() );
    QSpinBox *sb1 = new QSpinBox( -INT_MAX, INT_MAX, 1, cell2 );
    sb1->setValue( 0 );

    QLabel *label2 = new QLabel( "Enter a zoom value:", cell2 );
    label2->setMaximumHeight( label2->sizeHint().height() );
    QSpinBox *sb2 = new QSpinBox( 0, 1000, 10, cell2 );
    sb2->setSuffix( " %" );
    sb2->setSpecialValueText( "Automatic" );

    QLabel *label3 = new QLabel( "Enter a price:", cell2 );
    label3->setMaximumHeight( label3->sizeHint().height() );
    QSpinBox *sb3 = new QSpinBox( 0, INT_MAX, 1, cell2 );
    sb3->setPrefix( "$" );
    sb3->setValue( 355 );

    (void)new QWidget( cell2 );

    QHBox *row2 = new QHBox( this );

    QVBox *cell3 = new QVBox( row2 );
    cell3->setMargin( 10 );
    cell3->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
    QSlider *hslider = new QSlider( 0, 64, 1, 33, Qt::Horizontal, cell3 );
    QLCDNumber *lcd2 = new QLCDNumber( 2, cell3 );
    lcd2->display( 33 );
    lcd2->setSegmentStyle( QLCDNumber::Filled );
    connect( hslider, SIGNAL( valueChanged( int ) ), lcd2, SLOT( display( int ) ) );

    QHBox *cell4 = new QHBox( row2 );
    cell4->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
    cell4->setMargin( 10 );
    QSlider *vslider = new QSlider( 0, 64, 1, 8, Qt::Vertical, cell4 );
    QLCDNumber *lcd3 = new QLCDNumber( 3, cell4 );
    lcd3->display( 8 );
    connect( vslider, SIGNAL( valueChanged( int ) ), lcd3, SLOT( display( int ) ) );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "rangecontrols.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    RangeControls rangecontrols;
    rangecontrols.resize( 500, 300 );
    rangecontrols.setCaption( "Qt Example - Range Control Widgets" );
    a.setMainWidget( &rangecontrols );
    rangecontrols.show();

    return a.exec();
}

See also Examples.


Richtext

In this example we demonstrate how to display rich text in a widget. To do this some sayings taken from the famous Unix "fortune" are displayed nicely formatted.

Header file:

/****************************************************************************
** $Id:  qt/richtext.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef RICHTEXT_H
#define RICHTEXT_H

#include <qvbox.h>

class QTextView;
class QPushButton;

class MyRichText : public QVBox
{
    Q_OBJECT

public:
    MyRichText( QWidget *parent = 0, const char *name = 0 );

protected:
    QTextView *view;
    QPushButton *bClose, *bNext, *bPrev;
    int num;

protected slots:
    void prev();
    void next();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/richtext.cpp   3.0.5   edited Oct 22 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "richtext.h"

#include <qhbox.h>
#include <qhbox.h>
#include <qpushbutton.h>
#include <qtextview.h>
#include <qbrush.h>
#include <qapplication.h>

static const char* sayings[] = {
    "<b>Saying 1:</b><br>"
    "<hr><br><br>"
    "<big>Evil is that which one believes of others.  It is a sin to believe evil "
    "of others, but it is seldom a mistake.</big><br><br>"
    "<center><i>-- H.L. Mencken</i></center>",

    "<b>Saying 2:</b><br>"
    "<hr><br><br>"
    "<big>A well-used door needs no oil on its hinges.<br>"
    "A swift-flowing steam does not grow stagnant.<br>"
    "Neither sound nor thoughts can travel through a vacuum.<br>"
    "Software rots if not used.<br><br>"
    "These are great mysteries.</big><br><br>"
    "<center><i>-- Geoffrey James, \"The Tao of Programming\"</i></center>",

    "<b>Saying 3:</b><br>"
    "<hr><br><br>"
    "<big>Show business is just like high school, except you get paid.</big><br><br>"
    "<center><i>-- Martin Mull</i></center>",

    "<b>Saying 4:</b><br>"
    "<hr><br><br>"
    "<big><b>The Least Successful Executions</b><br>"
    "<twocolumn><p>      History has furnished us with two executioners worthy of attention. "
    "The first performed in Sydney in Australia.  In 1803 three attempts were "
    "made to hang a Mr. Joseph Samuels.  On the first two of these the rope "
    "snapped, while on the third Mr. Samuels just hung there peacefully until he "
    "and everyone else got bored.  Since he had proved unsusceptible to capital "
    "punishment, he was reprieved.</p>"
    "<p>        The most important British executioner was Mr. James Berry who "
    "tried three times in 1885 to hang Mr. John Lee at Exeter Jail, but on each "
    "occasion failed to get the trap door open.<!p>"
    "<p>        In recognition of this achievement, the Home Secretary commuted "
    "Lee's sentence to \"life\" imprisonment.  He was released in 1917, emigrated "
    "to America and lived until 1933.</p></twocolumn></big><br><br>"
    "<center><i>-- Stephen Pile, \"The Book of Heroic Failures\"</i></center>",

    "<b>Saying 5:</b><br>"
    "<hr><br><br>"
    "<big>If you can, help others.  If you can't, at least don't hurt others.</big><br><br>"
    "<center><i>-- the Dalai Lama</i></center>",

    "<b>Saying 6:</b><br>"
    "<hr><br><br>"
    "<big>Television has brought back murder into the home -- where it belongs.</big><br><br>"
    "<center><i>-- Alfred Hitchcock</i></center>",

    "<b>Saying 7:</b><br>"
    "<hr><br><br>"
    "<big>I don't know who my grandfather was; I am much more concerned to know "
    "what his grandson will be.</big><br><br>"
    "<center><i>-- Abraham Lincoln</i></center>",

    0
};

MyRichText::MyRichText( QWidget *parent, const char *name )
    : QVBox( parent, name )
{
    setMargin( 5 );

    view = new QTextView( this );
    view->setText( "This is a <b>Test</b> with <i>italic</i> <u>stuff</u>" );
    QBrush paper;
    paper.setPixmap( QPixmap( "../richtext/marble.png" ) );
    if ( paper.pixmap() != 0 )
        view->setPaper( paper );
    else
        view->setPaper( white );

    view->setText( sayings[0] );
    view->setMinimumSize( 450, 250 );

    QHBox *buttons = new QHBox( this );
    buttons->setMargin( 5 );

    bClose = new QPushButton( "&Close", buttons );
    bPrev = new QPushButton( "<< &Prev", buttons );
    bNext = new QPushButton( "&Next >>", buttons );

    bPrev->setEnabled( FALSE );

    connect( bClose, SIGNAL( clicked() ), qApp, SLOT( quit() ) );
    connect( bPrev, SIGNAL( clicked() ), this, SLOT( prev() ) );
    connect( bNext, SIGNAL( clicked() ), this, SLOT( next() ) );

    num = 0;
}

void MyRichText::prev()
{
    if ( num <= 0 )
        return;

    num--;

    view->setText( sayings[num] );

    if ( num == 0 )
        bPrev->setEnabled( FALSE );

    bNext->setEnabled( TRUE );
}

void MyRichText::next()
{
    if ( !sayings[++num] )
        return;

    view->setText( sayings[num] );

    if ( !sayings[num + 1] )
        bNext->setEnabled( FALSE );

    bPrev->setEnabled( TRUE );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "richtext.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    MyRichText richtext;
    richtext.resize( 450, 350 );
    richtext.setCaption( "Qt Example - Richtext" );
    a.setMainWidget( &richtext );
    richtext.show();

    return a.exec();
}

See also Examples.


Rot13

This example lets you enter a text into a mulitilineedit widget. It will be displayed in the edit widget to the right transformed using the rot13 algorithm.

Header file:

/****************************************************************************
** $Id:  qt/rot13.h   3.0.5   edited Oct 12 2001 $
**
** Definition of something or other
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef ROT13_H
#define ROT13_H

#include <qwidget.h>

class QMultiLineEdit;

class Rot13: public QWidget {
    Q_OBJECT
public:
    Rot13();

    QString rot13( const QString & ) const;

private slots:
    void changeLeft();
    void changeRight();

private:
    QMultiLineEdit * left, * right;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/rot13.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "rot13.h"

#include <qmultilineedit.h>
#include <qpushbutton.h>
#include <qapplication.h>
#include <qlayout.h>

Rot13::Rot13()
{
    left = new QMultiLineEdit( this, "left" );
    right = new QMultiLineEdit( this, "right" );
    connect( left, SIGNAL(textChanged()), this, SLOT(changeRight()) );
    connect( right, SIGNAL(textChanged()), this, SLOT(changeLeft()) );

    QPushButton * quit = new QPushButton( "&Quit", this );
    quit->setFocusPolicy( NoFocus );
    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    QGridLayout * l = new QGridLayout( this, 2, 2, 5 );
    l->addWidget( left, 0, 0 );
    l->addWidget( right, 0, 1 );
    l->addWidget( quit, 1, 1, AlignRight );

    left->setFocus();
}

void Rot13::changeLeft()
{
    left->blockSignals( TRUE );
    left->setText( rot13( right->text() ) );
    left->blockSignals( FALSE );
}

void Rot13::changeRight()
{
    right->blockSignals( TRUE );
    right->setText( rot13( left->text() ) );
    right->blockSignals( FALSE );
}

QString Rot13::rot13( const QString & input ) const
{
    QString r = input;
    int i = r.length();
    while( i-- ) {
        if ( r[i] >= QChar('A') && r[i] <= QChar('M') ||
             r[i] >= QChar('a') && r[i] <= QChar('m') )
            r[i] = (char)((int)QChar(r[i]) + 13);
        else if  ( r[i] >= QChar('N') && r[i] <= QChar('Z') ||
                   r[i] >= QChar('n') && r[i] <= QChar('z') )
            r[i] = (char)((int)QChar(r[i]) - 13);
    }
    return r;
}

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );
    Rot13 r;
    r.resize( 400, 400 );
    a.setMainWidget( &r );
    r.setCaption("Qt Example - ROT13");
    r.show();
    return a.exec();
}

See also Examples.


Simple Painting Application

This example implements the famous scribble example. You can draw around in the canvas with different pens and save the result as picture.

Header file:

/****************************************************************************
** $Id:  qt/scribble.h   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef SCRIBBLE_H
#define SCRIBBLE_H

#include <qmainwindow.h>
#include <qpen.h>
#include <qpoint.h>
#include <qpixmap.h>
#include <qwidget.h>
#include <qstring.h>
#include <qpointarray.h>

class QMouseEvent;
class QResizeEvent;
class QPaintEvent;
class QToolButton;
class QSpinBox;

class Canvas : public QWidget
{
    Q_OBJECT

public:
    Canvas( QWidget *parent = 0, const char *name = 0 );

    void setPenColor( const QColor &c )
    { pen.setColor( c ); }

    void setPenWidth( int w )
    { pen.setWidth( w ); }

    QColor penColor()
    { return pen.color(); }

    int penWidth()
    { return pen.width(); }

    void save( const QString &filename, const QString &format );

    void clearScreen();

protected:
    void mousePressEvent( QMouseEvent *e );
    void mouseReleaseEvent( QMouseEvent *e );
    void mouseMoveEvent( QMouseEvent *e );
    void resizeEvent( QResizeEvent *e );
    void paintEvent( QPaintEvent *e );

    QPen pen;
    QPointArray polyline;

    bool mousePressed;

    QPixmap buffer;

};

class Scribble : public QMainWindow
{
    Q_OBJECT

public:
    Scribble( QWidget *parent = 0, const char *name = 0 );

protected:
    Canvas* canvas;

    QSpinBox *bPWidth;
    QToolButton *bPColor, *bSave, *bClear;

protected slots:
    void slotSave();
    void slotColor();
    void slotWidth( int );
    void slotClear();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/scribble.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "scribble.h"

#include <qapplication.h>
#include <qevent.h>
#include <qpainter.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qspinbox.h>
#include <qtooltip.h>
#include <qrect.h>
#include <qpoint.h>
#include <qcolordialog.h>
#include <qfiledialog.h>
#include <qcursor.h>
#include <qimage.h>
#include <qstrlist.h>
#include <qpopupmenu.h>
#include <qintdict.h>

const bool no_writing = FALSE;

Canvas::Canvas( QWidget *parent, const char *name )
    : QWidget( parent, name, WStaticContents ), pen( Qt::red, 3 ), polyline(3),
      mousePressed( FALSE ), buffer( width(), height() )
{

    if ((qApp->argc() > 0) && !buffer.load(qApp->argv()[1]))
        buffer.fill( colorGroup().base() );
    setBackgroundMode( QWidget::PaletteBase );
#ifndef QT_NO_CURSOR
    setCursor( Qt::crossCursor );
#endif
}

void Canvas::save( const QString &filename, const QString &format )
{
    if ( !no_writing )
        buffer.save( filename, format.upper() );
}

void Canvas::clearScreen()
{
    buffer.fill( colorGroup().base() );
    repaint( FALSE );
}

void Canvas::mousePressEvent( QMouseEvent *e )
{
    mousePressed = TRUE;
    polyline[2] = polyline[1] = polyline[0] = e->pos();
}

void Canvas::mouseReleaseEvent( QMouseEvent * )
{
    mousePressed = FALSE;
}

void Canvas::mouseMoveEvent( QMouseEvent *e )
{
    if ( mousePressed ) {
        QPainter painter;
        painter.begin( &buffer );
        painter.setPen( pen );
        polyline[2] = polyline[1];
        polyline[1] = polyline[0];
        polyline[0] = e->pos();
        painter.drawPolyline( polyline );
        painter.end();

        QRect r = polyline.boundingRect();
        r = r.normalize();
        r.setLeft( r.left() - penWidth() );
        r.setTop( r.top() - penWidth() );
        r.setRight( r.right() + penWidth() );
        r.setBottom( r.bottom() + penWidth() );

        bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );
    }
}

void Canvas::resizeEvent( QResizeEvent *e )
{
    QWidget::resizeEvent( e );

    int w = width() > buffer.width() ?
            width() : buffer.width();
    int h = height() > buffer.height() ?
            height() : buffer.height();

    QPixmap tmp( buffer );
    buffer.resize( w, h );
    buffer.fill( colorGroup().base() );
    bitBlt( &buffer, 0, 0, &tmp, 0, 0, tmp.width(), tmp.height() );
}

void Canvas::paintEvent( QPaintEvent *e )
{
    QWidget::paintEvent( e );

    QMemArray<QRect> rects = e->region().rects();
    for ( uint i = 0; i < rects.count(); i++ ) {
        QRect r = rects[(int)i];
        bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );
    }
}

//------------------------------------------------------

Scribble::Scribble( QWidget *parent, const char *name )
    : QMainWindow( parent, name )
{
    canvas = new Canvas( this );
    setCentralWidget( canvas );

    QToolBar *tools = new QToolBar( this );

    bSave = new QToolButton( QPixmap(), "Save", "Save as PNG image", this, SLOT( slotSave() ), tools );
    bSave->setText( "Save as..." );

    tools->addSeparator();

    bPColor = new QToolButton( QPixmap(), "Choose Pen Color", "Choose Pen Color", this, SLOT( slotColor() ), tools );
    bPColor->setText( "Choose Pen Color..." );

    tools->addSeparator();

    bPWidth = new QSpinBox( 1, 20, 1, tools );
    QToolTip::add( bPWidth, "Choose Pen Width" );
    connect( bPWidth, SIGNAL( valueChanged( int ) ), this, SLOT( slotWidth( int ) ) );
    bPWidth->setValue( 3 );

    tools->addSeparator();

    bClear = new QToolButton( QPixmap(), "Clear Screen", "Clear Screen", this, SLOT( slotClear() ), tools );
    bClear->setText( "Clear Screen" );
}

void Scribble::slotSave()
{
    QPopupMenu *menu = new QPopupMenu( 0 );
    QIntDict<QString> formats;
    formats.setAutoDelete( TRUE );

    for ( unsigned int i = 0; i < QImageIO::outputFormats().count(); i++ ) {
        QString str = QString( QImageIO::outputFormats().at( i ) );
        formats.insert( menu->insertItem( QString( "%1..." ).arg( str ) ), new QString( str ) );
    }

    menu->setMouseTracking( TRUE );
    int id = menu->exec( bSave->mapToGlobal( QPoint( 0, bSave->height() + 1 ) ) );

    if ( id != -1 ) {
        QString format = *formats[ id ];

        QString filename = QFileDialog::getSaveFileName( QString::null, QString( "*.%1" ).arg( format.lower() ), this );
        if ( !filename.isEmpty() )
            canvas->save( filename, format );
    }

    delete menu;
}

void Scribble::slotColor()
{
    QColor c = QColorDialog::getColor( canvas->penColor(), this );
    if ( c.isValid() )
        canvas->setPenColor( c );
}

void Scribble::slotWidth( int w )
{
    canvas->setPenWidth( w );
}

void Scribble::slotClear()
{
    canvas->clearScreen();
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright ( C ) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "scribble.h"
#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    Scribble scribble;

    scribble.resize( 500, 350 );
    scribble.setCaption("Qt Example - Scribble");
    a.setMainWidget( &scribble );
    if ( QApplication::desktop()->width() > 550
         && QApplication::desktop()->height() > 366 )
        scribble.show();
    else
        scribble.showMaximized();
    return a.exec();
}

See also Examples.


Qt的文本引擎

贯穿整个库，Qt 3都使用了一个完全重新设计的文本引擎和布局引擎。

它支持在世界范围内使用的几乎所有书写系统，包括：

  • 阿拉伯语
  • 汉语
  • 古斯拉夫语 （俄语）
  • 希腊语
  • 希伯来语
  • 日语
  • 汉语
  • 拉丁语 （例如，英语和一些其它欧洲语言）
  • 泰国语
  • 越南语

这些书写系统中的一些展示了特殊的特征：

  • 特殊的断行符。一些亚洲语言在词中间没有空格。断行符出现在汉语、日语和汉语的字符（也有例外）后，或者泰国语中的逻辑词的边界后。

  • 双向书写。阿拉伯语和希伯来语是从右向左书写的，除了数字和嵌入的英文文本是从左向右书写的。准确的书写习惯在Unicode第9号技术报告有定义。

  • 无间距或者可区别的符号（欧洲语言中的重音或元音变音）。像越南语这样的一些语言很广泛地使用了这类符号并且同时字符中使用一些符号来澄清发音。

  • 连字。在特殊的内容中，相互跟随的一些字符被一些使用连字符的结合体替换。最普通的例子就是在美国和欧洲的书籍排版中使用的ff和fi连字。

除了现在仅仅被特殊情况下的阿拉伯语支持的连字，Qt试图处理所有上面提到的特殊特征。只要你使用Qt的输入（例如，QLineEdit，QTextView或者它们的继承类）和显示控制（例如，QLabel），你将永远不用担心这些特征。

对于这些书写系统的支持对程序员是透明的并且完全地封装在Qt的文本引擎中。这就意味着你不需要去知道使用特殊语言的书写系统，除了下面列出的一些小事情。

  • QPainter::drawText( int x, int y, const QString &str )将会在x和y参数确定的位置作为左边界可是写这个字符串。通常情况下给你的是左对齐的字符串。阿拉伯语和希伯来语的应用程序字符串是右对齐的，所以对于这些语言使用带有QRect的drawText()，因为这样的话函数就会根据语言在区域中画文字了。

  • 当你写自己的文本输入控制时，使用QFontMetrics::charWidth()来确定字符串中字符的宽度。在一些语言中（主要是阿拉伯语），符号的宽度和形状的变化依赖于周围的字符。写输入控制通常需要它将要使用的脚本的知识。通常最容易的方式是继承QLineEdit或者QTextView。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Scrollview

This example shows how to use Qt's scrollview. This is a widget optimized for very large contents.

Implementation:

/****************************************************************************
** $Id:  qt/scrollview.cpp   3.0.5   edited Oct 15 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qscrollview.h>
#include <qapplication.h>
#include <qmenubar.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qmessagebox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qmultilineedit.h>
#include <qsizegrip.h>
#include <stdlib.h>

static const int style_id       = 0x1000;
static const int lw_id          = 0x2000;
static const int mlw_id         = 0x4000;
static const int mw_id          = 0x8000;
static const int max_lw         = 16;
static const int max_mlw        = 5;
static const int max_mw         = 10;

class BigShrinker : public QFrame {
    Q_OBJECT
public:
    BigShrinker(QWidget* parent) :
        QFrame(parent)
    {
        setFrameStyle(QFrame::Box|QFrame::Sunken);
        int h=35;
        int b=0;
        for (int y=0; y<2000-h; y+=h+10) {
            if (y == 0) {
                QButton* q=new QPushButton("Quit", this);
                connect(q, SIGNAL(clicked()), qApp, SLOT(quit()));
            } else {
                QString str;
                if ( b > 0 ) {
                    str.sprintf("Button %d", b++);
                } else {
                    str = "I'm shrinking!";
                    ++b;
                }
                (new QPushButton(str, this))->move(y/2,y);
            }
        }
        resize(1000,2000);

        startTimer(250);
    }

    void timerEvent(QTimerEvent*)
    {
        int w=width();
        int h=height();
        if ( w > 50 ) w -= 1;
        if ( h > 50 ) h -= 2;
        resize(w,h);
    }

    void mouseReleaseEvent(QMouseEvent* e)
    {
        emit clicked(e->x(), e->y());
    }

signals:
    void clicked(int,int);
};

class BigMatrix : public QScrollView {
    QMultiLineEdit *dragging;
public:
    BigMatrix(QWidget* parent) :
        QScrollView(parent,"matrix", WStaticContents),
        bg("bg.ppm")
    {
        bg.load("bg.ppm");
        resizeContents(400000,300000);

        dragging = 0;
    }

    void viewportMousePressEvent(QMouseEvent* e)
    {
        int x, y;
        viewportToContents( e->x(),  e->y(), x, y );
        dragging = new QMultiLineEdit(viewport(),"Another");
        dragging->setText("Thanks!");
        dragging->resize(100,100);
        addChild(dragging, x, y);
        showChild(dragging);
    }

    void viewportMouseReleaseEvent(QMouseEvent*)
    {
        dragging = 0;
    }

    void viewportMouseMoveEvent(QMouseEvent* e)
    {
        if ( dragging ) {
            int mx, my;
            viewportToContents( e->x(),  e->y(), mx, my );
            int cx = childX(dragging);
            int cy = childY(dragging);
            int w = mx - cx + 1;
            int h = my - cy + 1;
            QString msg;
            msg.sprintf("at (%d,%d) %d by %d",cx,cy,w,h);
            dragging->setText(msg);
            dragging->resize(w,h);
        }
    }

protected:
    void drawContents(QPainter* p, int cx, int cy, int cw, int ch)
    {
        // The Background
        if ( !bg.isNull() ) {
            int rowheight=bg.height();
            int toprow=cy/rowheight;
            int bottomrow=(cy+ch+rowheight-1)/rowheight;
            int colwidth=bg.width();
            int leftcol=cx/colwidth;
            int rightcol=(cx+cw+colwidth-1)/colwidth;
            for (int r=toprow; r<=bottomrow; r++) {
                int py=r*rowheight;
                for (int c=leftcol; c<=rightcol; c++) {
                    int px=c*colwidth;
                    p->drawPixmap(px, py, bg);
                }
            }
        } else {
            p->fillRect(cx, cy, cw, ch, QColor(240,222,208));
        }

        // The Numbers
        {
            QFontMetrics fm=p->fontMetrics();
            int rowheight=fm.lineSpacing();
            int toprow=cy/rowheight;
            int bottomrow=(cy+ch+rowheight-1)/rowheight;
            int colwidth=fm.width("00000,000000 ")+3;
            int leftcol=cx/colwidth;
            int rightcol=(cx+cw+colwidth-1)/colwidth;
            QString str;
            for (int r=toprow; r<=bottomrow; r++) {
                int py=r*rowheight;
                for (int c=leftcol; c<=rightcol; c++) {
                    int px=c*colwidth;
                    str.sprintf("%d,%d",c,r);
                    p->drawText(px+3, py+fm.ascent(), str);
                }
            }

            // The Big Hint
            if (leftcol<10 && toprow<5) {
                p->setFont(QFont("Charter",30));
                p->setPen(red);
                QString text;
                text.sprintf("HINT:  Look at %d,%d",215000/colwidth,115000/rowheight);
                p->drawText(100,50,text);
            }
        }

        // The Big X
        {
            if (cx+cw>200000 && cy+ch>100000 && cx<230000 && cy<130000) {
                // Note that some X server cannot even handle co-ordinates
                // beyond about 4000, so you might not see this.
                p->drawLine(200000,100000,229999,129999);
                p->drawLine(229999,100000,200000,129999);

                // X marks the spot!
                p->setFont(QFont("Charter",100));
                p->setPen(blue);
                p->drawText(215000-500,115000-100,1000,200,AlignCenter,"YOU WIN!!!!!");
            }
        }
    }

private:
    QPixmap bg;
};

class ScrollViewExample : public QWidget {
    Q_OBJECT

public:
    ScrollViewExample(int technique, QWidget* parent=0, const char* name=0) :
        QWidget(parent,name)
    {
        QMenuBar* menubar = new QMenuBar(this);
        Q_CHECK_PTR( menubar );

        QPopupMenu* file = new QPopupMenu( menubar );
        Q_CHECK_PTR( file );
        menubar->insertItem( "&File", file );
        file->insertItem( "Quit", qApp,  SLOT(quit()) );

        vp_options = new QPopupMenu( menubar );
        Q_CHECK_PTR( vp_options );
        vp_options->setCheckable( TRUE );
        menubar->insertItem( "&ScrollView", vp_options );
        connect( vp_options, SIGNAL(activated(int)),
            this, SLOT(doVPMenuItem(int)) );

        vauto_id = vp_options->insertItem( "Vertical Auto" );
        vaoff_id = vp_options->insertItem( "Vertical AlwaysOff" );
        vaon_id = vp_options->insertItem( "Vertical AlwaysOn" );
        vp_options->insertSeparator();
        hauto_id = vp_options->insertItem( "Horizontal Auto" );
        haoff_id = vp_options->insertItem( "Horizontal AlwaysOff" );
        haon_id = vp_options->insertItem( "Horizontal AlwaysOn" );
        vp_options->insertSeparator();
        corn_id = vp_options->insertItem( "cornerWidget" );

        if (technique == 1) {
            vp = new QScrollView(this);
            BigShrinker *bs = new BigShrinker(0);//(vp->viewport());
            vp->addChild(bs);
            bs->setAcceptDrops(TRUE);
            QObject::connect(bs, SIGNAL(clicked(int,int)),
                            vp, SLOT(center(int,int)));
        } else {
            vp = new BigMatrix(this);
            if ( technique == 3 )
                vp->enableClipper(TRUE);
            srand(1);
            for (int i=0; i<30; i++) {
                QMultiLineEdit *l = new QMultiLineEdit(vp->viewport(),"First");
                l->setText("Drag out more of these.");
                l->resize(100,100);
                vp->addChild(l, rand()%800, rand()%10000);
            }
            vp->viewport()->setBackgroundMode(NoBackground);
        }

        f_options = new QPopupMenu( menubar );
        Q_CHECK_PTR( f_options );
        f_options->setCheckable( TRUE );
        menubar->insertItem( "F&rame", f_options );
        connect( f_options, SIGNAL(activated(int)),
            this, SLOT(doFMenuItem(int)) );

        f_options->insertItem( "No Frame", style_id );
        f_options->insertItem( "Box", style_id|QFrame::Box );
        f_options->insertItem( "Panel", style_id|QFrame::Panel );
        f_options->insertItem( "WinPanel", style_id|QFrame::WinPanel );
        f_options->insertSeparator();
        f_options->insertItem( "Plain", style_id|QFrame::Plain );
        f_options->insertItem( "Raised", style_id|QFrame::Raised );
        f_laststyle = f_options->indexOf(
            f_options->insertItem( "Sunken", style_id|QFrame::Sunken ));
        f_options->insertSeparator();
        lw_options = new QPopupMenu( menubar );
        Q_CHECK_PTR( lw_options );
        lw_options->setCheckable( TRUE );
        for (int lw = 1; lw <= max_lw; lw++) {
            QString str;
            str.sprintf("%d Pixels", lw);
            lw_options->insertItem( str, lw_id | lw );
        }
        f_options->insertItem( "Line Width", lw_options );
        connect( lw_options, SIGNAL(activated(int)),
            this, SLOT(doFMenuItem(int)) );
        mlw_options = new QPopupMenu( menubar );
        Q_CHECK_PTR( mlw_options );
        mlw_options->setCheckable( TRUE );
        for (int mlw = 0; mlw <= max_mlw; mlw++) {
            QString str;
            str.sprintf("%d Pixels", mlw);
            mlw_options->insertItem( str, mlw_id | mlw );
        }
        f_options->insertItem( "Midline Width", mlw_options );
        connect( mlw_options, SIGNAL(activated(int)),
            this, SLOT(doFMenuItem(int)) );
        mw_options = new QPopupMenu( menubar );
        Q_CHECK_PTR( mw_options );
        mw_options->setCheckable( TRUE );
        for (int mw = 0; mw <= max_mw; mw++) {
            QString str;
            str.sprintf("%d Pixels", mw);
            mw_options->insertItem( str, mw_id | mw );
        }
        f_options->insertItem( "Margin Width", mw_options );
        connect( mw_options, SIGNAL(activated(int)),
            this, SLOT(doFMenuItem(int)) );

        setVPMenuItems();
        setFMenuItems();

        QVBoxLayout* vbox = new QVBoxLayout(this);
        vbox->setMenuBar(menubar);
        menubar->setSeparator(QMenuBar::InWindowsStyle);
        vbox->addWidget(vp);
        vbox->activate();

        corner = new QSizeGrip(this);
        corner->hide();
    }

private slots:
    void doVPMenuItem(int id)
    {
        if (id == vauto_id ) {
            vp->setVScrollBarMode(QScrollView::Auto);
        } else if (id == vaoff_id) {
            vp->setVScrollBarMode(QScrollView::AlwaysOff);
        } else if (id == vaon_id) {
            vp->setVScrollBarMode(QScrollView::AlwaysOn);
        } else if (id == hauto_id) {
            vp->setHScrollBarMode(QScrollView::Auto);
        } else if (id == haoff_id) {
            vp->setHScrollBarMode(QScrollView::AlwaysOff);
        } else if (id == haon_id) {
            vp->setHScrollBarMode(QScrollView::AlwaysOn);
        } else if (id == corn_id) {
            bool corn = !vp->cornerWidget();
            vp->setCornerWidget(corn ? corner : 0);
        } else {
            return; // Not for us to process.
        }
        setVPMenuItems();
    }

    void setVPMenuItems()
    {
        QScrollView::ScrollBarMode vm = vp->vScrollBarMode();
        vp_options->setItemChecked( vauto_id, vm == QScrollView::Auto );
        vp_options->setItemChecked( vaoff_id, vm == QScrollView::AlwaysOff );
        vp_options->setItemChecked( vaon_id, vm == QScrollView::AlwaysOn );

        QScrollView::ScrollBarMode hm = vp->hScrollBarMode();
        vp_options->setItemChecked( hauto_id, hm == QScrollView::Auto );
        vp_options->setItemChecked( haoff_id, hm == QScrollView::AlwaysOff );
        vp_options->setItemChecked( haon_id, hm == QScrollView::AlwaysOn );

        vp_options->setItemChecked( corn_id, !!vp->cornerWidget() );
    }

    void doFMenuItem(int id)
    {
        if (id & style_id) {
            int sty;

            if (id == style_id) {
                sty = 0;
            } else if (id & QFrame::MShape) {
                sty = vp->frameStyle()&QFrame::MShadow;
                sty = (sty ? sty : QFrame::Plain) | (id&QFrame::MShape);
            } else {
                sty = vp->frameStyle()&QFrame::MShape;
                sty = (sty ? sty : QFrame::Box) | (id&QFrame::MShadow);
            }
            vp->setFrameStyle(sty);
        } else if (id & lw_id) {
            vp->setLineWidth(id&~lw_id);
        } else if (id & mlw_id) {
            vp->setMidLineWidth(id&~mlw_id);
        } else {
            vp->setMargin(id&~mw_id);
        }

        vp->update();
        setFMenuItems();
    }

    void setFMenuItems()
    {
        int sty = vp->frameStyle();

        f_options->setItemChecked( style_id, !sty );

        for (int i=1; i <= f_laststyle; i++) {
            int id = f_options->idAt(i);
            if (id & QFrame::MShape)
                f_options->setItemChecked( id,
                    ((id&QFrame::MShape) == (sty&QFrame::MShape)) );
            else
                f_options->setItemChecked( id,
                    ((id&QFrame::MShadow) == (sty&QFrame::MShadow)) );
        }

        for (int lw=1; lw<=max_lw; lw++)
            lw_options->setItemChecked( lw_id|lw, vp->lineWidth() == lw );

        for (int mlw=0; mlw<=max_mlw; mlw++)
            mlw_options->setItemChecked( mlw_id|mlw, vp->midLineWidth() == mlw );

        for (int mw=0; mw<=max_mw; mw++)
            mw_options->setItemChecked( mw_id|mw, vp->margin() == mw );
    }

private:
    QScrollView* vp;
    QPopupMenu* vp_options;
    QPopupMenu* f_options;
    QPopupMenu* lw_options;
    QPopupMenu* mlw_options;
    QPopupMenu* mw_options;
    QSizeGrip* corner;

    int vauto_id, vaoff_id, vaon_id,
        hauto_id, haoff_id, haon_id,
        corn_id;

    int f_laststyle;
};

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    ScrollViewExample ve1(1,0,"ve1");
    ScrollViewExample ve2(2,0,"ve2");
    ScrollViewExample ve3(3,0,"ve3");
    ve1.setCaption("Qt Example - Scrollviews");
    ve1.show();
    ve2.setCaption("Qt Example - Scrollviews");
    ve2.show();
    ve3.setCaption("Qt Example - Scrollviews");
    ve3.show();

    QObject::connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));

    return a.exec();
}

#include "scrollview.moc"

See also Examples.


Session Management

Definitions

A session is a group of applications running, each of which has a particular state. The session is controlled by a service called the session manager. The applications participating in the session are called session clients.

The session manager issues commands to its clients on behalf of the user. These commands may cause clients to commit unsaved changes (for example by saving open files), to preserve their state for future sessions or to terminate gracefully. The set of these operations is called session management.

In the common case, a session consists of all applications that a user runs on their desktop at a time. Under Unix/X11, however, a session may include applications running on different computers and may span multiple displays.

Shutting a session down

A session is shut down by the session manager, usually on behalf of the user when they want to log out. A system might also perform an automatic shutdown in an emergency situation, for example, if power is about to be lost. Clearly there is a significant big difference between both shutdowns. During the first, the user may want to interact with the application, specifying exactly which files should be saved and which should be discarded. In the latter case, there's no time for interaction. There may not even be a user sitting in front of the machine!

Protocols and support on different platforms

On Mac OS X and MS-Windows, there is nothing like complete session management for applications yet, i.e. no restoring of previous sessions. They do support graceful logouts where applications have the chance to cancel the process after getting confirmation from the user. This is the functionality that corresponds to the QApplication::commitData() method.

X11 has supported complete session management since X11R6.

Getting session management to work with Qt

Start by reimplementing QApplication::commitData() to enable your application to take part in the graceful logout process. If you target the MS-Windows platform only, this is all you can and have to provide. Ideally, your application should provide a shutdown dialog similar to the following one:

A typical dialog on shutdown

Example code to this dialog can be found in the documentation of QSessionManager::allowsInteraction().

For complete session management (only supported on X11R6 at present), you also have to take care of saving the state of the application and potentially restore the state in the next life cycle of the session. This saving is done by reimplementing QApplication::saveState(). All state data you are saving in this function, should be marked with the session identifier QApplication::sessionId(). This application specific identifier is globally unique, so no clashes will occur. (See QSessionManager for information on saving/restoring the state of a particular Qt application.)

Restoration is usually done in the application's main() function. Check if QApplication::isSessionRestored() is TRUE. If that's the case, use the session identifier QApplication::sessionId() again to access your state date and restore the state of the application.

Important: In order to allow the window manager to restore window attributes such as stacking order or geometry information, you must identify your top level widgets with unique application-wide object names (see QObject::setName()). When restoring the application, you must ensure that all restored top level widgets are given the same unique names they had before.

Testing and debugging session management

Session management support on Mac OS X and Windows is fairly limited due to the lack of this functionality in the operating system itself. Simply shut the session down and verify that your application behaves as wanted. It may be a good idea to launch another application, usually the integrated development environment, before starting your application. This other application will get the shutdown message afterwards, thus permitting you to cancel the shutdown. Otherwise you would have to log in again after each test run, which is not a problem per se but time consuming.

On Unix you can either use a desktop environment that supports standard X11R6 session management or, the recommended method, use the session manager reference implementation provided by the X Consortium. This sample manager is called xsm and is part of a standard X11R6 installation. As always with X11, a useful and informative manual page is provided. Using xsm is straightforward (apart from the clumsy Athena-based user interface). Here's a simple approach:

  • Run X11R6.
  • Create a dot file .xsmstartup in your home directory which contains the single line

    xterm

    This tells xsm that the default/failsafe session is just an xterm and nothing else. Otherwise xsm would try to invoke lots of clients including the windowmanager twm, which isn't very helpful.

  • Now launch xsm from another terminal window. Both a session manager window and the xterm will appear. The xterm has a nice property that sets it apart from all the other shells you are currently running: within its shell, the SESSION_MANAGER environment variable points to the session manager you just started.
  • Launch your application from the new xterm window. It will connect itself automatically to the session manager. You can check with the ClientList push button whether the connect was successful.
    Note: Never keep the ClientList open when you start or end session managed clients! Otherwise xsm is likely to crash.
  • Use the session manager's Checkpoint and Shutdown buttons with different settings and see how your application behaves. The save type local means that the clients should save their state. It corresponds to the QApplication::saveState() function. The global save type asks application to save their unsaved changes in the permanent, globally accessible storage. It invokes QApplication::commitData().
  • Whenever something crashes, blame xsm and not Qt. xsm is far from being a usable session manager on a user's desktop. It is, however, stable and useful enough to serve as testing environment.


Implicitly and Explicitly Shared Classes

These classes are normally-heavy classes which in Qt have been optimized by the use of reference counter and common data so they can be passed around.

The only important effect is that the classes listed here can be passed around as arguments efficiently, even though they may seem heavyweight.

QBitArray | Array of bits
QBitmap | Monochrome (1-bit depth) pixmaps
QBrush | Defines the fill pattern of shapes drawn by a QPainter
QCString | Abstraction of the classic C zero-terminated char array (char *)
QCursor | Mouse cursor with an arbitrary shape
QFont | Font used for drawing text
QFontInfo | General information about fonts
QFontMetrics | Font metrics information
QIconSet | Set of icons with different styles and sizes
QImage | Hardware-independent pixmap representation with direct access to the pixel data
QMap | Value-based template class that provides a dictionary
QPair | Value-based template class that provides a pair of elements
QPalette | Color groups for each widget state
QPen | Defines how a QPainter should draw lines and outlines of shapes
QPicture | Paint device that records and replays QPainter commands
QPixmap | Off-screen, pixel-based paint device
QPointArray | Array of points
QRegExp | Pattern matching using regular expressions
QString | Abstraction of Unicode text and the classic C null-terminated char array
QStringList | List of strings
QValueList | Value-based template class that provides doubly linked lists
QValueStack | Value-based template class that provides a stack
QValueVector | Value-based template class that provides a dynamic array


Shared Classes

Many C++ classes in Qt use explicit and implicit data sharing to maximize resource usage and minimize copying of data.

  • Overview
  • A QByteArray Example
  • Explicit vs. Implicit Sharing
  • Explicitly Shared Classes
  • Implicitly Shared Classes
  • QCString: implicit or explicit?

Overview

A shared class consists of a pointer to a shared data block that contains a reference count and the data.

When a shared object is created, it sets the reference count to 1. The reference count is incremented whenever a new object references the shared data, and decremented when the object dereferences the shared data. The shared data is deleted when the reference count becomes zero.

When dealing with shared objects, there are two ways of copying an object. We usually speak about deep and shallow copies. A deep copy implies duplicating an object. A shallow copy is a reference copy, we only copy a pointer to a shared data block. Making a deep copy can be expensive in terms of memory and CPU. Making a shallow copy is very fast, because it only involves setting a pointer and incrementing the reference count.

Object assignment (with operator=) for implicitly and explicitly shared objects is implemented as shallow copies. A deep copy can be made by calling a copy() function.

The benefit of sharing is that a program does not need to duplicate data when it is not required, which results in less memory usage and less copying of data. Objects can easily be assigned, sent as function arguments and returned from functions.

Now comes the distinction between explicit and implicit sharing. Explicit sharing means that the programmer must be aware of the fact that objects share common data. Implicit sharing means that the sharing mechanism takes place behind the scenes and the programmer does not need to worry about it.

A QByteArray Example

QByteArray is an example of a shared class that uses explicit sharing. Example:

                          //        a=         b=         c=
    QByteArray a(3),b(2)  // 1)     {?,?,?}    {?,?}
    b[0] = 12; b[1] = 34; // 2)     {?,?,?}    {12,34}
    a = b;                // 3)     {12,34}    {12,34}
    a[1] = 56;            // 4)     {12,56}    {12,56}
    QByteArray c = a;     // 5)     {12,56}    {12,56}    {12,56}
    a.detach();           // 6)     {12,56}    {12,56}    {12,56}
    a[1] = 78;            // 7)     {12,78}    {12,56}    {12,56}
    b = a.copy();         // 8)     {12,78}    {12,78}    {12,56}
    a[1] = 90;            // 9)     {12,90}    {12,78}    {12,56}

The assignment a = b on line 3 throws away a's original shared block (the reference count becomes zero), sets a's shared block to point to b's shared block and increments the reference count.

On line 4, the contents of a is modified. b is also modified, because a and b refer the same data block. This is the difference between explicit and implicit sharing (explained below).

The a object detaches from the common data on line 6. Detaching means to copy the shared data to make sure that an object has its own private data. Therefore, modifying a on line 7 will not affect b or c.

Finally, on line 8 we make a deep copy of a and assign it to b, so that when a is modified on line 9, b remains unchanged.

Explicit vs. Implicit Sharing

Implicit sharing automatically detaches the object from a shared block if the object is about to change and the reference count is greater than one. Explicit sharing leaves this job to the programmer. If an explicitly shared object is not detached, changing the object will change all other objects that refer to the same data.

Implicit sharing optimizes memory usage and copying of data without this side effect. So why didn't we implement implicit sharing for all shared classes? The answer is that a class that allows direct access to its internal data (for efficiency reasons), like QByteArray, cannot be implicitly shared, because it can be changed without letting QByteArray know.

An implicitly shared class has total control of its internal data. In any member functions that modify its data, it automatically detaches before modifying the data.

The QPen class, which uses implicit sharing, detaches from the shared data in all member functions that change the internal data.

Code fragment:

    void QPen::setStyle( PenStyle s )
    {
        detach();        // detach from common data
        data->style = s; // set the style member
    }

    void QPen::detach()
    {
        if ( data->count != 1 ) // only if >1 reference
            *this = copy();
    }

This is clearly not possible for QByteArray, because the programmer can do the following:

    QByteArray array( 10 );
    array.fill( 'a' );
    array[0] = 'f';        // will modify array
    array.data()[1] = 'i'; // will modify array

If we monitor changes in a QByteArray, the QByteArray class would become unacceptably slow.

Explicitly Shared Classes

All classes that are instances of the QMemArray template class are explicitly shared:

  • QBitArray
  • QPointArray
  • QByteArray
  • Any other instantiation of QMemArray<type>

These classes have a detach() function that can be called if you want your object to get a private copy of the shared data. They also have a copy() function that returns a deep copy with a reference count of 1.

The same is true for QImage, which does not inherit QMemArray. QMovie is also explicitly shared, but it does not support detach() and copy().

Implicitly Shared Classes

The Qt classes that are implicitly shared are:

  • QBitmap
  • QBrush
  • QCursor
  • QFont
  • QFontInfo
  • QFontMetrics
  • QIconSet
  • QMap
  • QPalette
  • QPen
  • QPicture
  • QPixmap
  • QRegion
  • QRegExp
  • QString
  • QStringList
  • QValueList
  • QValueStack

These classes automatically detach from common data if an object is about to be changed. The programmer will not even notice that the objects are shared. Thus you should treat separate instances of them as separate objects. They will always behave as separate objects but with the added bonus of sharing data whenever possible. For this reason, you can pass instances of these classes as arguments to functions by value without concern for the copying overhead.

Example:

    QPixmap p1, p2;
    p1.load( "image.bmp" );
    p2 = p1;                    // p1 and p2 share data
    QPainter paint;
    paint.begin( &p2 );         // cuts p2 loose from p1
    paint.drawText( 0,50, "Hi" );
    paint.end();

In this example, p1 and p2 share data until QPainter::begin() is called for p2, because painting a pixmap will modify it. The same happens also if anything is bitBlt()'ed into p2.

QCString: implicit or explicit?

QCString uses a mixture of implicit and explicit sharing. Functions inherited from QByteArray, such as data(), employ explicit sharing, while those only in QCString detach automatically. Thus, QCString is rather an "experts only" class, provided mainly to ease porting from Qt 1.x to Qt 2.0. We recommend that you use QString, a purely implicitly shared class.


Show Image

This example reads and displays an image in any supported image format (GIF, BMP, PPM, XMP, etc.).

Header file:

/****************************************************************************
** $Id:  qt/showimg.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef SHOWIMG_H
#define SHOWIMG_H

#include <qwidget.h>
#include <qimage.h>

class QLabel;
class QMenuBar;
class QPopupMenu;

class ImageViewer : public QWidget
{
    Q_OBJECT
public:
    ImageViewer( QWidget *parent=0, const char *name=0, int wFlags=0 );
    ~ImageViewer();
    bool        loadImage( const char *fileName );
protected:
    void        paintEvent( QPaintEvent * );
    void        resizeEvent( QResizeEvent * );
    void        mousePressEvent( QMouseEvent * );
    void        mouseReleaseEvent( QMouseEvent * );
    void        mouseMoveEvent( QMouseEvent * );

private:
    void        scale();
    int         conversion_flags;
    bool        smooth() const;
    bool        useColorContext() const;
    int         alloc_context;
    bool        convertEvent( QMouseEvent* e, int& x, int& y );
    const char* filename;
    QImage      image;                  // the loaded image
    QPixmap     pm;                     // the converted pixmap
    QPixmap     pmScaled;               // the scaled pixmap

    QMenuBar   *menubar;
    QPopupMenu  *file;
    QPopupMenu   *saveimage;
    QPopupMenu   *savepixmap;
    QPopupMenu  *edit;
    QPopupMenu  *options;

    QWidget    *helpmsg;
    QLabel     *status;
    int         si, sp, ac, co, mo, fd, bd, // Menu item ids
                td, ta, ba, fa, au, ad, dd,
                ss, cc, t1, t8, t32;
    void        updateStatus();
    void        setMenuItemFlags();
    bool        reconvertImage();
    int         pickx, picky;
    int         clickx, clicky;
    bool        may_be_other;
    static ImageViewer* other;
    void        setImage(const QImage& newimage);

private slots:
    void        to1Bit();
    void        to8Bit();
    void        to32Bit();
    void        toBitDepth(int);

    void        copy();
    void        paste();

    void        hFlip();
    void        vFlip();
    void        rot180();

    void        editText();

    void        newWindow();
    void        openFile();
    void        saveImage(int);
    void        savePixmap(int);
    void        giveHelp();
    void        doOption(int);
    void        copyFrom(ImageViewer*);
};

#endif // SHOWIMG_H

Implementation:

/****************************************************************************
** $Id:  qt/showimg.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "showimg.h"
#include "imagetexteditor.h"
#include <qmenubar.h>
#include <qfiledialog.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qlabel.h>
#include <qpainter.h>
#include <qapplication.h>
#include <qclipboard.h>

/*
  In the constructor, we just pass the standard parameters on to
  QWidget.

  The menu uses a single slot to simplify the process of adding
  more items to the options menu.
*/
ImageViewer::ImageViewer( QWidget *parent, const char *name, int wFlags )
    : QWidget( parent, name, wFlags ),
      conversion_flags( PreferDither ),
      filename( 0 ),
      helpmsg( 0 )
{
    pickx = -1;
    picky = -1;
    clickx = -1;
    clicky = -1;
    alloc_context = 0;

    menubar = new QMenuBar(this);
    menubar->setSeparator( QMenuBar::InWindowsStyle );

    QStrList fmt = QImage::outputFormats();
    saveimage = new QPopupMenu( menubar );
    savepixmap = new QPopupMenu( menubar );
    for (const char* f = fmt.first(); f; f = fmt.next()) {
        saveimage->insertItem( f );
        savepixmap->insertItem( f );
    }
    connect( saveimage, SIGNAL(activated(int)), this, SLOT(saveImage(int)) );
    connect( savepixmap, SIGNAL(activated(int)), this, SLOT(savePixmap(int)) );

    file = new QPopupMenu( menubar );
    menubar->insertItem( "&File", file );
    file->insertItem( "&New window", this,  SLOT(newWindow()), CTRL+Key_N );
    file->insertItem( "&Open...", this,  SLOT(openFile()), CTRL+Key_O );
    si = file->insertItem( "Save image", saveimage );
    sp = file->insertItem( "Save pixmap", savepixmap );
    file->insertSeparator();
    file->insertItem( "E&xit", qApp,  SLOT(quit()), CTRL+Key_Q );

    edit =  new QPopupMenu( menubar );
    menubar->insertItem( "&Edit", edit );
    edit->insertItem("&Copy", this, SLOT(copy()), CTRL+Key_C);
    edit->insertItem("&Paste", this, SLOT(paste()), CTRL+Key_V);
    edit->insertSeparator();
    edit->insertItem("&Horizontal flip", this, SLOT(hFlip()), ALT+Key_H);
    edit->insertItem("&Vertical flip", this, SLOT(vFlip()), ALT+Key_V);
    edit->insertItem("&Rotate 180", this, SLOT(rot180()), ALT+Key_R);
    edit->insertSeparator();
    edit->insertItem("&Text...", this, SLOT(editText()));
    edit->insertSeparator();
    t1 = edit->insertItem( "Convert to &1 bit", this, SLOT(to1Bit()) );
    t8 = edit->insertItem( "Convert to &8 bit", this, SLOT(to8Bit()) );
    t32 = edit->insertItem( "Convert to &32 bit", this, SLOT(to32Bit()) );

    options =  new QPopupMenu( menubar );
    menubar->insertItem( "&Options", options );
    ac = options->insertItem( "AutoColor" );
    co = options->insertItem( "ColorOnly" );
    mo = options->insertItem( "MonoOnly" );
    options->insertSeparator();
    fd = options->insertItem( "DiffuseDither" );
    bd = options->insertItem( "OrderedDither" );
    td = options->insertItem( "ThresholdDither" );
    options->insertSeparator();
    ta = options->insertItem( "ThresholdAlphaDither" );
    ba = options->insertItem( "OrderedAlphaDither" );
    fa = options->insertItem( "DiffuseAlphaDither" );
    options->insertSeparator();
    ad = options->insertItem( "PreferDither" );
    dd = options->insertItem( "AvoidDither" );
    options->insertSeparator();
    ss = options->insertItem( "Smooth scaling" );
    cc = options->insertItem( "Use color context" );
    if ( QApplication::colorSpec() == QApplication::ManyColor )
        options->setItemEnabled( cc, FALSE );
    options->setCheckable( TRUE );
    setMenuItemFlags();

    menubar->insertSeparator();

    QPopupMenu* help = new QPopupMenu( menubar );
    menubar->insertItem( "&Help", help );
    help->insertItem( "Help!", this, SLOT(giveHelp()), CTRL+Key_H );

    connect( options, SIGNAL(activated(int)), this, SLOT(doOption(int)) );

    status = new QLabel(this);
    status->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
    status->setFixedHeight( fontMetrics().height() + 4 );

    setMouseTracking( TRUE );
}

ImageViewer::~ImageViewer()
{
    if ( alloc_context )
        QColor::destroyAllocContext( alloc_context );
    if ( other == this )
        other = 0;
}

/*
  This function modifies the conversion_flags when an options menu item
  is selected, then ensures all menu items are up to date, and reconverts
  the image if possibly necessary.
*/
void ImageViewer::doOption(int item)
{
    if ( item == ss || item == cc ) {
        // Toggle
        bool newbool = !options->isItemChecked(item);
        options->setItemChecked(item, newbool);
        // And reconvert...
        reconvertImage();
        repaint(image.hasAlphaBuffer());        // show image in widget
        return;
    }

    if ( options->isItemChecked( item ) ) return; // They are all radio buttons

    int ocf = conversion_flags;

    if ( item == ac ) {
        conversion_flags = conversion_flags & ~ColorMode_Mask | AutoColor;
    } else if ( item == co ) {
        conversion_flags = conversion_flags & ~ColorMode_Mask | ColorOnly;
    } else if ( item == mo ) {
        conversion_flags = conversion_flags & ~ColorMode_Mask | MonoOnly;
    } else if ( item == fd ) {
        conversion_flags = conversion_flags & ~Dither_Mask | DiffuseDither;
    } else if ( item == bd ) {
        conversion_flags = conversion_flags & ~Dither_Mask | OrderedDither;
    } else if ( item == td ) {
        conversion_flags = conversion_flags & ~Dither_Mask | ThresholdDither;
    } else if ( item == ta ) {
        conversion_flags = conversion_flags & ~AlphaDither_Mask | ThresholdAlphaDither;
    } else if ( item == fa ) {
        conversion_flags = conversion_flags & ~AlphaDither_Mask | DiffuseAlphaDither;
    } else if ( item == ba ) {
        conversion_flags = conversion_flags & ~AlphaDither_Mask | OrderedAlphaDither;
    } else if ( item == ad ) {
        conversion_flags = conversion_flags & ~DitherMode_Mask | PreferDither;
    } else if ( item == dd ) {
        conversion_flags = conversion_flags & ~DitherMode_Mask | AvoidDither;
    }

    if ( ocf != conversion_flags ) {
        setMenuItemFlags();
        // And reconvert...
        reconvertImage();
        repaint(image.hasAlphaBuffer());        // show image in widget
    }
}

/*
  Set the options menu to reflect the conversion_flags value.
*/
void ImageViewer::setMenuItemFlags()
{
    // File
    bool valid_image = pm.size() != QSize( 0, 0 );
    file->setItemEnabled( si, valid_image );
    file->setItemEnabled( sp, valid_image );

    // Edit
    edit->setItemEnabled( t1, image.depth() != 1 );
    edit->setItemEnabled( t8, image.depth() != 8 );
    edit->setItemEnabled( t32, image.depth() != 32 );

    // Options
    bool may_need_color_dithering =
            !valid_image
        || image.depth() == 32 && QPixmap::defaultDepth() < 24;
    bool may_need_dithering = may_need_color_dithering
         || image.depth() > 1 && options->isItemChecked(mo)
         || image.depth() > 1 && QPixmap::defaultDepth() == 1;
    bool has_alpha_mask = !valid_image || image.hasAlphaBuffer();

    options->setItemEnabled( fd, may_need_dithering );
    options->setItemEnabled( bd, may_need_dithering );
    options->setItemEnabled( td, may_need_dithering );

    options->setItemEnabled( ta, has_alpha_mask );
    options->setItemEnabled( fa, has_alpha_mask );
    options->setItemEnabled( ba, has_alpha_mask );

    options->setItemEnabled( ad, may_need_color_dithering );
    options->setItemEnabled( dd, may_need_color_dithering );

    options->setItemChecked( ac, (conversion_flags & ColorMode_Mask) == AutoColor );
    options->setItemChecked( co, (conversion_flags & ColorMode_Mask) == ColorOnly );
    options->setItemChecked( mo, (conversion_flags & ColorMode_Mask) == MonoOnly );
    options->setItemChecked( fd, (conversion_flags & Dither_Mask) == DiffuseDither );
    options->setItemChecked( bd, (conversion_flags & Dither_Mask) == OrderedDither );
    options->setItemChecked( td, (conversion_flags & Dither_Mask) == ThresholdDither );
    options->setItemChecked( ta, (conversion_flags & AlphaDither_Mask) == ThresholdAlphaDither );
    options->setItemChecked( fa, (conversion_flags & AlphaDither_Mask) == DiffuseAlphaDither );
    options->setItemChecked( ba, (conversion_flags & AlphaDither_Mask) == OrderedAlphaDither );
    options->setItemChecked( ad, (conversion_flags & DitherMode_Mask) == PreferDither );
    options->setItemChecked( dd, (conversion_flags & DitherMode_Mask) == AvoidDither );
}

void ImageViewer::updateStatus()
{
    if ( pm.size() == QSize( 0, 0 ) ) {
        if ( filename )
            status->setText("Could not load image");
        else
            status->setText("No image - select Open from File menu.");
    } else {
        QString message, moremsg;
        message.sprintf("%dx%d", image.width(), image.height());
        if ( pm.size() != pmScaled.size() ) {
            moremsg.sprintf(" [%dx%d]", pmScaled.width(),
                pmScaled.height());
            message += moremsg;
        }
        moremsg.sprintf(", %d bits ", image.depth());
        message += moremsg;
        if (image.valid(pickx,picky)) {
            moremsg.sprintf("(%d,%d)=#%0*x ",
                          pickx, picky,
                          image.hasAlphaBuffer() ? 8 : 6,
                          image.pixel(pickx,picky));
            message += moremsg;
        }
        if ( image.numColors() > 0 ) {
            if (image.valid(pickx,picky)) {
                moremsg.sprintf(", %d/%d colors", image.pixelIndex(pickx,picky),
                    image.numColors());
            } else {
                moremsg.sprintf(", %d colors", image.numColors());
            }
            message += moremsg;
        }
        if ( image.hasAlphaBuffer() ) {
            if ( image.depth() == 8 ) {
                int i;
                bool alpha[256];
                int nalpha=0;

                for (i=0; i<256; i++)
                    alpha[i] = FALSE;

                for (i=0; i<image.numColors(); i++) {
                    int alevel = image.color(i) >> 24;
                    if (!alpha[alevel]) {
                        alpha[alevel] = TRUE;
                        nalpha++;
                    }
                }
                moremsg.sprintf(", %d alpha levels", nalpha);
            } else {
                // Too many pixels to bother counting.
                moremsg = ", 8-bit alpha channel";
            }
            message += moremsg;
        }
        status->setText(message);
    }
}

/*
  This function saves the image.
*/
void ImageViewer::saveImage( int item )
{
    const char* fmt = saveimage->text(item);
    QString savefilename = QFileDialog::getSaveFileName(QString::null, QString::null,
                                        this, filename);
    if ( !savefilename.isEmpty() )
        if ( !image.save( savefilename, fmt ) )
            QMessageBox::warning( this, "Save failed", "Error saving file" );
}

/*
  This function saves the converted image.
*/
void ImageViewer::savePixmap( int item )
{
    const char* fmt = savepixmap->text(item);
    QString savefilename = QFileDialog::getSaveFileName(QString::null,
                                        QString::null, this, filename);
    if ( !savefilename.isEmpty() )
        if ( !pmScaled.save( savefilename, fmt ) )
            QMessageBox::warning( this, "Save failed", "Error saving file" );
}

void ImageViewer::newWindow()
{
    ImageViewer* that = new ImageViewer(0, "new window", WDestructiveClose);
    that->options->setItemChecked( that->cc, useColorContext() );
    that->show();
}

/*
  This function is the slot for processing the Open menu item.
*/
void ImageViewer::openFile()
{
    QString newfilename = QFileDialog::getOpenFileName();
    if ( !newfilename.isEmpty() ) {
        loadImage( newfilename ) ;
        repaint();                      // show image in widget
    }
}

/*
  This function loads an image from a file and resizes the widget to
  exactly fit the image size. If the file was not found or the image
  format was unknown it will resize the widget to fit the errorText
  message (see above) displayed in the current font.

  Returns TRUE if the image was successfully loaded.
*/

bool ImageViewer::loadImage( const char *fileName )
{
    filename = fileName;
    bool ok = FALSE;
    if ( filename ) {
        QApplication::setOverrideCursor( waitCursor ); // this might take time
        ok = image.load(filename, 0);
        pickx = -1;
        clickx = -1;
        if ( ok )
            ok = reconvertImage();
        if ( ok ) {
            setCaption( filename );                     // set window caption
            int w = pm.width();
            int h = pm.height();

            const int reasonable_width = 128;
            if ( w < reasonable_width ) {
                // Integer scale up to something reasonable
                int multiply = ( reasonable_width + w - 1 ) / w;
                w *= multiply;
                h *= multiply;
            }

            h += menubar->heightForWidth(w) + status->height();
            resize( w, h );                             // we resize to fit image
        } else {
            pm.resize(0,0);                             // couldn't load image
            update();
        }
        QApplication::restoreOverrideCursor();  // restore original cursor
    }
    updateStatus();
    setMenuItemFlags();
    return ok;
}

bool ImageViewer::reconvertImage()
{
    bool success = FALSE;

    if ( image.isNull() ) return FALSE;

    if ( alloc_context ) {
        QColor::destroyAllocContext( alloc_context );
        alloc_context = 0;
    }
    if ( useColorContext() ) {
        alloc_context = QColor::enterAllocContext();
        // Clear the image to hide flickering palette
        QPainter painter(this);
        painter.eraseRect(0, menubar->heightForWidth( width() ), width(), height());
    }

    QApplication::setOverrideCursor( waitCursor ); // this might take time
    if ( pm.convertFromImage(image, conversion_flags) )
    {
        pmScaled = QPixmap();
        scale();
        resize( width(), height() );
        success = TRUE;                         // load successful
    } else {
        pm.resize(0,0);                         // couldn't load image
    }
    updateStatus();
    setMenuItemFlags();
    QApplication::restoreOverrideCursor();      // restore original cursor

    if ( useColorContext() )
        QColor::leaveAllocContext();

    return success;                             // TRUE if loaded OK
}

bool ImageViewer::smooth() const
{
    return options->isItemChecked(ss);
}

bool ImageViewer::useColorContext() const
{
    return options->isItemChecked(cc);
}

/*
  This functions scales the pixmap in the member variable "pm" to fit the
  widget size and  puts the resulting pixmap in the member variable "pmScaled".
*/

void ImageViewer::scale()
{
    int h = height() - menubar->heightForWidth( width() ) - status->height();

    if ( image.isNull() ) return;

    QApplication::setOverrideCursor( waitCursor ); // this might take time
    if ( width() == pm.width() && h == pm.height() )
    {                                           // no need to scale if widget
        pmScaled = pm;                          // size equals pixmap size
    } else {
        if (smooth()) {
            pmScaled.convertFromImage(image.smoothScale(width(), h),
                conversion_flags);
        } else {
            QWMatrix m;                         // transformation matrix
            m.scale(((double)width())/pm.width(),// define scale factors
                    ((double)h)/pm.height());
            pmScaled = pm.xForm( m );           // create scaled pixmap
        }
    }
    QApplication::restoreOverrideCursor();      // restore original cursor
}

/*
  The resize event handler, if a valid pixmap was loaded it will call
  scale() to fit the pixmap to the new widget size.
*/

void ImageViewer::resizeEvent( QResizeEvent * )
{
    status->setGeometry(0, height() - status->height(),
                        width(), status->height());

    if ( pm.size() == QSize( 0, 0 ) )           // we couldn't load the image
        return;

    int h = height() - menubar->heightForWidth( width() ) - status->height();
    if ( width() != pmScaled.width() || h != pmScaled.height())
    {                                           // if new size,
        scale();                                // scale pmScaled to window
        updateStatus();
    }
    if ( image.hasAlphaBuffer() )
        erase();
}

bool ImageViewer::convertEvent( QMouseEvent* e, int& x, int& y)
{
    if ( pm.size() != QSize( 0, 0 ) ) {
        int h = height() - menubar->heightForWidth( width() ) - status->height();
        int nx = e->x() * image.width() / width();
        int ny = (e->y()-menubar->heightForWidth( width() )) * image.height() / h;
        if (nx != x || ny != y ) {
            x = nx;
            y = ny;
            updateStatus();
            return TRUE;
        }
    }
    return FALSE;
}

void ImageViewer::mousePressEvent( QMouseEvent *e )
{
    may_be_other = convertEvent(e, clickx, clicky);
}

void ImageViewer::mouseReleaseEvent( QMouseEvent * )
{
    if ( may_be_other )
        other = this;
}

/*
  Record the pixel position of interest.
*/
void ImageViewer::mouseMoveEvent( QMouseEvent *e )
{
    if (convertEvent(e,pickx,picky)) {
        updateStatus();
        if ((e->state()&LeftButton)) {
            may_be_other = FALSE;
            if ( clickx >= 0 && other) {
                copyFrom(other);
            }
        }
    }
}

/*
  Draws the portion of the scaled pixmap that needs to be updated or prints
  an error message if no legal pixmap has been loaded.
*/

void ImageViewer::paintEvent( QPaintEvent *e )
{
    if ( pm.size() != QSize( 0, 0 ) ) {         // is an image loaded?
        QPainter painter(this);
        painter.setClipRect(e->rect());
        painter.drawPixmap(0, menubar->heightForWidth( width() ), pmScaled);
    }
}

/*
  Explain anything that might be confusing.
*/
void ImageViewer::giveHelp()
{
    if (!helpmsg) {
        QString helptext =
            "<b>Usage:</b> <tt>showimg [-m] <i>filename ...</i></tt>"
            "<blockquote>"
                "<tt>-m</tt> - use <i>ManyColor</i> color spec"
            "</blockquote>"
            "<p>Supported input formats:"
            "<blockquote>";
        helptext += QImage::inputFormatList().join(", ");
        helptext += "</blockquote>";

        helpmsg = new QMessageBox( "Help", helptext,
            QMessageBox::Information, QMessageBox::Ok, 0, 0, 0, 0, FALSE );
    }
    helpmsg->show();
    helpmsg->raise();
}

void ImageViewer::copyFrom(ImageViewer* s)
{
    if ( clickx >= 0 ) {
        int dx = clickx;
        int dy = clicky;
        int sx = s->clickx;
        int sy = s->clicky;
        int sw = QABS(clickx - pickx)+1;
        int sh = QABS(clicky - picky)+1;
        if ( clickx > pickx ) {
            dx = pickx;
            sx -= sw-1;
        }
        if ( clicky > picky ) {
            dy = picky;
            sy -= sh-1;
        }
        bitBlt( &image, dx, dy, &s->image, sx, sy, sw, sh );
        reconvertImage();
        repaint( image.hasAlphaBuffer() );
    }
}
ImageViewer* ImageViewer::other = 0;

void ImageViewer::hFlip()
{
    setImage(image.mirror(TRUE,FALSE));
}

void ImageViewer::vFlip()
{
    setImage(image.mirror(FALSE,TRUE));
}

void ImageViewer::rot180()
{
    setImage(image.mirror(TRUE,TRUE));
}

void ImageViewer::copy()
{
#ifndef QT_NO_MIMECLIPBOARD
    QApplication::clipboard()->setImage(image); // Less information loss
#endif
}

void ImageViewer::paste()
{
#ifndef QT_NO_MIMECLIPBOARD
    QImage p = QApplication::clipboard()->image();
    if ( !p.isNull() ) {
        filename = "pasted";
        setImage(p);
    }
#endif
}

void ImageViewer::setImage(const QImage& newimage)
{
    image = newimage;

    pickx = -1;
    clickx = -1;
    setCaption( filename );                     // set window caption
    int w = image.width();
    int h = image.height();
    if ( !w )
        return;

    const int reasonable_width = 128;
    if ( w < reasonable_width ) {
        // Integer scale up to something reasonable
        int multiply = ( reasonable_width + w - 1 ) / w;
        w *= multiply;
        h *= multiply;
    }

    h += menubar->heightForWidth(w) + status->height();
    resize( w, h );                             // we resize to fit image

    reconvertImage();
    repaint( image.hasAlphaBuffer() );

    updateStatus();
    setMenuItemFlags();
}

void ImageViewer::editText()
{
    ImageTextEditor editor(image,this);
    editor.exec();
}

void ImageViewer::to1Bit()
{
    toBitDepth(1);
}

void ImageViewer::to8Bit()
{
    toBitDepth(8);
}

void ImageViewer::to32Bit()
{
    toBitDepth(32);
}

void ImageViewer::toBitDepth(int d)
{
    image = image.convertDepth(d);
    reconvertImage();
    repaint( image.hasAlphaBuffer() );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "showimg.h"
#include "imagefip.h"
#include <qapplication.h>
#include <qimage.h>

int main( int argc, char **argv )
{
    if ( argc > 1 && QString(argv[1]) == "-m" ) {
        QApplication::setColorSpec( QApplication::ManyColor );
        argc--;
        argv++;
    }
    else if ( argc > 1 && QString(argv[1]) == "-n" ) {
        QApplication::setColorSpec( QApplication::NormalColor );
        argc--;
        argv++;
    }
    else {
        QApplication::setColorSpec( QApplication::CustomColor );
    }

    QApplication::setFont( QFont("Helvetica", 12) );
    QApplication a( argc, argv );

    ImageIconProvider iip;
    QFileDialog::setIconProvider( &iip );

    if ( argc <= 1 ) {
        // Create a window which looks after its own existence.
        ImageViewer *w =
            new ImageViewer(0, "new window", Qt::WDestructiveClose | Qt::WResizeNoErase );
        w->setCaption("Qt Example - Image Viewer");
        w->show();
    } else {
        for ( int i=1; i<argc; i++ ) {
            // Create a window which looks after its own existence.
            ImageViewer *w =
                new ImageViewer(0, argv[i], Qt::WDestructiveClose | Qt::WResizeNoErase );
            w->setCaption("Qt Example - Image Viewer");
            w->loadImage( argv[i] );
            w->show();
        }
    }

    QObject::connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));

    return a.exec();
}

See also Examples.


Walkthrough: A Simple Application

This walkthrough shows simple use of QMainWindow, QMenuBar, QPopupMenu, QToolBar and QStatusBar - classes that every modern application window tends to use.

It further illustrates some aspects of QWhatsThis (for simple help) and a typical main() using QApplication.

Finally, it shows a typical printout function based on QPrinter.

The declaration of ApplicationWindow

Here's the header file in full:

/****************************************************************************
** $Id:  qt/application.h   3.0.5   edited May 7 17:30 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef APPLICATION_H
#define APPLICATION_H

#include <qmainwindow.h>

class QTextEdit;

class ApplicationWindow: public QMainWindow
{
    Q_OBJECT

public:
    ApplicationWindow();
    ~ApplicationWindow();

protected:
    void closeEvent( QCloseEvent* );

private slots:
    void newDoc();
    void choose();
    void load( const QString &fileName );
    void save();
    void saveAs();
    void print();

    void about();
    void aboutQt();

private:
    QPrinter *printer;
    QTextEdit *e;
    QString filename;
};

#endif

It declares a class that inherits QMainWindow, with slots and private variables. The class predeclaration of QTextEdit at the beginning (instead of an include) helps to speed up compiles. With this trick, make depend won't insist on recompiling every .cpp file that includes application.h when qtextedit.h changes.

A simple main()

Let's first have a look at examples/main.cpp, in full ...

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "application.h"

int main( int argc, char ** argv ) {
    QApplication a( argc, argv );
    ApplicationWindow * mw = new ApplicationWindow();
    mw->setCaption( "Qt Example - Application" );
    mw->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    return a.exec();
}

... and go over main() in detail.

    int main( int argc, char ** argv ) {
        QApplication a( argc, argv );

With the above line, we create a QApplication object with the usual constructor and let it parse argc and argv. QApplication itself takes care of X11-specific command-line options like -geometry, thus the program automatically behaves the way X clients are expected to.

        ApplicationWindow * mw = new ApplicationWindow();
        mw->setCaption( "Qt Example - Application" );
        mw->show();

We create an ApplicationWindow as a top-level widget, set its window system caption to "Document 1", and show() it.

        a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );

When the application's last window is closed, it should quit. Both, the signal and the slot are predefined members of QApplication.

        return a.exec();

Having completed the application's initialization, we start the main event loop (the GUI), and eventually return the error code that QApplication returns when it leaves the event loop.

    }

The Implementation of ApplicationWindow

Since the implementation is quite large (almost 300 lines) we won't bore you with the preliminary headerfile #includes. Before we start with the constructor there are however three #include lines worth mentioning:

    #include "filesave.xpm"
    #include "fileopen.xpm"
    #include "fileprint.xpm"

The tool buttons in our application wouldn't be real without icons. These icons can be found in the above xpm files. If you ever moved a program to a different location and wondered why icons were missing afterwards you will probably agree that it is a good idea to compile them into the binary. This is what we are doing here.

    ApplicationWindow::ApplicationWindow()
        : QMainWindow( 0, "example application main window", WDestructiveClose )
    {

ApplicationWindow inherits QMainWindow, the Qt class that provides typical application main windows, with menu bars, toolbars, etc.

        printer = new QPrinter;

The application example can print things, and we chose to have a QPrinter object lying around so that when the user changes a setting during one printing, the new setting will be the default next time.

        QPixmap openIcon, saveIcon, printIcon;

For simplicity reasons, our example has no more than three commands in the toolbar. The above variables are used to hold an icon for each of them.

        QToolBar * fileTools = new QToolBar( this, "file operations" );

We create a toolbar in this window ...

        fileTools->setLabel( "File Operations" );

... and define a title for it. When a user drags the toolbar out of its location and drops it somewhere on the desktop, the toolbar-window will show "File Operations" as caption.

        openIcon = QPixmap( fileopen );
        QToolButton * fileOpen
            = new QToolButton( openIcon, "Open File", QString::null,
                               this, SLOT(choose()), fileTools, "open file" );

Now we create the first tool button for the fileTools toolbar with the appropriate icon and the tool-tip text "Open File". The fileopen.xpm we included at the beginning contains the definition of a pixmap named fileopen. This we use as the icon to illustrate our first tool button.

        saveIcon = QPixmap( filesave );
        QToolButton * fileSave
            = new QToolButton( saveIcon, "Save File", QString::null,
                               this, SLOT(save()), fileTools, "save file" );

        printIcon = QPixmap( fileprint );
        QToolButton * filePrint
            = new QToolButton( printIcon, "Print File", QString::null,
                               this, SLOT(print()), fileTools, "print file" );

Likewise we create two more tool buttons in this toolbar, each with appropriate icons and tool-tip text. All three buttons are connected to appropriate slots in this object; for example, the "Print File" button to ApplicationWindow::print().

        (void)QWhatsThis::whatsThisButton( fileTools );

The fourth button in the toolbar is somewhat peculiar: it's the one that provides "What's This?" help. This must be set up using a special function, as its mouse interface is different from usual.

        const char * fileOpenText = "<p><img source=\"fileopen\"> "
                     "Click this button to open a <em>new file</em>. <br>"
                     "You can also select the <b>Open</b> command "
                     "from the <b>File</b> menu.</p>";

        QWhatsThis::add( fileOpen, fileOpenText );

With the above line we add the "What's This?" help-text to the fileOpen button...

        QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen", openIcon );

... and tell the rich-text engine that when a help-text (like the one saved in fileOpenText) requests an image named "fileopen", the openIcon pixmap is used.

        const char * fileSaveText = "<p>Click this button to save the file you "
                     "are editing. You will be prompted for a file name.\n"
                     "You can also select the <b>Save</b> command "
                     "from the <b>File</b> menu.</p>";

        QWhatsThis::add( fileSave, fileSaveText );
        const char * filePrintText = "Click this button to print the file you "
                     "are editing.\n You can also select the Print "
                     "command from the File menu.";

        QWhatsThis::add( filePrint, filePrintText );

The "What's This?" help of the remaining two buttons doesn't make use of pixmaps, therefore all we have to do is to add the help-text to the button. Be however careful: To invoke the rich-text elements in fileSaveText, the entire string must be surrounded by <p> and </p>. In filePrintText, we don't have rich-text elements, so this is not necessary.

        QPopupMenu * file = new QPopupMenu( this );
        menuBar()->insertItem( "&File", file );

Next we create a QPopupMenu for the File menu and add it to the menu bar. With the ampersand previous to the letter F, we allow the user to use the shortcut Alt+F to open this menu.

        file->insertItem( "&New", this, SLOT(newDoc()), CTRL+Key_N );

Its first entry is connected to the (yet to be implementled) slot newDoc(). When the user chooses this New entry (e.g. via typing the letter N as marked by the ampersand) or uses the Ctrl+N accelerator, a new editor-window will pop up.

        int id;
        id = file->insertItem( openIcon, "&Open...",
                               this, SLOT(choose()), CTRL+Key_O );
        file->setWhatsThis( id, fileOpenText );

        id = file->insertItem( saveIcon, "&Save",
                               this, SLOT(save()), CTRL+Key_S );
        file->setWhatsThis( id, fileSaveText );

        id = file->insertItem( "Save &As...", this, SLOT(saveAs()) );
        file->setWhatsThis( id, fileSaveText );

We populate the File menu with three more commands (Open, Save and Save As), and set "What's This?" help for them. Note in particular that "What's This?" help and pixmaps are used in both the toolbar (above) and the menu bar (here).

        file->insertSeparator();

Then we insert a separator, ...

        id = file->insertItem( printIcon, "&Print...",
                               this, SLOT(print()), CTRL+Key_P );
        file->setWhatsThis( id, filePrintText );

        file->insertSeparator();

        file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_W );
        file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );

... the Print command with "What's This?" help, another separator and two more commands (Close and Quit) without "What's This?" and pixmaps. In case of the Close command, the signal is connected to the close() slot of the respective ApplicationWindow object whilst the Quit command affects the entire application.

Because ApplicationWindow is a QWidget, the close() function triggers a call to closeEvent() which we will implement later.

        menuBar()->insertSeparator();

Now that we are done with the File menu we shift our focus back to the menu bar and insert a separator. From now on further menu bar entries will be aligned to the right if the windows system style suggests so.

        QPopupMenu * help = new QPopupMenu( this );
        menuBar()->insertItem( "&Help", help );

        help->insertItem( "&About", this, SLOT(about()), Key_F1 );
        help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
        help->insertSeparator();
        help->insertItem( "What's &This", this, SLOT(whatsThis()), SHIFT+Key_F1 );

We create a Help menu, add it to the menu bar, and insert a few commands. Depending on the style it will appear on the right hand side of the menu bar or not.

        e = new QTextEdit( this, "editor" );
        e->setFocus();
        setCentralWidget( e );

Now we create a simple text-editor, set the initial focus to it, and make it the central widget of this window.

QMainWindow::centralWidget() is the heart of the entire application: It's what menu bar, statusbar and toolbars are all arranged around. Since the central widget is a text editing widget, we reveal at this line that our simple application is a text editor. :)

        statusBar()->message( "Ready", 2000 );

We make the statusbar say "Ready" for two seconds at startup, just to tell the user that this window has finished initialization and can be used.

        resize( 450, 600 );

Finally it's time to resize the new window to a a nice default size.

    }

At this stage, we are done with the constructor. Among others we have learned about the classic way of creating menus and toolbars. There is however a more modern approach to deal with this: actions that help you saving some work. You may have a look at how the ApplicationWindow constructor is implemented using actions. Here we'll continue with the destructor.

    ApplicationWindow::~ApplicationWindow()
    {
        delete printer;
    }

The only thing an ApplicationWindow widget needs to do in its destructor is to delete the printer it created. All other objects are child widgets, which Qt will delete as appropriate.

Now our task is to implement all the slots mentioned in the header file and used in the constructor.

    void ApplicationWindow::newDoc()
    {
        ApplicationWindow *ed = new ApplicationWindow;
        ed->setCaption("Qt Example - Application");
        ed->show();
    }

This slot, connected to the File->New menu item, simply creates a new ApplicationWindow and shows it.

    void ApplicationWindow::choose()
    {
        QString fn = QFileDialog::getOpenFileName( QString::null, QString::null,
                                                   this);
        if ( !fn.isEmpty() )
            load( fn );
        else
            statusBar()->message( "Loading aborted", 2000 );
    }

The choose() slot is connected to the Open menu item and tool button. With a little help from QFileDialog::getOpenFileName(), it asks the user for a file name and then either loads that file or gives an error message in the statusbar.

    void ApplicationWindow::load( const QString &fileName )
    {
        QFile f( fileName );
        if ( !f.open( IO_ReadOnly ) )
            return;

        QTextStream ts( &f );
        e->setText( ts.read() );
        e->setModified( FALSE );
        setCaption( fileName );
        statusBar()->message( "Loaded document " + fileName, 2000 );
    }

This function loads a file into the editor. When it's done, it sets the window system caption to the file name and displays a success message in the statusbar for two seconds. With files that exist but are not readable, nothing happens.

    void ApplicationWindow::save()
    {
        if ( filename.isEmpty() ) {
            saveAs();
            return;
        }

        QString text = e->text();
        QFile f( filename );
        if ( !f.open( IO_WriteOnly ) ) {
            statusBar()->message( QString("Could not write to %1").arg(filename),
                                  2000 );
            return;
        }

        QTextStream t( &f );
        t << text;
        f.close();

As its name suggests, this function saves the current file. If no filename has been specified so far, the saveAs() routine is called. Unwritable files cause the ApplicationWindow object to provide an error-message in the statusbar. Note that there are more than one possibilities to achieve this: compare the above statusBar()->message() line with the appropriate code in the load() function.

        e->setModified( FALSE );

Tell the editor that the contents haven't been edited since the last save. When the user does some further editing and wishes to close the window without explicit saving, ApplicationWindow::closeEvent() will ask about it.

        setCaption( filename );

It may be that the document was saved under a different name than the old caption suggests, so we set the window caption just to be sure.

        statusBar()->message( QString( "File %1 saved" ).arg( filename ), 2000 );
    }

With a message in the statusbar, we inform the user that the file was saved successfully.

    void ApplicationWindow::saveAs()
    {
        QString fn = QFileDialog::getSaveFileName( QString::null, QString::null,
                                                   this );
        if ( !fn.isEmpty() ) {
            filename = fn;
            save();
        } else {
            statusBar()->message( "Saving aborted", 2000 );
        }
    }

This function asks for a new name, saves the document under that name, and implicitly changes the window system caption to the new name.

    void ApplicationWindow::print()
    {

        const int Margin = 10;
        int pageNo = 1;

print() is called by the File->Print menu item and the filePrint tool button.

Because we don't want to print to the very edges of the paper, we use a little margin: 10 points. Furthermore we keep track of the page count.

        if ( printer->setup(this) ) {               // printer dialog

QPrinter::setup() invokes a print dialog, configures the printer object, and returns TRUE if the user wants to print or FALSE if not. So we test the return value; if it's TRUE, we...

            statusBar()->message( "Printing..." );

... set a statusbar message in case printing takes a while.

            QPainter p;
            if( !p.begin( printer ) )               // paint on printer
                return;

We create a painter for the output and decide that we wish to paint on the printer or do nothing at all.

            p.setFont( e->font() );
            int yPos        = 0;                    // y-position for each line
            QFontMetrics fm = p.fontMetrics();
            QPaintDeviceMetrics metrics( printer ); // need width/height
                                                    // of printer surface

Then we select the font our QTextEdit object returns as its current one, and set up some variables we'll need.

            for( int i = 0 ; i < e->lines() ; i++ ) {

As long as the editing widget contains more lines, we want to print them.

                if ( Margin + yPos > metrics.height() - Margin ) {

Before we print a line, we make sure that there is space for it on the current page. If not, we start a new page:

                    QString msg( "Printing (page " );
                    msg += QString::number( ++pageNo );
                    msg += ")...";
                    statusBar()->message( msg );
                    printer->newPage();             // no more room on this page
                    yPos = 0;                       // back to top of page

(Four lines to tell the user what we're doing, two lines to do it.)

                }

Now we know that there's space for the current line ...

                p.drawText( Margin, Margin + yPos,
                            metrics.width(), fm.lineSpacing(),
                            ExpandTabs | DontClip,
                            e->text( i ) );

... and we use the painter to print it.

In Qt, output to printers uses the exact same code as output to screen, pixmaps and picture metafiles. Therefore, we don't call a QPrinter function to draw text, but a QPainter function. QPainter works on all the output devices mentioned and has a device independent API. Most of its code is device independent, too, therefore it is less likely that your application will have odd bugs. (If the same code is used to print and to draw on the screen, it's less likely that you'll have print-only or screen-only bugs.)

                yPos = yPos + fm.lineSpacing();

With this line, we keep count of how much of the paper we've used so far.

            }
            p.end();                                // send job to printer

At this point we've printed all of the text in the editing widget and told the printer to finish off the last page.

            statusBar()->message( "Printing completed", 2000 );

Finally the user receives the message that we're done.

        } else {
            statusBar()->message( "Printing aborted", 2000 );
        }

If the user did not want to print (and QPrinter::setup() returned FALSE), we inform him or her about it.

    }

With this little effort we have printed a text document. So let's care about what happens when a user wishes to close() an ApplicationWindow.

    void ApplicationWindow::closeEvent( QCloseEvent* ce )
    {

This event gets to process window system close events. A close event is subtly different from a hide event: hide often means "iconify" whereas close means that the window is going away for good.

        if ( !e->isModified() ) {
            ce->accept();
            return;
        }

If the text hasn't been edited, we just accept the event. The window will be closed, and because we used the WDestructiveClose widget flag in the \e ApplicationWindow() constructor, the widget will be deleted.

        switch( QMessageBox::information( this, "Qt Application Example",
                                          "Do you want to save the changes"
                                          " to the document?",
                                          "Yes", "No", "Cancel",
                                          0, 1 ) ) {

Otherwise we ask the user: What do you want to do?

        case 0:
            save();
            ce->accept();
            break;

If he/she wants to save and then exit, we do that.

        case 1:
            ce->accept();
            break;

If the user however doesn't want to exit, we ignore the close event (there is a chance that we can't block it but we try).

        case 2:
        default: // just for sanity
            ce->ignore();
            break;

The last case -- the user wants to abandon the edits and exit -- is very simple.

        }
    }

Last but not least we implement the slots used by the help menu entries.

    void ApplicationWindow::about()
    {
        QMessageBox::about( this, "Qt Application Example",
                            "This example demonstrates simple use of "
                            "QMainWindow,\nQMenuBar and QToolBar.");
    }

    void ApplicationWindow::aboutQt()
    {
        QMessageBox::aboutQt( this, "Qt Application Example" );
    }

These two slots use ready-made "about" functions to provide some information about this program and the GUI toolkit it uses. (Although you don't need to provide an About Qt in your programs, if you use Qt for free we would appreciate it if you tell people what you're using.)

That was all we needed to write a complete, almost useful application with nice help-functions, almost as good as the "editors" some computer vendors ship with their desktops, in less than 300 lines of code. As we promised - a simple application.

See also Step-by-step Examples.


Walkthrough: A Simple Application with Actions

While reading through the implementation of the ApplicationWindow constructor you have maybe asked yourself: "The fileOpen tool-button in the toolbar does exactly the same thing as the File->Open menu-entry. Their "What's this?" help is the same, the icons common, the same slot is connected to both them ... Shouldn't it be possible to save some code and don't invent the wheel twice?"

Indeed, it is. In modern GUI-application programming you will use so called actions to do this. An action collects all the common items (icon, tooltip, menu-entry text, shortcuts, "What's this?" help-text and what to do -- the actual action) together. Whenever this action is required (in the toolbar, as a menu-entry) all the programmer has to do is to insert the action in the respective toolbar or menu. Its appearance (as a tool-button or a menu-entry) is something, the programmer does not has to worry about -- it's obvious from the context.

With the QAction class, Qt provides you with everything you need to use this striking concept. So let's write an ApplicationWindow constructor that makes use of actions.

The ApplicationWindow constructor with Actions

    ApplicationWindow::ApplicationWindow()
        : QMainWindow( 0, "example application main window", WDestructiveClose )
    {
        printer = new QPrinter;

Nothing new so far. But with the next lines...

        QAction * fileNewAction;
        QAction * fileOpenAction;
        QAction * fileSaveAction, * fileSaveAsAction, * filePrintAction;
        QAction * fileCloseAction, * fileQuitAction;

... the difference becomes obvious. Here we define the actions our application is supposed to undertake: it should create a new editor-instance (fileNewAction), open a file, save a file, save it under a different name, print the content of the editor, close an editor window and quit the entire application.

        fileNewAction = new QAction( "New", "&New", CTRL+Key_N, this, "new" );

The first one has the name new and can be reached via the accelerator Ctrl+N. When used as a menu-entry it will provide the entry New and can be reached via the accelerator Alt-N (&N). As we won't set a special tooltip-text, the text New with the accelerator Ctrl+N in brackets will show up when a user holds the mouse over a tool-button and does nothing.

        connect( fileNewAction, SIGNAL( activated() ) , this,
                 SLOT( newDoc() ) );

When the action becomes activated (the user chooses the respective menu-entry or clicks an appropriate tool-button), it connects to the newDoc() slot.

        fileOpenAction = new QAction( "Open File", QPixmap( fileopen ), "&Open",
                                      CTRL+Key_O, this, "open" );
        connect( fileOpenAction, SIGNAL( activated() ) , this, SLOT( choose() ) );

The same way we create an Open File action and connect its activated() signal to the choose() slot. There is however a novelty: the fileOpenAction (unlike fileNewAction) is assigned a pixmap (the one included with the fileopen.xpm file).

        const char * fileOpenText = "<p><img source=\"fileopen\"> "
                         "Click this button to open a <em>new file</em>. <br>"
                         "You can also select the <b>Open</b> command "
                         "from the <b>File</b> menu.</p>";

For the fileOpenAction we want to provide "What's This?" help and therefore define an appropriate rich-text.

        QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen",
                              fileOpenAction->iconSet().pixmap() );

As fileOpenText makes use of a pixmap, we have to inform the rich-text engine that it should provide the pixmap defined for fileOpenAction whenever a rich-text asks for an image-source named fileopen.

The slightly complex procedure to gain the pixmap from the action is due to the fact that a QAction is not simply assigned a pixmap but an entire iconset. A QIconSet provides up to six pixmaps suited for different sizes (large, small) and modes (active, disabled etc.). As we initially fed fileOpenAction with just one pixmap its iconset will be calculated from it automatically.

For simplicity reasons we want the icon in the "What's this?" text to be the same we used in the fileOpenAction constructor. This is done by using QIconSet::pixmap() upon fileOpenAction's iconSet().

        fileOpenAction->setWhatsThis( fileOpenText );

Finally we assign "What's this?" help to the fileOpenAction.

        fileSaveAction = new QAction( "Save File", QPixmap( filesave ),
                                      "&Save", CTRL+Key_S, this, "save" );
        connect( fileSaveAction, SIGNAL( activated() ) , this, SLOT( save() ) );

        const char * fileSaveText = "<p>Click this button to save the file you "
                         "are editing. You will be prompted for a file name.\n"
                         "You can also select the <b>Save</b> command "
                         "from the <b>File</b> menu.</p>";
        fileSaveAction->setWhatsThis( fileSaveText );

The same way we create a Save File action with a pixmap, "What's this?" help and the more common items like menu-entry text and accelerator. Note that we don't have to bother with the rich-text engine because the pixmap is not used in fileSaveText. When activated the fileSaveAction will call the save() slot.

        fileSaveAsAction = new QAction( "Save File As", "Save &as", 0,  this,
                                        "save as" );
        connect( fileSaveAsAction, SIGNAL( activated() ) , this,
                 SLOT( saveAs() ) );
        fileSaveAsAction->setWhatsThis( fileSaveText );

For the Save File As action we reuse fileSaveText but do without a pixmap. On activation, this action calls the saveAs() slot.

        filePrintAction = new QAction( "Print File", QPixmap( fileprint ),
                                       "&Print", CTRL+Key_P, this, "print" );
        connect( filePrintAction, SIGNAL( activated() ) , this,
                 SLOT( print() ) );

        const char * filePrintText = "Click this button to print the file you "
                         "are editing.\n You can also select the Print "
                         "command from the File menu.";
        filePrintAction->setWhatsThis( filePrintText );

The Print File action -- with an activated() signal connected to print() -- looks very much like fileSaveText.

        fileCloseAction = new QAction( "Close", "&Close", CTRL+Key_W, this,
                                       "close" );
        connect( fileCloseAction, SIGNAL( activated() ) , this,
                 SLOT( close() ) );
        fileQuitAction = new QAction( "Quit", "&Quit", CTRL+Key_Q, this,
                                      "quit" );
        connect( fileQuitAction, SIGNAL( activated() ) , qApp,
                 SLOT( closeAllWindows() ) );

For the last two actions, fileCloseAction and fileQuitAction, we do it the easy way: no "What's this?", no pixmaps. Thus we have defined all the actions we need.

The only thing left is to use them as menu- and toolbar-entries.

        // populate a tool bar with some actions

        QToolBar * fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );

First we create a toolbar in this window and define a caption for it.

As actions that weren't assigned a pixmap are quite useless in a toolbar we'll restrict ourselves to three tool-buttons for opening, saving and printing files.

        fileOpenAction->addTo( fileTools );

The first tool-button is easily installed: All we have to do is to add the fileOpenAction to the fileTools toolbar.

        fileSaveAction->addTo( fileTools );
        filePrintAction->addTo( fileTools );

The same easy procedure applies to fileSaveAction and filePrintAction.

        (void)QWhatsThis::whatsThisButton( fileTools );

To provide the user with a means to toggle his or her mouse in "What's this?" mode, we need a fourth icon in the toolbar: the (predefined) "What's this?" button.

        // populate a menu with all actions

        QPopupMenu * file = new QPopupMenu( this );
        menuBar()->insertItem( "&File", file );

Next we install the newly created file popup-menu in the menu bar. After we're done with this, we populate the menu ...

        fileNewAction->addTo( file );
        fileOpenAction->addTo( file );
        fileSaveAction->addTo( file );
        fileSaveAsAction->addTo( file );

... with some menu-entries derived from actions, ...

        file->insertSeparator();

... a separator ...

        filePrintAction->addTo( file );
        file->insertSeparator();
        fileCloseAction->addTo( file );
        fileQuitAction->addTo( file );

... and more actions and separators.

The rest of the constructor ...

        menuBar()->insertSeparator();

        // add a help menu

        QPopupMenu * help = new QPopupMenu( this );
        menuBar()->insertItem( "&Help", help );
        help->insertItem( "&About", this, SLOT(about()), Key_F1 );
        help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
        help->insertSeparator();
        help->insertItem( "What's &This", this, SLOT(whatsThis()),
                          SHIFT+Key_F1 );

        // create and define the central widget

        e = new QTextEdit( this, "editor" );
        e->setFocus();
        setCentralWidget( e );
        statusBar()->message( "Ready", 2000 );

        resize( 450, 600 );
    }

... is exactly the same as in the tool-button and menu-entry version.

See also Step-by-step Examples.


A Complete Application Window

This example program looks like a complete modern application. It has a menu bar, it has a tool bar, it has a status bar and works like a simple text editor.

There is a walkthrough of this example.

Header file:

/****************************************************************************
** $Id:  qt/application.h   3.0.5   edited May 7 17:30 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef APPLICATION_H
#define APPLICATION_H

#include <qmainwindow.h>

class QTextEdit;

class ApplicationWindow: public QMainWindow
{
    Q_OBJECT

public:
    ApplicationWindow();
    ~ApplicationWindow();

protected:
    void closeEvent( QCloseEvent* );

private slots:
    void newDoc();
    void choose();
    void load( const QString &fileName );
    void save();
    void saveAs();
    void print();

    void about();
    void aboutQt();

private:
    QPrinter *printer;
    QTextEdit *e;
    QString filename;
};

#endif

Implementation:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2002 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "application.h"

#include <qimage.h>
#include <qpixmap.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qtextedit.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qprinter.h>
#include <qapplication.h>
#include <qaccel.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qwhatsthis.h>

#include "filesave.xpm"
#include "fileopen.xpm"
#include "fileprint.xpm"

ApplicationWindow::ApplicationWindow()
    : QMainWindow( 0, "example application main window", WDestructiveClose )
{
    printer = new QPrinter;
    QPixmap openIcon, saveIcon, printIcon;

    QToolBar * fileTools = new QToolBar( this, "file operations" );
    fileTools->setLabel( "File Operations" );

    openIcon = QPixmap( fileopen );
    QToolButton * fileOpen
        = new QToolButton( openIcon, "Open File", QString::null,
                           this, SLOT(choose()), fileTools, "open file" );

    saveIcon = QPixmap( filesave );
    QToolButton * fileSave
        = new QToolButton( saveIcon, "Save File", QString::null,
                           this, SLOT(save()), fileTools, "save file" );

    printIcon = QPixmap( fileprint );
    QToolButton * filePrint
        = new QToolButton( printIcon, "Print File", QString::null,
                           this, SLOT(print()), fileTools, "print file" );

    (void)QWhatsThis::whatsThisButton( fileTools );

    const char * fileOpenText = "<p><img source=\"fileopen\"> "
                 "Click this button to open a <em>new file</em>. <br>"
                 "You can also select the <b>Open</b> command "
                 "from the <b>File</b> menu.</p>";

    QWhatsThis::add( fileOpen, fileOpenText );

    QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen", openIcon );

    const char * fileSaveText = "<p>Click this button to save the file you "
                 "are editing. You will be prompted for a file name.\n"
                 "You can also select the <b>Save</b> command "
                 "from the <b>File</b> menu.</p>";

    QWhatsThis::add( fileSave, fileSaveText );

    const char * filePrintText = "Click this button to print the file you "
                 "are editing.\n You can also select the Print "
                 "command from the File menu.";

    QWhatsThis::add( filePrint, filePrintText );

    QPopupMenu * file = new QPopupMenu( this );
    menuBar()->insertItem( "&File", file );

    file->insertItem( "&New", this, SLOT(newDoc()), CTRL+Key_N );

    int id;
    id = file->insertItem( openIcon, "&Open...",
                           this, SLOT(choose()), CTRL+Key_O );
    file->setWhatsThis( id, fileOpenText );

    id = file->insertItem( saveIcon, "&Save",
                           this, SLOT(save()), CTRL+Key_S );
    file->setWhatsThis( id, fileSaveText );

    id = file->insertItem( "Save &As...", this, SLOT(saveAs()) );
    file->setWhatsThis( id, fileSaveText );

    file->insertSeparator();

    id = file->insertItem( printIcon, "&Print...",
                           this, SLOT(print()), CTRL+Key_P );
    file->setWhatsThis( id, filePrintText );

    file->insertSeparator();

    file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_W );

    file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );

    menuBar()->insertSeparator();

    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertItem( "&Help", help );

    help->insertItem( "&About", this, SLOT(about()), Key_F1 );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
    help->insertSeparator();
    help->insertItem( "What's &This", this, SLOT(whatsThis()), SHIFT+Key_F1 );

    e = new QTextEdit( this, "editor" );
    e->setFocus();
    setCentralWidget( e );
    statusBar()->message( "Ready", 2000 );

    resize( 450, 600 );
}

ApplicationWindow::~ApplicationWindow()
{
    delete printer;
}

void ApplicationWindow::newDoc()
{
    ApplicationWindow *ed = new ApplicationWindow;
    ed->setCaption("Qt Example - Application");
    ed->show();
}

void ApplicationWindow::choose()
{
    QString fn = QFileDialog::getOpenFileName( QString::null, QString::null,
                                               this);
    if ( !fn.isEmpty() )
        load( fn );
    else
        statusBar()->message( "Loading aborted", 2000 );
}

void ApplicationWindow::load( const QString &fileName )
{
    QFile f( fileName );
    if ( !f.open( IO_ReadOnly ) )
        return;

    QTextStream ts( &f );
    e->setText( ts.read() );
    e->setModified( FALSE );
    setCaption( fileName );
    statusBar()->message( "Loaded document " + fileName, 2000 );
}

void ApplicationWindow::save()
{
    if ( filename.isEmpty() ) {
        saveAs();
        return;
    }

    QString text = e->text();
    QFile f( filename );
    if ( !f.open( IO_WriteOnly ) ) {
        statusBar()->message( QString("Could not write to %1").arg(filename),
                              2000 );
        return;
    }

    QTextStream t( &f );
    t << text;
    f.close();

    e->setModified( FALSE );

    setCaption( filename );

    statusBar()->message( QString( "File %1 saved" ).arg( filename ), 2000 );
}

void ApplicationWindow::saveAs()
{
    QString fn = QFileDialog::getSaveFileName( QString::null, QString::null,
                                               this );
    if ( !fn.isEmpty() ) {
        filename = fn;
        save();
    } else {
        statusBar()->message( "Saving aborted", 2000 );
    }
}

void ApplicationWindow::print()
{
    // ###### Rewrite to use QSimpleRichText to print here as well
    const int Margin = 10;
    int pageNo = 1;

    if ( printer->setup(this) ) {               // printer dialog
        statusBar()->message( "Printing..." );
        QPainter p;
        if( !p.begin( printer ) )               // paint on printer
            return;

        p.setFont( e->font() );
        int yPos        = 0;                    // y-position for each line
        QFontMetrics fm = p.fontMetrics();
        QPaintDeviceMetrics metrics( printer ); // need width/height
                                                // of printer surface
        for( int i = 0 ; i < e->lines() ; i++ ) {
            if ( Margin + yPos > metrics.height() - Margin ) {
                QString msg( "Printing (page " );
                msg += QString::number( ++pageNo );
                msg += ")...";
                statusBar()->message( msg );
                printer->newPage();             // no more room on this page
                yPos = 0;                       // back to top of page
            }
            p.drawText( Margin, Margin + yPos,
                        metrics.width(), fm.lineSpacing(),
                        ExpandTabs | DontClip,
                        e->text( i ) );
            yPos = yPos + fm.lineSpacing();
        }
        p.end();                                // send job to printer
        statusBar()->message( "Printing completed", 2000 );
    } else {
        statusBar()->message( "Printing aborted", 2000 );
    }
}

void ApplicationWindow::closeEvent( QCloseEvent* ce )
{
    if ( !e->isModified() ) {
        ce->accept();
        return;
    }

    switch( QMessageBox::information( this, "Qt Application Example",
                                      "Do you want to save the changes"
                                      " to the document?",
                                      "Yes", "No", "Cancel",
                                      0, 1 ) ) {
    case 0:
        save();
        ce->accept();
        break;
    case 1:
        ce->accept();
        break;
    case 2:
    default: // just for sanity
        ce->ignore();
        break;
    }
}

void ApplicationWindow::about()
{
    QMessageBox::about( this, "Qt Application Example",
                        "This example demonstrates simple use of "
                        "QMainWindow,\nQMenuBar and QToolBar.");
}

void ApplicationWindow::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Application Example" );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "application.h"

int main( int argc, char ** argv ) {
    QApplication a( argc, argv );
    ApplicationWindow * mw = new ApplicationWindow();
    mw->setCaption( "Qt Example - Application" );
    mw->show();
    a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
    return a.exec();
}

See also Examples.


A simple demonstration of QFont member functions

This example demonstrates the use of various QFont member functions.

It is covered in detail by a walkthrough.

The main window API (viewer.h):

/* $Id$ */

#ifndef VIEWER_H
#define VIEWER_H

#include <qwidget.h>
#include <qfont.h>

class QTextView;
class QPushButton;

class Viewer : public QWidget
{
Q_OBJECT

public:
    Viewer();

private slots:
    void setDefault();
    void setSansSerif();
    void setItalics();

private:
    void setFontSubstitutions();
    void layout();
    void showFontInfo( QFont & );

    QTextView * greetings;
    QTextView * fontInfo;

    QPushButton * defaultButton;
    QPushButton * sansSerifButton;
    QPushButton * italicsButton;
};

#endif

The main window implementation (viewer.cpp):

/* $Id$ */

#include "viewer.h"
#include <qstring.h>
#include <qstringlist.h>
#include <qtextview.h>
#include <qpushbutton.h>
#include <qlayout.h>

Viewer::Viewer()
       :QWidget()
{
    setFontSubstitutions();

    QString greeting_heb = QString::fromUtf8( "\327\251\327\234\327\225\327\235" );
    QString greeting_ru = QString::fromUtf8( "\320\227\320\264\321\200\320\260\320\262\321\201\321\202\320\262\321\203\320\271\321\202\320\265" );
    QString greeting_en( "Hello" );

    greetings = new QTextView( this, "textview" );

    greetings->setText( greeting_en + "\n" +
                       greeting_ru + "\n" +
                       greeting_heb );

    fontInfo = new QTextView( this, "fontinfo" );

    setDefault();

    defaultButton = new QPushButton( "Default", this,
                                                   "pushbutton1" );
    defaultButton->setFont( QFont( "times" ) );
    connect( defaultButton, SIGNAL( clicked() ),
             this, SLOT( setDefault() ) );

    sansSerifButton = new QPushButton( "Sans Serif", this,
                                                     "pushbutton2" );
    sansSerifButton->setFont( QFont( "Helvetica", 12 ) );
    connect( sansSerifButton, SIGNAL( clicked() ),
             this, SLOT( setSansSerif() ) );

    italicsButton = new QPushButton( "Italics", this,
                                                   "pushbutton3" );
    italicsButton->setFont( QFont( "lucida", 12, QFont::Bold, TRUE ) );
    connect( italicsButton, SIGNAL( clicked() ),
             this, SLOT( setItalics() ) );

    layout();
}

void Viewer::setDefault()
{
    QFont font( "Bavaria" );
    font.setPointSize( 24 );

    font.setWeight( QFont::Bold );
    font.setUnderline( TRUE );

    greetings->setFont( font );

    showFontInfo( font );
}

void Viewer::setSansSerif()
{
    QFont font( "Newyork", 18 );
    font.setStyleHint( QFont::SansSerif );
    greetings->setFont( font );

    showFontInfo( font );
}

void Viewer::setItalics()
{
    QFont font( "Tokyo" );
    font.setPointSize( 32 );
    font.setWeight( QFont::Bold );
    font.setItalic( TRUE );

    greetings->setFont( font );

    showFontInfo( font );
}

void Viewer::showFontInfo( QFont & font )
{
    QFontInfo info( font );

    QString messageText;
    messageText = "Font requested: \"" +
                  font.family() + "\" " +
                  QString::number( font.pointSize() ) + "pt<BR>" +
                  "Font used: \"" +
                  info.family() + "\" " +
                  QString::number( info.pointSize() ) + "pt<P>";

    QStringList substitutions = QFont::substitutes( font.family() );

    if ( ! substitutions.isEmpty() ){
        messageText += "The following substitutions exist for " + \
                       font.family() + ":<UL>";

        QStringList::Iterator i = substitutions.begin();
        while ( i != substitutions.end() ){
            messageText += "<LI>\"" + (* i) + "\"";
            i++;
        }
         messageText += "</UL>";
    } else {
        messageText += "No substitutions exist for " + \
                       font.family() + ".";
    }

    fontInfo->setText( messageText );
}

void Viewer::setFontSubstitutions()
{
    QStringList substitutes;
    substitutes.append( "Times" );
    substitutes +=  "Mincho",
    substitutes << "Arabic Newspaper" << "crox";

    QFont::insertSubstitutions( "Bavaria", substitutes );

    QFont::insertSubstitution( "Tokyo", "Lucida" );
}

// For those who prefer to use Qt Designer for creating GUIs
// the following function might not be of particular interest:
// all it does is creating the widget layout.

void Viewer::layout()
{
    QHBoxLayout * textViewContainer = new QHBoxLayout();
    textViewContainer->addWidget( greetings );
    textViewContainer->addWidget( fontInfo );

    QHBoxLayout * buttonContainer = new QHBoxLayout();

    buttonContainer->addWidget( defaultButton );
    buttonContainer->addWidget( sansSerifButton );
    buttonContainer->addWidget( italicsButton );

    int maxButtonHeight = defaultButton->height();

    if ( sansSerifButton->height() > maxButtonHeight )
        maxButtonHeight = sansSerifButton->height();
    if ( italicsButton->height() > maxButtonHeight )
        maxButtonHeight = italicsButton->height();

    defaultButton->setFixedHeight( maxButtonHeight );
    sansSerifButton->setFixedHeight( maxButtonHeight );
    italicsButton->setFixedHeight( maxButtonHeight );

    QVBoxLayout * container = new QVBoxLayout( this );
    container->addLayout( textViewContainer );
    container->addLayout( buttonContainer );

    resize( 700, 250 );
}

main() program (simple-qfont-demo.cpp):

/* $Id$ */

#include "viewer.h"

#include <qapplication.h>

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    Viewer * textViewer = new Viewer();
    textViewer->setCaption( "Qt Example - Simple QFont Demo" );
    app.setMainWidget( textViewer );
    textViewer->show();
    return app.exec();
}

See also QFont Examples.


Walkthrough: A simple QFont demonstration

The following walkthrough will show you how to make use of the font setting and manipulation techniques provided by QFont.

In addition it will show some aspects of widget layout -- if you prefer leaving this job to Qt Designer simply skip the relevant paragraphs. Moreover, if you have asked yourself how to add strings to a QStringList and how to step through its members, you will know after reading this walkthrough, or skipping to the relevant explanations in Viewer::showFontInfo() and Viewer::setFontSubstitutions().

To get the most out of the walkthrough you should at least be familiar with signals and slots.

The example program consists of a widget containing two QTextViews side by side. The one on the left shows greetings in English, Russian, and Hebrew. The one on the right shows some information about the fonts used to draw these greetings. Three push buttons in the bottom of the main window change the font used to display the greetings.

Note that the fonts and font characteristics in the example have been chosen for demonstration purposes only -- in a real world application they would rather count for bad design.

The API of the custom widget

The widget used in this example is a custom widget named Viewer.

    #include <qwidget.h>
    #include <qfont.h>

As we derive it from QWidget we include the relevant header file. Additionally we use a QFont object as a function argument, and therefore include the QFont class.

    class QTextView;
    class QPushButton;

Furthermore we declare the use of the QTextView and the QPushButton classes for class variables (we don't need to include them at this stage yet because we only use pointers to these classes).

    class Viewer : public QWidget
    {
    Q_OBJECT

The Viewer widget will have slots, so don't forget to add the Q_OBJECT macro.

    public:
        Viewer();

As we won't use more than one instance of this class there is no need for any complex constructors, a simple one without any arguments should be sufficient.

    private slots:
        void setDefault();

As previously mentioned we're going to have three push buttons. When the user clicks on them, something should happen. Thus we define one slot that sets the font in the greeting window back to the default, ...

        void setSansSerif();

... one that switches to a sans serif font, and ...

        void setItalics();

... one that shows the greetings in italics.

    private:
        void setFontSubstitutions();

Will will write the greetings using different alphabets. For users who don't have Unicode fonts installed we want to tell the application to try to exchange missing characters in one font with appropriate characters from other fonts. QFont does such font substitutions on its own but with this helper function we can define our preferred substitution pattern.

        void layout();

The task of putting the buttons and text views together we will put into a separate layout() function. This will make the code easier to understand and read.

        void showFontInfo( QFont & );

The last private function reveals font information in the text view on the right.

        QTextView * greetings;
        QTextView * fontInfo;

        QPushButton * defaultButton;
        QPushButton * sansSerifButton;
        QPushButton * italicsButton;
    };

Last but not least we define the elements of our GUI as private class variables.

The implementation of the Viewer widget

Now we will implement the Viewer class.

    #include "viewer.h"
    #include <qstring.h>
    #include <qstringlist.h>
    #include <qtextview.h>
    #include <qpushbutton.h>
    #include <qlayout.h>

First we include the relevant header files -- obviously the header of the Viewer class itself, of the QPushButton and QTextView widgets, and of the QString and QStringList classes. qlayout.h provides classes for horizontal and vertical layout and will be used in the layout() function.

    Viewer::Viewer()
           :QWidget()
    {

As already mentioned the finger print of the Viewer constructor is as simple as possible, without any arguments, derived from the QWidget default constructor.

        setFontSubstitutions();

First we define the font substitutions -- for clarity reasons we do this in a separate function.

        QString greeting_heb = QString::fromUtf8( "\327\251\327\234\327\225\327\235" );
        QString greeting_ru = QString::fromUtf8( "\320\227\320\264\321\200\320\260\320\262\321\201\321\202\320\262\321\203\320\271\321\202\320\265" );

The Hebrew and the Russian greeting we have readily available as UTF8 encoded strings. To use them in a QString we "import" them with QString::fromUtf8().

        QString greeting_en( "Hello" );

Dor the English greeting we use a simple QString.

        greetings = new QTextView( this, "textview" );

Now we create the first widget as a child of this widget, the QTextView with the identity name textview that shows the greetings.

        greetings->setText( greeting_en + "\n" +
                           greeting_ru + "\n" +
                           greeting_heb );

Now we set the text shown by greetings to the three greetings.

        fontInfo = new QTextView( this, "fontinfo" );

The second text view we call fontinfo and create it as a child of this Viewer widget.

        setDefault();

Using the setDefault() function we apply the initial font to the greetings greetings and fill the fontInfo textview with information about the font used.

        defaultButton = new QPushButton( "Default", this,
                                                       "pushbutton1" );

Now we create the first of the three push buttons -- the one that changes the font to the initial one -- with the label Default.

        defaultButton->setFont( QFont( "times" ) );

The label should be printed in a member font of the Times family. In the unlikely case that the user does not have installed a matching font, QFont is responsible in finding a replacement. Note that case-sensitivity is no issue when specifying the font family.

As we don't explicitly request a font size or weight, QFont tries to find a default 12 pt font with normal boldness.

        connect( defaultButton, SIGNAL( clicked() ),
                 this, SLOT( setDefault() ) );

In order to make something happening when the user clicks the defaultButton, we connect the QPushButton::clicked() signals issued from it to the Viewer's setDefault() slot.

        sansSerifButton = new QPushButton( "Sans Serif", this,
                                                         "pushbutton2" );
        sansSerifButton->setFont( QFont( "Helvetica", 12 ) );

The newly created second button is labelled Sans Serif in a 12 pt Helvetica font. Again if this is not possible because the requested font is not available on the system, QFont deals with it and finds a replacement.

        connect( sansSerifButton, SIGNAL( clicked() ),
                 this, SLOT( setSansSerif() ) );

We connect the clicked() signal of the sansSerifButton to the setSansSerif() slot.

        italicsButton = new QPushButton( "Italics", this,
                                                       "pushbutton3" );
        italicsButton->setFont( QFont( "lucida", 12, QFont::Bold, TRUE ) );

italicsButton, the last push button, is labelled Italics. This time we specify even more characteristics of the label font. We wish it to be a 12 pt bold member of the Lucida family. Also it should be in italics, indicated by the fourth QFont argument being TRUE.

        connect( italicsButton, SIGNAL( clicked() ),
                 this, SLOT( setItalics() ) );

Again, the italicsButton's clicked() signal is connected to a slot of this Viewer object setItalics().

        layout();
    }

Finally we arrange all five child widgets of this main window nicely using layout().

    void Viewer::setDefault()
    {
        QFont font( "Bavaria" );

For demonstration purposes on how the QFont substitution works we use a non-existant font family, Bavaria, as the default font for the greetings.

        font.setPointSize( 24 );

This font should have a size of 24 points, ...

        font.setWeight( QFont::Bold );

... it should be bold, ...

        font.setUnderline( TRUE );

... and the text written should be underlined.

        greetings->setFont( font );

Now we ask the greetings widget to use the font font.

As a member of the Bavaria font family is unlikely to be installed on your machine, run the program and observe how QFont finds a substitute. Later on we will define custom substitutions for Bavaria in the setFontSubstitutions() function.

        showFontInfo( font );
    }

Finally we use the function showFontInfo() to display appropriate information about the current font and how it maybe differs from the one requested.

    void Viewer::setSansSerif()
    {
        QFont font( "Newyork", 18 );

The slot to change the greeting font to sans serif is quite similar to setDefault(). Here we save a line of code and define the (non-existant) font family (NewYork) and size (18 points) at once.

        font.setStyleHint( QFont::SansSerif );

We use a style hint to ask QFont for a sans serif font (SansSerif is a member of the QFont::StyleHint enumeration).

As a member of the NewYork family is quite unlikely to be installed on your computer, QFont will try to follow the style hint and the font size and use this information to find a replacement font.

        greetings->setFont( font );

Finally we apply the requested font to the content of the greetings textview ...

        showFontInfo( font );
    }

... and display the appropriate font information in the fontInfo textview.

    void Viewer::setItalics()
    {
        QFont font( "Tokyo" );
        font.setPointSize( 32 );
        font.setWeight( QFont::Bold );
        font.setItalic( TRUE );

The setItalics() slot changes the greetings' font to a 32 pt bold and italic member of the (again non-existant) Tokyo family. Note that setFontSubstitutions() defines a substitution family for Tokyo.

        greetings->setFont( font );

We set the font of the greetings textview to font, and ...

        showFontInfo( font );
    }

... display the appropriate font information in the fontInfo textview.

    void Viewer::showFontInfo( QFont & font )
    {

Now, how do we show the font information?

        QFontInfo info( font );

First we obtain information about the font that is actually used when the font font is required, and store it in info.

        QString messageText;
        messageText = "Font requested: \"" +
                      font.family() + "\" " +

Then we start compiling the message that we want to show in the fontInfo textview. First, we print out the requested font family name. As we want to frame the family name with quotation marks, we have to escape the " character so that it is not confused with the C++ quotation marks used to terminate strings.

                      QString::number( font.pointSize() ) + "pt<BR>" +

We obtain the requested font size in points and convert it to a QString using QString::number(). Using <BR>; we add a rich-text linebreak to the messageText string.

                      "Font used: \"" +

After we have displayed information about the required font we want to contrast it with the one actually used. This is stored in the QFontInfo info variable.

                      info.family() + "\" " +

First we display the font family, ...

                      QString::number( info.pointSize() ) + "pt<P>";

... and then we append the actual font size, converted to a QString, to the message string. The unit abbreviation and a rich-text paragraph (<P>) follow.

If custom substitutions are available for the requested font, we're going to show them as well:

        QStringList substitutions = QFont::substitutes( font.family() );

First we store the entire list of substitutes in a string list.

        if ( ! substitutions.isEmpty() ){

If it contains at least one substitute ...

            messageText += "The following substitutions exist for " + \
                           font.family() + ":<UL>";

... we say so in the messageText, ...

            QStringList::Iterator i = substitutions.begin();

... and prepare ourselves to step through the list. For this purpose we set the list iterator i to the first list member of the substitutions string list.

            while ( i != substitutions.end() ){

As long as we haven't reached the last list member ...

                messageText += "<LI>\"" + (* i) + "\"";

we add a bullet list entry (<LI>) of the current list member (i.e. the font family name of the substitute), ...

                i++;
            }

... and move the iterator one step further.

             messageText += "</UL>";

Finally we add the end-of-bullet-list rich-text tag to the messageText string.

        } else {
            messageText += "No substitutions exist for " + \
                           font.family() + ".";
        }

If the substitution list was empty, we make a note about it in the messageText string.

        fontInfo->setText( messageText );
    }

Now that we have the messageText string ready we enter it into the fontInfo textview.

    void Viewer::setFontSubstitutions()
    {

With this function we finally reveal the secret of how to define custom substitutions for a font family.

        QStringList substitutes;

All we need is a string list.

        substitutes.append( "Times" );
        substitutes +=  "Mincho",
        substitutes << "Arabic Newspaper" << "crox";

In a real world application you will probably stick to one of the above methods to add strings to a string list. Here all possible ones are outlined to give you an overview.

After these append operations substitutes consists of four members: Times, Mincho, Arabic Newspaper, and Crox in this order. These are the font families that in the first place are searched for characters the base font does not provide.

        QFont::insertSubstitutions( "Bavaria", substitutes );

In Viewer objects, these four families provide a fallback for the Bavaria font family requested by the setDefault() slot.

        QFont::insertSubstitution( "Tokyo", "Lucida" );
    }

For the Tokyo family used in setItalics() we provide only one substitute family, Lucida. Because it is only one and not many as for Bavaria, we use QFont::insertSubstitution() instead of QFont::insertSubstitutions().

If you usually create your GUIs using Qt Designer this walkthrough has already come to an end. If this is one of your first encounters with Qt you might however continue with the explanation of the very simple main() function.

    void Viewer::layout()
    {

This last member function of the Viewer class does not cover any more QFont details. All it does is creating a nice automatic layout for the three push buttons and the two text views.

The best solution for this task is to have the two QTextViews lined up horizontally. The same applies to the QPushButtons. Finally both of these layouts are placed together into a vertical layout container. Qt takes care of the proportions so that everything looks nice.

        QHBoxLayout * textViewContainer = new QHBoxLayout();

Let's create the first layout that aligns its members horizontally, ...

        textViewContainer->addWidget( greetings );

... and add the QTextView with the greetings, ...

        textViewContainer->addWidget( fontInfo );

... as well as the text view with the font information. fontInfo appears to the right of greetings because it was added later.

        QHBoxLayout * buttonContainer = new QHBoxLayout();

Now we create the second layout for the push buttons.

        buttonContainer->addWidget( defaultButton );

defaultButton is placed on the left hand side of the layout, ...

        buttonContainer->addWidget( sansSerifButton );

... sansSerifButton in the middle, ...

        buttonContainer->addWidget( italicsButton );

... and italicsButton on the right hand side.

Unfortunately we face a tiny problem: remember that (a highly unusual thing to do in a real world application) the labels of the three buttons are drawn in different fonts. Whilst the automatic layout accounts for the fact all three buttons have the same width, the uncommon occurrence of different character heights leads to different button heights.

To make the application window look nice we have to help it a little.

        int maxButtonHeight = defaultButton->height();
        if ( sansSerifButton->height() > maxButtonHeight )
            maxButtonHeight = sansSerifButton->height();
        if ( italicsButton->height() > maxButtonHeight )
            maxButtonHeight = italicsButton->height();

By comparing the three button heights we find the largest one and store it in maxButtonHeight.

        defaultButton->setFixedHeight( maxButtonHeight );
        sansSerifButton->setFixedHeight( maxButtonHeight );
        italicsButton->setFixedHeight( maxButtonHeight );

Now we set the height of each button to this maximum value and make sure that the automatic layout does not change it.

This was the hardest part of the entire layout process. There is one task left:

        QVBoxLayout * container = new QVBoxLayout( this );

We create a layout that arranges its members vertically.

        container->addLayout( textViewContainer );

This container layout contains the text views on top, ...

        container->addLayout( buttonContainer );

... and the button row below.

        resize( 700, 250 );
    }

Finally we set the size of the entire main window to a width of 700 pixels and a height of 250 pixels.

The main program

There is not much to say about the main program.

    #include "viewer.h"
    #include <qapplication.h>

    int main( int argc, char **argv )
    {
        QApplication app( argc, argv );
        Viewer * textViewer = new Viewer();

We create an instance of the Viewer class, ...

        app.setMainWidget( textViewer );

... make it the main widget of the application object app, ...

        textViewer->show();

... display it to the user ...

        return app.exec();
    }

... and enter the application loop. Well done, that was all for today ...

See also Step-by-step Examples.


Drag and Drop (Simple)

This provides a very simple example of Qt's drag and drop functionality.

For a more complete example see the Drag and Drop example.

Header file:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qcursor.h>
#include <qsplitter.h>
#include <qlistbox.h>
#include <qiconview.h>
#include <qpixmap.h>

class QDragEnterEvent;
class QDragDropEvent;

class DDListBox : public QListBox
{
    Q_OBJECT
public:
    DDListBox( QWidget * parent = 0, const char * name = 0, WFlags f = 0 );
    // Low-level drag and drop
    void dragEnterEvent( QDragEnterEvent *evt );
    void dropEvent( QDropEvent *evt );
    void mousePressEvent( QMouseEvent *evt );
    void mouseMoveEvent( QMouseEvent * );
private:
    int dragging;
};

class DDIconViewItem : public QIconViewItem
{
public:
    DDIconViewItem( QIconView *parent, const QString& text, const QPixmap& icon ) :
        QIconViewItem( parent, text, icon ) {}
    DDIconViewItem( QIconView *parent, const QString &text ) :
        QIconViewItem( parent, text ) {}
    // High-level drag and drop
    bool acceptDrop( const QMimeSource *mime ) const;
    void dropped( QDropEvent *evt, const QValueList<QIconDragItem>& );
};

class DDIconView : public QIconView
{
    Q_OBJECT
public:
    DDIconView( QWidget * parent = 0, const char * name = 0, WFlags f = 0 ) :
        QIconView( parent, name, f ) {}
    // High-level drag and drop
    QDragObject *dragObject();
public slots:
    void slotNewItem( QDropEvent *evt, const QValueList<QIconDragItem>& list );
};

Implementation:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2001 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"

const char* red_icon[]={
"16 16 2 1",
"r c red",
". c None",
"................",
"................",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrr......rrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"..rrrrrrrrrrrr..",
"................",
"................"};

const char* blue_icon[]={
"16 16 2 1",
"b c blue",
". c None",
"................",
"................",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbb......bbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"..bbbbbbbbbbbb..",
"................",
"................"};

const char* green_icon[]={
"16 16 2 1",
"g c green",
". c None",
"................",
"................",
"..gggggggggggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..ggg......ggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"..gggggggggggg..",
"................",
"................"};

// ListBox -- low level drag and drop

DDListBox::DDListBox( QWidget * parent, const char * name, WFlags f ) :
    QListBox( parent, name, f )
{
    setAcceptDrops( TRUE );
    dragging = FALSE;
}

void DDListBox::dragEnterEvent( QDragEnterEvent *evt )
{
    if ( QTextDrag::canDecode( evt ) )
        evt->accept();
}

void DDListBox::dropEvent( QDropEvent *evt )
{
    QString text;

    if ( QTextDrag::decode( evt, text ) )
        insertItem( text );
}

void DDListBox::mousePressEvent( QMouseEvent *evt )
{
    QListBox::mousePressEvent( evt );
    dragging = TRUE;
}

void DDListBox::mouseMoveEvent( QMouseEvent * )
{
    if ( dragging ) {
        QDragObject *d = new QTextDrag( currentText(), this );
        d->dragCopy(); // do NOT delete d.
        dragging = FALSE;
    }
}

// IconViewIcon -- high level drag and drop

bool DDIconViewItem::acceptDrop( const QMimeSource *mime ) const
{
    if ( mime->provides( "text/plain" ) )
        return TRUE;
    return FALSE;
}

void DDIconViewItem::dropped( QDropEvent *evt, const QValueList<QIconDragItem>& )
{
    QString label;

    if ( QTextDrag::decode( evt, label ) )
        setText( label );
}

// IconView -- high level drag and drop

QDragObject *DDIconView::dragObject()
{
  return new QTextDrag( currentItem()->text(), this );
}

void DDIconView::slotNewItem( QDropEvent *evt, const QValueList<QIconDragItem>& )
{
    QString label;

    if ( QTextDrag::decode( evt, label ) ) {
        DDIconViewItem *item = new DDIconViewItem( this, label );
        item->setRenameEnabled( TRUE );
    }
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    // Create and show the widgets
    QSplitter *split = new QSplitter();
    DDIconView *iv   = new DDIconView( split );
    (void)             new DDListBox( split );
    app.setMainWidget( split );
    split->resize( 600, 400 );
    split->show();

    // Set up the connection so that we can drop items into the icon view
    QObject::connect(
        iv, SIGNAL(dropped(QDropEvent*, const QValueList<QIconDragItem>&)),
        iv, SLOT(slotNewItem(QDropEvent*, const QValueList<QIconDragItem>&)));

    // Populate the QIconView with icons
    DDIconViewItem *item;
    item = new DDIconViewItem( iv, "Red",   QPixmap( red_icon ) );
    item->setRenameEnabled( TRUE );
    item = new DDIconViewItem( iv, "Green", QPixmap( green_icon ) );
    item->setRenameEnabled( TRUE );
    item = new DDIconViewItem( iv, "Blue",  QPixmap( blue_icon ) );
    item->setRenameEnabled( TRUE );

    return app.exec();
}

See also Examples.


小表格样例

本样例显示QTable与QTableItem。

实现：

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited May 7 17:30 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qtable.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qstringlist.h>

// Qt logo: static const char *qtlogo_xpm[]
#include "qtlogo.xpm"

// Table size

const int numRows = 30;
const int numCols = 10;

// The program starts here.

int main( int argc, char **argv )
{
    QApplication app( argc, argv );

    QTable table( numRows, numCols );

    QHeader *header = table.horizontalHeader();
    header->setLabel( 0, QObject::tr( "Tiny" ), 40 );
    header->setLabel( 1, QObject::tr( "Checkboxes" ) );
    header->setLabel( 5, QObject::tr( "Combos" ) );
    header->setMovingEnabled(TRUE);

    QImage img( qtlogo_xpm );
    QPixmap pix = img.scaleHeight( table.rowHeight(3) );
    table.setPixmap( 3, 2, pix );
    table.setText( 3, 2, "A Pixmap" );

    QStringList comboEntries;
    comboEntries << "one" << "two" << "three" << "four";

    for ( int i = 0; i < numRows; ++i ){
        QComboTableItem * item = new QComboTableItem( &table, comboEntries, FALSE );
        item->setCurrentItem( i % 4 );
        table.setItem( i, 5, item );
    }
    for ( int j = 0; j < numRows; ++j )
        table.setItem( j, 1, new QCheckTableItem( &table, "Check me" ) );

    app.setMainWidget( &table );
    table.show();
    return app.exec();
}

也参见表格例程。

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


Sound Example

This example shows how easy it is to play sounds, e.g. .WAV files, if your machine is set up to play audio.

Header file:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#ifndef PLAY_H
#define PLAY_H

#include "qsound.h"
#include <qmainwindow.h>

class SoundPlayer : public QMainWindow {
    Q_OBJECT
public:
    SoundPlayer();

public slots:
    void doPlay1();
    void doPlay2();
    void doPlay3();
    void doPlay4();
    void doPlay34();
    void doPlay1234();

private:
    QSound bucket3;
    QSound bucket4;
};

#endif

Implementation:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
//
// Very simple example of QSound::play(filename)
//
// 99% of this program is just boilerplate Qt code to put up a nice
// window so you think something special is happening.
//

#include "sound.h"
#include <qapplication.h>
#include <qmessagebox.h>
#include <qmenubar.h>

SoundPlayer::SoundPlayer() :
    QMainWindow(),
    bucket3("sounds/3.wav"),
    bucket4("sounds/4.wav")
{
    if (!QSound::isAvailable()) {
        // Bail out.  Programs in which sound is not critical
        // could just silently (hehe) ignore the lack of a server.
        //
        QMessageBox::warning(this,"No Sound",
                "<p><b>Sorry, you are not running the Network Audio System.</b>"
                "<p>If you have the `au' command, run it in the background before this program. "
                "The latest release of the Network Audio System can be obtained from:"
                "<pre>\n"
                " &nbsp;\n"
                "   ftp.ncd.com:/pub/ncd/technology/src/nas\n"
                "   ftp.x.org:/contrib/audio/nas\n"
                "</pre>"
                "<p>Release 1.2 of NAS is also included with the X11R6"
                "contrib distribution."
                "<p>After installing NAS, you will then need to reconfigure Qt with NAS sound support");
    }

    QPopupMenu *file = new QPopupMenu;
    file->insertItem("Play &1",  this, SLOT(doPlay1()), CTRL+Key_1);
    file->insertItem("Play &2",  this, SLOT(doPlay2()), CTRL+Key_2);
    file->insertItem("Play from bucket &3",  this, SLOT(doPlay3()), CTRL+Key_3);
    file->insertItem("Play from bucket &4",  this, SLOT(doPlay4()), CTRL+Key_4);
    file->insertSeparator();
    file->insertItem("Play 3 and 4 together",  this, SLOT(doPlay34()));
    file->insertItem("Play all together",  this, SLOT(doPlay1234()));
    file->insertSeparator();
    file->insertItem("E&xit",  qApp, SLOT(quit()));
    menuBar()->insertItem("&File", file);
}

void SoundPlayer::doPlay1()
{
    QSound::play("sounds/1.wav");
}

void SoundPlayer::doPlay2()
{
    QSound::play("sounds/2.wav");
}

void SoundPlayer::doPlay3()
{
    bucket3.play();
}

void SoundPlayer::doPlay4()
{
    bucket4.play();
}

void SoundPlayer::doPlay34()
{
    // Some sound platforms will only play one sound at a time
    bucket3.play();
    bucket4.play();
}

void SoundPlayer::doPlay1234()
{
    // Some sound platforms will only play one sound at a time
    QSound::play("sounds/1.wav");
    QSound::play("sounds/2.wav");
    bucket3.play();
    bucket4.play();
}

int main(int argc, char** argv)
{
    QApplication app(argc,argv);
    SoundPlayer sp;
    app.setMainWidget(&sp);
    sp.setCaption("Qt Example - Sounds");
    sp.show();
    return app.exec();
}

See also Examples.


Splitter

This example shows how to use splitters. With their help users can decide herself/himself, how much space each of the multiple child items should get.

Implementation:

/****************************************************************************
** $Id:  qt/splitter.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qlabel.h>
#include <qsplitter.h>
#include <qmultilineedit.h>

#include <qpainter.h>

class Test : public QWidget {
public:
    Test(QWidget* parent=0, const char* name=0, int f=0);
    void paintEvent(QPaintEvent* e);
private:
};

Test::Test(QWidget* parent, const char* name, int f) :
    QWidget(parent, name, f)
{

}

void Test::paintEvent(QPaintEvent* e)
{
    QPainter p(this);
    p.setClipRect(e->rect());
    const int d = 1000; //large number
    int x1 = 0;
    int x2 = width()-1;
    int y1 = 0;
    int y2 = height()-1;

    int x = (x1+x2)/2;
    p.drawLine( x, y1, x+d, y1+d   );
    p.drawLine( x, y1, x-d, y1+d   );
    p.drawLine( x, y2, x+d, y2-d   );
    p.drawLine( x, y2, x-d, y2-d   );

    int y = (y1+y2)/2;
    p.drawLine( x1, y, x1+d, y+d   );
    p.drawLine( x1, y, x1+d, y-d   );
    p.drawLine( x2, y, x2-d, y+d   );
    p.drawLine( x2, y, x2-d, y-d   );
}

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );

    QSplitter *s1 = new QSplitter( QSplitter::Vertical, 0 , "main" );

    QSplitter *s2 = new QSplitter( QSplitter::Horizontal, s1, "top" );

    Test *t1 = new Test( s2, "topLeft" );
    t1->setBackgroundColor( Qt::blue.light( 180 ) );
    t1->setMinimumSize( 50, 0 );

    Test *t2 = new Test( s2, "topRight" );
    t2->setBackgroundColor( Qt::green.light( 180 ) );
    s2->setResizeMode( t2, QSplitter::KeepSize );
    s2->moveToFirst( t2 );

    QSplitter *s3 = new QSplitter( QSplitter::Horizontal,  s1, "bottom" );

    Test *t3 = new Test( s3, "bottomLeft" );
    t3->setBackgroundColor( Qt::red );
    Test *t4 = new Test( s3, "bottomMiddle" );
    t4->setBackgroundColor( Qt::white );

    Test *t5 = new Test( s3, "bottomRight" );
    t5->setMaximumHeight( 250 );
    t5->setMinimumSize( 80, 50 );
    t5->setBackgroundColor( Qt::yellow );

#ifdef Q_WS_QWS
    // Qt/Embedded XOR drawing not yet implemented.
    s1->setOpaqueResize( TRUE );
#endif
    s2->setOpaqueResize( TRUE );
    s3->setOpaqueResize( TRUE );

    a.setMainWidget( s1 );
    s1->setCaption("Qt Example - Splitters");
    s1->show();
    int result = a.exec();
    delete s1;
    return result;
}

See also Examples.


SQL Module - Drivers

  • Introduction
  • Building the drivers using configure
  • Building the plugins manually
    • QMYSQL3 - MySQL 3.x
      • General information
      • How to build the plugin on Unix/Linux
      • How to build the plugin on Windows
    • QOCI8 - Oracle Call Interface (OCI)
      • General information
      • Unicode support
      • BLOB/LOB support
      • How to build the plugin on Unix/Linux
      • How to build the plugin on Windows
    • QODBC3 - Open Database Connectivity (ODBC)
      • General information
      • How to build the plugin on Unix/Linux
      • How to build the plugin on Windows
    • QPSQL7 - PostgreSQL version 6 and 7
      • General information
      • Unicode support
      • BLOB support
      • How to build the plugin on Unix/Linux
    • QTDS7 - Sybase Adaptive Server and Microsoft SQL Server
      • How to build the plugin on Unix/Linux
      • How to build the plugin on Windows
  • Troubleshooting
  • How to write your own database driver

Introduction

The SQL Module uses driver plugins in order to communicate with different database APIs. Since the SQL Module API is database-independent, all database-specific code is contained within these drivers. Several drivers are supplied with Qt and other drivers can be added. The driver source code is supplied and can be used as a model for writing your own drivers.

To build a driver plugin you need the client API that is shipped with every Database Management System (DBMS). Most installation programs also allow you to install "development libraries", and these are what you need. These libraries are responsible for the low-level communication with the DBMS.

The currently available drivers shipped with Qt are:

  • QMYSQL3 - MySQL Driver
  • QOCI8 - Oracle Call Interface Driver, version 8 and 9
  • QODBC3 - Open Database Connectivity Driver
  • QPSQL7 - PostgreSQL v6.x and v7.x Driver
  • QTDS7 - Sybase Adaptive Server and Microsoft SQL Server Driver

Note that not all of the plugins are shipped with the Qt Free Edition due to license incompatibilities with the GPL.

Building the drivers using configure

The Qt configure script automatically detects the available client libraries on your machine. Run "configure -help" to see what drivers may be built. You should get an output similar to this:

Possible values for <driver>: [ mysql oci odbc psql tds ]
Auto-Detected on this system: [ mysql psql ]

Note that on Windows, the configure script doesn't currently do any auto-detection.

Note that configure cannot detect the neccessary libraries and include files if they are not in the standard paths, so it may be necessary to specify these paths using the "-I" and "-L" switches. If your MySQL include files are installed in /usr/local/mysql (or in C:\mysql\include on Windows), then pass the following parameter to configure: "-I/usr/local/mysql" (or "-I C:\mysql\include" for Windows).

Note that on Windows the parameter -I doesn't allow spaces in filenames, so use the 8.3 name instead, i.e. use "C:\progra~1\mysql" instead of "C:\program files\mysql".

Use the -qt-sql-<driver> parameter to build the database driver statically into your Qt library or -plugin-sql-<driver> to build the driver as a plugin. Look at the chapters below for additional information about required libraries.

Building the plugins manually

QMYSQL3 - MySQL 3.x

General information

MySQL 3.x doesn't support SQL transactions by default. There are some backends which offer this functionality. Recent versions of the MySQL client libraries (>3.23.34) allow you to use transactions on those modified servers.

If you have a recent client library and connect to a transaction-enabled MySQL server, a call to the QSqlDriver::hasFeature( QSqlDriver::Transactions ) function returns TRUE and SQL transactions can be used.

You can find information about MySQL on http://www.mysql.com

How to build the plugin on Unix/Linux

You need the MySQL header files and as well as the shared library "libmysqlclient.so". Depending on your Linux distribution you need to install a package which is usually called "mysql-devel".

Tell qmake where to find the MySQL header files and shared libraries (here it is assumed that MySQL is installed in /usr/local) and run make:

cd $QTDIR/plugins/src/sqldrivers/mysql
qmake -o Makefile "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient" mysql.pro
make

How to build the plugin on Windows

You need to get the MySQL installation files. Run SETUP.EXE and choose "Custom Install". Install the "Libs & Include Files" Module. Build the plugin as follows (here it is assumed that MySQL is installed in C:\MYSQL):

cd %QTDIR%\plugins\src\sqldrivers\mysql
qmake -o Makefile "INCLUDEPATH+=C:\MYSQL\INCLUDE" "LIBS+=C:\MYSQL\LIB\OPT\LIBMYSQL.LIB" mysql.pro
nmake

If you are not using a Microsoft compiler, replace "nmake" with "make" in the statement above.

QOCI8 - Oracle Call Interface (OCI)

General information

The Qt OCI plugin supports both Oracle 8 and Oracle 9. After connecting to the Oracle server, the plugin will auto-detect the database version and enable features accordingly.

Unicode support

If the Oracle server supports Unicode, the OCI plugin will use UTF-8 encoding to communicate with the server. When accessing an Oracle 8 database, only retrieval of Unicode strings are supported. For Oracle 9 both retrieval and insertion of Unicode strings are supported.

BLOB/LOB support

Binary Large Objects (BLOBs) can be retrieved, but be aware that this process may require a lot of memory. We recommend using separate queries and retrieving only one BLOB at a time.

Inserting BLOB fields is limited to Oracle's maximum SQL string size.

How to build the plugin on Unix/Linux

All files required to build driver should ship with the standard Oracle Client install.

Oracle library files required to build driver:

  • libclntsh.so
  • libclntsh.so.8.0 (Oracle 8) or libclntsh.so.9.0 (Oracle 9)
  • libwtc8.so or libwtc9.so

Tell qmake where to find the Oracle header files and shared libraries (it is assumed that the variable $ORACLE_HOME points to the directory where Oracle is installed) and run make:

If you are using Oracle 8:

cd $QTDIR/plugins/src/sqldrivers/oci
qmake -o Makefile "INCLUDEPATH+=$ORACLE_HOME/rdbms/public $ORACLE_HOME/rdbms/demo" "LIBS+=-L$ORACLE_HOME/lib -lclntsh -lwtc8" oci.pro
make

For Oracle version 9:

cd $QTDIR/plugins/src/sqldrivers/oci
qmake -o Makefile "INCLUDEPATH+=$ORACLE_HOME/rdbms/public $ORACLE_HOME/rdbms/demo" "LIBS+=-L$ORACLE_HOME/lib -lclntsh -lwtc9" oci.pro
make

How to build the plugin on Windows

Choosing the option "Programmer" in the Oracle Client Installer from the Oracle Client Installation CD is sufficient to build the plugin.

Build the plugin as follows (here it is assumed that Oracle Client is installed in C:\oracle):

set INCLUDE=%INCLUDE%;c:\oracle\oci\include
set LIB=%LIB%;c:\oracle\oci\lib\msvc
cd %QTDIR%\plugins\src\sqldrivers\oci
qmake -o Makefile oci.pro
nmake

When you run your application you will also need to add the oci.dll path to your PATH environment variable:

set PATH=%PATH%;c:\oracle\bin

If you are not using a Microsoft compiler, replace "nmake" with "make" in the statement above.

QODBC3 - Open Database Connectivity (ODBC)

General information

ODBC is a general interface that allows you to connect to multiple DBMS using a common interface. The QODBC3 driver allows you to connect to an ODBC driver manager and access the available data sources. Note that you also need to install and configure ODBC drivers for the ODBC driver manager that is installed on your system. The QODBC3 plugin then allows you to use these data sources in your Qt project.

On Windows systems after 95 an ODBC driver manager should be installed by default, for Unix systems there are some implementations which have to be installed first. Note that every client that uses your application is required to have an ODBC driver manager installed, otherwise the QODBC3 plugin will not work.

Be aware that when connecting to an ODBC datasource you must pass in the name of the ODBC datasource to the QSqlDatabase::setDatabaseName() function - not the actual database name.

The QODBC3 Plugin needs an ODBC compliant driver manager version 2.0 or greater to work. Some ODBC drivers claim to be version 2.0 compliant, but do not offer all needed functionality. The QODBC3 plugin therefore checks whether the data source can be used after a connection has been established and refuses to work if the check fails. If you don't like this behaviour, you can remove the #define ODBC_CHECK_DRIVER line from the file qsql_odbc.cpp. Do this at your own risk!

Note that some DBMSs, like Microsoft Access, does not return the primary index for a table through ODBC. You can still use the QODBC3 driver, but you will have to manage table indices yourself (through QSqlCursor::setPrimaryIndex()), otherwise INSERT, UPDATE and DELETE operations will fail in data-aware Qt widgets. You will have to comment out the #define ODBC_CHECK_DRIVER line and recompile the driver, otherwise you will not be able to connect to a Microsoft Access database.

How to build the plugin on Unix/Linux

It is recommended that you use unixODBC. You can find the newest version and ODBC drivers at http://www.unixodbc.org. You need the unixODBC header files and shared libraries.

Tell qmake where to find the unixODBC header files and shared libraries (here it is assumed that unixODBC is installed in /usr/local/unixODBC) and run make:

cd $QTDIR/plugins/src/sqldrivers/odbc
qmake "INCLUDEPATH+=/usr/local/unixODBC/include" "LIBS+=-L/usr/local/unixODBC/lib -lodbc"
make

How to build the plugin on Windows

The ODBC header and include files should already be installed in the right directories. You just have to build the plugin as follows:

cd %QTDIR%\plugins\src\sqldrivers\odbc
qmake -o Makefile odbc.pro
nmake

If you are not using a Microsoft compiler, replace "nmake" with "make" in the statement above.

QPSQL7 - PostgreSQL version 6 and 7

General information

The QPSQL7 driver supports both version 6 and 7 of PostgreSQL. We recommend compiling the plugin with a recent version of the PostgreSQL Client API (libpq) because it is more stable and still downward compatible.

If you want to link the plugin against the libpq shipped with version 6 we recomment a recent version like PostgreSQL 6.5.3, otherwise a connection to a version 7 server may not work.

The driver auto-detects the server version of PostgreSQL after a connection was successful. If the server is too old or the version information cannot be determined a warning is issued.

For more information about PostgreSQL visit http://www.postgresql.org.

Unicode support

The QPSQL7 driver automatically detects whether the PostgreSQL database you are connecting to supports Unicode or not. Unicode is automatically used if the server supports it. Note that the driver only supports the UTF-8 encoding. If your database uses any other encoding, the server has to be compiled with Unicode conversion support.

Unicode support was introduced in PostgreSQL version 7.1 and it will only work if both the server and the client library have been compiled with multibyte support. More information about how to set up a multibyte enabled PostgreSQL server can be found in the PostgreSQL Administrator Guide, Chapter 5.

BLOB support

Binary Large Objects can be fetched but not inserted. Please use the PostgreSQL command lo_import to insert binary data into the database.

How to build the plugin on Unix/Linux

Just installing "libpq.so" and the corresponding header files is unfortunately not sufficient. You have to get the whole source distribution and run the configure script once (there is no need to build it if you have already installed a binary distribution).

Tell qmake where to find the PostgreSQL header files and shared libraries (here it is assumed that you extracted the PostgreSQL source code in /usr/src/psql and the shared library is installed in /usr/lib) and run make:

cd $QTDIR/plugins/src/sqldrivers/psql
qmake -o Makefile "INCLUDEPATH+=/usr/src/psql/src/include /usr/src/psql/src/interfaces/libpq" "LIBS+=-L/usr/lib -lpq" psql.pro
make

QTDS7 - Sybase Adaptive Server and Microsoft SQL Server

How to build the plugin on Unix/Linux

Under Unix, two libraries are available which support the TDS protocol:

- FreeTDS, a free implementation of the TDS protocol ( http://www.freetds.org ). Note that FreeTDS is not yet stable, so some functionality may not work as expected.

- Sybase Open Client, available from http://www.sybase.com Note for Linux users: Get the Open Client RPM from http://linux.sybase.com

Regardless of which library you use, the shared object file "libsybdb.so" is needed. Set the SYBASE environment variable to point to the directory where you installed the client library and execute qmake:

cd $QTDIR/plugins/src/sqldrivers/tds
qmake -o Makefile "INCLUDEPATH=$SYBASE/include" "LIBS=-L$SYBASE/lib -lsybdb"
make

How to build the plugin on Windows

You can either use the DB-Library supplied by Microsoft or the Sybase Open Client ( http://www.sybase.com ). You have to include NTWDBLIB.LIB to build the plugin:

cd %QTDIR%\plugins\src\sqldrivers\tds
qmake -o Makefile "LIBS+=NTWDBLIB.LIB" tds.pro
nmake

By default the Microsoft library is used on Windows, if you want to force the use of the Sybase Open Client, you have to define Q_USE_SYBASE in %QTDIR%\src\sql\drivers\tds\qsql_tds.cpp.

Troubleshooting

You should always use client libraries that have been compiled with the same compiler as you are using for your project. If you cannot get a source distibution to compile the client libraries yourself, you have to make sure that the pre-compiled library is compatible with your compiler, otherwise you will get a lot of "undefined symbols" errors. Some compilers have tools to convert libraries, e.g. Borland ships the tool COFF2OMF.EXE to convert libraries that have been generated with Microsoft Visual C++.

If the compilation of a plugin succeeds but it cannot be loaded, make sure that the following requirements are met:

  • Make sure you are using a shared Qt library, you cannot use the plugins with a static build.
  • Make sure that the environment variable QTDIR points to the right directory. Go to the $QTDIR/plugins/sqldrivers directory and make sure that the plugin exists in that directory.
  • Make sure that the client libraries of the DBMS are available on the system. On Unix, run the command ldd and pass the name of the plugin as parameter, for example ldd libqsqlmysql.so. You will get a warning if any of the client libraries couldn't be found. On Windows, you can use the dependency walker of Visual Studio.

How to write your own database driver

QSqlDatabase is responsible for loading and managing database driver plugins. When a database is added (see QSqlDatabase::addDatabase()), the appropriate driver plugin is loaded (using QSqlDriverPlugin). QSqlDatabase relies on the driver plugin to provide interfaces for QSqlDriver and QSqlResult.

QSqlDriver is an abstract base class which defines the functionality of a SQL database driver. This includes functions such as QSqlDriver::open() and QSqlDriver::close(). QSqlDriver is responsible for connecting to a database, establish the proper environment, etc. In addition, QSqlDriver can create QSqlQuery objects appropriate for the particular database API. QSqlDatabase forwards many of its function calls directly to QSqlDriver which provides the concrete implementation.

QSqlResult is an abstract base class which defines the functionality of a SQL database query. This includes statements such as SELECT, UPDATE, or ALTER TABLE. QSqlResult contains functions such as QSqlResult::next() and QSqlResult::value(). QSqlResult is responsible for sending queries to the database, returning result data, etc. QSqlQuery forwards many of its function calls directly to QSqlResult which provides the concrete implementation.

QSqlDriver and QSqlResult are closely connected. When implementing a Qt SQL driver, both of these classes must to be subclassed and the abstract virtual methods in each class must be implemented.

To implement a Qt SQL driver as a plugin (so that it is recognized and loaded by the Qt library at runtime), the driver must use the Q_EXPORT_PLUGIN macro. Please read the Qt Plugin documentation for more information on this. You can also check out how this is done in the SQL plugins that is provided with Qt in QTDIR/plugins/src/sqldrivers and QTDIR/src/sql/drivers.


Qt SQL Examples

The following example programs show how to use the Qt SQL classes.

SQL Table

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


sql/overview/basicbrowsing2/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlDatabase *oracledb = QSqlDatabase::database( "ORACLE" );
        // Copy data from the oracle database to the ODBC (default)
        // database
        QSqlQuery target;
        QSqlQuery query( "SELECT id, name FROM people;", oracledb );
        int count = 0;
        if ( query.isActive() ) {
            while ( query.next() ) {
                target.exec( "INSERT INTO people ( id, name ) VALUES ( " +
                              query.value(0).toString() +
                              ", '" + query.value(1).toString() +  "' );" );
                if ( target.isActive() )
                    count += target.numRowsAffected();
            }
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/basicbrowsing/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlDatabase *oracledb = QSqlDatabase::database( "ORACLE" );
        // Copy data from the oracle database to the ODBC (default)
        // database
        QSqlQuery target;
        QSqlQuery query( "SELECT id, name FROM people;", oracledb );
        if ( query.isActive() ) {
            while ( query.next() ) {
                target.exec( "INSERT INTO people ( id, name ) VALUES ( " +
                              query.value(0).toString() +
                              ", '" + query.value(1).toString() +  "' );" );
            }
        }
    }

    return 0;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/basicdatamanip/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    int rows = 0;

    if ( createConnections() ) {
        QSqlQuery query( "INSERT INTO staff ( id, forename, surname, salary ) "
                     "VALUES ( 1155, 'Ginger', 'Davis', 50000 );" );
        if ( query.isActive() ) rows += query.numRowsAffected() ;

        query.exec( "UPDATE staff SET salary=60000 WHERE id=1155;" );
        if ( query.isActive() ) rows += query.numRowsAffected() ;

        query.exec( "DELETE FROM staff WHERE id=1155;" );
        if ( query.isActive() ) rows += query.numRowsAffected() ;
    }

    return ( rows == 3 ) ? 0 : 1;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/connect1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include "../login.h"

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( defaultDB ) {
        defaultDB->setDatabaseName( DB_SALES_DBNAME );
        defaultDB->setUserName( DB_SALES_USER );
        defaultDB->setPassword( DB_SALES_PASSWD );
        defaultDB->setHostName( DB_SALES_HOST );

        if ( defaultDB->open() ) {
            // Database successfully opened; we can now issue SQL commands.
        }
    }

    return 0;
}


sql/overview/create_connections/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        // Databases successfully opened; get pointers to them:
        QSqlDatabase *oracledb = QSqlDatabase::database( "ORACLE" );
        // Now we can now issue SQL commands to the oracle connection
        // or to the default connection
    }

    return 0;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/custom1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"

CustomEdit::CustomEdit( QWidget *parent, const char *name ) :
    QLineEdit( parent, name )
{
    connect( this, SIGNAL(textChanged(const QString &)),
             this, SLOT(changed(const QString &)) );
}

void CustomEdit::changed( const QString &line )
{
    setUpperLine( line );
}

void CustomEdit::setUpperLine( const QString &line )
{
    upperLineText = line.upper();
    setText( upperLineText );
}

QString CustomEdit::upperLine() const
{
    return upperLineText;
}

FormDialog::FormDialog()
{
    QLabel      *forenameLabel  = new QLabel( "Forename:", this );
    CustomEdit  *forenameEdit   = new CustomEdit( this );
    QLabel      *surnameLabel   = new QLabel( "Surname:", this );
    CustomEdit  *surnameEdit    = new CustomEdit( this );
    QLabel      *salaryLabel    = new QLabel( "Salary:", this );
    QLineEdit   *salaryEdit     = new QLineEdit( this );
    salaryEdit->setAlignment( Qt::AlignRight );
    QPushButton *saveButton     = new QPushButton( "&Save", this );
    connect( saveButton, SIGNAL(clicked()), this, SLOT(save()) );

    QGridLayout *grid = new QGridLayout( this );
    grid->addWidget( forenameLabel, 0, 0 );
    grid->addWidget( forenameEdit,  0, 1 );
    grid->addWidget( surnameLabel,  1, 0 );
    grid->addWidget( surnameEdit,   1, 1 );
    grid->addWidget( salaryLabel,   2, 0 );
    grid->addWidget( salaryEdit,    2, 1 );
    grid->addWidget( saveButton,    3, 0 );
    grid->activate();

    staffCursor = new QSqlCursor( "staff" );
    staffCursor->setTrimmed( "forename", TRUE );
    staffCursor->setTrimmed( "surname",  TRUE );
    idIndex = staffCursor->index( "id" );
    staffCursor->select( idIndex );
    staffCursor->first();

    propMap = new QSqlPropertyMap;
    propMap->insert( forenameEdit->className(), "upperLine" );

    sqlForm = new QSqlForm( this );
    sqlForm->setRecord( staffCursor->primeUpdate() );
    sqlForm->installPropertyMap( propMap );
    sqlForm->insert( forenameEdit, "forename" );
    sqlForm->insert( surnameEdit, "surname" );
    sqlForm->insert( salaryEdit, "salary" );
    sqlForm->readFields();
}

FormDialog::~FormDialog()
{
    delete staffCursor;
}

void FormDialog::save()
{
    sqlForm->writeFields();
    staffCursor->update();
    staffCursor->select( idIndex );
    staffCursor->first();
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( ! createConnections() )
        return 1;

    FormDialog *formDialog = new FormDialog();
    formDialog->show();
    app.setMainWidget( formDialog );

    return app.exec();
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/custom1/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qdialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qsqlform.h>
#include <qsqlpropertymap.h>
#include "../login.h"

bool createConnections();

class CustomEdit : public QLineEdit
{
    Q_OBJECT
    Q_PROPERTY( QString upperLine READ upperLine WRITE setUpperLine )
    public:
        CustomEdit( QWidget *parent=0, const char *name=0 );
        QString upperLine() const;
        void setUpperLine( const QString &line );
    public slots:
        void changed( const QString &line );
    private:
        QString upperLineText;
};

class FormDialog : public QDialog
{
    Q_OBJECT
    public:
        FormDialog();
        ~FormDialog();
    public slots:
        void save();
    private:
        QSqlCursor *staffCursor;
        QSqlForm *sqlForm;
        QSqlPropertyMap *propMap;
        QSqlIndex idIndex;
};


sql/overview/del/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "prices" );
        cur.select( "id=999" );
        if ( cur.next() ) {
            cur.primeDelete();
            cur.del();
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/extract/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "creditors" );

        QStringList orderFields = QStringList() << "surname" << "forename";
        QSqlIndex order = cur.index( orderFields );

        QStringList filterFields = QStringList() << "surname" << "city";
        QSqlIndex filter = cur.index( filterFields );
        cur.setValue( "surname", "Chirac" );
        cur.setValue( "city", "Paris" );

        cur.select( filter, order );

        while ( cur.next() ) {
            int id = cur.value( "id" ).toInt();
            QString name = cur.value( "forename" ).toString() + " " +
                           cur.value( "surname" ).toString();
            qDebug( QString::number( id ) + ": " + name );
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/form1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qdialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qsqlform.h>
#include "../login.h"

bool createConnections();

class FormDialog : public QDialog
{
    public:
        FormDialog();
};

FormDialog::FormDialog()
{
    QLabel *forenameLabel   = new QLabel( "Forename:", this );
    QLabel *forenameDisplay = new QLabel( this );
    QLabel *surnameLabel    = new QLabel( "Surname:", this );
    QLabel *surnameDisplay  = new QLabel( this );
    QLabel *salaryLabel     = new QLabel( "Salary:", this );
    QLineEdit *salaryEdit   = new QLineEdit( this );

    QGridLayout *grid = new QGridLayout( this );
    grid->addWidget( forenameLabel,     0, 0 );
    grid->addWidget( forenameDisplay,   0, 1 );
    grid->addWidget( surnameLabel,      1, 0 );
    grid->addWidget( surnameDisplay,    1, 1 );
    grid->addWidget( salaryLabel,       2, 0 );
    grid->addWidget( salaryEdit,        2, 1 );
    grid->activate();

    QSqlCursor staffCursor( "staff" );
    staffCursor.select();
    staffCursor.next();

    QSqlForm sqlForm( this );
    sqlForm.setRecord( staffCursor.primeUpdate() );
    sqlForm.insert( forenameDisplay, "forename" );
    sqlForm.insert( surnameDisplay, "surname" );
    sqlForm.insert( salaryEdit, "salary" );
    sqlForm.readFields();
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( ! createConnections() ) return 1;

    FormDialog *formDialog = new FormDialog();
    formDialog->show();
    app.setMainWidget( formDialog );

    return app.exec();
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/form2/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qdialog.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qsqlform.h>
#include "../login.h"

bool createConnections();

class FormDialog : public QDialog
{
    Q_OBJECT
    public:
        FormDialog();
        ~FormDialog();
    public slots:
        void save();
    private:
        QSqlCursor staffCursor;
        QSqlForm *sqlForm;
        QSqlIndex idIndex;
};


sql/overview/insert/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        int count = 0;
        QSqlCursor cur( "prices" );
        QStringList names = QStringList() <<
            "Screwdriver" << "Hammer" << "Wrench" << "Saw";
        int id = 20;
        for ( QStringList::Iterator name = names.begin();
              name != names.end(); ++name ) {
            QSqlRecord *buffer = cur.primeInsert();
            buffer->setValue( "id", id );
            buffer->setValue( "name", *name );
            buffer->setValue( "price", 100.0 + (double)id );
            count += cur.insert();
            id++;
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/navigating/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlQuery query( "SELECT id, name FROM people ORDER BY name;" );
        if ( ! query.isActive() ) return 1; // Query failed
        int i;
        i = query.size();               // In this example we have 9 records; i == 9.
        query.first();                  // Moves to the first record.
        i = query.at();                 // i == 0
        query.last();                   // Moves to the last record.
        i = query.at();                 // i == 8
        query.seek( query.size() / 2 ); // Moves to the middle record.
        i = query.at();                 // i == 4
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/order1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "staff" );
        QStringList fields = QStringList() << "surname" << "forename";
        QSqlIndex order = cur.index( fields );
        cur.select( order );
        while ( cur.next() ) {
            qDebug( cur.value( "id" ).toString() + ": " +
                    cur.value( "surname" ).toString() + " " +
                    cur.value( "forename" ).toString() );
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/order2/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "staff" );
        QStringList fields = QStringList() << "id" << "forename";
        QSqlIndex order = cur.index( fields );
        QSqlIndex filter = cur.index( "surname" );
        cur.setValue( "surname", "Bloggs" );
        cur.select( filter, order );
        while ( cur.next() ) {
            qDebug( cur.value( "id" ).toString() + ": " +
                    cur.value( "surname" ).toString() + " " +
                    cur.value( "forename" ).toString() );
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/retrieve1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlQuery query( "SELECT id, surname FROM staff;" );
        if ( query.isActive() ) {
            while ( query.next() ) {
                qDebug( query.value(0).toString() + ": " +
                        query.value(1).toString() );
            }
        }
    }

    return 0;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/retrieve2/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "staff" ); // Specify the table/view name
        cur.select(); // We'll retrieve every record
        while ( cur.next() ) {
            qDebug( cur.value( "id" ).toString() + ": " +
                    cur.value( "surname" ).toString() + " " +
                    cur.value( "salary" ).toString() );
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qdatatable.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor invoiceItemCursor( "invoiceitem" );

        QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

        app.setMainWidget( invoiceItemTable );

        invoiceItemTable->addColumn( "pricesid", "PriceID" );
        invoiceItemTable->addColumn( "quantity", "Quantity" );
        invoiceItemTable->addColumn( "paiddate", "Paid" );

        invoiceItemTable->refresh();
        invoiceItemTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass2/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"
#include <qdatatable.h>

InvoiceItemCursor::InvoiceItemCursor() :
    QSqlCursor( "invoiceitem" )
{
    // NOOP
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        InvoiceItemCursor invoiceItemCursor;

        QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

        app.setMainWidget( invoiceItemTable );

        invoiceItemTable->addColumn( "pricesid", "PriceID" );
        invoiceItemTable->addColumn( "quantity", "Quantity" );
        invoiceItemTable->addColumn( "paiddate", "Paid" );

        invoiceItemTable->refresh();
        invoiceItemTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass2/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

class QSqlRecord;

bool createConnections();

class InvoiceItemCursor : public QSqlCursor
{
    public:
        InvoiceItemCursor();
};


sql/overview/subclass3/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"
#include <qdatatable.h>

InvoiceItemCursor::InvoiceItemCursor() :
    QSqlCursor( "invoiceitem" )
{
    QSqlFieldInfo productName( "productname", QVariant::String );
    append( productName );
    setCalculated( productName.name(), TRUE );
}

QVariant InvoiceItemCursor::calculateField( const QString & name )
{
    if ( name == "productname" ) {
        QSqlQuery query( "SELECT name FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return query.value( 0 );
    }

    return QVariant( QString::null );
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        InvoiceItemCursor invoiceItemCursor;

        QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

        app.setMainWidget( invoiceItemTable );

        invoiceItemTable->addColumn( "productname", "Product" );
        invoiceItemTable->addColumn( "quantity",    "Quantity" );
        invoiceItemTable->addColumn( "paiddate",    "Paid" );

        invoiceItemTable->refresh();
        invoiceItemTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass3/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

class QSqlRecord;

bool createConnections();

class InvoiceItemCursor : public QSqlCursor
{
    public:
        InvoiceItemCursor();
    protected:
        QVariant calculateField( const QString & name );
};


sql/overview/subclass4/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"
#include <qdatatable.h>

InvoiceItemCursor::InvoiceItemCursor() :
    QSqlCursor( "invoiceitem" )
{
    QSqlFieldInfo productName( "productname", QVariant::String );
    append( productName );
    setCalculated( productName.name(), TRUE );

    QSqlFieldInfo productPrice( "price", QVariant::Double );
    append( productPrice );
    setCalculated( productPrice.name(), TRUE );

    QSqlFieldInfo productCost( "cost", QVariant::Double );
    append( productCost );
    setCalculated( productCost.name(), TRUE );
}

QVariant InvoiceItemCursor::calculateField( const QString & name )
{

    if ( name == "productname" ) {
        QSqlQuery query( "SELECT name FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return query.value( 0 );
    }
    else if ( name == "price" ) {
        QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return query.value( 0 );
    }
    else if ( name == "cost" ) {
        QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return QVariant( query.value( 0 ).toDouble() *
                             value( "quantity").toDouble() );
    }

    return QVariant( QString::null );
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        InvoiceItemCursor invoiceItemCursor;

        QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

        app.setMainWidget( invoiceItemTable );

        invoiceItemTable->addColumn( "productname", "Product" );
        invoiceItemTable->addColumn( "price",       "Price" );
        invoiceItemTable->addColumn( "quantity",    "Quantity" );
        invoiceItemTable->addColumn( "cost",        "Cost" );
        invoiceItemTable->addColumn( "paiddate",    "Paid" );

        invoiceItemTable->refresh();
        invoiceItemTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass4/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

class QSqlRecord;

bool createConnections();

class InvoiceItemCursor : public QSqlCursor
{
    public:
        InvoiceItemCursor();
    protected:
        QVariant calculateField( const QString & name );
};


sql/overview/subclass5/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"
#include <qdatatable.h>

InvoiceItemCursor::InvoiceItemCursor() :
    QSqlCursor( "invoiceitem" )
{
    QSqlFieldInfo productName( "productname", QVariant::String );
    append( productName );
    setCalculated( productName.name(), TRUE );

    QSqlFieldInfo productPrice( "price", QVariant::Double );
    append( productPrice );
    setCalculated( productPrice.name(), TRUE );

    QSqlFieldInfo productCost( "cost", QVariant::Double );
    append( productCost );
    setCalculated( productCost.name(), TRUE );
}

QVariant InvoiceItemCursor::calculateField( const QString & name )
{

    if ( name == "productname" ) {
        QSqlQuery query( "SELECT name FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return query.value( 0 );
    }
    else if ( name == "price" ) {
        QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return query.value( 0 );
    }
    else if ( name == "cost" ) {
        QSqlQuery query( "SELECT price FROM prices WHERE id=" +
                     field( "pricesid" )->value().toString() + ";" );
        if ( query.next() )
            return QVariant( query.value( 0 ).toDouble() *
                             value( "quantity").toDouble() );
    }

    return QVariant( QString::null );
}

QSqlRecord *InvoiceItemCursor::primeInsert()
{
    QSqlRecord *buffer = editBuffer();
    QSqlQuery query( "SELECT NEXTVAL( 'invoiceitem_seq' );" );
    if ( query.next() )
        buffer->setValue( "id", query.value( 0 ) );
    buffer->setValue( "paiddate", QDate::currentDate() );
    buffer->setValue( "quantity", 1 );

    return buffer;
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        InvoiceItemCursor invoiceItemCursor;

        QDataTable *invoiceItemTable = new QDataTable( &invoiceItemCursor );

        app.setMainWidget( invoiceItemTable );

        invoiceItemTable->addColumn( "productname", "Product" );
        invoiceItemTable->addColumn( "price",       "Price" );
        invoiceItemTable->addColumn( "quantity",    "Quantity" );
        invoiceItemTable->addColumn( "cost",        "Cost" );
        invoiceItemTable->addColumn( "paiddate",    "Paid" );

        invoiceItemTable->refresh();
        invoiceItemTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/subclass5/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qdatetime.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

class QSqlRecord;

bool createConnections();

class InvoiceItemCursor : public QSqlCursor
{
    public:
        InvoiceItemCursor();
        QSqlRecord *primeInsert();
    protected:
        QVariant calculateField( const QString & name );
};


sql/overview/table1/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qdatatable.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor staffCursor( "staff" );
        QDataTable *staffTable = new QDataTable( &staffCursor, TRUE );
        app.setMainWidget( staffTable );
        staffTable->refresh();
        staffTable->show();

        return app.exec();
    }

    return 0;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/table2/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qdatatable.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor staffCursor( "staff" );

        QDataTable *staffTable = new QDataTable( &staffCursor );

        app.setMainWidget( staffTable );

        staffTable->addColumn( "forename", "Forename" );
        staffTable->addColumn( "surname",  "Surname" );
        staffTable->addColumn( "salary",   "Annual Salary" );

        QStringList order = QStringList() << "surname" << "forename";
        staffTable->setSort( order );

        staffTable->refresh();
        staffTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/table3/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"
#include <qdatatable.h>

StatusPicker::StatusPicker( QWidget *parent, const char *name )
    : QComboBox( parent, name )
{
    QSqlCursor cur( "status" );
    cur.select( cur.index( "name" ) );

    int i = 0;
    while ( cur.next() ) {
        insertItem( cur.value( "name" ).toString(), i );
        index2id[i] = cur.value( "id" ).toInt();
        i++;
    }
}

int StatusPicker::statusId() const
{
    return index2id[ currentItem() ];
}

void StatusPicker::setStatusId( int statusid )
{
    QMap<int,int>::Iterator it;
    for ( it = index2id.begin(); it != index2id.end(); ++it ) {
        if ( it.data() == statusid ) {
            setCurrentItem( it.key() );
            break;
        }
    }
}

QWidget *CustomSqlEditorFactory::createEditor(
    QWidget *parent, const QSqlField *field )
{
    if ( field->name() == "statusid" ) {
        QWidget *editor = new StatusPicker( parent );
        return editor;
    }

    return QSqlEditorFactory::createEditor( parent, field );
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor staffCursor( "staff" );

        QDataTable              *staffTable     = new QDataTable( &staffCursor );
        QSqlPropertyMap         *propMap        = new QSqlPropertyMap();
        CustomSqlEditorFactory  *editorFactory  = new CustomSqlEditorFactory();
        propMap->insert( "StatusPicker", "statusid" );
        staffTable->installPropertyMap( propMap );
        staffTable->installEditorFactory( editorFactory );

        app.setMainWidget( staffTable );

        staffTable->addColumn( "forename", "Forename" );
        staffTable->addColumn( "surname",  "Surname" );
        staffTable->addColumn( "salary",   "Annual Salary" );
        staffTable->addColumn( "statusid", "Status" );

        QStringList order = QStringList() << "surname" << "forename";
        staffTable->setSort( order );

        staffTable->refresh();
        staffTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/table3/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qcombobox.h>
#include <qmap.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qsqleditorfactory.h>
#include <qsqlpropertymap.h>
#include "../login.h"

bool createConnections();

class StatusPicker : public QComboBox
{
    Q_OBJECT
    Q_PROPERTY( int statusid READ statusId WRITE setStatusId )
    public:
        StatusPicker( QWidget *parent=0, const char *name=0 );
        int statusId() const;
        void setStatusId( int id );
    private:
        QMap< int, int > index2id;
};

class CustomSqlEditorFactory : public QSqlEditorFactory
{
    Q_OBJECT
    public:
        QWidget *createEditor( QWidget *parent, const QSqlField *field );
};


sql/overview/table4/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "main.h"

StatusPicker::StatusPicker( QWidget *parent, const char *name )
    : QComboBox( parent, name )
{
    QSqlCursor cur( "status" );
    cur.select( cur.index( "name" ) );

    int i = 0;
    while ( cur.next() ) {
        insertItem( cur.value( "name" ).toString(), i );
        index2id[i] = cur.value( "id" ).toInt();
        i++;
    }
}

int StatusPicker::statusId() const
{
    return index2id[ currentItem() ];
}

void StatusPicker::setStatusId( int statusid )
{
    QMap<int,int>::Iterator it;
    for ( it = index2id.begin(); it != index2id.end(); ++it ) {
        if ( it.data() == statusid ) {
            setCurrentItem( it.key() );
            break;
        }
    }
}

void CustomTable::paintField( QPainter * p, const QSqlField* field,
                              const QRect & cr, bool b)
{
    if ( !field )
        return;
    if ( field->name() == "statusid" ) {
        QSqlQuery query( "SELECT name FROM status WHERE id=" +
                     field->value().toString() );
        QString text;
        if ( query.next() ) {
            text = query.value( 0 ).toString();
        }
        p->drawText( 2,2, cr.width()-4, cr.height()-4, fieldAlignment( field ), text );
    }
    else {
        QDataTable::paintField( p, field, cr, b) ;
    }
}

QWidget *CustomSqlEditorFactory::createEditor(
    QWidget *parent, const QSqlField *field )
{
    if ( field->name() == "statusid" ) {
        QWidget *editor = new StatusPicker( parent );
        return editor;
    }

    return QSqlEditorFactory::createEditor( parent, field );
}

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor staffCursor( "staff" );

        CustomTable             *staffTable     = new CustomTable( &staffCursor );
        QSqlPropertyMap         *propMap        = new QSqlPropertyMap();
        CustomSqlEditorFactory  *editorFactory  = new CustomSqlEditorFactory();
        propMap->insert( "StatusPicker", "statusid" );
        staffTable->installPropertyMap( propMap );
        staffTable->installEditorFactory( editorFactory );

        app.setMainWidget( staffTable );

        staffTable->addColumn( "forename", "Forename" );
        staffTable->addColumn( "surname",  "Surname" );
        staffTable->addColumn( "salary",   "Annual Salary" );
        staffTable->addColumn( "statusid", "Status" );

        QStringList order = QStringList() << "surname" << "forename";
        staffTable->setSort( order );

        staffTable->refresh();
        staffTable->show();

        return app.exec();
    }

    return 1;
}

bool createConnections()
{
    // create the default database connection
    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    // create a named connection to oracle
    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


sql/overview/table4/main.h Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qcombobox.h>
#include <qmap.h>
#include <qpainter.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include <qsqleditorfactory.h>
#include <qsqlpropertymap.h>
#include <qdatatable.h>
#include "../login.h"

bool createConnections();

class StatusPicker : public QComboBox
{
    Q_OBJECT
    Q_PROPERTY( int statusid READ statusId WRITE setStatusId )
public:
    StatusPicker( QWidget *parent=0, const char *name=0 );
    int statusId() const;
    void setStatusId( int id );
private:
    QMap< int, int > index2id;
};

class CustomTable : public QDataTable
{
    Q_OBJECT
public:
    CustomTable(
            QSqlCursor *cursor, bool autoPopulate = FALSE,
            QWidget * parent = 0, const char * name = 0 ) :
        QDataTable( cursor, autoPopulate, parent, name ) {}
    void paintField(
            QPainter * p, const QSqlField* field, const QRect & cr, bool );

};

class CustomSqlEditorFactory : public QSqlEditorFactory
{
    Q_OBJECT
public:
    QWidget *createEditor( QWidget *parent, const QSqlField *field );
};


sql/overview/update/main.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../login.h"

bool createConnections();

int main( int argc, char *argv[] )
{
    QApplication app( argc, argv );

    if ( createConnections() ) {
        QSqlCursor cur( "prices" );
        cur.select( "id=202" );
        if ( cur.next() ) {
            QSqlRecord *buffer = cur.primeUpdate();
            double price = buffer->value( "price" ).toDouble();
            double newprice = price * 1.05;
            buffer->setValue( "price", newprice );
            cur.update();
        }
    }

    return 0;
}

bool createConnections()
{

    QSqlDatabase *defaultDB = QSqlDatabase::addDatabase( DB_SALES_DRIVER );
    if ( ! defaultDB ) {
        qWarning( "Failed to connect to driver" );
        return FALSE;
    }
    defaultDB->setDatabaseName( DB_SALES_DBNAME );
    defaultDB->setUserName( DB_SALES_USER );
    defaultDB->setPassword( DB_SALES_PASSWD );
    defaultDB->setHostName( DB_SALES_HOST );
    if ( ! defaultDB->open() ) {
        qWarning( "Failed to open sales database: " +
                  defaultDB->lastError().driverText() );
        qWarning( defaultDB->lastError().databaseText() );
        return FALSE;
    }

    QSqlDatabase *oracle = QSqlDatabase::addDatabase( DB_ORDERS_DRIVER, "ORACLE" );
    if ( ! oracle ) {
        qWarning( "Failed to connect to oracle driver" );
        return FALSE;
    }
    oracle->setDatabaseName( DB_ORDERS_DBNAME );
    oracle->setUserName( DB_ORDERS_USER );
    oracle->setPassword( DB_ORDERS_PASSWD );
    oracle->setHostName( DB_ORDERS_HOST );
    if ( ! oracle->open() ) {
        qWarning( "Failed to open orders database: " +
                  oracle->lastError().driverText() );
        qWarning( oracle->lastError().databaseText() );
        return FALSE;
    }

    return TRUE;
}


SQL Table

This example shows how to use a QDataTable to browse data in a SQL database.

Implementation:

/****************************************************************************
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qsqldatabase.h>
#include <qdatatable.h>
#include <qsqlcursor.h>
#include <qmessagebox.h>

/* Modify the following to match your environment */
#define DRIVER       "QPSQL7"  /* see the Qt SQL documentation for a list of available drivers */
#define DATABASE     "simpledb" /* the name of your database */
#define USER         "trond"   /* user name with appropriate rights */
#define PASSWORD     "trond"   /* password for USER */
#define HOST         "silverfish.troll.no" /* host on which the database is running */

class SimpleCursor : public QSqlCursor
{
public:
    SimpleCursor () : QSqlCursor( "simpletable" ) {}
protected:
    QSqlRecord* primeInsert()
    {
        /* a real-world application would use sequences, or the like */
        QSqlRecord* buf = QSqlCursor::primeInsert();
        QSqlQuery q( "select max(id)+1 from simpletable;" );
        if ( q.next() )
               buf->setValue( "id", q.value(0) );
        return buf;
    }
};

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );

    QSqlDatabase * db = QSqlDatabase::addDatabase( DRIVER );
    db->setDatabaseName( DATABASE );
    db->setUserName( USER );
    db->setPassword( PASSWORD );
    db->setHostName( HOST );

    if( !db->open() ){
        QMessageBox::information( 0, "Unable to open database",
                                  db->lastError().databaseText() + "\nPlease read the README file in the sqltable directory for more information.");
        return 1;
    }

    SimpleCursor cursor;

    QDataTable table( &cursor ); /* data table uses our cursor */
    table.addColumn( "name", "Name" );
    table.addColumn( "address", "Address" );
    table.setSorting( TRUE );

    a.setMainWidget( &table );
    table.refresh(); /* load data */
    table.show();    /* show widget */

    return a.exec();
}

See also Qt SQL Examples.


表格样例

另一个QTable样例。

头文件：

实现：

/****************************************************************************
** $Id:  qt/statistics.cpp   3.0.5   edited Feb 18 11:55 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "statistics.h"

#include <qdir.h>
#include <qstringlist.h>
#include <qheader.h>
#include <qcombobox.h>
#include <stdlib.h>

const char* dirs[] = {
    "kernel",
    "tools",
    "widgets",
    "dialogs",
    "xml",
    "table",
    "network",
    "opengl",
    "canvas",
    0
};

Table::Table()
    : QTable( 10, 100, 0, "table" )
{
    setSorting( TRUE );
    horizontalHeader()->setLabel( 0, tr( "File" ) );
    horizontalHeader()->setLabel( 1, tr( "Size (bytes)" ) );
    horizontalHeader()->setLabel( 2, tr( "Use in Sum" ) );
    initTable();
    adjustColumn( 0 );

    // if the user edited something we might need to recalculate the sum
    connect( this, SIGNAL( valueChanged( int, int ) ),
             this, SLOT( recalcSum( int, int ) ) );
}

void Table::initTable()
{
    // read all the Qt source and header files into a list
    QStringList all;
    int i = 0;
    QString qtdir = getenv( "QTDIR" );
    while ( dirs[ i ] ) {
        QDir dir( qtdir + "/src/" + dirs[ i ] );
        QStringList lst = dir.entryList( "*.cpp; *.h" );
        for ( QStringList::Iterator it = lst.begin(); it != lst.end(); ++it ) {
            if ( ( *it ).contains( "moc" ) )
                continue;
            all << QString( dirs[ i ] ) + "/" + *it;
        }
        ++i;
    }

    // set the number of rows we'll need for the table
    setNumRows( all.count() + 1 );
    i = 0;
    int sum = 0;

    // insert the data into the table
    for ( QStringList::Iterator it = all.begin(); it != all.end(); ++it ) {
        setText( i, 0, *it );
        QFile f( qtdir + "/src/" + *it );
        setText( i, 1, QString::number( f.size() ) );
        ComboItem *ci = new ComboItem( this, QTableItem::WhenCurrent );
        setItem( i++, 2, ci );
        sum += f.size();
    }

    // last row should show the sum
    TableItem *i1 = new TableItem( this, QTableItem::Never, tr( "Sum" ) );
    setItem( i, 0, i1 );
    TableItem *i2 = new TableItem( this, QTableItem::Never, QString::number( sum ) );
    setItem( i, 1, i2 );
}

void Table::recalcSum( int, int col )
{
    // only recalc if a value in the second or third column changed
    if ( col < 1 || col > 2 )
        return;

    // recalc sum
    int sum = 0;
    for ( int i = 0; i < numRows() - 1; ++i ) {
        if ( text( i, 2 ) == "No" )
            continue;
        sum += text( i, 1 ).toInt();
    }

    // insert calculated data
    TableItem *i1 = new TableItem( this, QTableItem::Never, tr( "Sum" ) );
    setItem( numRows() - 1, 0, i1 );
    TableItem *i2 = new TableItem( this, QTableItem::Never, QString::number( sum ) );
    setItem( numRows() - 1, 1, i2 );
}

void Table::sortColumn( int col, bool ascending, bool /*wholeRows*/ )
{
    // sum row should not be sorted, so get rid of it for now
    clearCell( numRows() - 1, 0 );
    clearCell( numRows() - 1, 1 );
    // do sort
    QTable::sortColumn( col, ascending, TRUE );
    // re-insert sum row
    recalcSum( 0, 1 );
}

void TableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected )
{
    QColorGroup g( cg );
    // last row is the sum row - we want to make it more visible by
    // using a red background
    if ( row() == table()->numRows() - 1 )
        g.setColor( QColorGroup::Base, red );
    QTableItem::paint( p, g, cr, selected );
}

ComboItem::ComboItem( QTable *t, EditType et )
    : QTableItem( t, et, "Yes" ), cb( 0 )
{
    // we do not want this item to be replaced
    setReplaceable( FALSE );
}

QWidget *ComboItem::createEditor() const
{
    // create an editor - a combobox in our case
    ( (ComboItem*)this )->cb = new QComboBox( table()->viewport() );
    QObject::connect( cb, SIGNAL( activated( int ) ), table(), SLOT( doValueChanged() ) );
    cb->insertItem( "Yes" );
    cb->insertItem( "No" );
    // and initialize it
    cb->setCurrentItem( text() == "No" ? 1 : 0 );
    return cb;
}

void ComboItem::setContentFromEditor( QWidget *w )
{
    // the user changed the value of the combobox, so synchronize the
    // value of the item (its text), with the value of the combobox
    if ( w->inherits( "QComboBox" ) )
        setText( ( (QComboBox*)w )->currentText() );
    else
        QTableItem::setContentFromEditor( w );
}

void ComboItem::setText( const QString &s )
{
    if ( cb ) {
        // initialize the combobox from the text
        if ( s == "No" )
            cb->setCurrentItem( 1 );
        else
            cb->setCurrentItem( 0 );
    }
    QTableItem::setText( s );
}

主文件：

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "statistics.h"
#include <qapplication.h>
int main( int argc, char **argv )
{
    QApplication a(argc,argv);

    Table t;
    a.setMainWidget( &t );
    t.show();
    return a.exec();
}

也参见表格例程。

Copyright © 2002
Trolltech
Trademarks
译者:farfareast

Qt 3.0.5版


t7/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 7
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );
}

int LCDRange::value() const
{
    return slider->value();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}


t7/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 7
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );

    int value() const;

public slots:
    void setValue( int );

signals:
    void valueChanged( int );

private:
    QSlider *slider;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t7/main.cpp Example File

/****************************************************************
**
** Qt tutorial 7
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qvbox.h>
#include <qgrid.h>

#include "lcdrange.h"

class MyWidget : public QVBox
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    QGrid *grid = new QGrid( 4, this );

    LCDRange *previous = 0;
    for( int r = 0 ; r < 4 ; r++ ) {
        for( int c = 0 ; c < 4 ; c++ ) {
            LCDRange* lr = new LCDRange( grid );
            if ( previous )
                connect( lr, SIGNAL(valueChanged(int)),
                         previous, SLOT(setValue(int)) );
            previous = lr;
        }
    }
}

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    MyWidget w;
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t8/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 8
**
****************************************************************/

#include "cannon.h"
#include <qpainter.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint();
    emit angleChanged( ang );
}

void CannonField::paintEvent( QPaintEvent * )
{
    QString s = "Angle = " + QString::number( ang );
    QPainter p( this );
    p.drawText( 200, 200, s );
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t8/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 8
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int angle() const { return ang; }
    QSizePolicy sizePolicy() const;

public slots:
    void setAngle( int degrees );

signals:
    void angleChanged( int );

protected:
    void paintEvent( QPaintEvent * );

private:
    int ang;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t8/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 8
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );
}

int LCDRange::value() const
{
    return slider->value();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
      qWarning( "LCDRange::setRange(%d,%d)\n"
               "\tRange must be 0..99\n"
               "\tand minVal must not be greater than maxVal",
               minVal, maxVal );
      return;
    }
    slider->setRange( minVal, maxVal );
}


t8/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 8
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );

    int value() const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );

signals:
    void valueChanged( int );

private:
    QSlider  *slider;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t8/main.cpp Example File

/****************************************************************
**
** Qt tutorial 8
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

class MyWidget: public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle = new LCDRange( this, "angle" );
    angle->setRange( 5, 70 );

    CannonField *cannonField
        = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    //2x2, 10 pixel border

    grid->addWidget( quit, 0, 0 );
    grid->addWidget( angle, 1, 0, Qt::AlignTop );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    angle->setValue( 60 );
    angle->setFocus();
}

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    MyWidget w;
    w.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t9/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 9
**
****************************************************************/

#include "cannon.h"
#include <qpainter.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint();
    emit angleChanged( ang );
}

void CannonField::paintEvent( QPaintEvent * )
{
    QPainter p( this );

    p.setBrush( blue );
    p.setPen( NoPen );

    p.translate( 0, rect().bottom() );
    p.drawPie( QRect(-35, -35, 70, 70), 0, 90*16 );
    p.rotate( -ang );
    p.drawRect( QRect(33, -4, 15, 8) );
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t9/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 8
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int angle() const { return ang; }
    QSizePolicy sizePolicy() const;

public slots:
    void setAngle( int degrees );

signals:
    void angleChanged( int );

protected:
    void paintEvent( QPaintEvent * );

private:
    int ang;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t9/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 8
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );
}

int LCDRange::value() const
{
    return slider->value();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
      qWarning( "LCDRange::setRange(%d,%d)\n"
               "\tRange must be 0..99\n"
               "\tand minVal must not be greater than maxVal",
               minVal, maxVal );
      return;
    }
    slider->setRange( minVal, maxVal );
}


t9/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 8
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );

    int value() const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );

signals:
    void valueChanged( int );

private:
    QSlider  *slider;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t9/main.cpp Example File

/****************************************************************
**
** Qt tutorial 9
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

class MyWidget: public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle = new LCDRange( this, "angle" );
    angle->setRange( 5, 70 );

    CannonField *cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( angle, 1, 0, Qt::AlignTop );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    angle->setValue( 60 );
    angle->setFocus();
}

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    MyWidget w;
    w.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t10/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 10
**
****************************************************************/

#include "cannon.h"
#include <qpainter.h>
#include <qpixmap.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    f = 0;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint( cannonRect(), FALSE );
    emit angleChanged( ang );
}

void CannonField::setForce( int newton )
{
    if ( newton < 0 )
        newton = 0;
    if ( f == newton )
        return;
    f = newton;
    emit forceChanged( f );
}

void CannonField::paintEvent( QPaintEvent *e )
{
    if ( !e->rect().intersects( cannonRect() ) )
        return;

    QRect cr = cannonRect();
    QPixmap pix( cr.size() );
    pix.fill( this, cr.topLeft() );

    QPainter p( &pix );
    p.setBrush( blue );
    p.setPen( NoPen );
    p.translate( 0, pix.height() - 1 );
    p.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
    p.rotate( -ang );
    p.drawRect( QRect(33, -4, 15, 8) );
    p.end();

    p.begin( this );
    p.drawPixmap( cr.topLeft(), pix );
}

QRect CannonField::cannonRect() const
{
    QRect r( 0, 0, 50, 50 );
    r.moveBottomLeft( rect().bottomLeft() );
    return r;
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t10/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 10
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    QSizePolicy sizePolicy() const;

    int   angle() const { return ang; }
    int   force() const { return f; }

public slots:
    void  setAngle( int degrees );
    void  setForce( int newton );

signals:
    void  angleChanged( int );
    void  forceChanged( int );

protected:
    void  paintEvent( QPaintEvent * );

private:
    QRect cannonRect() const;

    int ang;
    int f;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t10/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 8
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );
}

int LCDRange::value() const
{
    return slider->value();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
      qWarning( "LCDRange::setRange(%d,%d)\n"
               "\tRange must be 0..99\n"
               "\tand minVal must not be greater than maxVal",
               minVal, maxVal );
      return;
    }
    slider->setRange( minVal, maxVal );
}


t10/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 8
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );

    int value() const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );

signals:
    void valueChanged( int );

private:
    QSlider  *slider;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t10/main.cpp Example File

/****************************************************************
**
** Qt tutorial 10
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

class MyWidget: public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle = new LCDRange( this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( this, "force" );
    force->setRange( 10, 50 );

    CannonField *cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
             force, SLOT(setValue(int)) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();
}

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    MyWidget w;
    w.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t11/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 11
**
****************************************************************/

#include "cannon.h"
#include <qtimer.h>
#include <qpainter.h>
#include <qpixmap.h>

#include <math.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    f = 0;
    timerCount = 0;
    autoShootTimer = new QTimer( this, "movement handler" );
    connect( autoShootTimer, SIGNAL(timeout()),
             this, SLOT(moveShot()) );
    shoot_ang = 0;
    shoot_f = 0;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint( cannonRect(), FALSE );
    emit angleChanged( ang );
}

void CannonField::setForce( int newton )
{
    if ( newton < 0 )
        newton = 0;
    if ( f == newton )
        return;
    f = newton;
    emit forceChanged( f );
}

void CannonField::shoot()
{
    if ( autoShootTimer->isActive() )
        return;
    timerCount = 0;
    shoot_ang = ang;
    shoot_f = f;
    autoShootTimer->start( 50 );
}

void CannonField::moveShot()
{
    QRegion r( shotRect() );
    timerCount++;

    QRect shotR = shotRect();

    if ( shotR.x() > width() || shotR.y() > height() )
        autoShootTimer->stop();
    else
        r = r.unite( QRegion( shotR ) );
    repaint( r );
}

void CannonField::paintEvent( QPaintEvent *e )
{
    QRect updateR = e->rect();
    QPainter p( this );

    if ( updateR.intersects( cannonRect() ) )
        paintCannon( &p );
    if ( autoShootTimer->isActive() &&
         updateR.intersects( shotRect() ) )
        paintShot( &p );
}

void CannonField::paintShot( QPainter *p )
{
    p->setBrush( black );
    p->setPen( NoPen );
    p->drawRect( shotRect() );
}

const QRect barrelRect(33, -4, 15, 8);

void CannonField::paintCannon( QPainter *p )
{
    QRect cr = cannonRect();
    QPixmap pix( cr.size() );
    pix.fill( this, cr.topLeft() );

    QPainter tmp( &pix );
    tmp.setBrush( blue );
    tmp.setPen( NoPen );

    tmp.translate( 0, pix.height() - 1 );
    tmp.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
    tmp.rotate( -ang );
    tmp.drawRect( barrelRect );
    tmp.end();

    p->drawPixmap( cr.topLeft(), pix );
}

QRect CannonField::cannonRect() const
{
    QRect r( 0, 0, 50, 50 );
    r.moveBottomLeft( rect().bottomLeft() );
    return r;
}

QRect CannonField::shotRect() const
{
    const double gravity = 4;

    double time      = timerCount / 4.0;
    double velocity  = shoot_f;
    double radians   = shoot_ang*3.14159265/180;

    double velx      = velocity*cos( radians );
    double vely      = velocity*sin( radians );
    double x0        = ( barrelRect.right()  + 5 )*cos(radians);
    double y0        = ( barrelRect.right()  + 5 )*sin(radians);
    double x         = x0 + velx*time;
    double y         = y0 + vely*time - 0.5*gravity*time*time;

    QRect r = QRect( 0, 0, 6, 6 );
    r.moveCenter( QPoint( qRound(x), height() - 1 - qRound(y) ) );
    return r;
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t11/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 11
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

class QTimer;

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int   angle() const { return ang; }
    int   force() const { return f; }
    QSizePolicy sizePolicy() const;

public slots:
    void  setAngle( int degrees );
    void  setForce( int newton );
    void  shoot();

private slots:
    void  moveShot();

signals:
    void  angleChanged( int );
    void  forceChanged( int );

protected:
    void  paintEvent( QPaintEvent * );

private:
    void  paintShot( QPainter * );
    void  paintCannon( QPainter * );
    QRect cannonRect() const;
    QRect shotRect() const;

    int ang;
    int f;

    int timerCount;
    QTimer * autoShootTimer;
    float shoot_ang;
    float shoot_f;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t11/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 8
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );
    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );
}

int LCDRange::value() const
{
    return slider->value();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
      qWarning( "LCDRange::setRange(%d,%d)\n"
               "\tRange must be 0..99\n"
               "\tand minVal must not be greater than maxVal",
               minVal, maxVal );
      return;
    }
    slider->setRange( minVal, maxVal );
}


t11/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 8
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );

    int value() const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );

signals:
    void valueChanged( int );

private:
    QSlider  *slider;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t11/main.cpp Example File

/****************************************************************
**
** Qt tutorial 11
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

class MyWidget: public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle = new LCDRange( this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( this, "force" );
    force->setRange( 10, 50 );

    CannonField *cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
             force, SLOT(setValue(int)) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), cannonField, SLOT(shoot()) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addStretch( 1 );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();
}

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    MyWidget w;
    w.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t12/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 12
**
****************************************************************/

#include "cannon.h"
#include <qtimer.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qdatetime.h>

#include <math.h>
#include <stdlib.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    f = 0;
    timerCount = 0;
    autoShootTimer = new QTimer( this, "movement handler" );
    connect( autoShootTimer, SIGNAL(timeout()),
             this, SLOT(moveShot()) );
    shoot_ang = 0;
    shoot_f = 0;
    target = QPoint( 0, 0 );
    setPalette( QPalette( QColor( 250, 250, 200) ) );
    newTarget();
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint( cannonRect(), FALSE );
    emit angleChanged( ang );
}

void CannonField::setForce( int newton )
{
    if ( newton < 0 )
        newton = 0;
    if ( f == newton )
        return;
    f = newton;
    emit forceChanged( f );
}

void CannonField::shoot()
{
    if ( autoShootTimer->isActive() )
        return;
    timerCount = 0;
    shoot_ang = ang;
    shoot_f = f;
    autoShootTimer->start( 50 );
}

void  CannonField::newTarget()
{
    static bool first_time = TRUE;
    if ( first_time ) {
        first_time = FALSE;
        QTime midnight( 0, 0, 0 );
        srand( midnight.secsTo(QTime::currentTime()) );
    }
    QRegion r( targetRect() );
    target = QPoint( 200 + rand() % 190,
                     10  + rand() % 255 );
    repaint( r.unite( targetRect() ) );
}

void CannonField::moveShot()
{
    QRegion r( shotRect() );
    timerCount++;

    QRect shotR = shotRect();

    if ( shotR.intersects( targetRect() ) ) {
        autoShootTimer->stop();
        emit hit();
    } else if ( shotR.x() > width() || shotR.y() > height() ) {
        autoShootTimer->stop();
        emit missed();
    } else {
        r = r.unite( QRegion( shotR ) );
    }

    repaint( r );
}

void CannonField::paintEvent( QPaintEvent *e )
{
    QRect updateR = e->rect();
    QPainter p( this );

    if ( updateR.intersects( cannonRect() ) )
        paintCannon( &p );
    if ( autoShootTimer->isActive() &&
         updateR.intersects( shotRect() ) )
        paintShot( &p );
    if ( updateR.intersects( targetRect() ) )
        paintTarget( &p );
}

void CannonField::paintShot( QPainter *p )
{
    p->setBrush( black );
    p->setPen( NoPen );
    p->drawRect( shotRect() );
}

void CannonField::paintTarget( QPainter *p )
{
    p->setBrush( red );
    p->setPen( black );
    p->drawRect( targetRect() );
}

const QRect barrelRect(33, -4, 15, 8);

void CannonField::paintCannon( QPainter *p )
{
    QRect cr = cannonRect();
    QPixmap pix( cr.size() );
    pix.fill( this, cr.topLeft() );

    QPainter tmp( &pix );
    tmp.setBrush( blue );
    tmp.setPen( NoPen );

    tmp.translate( 0, pix.height() - 1 );
    tmp.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
    tmp.rotate( -ang );
    tmp.drawRect( barrelRect );
    tmp.end();

    p->drawPixmap( cr.topLeft(), pix );
}

QRect CannonField::cannonRect() const
{
    QRect r( 0, 0, 50, 50 );
    r.moveBottomLeft( rect().bottomLeft() );
    return r;
}

QRect CannonField::shotRect() const
{
    const double gravity = 4;

    double time      = timerCount / 4.0;
    double velocity  = shoot_f;
    double radians   = shoot_ang*3.14159265/180;

    double velx      = velocity*cos( radians );
    double vely      = velocity*sin( radians );
    double x0        = ( barrelRect.right()  + 5 )*cos(radians);
    double y0        = ( barrelRect.right()  + 5 )*sin(radians);
    double x         = x0 + velx*time;
    double y         = y0 + vely*time - 0.5*gravity*time*time;

    QRect r = QRect( 0, 0, 6, 6 );
    r.moveCenter( QPoint( qRound(x), height() - 1 - qRound(y) ) );
    return r;
}

QRect CannonField::targetRect() const
{
    QRect r( 0, 0, 20, 10 );
    r.moveCenter( QPoint(target.x(),height() - 1 - target.y()) );
    return r;
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t12/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 12
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

class QTimer;

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int   angle() const { return ang; }
    int   force() const { return f; }
    QSizePolicy sizePolicy() const;

public slots:
    void  setAngle( int degrees );
    void  setForce( int newton );
    void  shoot();
    void  newTarget();

private slots:
    void  moveShot();

signals:
    void  hit();
    void  missed();
    void  angleChanged( int );
    void  forceChanged( int );

protected:
    void  paintEvent( QPaintEvent * );

private:
    void  paintShot( QPainter * );
    void  paintTarget( QPainter * );
    void  paintCannon( QPainter * );
    QRect cannonRect() const;
    QRect shotRect() const;
    QRect targetRect() const;

    int ang;
    int f;

    int timerCount;
    QTimer * autoShootTimer;
    float shoot_ang;
    float shoot_f;

    QPoint target;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t12/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 12
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>
#include <qlabel.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    init();
}

LCDRange::LCDRange( const char *s, QWidget *parent,
                    const char *name )
        : QVBox( parent, name )
{
    init();
    setText( s );
}

void LCDRange::init()
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );

    label = new QLabel( " ", this, "label"  );
    label->setAlignment( AlignCenter );

    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );
}

int LCDRange::value() const
{
    return slider->value();
}

const char *LCDRange::text() const
{
    return label->text();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
        qWarning( "LCDRange::setRange(%d,%d)\n"
                  "\tRange must be 0..99\n"
                  "\tand minVal must not be greater than maxVal",
                  minVal, maxVal );
        return;
    }
    slider->setRange( minVal, maxVal );
}

void LCDRange::setText( const char *s )
{
    label->setText( s );
}


t12/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 12
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qvbox.h>

class QSlider;
class QLabel;

class LCDRange : public QVBox
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );
    LCDRange( const char *s, QWidget *parent=0,
              const char *name=0 );

    int         value() const;
    const char *text()  const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );
    void setText( const char * );

signals:
    void valueChanged( int );

private:
    void init();

    QSlider     *slider;
    QLabel      *label;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t12/main.cpp Example File

/****************************************************************
**
** Qt tutorial 12
**
****************************************************************/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qfont.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

class MyWidget: public QWidget
{
public:
    MyWidget( QWidget *parent=0, const char *name=0 );
};

MyWidget::MyWidget( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    CannonField *cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
             force, SLOT(setValue(int)) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), cannonField, SLOT(shoot()) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addStretch( 1 );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();
}

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    MyWidget w;
    w.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &w );
    w.show();
    return a.exec();
}


t13/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 13
**
****************************************************************/

#include "cannon.h"
#include <qtimer.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qdatetime.h>

#include <math.h>
#include <stdlib.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    f = 0;
    timerCount = 0;
    autoShootTimer = new QTimer( this, "movement handler" );
    connect( autoShootTimer, SIGNAL(timeout()),
             this, SLOT(moveShot()) );
    shoot_ang = 0;
    shoot_f = 0;
    target = QPoint( 0, 0 );
    gameEnded = FALSE;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
    newTarget();
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint( cannonRect(), FALSE );
    emit angleChanged( ang );
}

void CannonField::setForce( int newton )
{
    if ( newton < 0 )
        newton = 0;
    if ( f == newton )
        return;
    f = newton;
    emit forceChanged( f );
}

void CannonField::shoot()
{
    if ( isShooting() )
        return;
    timerCount = 0;
    shoot_ang = ang;
    shoot_f = f;
    autoShootTimer->start( 50 );
    emit canShoot( FALSE );
}

void  CannonField::newTarget()
{
    static bool first_time = TRUE;
    if ( first_time ) {
        first_time = FALSE;
        QTime midnight( 0, 0, 0 );
        srand( midnight.secsTo(QTime::currentTime()) );
    }
    QRegion r( targetRect() );
    target = QPoint( 200 + rand() % 190,
                     10  + rand() % 255 );
    repaint( r.unite( targetRect() ) );
}

void CannonField::setGameOver()
{
    if ( gameEnded )
        return;
    if ( isShooting() )
        autoShootTimer->stop();
    gameEnded = TRUE;
    repaint();
}

void CannonField::restartGame()
{
    if ( isShooting() )
        autoShootTimer->stop();
    gameEnded = FALSE;
    repaint();
    emit canShoot( TRUE );
}

void CannonField::moveShot()
{
    QRegion r( shotRect() );
    timerCount++;

    QRect shotR = shotRect();

    if ( shotR.intersects( targetRect() ) ) {
        autoShootTimer->stop();
        emit hit();
        emit canShoot( TRUE );
    } else if ( shotR.x() > width() || shotR.y() > height() ) {
        autoShootTimer->stop();
        emit missed();
        emit canShoot( TRUE );
    } else {
        r = r.unite( QRegion( shotR ) );
    }

    repaint( r );
}

void CannonField::paintEvent( QPaintEvent *e )
{
    QRect updateR = e->rect();
    QPainter p( this );

    if ( gameEnded ) {
        p.setPen( black );
        p.setFont( QFont( "Courier", 48, QFont::Bold ) );
        p.drawText( rect(), AlignCenter, "Game Over" );
    }
    if ( updateR.intersects( cannonRect() ) )
        paintCannon( &p );
    if ( isShooting() && updateR.intersects( shotRect() ) )
        paintShot( &p );
    if ( !gameEnded && updateR.intersects( targetRect() ) )
        paintTarget( &p );
}

void CannonField::paintShot( QPainter *p )
{
    p->setBrush( black );
    p->setPen( NoPen );
    p->drawRect( shotRect() );
}

void CannonField::paintTarget( QPainter *p )
{
    p->setBrush( red );
    p->setPen( black );
    p->drawRect( targetRect() );
}

const QRect barrelRect(33, -4, 15, 8);

void CannonField::paintCannon( QPainter *p )
{
    QRect cr = cannonRect();
    QPixmap pix( cr.size() );
    pix.fill( this, cr.topLeft() );

    QPainter tmp( &pix );
    tmp.setBrush( blue );
    tmp.setPen( NoPen );

    tmp.translate( 0, pix.height() - 1 );
    tmp.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
    tmp.rotate( -ang );
    tmp.drawRect( barrelRect );
    tmp.end();

    p->drawPixmap( cr.topLeft(), pix );
}

QRect CannonField::cannonRect() const
{
    QRect r( 0, 0, 50, 50 );
    r.moveBottomLeft( rect().bottomLeft() );
    return r;
}

QRect CannonField::shotRect() const
{
    const double gravity = 4;

    double time      = timerCount / 4.0;
    double velocity  = shoot_f;
    double radians   = shoot_ang*3.14159265/180;

    double velx      = velocity*cos( radians );
    double vely      = velocity*sin( radians );
    double x0        = ( barrelRect.right()  + 5 )*cos(radians);
    double y0        = ( barrelRect.right()  + 5 )*sin(radians);
    double x         = x0 + velx*time;
    double y         = y0 + vely*time - 0.5*gravity*time*time;

    QRect r = QRect( 0, 0, 6, 6 );
    r.moveCenter( QPoint( qRound(x), height() - 1 - qRound(y) ) );
    return r;
}

QRect CannonField::targetRect() const
{
    QRect r( 0, 0, 20, 10 );
    r.moveCenter( QPoint(target.x(),height() - 1 - target.y()) );
    return r;
}

bool CannonField::isShooting() const
{
    return autoShootTimer->isActive();
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t13/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 13
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

class QTimer;

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int   angle() const { return ang; }
    int   force() const { return f; }
    bool  gameOver() const { return gameEnded; }
    bool  isShooting() const;
    QSizePolicy sizePolicy() const;

public slots:
    void  setAngle( int degrees );
    void  setForce( int newton );
    void  shoot();
    void  newTarget();
    void  setGameOver();
    void  restartGame();

private slots:
    void  moveShot();

signals:
    void  hit();
    void  missed();
    void  angleChanged( int );
    void  forceChanged( int );
    void  canShoot( bool );

protected:
    void  paintEvent( QPaintEvent * );

private:
    void  paintShot( QPainter * );
    void  paintTarget( QPainter * );
    void  paintCannon( QPainter * );
    QRect cannonRect() const;
    QRect shotRect() const;
    QRect targetRect() const;

    int ang;
    int f;

    int timerCount;
    QTimer * autoShootTimer;
    float shoot_ang;
    float shoot_f;

    QPoint target;

    bool gameEnded;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t13/gamebrd.cpp Example File

/****************************************************************
**
** Implementation of GameBoard class, Qt tutorial 13
**
****************************************************************/

#include "gamebrd.h"

#include <qfont.h>
#include <qapplication.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qlayout.h>

#include "lcdrange.h"
#include "cannon.h"

GameBoard::GameBoard( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    cannonField = new CannonField( this, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
             force, SLOT(setValue(int)) );

    connect( cannonField, SIGNAL(hit()),
             this, SLOT(hit()) );
    connect( cannonField, SIGNAL(missed()),
             this, SLOT(missed()) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), SLOT(fire()) );
    connect( cannonField, SIGNAL(canShoot(bool)),
             shoot, SLOT(setEnabled(bool)) );

    QPushButton *restart
        = new QPushButton( "&New Game", this, "newgame" );
    restart->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( restart, SIGNAL(clicked()), this, SLOT(newGame()) );

    hits = new QLCDNumber( 2, this, "hits" );
    shotsLeft = new QLCDNumber( 2, this, "shotsleft" );
    QLabel *hitsL = new QLabel( "HITS", this, "hitsLabel" );
    QLabel *shotsLeftL
        = new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( cannonField, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addWidget( hits );
    topBox->addWidget( hitsL );
    topBox->addWidget( shotsLeft );
    topBox->addWidget( shotsLeftL );
    topBox->addStretch( 1 );
    topBox->addWidget( restart );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();

    newGame();
}

void GameBoard::fire()
{
    if ( cannonField->gameOver() || cannonField->isShooting() )
        return;
    shotsLeft->display( shotsLeft->intValue() - 1 );
    cannonField->shoot();
}

void GameBoard::hit()
{
    hits->display( hits->intValue() + 1 );
    if ( shotsLeft->intValue() == 0 )
        cannonField->setGameOver();
    else
        cannonField->newTarget();
}

void GameBoard::missed()
{
    if ( shotsLeft->intValue() == 0 )
        cannonField->setGameOver();
}

void GameBoard::newGame()
{
    shotsLeft->display( 15 );
    hits->display( 0 );
    cannonField->restartGame();
    cannonField->newTarget();
}


t13/gamebrd.h Example File

/****************************************************************
**
** Definition of GameBoard class, Qt tutorial 13
**
****************************************************************/

#ifndef GAMEBRD_H
#define GAMEBRD_H

#include <qwidget.h>

class QPushButton;
class LCDRange;
class QLCDNumber;
class CannonField;

#include "lcdrange.h"
#include "cannon.h"

class GameBoard : public QWidget
{
    Q_OBJECT
public:
    GameBoard( QWidget *parent=0, const char *name=0 );

protected slots:
    void  fire();
    void  hit();
    void  missed();
    void  newGame();

private:
    QLCDNumber  *hits;
    QLCDNumber  *shotsLeft;
    CannonField *cannonField;
};

#endif // GAMEBRD_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t13/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 12
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>
#include <qlabel.h>
#include <qlayout.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    init();
}

LCDRange::LCDRange( const char *s, QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    init();
    setText( s );
}

void LCDRange::init()
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );

    label = new QLabel( " ", this, "label"  );
    label->setAlignment( AlignCenter );

    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );

    QVBoxLayout * l = new QVBoxLayout( this );
    l->addWidget( lcd, 1 );
    l->addWidget( slider );
    l->addWidget( label );
}

int LCDRange::value() const
{
    return slider->value();
}

const char *LCDRange::text() const
{
    return label->text();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
        qWarning( "LCDRange::setRange(%d,%d)\n"
                  "\tRange must be 0..99\n"
                  "\tand minVal must not be greater than maxVal",
                  minVal, maxVal );
        return;
    }
    slider->setRange( minVal, maxVal );
}

void LCDRange::setText( const char *s )
{
    label->setText( s );
}


t13/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 12
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qwidget.h>

class QSlider;
class QLabel;

class LCDRange : public QWidget
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );
    LCDRange( const char *s, QWidget *parent=0, const char *name=0 );

    int         value() const;
    const char *text()  const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );
    void setText( const char * );

signals:
    void valueChanged( int );

private:
    void init();

    QSlider     *slider;
    QLabel      *label;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t13/main.cpp Example File

/****************************************************************
**
** Qt tutorial 13
**
****************************************************************/

#include <qapplication.h>

#include "gamebrd.h"

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    GameBoard gb;
    gb.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &gb );
    gb.show();
    return a.exec();
}


t14/cannon.cpp Example File

/****************************************************************
**
** Implementation CannonField class, Qt tutorial 14
**
****************************************************************/

#include "cannon.h"
#include <qtimer.h>
#include <qpainter.h>
#include <qpixmap.h>
#include <qdatetime.h>

#include <math.h>
#include <stdlib.h>

CannonField::CannonField( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    ang = 45;
    f = 0;
    timerCount = 0;
    autoShootTimer = new QTimer( this, "movement handler" );
    connect( autoShootTimer, SIGNAL(timeout()),
             this, SLOT(moveShot()) );
    shoot_ang = 0;
    shoot_f = 0;
    target = QPoint( 0, 0 );
    gameEnded = FALSE;
    barrelPressed = FALSE;
    setPalette( QPalette( QColor( 250, 250, 200) ) );
    newTarget();
}

void CannonField::setAngle( int degrees )
{
    if ( degrees < 5 )
        degrees = 5;
    if ( degrees > 70 )
        degrees = 70;
    if ( ang == degrees )
        return;
    ang = degrees;
    repaint( cannonRect(), FALSE );
    emit angleChanged( ang );
}

void CannonField::setForce( int newton )
{
    if ( newton < 0 )
        newton = 0;
    if ( f == newton )
        return;
    f = newton;
    emit forceChanged( f );
}

void CannonField::shoot()
{
    if ( isShooting() )
        return;
    timerCount = 0;
    shoot_ang = ang;
    shoot_f = f;
    autoShootTimer->start( 50 );
    emit canShoot( FALSE );
}

void  CannonField::newTarget()
{
    static bool first_time = TRUE;
    if ( first_time ) {
        first_time = FALSE;
        QTime midnight( 0, 0, 0 );
        srand( midnight.secsTo(QTime::currentTime()) );
    }
    QRegion r( targetRect() );
    target = QPoint( 200 + rand() % 190,
                     10  + rand() % 255 );
    repaint( r.unite( targetRect() ) );
}

void CannonField::setGameOver()
{
    if ( gameEnded )
        return;
    if ( isShooting() )
        autoShootTimer->stop();
    gameEnded = TRUE;
    repaint();
}

void CannonField::restartGame()
{
    if ( isShooting() )
        autoShootTimer->stop();
    gameEnded = FALSE;
    repaint();
    emit canShoot( TRUE );
}

void CannonField::moveShot()
{
    QRegion r( shotRect() );
    timerCount++;

    QRect shotR = shotRect();

    if ( shotR.intersects( targetRect() ) ) {
        autoShootTimer->stop();
        emit hit();
        emit canShoot( TRUE );
    } else if ( shotR.x() > width() || shotR.y() > height() ||
                shotR.intersects(barrierRect()) ) {
        autoShootTimer->stop();
        emit missed();
        emit canShoot( TRUE );
    } else {
        r = r.unite( QRegion( shotR ) );
    }

    repaint( r );
}

void CannonField::mousePressEvent( QMouseEvent *e )
{
    if ( e->button() != LeftButton )
        return;
    if ( barrelHit( e->pos() ) )
        barrelPressed = TRUE;
}

void CannonField::mouseMoveEvent( QMouseEvent *e )
{
    if ( !barrelPressed )
        return;
    QPoint pnt = e->pos();
    if ( pnt.x() <= 0 )
        pnt.setX( 1 );
    if ( pnt.y() >= height() )
        pnt.setY( height() - 1 );
    double rad = atan(((double)rect().bottom()-pnt.y())/pnt.x());
    setAngle( qRound ( rad*180/3.14159265 ) );
}

void CannonField::mouseReleaseEvent( QMouseEvent *e )
{
    if ( e->button() == LeftButton )
        barrelPressed = FALSE;
}

void CannonField::paintEvent( QPaintEvent *e )
{
    QRect updateR = e->rect();
    QPainter p( this );

    if ( gameEnded ) {
        p.setPen( black );
        p.setFont( QFont( "Courier", 48, QFont::Bold ) );
        p.drawText( rect(), AlignCenter, "Game Over" );
    }
    if ( updateR.intersects( cannonRect() ) )
        paintCannon( &p );
    if ( updateR.intersects( barrierRect() ) )
        paintBarrier( &p );
    if ( isShooting() && updateR.intersects( shotRect() ) )
        paintShot( &p );
    if ( !gameEnded && updateR.intersects( targetRect() ) )
        paintTarget( &p );
}

void CannonField::paintShot( QPainter *p )
{
    p->setBrush( black );
    p->setPen( NoPen );
    p->drawRect( shotRect() );
}

void CannonField::paintTarget( QPainter *p )
{
    p->setBrush( red );
    p->setPen( black );
    p->drawRect( targetRect() );
}

void CannonField::paintBarrier( QPainter *p )
{
    p->setBrush( yellow );
    p->setPen( black );
    p->drawRect( barrierRect() );
}

const QRect barrelRect(33, -4, 15, 8);

void CannonField::paintCannon( QPainter *p )
{
    QRect cr = cannonRect();
    QPixmap pix( cr.size() );
    pix.fill( this, cr.topLeft() );

    QPainter tmp( &pix );
    tmp.setBrush( blue );
    tmp.setPen( NoPen );

    tmp.translate( 0, pix.height() - 1 );
    tmp.drawPie( QRect( -35,-35, 70, 70 ), 0, 90*16 );
    tmp.rotate( -ang );
    tmp.drawRect( barrelRect );
    tmp.end();

    p->drawPixmap( cr.topLeft(), pix );
}

QRect CannonField::cannonRect() const
{
    QRect r( 0, 0, 50, 50 );
    r.moveBottomLeft( rect().bottomLeft() );
    return r;
}

QRect CannonField::shotRect() const
{
    const double gravity = 4;

    double time      = timerCount / 4.0;
    double velocity  = shoot_f;
    double radians   = shoot_ang*3.14159265/180;

    double velx      = velocity*cos( radians );
    double vely      = velocity*sin( radians );
    double x0        = ( barrelRect.right()  + 5 )*cos(radians);
    double y0        = ( barrelRect.right()  + 5 )*sin(radians);
    double x         = x0 + velx*time;
    double y         = y0 + vely*time - 0.5*gravity*time*time;

    QRect r = QRect( 0, 0, 6, 6 );
    r.moveCenter( QPoint( qRound(x), height() - 1 - qRound(y) ) );
    return r;
}

QRect CannonField::targetRect() const
{
    QRect r( 0, 0, 20, 10 );
    r.moveCenter( QPoint(target.x(),height() - 1 - target.y()) );
    return r;
}

QRect CannonField::barrierRect() const
{
    return QRect( 145, height() - 100, 15, 100 );
}

bool CannonField::barrelHit( const QPoint &p ) const
{
    QWMatrix mtx;
    mtx.translate( 0, height() - 1 );
    mtx.rotate( -ang );
    mtx = mtx.invert();
    return barrelRect.contains( mtx.map(p) );
}

bool CannonField::isShooting() const
{
    return autoShootTimer->isActive();
}

QSize CannonField::sizeHint() const
{
    return QSize( 400, 300 );
}

QSizePolicy CannonField::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}


t14/cannon.h Example File

/****************************************************************
**
** Definition of CannonField class, Qt tutorial 14
**
****************************************************************/

#ifndef CANNON_H
#define CANNON_H

class QTimer;

#include <qwidget.h>

class CannonField : public QWidget
{
    Q_OBJECT
public:
    CannonField( QWidget *parent=0, const char *name=0 );

    int   angle() const { return ang; }
    int   force() const { return f; }
    bool  gameOver() const { return gameEnded; }
    bool  isShooting() const;
    QSize sizeHint() const;
    QSizePolicy sizePolicy() const;

public slots:
    void  setAngle( int degrees );
    void  setForce( int newton );
    void  shoot();
    void  newTarget();
    void  setGameOver();
    void  restartGame();

private slots:
    void  moveShot();

signals:
    void  hit();
    void  missed();
    void  angleChanged( int );
    void  forceChanged( int );
    void  canShoot( bool );

protected:
    void  paintEvent( QPaintEvent * );
    void  mousePressEvent( QMouseEvent * );
    void  mouseMoveEvent( QMouseEvent * );
    void  mouseReleaseEvent( QMouseEvent * );

private:
    void  paintShot( QPainter * );
    void  paintTarget( QPainter * );
    void  paintBarrier( QPainter * );
    void  paintCannon( QPainter * );
    QRect cannonRect() const;
    QRect shotRect() const;
    QRect targetRect() const;
    QRect barrierRect() const;
    bool  barrelHit( const QPoint & ) const;

    int ang;
    int f;

    int timerCount;
    QTimer * autoShootTimer;
    float shoot_ang;
    float shoot_f;

    QPoint target;

    bool gameEnded;
    bool barrelPressed;
};

#endif // CANNON_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t14/gamebrd.cpp Example File

/****************************************************************
**
** Implementation of GameBoard class, Qt tutorial 14
**
****************************************************************/

#include "gamebrd.h"

#include <qfont.h>
#include <qapplication.h>
#include <qlabel.h>
#include <qaccel.h>
#include <qpushbutton.h>
#include <qlcdnumber.h>
#include <qlayout.h>
#include <qvbox.h>

#include "lcdrange.h"
#include "cannon.h"

GameBoard::GameBoard( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    QPushButton *quit = new QPushButton( "&Quit", this, "quit" );
    quit->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );

    LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );
    angle->setRange( 5, 70 );

    LCDRange *force  = new LCDRange( "FORCE", this, "force" );
    force->setRange( 10, 50 );

    QVBox *box = new QVBox( this, "cannonFrame" );
    box->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );

    cannonField = new CannonField( box, "cannonField" );

    connect( angle, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setAngle(int)) );
    connect( cannonField, SIGNAL(angleChanged(int)),
             angle, SLOT(setValue(int)) );

    connect( force, SIGNAL(valueChanged(int)),
             cannonField, SLOT(setForce(int)) );
    connect( cannonField, SIGNAL(forceChanged(int)),
             force, SLOT(setValue(int)) );

    connect( cannonField, SIGNAL(hit()),
             this, SLOT(hit()) );
    connect( cannonField, SIGNAL(missed()),
             this, SLOT(missed()) );

    QPushButton *shoot = new QPushButton( "&Shoot", this, "shoot" );
    shoot->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( shoot, SIGNAL(clicked()), SLOT(fire()) );

    connect( cannonField, SIGNAL(canShoot(bool)),
             shoot, SLOT(setEnabled(bool)) );

    QPushButton *restart
        = new QPushButton( "&New Game", this, "newgame" );
    restart->setFont( QFont( "Times", 18, QFont::Bold ) );

    connect( restart, SIGNAL(clicked()), this, SLOT(newGame()) );

    hits = new QLCDNumber( 2, this, "hits" );
    shotsLeft = new QLCDNumber( 2, this, "shotsleft" );
    QLabel *hitsL = new QLabel( "HITS", this, "hitsLabel" );
    QLabel *shotsLeftL
        = new QLabel( "SHOTS LEFT", this, "shotsleftLabel" );

    QAccel *accel = new QAccel( this );
    accel->connectItem( accel->insertItem( Key_Enter ),
                        this, SLOT(fire()) );
    accel->connectItem( accel->insertItem( Key_Return ),
                        this, SLOT(fire()) );
    accel->connectItem( accel->insertItem( CTRL+Key_Q ),
                        qApp, SLOT(quit()) );

    QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
    grid->addWidget( quit, 0, 0 );
    grid->addWidget( box, 1, 1 );
    grid->setColStretch( 1, 10 );

    QVBoxLayout *leftBox = new QVBoxLayout;
    grid->addLayout( leftBox, 1, 0 );
    leftBox->addWidget( angle );
    leftBox->addWidget( force );

    QHBoxLayout *topBox = new QHBoxLayout;
    grid->addLayout( topBox, 0, 1 );
    topBox->addWidget( shoot );
    topBox->addWidget( hits );
    topBox->addWidget( hitsL );
    topBox->addWidget( shotsLeft );
    topBox->addWidget( shotsLeftL );
    topBox->addStretch( 1 );
    topBox->addWidget( restart );

    angle->setValue( 60 );
    force->setValue( 25 );
    angle->setFocus();

    newGame();
}

void GameBoard::fire()
{
    if ( cannonField->gameOver() || cannonField->isShooting() )
        return;
    shotsLeft->display( shotsLeft->intValue() - 1 );
    cannonField->shoot();
}

void GameBoard::hit()
{
    hits->display( hits->intValue() + 1 );
    if ( shotsLeft->intValue() == 0 )
        cannonField->setGameOver();
    else
        cannonField->newTarget();
}

void GameBoard::missed()
{
    if ( shotsLeft->intValue() == 0 )
        cannonField->setGameOver();
}

void GameBoard::newGame()
{
    shotsLeft->display( 15 );
    hits->display( 0 );
    cannonField->restartGame();
    cannonField->newTarget();
}


t14/gamebrd.h Example File

/****************************************************************
**
** Definition of GameBoard class, Qt tutorial 14
**
****************************************************************/

#ifndef GAMEBRD_H
#define GAMEBRD_H

#include <qwidget.h>

class QPushButton;
class LCDRange;
class QLCDNumber;
class CannonField;

#include "lcdrange.h"
#include "cannon.h"

class GameBoard : public QWidget
{
    Q_OBJECT
public:
    GameBoard( QWidget *parent=0, const char *name=0 );

protected slots:
    void  fire();
    void  hit();
    void  missed();
    void  newGame();

private:
    QLCDNumber  *hits;
    QLCDNumber  *shotsLeft;
    CannonField *cannonField;
};

#endif // GAMEBRD_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t14/lcdrange.cpp Example File

/****************************************************************
**
** Implementation of LCDRange class, Qt tutorial 12
**
****************************************************************/

#include "lcdrange.h"

#include <qslider.h>
#include <qlcdnumber.h>
#include <qlabel.h>
#include <qlayout.h>

LCDRange::LCDRange( QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    init();
}

LCDRange::LCDRange( const char *s, QWidget *parent, const char *name )
        : QWidget( parent, name )
{
    init();
    setText( s );
}

void LCDRange::init()
{
    QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
    slider = new QSlider( Horizontal, this, "slider" );
    slider->setRange( 0, 99 );
    slider->setValue( 0 );

    label = new QLabel( " ", this, "label"  );
    label->setAlignment( AlignCenter );

    connect( slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)) );
    connect( slider, SIGNAL(valueChanged(int)),
             SIGNAL(valueChanged(int)) );

    setFocusProxy( slider );

    QVBoxLayout * l = new QVBoxLayout( this );
    l->addWidget( lcd, 1 );
    l->addWidget( slider );
    l->addWidget( label );
}

int LCDRange::value() const
{
    return slider->value();
}

const char *LCDRange::text() const
{
    return label->text();
}

void LCDRange::setValue( int value )
{
    slider->setValue( value );
}

void LCDRange::setRange( int minVal, int maxVal )
{
    if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
        qWarning( "LCDRange::setRange(%d,%d)\n"
                  "\tRange must be 0..99\n"
                  "\tand minVal must not be greater than maxVal",
                  minVal, maxVal );
        return;
    }
    slider->setRange( minVal, maxVal );
}

void LCDRange::setText( const char *s )
{
    label->setText( s );
}


t14/lcdrange.h Example File

/****************************************************************
**
** Definition of LCDRange class, Qt tutorial 12
**
****************************************************************/

#ifndef LCDRANGE_H
#define LCDRANGE_H

#include <qwidget.h>

class QSlider;
class QLabel;

class LCDRange : public QWidget
{
    Q_OBJECT
public:
    LCDRange( QWidget *parent=0, const char *name=0 );
    LCDRange( const char *s, QWidget *parent=0, const char *name=0 );

    int         value() const;
    const char *text()  const;

public slots:
    void setValue( int );
    void setRange( int minVal, int maxVal );
    void setText( const char * );

signals:
    void valueChanged( int );

private:
    void init();

    QSlider     *slider;
    QLabel      *label;
};

#endif // LCDRANGE_H

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


t14/main.cpp Example File

/****************************************************************
**
** Qt tutorial 14
**
****************************************************************/

#include <qapplication.h>

#include "gamebrd.h"

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QApplication a( argc, argv );

    GameBoard gb;
    gb.setGeometry( 100, 100, 500, 355 );
    a.setMainWidget( &gb );
    gb.show();
    return a.exec();
}


Tabdialog

This example shows how to use a dialog with multiple tabs (pages). To start the program you have to specify a filename as the first argument. The dialog shows information about the file separated onto different tabs.

Header file:

/****************************************************************************
** $Id:  qt/tabdialog.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef TABDIALOG_H
#define TABDIALOG_H

#include <qtabdialog.h>
#include <qstring.h>
#include <qfileinfo.h>

class TabDialog : public QTabDialog
{
    Q_OBJECT

public:
    TabDialog( QWidget *parent, const char *name, const QString &_filename );

protected:
    QString filename;
    QFileInfo fileinfo;

    void setupTab1();
    void setupTab2();
    void setupTab3();

};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/tabdialog.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "tabdialog.h"

#include <qvbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qdatetime.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlistbox.h>
#include <qapplication.h>

TabDialog::TabDialog( QWidget *parent, const char *name, const QString &_filename )
    : QTabDialog( parent, name ), filename( _filename ), fileinfo( filename )
{
    setupTab1();
    setupTab2();
    setupTab3();

    connect( this, SIGNAL( applyButtonPressed() ), qApp, SLOT( quit() ) );
}

void TabDialog::setupTab1()
{
    QVBox *tab1 = new QVBox( this );
    tab1->setMargin( 5 );

    (void)new QLabel( "Filename:", tab1 );
    QLineEdit *fname = new QLineEdit( filename, tab1 );
    fname->setFocus();

    (void)new QLabel( "Path:", tab1 );
    QLabel *path = new QLabel( fileinfo.dirPath( TRUE ), tab1 );
    path->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    (void)new QLabel( "Size:", tab1 );
    QLabel *size = new QLabel( QString( "%1 KB" ).arg( fileinfo.size() ), tab1 );
    size->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    (void)new QLabel( "Last Read:", tab1 );
    QLabel *lread = new QLabel( fileinfo.lastRead().toString(), tab1 );
    lread->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    (void)new QLabel( "Last Modified:", tab1 );
    QLabel *lmodif = new QLabel( fileinfo.lastModified().toString(), tab1 );
    lmodif->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    addTab( tab1, "General" );
}

void TabDialog::setupTab2()
{
    QVBox *tab2 = new QVBox( this );
    tab2->setMargin( 5 );

    QButtonGroup *bg = new QButtonGroup( 1, QGroupBox::Horizontal, "Permissions", tab2 );

    QCheckBox *readable = new QCheckBox( "Readable", bg );
    if ( fileinfo.isReadable() )
        readable->setChecked( TRUE );

    QCheckBox *writable = new QCheckBox( "Writeable", bg );
    if ( fileinfo.isWritable() )
        writable->setChecked( TRUE );

    QCheckBox *executable = new QCheckBox( "Executable", bg );
    if ( fileinfo.isExecutable() )
        executable->setChecked( TRUE );

    QButtonGroup *bg2 = new QButtonGroup( 2, QGroupBox::Horizontal, "Owner", tab2 );

    (void)new QLabel( "Owner", bg2 );
    QLabel *owner = new QLabel( fileinfo.owner(), bg2 );
    owner->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    (void)new QLabel( "Group", bg2 );
    QLabel *group = new QLabel( fileinfo.group(), bg2 );
    group->setFrameStyle( QFrame::Panel | QFrame::Sunken );

    addTab( tab2, "Permissions" );
}

void TabDialog::setupTab3()
{
    QVBox *tab3 = new QVBox( this );
    tab3->setMargin( 5 );
    tab3->setSpacing( 5 );

    (void)new QLabel( QString( "Open %1 with:" ).arg( filename ), tab3 );

    QListBox *prgs = new QListBox( tab3 );
    for ( unsigned int i = 0; i < 30; i++ ) {
        QString prg = QString( "Application %1" ).arg( i );
        prgs->insertItem( prg );
    }
    prgs->setCurrentItem( 3 );

    (void)new QCheckBox( QString( "Open files with the extension '%1' always with this application" ).arg( fileinfo.extension() ), tab3 );

    addTab( tab3, "Applications" );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "tabdialog.h"
#include <qapplication.h>
#include <qstring.h>

int main( int argc, char **argv )
{

    QApplication a( argc, argv );

    TabDialog tabdialog( 0, "tabdialog", QString( argc < 2 ? "." : argv[1] ) );
    tabdialog.resize( 450, 350 );
    tabdialog.setCaption( "Qt Example - Tabbed Dialog" );
    a.setMainWidget( &tabdialog );
    tabdialog.show();

    return a.exec();
}

See also Examples.


table/bigtable/main.cpp Example File

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qtable.h>

// Table size

const int numRows = 1000000;
const int numCols = 1000000;

class MyTable : public QTable
{
public:
    MyTable( int r, int c ) : QTable( r, c ) {
        items.setAutoDelete( TRUE );
        widgets.setAutoDelete( TRUE );
        setCaption( tr( "This is a big table with 1.000.000x1.000.000 cells..." ) );
        setLeftMargin( fontMetrics().width( "W999999W" ) );
    }

    void resizeData( int ) {}
    QTableItem *item( int r, int c ) const { return items.find( indexOf( r, c ) ); }
    void setItem( int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); }
    void clearCell( int r, int c ) { items.remove( indexOf( r, c ) ); }
    void insertWidget( int r, int c, QWidget *w ) { widgets.replace( indexOf( r, c ), w );  }
    QWidget *cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); }
    void clearCellWidget( int r, int c ) { widgets.remove( indexOf( r, c ) ); }

private:
    QIntDict<QTableItem> items;
    QIntDict<QWidget> widgets;

};

// The program starts here.

int main( int argc, char **argv )
{
    QApplication app( argc, argv );

    MyTable table( numRows, numCols );
    app.setMainWidget( &table );
    table.show();
    return app.exec();
}


表格例程

下列样例程序演示了Qt表格模块的使用。

如何生成大的稀疏表格
小表格样例
表格样例

Copyright © 2002 Trolltech Trademarks 译者:farfareast
Qt 3.0.5版


Tablet Example

This example shows how to interact with a tablet device.

See $QTDIR/examples/tablet for the source code.

See also Examples.


A tiny SAX2 parser

This example presents a small SAX2 reader that outputs the names of all elements in an XML document on the command line. The element names are indented corresponding to their nesting

This example is thoroughly explained in a walkthrough.

Header file:

/****************************************************************************
** $Id:  qt/structureparser.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef STRUCTUREPARSER_H
#define STRUCTUREPARSER_H

#include <qxml.h>

class QString;

class StructureParser : public QXmlDefaultHandler
{
public:
    bool startDocument();
    bool startElement( const QString&, const QString&, const QString& ,
                       const QXmlAttributes& );
    bool endElement( const QString&, const QString&, const QString& );

private:
    QString indent;
};

#endif

Implementation:

/****************************************************************************
** $Id:  qt/structureparser.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "structureparser.h"

#include <stdio.h>
#include <qstring.h>

bool StructureParser::startDocument()
{
    indent = "";
    return TRUE;
}

bool StructureParser::startElement( const QString&, const QString&,
                                    const QString& qName,
                                    const QXmlAttributes& )
{
    printf( "%s%s\n", (const char*)indent, (const char*)qName );
    indent += "    ";
    return TRUE;
}

bool StructureParser::endElement( const QString&, const QString&, const QString& )
{
    indent.remove( 0, 4 );
    return TRUE;
}

Main:

/****************************************************************************
** $Id:  qt/tagreader.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "structureparser.h"
#include <qfile.h>
#include <qxml.h>
#include <qwindowdefs.h>

int main( int argc, char **argv )
{
    if ( argc < 2 ) {
        fprintf( stderr, "Usage: %s <xmlfile>\n", argv[0] );
        return 1;
    }
    for ( int i=1; i < argc; i++ ) {
        StructureParser handler;
        QFile xmlFile( argv[i] );
        QXmlInputSource source( &xmlFile );
        QXmlSimpleReader reader;
        reader.setContentHandler( &handler );
        reader.parse( source );
    }
    return 0;
}

See also Qt XML Examples.


Demonstration of SAX2 features

This example presents a small SAX2 reader that outputs the qualified names and the respective namespace URIs of all elements and attributes in an XML file. Additionally the tree structure of the document is displayed.

In three listviews the program shows the different output of the reader depending on how the SAX2 features http://xml.org/sax/features/namespaces and http://xml.org/sax/features/namespace-prefixes are set.

This example is thoroughly explained in a walkthrough.

Header file:

/*
$Id$
*/

#ifndef STRUCTUREPARSER_H
#define STRUCTUREPARSER_H

#include <qxml.h>
#include <qptrstack.h>

class QListView;
class QListViewItem;
class QString;

class StructureParser: public QXmlDefaultHandler
{
public:
    StructureParser( QListView * );
    bool startElement( const QString&, const QString&, const QString& ,
                       const QXmlAttributes& );
    bool endElement( const QString&, const QString&, const QString& );

    void setListView( QListView * );

private:
    QPtrStack<QListViewItem> stack;
    QListView * table;
};

#endif

Implementation:

/*
$Id$
*/

#include "structureparser.h"

#include <qstring.h>
#include <qlistview.h>

StructureParser::StructureParser( QListView * t )
                : QXmlDefaultHandler()
{
    setListView( t );
}

void StructureParser::setListView( QListView * t )
{
    table = t;
    table->setSorting( -1 );
    table->addColumn( "Qualified name" );
    table->addColumn( "Namespace" );
}

bool StructureParser::startElement( const QString& namespaceURI,
                                    const QString& ,
                                    const QString& qName,
                                    const QXmlAttributes& attributes)
{
    QListViewItem * element;

    if ( ! stack.isEmpty() ){
        QListViewItem *lastChild = stack.top()->firstChild();
        if ( lastChild ) {
            while ( lastChild->nextSibling() )
                lastChild = lastChild->nextSibling();
        }
        element = new QListViewItem( stack.top(), lastChild, qName, namespaceURI );
    } else {
        element = new QListViewItem( table, qName, namespaceURI );
    }
    stack.push( element );
    element->setOpen( TRUE );

    if ( attributes.length() > 0 ) {
        for ( int i = 0 ; i < attributes.length(); i++ ) {
            new QListViewItem( element, attributes.qName(i), attributes.uri(i) );
        }
    }
    return TRUE;
}

bool StructureParser::endElement( const QString&, const QString&,
                                  const QString& )
{
    stack.pop();
    return TRUE;
}

Main:

/****************************************************************************
** $Id:  qt/tagreader.cpp   3.0.5   edited May 24 18:49 $
**
** Copyright (C) 2001 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "structureparser.h"
#include <qapplication.h>
#include <qfile.h>
#include <qxml.h>
#include <qlistview.h>
#include <qgrid.h>
#include <qmainwindow.h>
#include <qlabel.h>

int main( int argc, char **argv )
{
    QApplication app( argc, argv );

    QFile xmlFile( argc == 2 ? argv[1] : "fnord.xml" );
    QXmlInputSource source( &xmlFile );

    QXmlSimpleReader reader;

    QGrid * container = new QGrid( 3 );

    QListView * nameSpace = new QListView( container, "table_namespace" );
    StructureParser * handler = new StructureParser( nameSpace );
    reader.setContentHandler( handler );
    reader.parse( source );

    QListView * namespacePrefix = new QListView( container,
                                                 "table_namespace_prefix" );
    handler->setListView( namespacePrefix );
    reader.setFeature( "http://xml.org/sax/features/namespace-prefixes",
                       TRUE );
    source.reset();
    reader.parse( source );

    QListView * prefix = new QListView( container, "table_prefix");
    handler->setListView( prefix );
    reader.setFeature( "http://xml.org/sax/features/namespaces", FALSE );
    source.reset();
    reader.parse( source );

    // namespace label
    (void) new QLabel(
             "Default:\n"
             "http://xml.org/sax/features/namespaces: TRUE\n"
             "http://xml.org/sax/features/namespace-prefixes: FALSE\n",
             container );

    // namespace prefix label
    (void) new QLabel(
             "\n"
             "http://xml.org/sax/features/namespaces: TRUE\n"
             "http://xml.org/sax/features/namespace-prefixes: TRUE\n",
             container );

    // prefix label
    (void) new QLabel(
             "\n"
             "http://xml.org/sax/features/namespaces: FALSE\n"
             "http://xml.org/sax/features/namespace-prefixes: TRUE\n",
             container );

    app.setMainWidget( container );
    container->show();
    return app.exec();
}

See also Qt XML Examples.


为什么Qt不用模板来实现信号和槽？

一个简单的答案是，当初Qt被设计的时候，因为各种各样的编译器的不充分，所以在多平台应用程序中完全使用模板机制是不可能的。甚至今天，许多被广泛使用的C++编译器在使用高级模板的时候还是有问题的。例如，你不能安全地依靠部分模板的示例，这对一些不平常的问题领域是必要的。因此Qt中模板的用法不得不保守。记住Qt是一个多平台的工具包，在Linux/g++平台上的进步不一定能够在其它情况下获得改进。

那些在模板执行上比较弱的编译器终将得到改进。但是，即使我们所有的用户以极好的模板支持接近一个完全现代的C++编译器的标准，我们也不会放弃通过使用我们的元对象编译器的基于字符串的途径。这里是为什么这样做的五个原因：

1. 语法问题

语法不是糖：我们用来表达我们的运算法则的语法较大程度上影响我们的代码的可读性和可维护性。Qt中信号和槽所用的语法在实践中被证明是非常成功的。这种语法是直观的、容易使用的和容易读的。人们在学习Qt时发现这种语法帮助他们理解和使用信号和槽的概念——而不管它们的高度抽象和通用的性质。此外，在类定义中信号声明保证了信号就像被保护的C++成员函数一样被保护。这帮助了程序员在刚开始的时候就获得了他们的设计权力，而不用不得不考虑设计模式。

2. 预编译程序是好的

Qt的moc（元对象编译器）提供了一种的方式除了那些编译语言的工具。它可以生成任何一个标准的C++编译器都能编译的额外的C++代码。元对象编译器读取C++源文件。如果它发现其中有一个或多个类的声明中含有“Q_OBJECT”这个宏，它就会为这些类生成另外一个包含元对象代码的C++源文件。这个由元对象编译器生成的C++源文件必须和它的类实现一起编译和连接（或者它也可以被#included到个类的源文件中）。有特色的是元对象编译器不是用手工来调用的，它可以自动地被连编系统调用，所以它不需要程序员额外的付出努力。

这里有一些其它的预编译程序，比如，rpc和idl，它们使程序或者对象能够通过进程或者machine boundaries来进行通讯。预编译程序的选择是编写编译器，专有的语言或者使用对话框或向导这些图形编程工具来生成晦涩的代码。我们能使我们的客户使用他们所喜欢的工具，而不是把他们锁定在一个专有的C++编译器或者一个特殊的集成开发环境。我们不强迫程序员把生成的代码添加到源程序仓库中，而是鼓励他们把我们的工具加入到他们的连编系统中：更加干净，更加安全和更加富有UNIX精神。

3. 灵活性为王

C++是一种标准化的、强大的和精心制作的多用途语言。它只是用来开发很多领域的软件项目的一种语言，生成许多种应用程序，从整个操作系统、数据库服务器和高性能的图形应用程序到普通的桌面应用程序。C++成功的关键之一是它着重于最大效能和最小内存占用同时保持ANSI-C的的兼容性的可伸缩语言设计

在这些优势当中，也有一些不利方面。对于C++，当它用来构成基于组件的图形用户界面编程的时候，静态的对象模型在使用Objective C途径的动态消息机制方面是明显的劣势。对于一个高端数据库服务器或者一个操作系统使用正确的图形用户界面前端工具的这一设计选择不是必须的。使用元对象编译器，我们可以把这一劣势转化为优势并且会加入当我们遇到安全的和有效的图形用户界面程序编程这一挑战的时候所需要的灵活性。

我们的方法比你用模板所能做到的一切更好。比如，我们有对象属性。并且我们可以重载信号和槽，当你在使用可以重载这一关键理念的语言进行程序设计的时候你会感到很自然。我们的信号只对一个类实例的大小增加了零个字节，也就是说我们能在不破坏二进制程序的兼容性的同时加入新的信号。因为我们不像模板那样过多地依靠内嵌，我们可以使得代码变得更小。添加一个新的连接就是增加一个简单地函数调用而不是一个复杂地模板函数。

另外一个好处就是我们可以在运行时探测对象的信号和槽。我们可以通过使用类型安全的名称调用而不用我们知道我们要连接的对象的确切类型来建立连接。这在一个基于模板的解决方案中是不可能的。这种运行时的自我检测扩充了一种新的功能，比如我们可以使用Qt设计器的XML格式的ui文件来生成和连接图形用户界面。

4. 调用性能不是一切

Qt的信号和槽的执行没有基于模板的解决方案那样快。发射一个信号的时间大约和普通模板实现中的四个普通函数调用的时间差不多，Qt要求努力控制到和十个普通函数调用差不多。这也不必惊讶，因为Qt机制中包括了一个通用调度器，自我测量和基本的脚本化的能力。它不过分依赖内嵌和代码扩展，并且它提供了运行时得无比安全性。Qt的迭代（iterator）是安全的而那些基于模板的更快的系统确不是。甚至在你发射一个信号到多个接收器的过程中，那些接收器可以被安全地删除而不会导致你的程序崩溃。没有了这种安全，你的程序在调试自由的内存读或写错误这种困难情况下最终会崩溃。

虽然如此，一个基于模板的解决方案不是能比使用信号和槽更加提高应用程序的性能吗？虽然Qt通过一个信号调用槽的时候会增加一点时间开销是真的，这个调用的开销只占整个槽调用的开销的很小比例。以上的情况都是基于Qt的信号和槽系统使用典型的空槽。一旦你在槽里面做任何有意义的事情时，比如一些简单的字符串操作，调用的时间开销就可以忽略不计了。Qt的系统非常的优化了，以至于任何东西都要求操作符new或者delete（比如，字符串操作或者从一个模板容器插入/删除一些东西）的时间开销要比发射一个信号多的多。

另外：如果你在一个性能为关键的任务中的一个严紧的内部回路中使用信号和槽并且你认为这种连接是瓶颈的话，建议你使用标准的监听接口模式来替代信号和槽。当这种情况发生时，总之你也许只需要一个一对一的连接。比如，你有一个对象从网络上下载数据，你使用信号来说明所需要的数据已经到达的这种设计是非常明智的。但是如果你需要向接收者一个字节一个字节地发送数据，使用监听接口要比信号和槽好。

5. 没有限制

因为我们有元对象编译器来处理信号和槽，我们可以向它添加一些其它模板不能做的但很有用的东西。在这之中，有我们利用生成的tr()函数进行作用域翻译，和一个自我测量和扩展的运行时的类型信息的先进的属性系统。属性系统有一个独一无二的优势：没有一个强大的和自我测量的属性系统——如果这不是不可能的——一个Qt设计器这样的强大的和通用的用户界面设计工具就很难被写出来。

带有元对象编译器预处理器的C++从本质上给我们带来对象的C的灵活性或一个Java的运行时环境，当保持C++的唯一特性和可伸缩的优点。它使得Qt成为我们今天拥有的灵活和舒适的工具。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Tetrix

This is the Qt implementation of the well known game Tetris.

Main:

/****************************************************************************
** $Id:  qt/tetrix.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "qtetrix.h"
#include "qdragapp.h"
#include "qfont.h"

int main( int argc, char **argv )
{
    QApplication::setColorSpec( QApplication::CustomColor );
    QDragApplication a(argc,argv);
    QTetrix *tetrix = new QTetrix;
    tetrix->setCaption("Tetrix");
    a.setMainWidget(tetrix);
    tetrix->setCaption("Qt Example - Tetrix");
    tetrix->show();
    return a.exec();
}

See also Examples.


Text Related Classes

These classes are relevant to text processing. See also the XML classes.

QChar | Lightweight Unicode character
QCharRef | Helper class for QString
QConstString | String objects using constant Unicode data
QCString | Abstraction of the classic C zero-terminated char array (char *)
QLabel | Text or image display
QSimpleRichText | Small displayable piece of rich text
QString | Abstraction of Unicode text and the classic C null-terminated char array
QStringList | List of strings
QStrList | Doubly-linked list of char*
QStyleSheet | Collection of styles for rich text rendering and a generator of tags
QStyleSheetItem | Encapsulation of a set of text styles
QTextBrowser | Rich text browser with hypertext navigation
QTextEdit | Powerful single-page rich text editor
QTextIStream | Convenience class for input streams
QTextOStream | Convenience class for output streams
QTextStream | Basic functions for reading and writing text using a QIODevice


Text Edit Example

This example displays a text editor with the user interface written in pure C++.

A similar example which uses Qt Designer to produce the user interface is in the Qt Designer manual.

See $QTDIR/examples/textedit for the source code.

See also Examples.


Themes (Styles)

This examples demonstrates how to let widgets be drawn in different styles (themes). As an example, themes looking like wood and metal are implemented. You can switch between the different styles during runtime using the pulldown menu.

Header file of the Wood theme:

/****************************************************************************
** $Id$
**
** Definition of something or other
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef WOOD_H
#define WOOD_H

#include <qwindowsstyle.h>
#include <qpalette.h>

#ifndef QT_NO_STYLE_WINDOWS

class NorwegianWoodStyle : public QWindowsStyle
{
public:
    NorwegianWoodStyle();
    void polish( QApplication*);
    void polish( QWidget* );
    void unPolish( QWidget* );
    void unPolish( QApplication*);

    void drawPrimitive( PrimitiveElement pe,
                        QPainter *p,
                        const QRect &r,
                        const QColorGroup &cg,
                        SFlags flags = Style_Default,
                        const QStyleOption& = QStyleOption::Default ) const;

    void drawControl( ControlElement element,
                      QPainter *p,
                      const QWidget *widget,
                      const QRect &r,
                      const QColorGroup &cg,
                      SFlags how = Style_Default,
                      const QStyleOption& = QStyleOption::Default ) const;

    void drawControlMask( ControlElement element,
                          QPainter *p,
                          const QWidget *widget,
                          const QRect &r,
                          const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl cc,
                             QPainter *p,
                             const QWidget *widget,
                             const QRect &r,
                             const QColorGroup &cg,
                             SFlags how = Style_Default,
                             SCFlags sub = SC_All,
                             SCFlags subActive = SC_None,
                             const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControlMask( ComplexControl control,
                                 QPainter *p,
                                 const QWidget *widget,
                                 const QRect &r,
                                 const QStyleOption& = QStyleOption::Default ) const;

    QRect querySubControlMetrics( ComplexControl control,
                                  const QWidget *widget,
                                  SubControl sc,
                                  const QStyleOption& = QStyleOption::Default ) const;

    QRect subRect( SubRect r, const QWidget *widget ) const;

private:
    void drawSemicircleButton(QPainter *p, const QRect &r, int dir,
                              bool sunken, const QColorGroup &g ) const;
    QPalette oldPalette;
    QPixmap *sunkenDark;
    QPixmap *sunkenLight;

};

#endif

#endif

Implementation of the Wood theme:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "wood.h"

#ifndef QT_NO_STYLE_WINDOWS

#include "qapplication.h"
#include "qcombobox.h"
#include "qpainter.h"
#include "qdrawutil.h" // for now
#include "qpixmap.h" // for now
#include "qpalette.h" // for now
#include "qwidget.h"
#include "qlabel.h"
#include "qimage.h"
#include "qpushbutton.h"
#include "qwidget.h"
#include "qrangecontrol.h"
#include "qscrollbar.h"
#include <limits.h>
#include "qstylefactory.h"

/* XPM */
static const char *polish_xpm[] = {
/* width height num_colors chars_per_pixel */
"    96    96      254            2",
/* colors */
".. c #9c4a34",
".# c #a4825c",
".a c #bc5e2c",
".b c #d48432",
".c c #dc9f51",
".d c #bc6e1c",
".e c #d4855d",
".f c #94664c",
".g c #bc714e",
".h c #8c6664",
".i c #d4923c",
".j c #bc8444",
".k c #d49360",
".l c #d4794e",
".m c #ecaf68",
".n c #bc8365",
".o c #d47439",
".p c #a46954",
".q c #dc9f70",
".r c #e48544",
".s c #bc7b51",
".t c #a47761",
".u c #bc7b42",
".v c #a4523c",
".w c #e4945e",
".x c #9c784c",
".y c #d4844a",
".z c #eca053",
".A c #bc614c",
".B c #e4855c",
".C c #bc8350",
".D c #c48e68",
".E c #b16634",
".F c #e49339",
".G c #bc703a",
".H c #bc7c67",
".I c #a45f34",
".J c #cc714d",
".K c #d48c5f",
".L c #a47057",
".M c #cc703a",
".N c #dca674",
".O c #b47859",
".P c #bc6729",
".Q c #d49475",
".R c #d48b4a",
".S c #cc8351",
".T c #cc8466",
".U c #ac6841",
".V c #e4a651",
".W c #e49576",
".X c #d47d31",
".Y c #ac6e4b",
".Z c #c07650",
".0 c #e48c43",
".1 c #e49452",
".2 c #9c745f",
".3 c #e47e54",
".4 c #cc7c4f",
".5 c #cc7c32",
".6 c #b46133",
".7 c #d49a68",
".8 c #d67e4f",
".9 c #bc7643",
"#. c #b47056",
"## c #d48b3a",
"#a c #dc9f5e",
"#b c #e49a60",
"#c c #cc6a31",
"#d c #8c6244",
"#e c #dc9a41",
"#f c #eca753",
"#g c #bc8a58",
"#h c #d48c76",
"#i c #bc693f",
"#j c #bc715d",
"#k c #9c6857",
"#l c #f4b171",
"#m c #bc8a6a",
"#n c #eca16d",
"#o c #a87e58",
"#p c #a4613f",
"#q c #a48569",
"#r c #d4846d",
"#s c #dc935f",
"#t c #c47c50",
"#u c #dc8449",
"#v c #bc6950",
"#w c #cc9678",
"#x c #c4703a",
"#y c #cc7b67",
"#z c #dc8c5e",
"#A c #ac7067",
"#B c #eca86e",
"#C c #b4786d",
"#D c #dc8c4a",
"#E c #b46842",
"#F c #d47c41",
"#G c #e48d51",
"#H c #e59a52",
"#I c #9c6e3f",
"#J c #d49351",
"#K c #cc843b",
"#L c #ecb678",
"#M c #9c5a38",
"#N c #d4795c",
"#O c #c47b39",
"#P c #ec9560",
"#Q c #ac764c",
"#R c #c48351",
"#S c #c48e74",
"#T c #cc7650",
"#U c #cc8a84",
"#V c #bc6a5c",
"#W c #e4af74",
"#X c #b46855",
"#Y c #e4a06e",
"#Z c #ac775b",
"#0 c #e48d5d",
"#1 c #c47d65",
"#2 c #cc763f",
"#3 c #b47e5d",
"#4 c #cc8a55",
"#5 c #cc8a67",
"#6 c #bf622f",
"#7 c #dc853b",
"#8 c #e49f4a",
"#9 c #9c505c",
"a. c #8c5644",
"a# c #cc7329",
"aa c #a45a51",
"ab c #b48264",
"ac c #9c7a7c",
"ad c #9c5f4f",
"ae c #b4844c",
"af c #a46749",
"ag c #dca664",
"ah c #b46e1c",
"ai c #c4762c",
"aj c #a45a3c",
"ak c #dc9a74",
"al c #ac7e46",
"am c #ac6a6c",
"an c #eca862",
"ao c #e49a41",
"ap c #e49a78",
"aq c #bc7660",
"ar c #d57e5e",
"as c #9c6e5c",
"at c #ab7e65",
"au c #cc8a44",
"av c #9c6240",
"aw c #bc6244",
"ax c #bc5d3f",
"ay c #e48550",
"az c #eca060",
"aA c #cc7160",
"aB c #cc7c42",
"aC c #b46241",
"aD c #b4726c",
"aE c #eca67f",
"aF c #9c6a3c",
"aG c #94685a",
"aH c #c48240",
"aI c #c48465",
"aJ c #dc7640",
"aK c #cc8f54",
"aL c #e4a76f",
"aM c #c4692e",
"aN c #dc9474",
"aO c #ac6050",
"aP c #b47048",
"aQ c #94614b",
"aR c #ac836c",
"aS c #a47048",
"aT c #b4764a",
"aU c #ec8e5c",
"aV c #dc9a53",
"aW c #cc765e",
"aX c #b48a64",
"aY c #dc9a63",
"aZ c #c47640",
"a0 c #ec9a60",
"a1 c #c48a54",
"a2 c #c48a67",
"a3 c #ac5a3c",
"a4 c #ac8458",
"a5 c #dc855d",
"a6 c #c4714d",
"a7 c #dc9243",
"a8 c #dc794e",
"a9 c #ac6955",
"b. c #cc8f67",
"b# c #ac6032",
"ba c #ac7056",
"bb c #dc7a34",
"bc c #ec9553",
"bd c #dc8d3b",
"be c #e4a060",
"bf c #f4a654",
"bg c #c46842",
"bh c #c46f62",
"bi c #ac613d",
"bj c #dc866c",
"bk c #c4694e",
"bl c #dc7d42",
"bm c #ec8d4f",
"bn c #dc9351",
"bo c #cc9177",
"bp c #c4695f",
"bq c #ecb075",
"br c #e4a75f",
"bs c #d4843c",
"bt c #bc722c",
"bu c #d4936c",
"bv c #d47644",
"bw c #bc7d5c",
"bx c #ac563c",
"by c #e4956c",
"bz c #a47a4c",
"bA c #d48454",
"bB c #bc825c",
"bC c #e49544",
"bD c #bc7044",
"bE c #bc7e74",
"bF c #d48d6c",
"bG c #cc7144",
"bH c #b47864",
"bI c #bc6a34",
"bJ c #d49684",
"bK c #d48b54",
"bL c #cc845c",
"bM c #cc8474",
"bN c #ac684c",
"bO c #cc7d5c",
"bP c #eca27c",
"bQ c #dc946c",
"bR c #c47c5c",
"bS c #dc8554",
"bT c #c47244",
"bU c #dc8c6c",
"bV c #dc8c54",
"bW c #b4684c",
"bX c #cc8344",
"bY c #c47b44",
"bZ c #c4825c",
"b0 c #e4a17c",
"b1 c #ac7a64",
"b2 c #e48c6c",
"b3 c #c47a74",
"b4 c #e49f54",
"b5 c #9c674c",
"b6 c #946764",
"b7 c #c48674",
/* pixels */
"#u#G#G#P#G#G#G.1#G#G.1.1.1.w#G.r#D.1.1.1#D#DbVbV.K.K.K.KbO.Z.Z#TaP.GaT.Z.O.O.O.H.9aP.ZaPaPaPbZbo.i.k#J.k#JbKbnbn#b#sbVbV#G#G.r.ray.r.0#G.0#G.1bc.r.0.0bc.0.0.0.r.1.1.1.1#G#D.0#D.0.0.0bcbcbc.1.0",
"#aagaLbrag#a#a#a#DbVbn#G#0.1#0#Da5#za5.4.J.Jbk#vbt.G#x.9bY.4#tbYbw.saPaP.Ub#af.Y.s.s.Z.saP#E.gbw.U.U.UaObWbWbWaPb#b#.E#t.K.K#z#s#s#sbQ#s#sbn#s#sbn#s.w#s.w#s#sbn.ybV#s#sbV#s#sbQ#aak.7.k.7.k.k.k",
"#..g#.#.#j#.#XbW#Z#o.O.O#3.n.n.Halalalala4aXaXa4#t.u.9#R#5bu.k#5bob7aIaI.nbwbw#m#5aIa2#5#5aIb7#5.DbBbB#3bwbw.C.O#oabab.naI.C#t#R.9#tbY#tbY.ZbY.s#t#t#t#R.sbY.s#tbD.Z.Z#t.9.Z#t.4bBbw.s.saT.9aTaT",
".ybS.ybSbVbVbVbVbl#u#u#ubSaybSay#s#za5#z#z#z.KbA.Qb.aIbZbZbB.g.U.gaP#.aP#.aPaP.O.9aP.g.s.O.ZaP.Z#CaD#Aamamamam#X#3#Z.OaPaPaPaP.saZbY#t#t#tbY#tbY#t#tbLbZ.SbR#t#tbZbRbZbRbR.sbRbR.4aBaB.4bY.4.4.4",
"bKbV#zbKbA.ybK#zbV#z#0bS#0#0#0aya5bA.4.4.4#T#xbgbwaq.O.g.O#j#.aPaCaC#v.g.gaPaP.Z#R#R#t#t#t.Z.s.Z#O#O.5aH#KbY.S#4bD.G#xaZaZ#2.SbVbV#s.wbV#zbSbAa5.e.KbQbQbU#s#z.K#5.K#5.T#4#5.Kb..4bZbL.T.ebL.K.K",
"#A#A#C#C#AaD#CbEatataRb1b1abb1.t#I.f#IaSbz.x.#.##v.g.g#1bR.T#5#hbObO.T.K.K#5.KbubL.4.4#t.4.Z#tbL.e#r.K.K.e.e.T#r.K#z.K#z#sbVbS#zbV#u#ubVbl#F.8.l#2.4.8bAbA.l.4bva6.g#x.g#x#i#i#i.L.Lba#Z#Z#Z#Zba",
"aPaT.u.u.s.C.C.C.SbA.S.4.SbA.8.8#r#rbF#h.TbO.T#h.KbF.e.e.S.S.S.S#u.y.8bA.e.4bA.e.K#zbQ#s.K.KbUbQ.y.R.y.yaB#O#xbT#t.4bLbLbL.4bL.S.4.S.4#T.Za6.Z.JbD.g.Z.g.Z.g.Z.ZaP.g#iaP#i#E#EaC.Obababa.ObH#Z.O",
"#zbSbA.e#za5.e.8bV.KbV.ybAbK#zbK.8.ybV#z.y#F.y#sbKbA.Rbn#sbn#b#b#Y.w#sbV.y.4.lbA.y.y.ybA#T.MbG.4bObO.4.SbLbOaq#..O.Yaf#p#p.I.U.UaT.Z.O.Oaq.O.H.Hb1b1#Z#Z.L#Zat#3bw.s.HbBb7aIaIaIbA.l.4aBbAbA.e.e",
"#DbVbn.w#s.w#sbVbAbSbSbV#D#GbS#0.1#H#H#H#b.1bn.1#4.S#t#t.S.TbL.S.K.K.K.S.SbK.e.S#t.4#t#tbDaPb#b#.U#E.9.S.ebVbS#G.K.K#r.l#y#T.Z.Z#2aB.S.ybS#u.8#F#Kau.y.S.y.y.R.y#z#z#sbn.1bna7bd#F#DbVbVbV#s.w#s",
".1#s.1#s.1bVbS.y.K#z#sbVbVbA.8#FbA.8ar.8.e#r.e#NbKbA.S.S.S.SbLbLaBaBaB#2aB.SbKbAbVbVbV#s.w#YbebQ.KbA.e.KbV.ybl.ybsbsbs#D#u#D#u.R.y#D#DbVbV#s#0.wbebe#b#bbQ.wbn#GbV#G#D#G#D#GbV#D.ybV#sbV#s#s.w#s",
".wbn.w.w#bbQbVbV.4.4.ybKbnbV#z#z#G#D#D#D#u#D.y.R#2aB#2.M#x.M#2#2#z#s.w#sbV#s.w#s.1.w.w#b.w.1#G#G#s#zbVbVbVbSbVbVbd#ubd.r#D#D#D#D.1bC.1.1.1.1#D.1bV#G#0#0#G.w.1a0bC#G.0aybS.Ba5a5bVbVbV.w#z.w#sbV",
"#ubVbVbVbV#GbV#D#s#sbn#b.w.w.1bVb2b2a5#z#z.K#zbA.w#s.w#sbV#s#z#s.w#b.w.w#GbV.w.w.X#Da0a0#G.1bcaz#G#GbS#GbV#ubV#0#z#0#0a5#0#0b2#0.0.r.0.0#u#u#F.o.M.M.M#F#ubV#G.1#b#P.w.w.w#0aya5.y#u.y.ybVbnbVbV",
".wbV#GbV#G#s#G#0.1#G.1.1.1#G#G.0#0#0.w.wby.wbQbn.w.w#G.w.wa0#b#P#u#G#G#0#G#G#G.w#baz#Yaz.1.0#D.0#G#G#G#GbVbl.8blbva8.8.B#z.Ba5#0ay#G#G#z#G#z#z#z#zbU#z#z#zbQbybQ#zbK#z#s#sbn.R.y#2#2aB.8bVbV#0bV",
".w.w.w#z.w.w.w.w#GbV.r.0.0#G#G#Gbda7a7#H#8#8#8#H#u#u#F#u#D#GbV#u#G#G.w.1.w#G.wa0bV#D#DbV.w#baz.w#G#G#G#G#0.BbSa5#u#u#D.1.1bn.0#7#z#0bSbSbSa5#z#z#r.e.e.4.4#2#2bT.4.4.4.S.R.Rbn.i#s.K#zbV#s#0bV.w",
"#u.8#u#u#ubV#GbVby.wbQ.w#b.wbVbl#T#T.l.ear.Ba5.8.w#G#G#G.w.1.1.1.1#G#G.w.1#G#G.w#P.w#G.1.w#P.w#0#D#DbV.w.w#0#0#0.w#b#baVaVbn.1#G.y.y#F#F#2.obv#Fay#z#GbVbV#z.e.e#z#z#zbV#s#s#s#sbQbQ#sbQ.wbV#G#0",
"#0#0#0#G#0#u#ublbDbT.4#4#zbQ.e.e#s#s#s#z.w#0#0aU#DbSbVbV#D#D#D#G.w#G#G.w#P.w.w.w#Gbmbmbmay#u#G.waz#b.w.w#Ga5bl#uaraW#i#i#ia6.4.ebVbnbQ#b.w.w#GbV#u.r.r#G#G#G#0a5.1.wbV#zbSar.J.JbT#x#2.y#F.8#u#G",
"#5.TbL#tbD#i.g.Z.SbA#zbAbKbSbSbA#u#D#G#u#u#u#DbV#GbVay#G#0#G#G.r#D#Gbn.w#b#b#HaY.1bVbV.y#u.y#F#Fbv.o.M#2#2#2aBbG.9#OaB.y#D.1.1.1.w#s.1.w#G#G#G.rbdbda7bdbnbn#sbQ.nbw.s.Z.4.8.8.8.obl#u#zbV#z.K.K",
"#i#x.Z#tbL.K.kbQbAbVbK#u.ybSbV#z#G.w.w#G#D#G#0#G.1#G#D.1.1.1.1.1bVbV#z.yaBaM.M.5.y.y.y#ubV.w#P.w.w.w#b.1.1.w.wby#b.w#b.w#b.w.1.1#u#u#ubVbAbK#z.S.T.TbO.Z#vbga3axbD#xaZ.8bAbAbAbA.e#4bA#ta6.P.6.6",
".S.4bL.e.e.e.ebA.8bSbSbSbVay#0#G.1.1a0.1#ba0#H#bbc#Hbc#Ha0bc.1.0#z.8#T.J.l.ebVbV#G#G#G.w.w.w.w#P.w#b#n#b.1.1.w#n.1.1.1#G#G#D#ublbl#2.4.4.g.Z#ZbN#9#9aa#X.g.ZbOar.Mbvbla5#z#zbA.laPbNbi.U.U#..Zbw",
"bL.e.e.e#zbSbSbl#u#DbS#G#G#0#G#G.1.1.1.1bc#Ha0.1#G.1.1a0#b.1#u#F.e.4#T.8by#b#na0a0#b.w.w.w.w#P#0bVbV.1.1#G#G#u#G.1#G#G#ubS.8.l#T.Z.g#ibW.UbNa9#p.UaP.9.S.ybVbV#Dayay#z#z.e.4bT#i.pad#pbN#.bRaI.T",
".4.e.KbS.8blblbSbSbS#GbV#G#0#G#G#G.0.1.1bcaz#H.1#G.1.w#P.w.w#z.8bK.KbQbQbV#u#D.1#0#G#G#G#G#G.1#P.1.1beazbe.1#G#u#zbK.K.4bO.Z#j#v#A#ka9.YbW.ZbL.4.R.R.ibn#D#u#F#FbS.S.4aqaPbNbi.I#.bWaP.gbObL.8bL",
".K.K#z.e#F.lbv#F#z#GbS#u#u#G.w#G#u#G#G#G.1a0bc.1#P#P#P.w#GbVarar.R#J#HaY.1.1.1#H#H#b.1.1bc.1#P.1.w#b#bazbe.w#zbA#t#t.Z.Z.Z.g#.#.b1ba#..Z.Z.lbS#u.y#u#ubSbS#N.laA#j.ga9#kad#ka9#..g.g#tbO.e.e.ebA",
".l.l.8.y.8bAbAa5bSbS#ubSbS#0.w#G#G#G#G#G.1bc.1bCbm.1.1.0#Dblbv#T#D.R.ybVbe#nazanananbeaz#b#bbc#H.wa0.1#sbV.S.S#t#t.s.Z.sbwaIaIaI#t#t.4bA.lbl#ubl.3a5a5.e.4bh#V#XbN#k#kaG#k.L.OaIbL.e.K.ebA.y.4.8",
"bSbAbAa5.ebA.8.4.8.ybS#z#G.w#0bSay#0bm#G#G.0.1.0bc#H.zbf.zbe.1#z.KbVbSbA.y#D#D.1bebebe#HbeazazazazazbebV.S.4#1bMbZbR.Z.Z.Z#t#tbYbl.o#ubS#Gay#0#uarbl.laB#t.uaT.Oad#kaGb6#ka9.g.Z#t#t.4.4#t.4bK.K",
"aBbs.y.ybA.l.lar.4aBaB.8.y#F#u.wbn#D#D#G.0.0a7.FbdbCbc.1.1.0.1bc.F#8#H.1.ybG.4.ebn#s#s#baY#saYaV#b.w#s#J.SaZbD.sbR#t.S#z#ubs#F.R#D#D.0#G#G#G#G.0#D.R.yaBbDbDaP.g#Zb1.L.fb6.h.hac.I.YaT.u#t.Z.Z#2",
"b3bR#1.4.4.4bX.R.K.KbV.ybl#F#F#F#za5a5.B#z#0#sby.1#G.1.1.1bm#G.1a0a0#H#H#b#b#s.ya#.X.y.ybVbn.w#bbebeaY#sbAbRbZa2au.S.R#s#z.y.e#zbs#ubn.1.1.1#G#D.0#D#D.RbA.4bO.4aPbD#Eb#af.I#Maf.2.x.L.L#Z.O.n#S",
"aObi#Xbw.s.sbY.SbXbK#z#z.w.w.wa0#z#za5bS.l.l.8bVbSbVbS#G#G#G.w#Pbe.w#b#bazbrb4#Hbebebe.1#u#F.5.X#F.y#s#Y.NaN.Q.Q.T.Tbu.w#sbn.1be#sbVbV.y.y.ybn#b#G#G#G#G#0bn#zbSbn#bbn#D.R.RaBbX#3.O.Yaf.I.Ibi#E",
"aVbX.G.6a3aCb3#U.y#z#s#0#z.w.w#s#H#H.1.1.0#G#Hb4bVbV#u#u#u#D.0#D.1.1.1#D#7#D#Hb4bCbc.1.w#b#b#n#nbe.1#u.yaBbX.S.kb4.cb4aYbA#T.4#r.4.K.K#s#s#s#D.y#GaybV.w.w.w.w.w#G.w.w.w#b.1bn.1#P.w.w#0#0aybS#G",
"bnaVaYbeaNarbp.A.P#2#F.y#u#s.w#sb4b4.1.1.1.1#H#H#nbeaz#b#HbnbCa7.zbe.z.1#D#D.w#Baz.z#H.w#P.w.w.wbebeanbrbebn.RbX.4bQb0aL#BaYa7.bbA.4#xaMaZ.ybK.kbA.4.4#F.8.ybA.ybv#u#ubS#sbV#D#zbl.ray#G#G#P.w#P",
".w#0bSbVbV#D#D.1aY#b.w#zbS#FaBaB#x.M.l.8a5byap#bbn.1bebebebebeaza7.0bd#u#ubSbS.BbC#D.0#D#G.w.w.1anazb4bebebebr#B.V.c#D#Oai.S#s.WaE#Y#Y#YaY.kaB#x#4.S.S.4aBbX.y.y.y.K#z.KbV#z.ybV.ybKbKbK.K.K#z.k",
".8.8#u#G.w#HaV.1#s.w#s#0#zbV.wbQ#na0by#0a5bSbvbg.M#F.y#ubSbA#z.k.w.w.w.wa0a0.w.w#H.w#HbV#D#u#G.1.1.1#b.w.1.1#D#DbVakaLaLaLbq#B.VaB.XaB.ybKbQaLaL.q.qaY#a#b.w#b#b#b#b.wbn#s#D.y#D#s#s#s#JbKau.SbA",
"b4#Hbe#baY#s.K.S.y#F.ybSbS.R#zbe#H#H.1#Gbc#b#bbn.w#bbybQ.4#xbga6#T.l#za5bV#G#Gbc.w#b#b.wbV#D.1beby.wbVbV#z#s.w#Y#bbeaY#J#s#Ybe.1#B#B#Bbr#s.RbA.KbKbnaV.w#b.w#Ha0b4anbe#Hbe.1.1#bbC#8bc#Ha0a0#Pbc",
"b4#8#8#H#HbCbC.1b4#b.w.1#P#G#G.0akbVbXaB#2#2.4bAbA.KbAbV#s#b#YaY.1bV.8aZ.GbYaB.S.RaV#abebn.1#8az#b.w.w#b#ba0by.w.1#Hazbebe.1#s#b#ebnbnbnaVaVaYbnbnb4bebe#abe#abebnbnbnbn.ibnbnbn##a7#8#8#ea7beaL",
"#Y.w.w#s.w#0#z#0#D#DbVbVbVbV#bana7#D.1.1#b.1#D#D#u#u#Fa#.o.y#D#D.r.r.w#b#Y#b#b.w.gbkbg#Tar#za5a5####.5.b.Ra7.1bn#HaV#H#Hbn#D#D.ybQbQ#z.K.e.K.e.ea7bnaVa7bnaY#aaL.m#Wbrbr#Ybr#W.m#L#L#L.mbeb4.w#b",
"#sbK.ybS#z#zbSbS.k.k.K.S.SbAbKbn.w.1#D#GbV#GbV.w#G#G#G#u#u#ubl#7.r#G#G#0#zayay.0#Y.wa5bS#zbS.8.M.4.Z#xbka6#TbObO#D.Rbn#s#bbebebebV.R.R.y.R#D#DbVbebe#BbqaLbebn.Rbnbnbebr#BbrbeaV#Da7bran.mbr.1#D",
"anazbean#Banbe#H.y#O#x#x.ybKbK.R.Jbvar.ebja5#N#TbvbS#z#0#0.1#0bV#G#u#u.o#Fbb#7bm#F#7#u#D#Dbn#bbe#s#s#sbn.w#zbVbVbkbpbpbpbhbhbhbhaAaAaWaW#N#r#rbFbs.ybKbn#b#YaLbq#Bbrbebebebr#BbqbeaLbe#Y#B#B#B#B",
"a7#DbCb4azananan#BaL#b#Yby#b#G#ub0aN.e#x#i#xaWbObAa5.e.8.4#2.4.4.w.wbQ#zbSbSbVbV.w#z#zbS.JbGbG.l#D#GbV.1.w.1#G#G#H#8#8#8aoa7#8#8#D#Dbn.1bnbC.1bC#b.w#D#D.y.5bs.y##a7#Hbranbe.1.i#sbn#D.Rbsbs#ubs",
"#b#0.y.8#2#2#2#2#F#u#G.w#0#G#Pazb4b4beb4bnbn##.5#xaB.4.4.4.e#z.K.e.SbA.8bA.ebK.K#zbV.y#ubVbVbVbVar.8ara8ara8a5ar.RbV#zbVbA.y#D#sbSa5a5bV#zbSbVbS#G#DbV#b#b.1bn#bananbeb4b4anananbean#B#B#Bazbebe",
"#0a5bSbV.w#Y#BaE.1#0.wbSay#uay#Gbd.FbCbC#H.zanaz#b#b#b.w#zbA#2#c.P#6#6.M#2.e.K.k#KaB.Xbsbn.1.1#7#Hbna7#D#D#D#D.0#0#zbVbV#u#F#FblbdbCbC.1bC#G.1.1bV#u#D#G#Hbean.manbeanan#B.manan.mbebe.1bV.1.1.1",
".zbCa7#Hazanb4#8#Y.w.y.8#z.w#G#D#G#0#P#0#0#0#uaJ#D#u#ubl#D#0.wb2.w.1#0#0.w#z.4.G#vbhbRbO#rar#N.l#4bL.S.4.4.4.4bLay#D#uay.1#Ha0.w.1.w.1.w#G#s#0.w#G.1.1an#Bazb4b4anazb4b4.zananan#f#f#8#b#H.w.1#b",
"b4#Hbd#Ha7#H.1.0a7#H#b.wbV#s.w#0#D#D#D#D#G#u#u#G#G#G#GbV#u.8.y#ubs#7#G.1.1bn#D.y#xbXbAbAbYbt.Z#RbXbK#s.k.R.S.RbAbl#F.o.o#Fbv.yblbV#u#7#G.1.z.z.z.w.1#G#u#D.0#G#nb4#H.1.1#b.zb4.z#H.1.1.1#Hbe.m#B",
"#Y.w#D.1ay.w.w#Ga7#H#H.w#G#G#G#G#D.wbV#G.1.w#G.1#D#D#ubSbA#u.KbV#s#G#u#u#ubVbn#s.zb4b4#sbO.g#V#X.MaB.yaBaB#2aZ#2.y.y.R.KbQ.KbQbu#zbAbK#s#bbe#Ybea0be#bbn.w#D.y#G.1bC.1.1a0#b.z.z.zbc#H.zbCao#HbC",
".wbS#0.wa0a0#na0azaz#b#H.1#G.0.0.w#P.w#G#0#G#uay#D#DbAbK#z.KbSbK.l.4bv.8#F.l.e.S#ubAbA.RbK.K.K#s.4bAa5#z#z#z#z#z#w#m#3ba.p.p.L.L.ZaZbD#t#R.SaKaKakap#Y#bak#s#zakbn#D#u#D.y#7bs#7#F#F#u#0#0#0by.w",
"bna7anbran#8az#8.1#ba0#bbcbeaza0a0.w#G#G.1bm#G#0.1#z#GbV#z#0#s#G.e#z#z#za5.8bGbgaAbv#T.l#F#Da7a7bQbybQ#z.e#z.ebAblblay.0ay.raJ.obR.s#tbR#t.s.s#tbDaZa6bT.Z.gbT.SbA.S.S.KbQ.q.q#YbqaLbeaV#D#u#D#u",
"auauaL#W#Wbr#L#Wbe#nbe.w.w.w.1a7.1#H.1.0#u#7#7.r.0#ubl#uay#Gay#u#z#za5#u#ubS#za5#D#u#u.8.8.8.8#r.4bYaZ.G.GaZaZaZ#t.SbLbFb.#5bO.Z#t.Z.Z#t.Z#iaC.E.Z#1.g.ga6#ibWbR.C.s#..OaPbNbi.Ua9ajaO#X#v#y#r#h",
"bL#1b.aI.g.I.UaP.GaZ#t.4.SbK#sbQbe#Bbe#b.1#D#D.w#G#DbSbl.8bl#u#F.8aB#F#F#F#ubV.w.ybSbS#u.8.8a5#z.k.K.KbK.KbQaYakbu.K.S.4.4.4.S.e.4.8.4.ebF.Kb.#h.gbR#taq.ZbW#E.gaP.YbNba#.babaaP#3.u.s#R#R.S.KbK",
"a6a6.Z.ebO.T.QaNa2a2aIaT.Ub#.6.EbIaZaZ.4.S.SbA.kakbQ.k.KbF.ebA.y.e.ebSbS#u.8#FbG#r#r#r.e#F.ybsbdbV#zbV.yaBaB#2#2#MavaS#Z.O.O.OaPa6#i#i.ZbRaI.H.n.ZaIaI.T#5aIbRb.b.bLaIbRbR.gbWaP.g#v.g.Z#x.gbT#i",
"#H.1#DaY.ybV.SaB.Y.O.O#.#X.ObBaIbR.T#1#t#1.Z.g.ZaP.U.U#EbW.g.g.g#T#T.4.l.l.8bS.e#F.8#F.l.8arararblbSa5#0bS.BbS#ubV#u#ubl#ublblbl#5bZ.gaP#.babN.pb##E#E#E.Z.g.gaIaB#2.ZbL.T.e.e.K#z.kby#b#b#Y#Baz",
"brbrb4#Hb4.1#D.0.R.y.y#F.yaBbvaB.Z.g.g.g#jaOaxbxaFaS.Y.O.s.s#ta2#Fbla5bSay#ua8bl.y.y.RbK#J.KbKbK.S#F.y.8.8bA#F.l.y.y.8.8.4.4.4.4aPbtaPaP#E.YaPbNaP.Z.sbwbw.C.CbZbB.C.Z#..O.H.OaP#RbX.SbK#JbnaV#a",
"aZ#taZ.Z.4bLbO.ebLbR.S.TbL.T#4buaK.S#R#R#4.Sbw#t#3aT.Z.ZbD#i.E#i#Z#ZafafbN#Z.na2.3ay.B.Bay.B.8a8bn.y.4.4.4.8.8bAbl.y.ybKbS.e.e.8#F.K#s#s.k.KbLbObL#t.Z.9.G.GbI.E.G.9aP.g.ZbZbZ#tbJaI#.#EbW#E.g.Z",
"aKaKaH.u.C.C.sbw.O.O.O.O.Y.Uba.O.uaPbtaT.u.s.s#Rb.#4#5bLbL#T.Z.4.4#t.4.4#t.4.y.ebKbAbV.KbAbAbA.K.KbVbAa5#z#z#z.y#z#zbS.8aB#2.M#2.o#F#ubl#F#u#G.wbQbKbKbnbQ#YaL#Y#saY.KbAbYaBaBbY#.bibiaPaI.Tb7bR",
"#h#5#1#X#jaOaaaa#M#paf.Ybaba.n#S.H#.#.aDaqaqaq.HaPbW#x.Z.4.Z.4bR#RbLb.b..k#4#R.4#RaH.u.u.u.ja1aK#F.S.4.K#zbQ#zbVbSbSbS.ybS#DbVbVayayayblbbbl#u#G#D#u#u#D.1.1#b#H#H#b#b#GbV#s#b.1#L#WaL#WbqaLbK#K",
".zanbeb4be#aaY#aak.k#4bL#t.G.G#i#1#j#j.gaq#j#.bW.ZaT#tbRbObRbLb.#u.r.r.r.r.rbmbm#za5bv.la5a5a5a5.K.4#xbg#xbg.MaM#2.8bV#s.w#sbV#ubS#z.1#z#G#G.1#G.1.1.1.1.1.1bc.1.1.1.1#G.wazaz#Bb4#8bC#Hbebe#H#b",
"#D#G#G#u#0#zbSbSbVbVbAbAbV#z#z#s#JbK.R#s#saYaVaYb.#4.SbL.4.Z#t#t.L.LaS.Lba.O.n#mbQ#z.K#zbQ#0.e#2bQ.K.K.K#z#s#z#D.y#F#F#F#F#F.oaB.8.y.8.y#ubV#0#D#u.r#G.0#G#G#Gbc.1#G#G#G#G#Hbc.1#naz#b.w.1#0#0#P",
".z.zbcbCbcbC.0.0be#b#ba0#H.1.1.w#Dbdbdbn#H#8.z.z#BaL#b.w#sbV#z#s.K.K.K#z.K.K#z.K#R.C.j#RauaubYbt.6#6a6bL#zak#bak#D#D#D.y#u#u#0#0.w#sbV#u#F#Fbl#u.w#0#G#G.1#G.1#G.r#GbV#GbV.1bc#H.w.w.wa0#0bS#G#0",
".w.w.1#G.1#P#G#P.w.1#H.1.1#D#D.1by#0#0#G#P.w.w#b#Hbc#Gay#G.r.1.wbv#F.l#F.laJbvblbA.8.l.8a5#z#zbS.K#4bO.4#TaBaB#Fb4#baz#b#P#zbl.o#F#D#0#G#G#GaU#0.B#u#u#u#G#G#0.1.w.w.w.w#0#G.1.1b4anbraz#8.1#8az",
"b4.1bnbC.1b4.zaz#f#fbr#fb4#8.Van#f#8#8ananbe#G#u.1#G#DbC.1.1.w.1.w.1#G#G#GbS#ubSaiaB.SbXaB#2.4bKbvar.ebF.T#1#j.gah#O##bnbn#D#baY.1#D#DbS#u#D#7#7.o#u#0.wbya0a0#0.wbn#0bSbAbS#z#0#8#8an.z.1bd.1a0",
"#b.1.1bn.1bebran#W.man.manbran.m.m#Bbebe.1#D#D#bbCbCbC#GbC#G.1#G#u.8#ubSbVbS#z#z.w#s#D#ubV.1.w.w#Da7bd#Dbs.5.5#O.Q.Q.K#N.Jbgawax#O.y#z#s#z#z#b#B.zazaz.1#GbC.0bd#7#D#ubSbV#G.wbebr.Vbe#8#D#7#7#G",
"#b#b#b#b.w#b#bbeb4#H.cbebe#bbnbK.e#z#z#sbVbs#D#G#z#z#za5a5#za5a5#sbn#z#z#z.y.8bAbl#F.o.o#u#G#G.r.1bnbn#D#DbV#z.w#T#x.MbGbla5a5.eaB.S.SbT.6.a#2bK.1bn.1bn.1bean#lazazbe.1.R#F.5a#.S.e.ebUbU.W.Wap",
".ybAbAbKbK#DbV.waV#HbebebeaYbnbn#z#FaB#F.y#D#Dbnbe#H.1bn.1#Dbnbn#8#eao#e#8#8#8#8#0#0#0.w#G#G.ray#2.J#2#2.la5#z.w#b.1#u#Gbnbn#D#DbAbA.4.4.8bA#z#z.e.8#T.J#x.l.K#z#D#0.w.w#b.qbraLanbr.Vbr#8bd.b.b",
"#B#B#Bazbrbebebe#8brbrbrbe.zbrbr.mbrb4#H#b#sbVbV#NaW#T#T.J.JbkbkaAbp#Vbpbhbpbpbp.e#zbQ.w.w#s.1.w#H#b.1#G#D#7#7#FbS.8.l.l.8a5#sbybV#G#0.w#0#z#Fa#.4#NbOar#r#r#z#za8.ybS.8.4aB.SbK.cb4anan.mbeanan",
"brbrbebrazbr#f.Vbr#f.manb4bebean.V.V.m.maL.1bA.y.Rbnbnbnbnbn#Hb4#Y.w#saYbQbnbK.RbT.GaM#2.4bVbVbK.8#F#u#z.wbybyby#G#G#zbV#u#F#F.obb#uay#0#0.w.w.w#b#b#sbn#D.X.5.b#z#0#za5bAbA.K#s#TaAbObO#T#T#raN",
"bnbnbnbeanbq#l#Lan.maLbrbebebrbeaVb4b4aVbnbn.wbe#T.4.ybAbK.KbQbQ#D.R#D.1.1#H.1#H#Y#s#zbVbV#z#u.ya5a5ar.l#T.J#vawa7#Hb4be#b.1.0.0#G#ublbv#c#c#2#u#Dbd#D.1.w#Hbean#b.w.wbVbSbVbVbVbVbV#D.1bV.1#ban",
"#Bbebe#abebeaVbnbn#sbn#D#s#a#b.w.q#b.q#Y#Ybe#HbnaY#baY#baVbnaVaV#bbn.w#bbebeaV#H#D.1bebe.w#G.wa0.z.z#HaV#HaYbnaV.ebLa6a6a6bOa5b2.w#b.w#zbU#s#s#zbA.lbv#T#T.l.y#0#8.1#D.1.wazaza0.w#P.wbebe#H#baz",
"az.1bcbc.1.1bCa0#H#8b4b4#H#Hbebr#b#bbn.ybXbK#s.c.ia7bebe#zbV.8a5bnaY.caLaLbe#H#H.kbKbKbK#s#b#b#H#bbV#DbV.wbe.w.1bCbCbn#D#2bg#i#i.J.lbA#s#b#bbQbQ#JbVbVbS#G#u.R.R.SaB#2#2aB#Fbd#H.z.1.wa0#b#Ybe#Y",
"au.S.S#J.k.R.kaY#DbVbV#sbn#s#s#b#Y#Y#Y#Yak.q#Y.N#Y#Y#a.R.y.y.ybV#ebrbq#WaL#B#bbV.i.RbVbn.1#bb4b4#s#D.y#ubV.1#b#H.1.1#bbe#Y#b#s#z#z#z#D#7bs#u.y.lai.5#F#u#0.wbebe.qakbQbQ#baY#b#b.1.1.0#G#D#ubb#F",
".k#s.k.k.K.KbK.KbA.KbK.K#z#s#z.K.5aBbX.4bY#RaHbY.Z.4.e#s#sbnb4#H.q#Y#sai.dbs#8anbeanan#Ybe#H#H#8#b#H.wbV#G#G.0.1.wbV#u#F#7#D.1b4#bbebebeazb4.1bVbebe.w#z#u#FaBai.4#2.4.ebQbQ.w#Y.w#G#GbVay#u#z.w",
"bm#G#Gaybl#ublblbAbA.8bSbAa5bS#F#D.1#zbnbVbK.K.K.K.e.4aB.y#Dbnbea7#8brbq#Y.K.ebU#Hbe#Yanazbeazanazaz#n#n.w.1.1.1.w.w.1#Pa0#b.1.0bV#G.1.1az#b.w#s#sbVbV#ubVbV.1#s#z.yaB#2bG.M#xbgbG.8#z#Yb0#b#s#z",
"bS#GaybS#G.w#b#b#zbV#0bV.w.w#G#G#G#G.1#G#zbV#D#u.y#D#z#s#s.K.8aiar.4.4bV#sbn.cbr#s#u#2.M#x.y#D#b.1#b#b#b#na0a0a0a0.1.0.X#7#u.1a0#z#D#u#F#u#ubVbV#n#n#b#Pby#b#Y#n#bbn#D#DbV.KbV#z.K#1#i.6.6bDbL.Q",
"#Ebi#p.U.Y#Z#C#3bAbAbKbV#s#G#s#0#D#G.w.w#0bc#Gay.1#D#7#F.ya5#s.WaV.cbebn#sbQ#h.T.K.kbQb0aE#YbV.X.y.y.y.ybV.w#b.1#8.1azazaza0a0.wa0.w#0#GbV#z#z#0#F#F#F#F#F#u#ubVbe#b.1aY.wbV.ybAbRbR.Zaq.Z#E.U.U",
".n#Z.p.Las.faQ.fafaf.U.UaPbD.Z#t.4bK#za5#z#G#G#G#G#G.w#G#GbV#u.ybUbQ#z#zbV#JbKbYb.#R.Z#tbA.wbe#n.R#D.y.y.8#Dbn#D#Y.w.wbn.w.waza0.1.1#H#b#P.w#GbV.w#0bV#u#u#u#u#ubv.o#F.y#DbK#z.K#z#4.4.S.TbL#t#t",
"bLaZbD#R#taP.U#Z.hb6as.L#k.pba#ZbD.s.ZbTbG.8bS#Gay.B#G#0#G#D.0#D#s.y.ybVbV.4.ZbL.s.s#R#4#s.w#H.1aY.qbebQ#s#s#sbnar.l.l#u.1#HbC.FbC.1bC.1.1.1.1.1aybVbV.w#s.w#s#0by#za5#u.y.4.l#r.y.8#F.8.K.e.4#T",
"#4#4.S.4#taZ#T#2aZaTbNaQ#daQ.fasaS#QaT.s.4.8ararbl#ubVbV#ubl#F.XbT.G#t.S#tbkbT.T.uaH#OaB#D.1.zaz.z#f.z.zb4.za0.z#Jbn#JbK.ybAbK#s#z#baz.z.z.zaobc.0.1#G.0#G#u#G#G#ubS#0bVa5bS#uaBaB.y.y#u#F#FbA.K",
"#zbK.e.S.8.S.S.T.O#Z.LaQaQaQb5af#..Z#t.4#F.yblblbl#ubVbVbK.S#t.saI#tbwbZaI#t#t.S.n#1.TbF#zbQby.wbebranbraz#b.1.wan#nbe.w#z.y#FaB.8.ybn#Haobcbcbc.1.1.1.1#G#G#G#0#G#0#GbV#ubVbVbV.8bAblbAbSbS.K.K",
"#F.l.8.4bLbRbRbR#Z.L#kafafbN#..Zbg.Jbv.8#u#D.0#7#ubS.y#t.s.Obaas#3baaP.Z.sbD.Z.Z.y#JaY#a#Ybe#b.wb4#b#bbebebebe#bbm.0#u#G.w.w#0bVbGbAbVbV.1.1.w#P.1#Ha0bc.1#Day#D#0.1bS#u#ubV#zbVar.8.l.8a5a5.e#N",
"#T.4.4bObw#.bNad#k.pba#.bR.4bAa5ara5#zbVbV#u.y.4.K#t.gbi#pb5.p#k.ZaP.Z#t.S.y#Dbna7bCb4.zazb4ao.1#b.1.1bVaybV#G.wa0.w#G#z#0#z.K.y.8bV.w.1.1.1bc.1bcbc#Ha0.1.0#G#G#G#G#G#G#GbVbV#ubla8a8blbSa5.8.4",
".e.T#1bw#..paQa.#E#v.Z.8.ebSbSay#FblbA.y.S.T.TaIaDbN#paj.U#v.g#ta6#TbAbSbS#G.1bc#GaU#P.w#0#GbSbS#G#Gay.r#D#G.w#P#D.y.8.4.4.e.e.e#u.1#P.1bc.1.1.1.0#Ha0#Hbc.1.1.way#0.w#0bV#GbV.ybl#F#u#zbVbKbA.y",
".g#.bW.UaOa9#..O.4.8bAbSbS#u.lbv.K.K.S#x#Eb#.v...Yba#..Z#T.4#Fbvbl#ubS#G.0#GbCbc#Pbc#P#P#G.w.w#P#Gbc.w.w.w.w#P.wb0.qbQ.K#r.S.S.S#G.1b4#P#H.1bc.1.1bca0.1#P.w.w.w#G#z#GbVbVbSbSbS#DbV#s.K#4.S.4.4",
"#EaC#i.gbT.4.4bAbAbAbSbAbA.4.ZaPa3.6#6#E#x.4bLbL.4bAbKbAbSbS#ubS#0#P#P.w.w.1.w.1#H.1a7bCbn#H#H#Hbybyby#z#z.8.4.4aM#xaZ#2.8.y#GbV#Gbc.w.1#G.w.1.wbcbC#G#G.1#G#GaybSbSbS.8bla5bA.8#z#z.KbZbRaT.ZaP",
".4#r.K#z#z#G#ubb.8.y.y.y#R.O#Z.tbMbM#5.ebA.R#D#Day.rayaybV#G.wby.1#G.w#G.w.wbV#u.TbObO.Z.Za6bD#ia6bTbDbD#iaP.s#t.K#s.wbya0#P.1bm#G#0#0.BbSayb2#0.1#G#u#GbVay.8.8blbSa5bSa5#za5bAar.Z.gbaa9baba.O",
"b2bS.8#N#T.Ja6bk.M.M.lbS#z#G#z.w#ubV#GbV.1#G#D.ra7bnaV#H#Hbnbn#D.l.4#2.E.6.6bT.T.X.X#u#D.1.1b4be.1#G#G#G.0#Gbcbc.1.1.w.1.w.1#D#G#D.0.0#D#GbVaybS#G.1.1#Dbn#DbnbV.SbA.KbVbK.4aZbD#F#ubVbSaybV.wbn",
"#D.0#Dbn.1#sbQ#s#za5#z.w#zbS.y#ubV.kbVbVbVbVbVbnaW.l.l.4#Narar.8bCbn#HaVbnaVbebea0.w.w.1.1a7#u#7.1#s#H.1.w#Ha0#b#G.w.w.w.1.w#G#G.0#G.1#0.w#0#0.wbS.ebS.e.l.4.JbG.y#u#D.w.w.w#sbQbV#s#0ay#ubV#D#D",
".0bn#Gbn#D.R.R.RbV#G#z#0bV#u#u.y.SaBbYaB#t.4bA.ea5#zb2bSbSbVbV.w.0.0a7#Hb4#Hbn#7a5#z#z.w.wa0a0#bbeaz#b#b#bbn#D.y.1#G#G#G#G#u#G#u.1.1#b.1aybl#Fa8bG#T.8.eby.Wb0bP#G#Gbm#Gbm#G#G#G#sbn.w#z#G#G#zbn",
"#z.w.w#zar.4#T.Jbv#F.ybSbV#ubSbVaY#s#s.Ka5.K#z.Kbl#u#D#G#D.rbd.ra5#0bS.BbVa5#ua8.ybla8#u#0#G#G#G.0#D#G.wbe#B#Ybe#P.w.w.w.1#0#G#G#G.1#P.w.w#0#0.w#baY#s.wbn.0#D#7ay.rbm.r#G#G#G#GbV#0#z#0#G#z.1.w",
".8ara5.Ka5.ear.e.w.w.wa0#bby.w#b#0#0bV#u#F#FbGbv.8.8ay#z#0#0#0#0#z#0a5aya5ayb2#0bV#GbV#D#u#u#D#Ga0a0bc.1bc#G#D#u#Day#D#GbV#G.w#s.w.w.w.w.w#z.w.waBbs.y#D#DbC.1bCbV#G#0.1#0#G#0#zbKbSbSbS#u#ubVbV",
"#Hb4bebeazbeaz#Y#ubV#u#z#u.y.8#F.w.w.w.w#0.w#0#z#G#ubl#F#u#u#u#Fbd#u#D.0#7#7#7#D#u#D#GbV#G.w#bbebc.1#G#G.1.w#P.w#b.wby#s.w.w#s.w#z#z.KbA.4#F#T#2ar.e.ebA.ebAbAbSbQ.w#s.w#z#zbK.4.y.8bSbS#0bSbVbn",
"bn.1a7bnbn#D###u.1#0bn.w#G#z#D#0#0bV.w.w.w#bbe#bb4b4#HbCa7#Dbd.ybs.R#D#u#u#F#7bs#u#u#u.ybA.S.4bLap#b.WbQ#z#s#z#z.8.4.8#2#2bG.MbT.4.SbA.S.4.S.K.Kararar.ea5.ebS.e.8.8.ybS#z#z#s.KbAbla5#0#0.w#s.w",
"#s#z#s#z#z#z#za5#D#D#GbV.wbV#z#0.Ka5bKbAau.R.S.R.lbAa5.e#r#NaAaAa6.ZaW#N#N.e.e.e.BbSa5.earbOa6#Ebi#EbDbDa6#t.4.4.ebA.SbA.e.K.K#zbL.T.KbL#t#TbL.Kbn.1.1.1.w#Hbeb4bV#z#z#G.w#z#z.K#za5#zby#0bVbV#z",
"#u#D#DbV#u#ua8#ubXau.y.y.ybs#DbsbK.SbL#RaIaI.C#3bw#t#R#R.S.S.S.y#t.gaPaP.gaT.Z.ObabaaP.Z.Z.Z.4.l#F#2#2#O.S.ebA.8.S#2aB.y#zbKbS.y#u#D.1.w.1bnbVbn#zbK.y.SbK#4.S#tbSbV#u.8.8#u.8#ubV.y.y.y#ubA#ubV",
".##q#qat.tas.2.2#A#A#AbH.H#C.H#CaMbI#x.GaZ.9bD.G.9bD.GbT#2#2aBaBbK.ybAbKbK.S.S.S#t.Z.Z.4bAbK#zbV#sbV.K.K.K#s.KbV.K.y.SbA.KbK.y.S.4.ybAbK.K.K.K.K.K.K.e.K#4.K#4bLa2#5.D#5a2aIaIa2aIbBbZbwbw.s.OaP",
"ba.O.Obaba#.#.#..A.A#v.Abkbkbk.A.y.8.SbA.e.S.S.4.K.e.e.e.e#z#z#0bS#ubV#zbV.y.ybS#4.SbY.S.y.yaBaB.4#t#t#t#t.S.S.S.e.4.4.S.K.KbL.S#hbF.TbR.gaPbWaP#Z#ZbaaS.p#kb5b5bNa9#..O.O.Oaq.ObaaP.O.O#Zba.Y.Y",
"#D#u#u#uaybSbS#u#s#s#z.w#s#s.1bnbQbQbQbQbQ.Q.K.T#t.4.Z#2#T.4.4.4bAbA.SbA.S.S.K.KbQ.K.K.K#5bLbL.SbO#R.T#5b.#5.K.kb.#5bLbZbZbR.Z.gaP#.aPbNbNbN.O.Hbwbwbwbw#3.O.O.O#2.4.8.8.8.8.ybAbA.e#z#s#z#s#z#s",
"#5.TbLbL.TbLbLbL#m#gae.CaX.Caeae.Z.4#tbLbLbZbR#tbObR#tbR.4.4.4#t.saP.U#E.YaP.U#..UbWbibWbNbNa9#..gbW.Z.sbwaP.G.9aP#E.U#E#EaPaP.U.Y#3bBaIbw.Cb.#w.ybSa5bVbSbV#z.w#z#z#z.K.K.e.ea5bAa5.ea5.ea5a5.e",
".U.Y.YaTaT.Z.O.gbRbRbwbw#tbB.s.ZbTbT.Z#t.4.4.4a6#t.Z#t#t#t#ta6bDaIbZbB.n#m.n#3#3#X#.aq.HbH#..H#m.TbRaIa2.DaI.T#4bwbRbwbwbZb.bob.#4b.buaK#R.s.9#t#3.O.O.Obw.sbw.sbwbwbwbw#tbwbRbB.Z.gaP.gaP.gaP.g",
"aB#FbSbVbV#D#ubVaya8bl.8aybS#u#u#zbVbV#zbV#zbK#u#u#u.y.8.ybA.ybA.4bY.4.4#t#tbDaZ#tbR.4#t.4#t#tbL.K#tbwaI#5aIbLbFaIaIbwbD.U#E.Ubi#EbDbD.ZbT#xbT#xabaRaR#oabat.O#Z.s#t.SbLaI#4aKb.b.b..Kbu.7.Qbub.",
".w#b#b#Y.w#0.1#G#z#G#z#G#b#b#b#s.1#G#G#G.1bc#G#G#G#Day#G#G#G#G#G.w#G#GbV.1#z.w#b.kbnbKbn#s#DbVbV.K#t#iaP.ZbW.g.Z.s.s.gaPaP.Zbw.Za6.Z.Z.8#r#z#ra5#D.r.r.r#Gbcbmbm#G.1.w.wbc.w#G#G#G#G#G#Ga0#P.1.r"
};

/* XPM */
static const char *button_xpm[] = {
/* width height num_colors chars_per_pixel */
"    96    96      254            2",
/* colors */
".. c #9c3218",
".# c #a4733e",
".a c #bc450a",
".b c #d4700c",
".c c #dc8c29",
".d c #bc5e00",
".e c #d46b37",
".f c #945431",
".g c #bc5a2c",
".h c #8c4e4b",
".i c #d47e16",
".j c #bc7422",
".k c #d47d3a",
".l c #d45e28",
".m c #ec9b3e",
".n c #bc6b43",
".o c #d45a13",
".p c #a45236",
".q c #dc8848",
".r c #e46b1b",
".s c #bc652f",
".t c #a46243",
".u c #bc6920",
".v c #a4391e",
".w c #e47b35",
".x c #9c6b30",
".y c #d46d24",
".z c #ec8a29",
".A c #bc452a",
".B c #e46833",
".C c #bc702e",
".D c #c47845",
".E c #b15314",
".F c #e47e10",
".G c #bc5a18",
".H c #bc6145",
".I c #a44d16",
".J c #cc5728",
".K c #d47439",
".L c #a45b39",
".M c #cc5815",
".N c #dc8f4c",
".O c #b46239",
".P c #bc5307",
".Q c #d4794f",
".R c #d47624",
".S c #cc6c2c",
".T c #cc6941",
".U c #ac5222",
".V c #e49328",
".W c #e4754d",
".X c #d4650b",
".Y c #ac592c",
".Z c #c05e2d",
".0 c #e4751a",
".1 c #e47d29",
".2 c #9c6143",
".3 c #e45f2b",
".4 c #cc632a",
".5 c #cc660d",
".6 c #b44b13",
".7 c #d48442",
".8 c #d66228",
".9 c #bc6221",
"#. c #b45736",
"## c #d47714",
"#a c #dc8936",
"#b c #e48237",
"#c c #cc530c",
"#d c #8c522b",
"#e c #dc8819",
"#f c #ec9129",
"#g c #bc7936",
"#h c #d46f50",
"#i c #bc521d",
"#j c #bc553b",
"#k c #9c523b",
"#l c #f49a45",
"#m c #bc7548",
"#n c #ec8643",
"#o c #a86d3a",
"#p c #a44d21",
"#q c #a4754b",
"#r c #d46547",
"#s c #dc7937",
"#t c #c4642d",
"#u c #dc6c21",
"#v c #bc4d2e",
"#w c #cc7e53",
"#x c #c45917",
"#y c #cc5c42",
"#z c #dc7036",
"#A c #ac5448",
"#B c #ec8f44",
"#C c #b45c4d",
"#D c #dc7622",
"#E c #b45222",
"#F c #d4651b",
"#G c #e47328",
"#H c #e58429",
"#I c #9c5f23",
"#J c #d47f2b",
"#K c #cc7116",
"#L c #eca24e",
"#M c #9c471c",
"#N c #d45b36",
"#O c #c46716",
"#P c #ec7836",
"#Q c #ac642d",
"#R c #c46f2e",
"#S c #c47551",
"#T c #cc5b2b",
"#U c #cc685f",
"#V c #bc4b3a",
"#W c #e49a4b",
"#X c #b44c35",
"#Y c #e48745",
"#Z c #ac613c",
"#0 c #e47234",
"#1 c #c46242",
"#2 c #cc5e1a",
"#3 c #b4683d",
"#4 c #cc7430",
"#5 c #cc7042",
"#6 c #bf4b0d",
"#7 c #dc6e13",
"#8 c #e48c21",
"#9 c #9c3445",
"a. c #8c432b",
"a# c #cc5e04",
"aa c #a43f33",
"ab c #b46d44",
"ac c #9c5e62",
"ad c #9c4833",
"ae c #b4742c",
"af c #a4522b",
"ag c #dc943c",
"ah c #b46000",
"ai c #c46309",
"aj c #a4441e",
"ak c #dc7f4c",
"al c #ac6e27",
"am c #ac4b4e",
"an c #ec9238",
"ao c #e48518",
"ap c #e47c4f",
"aq c #bc5c3e",
"ar c #d56238",
"as c #9c5840",
"at c #ab6946",
"au c #cc761f",
"av c #9c5024",
"aw c #bc4922",
"ax c #bc421d",
"ay c #e46927",
"az c #ec8836",
"aA c #cc513b",
"aB c #cc661d",
"aC c #b44a21",
"aD c #b4544c",
"aE c #ec8a55",
"aF c #9c5a20",
"aG c #94533f",
"aH c #c4701d",
"aI c #c46b42",
"aJ c #dc5a18",
"aK c #cc7b2f",
"aL c #e49046",
"aM c #c4520b",
"aN c #dc774c",
"aO c #ac4631",
"aP c #b45b28",
"aQ c #944e30",
"aR c #ac6e4d",
"aS c #a45f2a",
"aT c #b4612a",
"aU c #ec7032",
"aV c #dc872b",
"aW c #cc5939",
"aX c #b47844",
"aY c #dc843b",
"aZ c #c4601d",
"a0 c #ec7f36",
"a1 c #c47531",
"a2 c #c47344",
"a3 c #ac431d",
"a4 c #ac7439",
"a5 c #dc6735",
"a6 c #c4582a",
"a7 c #dc7c1b",
"a8 c #dc5d26",
"a9 c #ac5036",
"b. c #cc7742",
"b# c #ac4b13",
"ba c #ac5a37",
"bb c #dc5f0c",
"bc c #ec7a29",
"bd c #dc7813",
"be c #e48b37",
"bf c #f48e28",
"bg c #c44e1f",
"bh c #c44e3f",
"bi c #ac4b1e",
"bj c #dc6544",
"bk c #c44c2b",
"bl c #dc611a",
"bm c #ec7125",
"bn c #dc7d29",
"bo c #cc7752",
"bp c #c4473c",
"bq c #ec994b",
"br c #e49336",
"bs c #d46f16",
"bt c #bc600a",
"bu c #d47a46",
"bv c #d45b1e",
"bw c #bc653a",
"bx c #ac3c1d",
"by c #e47943",
"bz c #a46b2e",
"bA c #d46b2e",
"bB c #bc6c3a",
"bC c #e47f1b",
"bD c #bc5b22",
"bE c #bc6052",
"bF c #d47346",
"bG c #cc561f",
"bH c #b46044",
"bI c #bc5312",
"bJ c #d4775e",
"bK c #d4732e",
"bL c #cc6b37",
"bM c #cc644f",
"bN c #ac512d",
"bO c #cc6137",
"bP c #ec8552",
"bQ c #dc7944",
"bR c #c46339",
"bS c #dc6a2c",
"bT c #c45a21",
"bU c #dc6f44",
"bV c #dc732c",
"bW c #b4502c",
"bX c #cc6d1f",
"bY c #c46521",
"bZ c #c46939",
"b0 c #e48653",
"b1 c #ac6445",
"b2 c #e46e43",
"b3 c #c45851",
"b4 c #e48b2b",
"b5 c #9c5430",
"b6 c #944d49",
"b7 c #c46a51",
/* pixels */
".waB.U#5#Dba.##u#sbn#H.8#z.0#Db2.4#E.g.e#T#F#z#4bL.n#EbSbm.kauaz#Bbnbr#B.y#b#bb4.w.z#D.z#haKaZbr#Ha6bLaubn.w#Yb4.z#0#ba7an#s#Yb4b4.8.wbnaVaOb3aBbS.l.K.4bL.S#i#5#0#u.w.w#u.w.1#D#zaP#AbK.y#.#a#u",
"#b#F.Y.T#u.O#q#D#z.1b4ar.wbn.0bS#raC#..T.4.lbK#4aZ#Zbi#G#G#s.S.1bebnbr#BbA#b.1.1.w.z#Gan#5aK#tbr.1a6#1aua7bS.w#HbCa5#0#DazbK.w#8#H.8#0aVbXbibRbsbA.l.K.e.e.4#x.T#0.8.wbVbVbn#sbVbSaT#AbVbS.gag#G",
"#bbS.YbL#u.O#q#D#sa7bea5.w#G#D.8.K#ibW#1.4.8.e.SbD.p#pay#G.k.Sbcbebnbe#BbA#b.1bn.1bc#Gbe#1aHaZb4#D.Zb.aLan#0#Dbda7bS.ybCbe.y.w#8be#ubSaY.G#X#1.ybA.8#z.K.ebL.ZbL#0#u.w#GbV.w.1bnbA.u#C#z.y#.aL#G",
"#YbVaTbL#ubaatbV#zbnbe.K#zbnbn#N#z.g.UbwbO.4.S.4#R.L.UbSay.k#Jbc#abebrazbK#bbnbC#GbC#ub4#X.u.Z#HaY.eaI#Wbr.w.1#H#HbV.8b4anbS#s#H#b#GbVbe.6bw.4.ya5.y.ebS.e.e#t#t#G#u#zbVbV.w#s.w.e.u#CbKbS#.br#P",
".wbVaT.Tayba.t#u#zbnaza5ar#D.1#T#zbTaO#.bwbL.8#t#tas.Y#Gbl.K.k.1beanazbrbK.w.1.1.1bc#0be#j.C.4b4.ybO.g#Wana0aya7az.w#2az#B#z.w#HaY.wbVaNa3.s.4bA.e.8#F.8#z.ebLbD#0#u.w#GbV#b.1#s#z.s#AbAbV#jag#G",
"#0#D.ZbLbS#.as#u#z#Dbe.e.4.R#s.J#G.4a9.p#.bR.SaZaP.f#Z.w#u.K.R.1bebqbrbe#D#bbeb4#PbC#z#aaO.CbL.1bV.T.Ibr#8a0.w#Han#Y#2anan#z#0bC#s#H#DaraC.s.4.lbAbA.lblbS.e.K#i#ubV.w#s#GbQbV.wa5.CaD.ybV#.#a#G",
".1#u.ObLbS#..2a8#z##azar#T.RbQa6#u.4#.aQbNbR.S#T.UaQ#C#bblbK.kbCaV#l#fbebV#bbr.z#G.0bSaYaa.sbO#D.S.Q.U#Laz#n.w.1b4#B#2anbebS#zbC.KaV#Dbpb3bYbX.l.8bAbvblbS.e.k.g#u#G.w#GbVbVbS#s.e.C#CbKbV#X#a#G",
"#GbV.gbL#u#..2#ua5#u#Y.e.J.R#sbkbbbA.Oa.adbR.T#2#Z.f#3#bbl.KaYa0bn#L.Vbe.wbeanaz#P.0bS#aaabw.e.0aBaNaP#W#8a0#G.0#8aE#2an#HbS#0.1.S.1.1.A#U.S.Rar.4a5#FbSblbAbQ.ZblbV.w#0#DbV.ybV.8.CbE#zbVbW#a.1",
"#zaybR#m#s.A#AbX#D.1#u.wbvbV#z.M.8bA.4#E#k#Z.OaZ.hafbA#zbAbA#D#Hbnanbr#8aVb4#W#f.wbebVak#M.ObL.R.Ya2.Gbe.1aza7a7#Y.1#F#B.y.k#Db4.y#saY.P.ybX.K.4.8bS#zbS#u.8bA.SbDby#G.1#s.4.KbAbV.SatbVbl#Z#D#G",
"#Ga8bR#g#s.A#Aau#D#0bV.w#F#Ga5.M.ybA.8#v.p.L#ZaTb6afbAbVbA.KbV#8#s.m#fbr#H#H.m#f.1#bbV.k#p.ObR.y.Oa2aZ#n#baz#H#H.w#0#uaL#O.k#D#b#F.w#b#2#zbK.KaB.ybS#GbS#DbSbVbAbT.wbV#G#s.4#zbS.KbAat#z#u#obV#G",
"#zblbwae#z#v#A.y#Gbn#u.w.y#z#z.l.ybSbA.Zba#k.LbNas.UbK#0.8bKbVb4bnaL.mbrbe.canbr#H#bbA#4af.O.S.y.OaI#tbea0#b#H#b.y.w#G#b#x.KbV.w.y#s.w#F#s#zbVaBbS#ubS#GbSbSbK#z.4bQ.r.1bn.y#sbSbV.SaR#0#u.Obn.1",
"#G.8bw.C.w.AbH.ybV.w#za0bS#0.wbS.ybAbS.8#.afaQaQ.L.UbVbVbS.K#sb4#Dbranbrbebe.m#f.1a0bAbL.Y.O.T#F#.aT.4.w#b#H.w.w.8bS.w#Y#x.SbV.1bS#0#z.y#0#z.y.8#zbS#ubV#GbS#ubA#4.w.0.1#bbKbVbV.y.4b1bS#u.O#G.1",
"#bay#taX#sbk.H.y.w#G#u#bbVbV#z#z#RbAbS.ebRafaQ#d#kaP#s.wbA#zbn#H#sbeb4bebebeanb4.1#HbV#tba.YbL.y#X.U.S.wbc.1#GbV#zay#0by.y.SbV#PbS#zbS#u#z.wbl.y#GbS#u#G#GbV.ybK#z#b.0.1.wbnbV#DbA.Sb1#0bS#3#0.1",
"#bbSbB.C#sbk#CbsbV#z.yby#u#ubS#G.O.4#ubS.4bNaQaQ.pbD#G.wa5#s#s#H#abebe.zaY#bbr#8#D.1#z.Gba.U.TaB.Ob#bK.wbe#G#G#s.w#u#G#bbKbAbV#G.RbV#F#s.w.w#F#F.w#0#G#0#0aybSbSbQ.w#G#G.wbVbA#GbKbAab#0ay.n.1.w",
"#b#u.sae.1bk.H#D#z#D.8.wbS#u.y#z#Z.Z.lbSbA#.b5.fba.Z#s#GbS#z#sbe#bbrbebrbnbnan.V#D.1#z.G.nba#4bvbB.6#s.1az.0#G.w#Gay#P#GbKbK#b#G#z.waB.w.w.w#F#u#0.w.w#G#G#0bVbS.ebV#G#G.1#z.8bS#z.8b1#0bS.n#0#G",
"#s#u.Zaebn.A#Cbs#0#0#F#bbV.y#u.w.taPbvaya5.Zafas#Z#t#0#G#F.K#bbr.wbeanbrbnbK.man.1.w#s#i#S.ObuaBaI.EbQa7a0.0#G#0#D#Gaz#u.Rbnan.0bebQaB#s#sa0#F.wbS#G#G#G#G#G#zbA.ebl#G.0bV#z#F#0bK.8.tayay.H#D.r",
".1#zbT.ZbQ.yaMbK.K#0.w#0aY.SbV#ubMa3.K#Farbg#.aSbD.4#D#G#D.5#Y#b.qaV.V.m#z.e.m#fby#D#J#1.H.uaK.ZbRbIbe.1a0.w#D#D#Gbdb4b0.J.wa7ak#H#n#xb4#H#z#zbnay#G#u#G.1.1#G#u#s#Tbd#0b2#GbA.1.8#r#Ia5#sala5#D",
"#GbVbT.4bQ.8bI.Sa5bV.w#0#saB.kbVbM.6.Kbla5.J.Z#Q.sbK#G#G.1aB#Y#b#bb4.Vbr#F#z#B#8#0bdbK#j#.aP.S.g.TaZ#B#H.w#P.w#D#0.Fb4aNbv.1#DbV#Ha0.Mb4#H#za5#D#0#G#G.0.1.1.w#D#s#Ta7#0b2#D.8#H.y#r.fbA#zal#z.1",
"#GbV.Z#tbQ.S#xbLbK.w.wbV#sbYbV#G#5#6.SbA#zbv#taT.Z#z.w.1#zbX#Ybn.qb4.mb4aB#zbe#8#0bd.R#j#.bt#R.g#1aZbe.1#G.wbV#D#PbCbe.ear#D.1bX.1by.l.1.1a5a5#Dbm#G#G.1.1a0.w#G#s.la7.wa5#Dar#HbVbF#I.4a5ala5.1",
"#G#z#tbLbQbA.G#RbA.w.w#u.KaBbVbV.e#E#x.ybV.8.4.sbTa5.w#Gbn.4#Y.y#YaV.m#H#F#sbean#Gbn#s.gaDaT#R.g#t.4#b.0#G#G#G#D#0bCb4#x.e#G.1aB#G#0.8.1.1bS.B#G#G#G#G.1.1.1#G#u#z.e#H.w#z#D.8#H#z#haS.4#zal.4.1",
".1bV.4bLbQ.eaZaIau.w#0#Fa5#tbV.1bA#x#E.SbV#u#F.4bG#z#0#zbVbYakbX#YbnaL#b.ybV.1an#P#H#saqaq.u#4#j#1.S.1#u.1#0.1#G#0#Hbn#ibjbV#b#2bca5a5.1.0.l#z.0#G.1.1bcbc#b#D#u.war#8by#z#u.e#b.y.Tbz.4#za4.J#D",
"bc#z.4bZ.Q.S.9aI.R#b.w#F.K.4bV#G.R.4b#.T#u#D.y.8.8#GbcbVbK#R.qbKbebn.1#s#Dbs#Dbe.w#8aY#jaq.s.SaO.Z.S#D#7bm#G.w#u#0.zbn#xa5#G.1#2#bbSby.1#G.l#0.0.0bca0az#Ha0#G#u#0.B#8.w.K#D#r.1#FbO.x#T#zaX.J#D",
"#GbK.4bR.K.SbD.C.Sbe#0bG#zbAbV#D#DbL.v.T.y.0blarbS#G#G#D.KaH#Y#s#H.wbAbV#D#D#D#G.w.zaV#.aq.sbwax.gbA#D#7#G#u#G#u#uan##aW#NbV#D.4#bbvap#H#H.8#sa7.1.1bc#Ha0#H#0#D#0a5#8bQ#z.y.ebn.y.T.##x.KaXbkbV",
"#G#ua6#t.T.4.G#3.R#b#zbv.K.ebn.r#DbL..aI.4#7blar#G#Gay#u.KbY.N.cbnbe.ybVbn#G#b#u#b.zaYbW.H#R#tbx.Z.k.w.r#0ay.1#GaJaz.5bO#T.w#DbAbnbg#b#Hb4bVby.F.0bC.1.1.1#b#GbVaU.8#HbnbA.R#N.1#s#h.#bgbAa4#vbV",
"#G#u#tbO#t.K.9bw.lb4#G.8bla5aWa7ay.4.YaD.K#ublblay#G.1.y.K.Z#Y.iaY#T.R#Nbe#zbC.1#H#Bb..ZaPb.#3aFaPak#G.0.1#D#D#G#D#b#xbAbv#G#ubA.w.Mbn#nbVbS.1bdbcbm#P#G#Gbc.1#G#D.w#u.w.w#2bK#4bK.K#vbw.Q#tbt.K",
"#D#u.ZbR.4.ebD#tbAb4#u.8#u#z.lbn.rbAbabN#tbS#u#u.B#G#D#D.e.4#Ya7#b.4bnaW#H#zbC#GbcaL#4aTbW#4aTaS.UbQ#D#u#z#D#D#G#u#baBa5bS#G#u.K#b#F.1bebVbV#GbC#H.1#P.1.1#H#GbVbS#G#u.w#saBbA.SbAbF.gaqb..u.G.K",
"ay.y#t#t.Z.e.G#Ra5#Hblay#Db2.laVaybK#.#p.g.ybVbV#G.w#7#z.4.e#abeaY.ybn#T.1#zbC#D#G#b.S#t#x#5.Z.Y.U.kbSbl#GbA#u#G#u#b.4.e#z#G#FbAby.ybeaz#ubS.1bc.z.1#P.w.1bc#DaybV#G#F#G.w#2.S#t.R.e.g.OaI.9#x.K",
"#G.8#tbR#2.ebT#R.ebC#F#z#GbS.4#HaybA.Zajbi#tbVbV#0#G#F#saB#s.Rbe#bbAbn#Tbna5#GbCay.wbLbR.ZbL.Z.O#E.Kbl#ubVbKbSbVbl.w.4.8#0#ua#bVbQ#ube#b#u#G.1.1bf.0.w#Pa0#H.1#GbV#G#u.w#s.M.S#tbn.e#1.gbZ#R.9.K",
"#G.y#t.4#T.e#2.S#ra7#u#0#DbS#N#HbVbS#T.U#p.sbK#u#G#G.y#s.y#s.y#zaVbKbn.J.1a5bC.1#G#s.4bO.4bLbD.sbWbF.8ay#z#zbA#u#D#z.4.4#0#u.o#s.4bSbe#H#u#G.1.1.z#D#G.w#ba0.1#0#D.w#D.wbV#x.S.S#s.SbR.ObZ#5bYbO",
"#GbA#t.4.4#z#2.S#N#D#u#0.rbVarbn#GbS.4#vb5.O.Sbl#DbVa5.K#Dbn.ybVbn.Kbn.J#D#z#G.1.rbV.ZbR.Z#T#i.s.g.ebl#G#0.K#u.8#0bA.e#2.1#u.y#b#xbAbebn#D#Gbm.0beblbV.w.1bc.1#G#D.1#Ga0#s.M.S.Tbn.S.T#jbBbu.4.Z",
"#G.ya6.4.4#zaB.SaAbd#u#0bdbVarbn.w#u#F.g.pba#t#F.0#u#s.8bnb4.y.8aVbQ#Hbkbna5.1.w.1#z#tbL.4.Z.E#t.gbA#uay#sbS.K.y.w#2#z.4#0bl#D#Ybg#zbebC.0.w#G.1.1bvar#z#u.1.1#G#D.1bV#b#z#2bLbL#b.S#5#..g.k#t.Z",
"#GbAbD#t.4#0aB.yaA.y#F#0.r.w.8#DbybSbv#t#kas.s.X#D.y.Waibe#HbVa5aVbQb4bkbna5#G.1.w#s#tb.bR.4#ia2.g.y#F#u#GbKbV#ub2#c.K.4bV#7#DaYa6.kaza7#D#P.1bc#z#Tar.8#F.0.1.r#G.1#u#P#s#2bL.S#b.S#haP.U#5bY#T",
".w.4aI.sbAbSbK#ta6bsbd#za5.0bC.l.1#0bla6.Z#3aIbT#sbUaVara7.q#ebn#b#D#YaA#8#s#u.wbv.K.L#u#R.4#Z#F#T.e.8#z.e.l#sbs.w.P.e.w#G.r.r.1#T.wa7.z.1bea0.F.K#D.RbK.e#zbV#D.w.1#G#u.w#zaB.K#Y#ubOaC.gbobwaP",
"#GbYbZaPbA#u.y.g.Z.R#u#0#0.0bn.4#G#P#u#TaPba#t.G.ybQ.c.4#8#YbraYbn.R.wbp#ebn.8.1#F.K.L.rbL#t#Zbl#T.eaB#z#z.4#G#7.1#6.S.w#u#G.rbV.l.w.0be.1.wa0#8bV.R#J.K.4.8bV#G#G#G#G#G#b#saB.K.w.ybOaCaPb7.s.G",
"#G.4bB.U.SbVbAaPaW#D#Da5bSa7#H#2.w#PbSbA.ZaPbw#t.y#zbe.4br#sbq.c.w#D#s#Vao#z#u#G.l.KaS.rb..4afa5.4bS#Fa5#zbv#u#G#0#6bAbQ#u#G.w.8#z.wbd.z.1#b#H#HbS.y#HbQ#T#T#zbn#G#G.w#G.w.waB.K#s.8.T#v#.aIaPaT",
"bV.4.n#EbA#zbKaP#N#u.0ay.B#HaV.E#G.w#GbS#t.ZbZ.SbV#zbnbVbqai#WaL#b.1aYbp#e#zbS#G#F#z.L.rb..4afbS.lbS#F#u#z.8#u.1#0.M.8#z.o#0#baZa5.w#u.1#D#b#H.1bAbVaYbQ.8.J.y.w.w.w.1#0.w#s#2.SbVbA.K.gaPaIaP.Z",
".1#t#m.Y.SbVbK.g#N#u#7a5bVb4bn.6.w.w.0bS.S.saI#tbVbV#s#s#Y.daLaLbe.1bQbh#8#zbV#G.l.Kba.r.k#tbNay.l#u#F#ua5#F#u.1.w#2bAbS#F#z#Y.GbVa0#u#D#7az#b.y.ybe.1bVby.laB#b#P.1.w#G#GbVaB.S.y.e.K.g#..n.U.O",
"#z#t.naP.S.y.SaT.e#F#7aya5#HaV.6.w.1#G#G.ybD#tbk.4#JbQbn.Kbs#Bbebe#Hbnbp#8.ybSbSaJ.K.O.r#4.4#Z#u.8.8#ubS.8.lbVbn#z.e.ebSbbay#bbY#Ga0bS#D#Dbr#bbG#D#n.1#u#b.eaM#b.w#G#G#GbV#s.SbK.4.4#5aPaPbwb#.O",
".wbD#3.U.K.y.S.Z.e#7#7b2#ubnbebTbV.wbC.1#D.Z#tbT.ZbK#h.c.e#8#b#HaV.1bKbp#8.8#z#ubv#z.nbm#R.y.na8bS#FbV#zbG.ebn#D.4.KbKbV#7ay#baB#G.wbS.w#Hb4#s.4#Daz.1#D#nbV.M#H.w#G.w#G.w.wbK.e.lbA.KaPaPbwaf.O",
"#baZ#3#..KbS.S.O.ebs#D#0a8#7be.T#u.1bcbcbn.Z.S.TbLbY.TbrbUanbV#H#H#H.Rbp#8bA#zbSbl.K#mbm.4.ea2bl.ebG.wa5bg.S#s.y.G.k.KbVbm.0.w.Sbc.w.B#Bb4#H.y.e.1an#H.1a0bV.5aY.w.wa0.w.w#sbA.SbA.ebu.Z.O#m.Y.H",
".k#t#X.UbQ#4#tba.B#u#ubV.ya5a0.X.T#H#P#Ga7.y.n.u.sb..K#s#Hbe.i.k#D#YbT.e#0bl.waibA#RbQ#z#RbK.3.y#F#r.y#DaA#u.z#x#v#K#z.w#F#Y.g.R.w#HbCazbCbea#bnbean#H#0a0#G.y.1#G#PbV#b.X.1bV#t.y.KbL#R.9#5.s.9",
"bnbR#.bW.K.S.ZbabS#u#D#Gbl#z.w.XbO.1bcaUbC#J#1aH.s#R.k#ubean.RbK.1#s.G#z#0#F#saB.8.C#za5aHbAay.y.8#rbS#ubvbAb4bXbhaBbV#z#7.wbkaV#b.w#D.zbcbe.X#sbean#b#G#b#G.ybVbm.w#Daz#D.wbV.4.y#z.4#RaPaI.saP",
"bK.4aqbi.KbY.ZaPa5#u#GbVa8#z.w#ubOa7#P#Pb4aY.T#O#R.ZbQ#2#YanbVbKbe#zaMbQ#0.o#D.S.l.j.Kbv.ubV.B.R#F#rbS#u#TbAb4bAbR.X.y#z#ua5bg#a#b#H.0#H.1be.y#sbebe.1#G.w#G.ybVbm#G#D#Ya0.wbV#t.ybQ.4#t.ga2.Z.Z",
"bn#t.HbW.K.S.4.Z.e.ybV#D#u.w.1#D.ZbC#P.w.z#abFaB#4#tb0.Man#YbnbKbebV#2.w.w.o#ubX.8#R#z.l.u.K.BbK.l.e#u.8.l.R#sbAbObs#ubS#DbS#Tbe.wbV#D.w.w.1.y#b#Haz.1#G.w.w#u.ybm.1bVaza0#b#s#tbA#s#t#t.s#5.saP",
"#s.4bHbN#5.ybA.ZarbA#G#u#0.w.1.1.Zbn#G#0az#Y#z#D#sbAaE#xazbe.1#s.wbV.4.w#G#ubVaBa5aubQa5.ubAay#J.8#F.8.8#FbKbObY#rbnbV.J#D#zarbnbV#D#G#P#b#ubVaYbe#bbc#G.w.wbV#uay.w.w.1#G.w.wbD#T.K.4#t.O#5aPaP",
"#D#t#.bNbL.ybK.ZbO.S.w#u#Ga0a7.1a6#H.w#Gb4bebQ.1.w.w#Y.ybe#H#b#b#G#zbV#s#G#G.1#2#zau#0a5.jbA.B.Kar.y.8.8#D.K.gbtar.1bVbGbnbS#z.1#D#u.w.w#b#Fbn#saz#b.1#G.w.w.w.y#u#P#b.0.1.1#YaP.M.K.Z.Z.ZaI#EaP",
"bV#t.Ha9bLaB#z.4a6.4#b#D#Ga0#ub4bD#H.wbSao#bby.z#HbebV#Daz#Hb4#b.w#ubV.1.r#G.w.4#zbY.ea5a1bA.8bKarbsa5.8a7.K#V.Z#N.1bVbG#b.8a5#8.1#G.w.w#n.5.waYazbc#P.1#P.w#P#F#G.waz#Dbc#Gbeb#bGbU#t.saPb7.gbZ",
"bVbL#m#..SaBbV.l#EbLbe#G#G#b#7be#i#H#PbS.1.w.waz.1#n.X#ban#8b4#Ha0.ybK.way.r.wbKbSbt#2a5aK.Ka8bKarbd#z#ra7#s#X#R.l#7bV.lbe.Ma5azbe.1.1.w#n.X#baVaz#H.1#P#0#P.w#F.w#0.w.0az#GbQb#.4bQbL.Z.Z#5bwbo",
".K.K.T.gbO.4#s#Fbiapbca0.0be.1.1a6by#G#G#bb4be.zaY.R.y.1az#b#s#b.za5.8#H#2.1#Dbv.K.6bQ.K#F.Kbn.SblbV.k.4bQ.4.MbX#4#Har#D#s.4###bby.1anbebe#Fbe#baz.w.w.1bV.w.wbvaz#D#G#G#G#s.K.UbO.y.e#O#C.D.U.i",
"#t#tbRbW#R#tbV#2#E#b.1a0#Daz#s#GbTbybc#G.1#bbr#f.q#D.y#baz#H#DbV.za5#F#b.Jbna7ar#4#6.K.4.SbV.y#FbS#z.KbYbybAaBbKbLbn.8#G#s.Z##.w.w.1azbe.1.ybe.waza0#b.1bV#b.w.o#b#D#G#G#G#zbA#EbO.R#r#OaDbB.U.k",
"#ibwaI.Z.T#t.K#2bD.W#Gbc#G#b#H#GbDby.way.1#ban.zbe.y.y#b#n.w.y#D#Har#u.1#2bnbd.ebOa6.K#x.4bA.4.ya5bV.KaZbQa5.y#s.Sa7arbV#s#x.5.wbV#bb4an#u#saY#sbe.1#bbe.1#n#b.M.wbV#G#GbSbV.e.9.4.y.K.5#AbB.U#J",
"aPaIa2.s#5#t.K#ObDbQ#G.1.w#b.1#GbD#z.w.rbVbebr.zbQ.y.y#b#nbV#ubVaV.l#z#G#2#D#DbF.4bL.Kbg.Ka5.4.8#0.ybK.G#z#zaB.k.4#Da8.1bnbk.b#bbV.wbebr.y#Y#s#JbV#sazaz.1#b.1#2.w.w#G#G#GbV.K.S.S.y.KaHam#3aO.k",
".Z#5.Dbwb.#t.K.Sa6#z.1bcbe#b.w.0#i#z.w#Daybeazb4#s.8bV#n.w#GbV.w#H#T.w#D.l#Dbs.T#T#z#z#x#z#z.4.8bSaB.K.G.e#zaB.R.4#Dar.w.wa6.R#b#z.1bebeaB.NbA.S.SbVbebe#G.1.1#2#G.w#0bVbVbVbV.ebLaB.e#KambwbW#J",
"bWaIaIaP#5.S#s.e#t#s.w#G#Bbn#H#GaP.8.w#GbVbe#b.z#s#D.wa0.1#G.1beaY.Jby#7a5bV.5#1aBak#sbgbQ#z.8bA.BaBbQaZ#z#z#2.S.4#Da8.1#z#Ta7a0#s.1bebnbXaNbRaZ.4.S.w.1#G.1.w#2a5#0.Bbl#ubS.ybVbO#O.ebYambwbWbK",
".gbL.T.G.K.S.KbA.4#z#P#D#Y#Da0bc.s.4#P.w#Gbe.1a0#sbn#ba0.1.0#b.wbn#vby#7#z#z.5#jaB#b#z.M#z#z.8#FbS#2aYaZ.e#zaZ.R.4#Da5#GbVbO.1by.w#Dbr.R.S.QbZbD#1.S#z#G#u.w.waBbl#0bS.8bVbVblbSaq#x.T.Sam.CbWbn",
".ZbF#4.9.k.SbV.8.4#z.w#ube.y#bbc#t.4.w#P.w#b.w.zbn#D.1a0.1.1#H.1aVawby#F.w.w#O.g#Fak#DaMbV.ybA.l#u#2akaZbA#z#2bAbL.0ar#GbVbObn.w#Y#D#BbX.k.Qa2.sbM#tbA#u#G#nbybG#u#0a5bl#0bV.y#G#.bT#r#4#X.OaPbn",
".saIbwaPb..e.K.S.e.8#b#D#P.1#G.1.KaMb0#Da0bman#Jar#Y#8a0.w.w.1bC.ea7#GbS#b#T.Qahb4#D.y#2bS#zbl.ybV#Mbu#tbl#w.yblay#0.R#Hbk#D#H.1#bbV.V.4b4.TaubRbZ#t#t#z.1.1#b.9ar.w#ubv#zbdbs.K.O#t.KbD#3#ob##b",
".saIbR#E#5.4.y#2bA.4.way.w#G.w.1#s#x.q.y.w.0#nbn.l.w.1.1.wbV.1bCbL#H#G.8.1#x.Q#O#b#D#F.8bS#z.y.y#uav.K.Sbl#m.y#F#D#zbV#8bp.RaV#Hbeak.cbQ.c.T.S#tbR.s#tbK#G.1.w#OaW#b#ua8#0#ubs.K.Y.4#z.G#Zabb##s",
".gbwbw.UbL.4.SaB.S.8by#D.w#G.w.w.waZbQ.8#G#ube#J.l.waz.0.1#u#bbna6b4#z.l#u.M.K##az#D#FbVbSbS.y.8#uaS.SbLay#3.R.o#ubV#z#8bpbn#HazaYaL#Db0b4bu.R.S.Z.Z.Z.K#G.1#baB#i#b#D.8#0bdbs#rafbL.K#x.Oab.EbV",
"aPbDbw#EbZ.SbA.ybA#2#s#G.w#G.w.1by#2.K.4#z#G.wbK#ubnaz.X#P#Fbe#Da6bebV.l#GbG#Nbn#b.y#F#s.y.8bK.8bl#Z.4bF.0ba.K.oaybVbV#8bp#s#Hbe#JaL#OaLaY.w#s#z.Z.s.Z.4#u#G.w.y#iaV.1.Ba5.r#D.l#pbL#zaZaP.n#tbV",
"aP.UbZ#EbZ.K.K#z.e#2.wbV.1#G.1.wa0.8#r.4#0.w#z.y.1.waz#7a0#7#Y#2a6#b#u.8bnbl.Jbn#P#u#F.wbSaBbS.4#u.O.4b.ay.pbQ#F.1#ubAaobh#bbnbe#saLai#BbA#s#z#u.Zbw.ZbObS#G#b#D#iaV.1#z#0#D#u#y#pbL#saZaPaI.K#G",
".Z#Eb.aPbR.KbKbK.KbG.w#G#0#u.w.1#P.y.S.e#z.w.ybA#H.wa0#u#b#D#bbgbO.1#Fa5bna5bg#D#z#u#F#s#D#2.e.4bl.O.4#5.r.p.Kbv#H#F.ya7bhbe#D.1#Ybq.SaY#Tbn.ybs#taI.g.Z.8#D.w.1a6bnbn.B#0#D#D#T.I.4bV#2aP.C.K#G",
"bw.UboaP.ZbL.ybS.K.M#s.w#G#G#G#D.1#G.S.e.K#0#FbKbCaza0.1.1.1#s#ia5.0#F#s#Da5aw#bbl#0.obVbV.M.e.4bl.O.SbOaJ.LbQ.ya0#F#D#8bhbe#D#sbe#B#sa7.4.1.e#F#taI#.#j.l#u.1.1.4.1.0a5b2#D#u.Z.UbLbS.SaP#t#z.r",
".Zbib..U.g.S.S.y#zbT.w#s#G#u#G#GbmbV.S.e.ybVaB#s.Fa0.wa0.0b4#z#ib2.0.oby#D.eaxaY.o#0aB#ubV#2.8.4blaP.e.Z.o.Lbubl.wbl#s#8bhbe.y#b.1.V.W.b#rbe#z.RbYaI#.#v#Tbl.1.1.e#G#7#0#0#D.R.Z.U.S#zbV.s#R#s.r",
"a6#E#4.YaP#h.4#ubL.4#z.w#G.1.0#D#G#G#G#u.8bG.8#zbC.1a0#zbV#b#z.J.w#GbbbVbAaB#O.1#F.w.8bSay.o#FaP#5a6.4#tbR.Z#zbV.1bdbS#DaAbVbQ#e#BaBaEbA.4#sbs#Dbl#tb1#A.Zbl#u.wbV.y#zay.0.1.y#2aT.4bVbVaZ.9#say",
".ZbDb.#3#.bF.y#D.T.S#z.w.1.1#G.0#0bc.1.1bVbA.y#b.1.1.w#D#Gbe#z.l#b#u#u#GbA.S.y#D#D#s.y#zay#F.KbtbZ#i.8.Z.saZbA#u.wbCa5#DaA.RbQbn#B.X#Y.4.KbV#u#D.o#tba#k.g#2#u#sbn.y#0#G.rbC#DaB.Z.S#u#sbY#t#s.r",
".ZbDbubBaP.TbA.1.KbA.K.w#P#b.1.0#0.wb4#P.wbVbnazbC#H#0#u.1be#DbA.wblay#0.4.S#z#D#0bV.8.1ay#u#saP.g#i.4.Z#tbDbK#7.1bCa5bnaW.R#zbn#BaB#Y#x.KbVbn.0#u.4#.a9#i.4#u.1bQ#FbS#G.0.1#D.S.O.4#u.w#tbYbQ.0",
".8.ZaKaIbNbRbK.wbL.SbA.w.w.1#0#D.B.1#P.1.1bV#H.z.1#b#G#F.1be#7#s#zbv#0.w.4bT#sbS#G#u.y#zblbl#saPaP.Z.e#tbR#t#s#G.w.1bV.1aW.y.Kbnbr.y#YaM#s.y.1#GbSbA.Z.YbW.4bV.w#b#FbS#z.0.1bV.y.O#TbVbV#t#t#s#G",
"#rbT#RbwbN.g.K.1#t.4.4.w.way.w#GbS#G#Hbc.1.1ao.z.1#PbV#uazazbs#bbU#c#0#0.8.6#z#u#G#F#u#Gbb#F.k#E#.bRbF.Z#t#R#b.1#GbC#zbn#N.R.eaV#sbKaYaZ#s.y.1#G#G.l.ZbW.U.gbA#G.w#2bS#G#u.1bVbSaq.Zbl#z#tbY#s.0",
"#z#x.s.CbNaP.Kbn#T.S#F#z#0bl#0bVay.w.1.1.1.1bc.z.1.w#z#u#bb4#u#b#s#c.w#zbA.a#z#D#G#FbV#Gbl#u.K.YbaaI.K#i.s.Sbe.z#s#GbSbC#r#D.KaV.RbQ.k.y#s.y.1#Gaybl.l.ZbN.ZbK#G.w.oa5#z#u.1#s#u.Oa6#FbSbY.Zbn#G",
"#rbT.9b..ObW.KbVbL.K#T.w#0#F#0ayb2.1bc.1bc.wbcao.1#G#zbV.w.1.ybQ#s#2.w#F#z#2#b#7aUbl#0.1#u#GbLaPbN.Hb.aC.saK#Y.z#0.1bV.1#r#D.eaYbAaLaBbK#Dbn#G#G#0#ubSbLa9#Z#z#G#Gbv#z#z#F#D#0.8.H.Z.8bA#tbY#s.1",
"a5#x#t#w.HaP.Kbn.K.K#2.w.wa8.wbS#0.w.1.1.1#Pbcbc.1bV#0bV#sbV.lbQ#z#u.wa##zbK#B#7#0#u#D#G#G.wbObN.p.n#h.E#taKbe.z.w.1bSbCbFbV.ebn.KaL#x.k.y#b#D.0#ubl#u.4#pbN.S.rbV#F#z#z.o.1.w#F.H.J.la5bY.s#sbc",
"#Dab#3.ybw#Z.K#zbnararaB#bbGbS#G.1bc.1.0bc.1.1.0ay.w#F#n#sbeai#JbA#D#b.4.e.1.z.o.B.w#u.1#DbQbLaPb#.Z.g.ZbDaka0.w#GbV#G#bbsbea7bnbK.q#4bA#G#G.0#Dar.3.y.R.U#9.Tbd#uay#r#z.MbVbe#Kb1bD#2.e#t#tbn.r",
".raR.ObSbw#Z.KbK.1ar.ebsaY#T.e.1#GbCbc#Hbc#H.1.1bV#0#F#nbVbe.5bV.lbd#b#N.8bnaz#u#u#0.r.1#ubK#t.Z#EaIbR#1aZapbe.1.1#u#D.w.ybebnb4bn.q.S.4ay#G#D.Rbla5#u.RaP#9.Tbd.r#z.ebU.M#Gbeaub1.g.4.K#t#t#s.0",
".raR.Oa5bwba.e.y.1ar.e.y#s.8bS.1#u#Ga0a0#Ha0.1#GbVbV#F#bbV.w#FbVbv#D#sbO#T.1az#0#u#G#G.1#ubK.Z.s#EaI#t.ga6#Y#b#G.1#DbV#DbK#BaVbeaVaY.S.4bV#G#D.y.la5#u.i.9aabOa7.r#G.e#z.M#0#b.y#Z.Z.8bQbL#t.w.0",
".r#o.ObVbwaS.K.S.1.ebA#D.w.e.e#D#G#G.1#Ha0bc.1.0.w#u#F#P#u#z#ubS#T.1bnar.Jbn.1.w#u#G.0.1#Dbn.9bw#E.Taq.gbT#bbn#uan#G#b#Dbnbqa7be.w#a.4#F.w#G.RaBaB.ebSbn.S#X.Zbd#GbV.4#z#F#0#b.S#Z.gbAbQbZ#R#sbc",
"#GabbwbS#3.p#4bK.wa5.e#Dbnby.lbnbV.1#Pbc.1.1#G#G#s#u#FbybV#u#0#G#T.w#D#r#x.1#Gby#G.1#G.1.1bQ.Gbw.Z#5.Za6.Zak.w#D#B#H#b.y#baLbn#a#b#baB.8.w#0bAbD#t.4bS#D.y.g#vbn#GbV.4#z#u#GbQ.y.L.ZbAbU.S.s.w.0",
"bcat.sbV.O#k.K#4#H.ebAbC.0.W.4#Day#G.w.1.0#D#G#u.w#u#u#bbV#F.w#u.l#H.X#r.lbebCa0#G#G#G.1.1#Y.G.C.gaIbW#i.g#s#D.0azbe.1.5#YbeaYbe.w.wbX.y.wbn.4bD.ubh#N#ubV.Zbgbn#G#z#2bQbV.w.w.y#Z.g.l#sbRbY#s.0",
"bm.Obw#z.Ob5#4.SbebSbA.1#Db0.Jbn.8#G.w.1#Gay#G#G#s#u#u#Y.1aBbe.R.ybe.5#z.Kan.0a0#0.1#Gbc#baLbI.C.gbR#EbWbT#z.y#Gb4anbnbsaLbn#a#a#H#b.ybA.w#zbOaPaT#V.l#FbVbOa3#s#0.e#2by#G.1bn.Rat.Z.4#z#t.s#s.0",
"bm#Z.s.w.Ob5bL#tb4.ebSbC#7bPbGbV.8ay.w.w#G#D#0#G#0#ubV#n#saibe.R#0an.b#z#z#lbd#0.1#Gbc.1#H#Y.EbZaIb..gbR.Sak#G#nb4.m#b.ybq.RaLbea0#b.y.y.wbS.4.g.O#XaA#F#DaraxbQa5.ebTbQ.1a0#G.y#3.Zbv.K#t#tbn.r",
"#G.sbw#z#2bNa2bSbV.8bQbVay#G.y.SblbS#Gay#G#0#G#ubybvbe#b#z.4.q.S#8#b#za8#Daz#7.w.w.r.1.1#H#s.GbBaBb.aP.CbAbn.1b4ananan###Bbn.mbnb4#b.ybv#GbnaP#ZadbN#jbSay.MbD.n.1#z.4#z#bbCbV#zbwaPa6#5bZbD.y.1",
".1#tbw#z.4a9#5bV#z.8.w#G.r#G#ubAbSbS#z#0#G.1#0bS#z.o#bbn.y#2akaB.1.w#0.y#0az#Dbn.w#G#G.1#baY.9.C#2bL.Y.s.S#DbC#Hazbeana7brbn#Wbnan#b.K#u.w#bbDb1#k#k.g.Saybv#xbw.w#z.4bK#P#G#G#z.s.g.g.KbR.ZbV.1",
".w.Sbw#z.8#..D#u#z.y#s#0bmbm#D.Ka5bS#G.w#GbS#G#0a5#F.1#DaB.4bQ#2#D.w#zbS.wbe#u#0.wbV#G.1#b.KaP.Z.ZaIbN#..S#u.1.1b4anbe#Hbebebrbnbe.w#z#u.wbn#E.LaG#ka9.4#zblaZ.sbV#z.4#z.w.0#D#s.H#i#x#5bZ.Z#s.1",
".wbLbw.K.8.O#5.8#GbS.w.1.r#G.wbVbS.8bV#0#G#ubVbV#u.yaY#D#2.ebQ#2.1bVa5.8.w.1bSbS.w#G#G#G#GbA.g#.bLbRba.O.K#D.1.1b4anb4brbebrbrbn#Hbn.KbS.w#Db#.fb6aG#kaq#za5.8.Z#zbV.S#s.way#GbnbBaP.g.TbR#t#s.1",
"bcaI#t.K.8.Oa2.8.w#z#z#0#Gbm.wbKa5blbVbV#G#u#ua5.y#D.wbVbGbQ#baB.wbSbA.4#b.RbVbA#0bV#G.wbVbY.Z.O.TbR#.aPbQ.ya0#b.z#Bb4anbe#B#Y.ibe#sbV#s#b.Rafb6#k#kadaP.e#zbA.4bS#s.R#s.wbS#D.1b7#i#x#4bR.9bV#G",
".w#4bw.e.8.OaI#u#z#z#z#G#G#G.w.4#za5bS#GbVbVbVbS.4bKbV.K.MbQaY#FazbVbAaB.q#F#GbS#G.1#Haz#saBbZ.H.e.gbabN.q#7#b.zan.manbebrbrbrbn.1#D#zbV.1.R.I.ha9.L#kbN.4#zbA.8ar#s.Rbn#0.B#GbnaI#E#i#5.s.Z#s#D",
"#GaKbR.e.yaqaI.8#z#sbK#0#G#G#saZa5bAbSbVbV#zbV#u.l#z.ybV#x.w#bbdazbV.K.Sbr.5.w#z.1bcbcaz#baBbZ.O.ebWbabi.qbs.zb4ananan.1#Bbe#Wbn.1.y.y#DbnaB#M.h.g.Oa9bibTbAbA.8.J#sbn.Raya5bVa7aI#E#i.KbR#t#s.0",
"#Gb.bBa5bA.Oa2#u.K.K.4#z#G#GbQbDbA.8bS.y#ubVbVaB#r.KbA#zbg#Y#b#Ha0bV#sbKaLa#be#0.1#H.1#B.1bY#taP.KaPaP.U#Y#7.z.zananan.ibqaV.mbn#b#DbV#z.1bXafac.ZaI#..I#i.lbA.8.J#s.i.ya5a5#DbdaIaC#ib.bR.4bQ#D",
"#Gb..ZbAbAbaaIbV#zbA.ybKbV#sbV#Far#z#Dblblar.8aB.y#zbR.KbG.w.1.z.wbV#T.can.Sbr#8b4.w#nb4#L#.bJ#R#z.g#3a9bq#F.z#H#f.mbe#sbe#D#L##bC#s.ybl#P#3.2.I#tbL.g#..paP.e.obTbQ#s#2.ybV.y#FbA.O.L.4.4bB#a.0",
"#Gb..ga5.eaPbB.ya5bl.8bS#0bn#s#u.Z#zbV#Fa8.8bA.y.8#4bR#1.8#G.1.1#PbVaAb4br.e.V#8an.waz#8#WbiaIbX.k#v.uajaL#Fbc.1#fbeanbnaLa7#La7#8#sbK.r.w.O.x.Y#t.e.gbWadbN#4bl#xbQ.K#2#ubVbV#D.lba.LbZaBbwak.0",
"#G.KaP.e#z.ObZ.y#za5bSbS#z.w#0bV.g.K#s#ua8.lbl.y#F.4.Z#i#z#G.0.w.w#DbOan.V.ebeanbr.w#bbCaLbi#..Sby.g.saObe#u#H.1#8be#B#Dbebr#L#8bc#sbKay.w.Y.LaT.4.K#taP#pbibA#u#2#s#zaB.ybV#sbV.4bababLaB.s.7.0",
"#Gbu.ga5#s.Obw.yby#0bSbS#0#zaybSbabZ.K#zbl.8bA#u.8.Saq.6#YbV#Ga0be.1bOanbrbU#8.zaza0.w#H#WaP#EbK#b.Z#R#XaV#0.z.1#b.1#B.R#Yan.m#8#H#JbK#G#0af.L.u.4.ebO.gbN.U#t#z.ybQbV.8.y.wbVbVaBba#Z.T.4.s.kbc",
"a0.7aP.e#z#Zbw#u#0#0#0#u#G#G#uaya9bR#4bVbSa5bS#F.K.T.Z.6b0ay#D#bbebV#T.m#8bU#D.1#8#0.1bebqaIbW#J#b#x#R#v#D#0bC#H#HbV#Bbs#B.mbe#ea0bK.K#G#0.I#Z#t#tbA.ebO#..Ua6bV#F.w#sbVbV#z#sbVbA.O#Z.ebYaT.7bc",
"#P.Q.ga5#sba.sbAbV.wbS#u#z#GbVbVbaaT.SbKa5a5bS#F.ebL#EbD#b#u#u#Y#H.1#Tbebd.W#7bd.1bS#0beaL.T#Ebn#Y.g.S#y#u#0aobe.w.1azbs#Bbrb4a7a0au.K#Pay.I.O.Z.4.y.ebLbR#..P#z.8bV#0bVbn.w#s#sbAbH#ZbL.4.9.kbc",
".1buaPa5#z.Y.O#ubV#sbVbV.1#z#D.wba.Z.4bA.8.e.KbA.4#t.UbL#s#zbbbe#b#b#ran.b.W#7.1#8#G#0#HbKb7.gaV#BbT.K#r#Dby#H.m.1.1be#u#B.1.wbe#P.S#z.wbSbi.n.ZbK.4.e.8aI.Z.6.K#u#GbV#0bV#s.w.w.e#Z#Z.K.4aT.k.1",
".rb..g.e#s.YaPbV#z.wbnbV.wbn#Dbn.OaP.4.y.4#N.K.K#T#t.U.Q#z.w#F#YazanaNan.bap#Ga0az#0#P#b#KbR.Z#aaz#ibK#h#u.wbC#B#b.1bebs#B#D#baLbcbA.k#P#G#E#S#2.K.8bAbL.Tbw.6.K#G#0.wbVbVbV#s#s.e.Oba.K.4aT.k.0"
};

static void drawroundrect( QPainter *p, QCOORD x, QCOORD y,
                           QCOORD w, QCOORD h, QCOORD d );

static inline int buttonthickness( int d );

static QRegion roundRectRegion( const QRect& g, int r );

static void get_combo_parameters( const QRect &r,
                                  int &ew, int &awh, int &ax,
                                  int &ay, int &sh, int &dh,
                                  int &sy );

static int get_combo_extra_width( int h, int *return_awh = 0 );

enum { PointUp, PointDown, PointLeft, PointRight };

NorwegianWoodStyle::NorwegianWoodStyle() : QWindowsStyle()
{
}

/*!
  Reimplementation from QStyle
 */
void NorwegianWoodStyle::polish( QApplication *app)
{

    oldPalette = app->palette();

    // we simply create a nice QColorGroup with a couple of fancy wood
    // pixmaps here and apply to it all widgets

    QImage img(button_xpm);
    QImage orig = img;
    orig.detach();
    QPixmap button;
    button.convertFromImage(img);

    int i;
    for (i=0; i<img.numColors(); i++) {
        QRgb rgb = img.color(i);
        QColor c(rgb);
        rgb = c.dark(120).rgb();
        img.setColor(i,rgb);
    }
    QPixmap mid;
    mid.convertFromImage(img);

    img = orig;
    img.detach();
    for (i=0; i<img.numColors(); i++) {
        QRgb rgb = img.color(i);
        QColor c(rgb);
        rgb = c.light().rgb();
        img.setColor(i,rgb);
    }
    QPixmap light;
    light.convertFromImage(img);

    img = orig;
    img.detach();
    for (i=0; i<img.numColors(); i++) {
        QRgb rgb = img.color(i);
        QColor c(rgb);
        rgb = c.dark(180).rgb();
        img.setColor(i,rgb);
    }
    QPixmap dark;
    dark.convertFromImage(img);

    QImage bgimage(polish_xpm);
    QPixmap background;
    background.convertFromImage(bgimage);

    img = bgimage;
    img.detach();
    for (i=0; i<img.numColors(); i++) {
        QRgb rgb = img.color(i);
        QColor c(rgb);
        rgb = c.dark(180).rgb();
        img.setColor(i,rgb);
    }
    sunkenDark = new QPixmap;
    sunkenDark->convertFromImage(img);

    img = bgimage;
    img.detach();
    for (i=0; i<img.numColors(); i++) {
        QRgb rgb = img.color(i);
        QColor c(rgb);
        rgb = c.light(130).rgb();
        img.setColor(i,rgb);
    }
    sunkenLight= new QPixmap;
    sunkenLight->convertFromImage(img);

    QPalette op(QColor(212,140,95));
    // QPalette op(white);
    QColorGroup active (op.active().foreground(),
                     QBrush(op.active().button(),button),
                     QBrush(op.active().light(), light),
                     QBrush(op.active().dark(), dark),
                     QBrush(op.active().mid(), mid),
                     op.active().text(),
                     Qt::white,
                     QColor(236,182,120),
                     QBrush(op.active().background(), background)
                     );
    QColorGroup disabled (op.disabled().foreground(),
                     QBrush(op.disabled().button(),button),
                     QBrush(op.disabled().light(), light),
                     op.disabled().dark(),
                     QBrush(op.disabled().mid(), mid),
                     op.disabled().text(),
                     Qt::white,
                     QColor(236,182,120),
                     QBrush(op.disabled().background(), background)
                     );

   app->setPalette(QPalette(active, disabled, active), TRUE );

}

void NorwegianWoodStyle::unPolish( QApplication *app)
{
    app->setPalette(oldPalette, TRUE);
}

/*!
  Reimplementation from QStyle
 */
void NorwegianWoodStyle::polish( QWidget* w)
{

    // the polish function sets some widgets to transparent mode and
    // some to translate background mode in order to get the full
    // benefit from the nice pixmaps in the color group.

    if ( !w->isTopLevel() ) {
        if ( w->inherits("QPushButton")
             || w->inherits("QToolButton")
             || w->inherits("QComboBox") ) {
            w->setAutoMask( TRUE );
            return;
        }
        if ( w->backgroundPixmap() )
            w->setBackgroundOrigin( QWidget::WindowOrigin );
    }
}

void NorwegianWoodStyle::unPolish( QWidget* w)
{
    // the polish function sets some widgets to transparent mode and
    // some to translate background mode in order to get the full
    // benefit from the nice pixmaps in the color group.
    if ( !w->isTopLevel() ) {
        if ( w->inherits("QPushButton")
             || w->inherits("QToolButton")
             || w->inherits("QComboBox") ) {
            w->setAutoMask( FALSE );
            return;
        }
        if ( w->backgroundPixmap() )
            w->setBackgroundOrigin( QWidget::WidgetOrigin );
    }
}

void NorwegianWoodStyle::drawPrimitive( PrimitiveElement pe,
                                        QPainter *p,
                                        const QRect &r,
                                        const QColorGroup &cg,
                                        SFlags flags, const QStyleOption& opt ) const
{
    int x, y, w, h;
    r.rect( &x, &y, &w, &h );
    switch ( pe ) {
    case PE_ButtonCommand:
        {
            int d = QMIN( w, h ) / 2;
            int b = buttonthickness( d );

            QRegion internR = roundRectRegion( QRect(x + b, y + b,
                                                       w - 2 * b,
                                                       h - 2 * b), d - b );
            QPen oldPen = p->pen();

            QBrush brush( flags & Style_Sunken ? cg.brush(QColorGroup::Mid) :
                          cg.brush(QColorGroup::Button) );
            p->setClipRegion( internR );
            p->fillRect( r, brush );

            int e = QMIN( w, h ) / 2;
            QPoint p2( x + w - 1 - e, y + e );
            QPoint p3( x + e, y + h - 1 - e );

            QPointArray a;
            a.setPoints( 5, x,y, x+w-1, y, p2.x(), p2.y(), p3.x(), p3.y(),
                         x, y + h - 1 );
            p->setClipRegion( QRegion(a) - internR );

            p->fillRect( r, (flags & Style_Sunken ? QBrush( cg.dark(), *sunkenDark)
                                             : cg.brush(QColorGroup::Light)) );

            // A little inversion is needed the buttons
            // ( but not flat)
            if ( flags & Style_Raised || flags & Style_Sunken ) {
                a.setPoint( 0, x + w - 1, y + w - 1 );
                p->setClipRegion( QRegion( a ) - internR );

                p->fillRect( r, (flags & Style_Sunken ? QBrush( cg.light(), *sunkenLight) : cg.brush( QColorGroup::Dark ) ) );
            }
            p->setClipRegion( internR );
            p->setClipping( FALSE );
            p->setPen( cg.foreground() );
            drawroundrect( p, x, y, w, h, d );
            p->setPen( oldPen );
            break;
        }
    case PE_ScrollBarAddLine:
        if ( flags & Style_Horizontal )
            drawSemicircleButton( p, r, PointRight, flags & Style_Down, cg );
        else
            drawSemicircleButton( p, r, PointDown, flags & Style_Down, cg );
        break;
    case PE_ScrollBarSubLine:
        if ( flags & Style_Horizontal )
            drawSemicircleButton( p, r, PointLeft, flags & Style_Down, cg );
        else
            drawSemicircleButton( p, r, PointUp, flags & Style_Down, cg );
        break;
    default:
        QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, opt );
        break;
    }
}

void NorwegianWoodStyle::drawControl( ControlElement element,
                                      QPainter *p,
                                      const QWidget *widget,
                                      const QRect &r,
                                      const QColorGroup &cg,
                                      SFlags how, const QStyleOption& opt ) const
{
    switch( element ) {
    case CE_PushButton:
        {
            const QPushButton *btn;
            btn = ( const QPushButton * )widget;
            QColorGroup myCg( cg );
            SFlags flags = Style_Default;
            if ( btn->isOn() )
                flags |= Style_On;
            if ( btn->isDown() )
                flags |= Style_Down;
            if ( btn->isOn() || btn->isDown() )
                flags |= Style_Sunken;
            if ( btn->isDefault() )
                flags |= Style_Default;
            if ( ! btn->isFlat() && !(flags & Style_Down) )
                flags |= Style_Raised;

            int x1, y1, x2, y2;
            r.coords( &x1, &y1, &x2, &y2 );

            p->setPen( cg.foreground() );
            p->setBrush( QBrush( cg.button(), NoBrush ) );

            QBrush fill;
            if ( btn->isDown() )
                fill = cg.brush( QColorGroup::Mid );
            else if ( btn->isOn() )
                fill = QBrush( cg.mid(), Dense4Pattern );
            else
                fill = cg.brush( QColorGroup::Button );
            myCg.setBrush( QColorGroup::Mid, fill );

            if ( btn->isDefault() ) {
                x1 += 2;
                y1 += 2;
                x2 -= 2;
                y2 -= 2;
            }

            drawPrimitive( PE_ButtonCommand, p,
                           QRect( x1, y1, x2 - x1 + 1, y2 - y1 + 1),
                           myCg, flags, opt );

            if ( btn->isDefault() ) {
                QPen pen( Qt::black, 4 );
                pen.setCapStyle( Qt::RoundCap );
                pen.setJoinStyle( Qt::RoundJoin );
                p->setPen( pen );
                drawroundrect( p, x1 - 1, y1 - 1, x2 - x1 + 3, y2 - y1 + 3, 8 );
            }

            if ( btn->isMenuButton() ) {
                int dx = ( y1 - y2 - 4 ) / 3;

                // reset the flags
                flags = Style_Default;
                if ( btn->isEnabled() )
                    flags |= Style_Enabled;
                drawPrimitive( PE_ArrowDown, p,
                               QRect( x2 - dx, dx, y1, y2 - y1),
                               myCg, flags, opt );
            }

            if ( p->brush().style() != NoBrush )
                p->setBrush( NoBrush );
            break;
        }
    case CE_PushButtonLabel:
        {
            const QPushButton *btn;
            btn = (const QPushButton*)widget;
            int x, y, w, h;
            r.rect( &x, &y, &w, &h );

            int x1, y1, x2, y2;
            r.coords( &x1, &y1, &x2, &y2 );
            int dx = 0;
            int dy = 0;
            if ( btn->isMenuButton() )
                dx = ( y2 - y1 ) / 3;
            if ( dx || dy )
                p->translate( dx, dy );

            x += 2;
            y += 2;
            w -= 4;
            h -= 4;
            drawItem( p, QRect( x, y, w, h ),
                      AlignCenter | ShowPrefix,
                      cg, btn->isEnabled(),
                      btn->pixmap(), btn->text(), -1,
                      (btn->isDown() || btn->isOn()) ? &cg.brightText()
                      : &cg.buttonText() );
            if ( dx || dy )
                p->translate( -dx, -dy );
            break;
        }
    default:
        QWindowsStyle::drawControl( element, p, widget, r, cg, how, opt );
        break;
    }
}

void NorwegianWoodStyle::drawControlMask( ControlElement element,
                                          QPainter *p,
                                          const QWidget *widget,
                                          const QRect &r,
                                          const QStyleOption& opt ) const
{
    switch( element ) {
    case CE_PushButton:
        {
            int d = QMIN( r.width(), r.height() ) / 2;
            p->setPen( color1 );
            p->setBrush( color1 );
            drawroundrect( p, r.x(), r.y(), r.width(), r.height(), d );
            break;
        }
    default:
        QWindowsStyle::drawControlMask( element, p, widget, r, opt );
        break;
    }
}

void NorwegianWoodStyle::drawComplexControl( ComplexControl cc,
                                             QPainter *p,
                                             const QWidget *widget,
                                             const QRect &r,
                                             const QColorGroup &cg,
                                             SFlags how,
                                             SCFlags sub,
                                             SCFlags subActive,
                                             const QStyleOption& opt ) const
{
    switch( cc ) {
    case CC_ComboBox:
        {
            const QComboBox *cmb;
            cmb = (const QComboBox*)widget;

            int awh, ax, ay, sh, sy, dh, ew;
            get_combo_parameters( subRect(SR_PushButtonContents, widget),
                                  ew, awh, ax, ay, sh, dh, sy );
            drawPrimitive( PE_ButtonCommand, p, r, cg, Style_Raised, opt );
            QStyle *mstyle = QStyleFactory::create( "Motif" );
            if ( mstyle )
                mstyle->drawPrimitive( PE_ArrowDown, p,
                                       QRect(ax, ay, awh, awh), cg, how, opt );
            else
                drawPrimitive( PE_ArrowDown, p,
                               QRect(ax, ay, awh, awh), cg, how, opt );

            QPen oldPen = p->pen();
            p->setPen( cg.light() );
            p->drawLine( ax, sy, ax + awh - 1, sy );
            p->drawLine( ax, sy, ax, sy + sh - 1 );
            p->setPen( cg.dark() );
            p->drawLine( ax + 1, sy + sh - 1, ax + awh - 1, sy + sh - 1 );
            p->drawLine( ax + awh - 1, sy + 1, ax + awh - 1, sy + sh - 1 );
            p->setPen( oldPen );

            if ( cmb->editable() ) {
                QRect r( querySubControlMetrics(CC_ComboBox, widget,
                                                SC_ComboBoxEditField, opt) );
                qDrawShadePanel( p, r, cg, TRUE, 1,
                                 &cg.brush(QColorGroup::Button) );
            }

            break;
        }
    default:
        QWindowsStyle::drawComplexControl( cc, p, widget, r, cg, how,
                                           sub, subActive, opt );
        break;
    }
}

void NorwegianWoodStyle::drawComplexControlMask( ComplexControl control,
                                                 QPainter *p,
                                                 const QWidget *widget,
                                                 const QRect &r,
                                                 const QStyleOption& opt ) const
{
    switch ( control ) {
    case CC_ComboBox:
        {
            int d = QMIN( r.width(), r.height() ) / 2;
            p->setPen( color1 );
            p->setBrush( color1 );
            drawroundrect( p, r.x(), r.y(), r.width(), r.height(), d );
            break;
        }
    default:
        QWindowsStyle::drawComplexControlMask( control, p, widget, r, opt );
        break;
    }
}

QRect NorwegianWoodStyle::querySubControlMetrics( ComplexControl control,
                                                  const QWidget *widget,
                                                  SubControl sc,
                                                  const QStyleOption& opt ) const
{
    QRect rect;
    switch ( control ) {
    case CC_ComboBox:
        {
            switch( sc ) {
            case SC_ComboBoxEditField:
                {
                    rect = subRect( SR_PushButtonContents, widget );
                    int ew = get_combo_extra_width( rect.height(), 0 );
                    rect.setRect( rect.x() + 1, rect.y() + 1,
                                  rect.width() - 2 - ew, rect.height() - 2 );
                    break;
                }
            default:
                rect = QWindowsStyle::querySubControlMetrics( control, widget,
                                                              sc, opt );
                break;
            }
            break;
        }
    case CC_ScrollBar:
        {
            const QScrollBar* sb;
            sb = (const QScrollBar*)widget;
            bool horz = sb->orientation() == QScrollBar::Horizontal;
            int b = 2;
            int w = horz ? sb->height() : sb->width();

            switch ( sc ) {
            case SC_ScrollBarAddLine:
                rect.setRect( b, b, w - 2 * b, w - 2 * b );
                if ( horz )
                    rect.moveBy( sb->width() - w, 0 );
                else
                    rect.moveBy( 0, sb->height() - w );
                break;
            case SC_ScrollBarSubLine:
                rect.setRect( b, b, w - 2 * b, w - 2 * b );
                break;
            default:
                rect = QWindowsStyle::querySubControlMetrics( control, widget,
                                                              sc, opt );
                break;
            }
            break;
        }
    default:
        rect = QWindowsStyle::querySubControlMetrics( control, widget,
                                                      sc, opt );
        break;
    }
    return rect;
}

QRect NorwegianWoodStyle::subRect( SubRect sr, const QWidget * widget ) const
{
    QRect r;
    switch ( sr ) {
    case SR_PushButtonContents:
        {
            const QPushButton *btn;
            btn = (const QPushButton*)widget;
            r = btn->rect();
            int d = QMIN( r.width(), r.height() ) / 2;
            int b = buttonthickness( d );

            d -= b;
            b++;

            if ( r.width() < r.height() )
                r.setRect( r.x() + b, r.y() + d,
                           r.width() - 2 * b, r.height() - 2 * d );
            else
                r.setRect( r.x() + d, r.y() + b,
                           r.width() - 2 * d, r.height() - 2 * b );
            break;
        }
    case SR_ComboBoxFocusRect:
        {
            r = subRect( SR_PushButtonContents, widget );
            int ew = get_combo_extra_width( r.height() );
            r.setRect( r.x() + 1, r.y() + 1, r.width() - 2 - ew,
                       r.height() - 2 );
            break;
        }
    default:
        r = QWindowsStyle::subRect( sr, widget );
        break;
    }
    return r;
}

static void drawroundrect( QPainter *p, QCOORD x, QCOORD y,
                           QCOORD w, QCOORD h, QCOORD d )
{
    int rx = (200*d)/w;
    int ry = (200*d)/h;
    p->drawRoundRect( x, y, w, h, rx, ry );
}

static QRegion roundRectRegion( const QRect& g, int r )
{
    QPointArray a;
    a.setPoints( 8, g.x()+r, g.y(), g.right()-r, g.y(),
                 g.right(), g.y()+r, g.right(), g.bottom()-r,
                 g.right()-r, g.bottom(), g.x()+r, g.bottom(),
                 g.x(), g.bottom()-r, g.x(), g.y()+r );
    QRegion reg( a );
    int d = r*2-1;
    reg += QRegion( g.x(),g.y(),r*2,r*2, QRegion::Ellipse );
    reg += QRegion( g.right()-d,g.y(),r*2,r*2, QRegion::Ellipse );
    reg += QRegion( g.x(),g.bottom()-d,r*2,r*2, QRegion::Ellipse );
    reg += QRegion( g.right()-d,g.bottom()-d,r*2,r*2, QRegion::Ellipse );
    return reg;
}

static int get_combo_extra_width( int h, int *return_awh )
{
    int awh;
    if ( h < 8 ) {
        awh = 6;
    } else if ( h < 14 ) {
        awh = h - 2;
    } else {
        awh = h/2;
    }
    if ( return_awh )
        *return_awh = awh;
    return awh*3/2;
}

static void get_combo_parameters( const QRect &r,
                                  int &ew, int &awh, int &ax,
                                  int &ay, int &sh, int &dh,
                                  int &sy )
{
    ew = get_combo_extra_width( r.height(), &awh );

    sh = (awh+3)/4;
    if ( sh < 3 )
        sh = 3;
    dh = sh/2 + 1;

    ay = r.y() + (r.height()-awh-sh-dh)/2;
    if ( ay < 0 ) {
        //panic mode
        ay = 0;
        sy = r.height();
    } else {
        sy = ay+awh+dh;
    }
    ax = r.x() + r.width() - ew +(ew-awh)/2;
}

static inline int buttonthickness( int d )
{ return  d > 20 ? 5 : ( d < 10 ? 2: 3 ); }

void NorwegianWoodStyle::drawSemicircleButton( QPainter *p, const QRect &r,
                                               int dir, bool sunken,
                                               const QColorGroup &g ) const
{
    int b =  pixelMetric( PM_ScrollBarExtent ) > 20 ? 3 : 2;

     QRegion extrn(  r.x(),   r.y(),   r.width(),     r.height(),     QRegion::Ellipse );
     QRegion intern( r.x()+b, r.y()+b, r.width()-2*b, r.height()-2*b, QRegion::Ellipse );
    int w2 = r.width()/2;
    int h2 = r.height()/2;

    int bug = 1; //off-by-one somewhere!!!???

    switch( dir ) {
    case PointRight:
        extrn +=  QRegion( r.x(),  r.y(),   w2,     r.height() );
        intern += QRegion( r.x()+b,r.y()+b, w2-2*b, r.height()-2*b );
        break;
    case PointLeft:
        extrn +=  QRegion( r.x()+w2,  r.y(),   w2,     r.height() );
        intern += QRegion( r.x()+w2+b,r.y()+b, w2-2*b, r.height()-2*b );
        break;
    case PointUp:
        extrn +=  QRegion( r.x(),  r.y()+h2,   r.width(),     h2 );
        intern += QRegion( r.x()+b,r.y()+h2+b, r.width()-2*b-bug, h2-2*b-bug );
        break;
    case PointDown:
        extrn +=  QRegion( r.x(),  r.y(),   r.width(),     h2 );
        intern += QRegion( r.x()+b,r.y()+b, r.width()-2*b-bug, h2-2*b-bug );
        break;
    }

    extrn = extrn - intern;
    QPointArray a;
    a.setPoints( 3, r.x(), r.y(), r.x(), r.bottom(), r.right(), r.top() );

    QRegion oldClip = p->clipRegion();
    bool bReallyClip = p->hasClipping();  // clip only if we really want.
    p->setClipRegion( intern );
    p->fillRect( r, g.brush( QColorGroup::Button ) );

    p->setClipRegion( QRegion(a)&extrn );
    p->fillRect( r, sunken ? g.dark() : g.light() );

    a.setPoints( 3, r.right(), r.bottom(), r.x(), r.bottom(),
                 r.right(), r.top() );
    p->setClipRegion( QRegion(a) &  extrn );
    p->fillRect( r, sunken ? g.light() : g.dark() );

    p->setClipRegion( oldClip );
    p->setClipping( bReallyClip );
}

#endif

Header file of the Metal theme:

/****************************************************************************
** $Id:  qt/metal.h   3.0.5   edited Dec 4 2001 $
**
** Definition of the Metal Style for the themes example
**
** Created : 979899
**
** Copyright (C) 1997 by Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef METAL_H
#define METAL_H

#include <qwindowsstyle.h>
#include <qpalette.h>

#ifndef QT_NO_STYLE_WINDOWS

class MetalStyle : public QWindowsStyle
{
public:
    MetalStyle();
    void polish( QApplication*);
    void unPolish( QApplication*);
    void polish( QWidget* );
    void unPolish( QWidget* );

    void drawPrimitive( PrimitiveElement pe,
                        QPainter *p,
                        const QRect &r,
                        const QColorGroup &cg,
                        SFlags flags = Style_Default,
                        const QStyleOption& = QStyleOption::Default) const;

    void drawControl( ControlElement element,
                      QPainter *p,
                      const QWidget *widget,
                      const QRect &r,
                      const QColorGroup &cg,
                      SFlags how = Style_Default,
                      const QStyleOption& = QStyleOption::Default ) const;

    void drawComplexControl( ComplexControl cc,
                             QPainter *p,
                             const QWidget *widget,
                             const QRect &r,
                             const QColorGroup &cg,
                             SFlags how = Style_Default,
                             SCFlags sub = SC_All,
                             SCFlags subActive = SC_None,
                             const QStyleOption& = QStyleOption::Default ) const;
    int pixelMetric( PixelMetric, const QWidget * ) const;

private:
    void drawMetalFrame(  QPainter *p, int x, int y, int w, int h ) const;
    void drawMetalGradient( QPainter *p, int x, int y, int w, int h,
                          bool sunken, bool horz, bool flat=FALSE ) const;
    void drawMetalButton( QPainter *p, int x, int y, int w, int h,
                          bool sunken, bool horz, bool flat=FALSE ) const;
    QPalette oldPalette;
};

#endif

#endif

Implementation of the Metal theme:

/****************************************************************************
** $Id:  qt/metal.cpp   3.0.5   edited Dec 4 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "metal.h"

#ifndef QT_NO_STYLE_WINDOWS

#include "qapplication.h"
#include "qcombobox.h"
#include "qpainter.h"
#include "qdrawutil.h" // for now
#include "qpixmap.h" // for now
#include "qpalette.h" // for now
#include "qwidget.h"
#include "qlabel.h"
#include "qimage.h"
#include "qpushbutton.h"
#include "qwidget.h"
#include "qrangecontrol.h"
#include "qscrollbar.h"
#include "qslider.h"
#include <limits.h>

/////////////////////////////////////////////////////////
#include "stonedark.xpm"
#include "stone1.xpm"
#include "marble.xpm"
///////////////////////////////////////////////////////

MetalStyle::MetalStyle() : QWindowsStyle() { }

/*!
  Reimplementation from QStyle
 */
void MetalStyle::polish( QApplication *app)
{
    oldPalette = app->palette();

    // we simply create a nice QColorGroup with a couple of fancy
    // pixmaps here and apply to it all widgets

    QFont f("times", app->font().pointSize() );
    f.setBold( TRUE );
    f.setItalic( TRUE );
    app->setFont( f, TRUE, "QMenuBar");
    app->setFont( f, TRUE, "QPopupMenu");

    //    QPixmap button( stonedark_xpm );

    QColor gold("#B9B9A5A54040"); //same as topgrad below
    QPixmap button( 1, 1 ); button.fill( gold );

    QPixmap background(marble_xpm);
    QPixmap dark( 1, 1 ); dark.fill( red.dark() );
    QPixmap mid( stone1_xpm );
    QPixmap light( stone1_xpm );//1, 1 ); light.fill( green );

    QPalette op = app->palette();

    QColor backCol( 227,227,227 );

    // QPalette op(white);
    QColorGroup active (op.active().foreground(),
                     QBrush(op.active().button(),button),
                     QBrush(op.active().light(), light),
                     QBrush(op.active().dark(), dark),
                     QBrush(op.active().mid(), mid),
                     op.active().text(),
                     Qt::white,
                     op.active().base(),//                   QColor(236,182,120),
                     QBrush(backCol, background)
                     );
    active.setColor( QColorGroup::ButtonText,  Qt::white  );
    active.setColor( QColorGroup::Shadow,  Qt::black  );
    QColorGroup disabled (op.disabled().foreground(),
                     QBrush(op.disabled().button(),button),
                     QBrush(op.disabled().light(), light),
                     op.disabled().dark(),
                     QBrush(op.disabled().mid(), mid),
                     op.disabled().text(),
                     Qt::white,
                     op.disabled().base(),//                 QColor(236,182,120),
                     QBrush(backCol, background)
                     );

    QPalette newPalette( active, disabled, active );
    app->setPalette( newPalette, TRUE );
}

/*!
  Reimplementation from QStyle
 */
void MetalStyle::unPolish( QApplication *app)
{
    app->setPalette(oldPalette, TRUE);
    app->setFont( app->font(), TRUE );
}

/*!
  Reimplementation from QStyle
 */
void MetalStyle::polish( QWidget* w)
{

   // the polish function sets some widgets to transparent mode and
    // some to translate background mode in order to get the full
    // benefit from the nice pixmaps in the color group.

    if (w->inherits("QPushButton")){
        w->setBackgroundMode( QWidget::NoBackground );
        return;
    }

    if ( !w->isTopLevel() ) {
        if ( w->backgroundPixmap() )
            w->setBackgroundOrigin( QWidget::WindowOrigin );
    }
}

void MetalStyle::unPolish( QWidget* w)
{

   // the polish function sets some widgets to transparent mode and
    // some to translate background mode in order to get the full
    // benefit from the nice pixmaps in the color group.

    if (w->inherits("QPushButton")){
        w->setBackgroundMode( QWidget::PaletteButton );
        return;
    }
    if ( !w->isTopLevel() ) {
        if ( w->backgroundPixmap() )
            w->setBackgroundOrigin( QWidget::WidgetOrigin );
    }

}

void MetalStyle::drawPrimitive( PrimitiveElement pe,
                                QPainter *p,
                                const QRect &r,
                                const QColorGroup &cg,
                                SFlags flags, const QStyleOption& opt ) const
{
    switch( pe ) {
    case PE_HeaderSection:
        if ( flags & Style_Sunken )
            flags ^= Style_Sunken | Style_Raised;
        // fall through
    case PE_ButtonBevel:
    case PE_ButtonCommand:
            drawMetalButton( p, r.x(), r.y(), r.width(), r.height(),
                             (flags & (Style_Sunken|Style_On|Style_Down)),
                             TRUE, !(flags & Style_Raised) );
            break;
    case PE_PanelMenuBar:
        drawMetalFrame( p, r.x(), r.y(), r.width(), r.height() );
        break;
    case PE_ScrollBarAddLine:
        drawMetalButton( p, r.x(), r.y(), r.width(), r.height(),
                         flags & Style_Down, !( flags & Style_Horizontal ) );
        drawPrimitive( (flags & Style_Horizontal) ? PE_ArrowRight :PE_ArrowDown,
                       p, r, cg, flags, opt );
        break;
    case PE_ScrollBarSubLine:
        drawMetalButton( p, r.x(), r.y(), r.width(), r.height(),
                         flags & Style_Down, !( flags & Style_Horizontal ) );
        drawPrimitive( (flags & Style_Horizontal) ? PE_ArrowLeft : PE_ArrowUp,
                       p, r, cg, flags, opt );
        break;

    case PE_ScrollBarSlider:
        drawMetalButton( p, r.x(), r.y(), r.width(), r.height(), FALSE,
                         flags & Style_Horizontal );
        break;
    default:
        QWindowsStyle::drawPrimitive( pe, p, r, cg, flags, opt );
        break;
    }
}

void MetalStyle::drawControl( ControlElement element,
                              QPainter *p,
                              const QWidget *widget,
                              const QRect &r,
                              const QColorGroup &cg,
                              SFlags how,
                              const QStyleOption& opt ) const
{
    switch( element ) {
    case CE_PushButton:
        {
            const QPushButton *btn;
            btn = (const QPushButton*)widget;
            int x1, y1, x2, y2;

            r.coords( &x1, &y1, &x2, &y2 );

            p->setPen( cg.foreground() );
            p->setBrush( QBrush(cg.button(), NoBrush) );

            QBrush fill;
            if ( btn->isDown() )
                fill = cg.brush( QColorGroup::Mid );
            else if ( btn->isOn() )
                fill = QBrush( cg.mid(), Dense4Pattern );
            else
                fill = cg.brush( QColorGroup::Button );

            if ( btn->isDefault() ) {
                QPointArray a;
                a.setPoints( 9,
                             x1, y1, x2, y1, x2, y2, x1, y2, x1, y1+1,
                             x2-1, y1+1, x2-1, y2-1, x1+1, y2-1, x1+1, y1+1 );
                p->setPen( Qt::black );
                p->drawPolyline( a );
                x1 += 2;
                y1 += 2;
                x2 -= 2;
                y2 -= 2;
            }
            SFlags flags = Style_Default;
            if ( btn->isOn() )
                flags |= Style_On;
            if ( btn->isDown() )
                flags |= Style_Down;
            if ( !btn->isFlat() && !btn->isDown() )
                flags |= Style_Raised;
            drawPrimitive( PE_ButtonCommand, p,
                           QRect( x1, y1, x2 - x1 + 1, y2 - y1 + 1),
                           cg, flags, opt );

            if ( btn->isMenuButton() ) {
                flags = Style_Default;
                if ( btn->isEnabled() )
                    flags |= Style_Enabled;

                int dx = ( y1 - y2 - 4 ) / 3;
                drawPrimitive( PE_ArrowDown, p,
                               QRect(x2 - dx, dx, y1, y2 - y1),
                               cg, flags, opt );
            }
            if ( p->brush().style() != NoBrush )
                p->setBrush( NoBrush );
            break;
        }
    case CE_PushButtonLabel:
        {
            const QPushButton *btn;
            btn = (const QPushButton*)widget;
            int x, y, w, h;
            r.rect( &x, &y, &w, &h );

            int x1, y1, x2, y2;
            r.coords( &x1, &y1, &x2, &y2 );
            int dx = 0;
            int dy = 0;
            if ( btn->isMenuButton() )
                dx = ( y2 - y1 ) / 3;
            if ( btn->isOn() || btn->isDown() ) {
                dx--;
                dy--;
            }
            if ( dx || dy )
                p->translate( dx, dy );
            x += 2;
            y += 2;
            w -= 4;
            h -= 4;
            drawItem( p, QRect( x, y, w, h ),
                      AlignCenter|ShowPrefix,
                      cg, btn->isEnabled(),
                      btn->pixmap(), btn->text(), -1,
                      (btn->isDown() || btn->isOn())? &cg.brightText() : &cg.buttonText() );
            if ( dx || dy )
                p->translate( -dx, -dy );
            break;
        }
    default:
        QWindowsStyle::drawControl( element, p, widget, r, cg, how, opt );
        break;
    }
}
void MetalStyle::drawComplexControl( ComplexControl cc,
                                     QPainter *p,
                                     const QWidget *widget,
                                     const QRect &r,
                                     const QColorGroup &cg,
                                     SFlags how,
                                     SCFlags sub,
                                     SCFlags subActive,
                                     const QStyleOption& opt ) const
{
    switch ( cc ) {
    case CC_Slider:
        {
            const QSlider *slider = ( const QSlider* ) widget;
            QRect handle = querySubControlMetrics( CC_Slider, widget,
                                                   SC_SliderHandle, opt);
            if ( sub & SC_SliderGroove )
                QWindowsStyle::drawComplexControl( cc, p, widget, r, cg, how,
                                                   SC_SliderGroove, subActive, opt );
            if ( (sub & SC_SliderHandle) && handle.isValid() )
                drawMetalButton( p, handle.x(), handle.y(), handle.width(),
                                 handle.height(), FALSE,
                                 slider->orientation() == QSlider::Horizontal);
            break;
        }
    case CC_ComboBox:
        {
            // not exactly correct...
            const QComboBox *cmb = ( const QComboBox* ) widget;

            qDrawWinPanel( p, r.x(), r.y(), r.width(), r.height(), cg, TRUE,
                           cmb->isEnabled() ? &cg.brush( QColorGroup::Base ) :
                                              &cg.brush( QColorGroup::Background ) );
            drawMetalButton( p, r.x() + r.width() - 2 - 16, r.y() + 2, 16, r.height() - 4,
                             how & Style_Sunken, TRUE );
            drawPrimitive( PE_ArrowDown, p,
                           QRect( r.x() + r.width() - 2 - 16 + 2,
                                  r.y() + 2 + 2, 16 - 4, r.height() - 4 -4 ),
                           cg,
                           cmb->isEnabled() ? Style_Enabled : Style_Default,
                           opt );
            break;
        }
    default:
        QWindowsStyle::drawComplexControl( cc, p, widget, r, cg, how, sub, subActive,
                                           opt );
        break;
    }
}

/*!
  Draw a metallic button, sunken if \a sunken is TRUE, horizontal if
  /a horz is TRUE.
*/

void MetalStyle::drawMetalButton( QPainter *p, int x, int y, int w, int h,
                                  bool sunken, bool horz, bool flat  ) const
{

    drawMetalFrame( p, x, y, w, h );
    drawMetalGradient( p, x, y, w, h, sunken, horz, flat );
}

void MetalStyle::drawMetalFrame( QPainter *p, int x, int y, int w, int h ) const
{
    QColor top1("#878769691515");
    QColor top2("#C6C6B4B44949");

    QColor bot2("#70705B5B1414");
    QColor bot1("#56564A4A0E0E"); //first from the bottom

    int x2 = x + w - 1;
    int y2 = y + h - 1;

    //frame:

    p->setPen( top1 );
    p->drawLine( x, y2, x, y );
    p->drawLine( x, y, x2-1, y );
    p->setPen( top2 );
    p->drawLine( x+1, y2 -1, x+1, y+1 );
    p->drawLine( x+1, y+1 , x2-2, y+1 );

    p->setPen( bot1 );
    p->drawLine( x+1, y2, x2, y2 );
    p->drawLine( x2, y2, x2, y );
    p->setPen( bot2 );
    p->drawLine( x+1, y2-1, x2-1, y2-1 );
    p->drawLine( x2-1, y2-1, x2-1, y+1 );

}

void MetalStyle::drawMetalGradient( QPainter *p, int x, int y, int w, int h,
                                    bool sunken, bool horz, bool flat  ) const

{
    QColor highlight("#E8E8DDDD6565");
    QColor subh1("#CECEBDBD5151");
    QColor subh2("#BFBFACAC4545");

    QColor topgrad("#B9B9A5A54040");
    QColor botgrad("#89896C6C1A1A");

    if ( flat && !sunken ) {
            p->fillRect( x + 2, y + 2, w - 4,h -4, topgrad );
    } else {
        // highlight:
        int i = 0;
        int x1 = x + 2;
        int y1 = y + 2;
        int x2 = x + w - 1;
        int y2 = y + h - 1;
        if ( horz )
            x2 = x2 - 2;
        else
            y2 = y2 - 2;

#define DRAWLINE if (horz) \
                    p->drawLine( x1, y1+i, x2, y1+i ); \
                 else \
                    p->drawLine( x1+i, y1, x1+i, y2 ); \
                 i++;

        if ( !sunken ) {
            p->setPen( highlight );
            DRAWLINE;
            DRAWLINE;
            p->setPen( subh1 );
            DRAWLINE;
            p->setPen( subh2 );
            DRAWLINE;
        }
        // gradient:
        int ng = (horz ? h : w) - 8; // how many lines for the gradient?

        int h1, h2, s1, s2, v1, v2;
        if ( !sunken ) {
            topgrad.hsv( &h1, &s1, &v1 );
            botgrad.hsv( &h2, &s2, &v2 );
        } else {
            botgrad.hsv( &h1, &s1, &v1 );
            topgrad.hsv( &h2, &s2, &v2 );
        }

        if ( ng > 1 ) {
            for ( int j =0; j < ng; j++ ) {
                p->setPen( QColor( h1 + ((h2-h1)*j)/(ng-1),
                                   s1 + ((s2-s1)*j)/(ng-1),
                                   v1 + ((v2-v1)*j)/(ng-1),  QColor::Hsv ) );
                DRAWLINE;
            }
        } else if ( ng == 1 ) {
            p->setPen( QColor((h1+h2)/2, (s1+s2)/2, (v1+v2)/2, QColor::Hsv) );
            DRAWLINE;
        }
        if ( sunken ) {
            p->setPen( subh2 );
            DRAWLINE;

            p->setPen( subh1 );
            DRAWLINE;

            p->setPen( highlight );
            DRAWLINE;
            DRAWLINE;
        }
    }
}

int MetalStyle::pixelMetric( PixelMetric metric, const QWidget *w ) const
{
    switch ( metric ) {
    case PM_MenuBarFrameWidth:
        return 2;
    default:
        return QWindowsStyle::pixelMetric( metric, w );
    }
}

#endif

Header file of the example:

/****************************************************************************
** $Id:  qt/themes.h   3.0.5   edited Nov 23 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef THEMES_H
#define THEMES_H

#include <qmainwindow.h>
#include <qfont.h>

class QTabWidget;

class Themes: public QMainWindow
{
    Q_OBJECT

public:
    Themes( QWidget *parent = 0, const char *name = 0, WFlags f = WType_TopLevel );

protected:
    QTabWidget *tabwidget;

protected slots:
    void makeStyle(const QString &);
    void about();
    void aboutQt();

private:
    QFont appFont;
};

#endif

Implementation of the example:

/****************************************************************************
** $Id:  qt/themes.cpp   3.0.5   edited Dec 4 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "themes.h"
#include "wood.h"
#include "metal.h"

#include "../buttongroups/buttongroups.h"
#include "../lineedits/lineedits.h"
#include "../listboxcombo/listboxcombo.h"
#include "../checklists/checklists.h"
#include "../progressbar/progressbar.h"
#include "../rangecontrols/rangecontrols.h"
#include "../richtext/richtext.h"

#include <qtabwidget.h>
#include <qapplication.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qfont.h>
#include <qstylefactory.h>
#include <qaction.h>
#include <qsignalmapper.h>
#include <qdict.h>

Themes::Themes( QWidget *parent, const char *name, WFlags f )
    : QMainWindow( parent, name, f )
{
    appFont = QApplication::font();
    tabwidget = new QTabWidget( this );

    tabwidget->addTab( new ButtonsGroups( tabwidget ), "Buttons/Groups" );
    QHBox *hbox = new QHBox( tabwidget );
    hbox->setMargin( 5 );
    (void)new LineEdits( hbox );
    (void)new ProgressBar( hbox );
    tabwidget->addTab( hbox, "Lineedits/Progressbar" );
    tabwidget->addTab( new ListBoxCombo( tabwidget ), "Listboxes/Comboboxes" );
    tabwidget->addTab( new CheckLists( tabwidget ), "Listviews" );
    tabwidget->addTab( new RangeControls( tabwidget ), "Rangecontrols" );
    tabwidget->addTab( new MyRichText( tabwidget ), "Fortune" );

    setCentralWidget( tabwidget );

    QPopupMenu *style = new QPopupMenu( this );
    style->setCheckable( TRUE );
    menuBar()->insertItem( "&Style" , style );

    style->setCheckable( TRUE );
    QActionGroup *ag = new QActionGroup( this, 0 );
    ag->setExclusive( TRUE );
    QSignalMapper *styleMapper = new QSignalMapper( this );
    connect( styleMapper, SIGNAL( mapped( const QString& ) ), this, SLOT( makeStyle( const QString& ) ) );
    QStringList list = QStyleFactory::keys();
    list.sort();
#ifndef QT_NO_STYLE_WINDOWS
    list.insert(list.begin(), "Norwegian Wood");
    list.insert(list.begin(), "Metal");
#endif
    QDict<int> stylesDict( 17, FALSE );
    for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
        QString styleStr = *it;
        QString styleAccel = styleStr;
        if ( stylesDict[styleAccel.left(1)] ) {
            for ( uint i = 0; i < styleAccel.length(); i++ ) {
                if ( !stylesDict[styleAccel.mid( i, 1 )] ) {
                    stylesDict.insert(styleAccel.mid( i, 1 ), (const int *)1);
                    styleAccel = styleAccel.insert( i, '&' );
                    break;
                }
            }
        } else {
            stylesDict.insert(styleAccel.left(1), (const int *)1);
            styleAccel = "&"+styleAccel;
        }
        QAction *a = new QAction( styleStr, QIconSet(), styleAccel, 0, ag, 0, ag->isExclusive() );
        connect( a, SIGNAL( activated() ), styleMapper, SLOT(map()) );
        styleMapper->setMapping( a, a->text() );
    }
    ag->addTo(style);
    style->insertSeparator();
    style->insertItem("&Quit", qApp, SLOT( quit() ), CTRL | Key_Q );

    QPopupMenu * help = new QPopupMenu( this );
    menuBar()->insertSeparator();
    menuBar()->insertItem( "&Help", help );
    help->insertItem( "&About", this, SLOT(about()), Key_F1);
    help->insertItem( "About &Qt", this, SLOT(aboutQt()));

#ifndef QT_NO_STYLE_WINDOWS
    qApp->setStyle( new NorwegianWoodStyle );
#endif
}

void Themes::makeStyle(const QString &style)
{
    if(style == "Norwegian Wood") {
#ifndef QT_NO_STYLE_WINDOWS
        qApp->setStyle( new NorwegianWoodStyle );
#endif
    } else if( style == "Metal" ) {
#ifndef QT_NO_STYLE_WINDOWS
        qApp->setStyle( new MetalStyle );
#endif
    } else {
        qApp->setStyle(style);
        if(style == "Platinum") {
            QPalette p( QColor( 239, 239, 239 ) );
            qApp->setPalette( p, TRUE );
            qApp->setFont( appFont, TRUE );
        } else if(style == "Windows") {
            qApp->setFont( appFont, TRUE );
        } else if(style == "CDE") {
            QPalette p( QColor( 75, 123, 130 ) );
            p.setColor( QPalette::Active, QColorGroup::Base, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Inactive, QColorGroup::Base, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Disabled, QColorGroup::Base, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Active, QColorGroup::Highlight, Qt::white );
            p.setColor( QPalette::Active, QColorGroup::HighlightedText, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Inactive, QColorGroup::Highlight, Qt::white );
            p.setColor( QPalette::Inactive, QColorGroup::HighlightedText, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Disabled, QColorGroup::Highlight, Qt::white );
            p.setColor( QPalette::Disabled, QColorGroup::HighlightedText, QColor( 55, 77, 78 ) );
            p.setColor( QPalette::Active, QColorGroup::Foreground, Qt::white );
            p.setColor( QPalette::Active, QColorGroup::Text, Qt::white );
            p.setColor( QPalette::Active, QColorGroup::ButtonText, Qt::white );
            p.setColor( QPalette::Inactive, QColorGroup::Foreground, Qt::white );
            p.setColor( QPalette::Inactive, QColorGroup::Text, Qt::white );
            p.setColor( QPalette::Inactive, QColorGroup::ButtonText, Qt::white );
            p.setColor( QPalette::Disabled, QColorGroup::Foreground, Qt::lightGray );
            p.setColor( QPalette::Disabled, QColorGroup::Text, Qt::lightGray );
            p.setColor( QPalette::Disabled, QColorGroup::ButtonText, Qt::lightGray );
            qApp->setPalette( p, TRUE );
            qApp->setFont( QFont( "times", appFont.pointSize() ), TRUE );
        } else if(style == "Motif" || style == "MotifPlus") {
            QPalette p( QColor( 192, 192, 192 ) );
            qApp->setPalette( p, TRUE );
            qApp->setFont( appFont, TRUE );
        }
    }
}

void Themes::about()
{
    QMessageBox::about( this, "Qt Themes Example",
                        "<p>This example demonstrates the concept of "
                        "<b>generalized GUI styles </b> first introduced "
                        " with the 2.0 release of Qt.</p>" );
}

void Themes::aboutQt()
{
    QMessageBox::aboutQt( this, "Qt Themes Example" );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <qwindowsstyle.h>
#include "themes.h"

#include "metal.h"

int main( int argc, char ** argv )
{
    QApplication::setColorSpec( QApplication::ManyColor );
    QApplication a( argc, argv );

    Themes themes;
    themes.setCaption( "Qt Example - Themes (QStyle)" );
    themes.resize( 640, 400 );
    a.setMainWidget( &themes );
    themes.show();

    return a.exec();
}

See also Examples.


线程

这些类是和线程应用程序相关的。

QMutex | 线程之间的访问顺序化
QSemaphore | 健壮的整数新号量
QThread | 与平台无关的线程
QWaitCondition | 线程之间允许等待/唤醒的条件

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Tic Tac Toe

This is an implementation of the Tic-tac-toe game.

We didn't put much effort in making a clever algorithm so it's not a challenge to play against the computer. Instead, study the source code to see how you can make reusable components such as the TicTacGameBoard widget.

Header file:

/****************************************************************************
** $Id:  qt/tictac.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef TICTAC_H
#define TICTAC_H

#include <qpushbutton.h>
#include <qptrvector.h>

class QComboBox;
class QLabel;

// --------------------------------------------------------------------------
// TicTacButton implements a single tic-tac-toe button
//

class TicTacButton : public QPushButton
{
    Q_OBJECT
public:
    TicTacButton( QWidget *parent );
    enum Type { Blank, Circle, Cross };
    Type        type() const            { return t; }
    void        setType( Type type )    { t = type; repaint(); }
    QSizePolicy sizePolicy() const
    { return QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ); }
    QSize sizeHint() const { return QSize( 32, 32 ); }
    QSize minimumSizeHint() const { return QSize( 10, 10 ); }
protected:
    void        drawButtonLabel( QPainter * );
private:
    Type t;
};

// Using template vector to make vector-class of TicTacButton.
// This vector is used by the TicTacGameBoard class defined below.

typedef QPtrVector<TicTacButton>        TicTacButtons;
typedef QMemArray<int>          TicTacArray;

// --------------------------------------------------------------------------
// TicTacGameBoard implements the tic-tac-toe game board.
// TicTacGameBoard is a composite widget that contains N x N TicTacButtons.
// N is specified in the constructor.
//

class TicTacGameBoard : public QWidget
{
    Q_OBJECT
public:
    TicTacGameBoard( int n, QWidget *parent=0, const char *name=0 );
   ~TicTacGameBoard();
    enum        State { Init, HumansTurn, HumanWon, ComputerWon, NobodyWon };
    State       state() const           { return st; }
    void        computerStarts( bool v );
    void        newGame();
signals:
    void        finished();                     // game finished
private slots:
    void        buttonClicked();
private:
    void        setState( State state ) { st = state; }
    void        updateButtons();
    int checkBoard( TicTacArray * );
    void        computerMove();
    State       st;
    int         nBoard;
    bool        comp_starts;
    TicTacArray *btArray;
    TicTacButtons *buttons;
};

// --------------------------------------------------------------------------
// TicTacToe implements the complete game.
// TicTacToe is a composite widget that contains a TicTacGameBoard and
// two push buttons for starting the game and quitting.
//

class TicTacToe : public QWidget
{
    Q_OBJECT
public:
    TicTacToe( int boardSize=3, QWidget *parent=0, const char *name=0 );
private slots:
    void        newGameClicked();
    void        gameOver();
private:
    void        newState();
    QComboBox   *whoStarts;
    QPushButton *newGame;
    QPushButton *quit;
    QLabel      *message;
    TicTacGameBoard *board;
};

#endif // TICTAC_H

Implementation:

/****************************************************************************
** $Id:  qt/tictac.cpp   3.0.5   edited Nov 14 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "tictac.h"
#include <qapplication.h>
#include <qpainter.h>
#include <qdrawutil.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>
#include <stdlib.h>                             // rand() function
#include <qdatetime.h>                          // seed for rand()

//***************************************************************************
//* TicTacButton member functions
//***************************************************************************

// --------------------------------------------------------------------------
// Creates a TicTacButton
//

TicTacButton::TicTacButton( QWidget *parent ) : QPushButton( parent )
{
    t = Blank;                                  // initial type
}

// --------------------------------------------------------------------------
// Paints TicTacButton
//

void TicTacButton::drawButtonLabel( QPainter *p )
{
    QRect r = rect();
    p->setPen( QPen( white,2 ) );               // set fat pen
    if ( t == Circle ) {
        p->drawEllipse( r.left()+4, r.top()+4, r.width()-8, r.height()-8 );
    } else if ( t == Cross ) {                  // draw cross
        p->drawLine( r.topLeft()   +QPoint(4,4), r.bottomRight()-QPoint(4,4));
        p->drawLine( r.bottomLeft()+QPoint(4,-4),r.topRight()   -QPoint(4,-4));
    }
}

//***************************************************************************
//* TicTacGameBoard member functions
//***************************************************************************

// --------------------------------------------------------------------------
// Creates a game board with N x N buttons and connects the "clicked()"
// signal of all buttons to the "buttonClicked()" slot.
//

TicTacGameBoard::TicTacGameBoard( int n, QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    st = Init;                                  // initial state
    nBoard = n;
    n *= n;                                     // make square
    comp_starts = FALSE;                        // human starts
    buttons = new TicTacButtons(n);             // create real buttons
    btArray = new TicTacArray(n);               // create button model
    QGridLayout * grid = new QGridLayout( this, nBoard, nBoard, 4 );
    QPalette p( blue );
    for ( int i=0; i<n; i++ ) {                 // create and connect buttons
        TicTacButton *ttb = new TicTacButton( this );
        ttb->setPalette( p );
        ttb->setEnabled( FALSE );
        connect( ttb, SIGNAL(clicked()), SLOT(buttonClicked()) );
        grid->addWidget( ttb, i%nBoard, i/nBoard );
        buttons->insert( i, ttb );
        btArray->at(i) = TicTacButton::Blank;   // initial button type
    }
    QTime t = QTime::currentTime();             // set random seed
    srand( t.hour()*12+t.minute()*60+t.second()*60 );
}

TicTacGameBoard::~TicTacGameBoard()
{
    delete buttons;
    delete btArray;
}

// --------------------------------------------------------------------------
// TicTacGameBoard::computerStarts( bool v )
//
// Computer starts if v=TRUE. The human starts by default.
//

void TicTacGameBoard::computerStarts( bool v )
{
    comp_starts = v;
}

// --------------------------------------------------------------------------
// TicTacGameBoard::newGame()
//
// Clears the game board and prepares for a new game
//

void TicTacGameBoard::newGame()
{
    st = HumansTurn;
    for ( int i=0; i<nBoard*nBoard; i++ )
        btArray->at(i) = TicTacButton::Blank;
    if ( comp_starts )
        computerMove();
    else
        updateButtons();
}

// --------------------------------------------------------------------------
// TicTacGameBoard::buttonClicked()             - SLOT
//
// This slot is activated when a TicTacButton emits the signal "clicked()",
// i.e. the user has clicked on a TicTacButton.
//

void TicTacGameBoard::buttonClicked()
{
    if ( st != HumansTurn )                     // not ready
        return;
    int i = buttons->findRef( (TicTacButton*)sender() );
    TicTacButton *b = buttons->at(i);           // get piece that was pressed
    if ( b->type() == TicTacButton::Blank ) {   // empty piece?
        btArray->at(i) = TicTacButton::Circle;
        updateButtons();
        if ( checkBoard( btArray ) == 0 )       // not a winning move?
            computerMove();
        int s = checkBoard( btArray );
        if ( s ) {                              // any winners yet?
            st = s == TicTacButton::Circle ? HumanWon : ComputerWon;
            emit finished();
        }
    }
}

// --------------------------------------------------------------------------
// TicTacGameBoard::updateButtons()
//
// Updates all buttons that have changed state
//

void TicTacGameBoard::updateButtons()
{
    for ( int i=0; i<nBoard*nBoard; i++ ) {
        if ( buttons->at(i)->type() != btArray->at(i) )
            buttons->at(i)->setType( (TicTacButton::Type)btArray->at(i) );
        buttons->at(i)->setEnabled( buttons->at(i)->type() ==
                                    TicTacButton::Blank );
    }
}

// --------------------------------------------------------------------------
// TicTacGameBoard::checkBoard()
//
// Checks if one of the players won the game, works for any board size.
//
// Returns:
//  - TicTacButton::Cross  if the player with X buttons won
//  - TicTacButton::Circle if the player with O buttons won
//  - Zero (0) if there is no winner yet
//

int TicTacGameBoard::checkBoard( TicTacArray *a )
{
    int  t = 0;
    int  row, col;
    bool won = FALSE;
    for ( row=0; row<nBoard && !won; row++ ) {  // check horizontal
        t = a->at(row*nBoard);
        if ( t == TicTacButton::Blank )
            continue;
        col = 1;
        while ( col<nBoard && a->at(row*nBoard+col) == t )
            col++;
        if ( col == nBoard )
            won = TRUE;
    }
    for ( col=0; col<nBoard && !won; col++ ) {  // check vertical
        t = a->at(col);
        if ( t == TicTacButton::Blank )
            continue;
        row = 1;
        while ( row<nBoard && a->at(row*nBoard+col) == t )
            row++;
        if ( row == nBoard )
            won = TRUE;
    }
    if ( !won ) {                               // check diagonal top left
        t = a->at(0);                           //   to bottom right
        if ( t != TicTacButton::Blank ) {
            int i = 1;
            while ( i<nBoard && a->at(i*nBoard+i) == t )
                i++;
            if ( i == nBoard )
                won = TRUE;
        }
    }
    if ( !won ) {                               // check diagonal bottom left
        int j = nBoard-1;                       //   to top right
        int i = 0;
        t = a->at(i+j*nBoard);
        if ( t != TicTacButton::Blank ) {
            i++; j--;
            while ( i<nBoard && a->at(i+j*nBoard) == t ) {
                i++; j--;
            }
            if ( i == nBoard )
                won = TRUE;
        }
    }
    if ( !won )                                 // no winner
        t = 0;
    return t;
}

// --------------------------------------------------------------------------
// TicTacGameBoard::computerMove()
//
// Puts a piece on the game board. Very, very simple.
//

void TicTacGameBoard::computerMove()
{
    int numButtons = nBoard*nBoard;
    int *altv = new int[numButtons];            // buttons alternatives
    int altc = 0;
    int stopHuman = -1;
    TicTacArray a = btArray->copy();
    int i;
    for ( i=0; i<numButtons; i++ ) {            // try all positions
        if ( a[i] != TicTacButton::Blank )      // already a piece there
            continue;
        a[i] = TicTacButton::Cross;             // test if computer wins
        if ( checkBoard(&a) == a[i] ) {         // computer will win
            st = ComputerWon;
            stopHuman = -1;
            break;
        }
        a[i] = TicTacButton::Circle;            // test if human wins
        if ( checkBoard(&a) == a[i] ) {         // oops...
            stopHuman = i;                      // remember position
            a[i] = TicTacButton::Blank;         // restore button
            continue;                           // computer still might win
        }
        a[i] = TicTacButton::Blank;             // restore button
        altv[altc++] = i;                       // remember alternative
    }
    if ( stopHuman >= 0 )                       // must stop human from winning
        a[stopHuman] = TicTacButton::Cross;
    else if ( i == numButtons ) {               // tried all alternatives
        if ( altc > 0 )                         // set random piece
            a[altv[rand()%(altc--)]] = TicTacButton::Cross;
        if ( altc == 0 ) {                      // no more blanks
            st = NobodyWon;
            emit finished();
        }
    }
    *btArray = a;                               // update model
    updateButtons();                            // update buttons
    delete[] altv;
}

//***************************************************************************
//* TicTacToe member functions
//***************************************************************************

// --------------------------------------------------------------------------
// Creates a game widget with a game board and two push buttons, and connects
// signals of child widgets to slots.
//

TicTacToe::TicTacToe( int boardSize, QWidget *parent, const char *name )
    : QWidget( parent, name )
{
    QVBoxLayout * l = new QVBoxLayout( this, 6 );

    // Create a message label

    message = new QLabel( this );
    message->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
    message->setAlignment( AlignCenter );
    l->addWidget( message );

    // Create the game board and connect the signal finished() to this
    // gameOver() slot

    board = new TicTacGameBoard( boardSize, this );
    connect( board, SIGNAL(finished()), SLOT(gameOver()) );
    l->addWidget( board );

    // Create a horizontal frame line

    QFrame *line = new QFrame( this );
    line->setFrameStyle( QFrame::HLine | QFrame::Sunken );
    l->addWidget( line );

    // Create the combo box for deciding who should start, and
    // connect its clicked() signals to the buttonClicked() slot

    whoStarts = new QComboBox( this );
    whoStarts->insertItem( "Computer starts" );
    whoStarts->insertItem( "Human starts" );
    l->addWidget( whoStarts );

    // Create the push buttons and connect their clicked() signals
    // to this right slots.

    newGame = new QPushButton( "Play!", this );
    connect( newGame, SIGNAL(clicked()), SLOT(newGameClicked()) );
    quit = new QPushButton( "Quit", this );
    connect( quit, SIGNAL(clicked()), qApp, SLOT(quit()) );
    QHBoxLayout * b = new QHBoxLayout;
    l->addLayout( b );
    b->addWidget( newGame );
    b->addWidget( quit );

    newState();
}

// --------------------------------------------------------------------------
// TicTacToe::newGameClicked()                  - SLOT
//
// This slot is activated when the new game button is clicked.
//

void TicTacToe::newGameClicked()
{
    board->computerStarts( whoStarts->currentItem() == 0 );
    board->newGame();
    newState();
}

// --------------------------------------------------------------------------
// TicTacToe::gameOver()                        - SLOT
//
// This slot is activated when the TicTacGameBoard emits the signal
// "finished()", i.e. when a player has won or when it is a draw.
//

void TicTacToe::gameOver()
{
    newState();                                 // update text box
}

// --------------------------------------------------------------------------
// Updates the message to reflect a new state.
//

void TicTacToe::newState()
{
    static const char *msg[] = {                // TicTacGameBoard::State texts
        "Click Play to start", "Make your move",
        "You won!", "Computer won!", "It's a draw" };
    message->setText( msg[board->state()] );
    return;
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include <stdlib.h>
#include "tictac.h"

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    int n = 3;
    if ( argc == 2 )                            // get board size n
        n = atoi(argv[1]);
    if ( n < 3 || n > 10 ) {                    // out of range
        qWarning( "%s: Board size must be from 3x3 to 10x10", argv[0] );
        return 1;
    }
    TicTacToe ttt( n );                         // create game
    a.setMainWidget( &ttt );
    ttt.setCaption("Qt Example - TicTac");
    ttt.show();                                 // show widget
    return a.exec();                            // go
}

See also Examples.


时间和日期

这些类提供了不依赖与系统的日期和时间的抽象。

可能会用到：Qt适应2000年问题声明.

QDate | 日期功能
QDateEdit | 日期编辑器
QDateTime | 日期和时间功能
QDateTimeEdit | 把一个QDataEdit和一个QTimeEdit窗口部件组合为一个单一的窗口部件来编辑日期时间
QTime | 时钟时间功能
QTimeEdit | 时间编辑器
QTimer | 定时器信号和单触发定时器

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


定时器

在Qt中，QObject，所有Qt对象的基类，提供了一个基本的定时器。通过QObject::startTimer()，你可以把一个以毫秒为单位的时间间隔作为参数来开始定时器。这个函数返回一个唯一的整数的定时器的标识符。这个定时器现在就会在每一个时间间隔“触发”，直到你明确地使用这个定时器的标识符来调用QObject::killTimer()结束。

对于这种工作机制，应用程序不得不在一个事件回路中运行。你通过QApplication::exec()来开始一个事件回路。当定时器触发时，应用程序会发送一个QTimerEvent，并且控制流直到定时器事件被处理时才会离开事件回路。这暗示着当你的应用程序正忙于其它事情的时候，定时器不能触发。换句话说，定时器的精确性依赖于你的应用程序的间隔尺度。

事实上，对于间隔值是没有上限的（超过一年也是可能的）。精确性依赖于位于下面的操作系统。Windows 95/98的精确度为55毫秒（每秒18.2次），其它我们已经测试过的操作系统（UNIX X11、Windows NT和OS/2）都可以处理1毫秒的间隔。

定时器功能的主要的应用程序接口是QTimer。这个类可以提供当定时器触发的时候发射一个信号的有规律的定时器，并且继承了QObject，所以它很适合绝大多数图形用户界面程序的所有权结构。通常的使用方法如下：

    QTimer * counter = new QTimer( this );
    connect( counter, SIGNAL(timeout()),
             this, SLOT(updateCaption()) );
    counter->start( 1000 );

counter定时器被作为这个窗口部件的子类，这样当这个窗口部件被删除时，定时器也会被删除。接下来，它的timeout信号被连接到将要做工作的槽上，最后它开始了。

QTimer也提供了一个简单的只有一次定时器的应用程序接口。QButton，当键盘被用来“按下”按钮的时候，在按钮被按下来显示按钮和接下来（0.1秒之后）被释放时使用它来显示按钮，例如：

    QTimer::singleShot( 100, this, SLOT(animateTimeout()) );

在这行代码之后0.1秒时，同一个按钮的animateTimeout()槽被调用。

这里是一个通过QTimer对象的信号和槽来进行对象通讯的不太复杂的实例的大纲。它示范了一个单线程应用程序如何使用定时器在不阻塞用户界面的情况下进行精确运算的。

    // Mandelbrot类使用QTimer在不阻塞CPU的情况下来计算一个扫描行。
    // 它继承了QObject来使用信号和槽。调用start()来开始运算。当运
    // 算完成时，done()信号被发射。注意这个例子并不完全，只是一个
    // 大纲。

    class Mandelbrot : public QObject
    {
        Q_OBJECT // 因为需要使用信号/槽
    public:
        Mandelbrot( QObject *parent=0, const char *name );
        ...
    public slots:
        void start();
    signals:
        void done();
    private slots:
        void calculate();
        private:
        QTimer timer;
        ...
    };

    //
    // 构造并初始化Mandelbrot对象。
    //

    Mandelbrot::Mandelbrot( QObject *parent=0, const char *name )
    : QObject( parent, name )
    {
        connect( &timer, SIGNAL(timeout()), SLOT(calculate()) );
        ...
    }

    //
    // 开始运算任务。内部的calculate()槽会每10毫秒被激活一次。
    //

    void Mandelbrot::start()
    {
        if ( !timer.isActive() ) // 还没有准备好运行
            timer.start( 10 );   // 每10毫秒超时
    }

    //
    // 每次运算一个扫描行。
    // 当结束时发射done()信号。
    //

    void Mandelbrot::calculate()
    {
        ...                // 执行一个扫描行的运算
        if ( finished ) {  // 没有更多的扫描行了
            timer.stop();
            emit done();
        }
    }

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


A Tiny Example Featuring a Toggle Action

This example program demonstrates the use of QAction in its incarnation as a toggle action.

Main:

#include <qapplication.h>
#include <qmainwindow.h>
#include <qtoolbar.h>
#include <qaction.h>

#include "labelonoff.xpm"

int main( int argc, char **argv )
{
    QApplication app( argc, argv );
    QMainWindow * window = new QMainWindow;
    window->setCaption("Qt Example - Toggleaction");
    QToolBar * toolbar = new QToolBar( window );

    QAction * labelonoffaction = new QAction( window, "labelonoff", TRUE );

    labelonoffaction->setText( "labels on/off" );
    labelonoffaction->setAccel( Qt::ALT+Qt::Key_L );
    labelonoffaction->setIconSet( (QPixmap) labelonoff_xpm );

    QObject::connect( labelonoffaction, SIGNAL( toggled( bool ) ),
                      window, SLOT( setUsesTextLabel( bool ) ) );

    labelonoffaction->addTo( toolbar );

    app.setMainWidget( window );
    window->show();
    return app.exec();
}

See also QAction Examples.


Non-GUI Classes

The non-GUI classes are general-purpose collection and string classes that may be used independently of the GUI classes.

In particular, these classes do not depend on QApplication at all, and so can be used in non-GUI programs.

See also the introduction to the Qt collection classes.

QAsciiCache | Template class that provides a cache based on char* keys
QAsciiCacheIterator | Iterator for QAsciiCache collections
QAsciiDict | Template class that provides a dictionary based on char* keys
QAsciiDictIterator | Iterator for QAsciiDict collections
QBitArray | Array of bits
QByteArray | Array of bytes
QCache | Template class that provides a cache based on QString keys
QCacheIterator | Iterator for QCache collections
QCString | Abstraction of the classic C zero-terminated char array (char *)
QDict | Template class that provides a dictionary based on QString keys
QDictIterator | Iterator for QDict collections
QIntCache | Template class that provides a cache based on long keys
QIntCacheIterator | Iterator for QIntCache collections
QIntDict | Template class that provides a dictionary based on long keys
QIntDictIterator | Iterator for QIntDict collections
QMap | Value-based template class that provides a dictionary
QMapConstIterator | Iterator for QMap
QMapIterator | Iterator for QMap
QMemArray | Template class that provides arrays of simple types
QObjectList | QPtrList of QObjects
QObjectListIt | Iterator for QObjectLists
QPair | Value-based template class that provides a pair of elements
QPtrCollection | The base class of most pointer-based Qt collections
QPtrDict | Template class that provides a dictionary based on void* keys
QPtrDictIterator | Iterator for QPtrDict collections
QPtrList | Template class that provides doubly-linked lists
QPtrListIterator | Iterator for QPtrList collections
QPtrQueue | Template class that provides a queue
QPtrStack | Template class that provides a stack
QPtrVector | Template collection class that provides a vector (array)
QRegExp | Pattern matching using regular expressions
QStrIList | Doubly-linked list of char* with case-insensitive comparison
QString | Abstraction of Unicode text and the classic C null-terminated char array
QStringList | List of strings
QStrList | Doubly-linked list of char*
QStrListIterator | Iterator for the QStrList and QStrIList classes
QValueList | Value-based template class that provides doubly linked lists
QValueListConstIterator | Const iterator for QValueList
QValueListIterator | Iterator for QValueList
QValueStack | Value-based template class that provides a stack
QValueVector | Value-based template class that provides a dynamic array


Advanced use of tool tips

This example widget demonstrates how to use tool tips for static and dynamic regions within a widget.

It displays two blue and one red rectangle. The blue ones move every time you click on them, the red one is static. There are dynamic tool tips on the blue rectangles and a static tool tip on the red one.

Header file:

/****************************************************************************
** $Id:  qt/tooltip.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qwidget.h>
#include <qtooltip.h>

class DynamicTip : public QToolTip
{
public:
    DynamicTip( QWidget * parent );

protected:
    void maybeTip( const QPoint & );
};

class TellMe : public QWidget
{
    Q_OBJECT
public:
    TellMe( QWidget * parent = 0, const char * name = 0 );
    ~TellMe();

    QRect tip( const QPoint & );

protected:
    void paintEvent( QPaintEvent * );
    void mousePressEvent( QMouseEvent * );
    void resizeEvent( QResizeEvent * );

private:
    QRect randomRect();

    QRect r1, r2, r3;
    DynamicTip * t;
};

Implementation:

/****************************************************************************
** $Id:  qt/tooltip.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "tooltip.h"
#include <qapplication.h>
#include <qpainter.h>
#include <stdlib.h>

DynamicTip::DynamicTip( QWidget * parent )
    : QToolTip( parent )
{
    // no explicit initialization needed
}

void DynamicTip::maybeTip( const QPoint &pos )
{
    if ( !parentWidget()->inherits( "TellMe" ) )
        return;

    QRect r( ((TellMe*)parentWidget())->tip(pos) );
    if ( !r.isValid() )
        return;

    QString s;
    s.sprintf( "position: %d,%d", r.center().x(), r.center().y() );
    tip( r, s );
}

TellMe::TellMe( QWidget * parent , const char * name  )
    : QWidget( parent, name )
{
    setMinimumSize( 30, 30 );
    r1 = randomRect();
    r2 = randomRect();
    r3 = randomRect();

    t = new DynamicTip( this );

    QToolTip::add( this, r3, "this color is called red" ); // <- helpful
}

TellMe::~TellMe()
{
    delete t;
    t = 0;
}

void TellMe::paintEvent( QPaintEvent * e )
{
    QPainter p( this );

    // I try to be efficient here, and repaint only what's needed

    if ( e->rect().intersects( r1 ) ) {
        p.setBrush( blue );
        p.drawRect( r1 );
    }

    if ( e->rect().intersects( r2 ) ) {
        p.setBrush( blue );
        p.drawRect( r2 );
    }

    if ( e->rect().intersects( r3 ) ) {
        p.setBrush( red );
        p.drawRect( r3 );
    }
}

void TellMe::mousePressEvent( QMouseEvent * e )
{
    if ( r1.contains( e->pos() ) )
        r1 = randomRect();
    if ( r2.contains( e->pos() ) )
        r2 = randomRect();
    repaint();
}

void TellMe::resizeEvent( QResizeEvent * )
{
    if ( !rect().contains( r1 ) )
         r1 = randomRect();
    if ( !rect().contains( r2 ) )
         r2 = randomRect();
}

QRect TellMe::randomRect()
{
    return QRect( ::rand() % (width() - 20), ::rand() % (height() - 20),
                  20, 20 );
}

QRect TellMe::tip( const QPoint & p )
{
    if ( r1.contains( p ) )
        return r1;
    else if ( r2.contains( p ) )
        return r2;
    else
        return QRect( 0,0, -1,-1 );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>
#include "tooltip.h"

int main( int argc, char ** argv )
{
    QApplication a( argc, argv );

    TellMe mw;
    mw.setCaption( "Qt Example - Dynamic Tool Tips" );
    a.setMainWidget( &mw );
    mw.show();

    return a.exec();
}

See also Examples.


Trivial Example

This example is trivial, and thus useful for investigating problems you might have installing the extension.

To build the example, you must first build the Qt Netscape Plugin Extension library. Then type make in extensions/nsplugin/examples/trivial/ and copy the resulting trivial.so or nptrivial.dll to the Plugins directory of your WWW browser.

Implementation:

// Qt stuff
#include "qnp.h"
#include <qpainter.h>
#include <qmessagebox.h>

class Trivial : public QNPWidget {
    Q_OBJECT
public:
    void mouseReleaseEvent(QMouseEvent* event)
    {
        QMessageBox::aboutQt(this);
    }

    void paintEvent(QPaintEvent* event)
    {
        QPainter p(this);
        p.setClipRect(event->rect());
        int w = width();
        p.drawRect(rect());
        p.drawText(w/8, 0, w-w/4, height(), AlignCenter|WordBreak, "Trivial!");
    }
};

class TrivialInstance : public QNPInstance {
    Q_OBJECT
public:
    QNPWidget* newWindow()
    {
        return new Trivial;
    }

    void print(QPainter* p)
    {
        p->drawText(0,0,"Hello");
    }
};

class TrivialPlugin : public QNPlugin {
public:
    QNPInstance* newInstance()
    {
        return new TrivialInstance;
    }

    const char* getMIMEDescription() const
    {
        return "trivial/very:xxx:Trivial and useless";
    }

    const char * getPluginNameString() const
    {
        return "Trivial Qt-based Plugin";
    }

    const char * getPluginDescriptionString() const
    {
        return "A Qt-based LiveConnected plug-in that does nothing";
    }

};

QNPlugin* QNPlugin::create()
{
    return new TrivialPlugin;
}

#include "trivial.moc"

See also LiveConnect Examples.


Qt教程一 —— 第八章：准备战斗

Screenshot of tutorial eight

在这个例子中，我们介绍可以画自己的第一个自定义窗口部件。我们也加入了一个有用的键盘接口（只用了两行代码）。

  • t8/lcdrange.h包含LCDRange类定义。
  • t8/lcdrange.cpp包含LCDRange类实现。
  • t8/cannon.h包含CannonField类定义。
  • t8/cannon.cpp包含CannonField类实现。
  • t8/main.cpp包含MyWidget和main。

一行一行地解说

t8/lcdrange.h

这个文件和第七章中的lcdrange.h很相似。我们添加了一个槽：setRange()。

        void setRange( int minVal, int maxVal );

现在我们添加了设置LCDRange范围的可能性。直到现在，它就可以被设置为0～99。

t8/lcdrange.cpp

在构造函数中有一个变化（稍后我们会讨论的）。

    void LCDRange::setRange( int minVal, int maxVal )
    {
        if ( minVal < 0 || maxVal > 99 || minVal > maxVal ) {
          qWarning( "LCDRange::setRange(%d,%d)\n"
                   "\tRange must be 0..99\n"
                   "\tand minVal must not be greater than maxVal",
                   minVal, maxVal );
          return;
        }
        slider->setRange( minVal, maxVal );
    }

setRange()设置了LCDRange中滑块的范围。因为我们已经把QLCDNumber设置为只显示两位数字了，我们想通过限制minVal和maxVal为0~99来避免QLCDNumber的溢出。（我们可以允许最小值为-9，但是我们没有那样做。）如果参数是非法的，我们使用Qt的qWarning()函数来向用户发出警告并立即返回。qWarning()是一个像printf一样的函数，默认情况下它的输出发送到stderr。如果你想改变的话，你可以使用::qInstallMsgHandler()函数安装自己的处理函数。

t8/cannon.h

CanonField是一个知道如何显示自己的新的自定义窗口部件。

    class CannonField : public QWidget
    {
        Q_OBJECT
    public:
        CannonField( QWidget *parent=0, const char *name=0 );

CanonField继承了QWidget，我们使用了LCDRange中同样的方式。

        int angle() const { return ang; }
        QSizePolicy sizePolicy() const;

    public slots:
        void setAngle( int degrees );

    signals:
        void angleChanged( int );

目前，CanonField只包含一个角度值，我们使用了LCDRange中同样的方式。

    protected:
        void paintEvent( QPaintEvent * );

这是我们在QWidget中遇到的许多事件处理器中的第二个。只要一个窗口部件需要刷新它自己（比如，画窗口部件表面），这个虚函数就会被Qt调用。

t8/cannon.cpp

    CannonField::CannonField( QWidget *parent, const char *name )
            : QWidget( parent, name )
    {

我们又一次使用和前一章中的LCDRange同样的方式。

        ang = 45;
        setPalette( QPalette( QColor( 250, 250, 200) ) );
    }

构造函数把角度值初始化为45度并且给这个窗口部件设置了一个自定义调色板。

这个调色板只是说明背景色，并选择了其它合适的颜色。（对于这个窗口部件，只有背景色和文本颜色是要用到的。）

    void CannonField::setAngle( int degrees )
    {
        if ( degrees < 5 )
            degrees = 5;
        if ( degrees > 70 )
            degrees = 70;
        if ( ang == degrees )
            return;
        ang = degrees;
        repaint();
        emit angleChanged( ang );
    }

这个函数设置角度值。我们选择了一个5～70的合法范围，并根据这个范围来调节给定的degrees的值。当新的角度值超过了范围，我们选择了不使用警告。

如果新的角度值和旧的一样，我们立即返回。这只对当角度值真的发生变化时，发射angleChanged()信号有重要意义。

然后我们设置新的角度值并重新画我们的窗口部件。QWidget::repaint()函数清空窗口部件（通常用背景色来充满）并向窗口部件发出一个绘画事件。这样的结构就是调用窗口部件的绘画事件函数一次。

最后，我们发射angleChanged()信号来告诉外面的世界，角度值发生了变化。emit关键字只是Qt中的关键字，而不是标准C++的语法。实际上，它只是一个宏。

    void CannonField::paintEvent( QPaintEvent * )
    {
        QString s = "Angle = " + QString::number( ang );
        QPainter p( this );
        p.drawText( 200, 200, s );
    }

这是我们第一次试图写一个绘画事件处理程序。这个事件参数包含一个绘画事件的描述。QPaintEvent包含一个必须被刷新的窗口部件的区域。现在，我们比较懒惰，并且只是画每一件事。

我们的代码在一个固定位置显示窗口部件的角度值。首先我们创建一个含有一些文本和角度值的QString，然后我们创建一个操作这个窗口部件的QPainter并使用它来画这个字符串。我们一会儿会回到QPainter，它可以做很多事。

t8/main.cpp

    #include "cannon.h"

我们包含了我们的新类：

    class MyWidget: public QWidget
    {
    public:
        MyWidget( QWidget *parent=0, const char *name=0 );
    };

这一次我们在顶层窗口部件中只使用了一个LCDRange和一个CanonField。

        LCDRange *angle = new LCDRange( this, "angle" );

在构造函数中，我们创建并设置了我们的LCDRange。

        angle->setRange( 5, 70 );

我们设置LCDRange能够接受的范围是5～70度。

        CannonField *cannonField
            = new CannonField( this, "cannonField" );

我们创建了我们的CannonField。

        connect( angle, SIGNAL(valueChanged(int)),
                 cannonField, SLOT(setAngle(int)) );
        connect( cannonField, SIGNAL(angleChanged(int)),
                 angle, SLOT(setValue(int)) );

这里我们把LCDRange的valueChanged()信号和CannonField的setAngle()槽连接起来了。只要用户操作LCDRange，就会刷新CannonField的角度值。我们也把它反过来连接了，这样CannonField中角度的变化就可以刷新LCDRange的值。在我们的例子中，我们从来没有直接改变CannonField的角度，但是通过我们的最后一个connect()我们就可以确保没有任何变化可以改变这两个值之间的同步关系。

这说明了组件编程和正确封装的能力。

注意只有当角度确实发生变化时，才发射angleChanged()是多么的重要。如果LCDRange和CanonField都省略了这个检查，这个程序就会因为第一次数值变化而进入到一个无限循环当中。

        QGridLayout *grid = new QGridLayout( this, 2, 2, 10 );
        //2×2，10像素的边界

到现在为止，我们没有因为几何管理把QVBox和QGrid窗口部件集成到一起。现在，无论如何，我们需要对我们的布局加一些控制，所以我们使用了更加强大的QGridLayout类。QGridLayout不是一个窗口部件，它是一个可以管理任何窗口部件作为子对象的不同的类。

就像注释中所说的，我们创建了一个以10像素为边界的2*2的数组。（QGridLayout的构造函数有一点神秘，所以最好在这里加入一些注释。）

        grid->addWidget( quit, 0, 0 );

我们在网格的左上的单元格中加入一个Quit按钮：0,0。

        grid->addWidget( angle, 1, 0, Qt::AlignTop );

我们把angle这个LCDRange放到左下的单元格，在单元格内向上对齐。（这只是QGridLayout所允许的一种对齐方式，而QGrid不允许。）

        grid->addWidget( cannonField, 1, 1 );

我们把CannonField对象放到右下的单元格。（右上的单元格是空的。）

        grid->setColStretch( 1, 10 );

我们告诉QGridLayout右边的列（列1）是可拉伸的。因为左边的列不是（它的拉伸因数是0，这是默认值），QGridLayout就会在MyWidget被重新定义大小的时候试图让左面的窗口部件大小不变，而重新定义CannonField的大小。

        angle->setValue( 60 );

我们设置了一个初始角度值。注意这将会引发从LCDRange到CannonField的连接。

        angle->setFocus();

我们刚才做的是设置angle获得键盘焦点，这样默认情况下键盘输入会到达LCDRange窗口部件。

LCDRange没有包含任何keyPressEvent()，所以这看起来不太可能有用。无论如何，它的构造函数中有了新的一行：

        setFocusProxy( slider );

LCDRange设置滑块作为它的焦点代理。这就是说当程序或者用户想要给LCDRange一个键盘焦点，滑块就会就会注意到它。QSlider有一个相当好的键盘接口，所以就会出现我们给LCDRange添加的这一行。

行为

键盘现在可以做一些事了——方向键、Home、End、PageUp和PageDown都可以作一些事情。

当滑块被操作，CannonFiled会显示新的角度值。如果重新定义大小，CannonField会得到尽可能多的空间。

在8位的Windows机器上显示新的颜色会颤动的要命。下一章会处理这些的。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

设置重新定义窗口的大小。如果你把它变窄或者变矮会发生什么？

如果你把AlignTop删掉，LCDRange的位置会发生什么变化？为什么？

如果你给左面的列一个非零的拉伸因数，当你重新定义窗口大小时会发生什么？

不考虑setFocus()调用。你更喜欢什么样的行为？

试着在QButton::setText()调用中把“Quit”改为“&Quit”。按钮看起来变成什么样子了？如果你在程序运行的时候按下Alt+Q会发生什么？（在少量键盘中时Meta+Q。）

把CannonField的文本放到中间。

现在你可以进行第九章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Qt教程一 —— 第十一章：悬在空中的砖

Screenshot of tutorial twelve

在这个例子中，我们扩展我们的LCDRange类来包含一个文本标签。我们也会给射击提供一个目标。

  • t12/lcdrange.h包含LCDRange类定义。
  • t12/lcdrange.cpp包含LCDRange类实现。
  • t12/cannon.h包含CannonField类定义。
  • t12/cannon.cpp包含CannonField类实现。
  • t12/main.cpp包含MyWidget和main。

一行一行地解说

t12/lcdrange.h

LCDRange现在有了一个文本标签。

    class QLabel;

我们名称声明QLabel，因为我们将在这个类声明中使用一个QLabel的指针。

    class LCDRange : public QVBox
    {
        Q_OBJECT
    public:
        LCDRange( QWidget *parent=0, const char *name=0 );
        LCDRange( const char *s, QWidget *parent=0,
                  const char *name=0 );

我们添加了一个新的构造函数，这个构造函数在父对象和名称之外还设置了标签文本。

        const char *text()  const;

这个函数返回标签文本。

        void setText( const char * );

这个槽设置标签文本。

    private:
        void init();

因为我们现在有了两个构造函数，我们选择把通常的初始化放在一个私有的init()函数。

        QLabel      *label;

我们还有一个新的私有变量：一个QLabel。QLabel是一个Qt标准窗口部件并且可以显示一个有或者没有框架的文本或者pixmap。

t12/lcdrange.cpp

    #include <qlabel.h>

这里我们包含了QLabel类定义。

    LCDRange::LCDRange( QWidget *parent, const char *name )
            : QVBox( parent, name )
    {
        init();
    }

这个构造函数调用了init()函数，它包括了通常的初始化代码。

    LCDRange::LCDRange( const char *s, QWidget *parent,
                        const char *name )
            : QVBox( parent, name )
    {
        init();
        setText( s );
    }

这个构造函数首先调用了init()然后设置标签文本。

    void LCDRange::init()
    {
        QLCDNumber *lcd  = new QLCDNumber( 2, this, "lcd"  );
        slider = new QSlider( Horizontal, this, "slider" );
        slider->setRange( 0, 99 );
        slider->setValue( 0 );

        label = new QLabel( " ", this, "label"  );
        label->setAlignment( AlignCenter );

        connect( slider, SIGNAL(valueChanged(int)),
                 lcd, SLOT(display(int)) );
        connect( slider, SIGNAL(valueChanged(int)),
                 SIGNAL(valueChanged(int)) );

        setFocusProxy( slider );
    }

lcd和slider的设置和上一章一样。接下来我们创建一个QLabel并且让它的内容中间对齐（垂直方向和水平方向都是）。connect()语句也来自于上一章。

    const char *LCDRange::text() const
    {
        return label->text();
    }

这个函数返回标签文本。

    void LCDRange::setText( const char *s )
    {
        label->setText( s );
    }

这个函数设置标签文本。

t12/cannon.h

CannonField现在有两个新的信号：hit()和missed()。另外它还包含一个目标。

        void  newTarget();

这个槽在新的位置生成一个新的目标。

    signals:
        void  hit();
        void  missed();

hit()信号是当炮弹击中目标的时候被发射的。missed()信号是当炮弹移动超出了窗口部件的右面或者下面的边界时被发射的（例如，当然这种情况下它将不会击中目标）。

        void  paintTarget( QPainter * );

这个私有函数绘制目标。

        QRect targetRect() const;

这个私有函数返回一个封装了目标的矩形。

        QPoint target;

这个私有变量包含目标的中心点。

t12/cannon.cpp

    #include <qdatetime.h>

我们包含了QDate、QTime和QDateTime类定义。

    #include <stdlib.h>

我们包含了stdlib库，因为我们需要rand()函数。

        newTarget();

这一行已经被添加到了构造函数中。它为目标创建一个“随机的”位置。实际上，newTarget()函数还试图绘制目标。因为我们在一个构造函数中，CannonField窗口部件还是不可以见的。Qt保证在一个隐藏的窗口部件中调用repaint()是没有害处的。

    void  CannonField::newTarget()
    {
        static bool first_time = TRUE;
        if ( first_time ) {
            first_time = FALSE;
            QTime midnight( 0, 0, 0 );
            srand( midnight.secsTo(QTime::currentTime()) );
        }
        QRegion r( targetRect() );
        target = QPoint( 200 + rand() % 190,
                         10  + rand() % 255 );
        repaint( r.unite( targetRect() ) );
    }

这个私有函数创建了一个在新的“随机的”位置的目标中心点。

我们使用rand()函数来获得随机整数。rand()函数通常会在你每次运行这个程序的时候返回同样一组值。这就会使每次运行的时候目标都出现在同样的位置。为了避免这些，我们必须在这个函数第一次被调用的时候设置一个随机种子。为了避免同样一组数据，随机种子也必须是随机的。解决方法就是使用从午夜到现在的秒数作为一个假的随机值。

首先我们创建一个静态布尔型局域变量。静态变量就是在调用函数前后都保证它的值不变。

if测试会成功，因为只有当这个函数第一次被调用的时候，我们在if块中把first_time设置为FALSE。

然后我们创建一个QTime对象midnight，它将会提供时间00:00:00。接下来我们获得从午夜到现在所过的秒数并且使用它作为一个随机种子。请看QDate、QTime和QDateTime文档来获得更多的信息。

最后我们计算目标的中心点。我们把它放在一个矩形中（x=200，y=35，width=190，height=255），（例如，可能的x和y值是x=200~389和y=35~289）在一个我们把窗口边界的下边界作为y的零点，并且y向上增加，X轴向通常一样，左边界为零点，并且x向右增加的坐标系统中。

通过经验，我们发现这都在炮弹的射程之内。

注意rand()返回一个>=0的随机整数。

    void CannonField::moveShot()
    {
        QRegion r( shotRect() );
        timerCount++;

        QRect shotR = shotRect();

定时器时间这部分和上一章一样。

        if ( shotR.intersects( targetRect() ) ) {
            autoShootTimer->stop();
            emit hit();

if语句检查炮弹矩形和目标矩形是否相交。如果是的，炮弹击中了目标（哎哟！）。我们停止射击定时器并且发射hit()信号来告诉外界目标已经被破坏，并返回。

注意，我们可以在这个点上创建一个新的目标，但是因为CannonField是一个组件，所以我们要把这样的决定留给组件的使用者。

        } else if ( shotR.x() > width() || shotR.y() > height() ) {
            autoShootTimer->stop();
            emit missed();

这个if语句和上一章一样，除了现在它发射missed()信号告诉外界这次失败。

        } else {

函数的其余部分和以前一样。

CannonField::paintEvent() is as before, except that this has been added:

        if ( updateR.intersects( targetRect() ) )
            paintTarget( &p );

这两行确认在需要的时候目标也被绘制。

    void CannonField::paintTarget( QPainter *p )
    {
        p->setBrush( red );
        p->setPen( black );
        p->drawRect( targetRect() );
    }

这个私有函数绘制目标，一个由红色填充，有黑色边框的矩形。

    QRect CannonField::targetRect() const
    {
        QRect r( 0, 0, 20, 10 );
        r.moveCenter( QPoint(target.x(),height() - 1 - target.y()) );
        return r;
    }

这个私有函数返回封装目标的矩形。从newTarget()中所得的target点使用0点在窗口部件的下边界的y。我们在调用QRect::moveCenter()之前在窗口坐标中计算这个点。

我们选择这个坐标映射的原因是在目标和窗口部件的下边界之间垂直距离。记住这些可以让用户或者程序在任何时候都可以重新定义窗口部件的大小。

t12/main.cpp

在MyWidget类中没有新的成员了，但是我们稍微改变了一下构造函数来设置新的LCDRange的文本标签。

        LCDRange *angle  = new LCDRange( "ANGLE", this, "angle" );

我们设置角度的文本标签为“ANGLE”。

        LCDRange *force  = new LCDRange( "FORCE", this, "force" );

我们设置力量的文本标签为“FORCE”。

行为

加农炮会向目标射击，当它射中目标的时候，一个新的目标会自动被创建。

LCDRange窗口部件看起来有一点奇怪——QVBox中内置的管理给了标签太多的空间而其它的却不够。我们将会在下一章修正这一点。

（请看编译来学习如何创建一个makefile和连编应用程序。）

练习

创建一个作弊的按钮，当按下它的时候，让CannonField画出炮弹在五秒中的轨迹。

如果你在上一章做了“圆形炮弹”的练习，试着改变shotRect()为可以返回一个QRegion的shotRegion()，这样你就可以真正的做到准确碰撞检测。

做一个移动目标。

确认目标被完全创建在屏幕上。

确认加农炮窗口部件不能被重新定义大小，这样目标不是可见的。提示：QWidget::setMinimumSize()是你的朋友。

不容易的是在同一时刻让几个炮弹在空中成为可能。提示：建立一个炮弹对象。

现在你可以进行第十三章了。

 [上一章]
[下一章]
[教程一主页]

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


关于Unicode

Unicode是一个16位的字符集，它可以移植到所有主要的计算机平台并且覆盖几乎整个世界。它也是单一地区的；它不包括代码页或者其它让软件很难读写和测试的复杂的东西。现在还没有一个合理的多平台的字符集可以和它竞争。由于以上原因，Trolltech公司从Qt 2.0开始选择Unicode作为它天然的字符集。

在互联网上关于Unicode的信息。

Unicode协会提供了大量的文档，包括

  • Unicode的技术介绍
  • 标准的主页

标准

标准当前的版本是3.0.1。

  • Unicode标准，3.0版。也可以看它的主页。
  • Unicode标准，2.0版。 也可以看在www.unicode.org的 2.1版的改进和2.1.9版和2.1.9的数据文件。

Qt中的Unicode

在Qt中，和大多数使用Qt的应用程序中，几乎所有的或全部的用户可见的字符串都被使用Unicode方式存储。Qt提供了：

  • 对于文件输入输出，和传统的编码格式的互译——请看QTextCodec和QTextStream。
  • 从输入法和8位键盘输入的翻译。
  • 对于屏幕上显示，翻译到传统字符集。
  • 一个字符串类，QString，存储Unicode字符，它支持包括快速的（高速缓存的）和US-ASCII互译的C字符串的移植，并且支持所有常用的字符串操作。
  • 在适当的时候使用支持Unicode的窗口部件。
  • Unicode支持在Windows 95/98/NT/2000上的检测，这样Qt就可以在那些甚至不支持Unicode的Windows平台上提供Unicode。

为了获得Unicode的益处，我们建议使用QString来存储所有用户可见的字符串并且使用QTextStream来处理所有文本文件输入输出。在你写的任何一个自定制的窗口部件中使用QKeyEvent::text()来处理键盘输入；它对于西欧或者北美的速度较慢的打字员来说没有什么不同的，但是对于那些速度较快或者使用特殊输入法的人们来说使用text()是有好处的。

在Qt中所有可能是用户可见字符串的函数参数，QLabel::setText()和很多其它函数，使用const QString &来作为类型。QString对于像下面这样的const char *工作的

        myLabel->setText( "Hello, Dolly!" );

提供了隐式调用。还有一个函数QObject::tr()也提供翻译支持，像这样：

        myLabel->setText( tr("Hello, Dolly!") );

tr()（有时被简化）从const char *映射到Unicode字符串，并且使用QTranslator对象来进行这个映射。

程序需要和其它程序进行通讯或者使用传统文件格式进行读写文件，Qt提供了大量的内置的QTextCodec类，这些类知道如何在Unicode和传统编码之间进行翻译。

默认地，和const char *的互相转换使用基于本地的编码解码器。无论如何，程序都能够很容易地找到其它地区的编码解码器，并且可以对于任何一个打开的文件或者网络连接使用一个特殊的编码解码器。安装那些内置的编码解码器不支持新的编码解码器也是很容易的。（写这篇文档的时候，越南语/VISCII就是一个这样的例子。）

尽管US-ASCII和ISO-8859-1是非常普通的，这里也提供了可以和它们互相映射的特别快的函数。举例来说，打开一个应用程序的图标也许会这样做：

        QFile f( QString::fromLatin1("appicon.png") );

关于输出，Qt对于从Unicode到任何一个系统和字体提供的编码的转换作出了最大的努力。基于操作系统、本地和字体的可用性和Qt对所使用的字符的支持，这种转换也许是好的，也许是坏的。我们将在即将推出的版本中继续改进，以最普通的地区编码作为重点。

Copyright © 2002 Trolltech Trademarks 译者:Cavendish
Qt 3.0.5版


Widgets Example

This example shows most of Qt's widgets in action. It is similar to the demo example in $QTDIR/examples/demo.

Run the program, then click the right mouse button + Ctrl to identify a widget.

See $QTDIR/examples/widgets for the source code.

See also Examples.


Wizard

This example shows the usage of Qt's wizard class. A wizard should be used to help a user with complicated actions.

Header file:

/****************************************************************************
** $Id:  qt/wizard.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef WIZARD_H
#define WIZARD_H

#include <qwizard.h>

class QWidget;
class QHBox;
class QLineEdit;
class QLabel;

class Wizard : public QWizard
{
    Q_OBJECT

public:
    Wizard( QWidget *parent = 0, const char *name = 0 );

    void showPage(QWidget* page);

protected:
    void setupPage1();
    void setupPage2();
    void setupPage3();

    QHBox *page1, *page2, *page3;
    QLineEdit *key, *firstName, *lastName, *address, *phone, *email;
    QLabel *lKey, *lFirstName, *lLastName, *lAddress, *lPhone, *lEmail;

protected slots:
    void keyChanged( const QString & );
    void dataChanged( const QString & );

};

#endif

Implementation:

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "wizard.h"

#include <qwidget.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <qapplication.h>

Wizard::Wizard( QWidget *parent, const char *name )
    : QWizard( parent, name, TRUE )
{
    setupPage1();
    setupPage2();
    setupPage3();

    key->setFocus();
}

void Wizard::setupPage1()
{
    page1 = new QHBox( this );
    page1->setSpacing(8);

    QLabel *info = new QLabel( page1 );
    info->setPalette( yellow );
    info->setText( "Enter your personal\n"
                   "key here.\n\n"
                   "Your personal key\n"
                   "consists of 4 digits" );
    info->setIndent( 8 );
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page1 );

    QHBox *row1 = new QHBox( page );

    (void)new QLabel( "Key:", row1 );

    key = new QLineEdit( row1 );
    key->setMaxLength( 4 );
    key->setValidator( new QIntValidator( 1000, 9999, key ) );

    connect( key, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( keyChanged( const QString & ) ) );

    addPage( page1, "Personal Key" );

    setNextEnabled( page1, FALSE );
    setHelpEnabled( page1, FALSE );
}

void Wizard::setupPage2()
{
    page2 = new QHBox( this );
    page2->setSpacing(8);

    QLabel *info = new QLabel( page2 );
    info->setPalette( yellow );
    info->setText( "\n"
                   "  Enter your personal  \n"
                   "  data here.  \n\n"
                   "  The required fields are  \n"
                   "  First Name, Last Name \n"
                   "  and E-Mail.  \n" );
    info->setIndent(8);
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page2 );

    QHBox *row1 = new QHBox( page );
    QHBox *row2 = new QHBox( page );
    QHBox *row3 = new QHBox( page );
    QHBox *row4 = new QHBox( page );
    QHBox *row5 = new QHBox( page );

    QLabel *label1 = new QLabel( " First Name: ", row1 );
    label1->setAlignment( Qt::AlignVCenter );
    QLabel *label2 = new QLabel( " Last Name: ", row2 );
    label2->setAlignment( Qt::AlignVCenter );
    QLabel *label3 = new QLabel( " Address: ", row3 );
    label3->setAlignment( Qt::AlignVCenter );
    QLabel *label4 = new QLabel( " Phone Number: ", row4 );
    label4->setAlignment( Qt::AlignVCenter );
    QLabel *label5 = new QLabel( " E-Mail: ", row5 );
    label5->setAlignment( Qt::AlignVCenter );

    label1->setMinimumWidth( label4->sizeHint().width() );
    label2->setMinimumWidth( label4->sizeHint().width() );
    label3->setMinimumWidth( label4->sizeHint().width() );
    label4->setMinimumWidth( label4->sizeHint().width() );
    label5->setMinimumWidth( label4->sizeHint().width() );

    firstName = new QLineEdit( row1 );
    lastName = new QLineEdit( row2 );
    address = new QLineEdit( row3 );
    phone = new QLineEdit( row4 );
    email = new QLineEdit( row5 );

    connect( firstName, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );
    connect( lastName, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );
    connect( email, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );

    addPage( page2, "Personal Data" );

    setHelpEnabled( page2, FALSE );
}

void Wizard::setupPage3()
{
    page3 = new QHBox( this );
    page3->setSpacing(8);

    QLabel *info = new QLabel( page3 );
    info->setPalette( yellow );
    info->setText( "\n"
                   "  Look here to see of  \n"
                   "  the data you entered  \n"
                   "  is correct. To confirm,  \n"
                   "  press the [Finish] button  \n"
                   "  else go back to correct  \n"
                   "  mistakes." );
    info->setIndent(8);
    info->setAlignment( AlignTop|AlignLeft );
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page3 );

    QHBox *row1 = new QHBox( page );
    QHBox *row2 = new QHBox( page );
    QHBox *row3 = new QHBox( page );
    QHBox *row4 = new QHBox( page );
    QHBox *row5 = new QHBox( page );
    QHBox *row6 = new QHBox( page );

    QLabel *label1 = new QLabel( " Personal Key: ", row1 );
    label1->setAlignment( Qt::AlignVCenter );
    QLabel *label2 = new QLabel( " First Name: ", row2 );
    label2->setAlignment( Qt::AlignVCenter );
    QLabel *label3 = new QLabel( " Last Name: ", row3 );
    label3->setAlignment( Qt::AlignVCenter );
    QLabel *label4 = new QLabel( " Address: ", row4 );
    label4->setAlignment( Qt::AlignVCenter );
    QLabel *label5 = new QLabel( " Phone Number: ", row5 );
    label5->setAlignment( Qt::AlignVCenter );
    QLabel *label6 = new QLabel( " E-Mail: ", row6 );
    label6->setAlignment( Qt::AlignVCenter );

    label1->setMinimumWidth( label1->sizeHint().width() );
    label2->setMinimumWidth( label1->sizeHint().width() );
    label3->setMinimumWidth( label1->sizeHint().width() );
    label4->setMinimumWidth( label1->sizeHint().width() );
    label5->setMinimumWidth( label1->sizeHint().width() );
    label6->setMinimumWidth( label1->sizeHint().width() );

    lKey = new QLabel( row1 );
    lFirstName = new QLabel( row2 );
    lLastName = new QLabel( row3 );
    lAddress = new QLabel( row4 );
    lPhone = new QLabel( row5 );
    lEmail = new QLabel( row6 );

    addPage( page3, "Finish" );

    setFinishEnabled( page3, TRUE );
    setHelpEnabled( page3, FALSE );
}

void Wizard::showPage( QWidget* page )
{
    if ( page == page1 ) {
    } else if ( page == page2 ) {
    } else if ( page == page3 ) {
        lKey->setText( key->text() );
        lFirstName->setText( firstName->text() );
        lLastName->setText( lastName->text() );
        lAddress->setText( address->text() );
        lPhone->setText( phone->text() );
        lEmail->setText( email->text() );
    }

    QWizard::showPage(page);

    if ( page == page1 ) {
        keyChanged( key->text() );
        key->setFocus();
    } else if ( page == page2 ) {
        dataChanged( firstName->text() );
        firstName->setFocus();
    } else if ( page == page3 ) {
        finishButton()->setEnabled( TRUE );
        finishButton()->setFocus();
    }
}

void Wizard::keyChanged( const QString &text )
{
    QString t = text;
    int p = 0;
    bool on = ( key->validator()->validate(t, p) == QValidator::Acceptable );
    nextButton()->setEnabled( on );
}

void Wizard::dataChanged( const QString & )
{
    if ( !firstName->text().isEmpty() &&
         !lastName->text().isEmpty() &&
         !email->text().isEmpty() )
        nextButton()->setEnabled( TRUE );
    else
        nextButton()->setEnabled( FALSE );
}

Main:

/****************************************************************************
** $Id:  qt/main.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "wizard.h"
#include <qapplication.h>

int main(int argc,char **argv)
{
    QApplication a(argc,argv);

    Wizard wizard;
    wizard.setCaption("Qt Example - Wizard");
    return wizard.exec();
}

See also Examples.


wizard/wizard.cpp Example File

/****************************************************************************
** $Id$
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include "wizard.h"

#include <qwidget.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <qapplication.h>

Wizard::Wizard( QWidget *parent, const char *name )
    : QWizard( parent, name, TRUE )
{
    setupPage1();
    setupPage2();
    setupPage3();

    key->setFocus();
}

void Wizard::setupPage1()
{
    page1 = new QHBox( this );
    page1->setSpacing(8);

    QLabel *info = new QLabel( page1 );
    info->setPalette( yellow );
    info->setText( "Enter your personal\n"
                   "key here.\n\n"
                   "Your personal key\n"
                   "consists of 4 digits" );
    info->setIndent( 8 );
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page1 );

    QHBox *row1 = new QHBox( page );

    (void)new QLabel( "Key:", row1 );

    key = new QLineEdit( row1 );
    key->setMaxLength( 4 );
    key->setValidator( new QIntValidator( 1000, 9999, key ) );

    connect( key, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( keyChanged( const QString & ) ) );

    addPage( page1, "Personal Key" );

    setNextEnabled( page1, FALSE );
    setHelpEnabled( page1, FALSE );
}

void Wizard::setupPage2()
{
    page2 = new QHBox( this );
    page2->setSpacing(8);

    QLabel *info = new QLabel( page2 );
    info->setPalette( yellow );
    info->setText( "\n"
                   "  Enter your personal  \n"
                   "  data here.  \n\n"
                   "  The required fields are  \n"
                   "  First Name, Last Name \n"
                   "  and E-Mail.  \n" );
    info->setIndent(8);
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page2 );

    QHBox *row1 = new QHBox( page );
    QHBox *row2 = new QHBox( page );
    QHBox *row3 = new QHBox( page );
    QHBox *row4 = new QHBox( page );
    QHBox *row5 = new QHBox( page );

    QLabel *label1 = new QLabel( " First Name: ", row1 );
    label1->setAlignment( Qt::AlignVCenter );
    QLabel *label2 = new QLabel( " Last Name: ", row2 );
    label2->setAlignment( Qt::AlignVCenter );
    QLabel *label3 = new QLabel( " Address: ", row3 );
    label3->setAlignment( Qt::AlignVCenter );
    QLabel *label4 = new QLabel( " Phone Number: ", row4 );
    label4->setAlignment( Qt::AlignVCenter );
    QLabel *label5 = new QLabel( " E-Mail: ", row5 );
    label5->setAlignment( Qt::AlignVCenter );

    label1->setMinimumWidth( label4->sizeHint().width() );
    label2->setMinimumWidth( label4->sizeHint().width() );
    label3->setMinimumWidth( label4->sizeHint().width() );
    label4->setMinimumWidth( label4->sizeHint().width() );
    label5->setMinimumWidth( label4->sizeHint().width() );

    firstName = new QLineEdit( row1 );
    lastName = new QLineEdit( row2 );
    address = new QLineEdit( row3 );
    phone = new QLineEdit( row4 );
    email = new QLineEdit( row5 );

    connect( firstName, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );
    connect( lastName, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );
    connect( email, SIGNAL( textChanged( const QString & ) ),
             this, SLOT( dataChanged( const QString & ) ) );

    addPage( page2, "Personal Data" );

    setHelpEnabled( page2, FALSE );
}

void Wizard::setupPage3()
{
    page3 = new QHBox( this );
    page3->setSpacing(8);

    QLabel *info = new QLabel( page3 );
    info->setPalette( yellow );
    info->setText( "\n"
                   "  Look here to see of  \n"
                   "  the data you entered  \n"
                   "  is correct. To confirm,  \n"
                   "  press the [Finish] button  \n"
                   "  else go back to correct  \n"
                   "  mistakes." );
    info->setIndent(8);
    info->setAlignment( AlignTop|AlignLeft );
    info->setMaximumWidth( info->sizeHint().width() );

    QVBox *page = new QVBox( page3 );

    QHBox *row1 = new QHBox( page );
    QHBox *row2 = new QHBox( page );
    QHBox *row3 = new QHBox( page );
    QHBox *row4 = new QHBox( page );
    QHBox *row5 = new QHBox( page );
    QHBox *row6 = new QHBox( page );

    QLabel *label1 = new QLabel( " Personal Key: ", row1 );
    label1->setAlignment( Qt::AlignVCenter );
    QLabel *label2 = new QLabel( " First Name: ", row2 );
    label2->setAlignment( Qt::AlignVCenter );
    QLabel *label3 = new QLabel( " Last Name: ", row3 );
    label3->setAlignment( Qt::AlignVCenter );
    QLabel *label4 = new QLabel( " Address: ", row4 );
    label4->setAlignment( Qt::AlignVCenter );
    QLabel *label5 = new QLabel( " Phone Number: ", row5 );
    label5->setAlignment( Qt::AlignVCenter );
    QLabel *label6 = new QLabel( " E-Mail: ", row6 );
    label6->setAlignment( Qt::AlignVCenter );

    label1->setMinimumWidth( label1->sizeHint().width() );
    label2->setMinimumWidth( label1->sizeHint().width() );
    label3->setMinimumWidth( label1->sizeHint().width() );
    label4->setMinimumWidth( label1->sizeHint().width() );
    label5->setMinimumWidth( label1->sizeHint().width() );
    label6->setMinimumWidth( label1->sizeHint().width() );

    lKey = new QLabel( row1 );
    lFirstName = new QLabel( row2 );
    lLastName = new QLabel( row3 );
    lAddress = new QLabel( row4 );
    lPhone = new QLabel( row5 );
    lEmail = new QLabel( row6 );

    addPage( page3, "Finish" );

    setFinishEnabled( page3, TRUE );
    setHelpEnabled( page3, FALSE );
}

void Wizard::showPage( QWidget* page )
{
    if ( page == page1 ) {
    } else if ( page == page2 ) {
    } else if ( page == page3 ) {
        lKey->setText( key->text() );
        lFirstName->setText( firstName->text() );
        lLastName->setText( lastName->text() );
        lAddress->setText( address->text() );
        lPhone->setText( phone->text() );
        lEmail->setText( email->text() );
    }

    QWizard::showPage(page);

    if ( page == page1 ) {
        keyChanged( key->text() );
        key->setFocus();
    } else if ( page == page2 ) {
        dataChanged( firstName->text() );
        firstName->setFocus();
    } else if ( page == page3 ) {
        finishButton()->setEnabled( TRUE );
        finishButton()->setFocus();
    }
}

void Wizard::keyChanged( const QString &text )
{
    QString t = text;
    int p = 0;
    bool on = ( key->validator()->validate(t, p) == QValidator::Acceptable );
    nextButton()->setEnabled( on );
}

void Wizard::dataChanged( const QString & )
{
    if ( !firstName->text().isEmpty() &&
         !lastName->text().isEmpty() &&
         !email->text().isEmpty() )
        nextButton()->setEnabled( TRUE );
    else
        nextButton()->setEnabled( FALSE );
}


wizard/wizard.h Example File

/****************************************************************************
** $Id:  qt/wizard.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef WIZARD_H
#define WIZARD_H

#include <qwizard.h>

class QWidget;
class QHBox;
class QLineEdit;
class QLabel;

class Wizard : public QWizard
{
    Q_OBJECT

public:
    Wizard( QWidget *parent = 0, const char *name = 0 );

    void showPage(QWidget* page);

protected:
    void setupPage1();
    void setupPage2();
    void setupPage3();

    QHBox *page1, *page2, *page3;
    QLineEdit *key, *firstName, *lastName, *address, *phone, *email;
    QLabel *lKey, *lFirstName, *lLastName, *lAddress, *lPhone, *lEmail;

protected slots:
    void keyChanged( const QString & );
    void dataChanged( const QString & );

};

#endif

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


Transformed Graphics Demo

This example lets the user rotate, shear and scale text and graphics arbitrarily.

Implementation:

/****************************************************************************
** $Id:  qt/xform.cpp   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include <qapplication.h>

#include <qdialog.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qlcdnumber.h>
#include <qslider.h>
#include <qmenubar.h>
#include <qfontdialog.h>
#include <qlayout.h>
#include <qvbox.h>
#include <qwidgetstack.h>

#include <qpainter.h>
#include <qpixmap.h>
#include <qpicture.h>

#include <stdlib.h>

class ModeNames {
public:
    enum Mode { Text, Image, Picture };
};

class XFormControl : public QVBox, public ModeNames
{
    Q_OBJECT
public:
    XFormControl( const QFont &initialFont, QWidget *parent=0, const char *name=0 );
   ~XFormControl() {}

    QWMatrix matrix();

signals:
    void newMatrix( QWMatrix );
    void newText( const QString& );
    void newFont( const QFont & );
    void newMode( int );
private slots:
    void newMtx();
    void newTxt(const QString&);
    void selectFont();
    void fontSelected( const QFont & );
    void changeMode(int);
    void timerEvent(QTimerEvent*);
private:
    Mode mode;
    QSlider      *rotS;                // Rotation angle scroll bar
    QSlider      *shearS;              // Shear value scroll bar
    QSlider      *magS;                // Magnification value scroll bar
    QLCDNumber   *rotLCD;              // Rotation angle LCD display
    QLCDNumber   *shearLCD;            // Shear value LCD display
    QLCDNumber   *magLCD;              // Magnification value LCD display
    QCheckBox    *mirror;              // Checkbox for mirror image on/of
    QWidgetStack* optionals;
    QLineEdit    *textEd;              // Inp[ut field for xForm text
    QPushButton  *fpb;                 // Select font push button
    QRadioButton *rb_txt;              // Radio button for text
    QRadioButton *rb_img;              // Radio button for image
    QRadioButton *rb_pic;              // Radio button for picture
    QFont currentFont;
};

/*
  ShowXForm displays a text or a pixmap (QPixmap) using a coordinate
  transformation matrix (QWMatrix)
*/

class ShowXForm : public QWidget, public ModeNames
{
    Q_OBJECT
public:
    ShowXForm( const QFont &f, QWidget *parent=0, const char *name=0 );
   ~ShowXForm() {}
    void showIt();                      // (Re)displays text or pixmap

    Mode mode() const { return m; }
public slots:
    void setText( const QString& );
    void setMatrix( QWMatrix );
    void setFont( const QFont &f );
    void setPixmap( QPixmap );
    void setPicture( const QPicture& );
    void setMode( int );
private:
    QSizePolicy sizePolicy() const;
    QSize sizeHint() const;
    void paintEvent( QPaintEvent * );
    void resizeEvent( QResizeEvent * );
    QWMatrix  mtx;                      // coordinate transform matrix
    QString   text;                     // text to be displayed
    QPixmap   pix;                      // pixmap to be displayed
    QPicture  picture;                  // text to be displayed
    QRect     eraseRect;                // covers last displayed text/pixmap
    Mode      m;
};

XFormControl::XFormControl( const QFont &initialFont,
                            QWidget *parent, const char *name )
        : QVBox( parent, name )
{
    setSpacing(6);
    setMargin(6);
    currentFont = initialFont;
    mode = Image;

    rotLCD      = new QLCDNumber( 4, this, "rotateLCD" );
    rotS        = new QSlider( QSlider::Horizontal, this,
                                  "rotateSlider" );
    shearLCD    = new QLCDNumber( 5,this, "shearLCD" );
    shearS      = new QSlider( QSlider::Horizontal, this,
                                  "shearSlider" );
    mirror      = new QCheckBox( this, "mirrorCheckBox" );
    rb_txt = new QRadioButton( this, "text" );
    rb_img = new QRadioButton( this, "image" );
    rb_pic = new QRadioButton( this, "picture" );
    optionals = new QWidgetStack(this);
    QVBox* optionals_text = new QVBox(optionals);
    optionals_text->setSpacing(6);
    QVBox* optionals_other = new QVBox(optionals);
    optionals_other->setSpacing(6);
    optionals->addWidget(optionals_text,0);
    optionals->addWidget(optionals_other,1);
    fpb         = new QPushButton( optionals_text, "text" );
    textEd      = new QLineEdit( optionals_text, "text" );
    textEd->setFocus();

    rotLCD->display( "  0'" );

    rotS->setRange( -180, 180 );
    rotS->setValue( 0 );
    connect( rotS, SIGNAL(valueChanged(int)), SLOT(newMtx()) );

    shearLCD->display( "0.00" );

    shearS->setRange( -25, 25 );
    shearS->setValue( 0 );
    connect( shearS, SIGNAL(valueChanged(int)), SLOT(newMtx()) );

    mirror->setText( tr("Mirror") );
    connect( mirror, SIGNAL(clicked()), SLOT(newMtx()) );

    QButtonGroup *bg = new QButtonGroup(this);
    bg->hide();
    bg->insert(rb_txt,0);
    bg->insert(rb_img,1);
    bg->insert(rb_pic,2);
    rb_txt->setText( tr("Text") );
    rb_img->setText( tr("Image") );
    rb_img->setChecked(TRUE);
    rb_pic->setText( tr("Picture") );
    connect( bg, SIGNAL(clicked(int)), SLOT(changeMode(int)) );

    fpb->setText( tr("Select font...") );
    connect( fpb, SIGNAL(clicked()), SLOT(selectFont()) );

    textEd->setText( "Troll" );
    connect( textEd, SIGNAL(textChanged(const QString&)),
                     SLOT(newTxt(const QString&)) );

    magLCD = new QLCDNumber( 4,optionals_other, "magLCD" );
    magLCD->display( "100" );
    magS = new QSlider( QSlider::Horizontal, optionals_other,
                           "magnifySlider" );
    magS->setRange( 0, 800 );
    connect( magS, SIGNAL(valueChanged(int)), SLOT(newMtx()) );
    magS->setValue( 0 );
    connect( magS, SIGNAL(valueChanged(int)), magLCD, SLOT(display(int)));

    optionals_text->adjustSize();
    optionals_other->adjustSize();
    changeMode(Image);

    startTimer(20); // start an initial animation
}

void XFormControl::timerEvent(QTimerEvent*)
{
    int v = magS->value();
    v = (v+2)+v/10;
    if ( v >= 200 ) {
        v = 200;
        killTimers();
    }
    magS->setValue(v);
}

/*
    Called whenever the user has changed one of the matrix parameters
    (i.e. rotate, shear or magnification)
*/
void XFormControl::newMtx()
{
    emit newMatrix( matrix() );
}

void XFormControl::newTxt(const QString& s)
{
    emit newText(s);
    changeMode(Text);
}

/*
    Calculates the matrix appropriate for the current controls,
    and updates the displays.
*/
QWMatrix XFormControl::matrix()
{
    QWMatrix m;
    if (mode != Text) {
        double magVal = 1.0*magS->value()/100;
        m.scale( magVal, magVal );
    }
    double shearVal = 1.0*shearS->value()/25;
    m.shear( shearVal, shearVal );
    m.rotate( rotS->value() );
    if ( mirror->isChecked() ) {
        m.scale( 1, -1 );
        m.rotate( 180 );
    }

    QString tmp;
    tmp.sprintf( "%1.2f", shearVal  );
    if ( shearVal >= 0 )
        tmp.insert( 0, " " );
    shearLCD->display( tmp );

    int rot = rotS->value();
    if ( rot < 0 )
        rot = rot + 360;
    tmp.sprintf( "%3i'", rot );
    rotLCD->display( tmp );
    return m;
}

void XFormControl::selectFont()
{
    bool ok;
    QFont f = QFontDialog::getFont( &ok, currentFont );
    if ( ok ) {
        currentFont = f;
        fontSelected( f );
    }
}

void XFormControl::fontSelected( const QFont &font )
{
    emit newFont( font );
    changeMode(Text);
}

/*
    Sets the mode - Text, Image, or Picture.
*/

void XFormControl::changeMode(int m)
{
    mode = (Mode)m;

    emit newMode( m );
    newMtx();
    if ( mode == Text ) {
        optionals->raiseWidget(0);
        rb_txt->setChecked(TRUE);
    } else {
        optionals->raiseWidget(1);
        if ( mode == Image )
            rb_img->setChecked(TRUE);
        else
            rb_pic->setChecked(TRUE);
    }
    qApp->flushX();
}

ShowXForm::ShowXForm( const QFont &initialFont,
                      QWidget *parent, const char *name )
        : QWidget( parent, name, WResizeNoErase )
{
    setFont( initialFont );
    setBackgroundColor( white );
    m = Text;
    eraseRect = QRect( 0, 0, 0, 0 );
}

QSizePolicy ShowXForm::sizePolicy() const
{
    return QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}

QSize ShowXForm::sizeHint() const
{
    return QSize(400,400);
}

void ShowXForm::paintEvent( QPaintEvent * )
{
    showIt();
}

void ShowXForm::resizeEvent( QResizeEvent * )
{
    eraseRect = QRect( width()/2, height()/2, 0, 0 );
    repaint(rect());
}

void ShowXForm::setText( const QString& s )
{
    text = s;
    showIt();
}

void ShowXForm::setMatrix( QWMatrix w )
{
    mtx = w;
    showIt();
}

void ShowXForm::setFont( const QFont &f )
{
    m = Text;
    QWidget::setFont( f );
}

void ShowXForm::setPixmap( QPixmap pm )
{
    pix  = pm;
    m    = Image;
    showIt();
}

void ShowXForm::setPicture( const QPicture& p )
{
    picture = p;
    m = Picture;
    showIt();
}

void ShowXForm::setMode( int mode )
{
    m = (Mode)mode;
}

void ShowXForm::showIt()
{
    QPainter p;
    QRect r;      // rectangle covering new text/pixmap in virtual coordinates
    QWMatrix um;  // copy user specified transform
    int textYPos = 0; // distance from boundingRect y pos to baseline
    int textXPos = 0; // distance from boundingRect x pos to text start
    QRect br;
    QFontMetrics fm( fontMetrics() );   // get widget font metrics
    switch ( mode() ) {
      case Text:
        br = fm.boundingRect( text );   // rectangle covering text
        r  = br;
        textYPos = -r.y();
        textXPos = -r.x();
        br.moveTopLeft( QPoint( -br.width()/2, -br.height()/2 ) );
        break;
      case Image:
        r = pix.rect();
        break;
      case Picture:
        // ### need QPicture::boundingRect()
        r = QRect(0,0,1000,1000);
        break;
    }
    r.moveTopLeft( QPoint(-r.width()/2, -r.height()/2) );
          // compute union of new and old rect
          // the resulting rectangle will cover what is already displayed
          // and have room for the new text/pixmap
    eraseRect = eraseRect.unite( mtx.map(r) );
    eraseRect.moveBy( -1, -1 ); // add border for matrix round off
    eraseRect.setSize( QSize( eraseRect.width() + 2,eraseRect.height() + 2 ) );
    int pw = QMIN(eraseRect.width(),width());
    int ph = QMIN(eraseRect.height(),height());
    QPixmap pm( pw, ph );               // off-screen drawing pixmap
    pm.fill( backgroundColor() );

    p.begin( &pm );
    um.translate( pw/2, ph/2 ); // 0,0 is center
    um = mtx * um;
    p.setWorldMatrix( um );
    switch ( mode() ) {
      case Text:
        p.setFont( font() );            // use widget font
        p.drawText( r.left() + textXPos, r.top() + textYPos, text );
#if 0
        p.setPen( red );
        p.drawRect( br );
#endif
        break;
      case Image:
        p.drawPixmap( -pix.width()/2, -pix.height()/2, pix );
        //QPixmap rotated = pix.xForm(mtx);
        //bitBlt( &pm, pm.width()/2 - rotated.width()/2,
                //pm.height()/2 - rotated.height()/2, &rotated );
        break;
      case Picture:
        // ### need QPicture::boundingRect()
        p.scale(0.25,0.25);
        p.translate(-230,-180);
        p.drawPicture( picture );
    }
    p.end();

    int xpos = width()/2  - pw/2;
    int ypos = height()/2 - ph/2;
    bitBlt( this, xpos, ypos,                   // copy pixmap to widget
            &pm, 0, 0, -1, -1 );
    eraseRect =  mtx.map( r );
}

/*
    Grand unifying widget, putting ShowXForm and XFormControl
    together.
*/

class XFormCenter : public QHBox, public ModeNames
{
    Q_OBJECT
public:
    XFormCenter( QWidget *parent=0, const char *name=0 );
public slots:
    void setFont( const QFont &f ) { sx->setFont( f ); }
    void newMode( int );
private:
    ShowXForm   *sx;
    XFormControl *xc;
};

void XFormCenter::newMode( int m )
{
    static bool first_i = TRUE;
    static bool first_p = TRUE;

    if ( sx->mode() == m )
        return;
    if ( m == Image && first_i ) {
        first_i = FALSE;
        QPixmap pm;
        if ( pm.load( "image.any" ) )
            sx->setPixmap( pm );
        return;
    }
    if ( m == Picture && first_p ) {
        first_p = FALSE;
        QPicture p;
        if (p.load( "picture.any" ))
            sx->setPicture( p );
        return;
    }
    sx->setMode(m);
}

XFormCenter::XFormCenter( QWidget *parent, const char *name )
    : QHBox( parent, name )
{
    QFont f( "Charter", 36, QFont::Bold );

    xc = new XFormControl( f, this );
    sx = new ShowXForm( f, this );
    setStretchFactor(sx,1);
    xc->setFrameStyle( QFrame::Panel | QFrame::Raised );
    xc->setLineWidth( 2 );
    connect( xc, SIGNAL(newText(const QString&)), sx,
                 SLOT(setText(const QString&)) );
    connect( xc, SIGNAL(newMatrix(QWMatrix)),
             sx, SLOT(setMatrix(QWMatrix)) );
    connect( xc, SIGNAL(newFont(const QFont&)), sx,
                 SLOT(setFont(const QFont&)) );
    connect( xc, SIGNAL(newMode(int)), SLOT(newMode(int)) );
    sx->setText( "Troll" );
    newMode( Image );
    sx->setMatrix(xc->matrix());
}

int main( int argc, char **argv )
{
    QApplication a( argc, argv );

    XFormCenter *xfc = new XFormCenter;

    a.setMainWidget( xfc );
    xfc->setCaption("Qt Example - XForm");
    xfc->show();
    return a.exec();
}

#include "xform.moc"                  // include metadata generated by the moc

See also Examples.


Qt XML Examples

The following example programs show how to use the Qt XML classes.

Outliner to show use of DOM
A tiny SAX2 parser
Demonstration of SAX2 features

Copyright © 2002 TrolltechTrademarks
Qt version 3.0.5


Walkthrough: Using SAX2 features with the Qt XML classes

This document assumes that you are familiar with namespaces in XML and the concept of a SAX2 parser. If features of SAX2 readers are new to you please read the feature section of the SAX2 document.

As a novice to the Qt XML classes it is advisable to have a look at the tiny SAX2 parser walkthrough before reading on.

This walkthrough covers two topics: First of all it shows how to set SAX2 features and secondly how to integrate the Qt XML functionality into a Qt GUI application.

The resulting application allows you to compare the output of the reader depending on how the two features http://xml.org/sax/features/namespace-prefixes and http://xml.org/sax/features/namespaces are set. To do this it shows tree views of the read XML file listing the qualified names of elements and attributes and the respective namespace URIs.

Setting features

Let's begin with the main program of the application. First the boring part: we include all the classes we need:

    #include "structureparser.h"
    #include <qapplication.h>
    #include <qfile.h>
    #include <qxml.h>
    #include <qlistview.h>
    #include <qgrid.h>
    #include <qmainwindow.h>
    #include <qlabel.h>

structureparser.h contains the API of the XML parser that we implement in structureparser.cpp.

    int main( int argc, char **argv )
    {
        QApplication app( argc, argv );

As usual we then create a Qt application object and hand command line arguments over to it.

        QFile xmlFile( argc == 2 ? argv[1] : "fnord.xml" );

If the user runs the program with one filename as an argument we process this file, otherwise we use the fnord.xml file from the example directory for demonstration purposes.

        QXmlInputSource source( &xmlFile );

We use xmlFile as the XML Input Source...

        QXmlSimpleReader reader;

... and instantiate a reader object. Later we will manipulate its features and thus influence how the XML data are read.

        QGrid * container = new QGrid( 3 );

Now let's think about presenting the output: As described in the Qt SAX2 documentation there are three valid combinations of http://xml.org/sax/features/namespace-prefixes and http://xml.org/sax/features/namespaces: TRUE/TRUE, TRUE/FALSE and FALSE/TRUE. To show the relevant output side by side of each other and mark them with three labels makes up for a grid layout consisting of three columns (and thus two lines).

        QListView * nameSpace = new QListView( container, "table_namespace" );

The most natural way of presenting XML elements is in a tree. Thus we use a listview. Its name nameSpace indicates that this one will be used to present the combination of http://xml.org/sax/features/namespaces being TRUE and http://xml.org/sax/features/namespace-prefixes being FALSE -- the default configuration of a QXmlSimpleReader.

Being the first grid entry the nameSpace listview will appear in the upper left corner of the virtual grid.

        StructureParser * handler = new StructureParser( nameSpace );

Then we create a handler that deals with the XML data read by the reader. As the provided handler class QXmlDefaultHandler simply does nothing with the data from the reader, we can't use it right away. Instead we have to subclass our own StructureParser from it.

        reader.setContentHandler( handler );

The handler serves as content handler for the reader. Note that for simplicity reasons we don't register e.g. an error handler. Thus our program will not complain about for example missing closing tags in the parsed XML document.

        reader.parse( source );

Finally we parse the document with the reader's default feature settings.

        QListView * namespacePrefix = new QListView( container,
                                                     "table_namespace_prefix" );

Now we prepare for the parsing of the same XML input source with different reader settings. The output will be presented in a second QListView, namespacePrefix. As it is the second member of the container grid it will appear in the middle of the upper grid row.

        handler->setListView( namespacePrefix );

Then we ask the handler to present the data in the namespacePrefix listview.

        reader.setFeature( "http://xml.org/sax/features/namespace-prefixes",
                           TRUE );

Now we modify the behaviour of the reader and change http://xml.org/sax/features/namespace-prefixes from the default FALSE to TRUE. The http://xml.org/sax/features/namespaces feature has still its default setting TRUE.

        source.reset();

We have to reset the input source to make the new parsing start from the beginning of the document again.

        reader.parse( source );

Finally we parse the XML file a second time with the changed reader settings (TRUE/TRUE).

        QListView * prefix = new QListView( container, "table_prefix");
        handler->setListView( prefix );
        reader.setFeature( "http://xml.org/sax/features/namespaces", FALSE );
        source.reset();
        reader.parse( source );

Next we prepare and use the upper right listview to show the reader results with the feature setting http://xml.org/sax/features/namespaces FALSE and http://xml.org/sax/features/namespace-prefixes TRUE.

        // namespace label
        (void) new QLabel(
                 "Default:\n"
                 "http://xml.org/sax/features/namespaces: TRUE\n"
                 "http://xml.org/sax/features/namespace-prefixes: FALSE\n",
                 container );

        // namespace prefix label
        (void) new QLabel(
                 "\n"
                 "http://xml.org/sax/features/namespaces: TRUE\n"
                 "http://xml.org/sax/features/namespace-prefixes: TRUE\n",
                 container );

        // prefix label
        (void) new QLabel(
                 "\n"
                 "http://xml.org/sax/features/namespaces: FALSE\n"
                 "http://xml.org/sax/features/namespace-prefixes: TRUE\n",
                 container );

The second row of the container grid is filled with three labels denoting the reader settings that belong to the above listview.

        app.setMainWidget( container );
        container->show();
        return app.exec();
    }

Same procedure as with every Qt GUI program: the grid serves as the main widget of our application and is shown. After that we enter the GUI's event loop.

The handler API

Let's have a brief look at the API of our handler class StructureParser:

    #include <qxml.h>
    #include <qptrstack.h>

    class QListView;
    class QListViewItem;
    class QString;

    class StructureParser: public QXmlDefaultHandler
    {

We derive it from the QXmlDefaultHandler class that implements a handler that simply does nothing.

    public:
        StructureParser( QListView * );

This makes it easy for us to implement only the functionality we in fact need. In our case this is the constructor that takes a QListView as an argument,

        bool startElement( const QString&, const QString&, const QString& ,
                           const QXmlAttributes& );

the function to execute at the occurrence of element start tags (inherited from QXmlContentHandler), and

        bool endElement( const QString&, const QString&, const QString& );

the code to run when an end tag occurs.

All we have to implement so far is content handling.

        void setListView( QListView * );

In addition we have a function that selects a listview for the output.

    private:
        QPtrStack<QListViewItem> stack;

Keep in mind that we write a SAX2 parser that doesn't have an object model to keep all elements and attributes in memory. To display the elements and attributes in a tree like structure we must however keep track of all elements that haven't been closed yet.

To do this we use a LIFO stack of QListItems. An element will be added to the stack when its start tag appears and removed as soon as its end tag is parsed.

        QListView * table;
    };

Apart from this we define a member variable that contains the currently used listview.

The handler itself

Now that we defined the API we have to implement the relevant functions.

    #include "structureparser.h"

    #include <qstring.h>
    #include <qlistview.h>

    StructureParser::StructureParser( QListView * t )
                    : QXmlDefaultHandler()
    {

First we have the constructor that takes a listview pointer as its argument.

        setListView( t );
    }

All we have to do here is to prepare the argument QListView before usage. This we do with the setListView() function.

    void StructureParser::setListView( QListView * t )
    {
        table = t;

First we store the argument away.

        table->setSorting( -1 );

We want the elements to be listed as they appear in the document -- and not for example sorted alphabetically. That's why we switch off sorting at all.

        table->addColumn( "Qualified name" );
        table->addColumn( "Namespace" );
    }

The listview now consists of two columns: one for the element's or attribute's qualified names and one for their namespace URIs. Columns are added from left to right and with the title as an argument.

Now let's deal with XML content handling.

    bool StructureParser::startElement( const QString& namespaceURI,
                                        const QString& ,
                                        const QString& qName,
                                        const QXmlAttributes& attributes)
    {

When we come across the start tag of an element the handler does the real work. Although startElement is called with four arguments we keep track of only three: the namespace URI of the element, its qualified name and its attributes. If an element has no namespace assigned or if the feature settings of the reader don't provide the handler with namespace URIs at all namespaceURI contains an empty string.

Note that we don't assign a variable to the second argument -- we're simply not interested in the local name of the element.

        QListViewItem * element;

Whenever an element occurs we want to show it in the listview. Therefore we define a QListViewItem variable.

        if ( ! stack.isEmpty() ){
            QListViewItem *lastChild = stack.top()->firstChild();

As long as the element stack isn't empty the current element is a child of the topmost (last unclosed) element on the stack. Thus we create a new QListViewItem as a child of QPtrStack::stack.top() with the new element's qualified name in the first column and the according namespace URI (or nothing) in the second one.

The QListViewItem is usally inserted as the first child. This means that we would get the elements in reverse order. So we first search for the last child of the QPtrStack::stack.top() element and insert it after this element.

In a valid XML document this applies to all elements except the document root.

            if ( lastChild ) {
                while ( lastChild->nextSibling() )
                    lastChild = lastChild->nextSibling();
            }
            element = new QListViewItem( stack.top(), lastChild, qName, namespaceURI );
        } else {
            element = new QListViewItem( table, qName, namespaceURI );
        }

The root element we have to handle separately because it is the first element to go onto the QListViewItem stack. Its listview item is therefore a direct child of the table listview itself.

        stack.push( element );

Now we put the element's listview item on top of the stack.

        element->setOpen( TRUE );

By default a QListView presents all of its nodes closed. The user may then click on the + icon to see the child entries.

We however want to see the entire element tree at once when we run the program. Therefore we open each listview item manually.

        if ( attributes.length() > 0 ) {

What do we do if an element has attributes?

            for ( int i = 0 ; i < attributes.length(); i++ ) {
                new QListViewItem( element, attributes.qName(i), attributes.uri(i) );
            }
        }

For each of them we create a new listview item to present the attribute's qualified name and the relevant namespace URI (or nothing). Obviously attribute is a child of the current element.

        return TRUE;
    }

To prevent the reader from throwing an error we have to return TRUE when we successfully dealt with an element's start tag.

    bool StructureParser::endElement( const QString&, const QString&,
                                      const QString& )
    {
        stack.pop();

Whenever we come across an element's closing tag we have to remove its listview item from the stack as it can't have children any longer.

        return TRUE;
    }

And so we're done.

See also Step-by-step Examples.


Walkthrough: How to use the Qt SAX2 classes

For a general discussion of the XML topics in Qt please refer to the document XML Module. To learn more about SAX2 see the document describing the Qt SAX2 implementation.

Before reading on you should at least be familiar with the Introduction to SAX2.

A tiny parser

In this section we will present a small example reader that outputs the names of all elements in an XML document on the command line. The element names are indented corresponding to their nesting level.

As mentioned in Introduction to SAX2 we have to implement the functions of the handler classes that we are interested in. In our case these are only three: QXmlContentHandler::startDocument(), QXmlContentHandler::startElement() and QXmlContentHandler::endElement().

For this purpose we use a subclass of the QXmlDefaultHandler (remember that the special handler classes are all abstract and the default handler class provides an implementation that does not change the parsing behavior):

/****************************************************************************
** $Id:  qt/structureparser.h   3.0.5   edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef STRUCTUREPARSER_H
#define STRUCTUREPARSER_H

#include <qxml.h>

class QString;

class StructureParser : public QXmlDefaultHandler
{
public:
    bool startDocument();
    bool startElement( const QString&, const QString&, const QString& ,
                       const QXmlAttributes& );
    bool endElement( const QString&, const QString&, const QString& );

private:
    QString indent;
};

#endif

Apart from the private helper variable indent that we will use to get indentation right, there is nothing special about our new StructureParser class.

Even the implementation is straight-forward:

    #include "structureparser.h"

    #include <stdio.h>
    #include <qstring.h>

First we overload QXmlContentHandler::startDocument() with a non-empty version.

    bool StructureParser::startDocument()
    {
        indent = "";
        return TRUE;
    }

At the beginning of the document we simply set indent to an empty string because we want to print out the root element without any indentation. Also we return TRUE so that the parser continues without reporting an error.

Because we want to be informed when the parser comes accross a start tag of an element and subsequently print it out, we have to overload QXmlContentHandler::startElement().

    bool StructureParser::startElement( const QString&, const QString&,
                                        const QString& qName,
                                        const QXmlAttributes& )
    {
        printf( "%s%s\n", (const char*)indent, (const char*)qName );
        indent += "    ";
        return TRUE;
    }

This is what the implementation does: The name of the element with preceding indentation is printed out followed by a linebreak. Strictly speaking qName contains the local element name without an eventual prefix denoting the namespace.

If another element follows before the current element's end tag it should be indented. Therefore we add four spaces to the indent string.

Finally we return TRUE in order to let the parser continue without errors.

The last functionality we need to add is the parser's behaviour when an end tag occurs. This means overloading QXmlContentHandler::endElement().

    bool StructureParser::endElement( const QString&, const QString&, const QString& )
    {
        indent.remove( 0, 4 );
        return TRUE;
    }

Obviously we then should shorten the indent string by the four whitespaces added in startElement().

With this we're done with our parser and can start writing the main() program.

    #include "structureparser.h"
    #include <qfile.h>
    #include <qxml.h>

    #include <qwindowdefs.h>

    int main( int argc, char **argv )
    {
        if ( argc < 2 ) {
            fprintf( stderr, "Usage: %s <xmlfile>\n", argv[0] );
            return 1;
        }
        for ( int i=1; i < argc; i++ ) {

Successively we deal with all files given as command line arguments.

            StructureParser handler;

The next step is to create an instance of the StructureParser.

            QFile xmlFile( argv[i] );
            QXmlInputSource source( &xmlFile );

Then we create a QXmlInputSource for the XML file to be parsed.

            QXmlSimpleReader reader;
            reader.setContentHandler( &handler );

After that we set up the reader. As our StructureParser class deals with QXmlContentHandler functionality only we simply register it as the content handler of our choice.

            reader.parse( source );

Now we take our input source and start parsing.

        }
        return 0;
    }

Running the program on the following XML file...

<animals>
<mammals>
  <monkeys> <gorilla/> <orang-utan/> </monkeys>
</mammals>
<birds> <pigeon/> <penguin/> </birds>
</animals>

... produces the following output:

animals
    mammals
        monkeys
            gorilla
            orang-utan
    birds
        pigeon
        penguin

It will however refuse to produce the correct result if you e.g. insert a whitespace between a < and the element name in your test-XML file. To prevent such annoyances you should always install an error handler with QXmlReader::setErrorHandler(). This allows you to report parsing errors to the user.

See also Step-by-step Examples.


XML

These classes are relevant to XML users.

QDomAttr | Represents one attribute of a QDomElement
QDomCDATASection | Represents an XML CDATA section
QDomCharacterData | Represents a generic string in the DOM
QDomComment | Represents an XML comment
QDomDocument | Represents an XML document
QDomDocumentFragment | Tree of QDomNodes which is not usually a complete QDomDocument
QDomDocumentType | The representation of the DTD in the document tree
QDomElement | Represents one element in the DOM tree
QDomEntity | Represents an XML entity
QDomEntityReference | Represents an XML entity reference
QDomImplementation | Information about the features of the DOM implementation
QDomNamedNodeMap | Collection of nodes that can be accessed by name
QDomNode | The base class for all the nodes in a DOM tree
QDomNodeList | List of QDomNode objects
QDomNotation | Represents an XML notation
QDomProcessingInstruction | Represents an XML processing instruction
QDomText | Represents text data in the parsed XML document
QXmlAttributes | XML attributes
QXmlContentHandler | Interface to report the logical content of XML data
QXmlDeclHandler | Interface to report declaration content of XML data
QXmlDefaultHandler | Default implementation of all XML handler classes
QXmlDTDHandler | Interface to report DTD content of XML data
QXmlEntityResolver | Interface to resolve external entities contained in XML data
QXmlErrorHandler | Interface to report errors in XML data
QXmlInputSource | The input data for the QXmlReader subclasses
QXmlLexicalHandler | Interface to report the lexical content of XML data
QXmlLocator | The XML handler classes with information about the parsing position within a file
QXmlNamespaceSupport | Helper class for XML readers which want to include namespace support
QXmlParseException | Used to report errors with the QXmlErrorHandler interface
QXmlReader | Interface for XML readers (i.e. parsers)
QXmlSimpleReader | Implementation of a simple XML reader (parser)