diff options
author | Alexis Menard <alexis.menard@nokia.com> | 2009-04-17 14:06:06 (GMT) |
---|---|---|
committer | Alexis Menard <alexis.menard@nokia.com> | 2009-04-17 14:06:06 (GMT) |
commit | f15b8a83e2e51955776a3f07cb85ebfc342dd8ef (patch) | |
tree | c5dc684986051654898db11ce73e03b9fec8db99 /doc/src/snippets/code | |
download | Qt-f15b8a83e2e51955776a3f07cb85ebfc342dd8ef.zip Qt-f15b8a83e2e51955776a3f07cb85ebfc342dd8ef.tar.gz Qt-f15b8a83e2e51955776a3f07cb85ebfc342dd8ef.tar.bz2 |
Initial import of statemachine branch from the old kinetic repository
Diffstat (limited to 'doc/src/snippets/code')
416 files changed, 26334 insertions, 0 deletions
diff --git a/doc/src/snippets/code/doc.src.qtscripttools.qdoc b/doc/src/snippets/code/doc.src.qtscripttools.qdoc new file mode 100644 index 0000000..c691f17 --- /dev/null +++ b/doc/src/snippets/code/doc.src.qtscripttools.qdoc @@ -0,0 +1,8 @@ +//! [0] + #include <QtScriptTools> +//! [0] + + +//! [1] + QT += scripttools +//! [1] diff --git a/doc/src/snippets/code/doc_src_activeqt-dumpcpp.qdoc b/doc/src/snippets/code/doc_src_activeqt-dumpcpp.qdoc new file mode 100644 index 0000000..df1d542 --- /dev/null +++ b/doc/src/snippets/code/doc_src_activeqt-dumpcpp.qdoc @@ -0,0 +1,25 @@ +//! [0] +Outlook::Application *outlook = new Outlook::Application; +//! [0] + + +//! [1] +Outlook::_NameSpace *session = outlook->Session(); +//! [1] + + +//! [2] +Outlook::NameSpace *session = outlook->Session(); +//! [2] + + +//! [3] +Outlook::_NameSpace *tmp = outlook->Session(); +Outlook::NameSpace *session = new Outlook::NameSpace(tmp); +delete tmp; // or any other use of tmp: segfault +//! [3] + + +//! [4] +Outlook::NameSpace *session = new Outlook::NameSpace(outlook->Session()); +//! [4] diff --git a/doc/src/snippets/code/doc_src_appicon.qdoc b/doc/src/snippets/code/doc_src_appicon.qdoc new file mode 100644 index 0000000..c8883fe --- /dev/null +++ b/doc/src/snippets/code/doc_src_appicon.qdoc @@ -0,0 +1,23 @@ +//! [0] +IDI_ICON1 ICON DISCARDABLE "myappico.ico" +//! [0] + + +//! [1] +RC_FILE = myapp.rc +//! [1] + + +//! [2] +ICON = myapp.icns +//! [2] + + +//! [3] +kde-config --path icon +//! [3] + + +//! [4] +gnome-config --datadir +//! [4] diff --git a/doc/src/snippets/code/doc_src_assistant-manual.qdoc b/doc/src/snippets/code/doc_src_assistant-manual.qdoc new file mode 100644 index 0000000..383bd61 --- /dev/null +++ b/doc/src/snippets/code/doc_src_assistant-manual.qdoc @@ -0,0 +1,110 @@ +//! [0] +assistant -collectionFile file +//! [0] + + +//! [1] +<?xml version="1.0" encoding="utf-8" ?> +<QHelpCollectionProject version="1.0"> + <assistant> + <title>My Application Help</title> + <startPage>qthelp://com.mycompany.1_0_0/doc/index.html</startPage> + <currentFilter>myfilter</currentFilter> + <applicationIcon>application.png</applicationIcon> + <enableFilterFunctionality>false</enableFilterFunctionality> + <enableDocumentationManager>false</enableDocumentationManager> + <enableAddressBar visible="true">true</enableAddressBar> + <cacheDirectory>mycompany/myapplication</cacheDirectory> + <aboutMenuText> + <text>About My Application</text> + <text language="de">Über meine Applikation...</text> + </aboutMenuText> + <aboutDialog> + <file>about.txt</file> + <file language="de">ueber.txt</file> + <icon>about.png</icon> + </aboutDialog> + </assistant> + <docFiles> + <generate> + <file> + <input>myapplication-manual.qhp</input> + <output>myapplication-manual.qch</output> + </file> + </generate> + <register> + <file>myapplication-manual.qch</file> + </register> + </docFiles> +</QHelpCollectionProject> +//! [1] + + +//! [2] +QProcess *process = new QProcess; +QStringList args; +args << QLatin1String("-collectionFile") + << QLatin1String("mycollection.qhc") + << QLatin1String("-enableRemoteControl"); +process->start(QLatin1String("assistant"), args); +if (!process->waitForStarted()) + return; +//! [2] + + +//! [3] +QByteArray ba; +ba.append("setSource qthelp://com.mycompany.1_0_0/doc/index.html"); +ba.append('\0'); +process->write(ba); +//! [3] + + +//! [4] +QByteArray ba; +ba.append("hide bookmarks;"); +ba.append("hide index;"); +ba.append("setSource qthelp://com.mycompany.1_0_0/doc/index.html"); +ba.append('\0'); +process->write(ba); +//! [4] + +//! [5] +<?xml version="1.0" encoding="utf-8" ?> +<QHelpCollectionProject version="1.0"> + ... + <docFiles> + <register> + <file>myapplication-manual.qch</file> + <file>another-manual.qch</file> + </register> + </docFiles> +</QHelpCollectionProject> +//! [5] + +//! [6] +assistant -collectionFile mycollection.qhc -register myapplication-manual.qch +//! [6] + +//! [7] +<?xml version="1.0" encoding="utf-8" ?> +<QHelpCollectionProject version="1.0"> + <assistant> + <title>My Application Help</title> + <cacheDirectory>mycompany/myapplication</cacheDirectory> + ... + </assistant> +</QHelpCollectionProject> +//! [7] + +//! [8] +assistant -collectionFile mycollection.qhc +//! [8] + +//! [9] +%QDesktopServices::DataLocation%/mycompany/myapplication/mycollection.qhc +//! [9] + +//! [10] +qcollectiongenerator mycollection.qhcp -o mycollection.qhc +//! [10] diff --git a/doc/src/snippets/code/doc_src_atomic-operations.qdoc b/doc/src/snippets/code/doc_src_atomic-operations.qdoc new file mode 100644 index 0000000..acda5e4 --- /dev/null +++ b/doc/src/snippets/code/doc_src_atomic-operations.qdoc @@ -0,0 +1,71 @@ +//! [0] +if (*ptr == expected) { + *ptr = newval; + return !0; +} +return 0; +//! [0] + + +//! [1] +if (*ptr == expected) { + *ptr = newval; + return !0; +} +return 0; +//! [1] + + +//! [2] +++(*ptr); +return *ptr ? !0 : 0; +//! [2] + + +//! [3] +return ++(*ptr); +//! [3] + + +//! [4] +++(*ptr); +return !(ControlRegister & ZeroFlag); +//! [4] + + +//! [5] +--(*ptr); +return *ptr ? : 0; +//! [5] + + +//! [6] +return --(*ptr); +//! [6] + + +//! [7] +--(*ptr); +return !(ControlRegister & ZeroFlag); +//! [7] + + +//! [8] +tmp = *ptr; +*ptr = newval; +return tmp; +//! [8] + + +//! [9] +tmp = *ptr; +*ptr = newval; +return tmp; +//! [9] + + +//! [10] +tmp = *ptr; +*ptr += value; +return tmp; +//! [10] diff --git a/doc/src/snippets/code/doc_src_compiler-notes.qdoc b/doc/src/snippets/code/doc_src_compiler-notes.qdoc new file mode 100644 index 0000000..12095d0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_compiler-notes.qdoc @@ -0,0 +1,8 @@ +//! [0] +QTDIR=C:\Progra~1\Qt +//! [0] + + +//! [1] +/usr/vacpp/bin/makeC++SharedLib -o shr1.o cplussource1.o +//! [1] diff --git a/doc/src/snippets/code/doc_src_containers.qdoc b/doc/src/snippets/code/doc_src_containers.qdoc new file mode 100644 index 0000000..9d6ba8d --- /dev/null +++ b/doc/src/snippets/code/doc_src_containers.qdoc @@ -0,0 +1,235 @@ +//! [0] +class Employee +{ +public: + Employee() {} + Employee(const Employee &other); + + Employee &operator=(const Employee &other); + +private: + QString myName; + QDate myDateOfBirth; +}; +//! [0] + + +//! [1] +QList<QString> list; +list << "A" << "B" << "C" << "D"; + +QListIterator<QString> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [1] + + +//! [2] +QListIterator<QString> i(list); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [2] + + +//! [3] +QMutableListIterator<int> i(list); +while (i.hasNext()) { + if (i.next() % 2 != 0) + i.remove(); +} +//! [3] + + +//! [4] +QMutableListIterator<int> i(list); +i.toBack(); +while (i.hasPrevious()) { + if (i.previous() % 2 != 0) + i.remove(); +} +//! [4] + + +//! [5] +QMutableListIterator<int> i(list); +while (i.hasNext()) { + if (i.next() > 128) + i.setValue(128); +} +//! [5] + + +//! [6] +QMutableListIterator<int> i(list); +while (i.hasNext()) + i.next() *= 2; +//! [6] + + +//! [7] +QMap<QString, QString> map; +map.insert("Paris", "France"); +map.insert("Guatemala City", "Guatemala"); +map.insert("Mexico City", "Mexico"); +map.insert("Moscow", "Russia"); +... + +QMutableMapIterator<QString, QString> i(map); +while (i.hasNext()) { + if (i.next().key().endsWith("City")) + i.remove(); +} +//! [7] + + +//! [8] +QMap<int, QWidget *> map; +QHash<int, QWidget *> hash; + +QMapIterator<int, QWidget *> i(map); +while (i.hasNext()) { + i.next(); + hash.insert(i.key(), i.value()); +} +//! [8] + + +//! [9] +QMutableMapIterator<int, QWidget *> i(map); +while (i.findNext(widget)) + i.remove(); +//! [9] + + +//! [10] +QList<QString> list; +list << "A" << "B" << "C" << "D"; + +QList<QString>::iterator i; +for (i = list.begin(); i != list.end(); ++i) + *i = (*i).toLower(); +//! [10] + + +//! [11] +QList<QString> list; +list << "A" << "B" << "C" << "D"; + +QList<QString>::iterator i = list.end(); +while (i != list.begin()) { + --i; + *i = (*i).toLower(); +} +//! [11] + + +//! [12] +QList<QString>::const_iterator i; +for (i = list.constBegin(); i != list.constEnd(); ++i) + qDebug() << *i; +//! [12] + + +//! [13] +QMap<int, int> map; +... +QMap<int, int>::const_iterator i; +for (i = map.constBegin(); i != map.constEnd(); ++i) + qDebug() << i.key() << ":" << i.value(); +//! [13] + + +//! [14] +// RIGHT +const QList<int> sizes = splitter->sizes(); +QList<int>::const_iterator i; +for (i = sizes.begin(); i != sizes.end(); ++i) + ... + +// WRONG +QList<int>::const_iterator i; +for (i = splitter->sizes().begin(); + i != splitter->sizes().end(); ++i) + ... +//! [14] + + +//! [15] +QLinkedList<QString> list; +... +QString str; +foreach (str, list) + qDebug() << str; +//! [15] + + +//! [16] +QLinkedList<QString> list; +... +QLinkedListIterator<QString> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [16] + + +//! [17] +QLinkedList<QString> list; +... +foreach (QString str, list) + qDebug() << str; +//! [17] + + +//! [18] +QLinkedList<QString> list; +... +foreach (QString str, list) { + if (str.isEmpty()) + break; + qDebug() << str; +} +//! [18] + + +//! [19] +QMap<QString, int> map; +... +foreach (QString str, map.keys()) + qDebug() << str << ":" << map.value(str); +//! [19] + + +//! [20] +QMultiMap<QString, int> map; +... +foreach (QString str, map.uniqueKeys()) { + foreach (int i, map.values(str)) + qDebug() << str << ":" << i; +} +//! [20] + + +//! [21] +forever { + ... +} +//! [21] + + +//! [22] +CONFIG += no_keywords +//! [22] + + +//! [23] +QString onlyLetters(const QString &in) +{ + QString out; + for (int j = 0; j < in.size(); ++j) { + if (in[j].isLetter()) + out += in[j]; + } + return out; +} +//! [23] diff --git a/doc/src/snippets/code/doc_src_coordsys.qdoc b/doc/src/snippets/code/doc_src_coordsys.qdoc new file mode 100644 index 0000000..4674e75 --- /dev/null +++ b/doc/src/snippets/code/doc_src_coordsys.qdoc @@ -0,0 +1,47 @@ +//! [0] +QPainter painter(this); + +painter.setPen(Qt::darkGreen); +painter.drawRect(1, 2, 6, 4); +//! [0] + + +//! [1] +QPainter painter(this); + +painter.setPen(Qt::darkGreen); +painter.drawLine(2, 7, 6, 1); +//! [1] + + +//! [2] +QPainter painter(this); +painter.setRenderHint( + QPainter::Antialiasing); +painter.setPen(Qt::darkGreen); +painter.drawRect(1, 2, 6, 4); +//! [2] + + +//! [3] +QPainter painter(this); +painter.setRenderHint( + QPainter::Antialiasing); +painter.setPen(Qt::darkGreen); +painter.drawLine(2, 7, 6, 1); +//! [3] + + +//! [4] +QPainter painter(this); +painter.setWindow(QRect(-50, -50, 100, 100)); +//! [4] + + +//! [5] +int side = qMin(width(), height()) +int x = (width() - side / 2); +int y = (height() - side / 2); + +painter.setViewport(x, y, side, side); +//! [5] diff --git a/doc/src/snippets/code/doc_src_debug.qdoc b/doc/src/snippets/code/doc_src_debug.qdoc new file mode 100644 index 0000000..0e8a1c5 --- /dev/null +++ b/doc/src/snippets/code/doc_src_debug.qdoc @@ -0,0 +1,24 @@ +//! [0] +qDebug() << "Widget" << widget << "at position" << widget->pos(); +//! [0] + + +//! [1] +char *alloc(int size) +{ + Q_ASSERT(size > 0); + char *ptr = new char[size]; + Q_CHECK_PTR(ptr); + return ptr; +} +//! [1] + + +//! [2] +char *alloc(int size) +{ + char *ptr; + Q_CHECK_PTR(ptr = new char[size]); // WRONG + return ptr; +} +//! [2] diff --git a/doc/src/snippets/code/doc_src_deployment.qdoc b/doc/src/snippets/code/doc_src_deployment.qdoc new file mode 100644 index 0000000..844041a --- /dev/null +++ b/doc/src/snippets/code/doc_src_deployment.qdoc @@ -0,0 +1,409 @@ +//! [0] +cd /path/to/Qt +./configure -static -prefix /path/to/Qt <other parameters> +make sub-src +//! [0] + + +//! [1] +cd /path/to/Qt/examples/tools/plugandpaint +//! [1] + + +//! [2] +make clean +PATH=/path/to/Qt/bin:$PATH +export PATH +qmake -config release +make +//! [2] + + +//! [3] +ldd ./application +//! [3] + + +//! [4] +cd /path/to/Qt/examples/tools/plugandpaint +//! [4] + + +//! [5] +make clean +qmake -config release +make +//! [5] + + +//! [6] +cd ../plugandpaintplugins +make clean +qmake -config release +make +//! [6] + + +//! [7] +#!/bin/sh +appname=`basename $0 | sed s,\.sh$,,` + +dirname=`dirname $0` +tmp="${dirname#?}" + +if [ "${dirname%$tmp}" != "/" ]; then +dirname=$PWD/$dirname +fi +LD_LIBRARY_PATH=$dirname +export LD_LIBRARY_PATH +$dirname/$appname $* +//! [7] + + +//! [8] +DESTDIR = /path/to/Qt/plugandpaint/plugins +//! [8] + + +//! [9] +qApp->addLibraryPath("/some/other/path"); +//! [9] + + +//! [10] +ldd ./application +//! [10] + + +//! [11] +cd C:\path\to\Qt +configure -static <any other options you need> +//! [11] + + +//! [12] +nmake sub-src +//! [12] + + +//! [13] +cd examples\tools\plugandpaint +//! [13] + + +//! [14] +nmake clean +qmake -config release +nmake +//! [14] + + +//! [15] +cd examples\tools\plugandpaint +//! [15] + + +//! [16] +nmake clean +qmake -config release +nmake +//! [16] + + +//! [17] +cd ..\plugandpaintplugins +nmake clean +qmake -config release +nmake +//! [17] + + +//! [18] +plugins\pnp_basictools.dll +plugins\pnp_extrafilters.dll +//! [18] + + +//! [19] +qApp->addLibraryPath("C:\some\other\path"); +//! [19] + + +//! [20] +embed_manifest_dll +embed_manifest_exe +//! [20] + + +//! [21] +CONFIG += embed_manifest_exe +//! [21] + + +//! [22] +<Visual Studio Install Path>\VC\redist\<Architecture>\Microsoft.VC80.CRT +//! [22] + + +//! [23] +CONFIG-=embed_manifest_dll +//! [23] + + +//! [24] +depends <application executable> +//! [24] + + +//! [25] +C:<path to Qt>\plugins +//! [25] + + +//! [26] +CONFIG-=app_bundle +//! [26] + + +//! [27] +cd /path/to/Qt +./configure -static <other parameters> +make sub-src +//! [27] + + +//! [28] +cd /path/to/Qt/examples/tools/plugandpaint +//! [28] + + +//! [29] +make clean +qmake -config release +make +//! [29] + + +//! [30] +otool -L plugandpaint.app/Contents/MacOs/plugandpaint +//! [30] + + +//! [31] +plugandpaint.app/Contents/MacOS/plugandpaint: +/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon + (compatibility version 2.0.0, current version 128.0.0) +/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime + (compatibility version 1.0.0, current version 10.0.0) +/usr/lib/libz.1.dylib + (compatibility version 1.0.0, current version 1.2.3) +/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices + (compatibility version 1.0.0, current version 22.0.0) +/usr/lib/libstdc++.6.dylib + (compatibility version 7.0.0, current version 7.3.0) +/usr/lib/libgcc_s.1.dylib + (compatibility version 1.0.0, current version 1.0.0) +/usr/lib/libmx.A.dylib + (compatibility version 1.0.0, current version 92.0.0) +/usr/lib/libSystem.B.dylib + (compatibility version 1.0.0, current version 88.0.0) +//! [31] + + +//! [32] +-lQtGui +//! [32] + + +//! [33] +/where/static/qt/lib/is/libQtGui.a +//! [33] + + +//! [34] +cd /path/to/Qt/examples/tools/plugandpaint +//! [34] + + +//! [35] +make clean +qmake -config release +make +//! [35] + + +//! [36] +cd ../plugandpaintplugins +make clean +qmake -config release +make +//! [36] + + +//! [37] +otool -L QtGui.framework/QtGui +//! [37] + + +//! [38] +QtGui.framework/QtGui: +/path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui + (compatibility version 4.0.0, current version 4.0.1) +/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon + (compatibility version 2.0.0, current version 128.0.0) +/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime + (compatibility version 1.0.0, current version 10.0.0) +/path/to/Qt/QtCore.framework/Versions/4.0/QtCore + (compatibility version 4.0.0, current version 4.0.1) +/usr/lib/libz.1.dylib + (compatibility version 1.0.0, current version 1.2.3) +/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices + (compatibility version 1.0.0, current version 22.0.0) +/usr/lib/libstdc++.6.dylib + (compatibility version 7.0.0, current version 7.3.0) +/usr/lib/libgcc_s.1.dylib + (compatibility version 1.0.0, current version 1.0.0) +/usr/lib/libmx.A.dylib + (compatibility version 1.0.0, current version 92.0.0) +/usr/lib/libSystem.B.dylib + (compatibility version 1.0.0, current version 88.0.0) +//! [38] + + +//! [39] +mkdir plugandpaint.app/Contents/Frameworks +cp -R /path/to/Qt/lib/QtCore.framework + plugandpaint.app/Contents/Frameworks +cp -R /path/to/Qt/lib/QtGui.framework + plugandpaint.app/Contents/Frameworks +//! [39] + + +//! [40] +install_name_tool -id @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore + plugandpaint.app/Contents/Frameworks/QtCore.framework/Versions/4.0/QtCore +install_name_tool -id @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui + plugandpaint.app/Contents/Frameworks/QtGui.framework/Versions/4.0/QtGui +//! [40] + + +//! [41] +install_name_tool -change path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore + @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore + plugandpaint.app/Contents/MacOs/plugandpaint +install_name_tool -change path/to/qt/lib/QtGui.framework/Versions/4.0/QtGui + @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui + plugandpaint.app/Contents/MacOs/plugandpaint +//! [41] + + +//! [42] +install_name_tool -change path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore + @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore + plugandpaint.app/Contents/Frameworks/QtGui.framework/Versions/4.0/QtGui +//! [42] + + +//! [43] +mv plugins plugandpaint.app/Contents +//! [43] + + +//! [44] +libpnp_basictools.dylib: +libpnp_basictools.dylib + (compatibility version 0.0.0, current version 0.0.0) +/path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui + (compatibility version 4.0.0, current version 4.0.1) +/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon + (compatibility version 2.0.0, current version 128.0.0) +/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime + (compatibility version 1.0.0, current version 10.0.0) +/path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore + (compatibility version 4.0.0, current version 4.0.1) +/usr/lib/libz.1.dylib + (compatibility version 1.0.0, current version 1.2.3) +/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices + (compatibility version 1.0.0, current version 22.0.0) +/usr/lib/libstdc++.6.dylib + (compatibility version 7.0.0, current version 7.3.0) +/usr/lib/libgcc_s.1.dylib + (compatibility version 1.0.0, current version 1.0.0) +/usr/lib/libmx.A.dylib + (compatibility version 1.0.0, current version 92.0.0) +/usr/lib/libSystem.B.dylib + (compatibility version 1.0.0, current version 88.0.0) +//! [44] + + +//! [45] +install_name_tool -change /path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore + @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore + plugandpaint.app/Contents/plugins/libpnp_basictools.dylib +install_name_tool -change /path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui + @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui + plugandpaint.app/Contents/plugins/libpnp_basictools.dylib +//! [45] + + +//! [46] +#elif defined(Q_OS_MAC) +if (pluginsDir.dirName() == "MacOS") { + pluginsDir.cdUp(); +} +#endif +//! [46] + + +//! [47] +cp -R /path/to/Qt/plugins/imageformats + pluginandpaint.app/Contents/plugins +//! [47] + + +//! [48] +install_name_tool -change /path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui + @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui + plugandpaint.app/Contents/plugins/imageformats/libqjpeg.dylib +install_name_tool -change /path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore + @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore + plugandpaint.app/Contents/plugins/imageformats/libqjpeg.dylib +//! [48] + + +//! [49] +QDir dir(QApplication::applicationDirPath()); +dir.cdUp(); +dir.cd("plugins"); +QApplication::setLibraryPaths(QStringList(dir.absolutePath())); +//! [49] + + +//! [50] +otool -L MyApp.app/Contents/MacOS/MyApp +//! [50] + + +//! [51] +QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.3 +//! [51] + +//! [51a] +install_name_tool -change /System/Library/Frameworks/CoreVideo.framework/ +Versions/A/CoreVideo /System/Library/Frameworks/QuartzCore.framework/ +Versions/A/QuartzCore libphonon_qt7.dylib +//! [51a] + +//! [51b] +./CONFIGURE - SDK MacOSX10.4u.sdk +//! [51b] + +//! [52] +./configure (other arguments) -universal -sdk /Developer/SDKs/MacOSX10.4u.sdk +//! [52] + + +//! [53] +QMAKE_MAC_SDK=/Developer/SDKs/MacOSX10.4u.sdk +CONFIG+=x86 ppc +//! [53] diff --git a/doc/src/snippets/code/doc_src_designer-manual.qdoc b/doc/src/snippets/code/doc_src_designer-manual.qdoc new file mode 100644 index 0000000..6730815 --- /dev/null +++ b/doc/src/snippets/code/doc_src_designer-manual.qdoc @@ -0,0 +1,98 @@ +//! [0] +CONFIG += uitools +//! [0] + + +//! [1] +#include <QtUiTools> +//! [1] + + +//! [2] +void on_<object name>_<signal name>(<signal parameters>); +//! [2] + + +//! [3] +CONFIG += release +//! [3] + + +//! [4] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [4] + + +//! [5] +QT += script +//! [5] + + +//! [6] +widget.text = 'Hi - I was built ' + new Date().toString(); +//! [6] + + +//! [7] +class MyExtension: public QObject, + public QdesignerContainerExtension +{ + Q_OBJECT + Q_INTERFACE(QDesignerContainerExtension) + + ... +} +//! [7] + + +//! [8] +QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + if (iid != Q_TYPEID(QDesignerContainerExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*> + (object)) + return new MyContainerExtension(widget, parent); + + return 0; +} +//! [8] + + +//! [9] +QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) { + return new MyContainerExtension(widget, parent); + + } else { + return 0; + } +} +//! [9] + + +//! [10] +void MyPlugin::initialize(QDesignerFormEditorInterface *formEditor) +{ + if (initialized) + return; + + QExtensionManager *manager = formEditor->extensionManager(); + Q_ASSERT(manager != 0); + + manager->registerExtensions(new MyExtensionFactory(manager), + Q_TYPEID(QDesignerTaskMenuExtension)); + + initialized = true; +} +//! [10] diff --git a/doc/src/snippets/code/doc_src_dnd.qdoc b/doc/src/snippets/code/doc_src_dnd.qdoc new file mode 100644 index 0000000..40df804 --- /dev/null +++ b/doc/src/snippets/code/doc_src_dnd.qdoc @@ -0,0 +1,34 @@ +//! [0] +void MyQt3Widget::customStartDragFunction() +{ + QDragObject *d = new QTextDrag( myHighlightedText(), this ); + d->dragCopy(); + // do NOT delete d. +} +//! [0] + + +//! [1] +void MyQt3Widget::dragEnterEvent(QDragEnterEvent* event) +{ + event->accept( + QTextDrag::canDecode(event) || + QImageDrag::canDecode(event) + ); +} +//! [1] + + +//! [2] +void MyQt3Widget::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()); + } +} +//! [2] diff --git a/doc/src/snippets/code/doc_src_emb-charinput.qdoc b/doc/src/snippets/code/doc_src_emb-charinput.qdoc new file mode 100644 index 0000000..2539e13 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-charinput.qdoc @@ -0,0 +1,20 @@ +//! [0] +./configure -help +//! [0] + + +//! [1] +configure -qt-kbd-s15000 +//! [1] + + +//! [2] +export QWS_KEYBOARD=<driver>[:<driver specific options>] +//! [2] + + +//! [3] +export QWS_KEYBOARD="<driver>[:<driver specific options>] + <driver>[:<driver specific options>] + <driver>[:<driver specific options>]" +//! [3] diff --git a/doc/src/snippets/code/doc_src_emb-crosscompiling.qdoc b/doc/src/snippets/code/doc_src_emb-crosscompiling.qdoc new file mode 100644 index 0000000..3791bfc --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-crosscompiling.qdoc @@ -0,0 +1,36 @@ +//! [0] +export PATH=path/to/cross/compiler:$PATH +//! [0] + + +//! [1] +./configure -embedded arm -xplatform qws/linux-arm-g++ <other options> +//! [1] + + +//! [2] +cp path/to/QtEmbedded/mkspecs/qws/linux-mips-g++/... + path/to/QtEmbedded/mkspecs/qws/linux-myarchitecture-g++/... +//! [2] + + +//! [3] +cd path/to/QtEmbedded +./configure -embedded <architecture> -qt-kbd-<keyboarddriver> + -qt-mouse-<mousedriver> -qt-gfx-<screendriver> +//! [3] + + +//! [4] +cd path/to/QtEmbedded +./configure <other options> + -L /path/to/libjpeg/libraries -I /path/to/libjpeg/headers +//! [4] + + +//! [5] +cd path/to/myApplication +qmake -project +qmake +make +//! [5] diff --git a/doc/src/snippets/code/doc_src_emb-envvars.qdoc b/doc/src/snippets/code/doc_src_emb-envvars.qdoc new file mode 100644 index 0000000..c242ff3 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-envvars.qdoc @@ -0,0 +1,38 @@ +//! [0] +export QWS_DISPLAY=<driver>[:<driver specific options>]... + [:<display num>] +//! [0] + + +//! [1] +export QWS_SIZE=<width>x<height> +//! [1] + + +//! [2] +export QWS_MOUSE_PROTO=<driver>[:<driver specific options>] +//! [2] + + +//! [3] +export QWS_MOUSE_PROTO="<driver>[:<driver specific options>] + <driver>[:<driver specific options>] + <driver>[:<driver specific options>]" +//! [3] + + +//! [4] +export QWS_MOUSE_PROTO="Vr41xx:press=500:/dev/misc/ts" +//! [4] + + +//! [5] +export QWS_KEYBOARD=<driver>[:<driver specific options>] +//! [5] + + +//! [6] +export QWS_KEYBOARD="<driver>[:<driver specific options>] + <driver>[:<driver specific options>] + <driver>[:<driver specific options>]" +//! [6] diff --git a/doc/src/snippets/code/doc_src_emb-features.qdoc b/doc/src/snippets/code/doc_src_emb-features.qdoc new file mode 100644 index 0000000..e64a0ae --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-features.qdoc @@ -0,0 +1,18 @@ +//! [0] +configure.exe -D QT_NO_THREAD +//! [0] + + +//! [1] +./configure -no-feature-thread +//! [1] + + +//! [2] +configure.exe -qconfig myfile +//! [2] + + +//! [3] +./configure -qconfig myfile +//! [3] diff --git a/doc/src/snippets/code/doc_src_emb-fonts.qdoc b/doc/src/snippets/code/doc_src_emb-fonts.qdoc new file mode 100644 index 0000000..b39cb6f --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-fonts.qdoc @@ -0,0 +1,3 @@ +//! [0] +name file renderer italic weight size flags +//! [0] diff --git a/doc/src/snippets/code/doc_src_emb-install.qdoc b/doc/src/snippets/code/doc_src_emb-install.qdoc new file mode 100644 index 0000000..fe53614 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-install.qdoc @@ -0,0 +1,37 @@ +//! [0] +cd <anywhere> +gunzip qt-embedded-linux-commercial-src-%VERSION%.tar.gz +tar xf qt-embedded-linux-commercial-src-%VERSION%.tar +//! [0] + + +//! [1] +~/qt-embedded-linux-commercial-src-%VERSION% +//! [1] + + +//! [2] +cd ~/qt-embedded-linux-commercial-src-%VERSION% +./configure -embedded [architecture] +//! [2] + + +//! [3] +make +//! [3] + + +//! [4] +su -c "make install" +//! [4] + + +//! [5] +PATH=/usr/local/Trolltech/QtEmbedded-%VERSION%/bin:$PATH +export PATH +//! [5] + + +//! [6] +setenv PATH /usr/local/Trolltech/QtEmbedded-%VERSION%/bin:$PATH +//! [6] diff --git a/doc/src/snippets/code/doc_src_emb-performance.qdoc b/doc/src/snippets/code/doc_src_emb-performance.qdoc new file mode 100644 index 0000000..7dcba12 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-performance.qdoc @@ -0,0 +1,36 @@ +//! [0] +./configure -static +//! [0] + + +//! [1] +void *operator new[](size_t size) +{ + return malloc(size); +} + +void *operator new(size_t size) +{ + return malloc(size); +} + +void operator delete[](void *ptr) +{ + free(ptr); +} + +void operator delete[](void *ptr, size_t) +{ + free(ptr); +} + +void operator delete(void *ptr) +{ + free(ptr); +} + +void operator delete(void *ptr, size_t) +{ + free(ptr); +} +//! [1] diff --git a/doc/src/snippets/code/doc_src_emb-pointer.qdoc b/doc/src/snippets/code/doc_src_emb-pointer.qdoc new file mode 100644 index 0000000..37eb9c6 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-pointer.qdoc @@ -0,0 +1,68 @@ +//! [0] + <qtopia-root-dir>/qtopiacore/qt/configure -embedded -help |grep -a1 mouse +//! [0] + + +//! [1] + ./configure -extra-qtopiacore-config -qt-mouse-tslib +//! [1] + + +//! [2] + ./configure -help +//! [2] + + +//! [3] + configure -qt-mouse-tslib +//! [3] + + +//! [4] +export QWS_MOUSE_PROTO=<driver>[:<driver specific options>] +//! [4] + + +//! [5] +export QWS_MOUSE_PROTO="<driver>[:<driver specific options>] + <driver>[:<driver specific options>] + <driver>[:<driver specific options>]" +//! [5] + + +//! [6] +export QWS_MOUSE_PROTO="Vr41xx:press=500:/dev/misc/ts" +//! [6] + + +//! [7] +./configure -L <path to tslib library> -I <path to tslib headers> +//! [7] + + +//! [8] +module_raw input +module linear +//! [8] + + +//! [9] +QWS_MOUSE_PROTO=IntelliMouse:/dev/input/mouse0 +//! [9] + + +//! [10] +cat /dev/input/mouse0 | hexdump +//! [10] + + +//! [11] +QWS_MOUSE_PROTO=IntelliMouse:/dev/input/mouse0 +//! [11] + + +//! [12] +chmod a+rw /dev/input/mouse0 +//! [12] + + diff --git a/doc/src/snippets/code/doc_src_emb-qvfb.qdoc b/doc/src/snippets/code/doc_src_emb-qvfb.qdoc new file mode 100644 index 0000000..827c84a --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-qvfb.qdoc @@ -0,0 +1,70 @@ +//! [0] +cd path/to/QtEmbedded +./configure -qvfb +make +//! [0] + + +//! [1] +cd path/to/Qt/tools/qvfb +make +./qvfb +//! [1] + + +//! [2] +cd path/to/Qt/tools/qvfb/ClamshellPhone.skin/ +//! [2] + + +//! [3] +[SkinFile] +Up=ClamshellPhone1-5.png +Down=ClamshellPhone1-5-pressed.png +Closed=ClamshellPhone1-5-closed.png +Screen=72 84 176 208 +Areas=22 + +"Power" 0x0100000a 205 563 249 586 +"1" 0x0031 62 414 119 438 +"2" 0x0032 130 414 189 438 +"3" 0x0033 198 413 257 438 +"4" 0x0034 54 444 117 470 +"5" 0x0035 128 444 189 471 +"6" 0x0036 202 444 264 471 +"7" 0x0037 47 477 113 507 +"8" 0x0038 126 477 190 507 +"9" 0x0039 205 478 270 509 +"*" 0x002a 39 515 110 552 +"0" 0x0030 122 515 195 553 +"#" 0x0023 207 516 280 553 +"Context1" 0x01100000 137 360 108 383 123 410 90 409 60 387 63 378 + 100 362 +"Back" 0x01000061 184 361 206 376 213 387 197 410 226 410 256 392 + 258 381 244 369 +"Backspace" 0x01000003 68 563 113 587 +"Select" 0x01010000 160 391 172 390 181 386 184 381 180 377 173 + 373 165 372 155 372 145 375 138 378 136 + 382 138 387 147 390 +"Left" 0x1000012 141 390 136 385 136 381 143 375 132 371 120 + 380 121 393 129 401 +"Down" 0x1000015 143 389 130 402 162 412 191 404 175 390 +"Right" 0x1000014 186 370 176 375 184 382 182 387 175 390 190 404 + 201 396 202 375 +"Up" 0x1000013 133 370 143 374 176 374 185 370 169 362 149 362 +"Flip" 0x01100006 98 325 225 353 +//! [3] + + +//! [4] +cd path/to/QtEmbedded/examples/widgets/analogclock +make +./analogclock -qws +//! [4] + + +//! [5] +cd path/to/QtEmbedded/examples/widgets/analogclock +make +./analogclock -qws -display QVFb:0 +//! [5] diff --git a/doc/src/snippets/code/doc_src_emb-running.qdoc b/doc/src/snippets/code/doc_src_emb-running.qdoc new file mode 100644 index 0000000..b15cfc1 --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-running.qdoc @@ -0,0 +1,61 @@ +//! [0] +cd path/to/QtEmbedded/demos/textedit +./textedit -qws +//! [0] + + +//! [1] +./myfirstserverapplication -qws -display "transformed:rot90:1" +./mysecondserverapplication -qws -display "QVFb:2" +//! [1] + + +//! [2] +./myclientapplication -display "QVFb:2" +//! [2] + + +//! [3] +./myserverapplication -qws -display "Multi: QVFb:0 + QVFb:1:offset=0,0 VNC:offset=640,0 :2" +//! [3] + + +//! [4] +./myapplication -fn helvetica +//! [4] + + +//! [5] +./myapplication -bg blue +//! [5] + + +//! [6] +./myapplication -btn green +//! [6] + + +//! [7] +./myapplication -fg 'dark blue' +//! [7] + + +//! [8] +./myapplication -name texteditapplication +//! [8] + + +//! [9] +./myapplication -title 'Text Edit' +//! [9] + + +//! [10] +./myapplication -geometry 300x200+50+50 +//! [10] + + +//! [11] +./myapplication -decoration windows +//! [11] diff --git a/doc/src/snippets/code/doc_src_emb-vnc.qdoc b/doc/src/snippets/code/doc_src_emb-vnc.qdoc new file mode 100644 index 0000000..c35274f --- /dev/null +++ b/doc/src/snippets/code/doc_src_emb-vnc.qdoc @@ -0,0 +1,25 @@ +//! [0] +cd path/to/QtEmbedded +./configure -qt-gfx-vnc +make +//! [0] + + +//! [1] +cd path/to/QtEmbedded/examples/widgets/analogclock +./analogclock -qws -display VNC:0 +//! [1] + + +//! [2] +vncviewer localhost:0 +//! [2] + +//! [Starting server] +analogclock -qws -display VNC:0 +//! [Starting server] +//! [Starting clients] +calculator -display VNC:0 +scribble -display VNC:0 +imageviewer -display VNC:0 +//! [Starting clients] diff --git a/doc/src/snippets/code/doc_src_examples_activeqt_comapp.qdoc b/doc/src/snippets/code/doc_src_examples_activeqt_comapp.qdoc new file mode 100644 index 0000000..0414e50 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_activeqt_comapp.qdoc @@ -0,0 +1,39 @@ +//! [0] +Private Application As comappLib.Application +Private MyApp As Boolean + +Private Sub UpdateList() + DocumentList.Clear + DocumentsCount.Caption = Application.documents.Count + For Index = 0 To Application.documents.Count - 1 + DocumentList.AddItem (Application.documents.Item(Index).Title) + Next +End Sub + +Private Sub Form_Load() + On Error GoTo CreateNew + Set Application = GetObject(, "comapp.Application") + MyApp = False + GoTo Initialized +CreateNew: + On Error GoTo InitializeFailed + Set Application = New Application + Application.Visible = True + MyApp = True +Initialized: + Caption = Application.id + UpdateList +InitializeFailed: +End Sub + +Private Sub Form_Unload(Cancel As Integer) + If MyApp Then + Application.quit + End If +End Sub + +Private Sub NewDocument_Click() + Application.documents.addDocument + UpdateList +End Sub +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_activeqt_dotnet.qdoc b/doc/src/snippets/code/doc_src_examples_activeqt_dotnet.qdoc new file mode 100644 index 0000000..3bdf9fa --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_activeqt_dotnet.qdoc @@ -0,0 +1,4 @@ +//! [0] +' VB is case insensitive, but our C++ controls are not. +' Me.resetButton.enabled = True +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_activeqt_menus.qdoc b/doc/src/snippets/code/doc_src_examples_activeqt_menus.qdoc new file mode 100644 index 0000000..18849dd --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_activeqt_menus.qdoc @@ -0,0 +1,6 @@ +//! [0] +<object ID="QMenus" CLASSID="CLSID:4dc3f340-a6f7-44e4-a79b-3e9217695fbd" +CODEBASE="http://qtsoftware.com/demos/menusax.cab"> +[Object not available! Did you forget to build and register the server?] +</object> +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_ahigl.qdoc b/doc/src/snippets/code/doc_src_examples_ahigl.qdoc new file mode 100644 index 0000000..bf29cda --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_ahigl.qdoc @@ -0,0 +1,8 @@ +//! [0] +myApplication -qws -display ahigl +//! [0] + + +//! [1] +myApplication -qws -display ahigl +//! [1] diff --git a/doc/src/snippets/code/doc_src_examples_application.qdoc b/doc/src/snippets/code/doc_src_examples_application.qdoc new file mode 100644 index 0000000..85e04f7 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_application.qdoc @@ -0,0 +1,5 @@ +//! [0] +application -style=windows +application -style=motif +application -style=cde +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_arrowpad.qdoc b/doc/src/snippets/code/doc_src_examples_arrowpad.qdoc new file mode 100644 index 0000000..ba7f8eb --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_arrowpad.qdoc @@ -0,0 +1,19 @@ +//! [0] +qApp->translate("ArrowPad", x) +//! [0] + + +//! [1] +lrelease arrowpad.pro +//! [1] + + +//! [2] +export LANG=fr +setenv LANG fr +//! [2] + + +//! [3] +set LANG=fr +//! [3] diff --git a/doc/src/snippets/code/doc_src_examples_containerextension.qdoc b/doc/src/snippets/code/doc_src_examples_containerextension.qdoc new file mode 100644 index 0000000..299c0dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_containerextension.qdoc @@ -0,0 +1,4 @@ +//! [0] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_customwidgetplugin.qdoc b/doc/src/snippets/code/doc_src_examples_customwidgetplugin.qdoc new file mode 100644 index 0000000..299c0dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_customwidgetplugin.qdoc @@ -0,0 +1,4 @@ +//! [0] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_dropsite.qdoc b/doc/src/snippets/code/doc_src_examples_dropsite.qdoc new file mode 100644 index 0000000..fd949ea --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_dropsite.qdoc @@ -0,0 +1,3 @@ +//! [0] +foreach(variable, container) +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_editabletreemodel.qdoc b/doc/src/snippets/code/doc_src_examples_editabletreemodel.qdoc new file mode 100644 index 0000000..2475842 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_editabletreemodel.qdoc @@ -0,0 +1,8 @@ +//! [0] +QVariant a = model->index(0, 0, QModelIndex()).data(); +//! [0] + + +//! [1] +QVariant b = model->index(1, 0, QModelIndex()).data(); +//! [1] diff --git a/doc/src/snippets/code/doc_src_examples_hellotr.qdoc b/doc/src/snippets/code/doc_src_examples_hellotr.qdoc new file mode 100644 index 0000000..4f31bc0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_hellotr.qdoc @@ -0,0 +1,31 @@ +//! [0] +lupdate -verbose hellotr.pro +//! [0] + + +//! [1] +<!DOCTYPE TS><TS> +<context> + <name>QPushButton</name> + <message> + <source>Hello world!</source> + <translation type="unfinished"></translation> + </message> +</context> +</TS> +//! [1] + + +//! [2] +linguist hellotr_la.ts +//! [2] + + +//! [3] +<translation type='unfinished'></translation> +//! [3] + + +//! [4] +<translation>Orbis, te saluto!</translation> +//! [4] diff --git a/doc/src/snippets/code/doc_src_examples_icons.qdoc b/doc/src/snippets/code/doc_src_examples_icons.qdoc new file mode 100644 index 0000000..3d33dff --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_icons.qdoc @@ -0,0 +1,14 @@ +//! [0] +if (!condition) + qFatal("ASSERT: "condition" in file ..."); +//! [0] + + +//! [1] +qmake "CONFIG += debug" icons.pro +//! [1] + + +//! [2] +qmake "CONFIG += release" icons.pro +//! [2] diff --git a/doc/src/snippets/code/doc_src_examples_imageviewer.qdoc b/doc/src/snippets/code/doc_src_examples_imageviewer.qdoc new file mode 100644 index 0000000..c1854ec --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_imageviewer.qdoc @@ -0,0 +1,24 @@ +//! [0] +imageLabel->resize(imageLabel->pixmap()->size()); +//! [0] + + +//! [1] +if (!imageLabel->pixmap()) + qFatal("ASSERT: "imageLabel->pixmap()" in file ..."); +//! [1] + + +//! [2] +qmake "CONFIG += debug" foo.pro +//! [2] + + +//! [3] +qmake "CONFIG += release" foo.pro +//! [3] + + +//! [4] +scrollBar->setValue(int(factor * scrollBar->value())); +//! [4] diff --git a/doc/src/snippets/code/doc_src_examples_qtscriptcustomclass.qdoc b/doc/src/snippets/code/doc_src_examples_qtscriptcustomclass.qdoc new file mode 100644 index 0000000..f958cc9 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_qtscriptcustomclass.qdoc @@ -0,0 +1,35 @@ +//! [0] +var ba = new ByteArray(); // constructs an empty ByteArray +var ba2 = new ByteArray(10); // constructs a ByteArray of length 10 (all bytes initialized to 0) +//! [0] + + +//! [1] +for (var i = 0; i < ba.length; ++i) + ba[i] = 123; +//! [1] + + +//! [2] +ba[0] = 257; +print(ba[0]); // 1 +//! [2] + + +//! [3] +var ba3 = new ByteArray(); +print(ba3.length); // 0 +ba[0] = 64; +print(ba3.length); // 1 +//! [3] + + +//! [4] +ba["foo"] = "Hello"; +//! [4] + + +//! [5] +var ba64 = ba.toBase64(); +print(ba64.toLatin1String()); +//! [5] diff --git a/doc/src/snippets/code/doc_src_examples_simpledommodel.qdoc b/doc/src/snippets/code/doc_src_examples_simpledommodel.qdoc new file mode 100644 index 0000000..c74a176 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_simpledommodel.qdoc @@ -0,0 +1,20 @@ +//! [0] +// file is an open QFile object. +QDomDocument document; +if (document.setContent(&file)) { + + QDomElement documentElement = document.documentElement(); + QString text; + QDomNode node = documentElement.firstChild(); + + while (!node.isNull()) { + if (node.isText()) + text += node.nodeValue(); + else if (node.hasChildNodes()) { + // Examine the node's children and read any text found. + ... + } + node = node.nextSibling(); + } +} +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_simpletreemodel.qdoc b/doc/src/snippets/code/doc_src_examples_simpletreemodel.qdoc new file mode 100644 index 0000000..907f3db --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_simpletreemodel.qdoc @@ -0,0 +1,12 @@ +//! [0] +Getting Started How to familiarize yourself with Qt Designer + Launching Designer Running the Qt Designer application + The User Interface How to interact with Qt Designer +//! [0] + + +//! [1] +Connection Editing Mode Connecting widgets together with signals and slots + Connecting Objects Making connections in Qt Designer + Editing Connections Changing existing connections +//! [1] diff --git a/doc/src/snippets/code/doc_src_examples_svgalib.qdoc b/doc/src/snippets/code/doc_src_examples_svgalib.qdoc new file mode 100644 index 0000000..3b63146 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_svgalib.qdoc @@ -0,0 +1,3 @@ +//! [0] +myApplication -qws -display svgalib +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_taskmenuextension.qdoc b/doc/src/snippets/code/doc_src_examples_taskmenuextension.qdoc new file mode 100644 index 0000000..299c0dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_taskmenuextension.qdoc @@ -0,0 +1,4 @@ +//! [0] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_textfinder.qdoc b/doc/src/snippets/code/doc_src_examples_textfinder.qdoc new file mode 100644 index 0000000..349becf --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_textfinder.qdoc @@ -0,0 +1,6 @@ +//! [0] +CONFIG += uitools +HEADERS = textfinder.h +RESOURCES = textfinder.qrc +SOURCES = textfinder.cpp main.cpp +//! [0] diff --git a/doc/src/snippets/code/doc_src_examples_trollprint.qdoc b/doc/src/snippets/code/doc_src_examples_trollprint.qdoc new file mode 100644 index 0000000..7f51a15 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_trollprint.qdoc @@ -0,0 +1,35 @@ +//! [0] +twoSidedEnabledRadio = new QRadioButton(tr("Enabled", "two-sided")); +twoSidedDisabledRadio = new QRadioButton(tr("Disabled", "two-sided")); +//! [0] + + +//! [1] +colorsEnabledRadio = new QRadioButton(tr("Enabled", "colors"), colors); +colorsDisabledRadio = new QRadioButton(tr("Disabled", "colors"), colors); +//! [1] + + +//! [2] +/* + 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. + + ... +//! [2] + + +//! [3] +/* + 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. +//! [3] diff --git a/doc/src/snippets/code/doc_src_examples_tutorial.qdoc b/doc/src/snippets/code/doc_src_examples_tutorial.qdoc new file mode 100644 index 0000000..0b79563 --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_tutorial.qdoc @@ -0,0 +1,10 @@ +//! [0] +qmake -project +qmake +//! [0] + + +//! [1] +qmake -project +qmake +//! [1] diff --git a/doc/src/snippets/code/doc_src_examples_worldtimeclockplugin.qdoc b/doc/src/snippets/code/doc_src_examples_worldtimeclockplugin.qdoc new file mode 100644 index 0000000..299c0dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_examples_worldtimeclockplugin.qdoc @@ -0,0 +1,4 @@ +//! [0] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [0] diff --git a/doc/src/snippets/code/doc_src_exportedfunctions.qdoc b/doc/src/snippets/code/doc_src_exportedfunctions.qdoc new file mode 100644 index 0000000..f0e5fb5 --- /dev/null +++ b/doc/src/snippets/code/doc_src_exportedfunctions.qdoc @@ -0,0 +1,17 @@ +//! [0] +#ifdef Q_WS_X11 +void qt_x11_wait_for_window_manager(QWidget *widget); +#endif + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + ... + window.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&window); +#endif + ... + return app.exec(); +} +//! [0] diff --git a/doc/src/snippets/code/doc_src_gpl.qdoc b/doc/src/snippets/code/doc_src_gpl.qdoc new file mode 100644 index 0000000..b6ef954 --- /dev/null +++ b/doc/src/snippets/code/doc_src_gpl.qdoc @@ -0,0 +1,679 @@ +//! [GPL v3] + You may use, distribute and copy the Qt GUI Toolkit under the terms of + GNU General Public License version 3, which is displayed below. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +them 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 prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey 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; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + 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. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +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. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + 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 +state 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) <year> <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 3 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, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program 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, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU 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 Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. +//! [GPL v3] diff --git a/doc/src/snippets/code/doc_src_graphicsview.qdoc b/doc/src/snippets/code/doc_src_graphicsview.qdoc new file mode 100644 index 0000000..4c19784 --- /dev/null +++ b/doc/src/snippets/code/doc_src_graphicsview.qdoc @@ -0,0 +1,77 @@ +//! [0] +QGraphicsScene scene; +QGraphicsRectItem *rect = scene.addRect(QRectF(0, 0, 100, 100)); + +QGraphicsItem *item = scene.itemAt(50, 50); +// item == rect +//! [0] + + +//! [1] +QGraphicsScene scene; +myPopulateScene(&scene); + +QGraphicsView view(&scene); +view.show(); +//! [1] + + +//! [2] +class View : public QGraphicsView +{ +Q_OBJECT + ... +public slots: + void zoomIn() { scale(1.2, 1.2); } + void zoomOut() { scale(1 / 1.2, 1 / 1.2); } + void rotateLeft() { rotate(-10); } + void rotateRight() { rotate(10); } + ... +}; +//! [2] + + +//! [3] +QGraphicsScene scene; +scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green)); + +QPrinter printer; +if (QPrintDialog(&printer).exec() == QDialog::Accepted) { + QPainter painter(&printer); + painter.setRenderHint(QPainter::Antialiasing); + scene.render(&painter); +} +//! [3] + + +//! [4] +QGraphicsScene scene; +scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt::black), QBrush(Qt::green)); + +QPixmap pixmap; +QPainter painter(&pixmap); +painter.setRenderHint(QPainter::Antialiasing); +scene.render(&painter); +painter.end(); + +pixmap.save("scene.png"); +//! [4] + + +//! [5] +void CustomItem::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + QMimeData *data = new QMimeData; + data->setColor(Qt::green); + + QDrag *drag = new QDrag(event->widget()); + drag->setMimeData(data); + drag->start(); +} +//! [5] + + +//! [6] +QGraphicsView view(&scene); +view.setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); +//! [6] diff --git a/doc/src/snippets/code/doc_src_groups.qdoc b/doc/src/snippets/code/doc_src_groups.qdoc new file mode 100644 index 0000000..51c2944 --- /dev/null +++ b/doc/src/snippets/code/doc_src_groups.qdoc @@ -0,0 +1,26 @@ +//! [0] +void QPen::setStyle(Qt::PenStyle style) +{ + detach(); // detach from common data + d->style = style; // set the style member +} + +void QPen::detach() +{ + if (d->ref != 1) { + ... // perform a deep copy + } +} +//! [0] + + +//! [1] +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(); +//! [1] diff --git a/doc/src/snippets/code/doc_src_i18n.qdoc b/doc/src/snippets/code/doc_src_i18n.qdoc new file mode 100644 index 0000000..857e70c --- /dev/null +++ b/doc/src/snippets/code/doc_src_i18n.qdoc @@ -0,0 +1,155 @@ +//! [0] +LoginWidget::LoginWidget() +{ + QLabel *label = new QLabel(tr("Password:")); + ... +} +//! [0] + + +//! [1] +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); +} +//! [1] + + +//! [2] +QString FriendlyConversation::greeting(int type) +{ + static const char *greeting_strings[] = { + QT_TR_NOOP("Hello"), + QT_TR_NOOP("Goodbye") + }; + return tr(greeting_strings[type]); +} +//! [2] + + +//! [3] +static const char *greeting_strings[] = { + QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), + QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") +}; + +QString FriendlyConversation::greeting(int type) +{ + return tr(greeting_strings[type]); +} + +QString global_greeting(int type) +{ + return qApp->translate("FriendlyConversation", + greeting_strings[type]); +} +//! [3] + + +//! [4] +void FileCopier::showProgress(int done, int total, + const QString ¤tFile) +{ + label.setText(tr("%1 of %2 files copied.\nCopying: %3") + .arg(done) + .arg(total) + .arg(currentFile)); +} +//! [4] + + +//! [5] +QString s1 = "%1 of %2 files copied. Copying: %3"; +QString s2 = "Kopierer nu %3. Av totalt %2 filer er %1 kopiert."; + +qDebug() << s1.arg(5).arg(10).arg("somefile.txt"); +qDebug() << s2.arg(5).arg(10).arg("somefile.txt"); +//! [5] + + +//! [6] +5 of 10 files copied. Copying: somefile.txt +Kopierer nu somefile.txt. Av totalt 10 filer er 5 kopiert. +//! [6] + + +//! [7] +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 +//! [7] + + +//! [8] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QTranslator qtTranslator; + qtTranslator.load("qt_" + QLocale::system().name(), + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + app.installTranslator(&qtTranslator); + + QTranslator myappTranslator; + myappTranslator.load("myapp_" + QLocale::system().name()); + app.installTranslator(&myappTranslator); + + ... + return app.exec(); +} +//! [8] + + +//! [9] +QString string = ...; // some Unicode text + +QTextCodec *codec = QTextCodec::codecForName("ISO 8859-5"); +QByteArray encodedString = codec->fromUnicode(string); +//! [9] + + +//! [10] +QByteArray encodedString = ...; // some ISO 8859-5 encoded text + +QTextCodec *codec = QTextCodec::codecForName("ISO 8859-5"); +QString string = codec->toUnicode(encodedString); +//! [10] + + +//! [11] +void Clock::setTime(const QTime &time) +{ + if (tr("AMPM") == "AMPM") { + // 12-hour clock + } else { + // 24-hour clock + } +} +//! [11] + + +//! [12] +void QWidget::changeEvent(QEvent *event) +{ + if (e->type() == QEvent::LanguageChange) { + titleLabel->setText(tr("Document Title")); + ... + okPushButton->setText(tr("&OK")); + } else + QWidget::changeEvent(event); +} +//! [12] diff --git a/doc/src/snippets/code/doc_src_installation.qdoc b/doc/src/snippets/code/doc_src_installation.qdoc new file mode 100644 index 0000000..66bb998 --- /dev/null +++ b/doc/src/snippets/code/doc_src_installation.qdoc @@ -0,0 +1,127 @@ +//! [0] +cd /tmp +gunzip qt-x11-opensource-desktop-%VERSION%.tar.gz # uncompress the archive +tar xvf qt-x11-opensource-desktop-%VERSION%.tar # unpack it +//! [0] + + +//! [1] +cd /tmp/qt-x11-opensource-desktop-%VERSION% +./configure +//! [1] + + +//! [2] +make +//! [2] + + +//! [3] +make install +//! [3] + + +//! [4] +PATH - to locate qmake, moc and other Qt tools +//! [4] + + +//! [5] +PATH=/usr/local/Trolltech/Qt-%VERSION%/bin:$PATH +export PATH +//! [5] + + +//! [6] +setenv PATH /usr/local/Trolltech/Qt-%VERSION%/bin:$PATH +//! [6] + + +//! [7] +PATH - to locate qmake, moc and other Qt tools +//! [7] + + +//! [8] +C: +cd /D C:\Qt\4.4.0-rc1 +configure +//! [8] + + +//! [9] +configure -platform win32-msvc +//! [9] + + +//! [10] +nmake +//! [10] + + +//! [11] +cd /tmp +gunzip qt-mac-opensource-desktop-%VERSION%.tar.gz # uncompress the archive +tar xvf qt-mac-opensource-desktop-%VERSION%.tar # unpack it +//! [11] + + +//! [12] +cd /tmp/qt-mac-opensource-desktop-%VERSION% +./configure +//! [12] + + +//! [13] +make +//! [13] + + +//! [14] +sudo make -j1 install +//! [14] + + +//! [15] +PATH - to locate qmake, moc and other Qt tools +//! [15] + + +//! [16] +PATH=/usr/local/Trolltech/Qt-%VERSION%/bin:$PATH +export PATH +//! [16] + + +//! [17] +setenv PATH /usr/local/Trolltech/Qt-%VERSION%/bin:$PATH +//! [17] + + +//! [18] +PATH - to locate qmake, moc and other Qt tools +//! [18] + + +//! [19] +C: +cd \Qt\%VERSION% +configure -platform win32-msvc2005 -xplatform wincewm50pocket-msvc2005 +//! [19] + + +//! [20] +set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ce\include;C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Include\Armv4i +set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ce\lib\armv4i;C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Lib\ARMV4I +set PATH=C:\Program Files\Microsoft Visual Studio 8\VC\ce\bin\x86_arm;%PATH% +//! [20] + + +//! [21] +setcepaths wincewm50pocket-msvc2005 +//! [21] + + +//! [22] +nmake +//! [22] diff --git a/doc/src/snippets/code/doc_src_introtodbus.qdoc b/doc/src/snippets/code/doc_src_introtodbus.qdoc new file mode 100644 index 0000000..bedfe7f --- /dev/null +++ b/doc/src/snippets/code/doc_src_introtodbus.qdoc @@ -0,0 +1,3 @@ +//! [0] +org.freedesktop.DBus +//! [0] diff --git a/doc/src/snippets/code/doc_src_layout.qdoc b/doc/src/snippets/code/doc_src_layout.qdoc new file mode 100644 index 0000000..48e10e9 --- /dev/null +++ b/doc/src/snippets/code/doc_src_layout.qdoc @@ -0,0 +1,119 @@ +//! [0] +#ifndef CARD_H +#define CARD_H + +#include <QLayout> +#include <QList> + +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; + QLayoutItem *itemAt(int) const; + QLayoutItem *takeAt(int); + void setGeometry(const QRect &rect); + +private: + QList<QLayoutItem*> list; +}; +#endif +//! [0] + + +//! [1] +#include "card.h" +//! [1] + + +//! [2] +QLayoutItem *CardLayout::itemAt(int idx) const +{ + // QList::value() performs index checking, and returns 0 if we are + // outside the valid range + return list.value(idx); +} + +QLayoutItem *CardLayout::takeAt(int idx) +{ + // QList::take does not do index checking + return idx >= 0 && idx < list.size() ? list.takeAt(idx) : 0; +} +//! [2] + + +//! [3] +void CardLayout::addItem(QLayoutItem *item) +{ + list.append(item); +} +//! [3] + + +//! [4] +CardLayout::~CardLayout() +{ + deleteAllItems(); +} +//! [4] + + +//! [5] +void CardLayout::setGeometry(const QRect &r) +{ + QLayout::setGeometry(r); + + if (list.size() == 0) + return; + + int w = r.width() - (list.count() - 1) * spacing(); + int h = r.height() - (list.count() - 1) * spacing(); + int i = 0; + while (i < list.size()) { + QLayoutItem *o = list.at(i); + QRect geom(r.x() + i * spacing(), r.y() + i * spacing(), w, h); + o->setGeometry(geom); + ++i; + } +} +//! [5] + + +//! [6] +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 + int i = 0; + while (i < n) { + QLayoutItem *o = list.at(i); + s = s.expandedTo(o->sizeHint()); + ++i; + } + return s + n*QSize(spacing(), spacing()); +} + +QSize CardLayout::minimumSize() const +{ + QSize s(0,0); + int n = list.count(); + int i = 0; + while (i < n) { + QLayoutItem *o = list.at(i); + s = s.expandedTo(o->minimumSize()); + ++i; + } + return s + n*QSize(spacing(), spacing()); +} +//! [6] diff --git a/doc/src/snippets/code/doc_src_lgpl.qdoc b/doc/src/snippets/code/doc_src_lgpl.qdoc new file mode 100644 index 0000000..dc76d85 --- /dev/null +++ b/doc/src/snippets/code/doc_src_lgpl.qdoc @@ -0,0 +1,507 @@ +//! [LGPL v2.1] + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, 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 library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete 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 distribute a copy of this License along with the +Library. + + 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 Library or any portion +of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +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 Library, 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 Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you 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. + + If distribution of 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 satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be 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. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library 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. + + 9. 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 Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +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 with +this License. + + 11. 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 Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library 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 Library. + +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. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library 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. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +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 Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. 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 LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. 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 library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + + +//! [LGPL v2.1] diff --git a/doc/src/snippets/code/doc_src_licenses.qdoc b/doc/src/snippets/code/doc_src_licenses.qdoc new file mode 100644 index 0000000..4a95a50 --- /dev/null +++ b/doc/src/snippets/code/doc_src_licenses.qdoc @@ -0,0 +1,108 @@ +//! [1] + [utopiafonts] 1999 free font + ---------------------------------------------------- + + this font is provided free for personal or commercial use, + it can be redistributed however it may not be sold. + ---------------------------------------------------- + (C) 1999 utopiafonts. dale_thorpe@bssc.edu.au +//! [1] + + +//! [2] + Bitstream Vera Fonts Copyright + ------------------------------ + + Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is + a trademark of Bitstream, Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of the fonts accompanying this license ("Fonts") and associated + documentation files (the "Font Software"), to reproduce and distribute the + Font Software, including without limitation the rights to use, copy, merge, + publish, distribute, and/or sell copies of the Font Software, and to permit + persons to whom the Font Software is furnished to do so, subject to the + following conditions: + + The above copyright and trademark notices and this permission notice shall + be included in all copies of one or more of the Font Software typefaces. + + The Font Software may be modified, altered, or added to, and in particular + the designs of glyphs or characters in the Fonts may be modified and + additional glyphs or characters may be added to the Fonts, only if the fonts + are renamed to names not containing either the words "Bitstream" or the word + "Vera". + + This License becomes null and void to the extent applicable to Fonts or Font + Software that has been modified and is distributed under the "Bitstream + Vera" names. + + The Font Software may be sold as part of a larger software package but no + copy of one or more of the Font Software typefaces may be sold by itself. + + THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, + TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME + FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING + ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF + THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE + FONT SOFTWARE. + + Except as contained in this notice, the names of Gnome, the Gnome + Foundation, and Bitstream Inc., shall not be used in advertising or + otherwise to promote the sale, use or other dealings in this Font Software + without prior written authorization from the Gnome Foundation or Bitstream + Inc., respectively. For further information, contact: fonts at gnome dot + org. + + Arev Fonts Copyright + ------------------------------ + + Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of the fonts accompanying this license ("Fonts") and + associated documentation files (the "Font Software"), to reproduce + and distribute the modifications to the Bitstream Vera Font Software, + including without limitation the rights to use, copy, merge, publish, + distribute, and/or sell copies of the Font Software, and to permit + persons to whom the Font Software is furnished to do so, subject to + the following conditions: + + The above copyright and trademark notices and this permission notice + shall be included in all copies of one or more of the Font Software + typefaces. + + The Font Software may be modified, altered, or added to, and in + particular the designs of glyphs or characters in the Fonts may be + modified and additional glyphs or characters may be added to the + Fonts, only if the fonts are renamed to names not containing either + the words "Tavmjong Bah" or the word "Arev". + + This License becomes null and void to the extent applicable to Fonts + or Font Software that has been modified and is distributed under the + "Tavmjong Bah Arev" names. + + The Font Software may be sold as part of a larger software package but + no copy of one or more of the Font Software typefaces may be sold by + itself. + + THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL + TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL + DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM + OTHER DEALINGS IN THE FONT SOFTWARE. + + Except as contained in this notice, the name of Tavmjong Bah shall not + be used in advertising or otherwise to promote the sale, use or other + dealings in this Font Software without prior written authorization + from Tavmjong Bah. For further information, contact: tavmjong @ free + . fr. + +//! [2] diff --git a/doc/src/snippets/code/doc_src_linguist-manual.qdoc b/doc/src/snippets/code/doc_src_linguist-manual.qdoc new file mode 100644 index 0000000..ce3b997 --- /dev/null +++ b/doc/src/snippets/code/doc_src_linguist-manual.qdoc @@ -0,0 +1,183 @@ +//! [0] +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 +//! [0] + + +//! [1] +CODECFORTR = ISO-8859-5 +//! [1] + + +//! [2] +CODECFORSRC = UTF-8 +//! [2] + + +//! [3] +label->setText(tr("F\374r \310lise")); +//! [3] + + +//! [4] +Usage: + lupdate [options] [project-file] + lupdate [options] [source-file|path]... -ts ts-files +Options: + -help Display this information and exit. + -noobsolete + Drop all obsolete strings. + -extensions <ext>[,<ext>]... + Process files with the given extensions only. + The extension list must be separated with commas, not with whitespace. + Default: 'ui,c,c++,cc,cpp,cxx,ch,h,h++,hh,hpp,hxx'. + -pluralonly + Only include plural form messages. + -silent + Don't explain what is being done. + -version + Display the version of lupdate and exit. +//! [4] + + +//! [5] +Usage: + lrelease [options] project-file + lrelease [options] ts-files [-qm qm-file] +Options: + -help Display this information and exit + -compress + Compress the .qm files + -nounfinished + Do not include unfinished translations + -removeidentical + If the translated text is the same as + the source text, do not include the message + -silent + Don't explain what is being done + -version + Display the version of lrelease and exit +//! [5] + + +void wrapInFunction() +{ +//! [6] +button = new QPushButton("&Quit", this); +//! [6] + + +//! [7] +button = new QPushButton(tr("&Quit"), this); +//! [7] + + +//! [8] +QPushButton::tr("&Quit") +//! [8] + + +//! [9] +QObject::tr("&Quit") +//! [9] + + +//! [10] +rbc = new QRadioButton(tr("Enabled", "Color frame"), this); +//! [10] + + +//! [11] +rbh = new QRadioButton(tr("Enabled", "Hue frame"), this); +//! [11] +} + + +//! [12] +/* + TRANSLATOR FindDialog + + Choose Edit|Find from the menu bar or press Ctrl+F to pop up the + Find dialog. + + ... +*/ +//! [12] + +//! [13] +/* + TRANSLATOR MyNamespace::MyClass + + Necessary for lupdate. + + ... +*/ +//! [13] + +//! [14] +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); +} +//! [14] + + +//! [15] +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]); +} +//! [15] + + +//! [16] +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]); +} +//! [16] + +void wrapInFunction() +{ + +//! [17] +QString tr(const char *text, const char *comment, int n); +//! [17] + +//! [18] +tr("%n item(s) replaced", "", count); +//! [18] + +} + diff --git a/doc/src/snippets/code/doc_src_mac-differences.qdoc b/doc/src/snippets/code/doc_src_mac-differences.qdoc new file mode 100644 index 0000000..a4d9578 --- /dev/null +++ b/doc/src/snippets/code/doc_src_mac-differences.qdoc @@ -0,0 +1,36 @@ +//! [0] +QMAKE_LFLAGS_SONAME = -Wl,-install_name,@executable_path/../Frameworks/ +//! [0] + + +//! [1] +#ifdef Q_WS_MAC + CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); + CFStringRef macPath = CFURLCopyFileSystemPath(appUrlRef, + kCFURLPOSIXPathStyle); + const char *pathPtr = CFStringGetCStringPtr(macPath, + CFStringGetSystemEncoding()); + qDebug("Path = %s", pathPtr); + CFRelease(appUrlRef); + CFRelease(macPath); +#endif +//! [1] + + +//! [2] +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" +"http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>LprojCompatibleVersion</key> + <string>123</string> + <key>LprojLocale</key> + <string>no</string> + <key>LprojRevisionLevel</key> + <string>1</string> + <key>LprojVersion</key> + <string>123</string> +</dict> +</plist> +//! [2] diff --git a/doc/src/snippets/code/doc_src_moc.qdoc b/doc/src/snippets/code/doc_src_moc.qdoc new file mode 100644 index 0000000..59739e1 --- /dev/null +++ b/doc/src/snippets/code/doc_src_moc.qdoc @@ -0,0 +1,124 @@ +//! [0] +moc_%.cpp: %.h + moc $(DEFINES) $(INCPATH) $< -o $@ +//! [0] + + +//! [1] +moc_foo.cpp: foo.h + moc $(DEFINES) $(INCPATH) $< -o $@ +//! [1] + + +//! [2] +foo.o: foo.moc + +foo.moc: foo.cpp + moc $(DEFINES) $(INCPATH) -i $< -o $@ +//! [2] + + +//! [3] +#include "foo.moc" +//! [3] + + +//! [4] +#ifndef Q_MOC_RUN + ... +#endif +//! [4] + + +//! [5] +class SomeTemplate<int> : public QFrame +{ + Q_OBJECT + ... + +signals: + void mySignal(int); +}; +//! [5] + + +//! [6] +// correct +class SomeClass : public QObject, public OtherClass +{ + ... +}; +//! [6] + + +//! [7] +class SomeClass : public QObject +{ + Q_OBJECT + +public slots: + void apply(void (*apply)(List *, void *), char *); // WRONG +}; +//! [7] + + +//! [8] +typedef void (*ApplyFunction)(List *, void *); + +class SomeClass : public QObject +{ + Q_OBJECT + +public slots: + void apply(ApplyFunction, char *); +}; +//! [8] + + +//! [9] +class MyClass : public QObject +{ + Q_OBJECT + + enum Error { + ConnectionRefused, + RemoteHostClosed, + UnknownError + }; + +signals: + void stateChanged(MyClass::Error error); +}; +//! [9] + + +//! [10] +#ifdef ultrix +#define SIGNEDNESS(a) unsigned a +#else +#define SIGNEDNESS(a) a +#endif + +class Whatever : public QObject +{ + Q_OBJECT + +signals: + void someSignal(SIGNEDNESS(int)); +}; +//! [10] + + +//! [11] +class A +{ +public: + class B + { + Q_OBJECT + + public slots: // WRONG + void b(); + }; +}; +//! [11] diff --git a/doc/src/snippets/code/doc_src_model-view-programming.qdoc b/doc/src/snippets/code/doc_src_model-view-programming.qdoc new file mode 100644 index 0000000..3501ce0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_model-view-programming.qdoc @@ -0,0 +1,36 @@ +//! [0] +QAbstractItemModel *model = index.model(); +//! [0] + + +//! [1] +QModelIndex index = model->index(row, column, ...); +//! [1] + + +//! [2] +QModelIndex indexA = model->index(0, 0, QModelIndex()); +QModelIndex indexB = model->index(1, 1, QModelIndex()); +QModelIndex indexC = model->index(2, 1, QModelIndex()); +//! [2] + + +//! [3] +QModelIndex index = model->index(row, column, parent); +//! [3] + + +//! [4] +QModelIndex indexA = model->index(0, 0, QModelIndex()); +QModelIndex indexC = model->index(2, 1, QModelIndex()); +//! [4] + + +//! [5] +QModelIndex indexB = model->index(1, 0, indexA); +//! [5] + + +//! [6] +QVariant value = model->data(index, role); +//! [6] diff --git a/doc/src/snippets/code/doc_src_modules.qdoc b/doc/src/snippets/code/doc_src_modules.qdoc new file mode 100644 index 0000000..e9006fd --- /dev/null +++ b/doc/src/snippets/code/doc_src_modules.qdoc @@ -0,0 +1,3 @@ +//! [0] +QT -= gui +//! [0] diff --git a/doc/src/snippets/code/doc_src_objecttrees.qdoc b/doc/src/snippets/code/doc_src_objecttrees.qdoc new file mode 100644 index 0000000..216027f --- /dev/null +++ b/doc/src/snippets/code/doc_src_objecttrees.qdoc @@ -0,0 +1,20 @@ +//![0] +int main() +{ + QWidget window; + QPushButton quit("Quit", &window); + ... +} +//![0] + + +//![1] +int main() +{ + QPushButton quit("Quit"); + QWidget window; + + quit.setParent(&window); + ... +} +//![1] diff --git a/doc/src/snippets/code/doc_src_phonon-api.qdoc b/doc/src/snippets/code/doc_src_phonon-api.qdoc new file mode 100644 index 0000000..e230792 --- /dev/null +++ b/doc/src/snippets/code/doc_src_phonon-api.qdoc @@ -0,0 +1,224 @@ +//! [0] +PushStream::PushStream(QObject *parent) + : AbstractMediaStream(parent), m_timer(new QTimer(this)) +{ + setStreamSize(getMediaStreamSize()); + + connect(m_timer, SIGNAL(timeout()), SLOT(moreData())); + m_timer->setInterval(0); +} + +void PushStream::moreData() +{ + const QByteArray data = getMediaData(); + if (data.isEmpty()) { + endOfData(); + } else { + writeData(data); + } +} + +void PushStream::needData() +{ + m_timer->start(); + moreData(); +} + +void PushStream::enoughData() +{ + m_timer->stop(); +} +//! [0] + + +//! [1] +PullStream::PullStream(QObject *parent) + : AbstractMediaStream(parent) +{ + setStreamSize(getMediaStreamSize()); +} + +void PullStream::needData() +{ + const QByteArray data = getMediaData(); + if (data.isEmpty()) { + endOfData(); + } else { + writeData(data); + } +} +//! [1] + + +//! [2] +seekStream(0); +//! [2] + + +//! [3] +MediaObject m; +QString fileName("/home/foo/bar.ogg"); +QUrl url("http://www.example.com/stream.mp3"); +QBuffer *someBuffer; +m.setCurrentSource(fileName); +m.setCurrentSource(url); +m.setCurrentSource(someBuffer); +m.setCurrentSource(Phonon::Cd); +//! [3] + + +//! [4] +VideoPlayer *player = new VideoPlayer(Phonon::VideoCategory, parentWidget); +connect(player, SIGNAL(finished()), player, SLOT(deleteLater())); +player->play(url); +//! [4] + + +//! [5] +audioPlayer->load(url); +audioPlayer->play(); +//! [5] + + +//! [6] +media = new MediaObject(this); +connect(media, SIGNAL(finished()), SLOT(slotFinished()); +media->setCurrentSource("/home/username/music/filename.ogg"); + +... + +media->play(); +//! [6] + + +//! [7] +media->setCurrentSource(":/sounds/startsound.ogg"); +media->enqueue("/home/username/music/song.mp3"); +media->enqueue(":/sounds/endsound.ogg"); +//! [7] + + +//! [8] + media->setCurrentSource(":/sounds/startsound.ogg"); + connect(media, SIGNAL(aboutToFinish()), SLOT(enqueueNextSource())); +} + +void enqueueNextSource() +{ + media->enqueue("/home/username/music/song.mp3"); +} +//! [8] + + +//! [9] +int x = 200; +media->setTickInterval(x); +Q_ASSERT(x == producer->tickInterval()); +//! [9] + + +//! [10] +int x = 200; +media->setTickInterval(x); +Q_ASSERT(x >= producer->tickInterval() && + x <= 2producer->tickInterval()); +//! [10] + + +//! [11] + connect(media, SIGNAL(hasVideoChanged(bool)), hasVideoChanged(bool)); + media->setCurrentSource("somevideo.avi"); + media->hasVideo(); // returns false; +} + +void hasVideoChanged(bool b) +{ + // b == true + media->hasVideo(); // returns true; +} +//! [11] + + +//! [12] + connect(media, SIGNAL(hasVideoChanged(bool)), hasVideoChanged(bool)); + media->setCurrentSource("somevideo.avi"); + media->hasVideo(); // returns false; +} + +void hasVideoChanged(bool b) +{ + // b == true + media->hasVideo(); // returns true; +} +//! [12] + + +//! [13] +setMetaArtist(media->metaData("ARTIST")); +setMetaAlbum(media->metaData("ALBUM")); +setMetaTitle(media->metaData("TITLE")); +setMetaDate(media->metaData("DATE")); +setMetaGenre(media->metaData("GENRE")); +setMetaTrack(media->metaData("TRACKNUMBER")); +setMetaComment(media->metaData("DESCRIPTION")); +//! [13] + + +//! [14] +QUrl url("http://www.example.com/music.ogg"); +media->setCurrentSource(url); +//! [14] + + +//! [15] +progressBar->setRange(0, 100); // this is the default +connect(media, SIGNAL(bufferStatus(int)), progressBar, SLOT(setValue(int))); +//! [15] + + +//! [16] +QObject::connect(BackendCapabilities::notifier(), SIGNAL(capabilitiesChanged()), ... +//! [16] + + +//! [17] +QComboBox *cb = new QComboBox(parentWidget); +ObjectDescriptionModel *model = new ObjectDescriptionModel(cb); +model->setModelData(BackendCapabilities::availableAudioOutputDevices()); +cb->setModel(model); +cb->setCurrentIndex(0); // select first entry +//! [17] + + +//! [18] +int cbIndex = cb->currentIndex(); +AudioOutputDevice selectedDevice = model->modelData(cbIndex); +//! [18] + + +//! [19] +Path path = Phonon::createPath(...); +Effect *effect = new Effect(this); +path.insertEffect(effect); +//! [19] + + +//! [20] +MediaObject *media = new MediaObject; +AudioOutput *output = new AudioOutput(Phonon::MusicCategory); +Path path = Phonon::createPath(media, output); +Q_ASSERT(path.isValid()); // for this simple case the path should always be + //valid - there are unit tests to ensure it +// insert an effect +QList<EffectDescription> effectList = BackendCapabilities::availableAudioEffects(); +if (!effectList.isEmpty()) { + Effect *effect = path.insertEffect(effectList.first()); +} +//! [20] + + +//! [21] +MediaObject *media = new MediaObject(parent); +VideoWidget *vwidget = new VideoWidget(parent); +Phonon::createPath(media, vwidget); +//! [21] diff --git a/doc/src/snippets/code/doc_src_phonon.qdoc b/doc/src/snippets/code/doc_src_phonon.qdoc new file mode 100644 index 0000000..3e4bce4 --- /dev/null +++ b/doc/src/snippets/code/doc_src_phonon.qdoc @@ -0,0 +1,13 @@ +//! [0] +QT += phonon +//! [0] + + +//! [1] +QT += phonon +//! [1] + + +//! [2] +#include <Phonon/MediaObject> +//! [2] diff --git a/doc/src/snippets/code/doc_src_platform-notes.qdoc b/doc/src/snippets/code/doc_src_platform-notes.qdoc new file mode 100644 index 0000000..ed56a08 --- /dev/null +++ b/doc/src/snippets/code/doc_src_platform-notes.qdoc @@ -0,0 +1,39 @@ +//! [0] +undefined reference to `_vt.11QPushButton' +//! [0] + + +//! [1] +ANSI C++ forbids declaration ... with no type +//! [1] + + +//! [2] +c:\program.obj not found +//! [2] + + +//! [3] +-universal -sdk /Developer/SDKs/MacOSX10.4u.sdk +//! [3] + + +//! [4] +QMAKE_MAC_SDK=/Developer/SDKs/MacOSX10.4u.sdk +CONFIG+=x86 ppc +//! [4] + + +//! [5] +/usr/bin/ld: /System/Library/Frameworks/Carbon.framework/Carbon +load command 20 unknown cmd field +/usr/bin/ld: /usr/lib/libSystem.dylib +load command 6 unknown cmd field +//! [5] + + +//! [6] +ld: common symbols not allowed with MH_DYLIB output format with the -multi_module option +/usr/local/mysql/lib/libmysqlclient.a(my_error.o) definition of common _errbuff (size 512) +/usr/bin/libtool: internal link edit command failed +//! [6] diff --git a/doc/src/snippets/code/doc_src_plugins-howto.qdoc b/doc/src/snippets/code/doc_src_plugins-howto.qdoc new file mode 100644 index 0000000..45c8690 --- /dev/null +++ b/doc/src/snippets/code/doc_src_plugins-howto.qdoc @@ -0,0 +1,67 @@ +//! [0] +class MyStylePlugin : public QStylePlugin +{ +public: + QStringList keys() const; + QStyle *create(const QString &key); +}; +//! [0] + + +//! [1] +#include "mystyleplugin.h" + +QStringList MyStylePlugin::keys() const +{ + return QStringList() << "MyStyle"; +} + +QStyle *MyStylePlugin::create(const QString &key) +{ + if (key.toLower() == "mystyle") + return new MyStyle; + return 0; +} + +Q_EXPORT_PLUGIN2(pnp_mystyleplugin, MyStylePlugin) +//! [1] + + +//! [2] +QApplication::setStyle(QStyleFactory::create("MyStyle")); +//! [2] + + +//! [3] +CONFIG += release +//! [3] + + +//! [4] +#include <QApplication> +#include <QtPlugin> + +Q_IMPORT_PLUGIN(qjpeg) +Q_IMPORT_PLUGIN(qgif) +Q_IMPORT_PLUGIN(qkrcodecs) + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + ... + return app.exec(); +} +//! [4] + + +//! [5] +QTPLUGIN += qjpeg \ + qgif \ + qkrcodecs +//! [5] + + +//! [6] +HKEY_CURRENT_USER\Software\Trolltech\OrganizationDefaults\Qt Plugin Cache 4.2.debug +HKEY_CURRENT_USER\Software\Trolltech\OrganizationDefaults\Qt Plugin Cache 4.2.false +//! [6] diff --git a/doc/src/snippets/code/doc_src_porting-qsa.qdoc b/doc/src/snippets/code/doc_src_porting-qsa.qdoc new file mode 100644 index 0000000..0dc572c --- /dev/null +++ b/doc/src/snippets/code/doc_src_porting-qsa.qdoc @@ -0,0 +1,187 @@ +//! [0] +point = new Object(); +point.x = 12; +point.y = 35; +//! [0] + + +//! [1] +function manhattanLength(point) { + return point.x + point.y; +} +//! [1] + + +//! [2] +manhattanLength = function(point) { + return point.x + point.y; +} +//! [2] + + +//! [3] +point.manhattanLength = function() { + return this.x + this.y; +} +print(point.manhattanLength()); // prints 47 +//! [3] + + +//! [4] +class Point() { + var x; + var y; + function manhattanLength() { return x + y; } +} +//! [4] + + +//! [5] +point.manhattanLength = function() { + return this.x + this.y; +} +print(point.manhattanLength()); // prints 47 +//! [5] + + +//! [6] +class Car { + var regNumber; + function Car(regnr) { + regNumber = regnr; + } +} +var car = new Car("ABC 123"); +//! [6] + + +//! [7] +function Car(regnr) { + this.regNumber = regnr; +} +var car = new Car("ABC 123"); +//! [7] + + +//! [8] +var car = new Object(); +car.constructor = function(regnr) { ... } +car.constructor(); +//! [8] + + +//! [9] +class Car { + var regNumber; + function Car(regnr) { + regNumber = regnr; + } + function toString() { + return regNumber; + } +} +//! [9] + + +//! [10] +function Car(regnr) { + this.regNumber = regnr; + this.toString = function() { return this.regNumber; } +} +//! [10] + + +//! [11] +function Car(regnr) { + this.regNumber = regnr; +} +Car.prototype.toString = function() { return this.regNumber; } +//! [11] + + +//! [12] +class GasolineCar extends Car { + function GasolineCar(regnr) { + Car(regnr); + } + function toString() { + return "GasolineCar(" + regNumber + ")"; + } +} +//! [12] + + +//! [13] +function GasolineCar(regnr) { + Car(regnr); +} +GasolineCar.prototype = new Car(); +GasolineCar.prototype.toString = function() { + return "GasolineCar(" + this.regNumber + ")"; +} +//! [13] + + +//! [14] +class Car { + static var globalCount = 0; +} +print(Car.globalCount); +//! [14] + + +//! [15] +Car.globalCount = 0; +print(Car.globalCount); +//! [15] + + +//! [16] +QPushButton *button = new QPushButton(); +button->setObjectName("button"); +interpreter->addTransientObject(button); +//! [16] + + +//! [17] +QPushButton *button = new QPushButton(); +QScriptValue scriptButton = engine.newQObject(button); +engine.globalObject().setProperty("button", scriptButton); +//! [17] + + +//! [18] +ModuleFactory::ModuleFactory() +{ + registerClass( "ImageSource", &ImgSource::staticMetaObject); + ... +} + +QObject *ModuleFactory::create( const QString &type, + const QVariantList &, + QObject * ) +{ + if ( type == "ImageSource" ) + return new ImgSource(); + ... +} + +... + +interpreter.addObjectFactory(new ModuleFactory()); +//! [18] + + +//! [19] +QScriptValue construct_QPushButton(QScriptContext *, QScriptEngine *engine) { + return engine->newQObject(new QPushButton()); +} + +... + +QScriptValue constructor = engine.newFunction(construct_QPushButton); +QScriptValue value = + engine.newQMetaObject(&QPushButton::staticMetaObject, + constructor); +engine.globalObject().setProperty("QPushButton", value); +//! [19] diff --git a/doc/src/snippets/code/doc_src_porting4-canvas.qdoc b/doc/src/snippets/code/doc_src_porting4-canvas.qdoc new file mode 100644 index 0000000..e386607 --- /dev/null +++ b/doc/src/snippets/code/doc_src_porting4-canvas.qdoc @@ -0,0 +1,116 @@ +//! [0] +item->scene().sceneRect().intersects(item->sceneBoundingRect()); +//! [0] + + +//! [1] +class TileScene : public QGraphicsScene +{ +public: + ... + + void setTiles(const QPixmap &pixmap, int h, int v, + int tileHeight, int tileWidth); + void setTile(int x, int y, int tilenum); + +private: + QRect tileRect(int x, int y) const; + QRect tileRect(int tileNum) const; + + QVector<QVector<int> > tiles; + QPixmap tilePixmap; + int tileW, tileH; + int hTiles, vTiles; +}; +//! [1] + + +//! [2] +void TileScene::setTiles(const QPixmap &pixmap, int h, int v, + int tileHeight, int tileWidth) +{ + tilePixmap = pixmap; + tileW = tileWidth; + tileH = tileHeight; + hTiles = h; + vTiles = v; + + tiles.resize(v); + for (int y = 0; y < v; ++y) + tiles[y].resize(h); +} +//! [2] + + +//! [3] +void TileScene::setTile(int x, int y, int tilenum) +{ + tiles[y][x] = tilenum; + update(tileRect(x, y)); +} +//! [3] + + +//! [4] +QRect TileScene::tileRect(int x, int y) const +{ + return QRect(x * tileW, y * tileH, tileW, tileH); +} +//! [4] + + +//! [5] +QRect TileScene::tileRect(int tileNum) const +{ + int numHTiles = tilePixmap.width() / tileW; + int numVTiles = tilePixmap.height() / tileH; + return tileRect(tileNum % numHTiles, tileNum / numHTiles); +} +//! [5] + + +//! [6] +void drawBackground(QPainter *painter, const QRectF &exposed) +{ + for (int y = 0; y < vTiles; ++y) { + for (int x = 0; x < hTiles; ++x) { + QRect destRect = tileRect(x, y); + if (exposed.intersects(destRect)) { + painter->drawPixmap(destRect, tilePixmap, + tileRect(tiles[y][x])); + } + } + } +} +//! [6] + + +//! [7] + // Before + Q3CanvasEllipse ellipse(10, 10); + + // After + QGraphicsEllipseItem ellipse(-5, -5, 10, 10); +//! [7] + + +//! [8] +static QPainterPath fromControlPoints(const Q3PointArray &pa) +{ + QPainterPath path; + path.moveTo(pa[0]); + for (int i = 1; i < pa.size(); i += 3) + path.cubicTo(pa[i], pa[(i + 1) % pa.size()], pa[(i + 2) % pa.size()]); + return path; +} +//! [8] + + +//! [9] +wildcardPath.replace("%1", "*"); +QFileInfo fi(wildcardPath); + +QList<QPixmap> frames; +foreach (QString entry, QDir(fi.path(), fi.fileName()).entryList()) + frames << QPixmap(fi.path() + "/" + entry); +//! [9] diff --git a/doc/src/snippets/code/doc_src_porting4-designer.qdoc b/doc/src/snippets/code/doc_src_porting4-designer.qdoc new file mode 100644 index 0000000..d4abaa0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_porting4-designer.qdoc @@ -0,0 +1,159 @@ +//! [0] +namespace Ui { + +class HelloWorld +{ +public: + QVBoxLayout *vboxLayout; + QPushButton *pushButton; + + void setupUi(QWidget *HelloWorld) + { + HelloWorld->setObjectName(QString::fromUtf8("HelloWorld")); + + vboxLayout = new QVBoxLayout(HelloWorld); + vboxLayout->setObjectName(QString::fromUtf8("vboxLayout")); + + pushButton = new QPushButton(HelloWorld); + pushButton->setObjectName(QString::fromUtf8("pushButton")); + + vboxLayout->addWidget(pushButton); + + retranslateUi(HelloWorld); + } +}; + +} +//! [0] + + +//! [1] +#include <QApplication> +#include <QWidget> + +#include "ui_helloworld.h" // defines Ui::HelloWorld + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QWidget w; + Ui::HelloWorld ui; + ui.setupUi(&w); + + w.show(); + return app.exec(); +} +//! [1] + + +//! [2] +#include <QApplication> +#include <QWidget> + +#include "ui_helloworld.h" // defines Ui::HelloWorld + +class HelloWorldWidget : public QWidget, public Ui::HelloWorld +{ + Q_OBJECT + +public: + HelloWorldWidget(QWidget *parent = 0) + : QWidget(parent) + { setupUi(this); } +}; + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + HelloWorldWidget w; + w.show(); + return app.exec(); +} +//! [2] + + +//! [3] +uic3 myform.ui > myform.h +uic3 -impl myform.h myform.ui > myform.cpp +//! [3] + + +//! [4] +uic3 -convert myform3.ui > myform4.ui +//! [4] + + +//! [5] +class HelloWorldWidget : public QWidget, public Ui::HelloWorld +{ + Q_OBJECT + +public: + HelloWorldWidget(QWidget *parent = 0); + +public slots: + void mySlot(); +}; + +HelloWorldWidget::HelloWorldWidget(QWidget *parent) + : QWidget(parent) +{ + setupUi(this); + + QObject::connect(pushButton, SIGNAL(clicked()), + this, SLOT(mySlot())); +} + +void HelloWorldWidget::mySlot() +{ + ... +} +//! [5] + + +//! [6] +class HelloWorldWidget : public QWidget, public Ui::HelloWorld +{ + Q_OBJECT + +public: + HelloWorldWidget(QWidget *parent = 0); + +public slots: + void on_pushButton_clicked(); +}; + +HelloWorldWidget::HelloWorldWidget(QWidget *parent) + : QWidget(parent) +{ + setupUi(this); +} + +void HelloWorldWidget::on_pushButton_clicked() +{ + ... +} +//! [6] + + +//! [7] +<RCC version="1.0"> + <qresource prefix="/icons"> + <file>yes.png</file> + <file>no.png</file> + </qresource> +</RCC> +//! [7] + + +//! [8] +RESOURCES += icons.qrc +//! [8] + + +//! [9] +QFile file(":/icons/yes.png"); +QIcon icon(":/icons/no.png"); +QPixmap pixmap(":/icons/no.png"); +//! [9] diff --git a/doc/src/snippets/code/doc_src_porting4.qdoc b/doc/src/snippets/code/doc_src_porting4.qdoc new file mode 100644 index 0000000..14fddf8 --- /dev/null +++ b/doc/src/snippets/code/doc_src_porting4.qdoc @@ -0,0 +1,473 @@ +//! [0] +void MyButton::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + drawButton(&painter); +} +//! [0] + + +//! [1] +ba.at(0) = 'X'; +//! [1] + + +//! [2] +ba[0] = 'X'; +//! [2] + + +//! [3] +if (!cache.insert(key, object)) + delete object; +//! [3] + + +//! [4] +cache.insert(key, object); +//! [4] + + +//! [5] +Q3Cache<QWidget> cache; +cache.insert(widget->name(), widget); +... +QWidget *foo = cache.take("foo"); +if (foo) + foo->show(); +//! [5] + + +//! [6] +typedef QWidget *QWidgetPtr; +QCache<QString, QWidgetPtr> cache; +cache.insert(widget->name(), new QWidgetPtr(widget)); +... +QWidgetPtr *ptr = cache.take("foo"); +if (ptr) { + QWidget *foo = *ptr; + delete ptr; + foo->show(); +} +//! [6] + + +//! [7] +painter.setBrush(palette().brush(QPalette::Text)); +//! [7] + + +//! [8] +QByteArray ba("Hello"); +ba.size(); // returns 5 (the '\0' is not counted) +ba.length(); // returns 5 +ba.data()[5]; // returns '\0' +//! [8] + + +//! [9] +dict.replace(key, value); +//! [9] + + +//! [10] +delete hash.take(key); +hash.insert(key, value); +//! [10] + + +//! [11] +dict.remove(key, value); +//! [11] + + +//! [12] +delete hash.take(key); +//! [12] + + +//! [13] +dict.clear(); +//! [13] + + +//! [14] +while (!hash.isEmpty()) { + T *value = *hash.begin(); + hash.erase(hash.begin()); + delete value; +} +//! [14] + + +//! [15] +qDeleteAll(hash); +hash.clear(); +//! [15] + + +//! [16] +Q3DictIterator<QWidget> i(dict); +while (i.current() != 0) { + do_something(i.currentKey(), i.current()); + ++i; +} +//! [16] + + +//! [17] +QHashIterator<QString, QWidget *> i(hash); +while (i.hasNext()) { + i.next(); // must come first + do_something(i.key(), i.value()); +} +//! [17] + + +//! [18] +QList<QWidget *> myWidgets = qFindChildren<QWidget *>(myParent); +//! [18] + + +//! [19] +list.replace(index, value); +//! [19] + + +//! [20] +delete list[index]; +list[index] = value; +//! [20] + + +//! [21] +list.removeFirst(); +//! [21] + + +//! [22] +delete list.takeFirst(); +//! [22] + + +//! [23] +list.removeLast(); +//! [23] + + +//! [24] +delete list.takeLast(); +//! [24] + + +//! [25] +list.remove(index); +//! [25] + + +//! [26] +delete list.takeAt(index); +//! [26] + + +//! [27] +list.remove(value); +//! [27] + + +//! [28] +int i = list.indexOf(value); +if (i != -1) + delete list.takeAt(i); +//! [28] + + +//! [29] +list.remove(); +//! [29] + + +//! [30] +QMutableListIterator<T *> i; +... +delete i.value(); +i.remove(); +//! [30] + + +//! [31] +list.clear(); +//! [31] + + +//! [32] +while (!list.isEmpty()) + delete list.takeFirst(); +//! [32] + + +//! [33] +qDeleteAll(list); +list.clear(); +//! [33] + + +//! [34] +QPtrList<QWidget> list; +... +while (list.current() != 0) { + do_something(list.current()); + list.next(); +} +//! [34] + + +//! [35] +QList<QWidget *> list; +... +QListIterator<QWidget *> i(list); +while (i.hasNext()) + do_something(i.next()); +//! [35] + + +//! [36] +QPtrList<QWidget> list; +... +QPtrListIterator<QWidget> i; +while (i.current() != 0) { + do_something(i.current()); + i.next(); +} +//! [36] + + +//! [37] +QList<QWidget *> list; +... +QListIterator<QWidget *> i(list); +while (i.hasNext()) + do_something(i.next()); +//! [37] + + +//! [38] +queue.dequeue(); +//! [38] + + +//! [39] +delete queue.dequeue(); +//! [39] + + +//! [40] +queue.remove(); +//! [40] + + +//! [41] +delete queue.dequeue(); +//! [41] + + +//! [42] +queue.clear(); +//! [42] + + +//! [43] +while (!queue.isEmpty()) + delete queue.dequeue(); +//! [43] + + +//! [44] +qDeleteAll(queue); +queue.clear(); +//! [44] + + +//! [45] +stack.pop(); +//! [45] + + +//! [46] +delete stack.pop(); +//! [46] + + +//! [47] +stack.remove(); +//! [47] + + +//! [48] +delete stack.pop(); +//! [48] + + +//! [49] +stack.clear(); +//! [49] + + +//! [50] +while (!stack.isEmpty()) + delete stack.pop(); +//! [50] + + +//! [51] +qDeleteAll(stack); +stack.clear(); +//! [51] + + +//! [52] +vect.insert(i, ptr); +//! [52] + + +//! [53] +delete vect[i]; +vect[i] = ptr; +//! [53] + + +//! [54] +vect.remove(i); +//! [54] + + +//! [55] +delete vect[i]; +vect[i] = 0; +//! [55] + + +//! [56] +T *ptr = vect.take(i); +//! [56] + + +//! [57] +T *ptr = vect[i]; +vect[i] = 0; +//! [57] + + +//! [58] +vect.resize(n) +//! [58] + + +//! [59] +while (n > vect.size()) + vect.append(0); +while (n < vect.size() { + T *ptr = vect.last(); + vect.remove(vect.size() - 1); + delete ptr; +} +//! [59] + + +//! [60] +vect.clear(); +//! [60] + + +//! [61] +for (int i = 0; i < vect.size(); ++i) + T *ptr = vect[i]; + vect[i] = 0; + delete ptr; +} +//! [61] + + +//! [62] +qDeleteAll(vect); +vect.clear(); +//! [62] + + +//! [63] +struct Shared +{ + Shared() : count(1) {} + void ref() { ++count; } + bool deref() { return !--count; } + uint count; +}; +//! [63] + +//! [63a] +// Declare the object +QSimpleRichText richText(text, font); + +// Set the width of the paragraph to w +richText.setWidth(w); + +// Or set a resonable default size +richText.adjustSize(); + +// Query for its used size +int width = richText.widthUsed(); +int height = richText.height(); + +// Draw +richText.draw(painter, x, y, clipRect, colorGroup); +//! [63a] + + +//! [63b] +// Declare the object +QTextDocument doc; + +// If text is rich text, use setHtml() +doc.setHtml(text); + +// Otherwise, use setPlainText() +doc.setPlainText(text); + +// Set the width of the paragraph of text to w +doc.setTextWidth(w); + +// Query for the used size +int width = doc.idealWidth(); +int height = doc.size().height(); + +// Draw +painter.translate(x, y); +doc.drawContents(painter, clipRect); + +// If you have a palette/colorgroup you can draw using lower-level functions: +QAbstractTextDocumentLayout::PaintContext context; +context.palette = myPalette; +doc.documentLayout()->draw(painter, context); +//! [63b] + +//! [63c] +QSlider *slider; +slider->style()->subControlRect(CC_Slider, sliderOption, SC_SliderHandle, slider); +//! [63c] + +//! [64] +QString greeting = "Hello"; +const char *badData = greeting.toAscii().constData(); // data is invalid +QByteArray asciiData = greeting.toAscii(); +const char *goodData = asciiData.constData(); +//! [64] + + +//! [65] +str.at(0) = 'X'; +//! [65] + + +//! [66] +str[0] = 'X'; +//! [66] diff --git a/doc/src/snippets/code/doc_src_properties.qdoc b/doc/src/snippets/code/doc_src_properties.qdoc new file mode 100644 index 0000000..ba7f79b --- /dev/null +++ b/doc/src/snippets/code/doc_src_properties.qdoc @@ -0,0 +1,77 @@ +//! [0] +Q_PROPERTY(type name + READ getFunction + [WRITE setFunction] + [RESET resetFunction] + [DESIGNABLE bool] + [SCRIPTABLE bool] + [STORED bool] + [USER bool]) +//! [0] + + +//! [1] +Q_PROPERTY(bool focus READ hasFocus) +Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) +Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor RESET unsetCursor) +//! [1] + + +//! [2] +Q_PROPERTY(QDate date READ getDate WRITE setDate) +//! [2] + + +//! [3] +QPushButton *button = new QPushButton; +QObject *object = button; + +button->setDown(true); +object->setProperty("down", true); +//! [3] + + +//! [4] +QObject *object = ... +const QMetaObject *metaobject = object->metaObject(); +int count = metaobject->propertyCount(); +for (int i=0; i<count; ++i) { + QMetaProperty metaproperty = metaobject->property(i); + const char *name = metaproperty.name(); + QVariant value = object->property(name); + ... +} +//! [4] + + +//! [5] +class MyClass : public QObject +{ + Q_OBJECT + Q_PROPERTY(Priority priority READ priority WRITE setPriority) + Q_ENUMS(Priority) + +public: + MyClass(QObject *parent = 0); + ~MyClass(); + + enum Priority { High, Low, VeryHigh, VeryLow }; + + void setPriority(Priority priority); + Priority priority() const; +}; +//! [5] + + +//! [6] +MyClass *myinstance = new MyClass; +QObject *object = myinstance; + +myinstance->setPriority(MyClass::VeryHigh); +object->setProperty("priority", "VeryHigh"); +//! [6] + + +//! [7] +Q_CLASSINFO("Version", "3.0.0") +//! [7] diff --git a/doc/src/snippets/code/doc_src_q3asciidict.qdoc b/doc/src/snippets/code/doc_src_q3asciidict.qdoc new file mode 100644 index 0000000..e2c876a --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3asciidict.qdoc @@ -0,0 +1,52 @@ +//! [0] +Q3AsciiDict<QLineEdit> fields; // char* keys, QLineEdit* values +fields.insert( "forename", new QLineEdit( this ) ); +fields.insert( "surname", new QLineEdit( this ) ); + +fields["forename"]->setText( "Homer" ); +fields["surname"]->setText( "Simpson" ); + +Q3AsciiDictIterator<QLineEdit> it( fields ); // See Q3AsciiDictIterator +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; +//! [0] + + +//! [1] +Q3AsciiDict<char> dict; + ... +if ( dict.find(key) ) + dict.remove( key ); +dict.insert( key, item ); +//! [1] + + +//! [2] +Q3AsciiDict<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" ); + +Q3AsciiDictIterator<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 +//! [2] diff --git a/doc/src/snippets/code/doc_src_q3dict.qdoc b/doc/src/snippets/code/doc_src_q3dict.qdoc new file mode 100644 index 0000000..f79d0f7 --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3dict.qdoc @@ -0,0 +1,29 @@ +//! [0] +Q3Dict<char> dict; + ... +if ( dict.find( key ) ) + dict.remove( key ); +dict.insert( key, item ); +//! [0] + + +//! [1] +Q3Dict<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" ); + +Q3DictIterator<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 +//! [1] diff --git a/doc/src/snippets/code/doc_src_q3intdict.qdoc b/doc/src/snippets/code/doc_src_q3intdict.qdoc new file mode 100644 index 0000000..0fae2c8 --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3intdict.qdoc @@ -0,0 +1,51 @@ +//! [0] +Q3IntDict<QLineEdit> fields; // long int keys, QLineEdit* values +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" ); + +Q3IntDictIterator<QLineEdit> it( fields ); +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" +//! [0] + + +//! [1] +Q3IntDict<char> dict; +// ... +if ( dict.find(key) ) + dict.remove( key ); +dict.insert( key, item ); +//! [1] + + +//! [2] +Q3IntDict<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" ); + +Q3IntDictIterator<QLineEdit> it( fields ); +for ( ; it.current(); ++it ) + cout << it.currentKey() << ": " << it.current()->text() << endl; + +// Output (random order): +// 0: Homer +// 1: Simpson +// 2: 45 +//! [2] diff --git a/doc/src/snippets/code/doc_src_q3memarray.qdoc b/doc/src/snippets/code/doc_src_q3memarray.qdoc new file mode 100644 index 0000000..b56ef4e --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3memarray.qdoc @@ -0,0 +1,80 @@ +//! [0] +#include <q3memarray.h> +#include <stdio.h> + +Q3MemArray<int> fib( int num ) // returns fibonacci array +{ + Q_ASSERT( num > 2 ); + Q3MemArray<int> f( num ); // array of ints + + f[0] = f[1] = 1; + for ( int i = 2; i < num; i++ ) + f[i] = f[i-1] + f[i-2]; + + return f; +} + +int main() +{ + Q3MemArray<int> a = fib( 6 ); // get first 6 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] +0: 1 +1: 1 +2: 2 +3: 3 +4: 5 +5: 8 +1 is found 2 times +5 is found at index 4 +//! [1] + + +//! [2] +// MyStruct may be padded to 4 or 8 bytes +struct MyStruct +{ + short i; // 2 bytes + char c; // 1 byte +}; + +Q3MemArray<MyStruct> a(1); +a[0].i = 5; +a[0].c = 't'; + +MyStruct x; +x.i = '5'; +x.c = 't'; +int i = a.find( x ); // may return -1 if the pad bytes differ +//! [2] + + +//! [3] +static char bindata[] = { 231, 1, 44, ... }; +QByteArray a; +a.setRawData( bindata, sizeof(bindata) ); // a points to bindata +QDataStream s( a, IO_ReadOnly ); // open on a's data +s >> <something>; // read raw bindata +a.resetRawData( bindata, sizeof(bindata) ); // finished +//! [3] + + +//! [4] +static char bindata[] = { 231, 1, 44, ... }; +QByteArray a, b; +a.setRawData( bindata, sizeof(bindata) ); // a points to bindata +a.resize( 8 ); // will crash +b = a; // will crash +a[2] = 123; // might crash +// forget to resetRawData: will crash +//! [4] diff --git a/doc/src/snippets/code/doc_src_q3ptrdict.qdoc b/doc/src/snippets/code/doc_src_q3ptrdict.qdoc new file mode 100644 index 0000000..d23824b --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3ptrdict.qdoc @@ -0,0 +1,66 @@ +//! [0] +Q3PtrDict<char> fields; // void* keys, char* values + +QLineEdit *le1 = new QLineEdit( this ); +le1->setText( "Simpson" ); +QLineEdit *le2 = new QLineEdit( this ); +le2->setText( "Homer" ); +QLineEdit *le3 = new QLineEdit( this ); +le3->setText( "45" ); + +fields.insert( le1, "Surname" ); +fields.insert( le2, "Forename" ); +fields.insert( le3, "Age" ); + +Q3PtrDictIterator<char> it( fields ); +for( ; it.current(); ++it ) + cout << it.current() << endl; +cout << endl; + +if ( fields[le1] ) // Prints "Surname: Simpson" + cout << fields[le1] << ": " << le1->text() << endl; +if ( fields[le2] ) // Prints "Forename: Homer" + cout << fields[le2] << ": " << le2->text() << endl; + +fields.remove( le1 ); // Removes le1 from the dictionary +cout << le1->text() << endl; // Prints "Simpson" +//! [0] + + +//! [1] +Q3PtrDict<ItemType> dict; + ... +if ( dict.find( key ) ) + dict.remove( key ); +dict.insert( key, item ); +//! [1] + + +//! [2] +Q3PtrDict<char> fields; + +QLineEdit *le1 = new QLineEdit( this ); +le1->setText( "Simpson" ); +QLineEdit *le2 = new QLineEdit( this ); +le2->setText( "Homer" ); +QLineEdit *le3 = new QLineEdit( this ); +le3->setText( "45" ); + +fields.insert( le1, "Surname" ); +fields.insert( le2, "Forename" ); +fields.insert( le3, "Age" ); + +Q3PtrDictIterator<char> it( fields ); +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 +//! [2] + + diff --git a/doc/src/snippets/code/doc_src_q3ptrlist.qdoc b/doc/src/snippets/code/doc_src_q3ptrlist.qdoc new file mode 100644 index 0000000..f416784 --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3ptrlist.qdoc @@ -0,0 +1,82 @@ +//! [0] +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; +}; + +Q3PtrList<Employee> list; +list.setAutoDelete( TRUE ); // the list owns the objects + +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; + +// very inefficient for big lists +for ( uint i = 0; i < list.count(); ++i ) + if ( list.at(i) ) + cout << list.at( i )->surname().latin1() << endl; +//! [0] + + +//! [1] +Doe, John earns 50000 +Williams, Jane earns 80000 +Jones, Tom earns 60000 + +Doe +Williams +Jones +//! [1] + + +//! [2] +if ( list.findRef( item ) != -1 ) + list.remove(); +//! [2] + + +//! [3] +Q3PtrList<Employee> list; + +list.append( new Employee("John", "Doe", 50000) ); +list.append( new Employee("Jane", "Williams", 80000) ); +list.append( new Employee("Tom", "Jones", 60000) ); + +Q3PtrListIterator<Employee> it( list ); +Employee *employee; +while ( (employee = it.current()) != 0 ) { + ++it; + cout << employee->surname().latin1() << ", " << + employee->forename().latin1() << " earns " << + employee->salary() << endl; +} +//! [3] + + +//! [4] +Doe, John earns 50000 +Williams, Jane earns 80000 +Jones, Tom earns 60000 +//! [4] diff --git a/doc/src/snippets/code/doc_src_q3valuelist.qdoc b/doc/src/snippets/code/doc_src_q3valuelist.qdoc new file mode 100644 index 0000000..5a6d564 --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3valuelist.qdoc @@ -0,0 +1,95 @@ +//! [0] +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 Q3ValueList<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; + +// Output: +// Doe, John earns 50000 +// Williams, Jane earns 80000 +// Hawthorne, Mary earns 90000 +// Jones, Tom earns 60000 +//! [0] + + +//! [1] +Q3ValueList<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; +} +... +Q3ValueList<double> dlist; +double d = dlist.last(); // undefined +//! [1] + + +//! [2] +Q3ValueList<int> l; +... +Q3ValueList<int>::iterator it = l.end(); +--it; +if ( it != end() ) + // ... +//! [2] + + +//! [3] +Q3ValueList<int> l; +... +Q3ValueList<int>::iterator it = l.end(); +--it; +if ( it != end() ) + // ... +//! [3] + + +//! [4] +EmployeeList::iterator it; +for ( it = list.begin(); it != list.end(); ++it ) + cout << (*it).surname().latin1() << ", " << + (*it).forename().latin1() << " earns " << + (*it).salary() << endl; + +// Output: +// Doe, John earns 50000 +// Williams, Jane earns 80000 +// Hawthorne, Mary earns 90000 +// Jones, Tom earns 60000 +//! [4] diff --git a/doc/src/snippets/code/doc_src_q3valuestack.qdoc b/doc/src/snippets/code/doc_src_q3valuestack.qdoc new file mode 100644 index 0000000..61d564b --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3valuestack.qdoc @@ -0,0 +1,13 @@ +//! [0] +Q3ValueStack<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 +//! [0] diff --git a/doc/src/snippets/code/doc_src_q3valuevector.qdoc b/doc/src/snippets/code/doc_src_q3valuevector.qdoc new file mode 100644 index 0000000..792bfac --- /dev/null +++ b/doc/src/snippets/code/doc_src_q3valuevector.qdoc @@ -0,0 +1,85 @@ +//! [0] +#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 Q3ValueVector<Employee> EmployeeVector; + EmployeeVector vec( 3 ); // vector of 3 Employees + + vec[0] = Employee( "Bill", 50000 ); + vec[1] = Employee( "Steve", 80000 ); + vec[2] = Employee( "Ron", 60000 ); + + Employee joe( "Joe", 50000 ); + vec.push_back( joe ); // vector expands to accommodate 4 Employees + joe.setSalary( 70000 ); + + EmployeeVector::iterator it; + for( it = vec.begin(); it != vec.end(); ++it ) + printf( "%s earns %d\n", (*it).name().latin1(), (*it).salary() ); + + return 0; +} +//! [0] + + +//! [1] +Bill earns 50000 +Steve earns 80000 +Ron earns 60000 +Joe earns 50000 +//! [1] + + +//! [2] +Q3ValueVector<int> vec1; // an empty vector +vec1[10] = 4; // WARNING: undefined, probably a crash + +Q3ValueVector<QString> vec2(25); // initialize with 25 elements +vec2[10] = "Dave"; // OK +//! [2] + + +//! [3] +void func( Q3ValueVector<int>& vec ) +{ + if ( vec.size() > 10 ) { + vec[9] = 99; // OK + } +}; +//! [3] + + +//! [4] +Q3ValueVector<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; +} +... +Q3ValueVector<double> dvec; +double d = dvec.back(); // undefined behavior +//! [4] diff --git a/doc/src/snippets/code/doc_src_qalgorithms.qdoc b/doc/src/snippets/code/doc_src_qalgorithms.qdoc new file mode 100644 index 0000000..69d943c --- /dev/null +++ b/doc/src/snippets/code/doc_src_qalgorithms.qdoc @@ -0,0 +1,314 @@ +//! [0] +QStringList list; +list << "one" << "two" << "three"; + +qFill(list.begin(), list.end(), "eleven"); +// list: [ "eleven", "eleven", "eleven" ] +//! [0] + + +//! [1] +qFill(list.begin() + 1, list.end(), "six"); +// list: [ "eleven", "six", "six" ] +//! [1] + + +//! [2] +QChar resolveEntity(const QString &entity) +{ + static const QLatin1String name_table[] = { + "AElig", "Aacute", ..., "zwnj" + }; + static const ushort value_table[] = { + 0x0061, 0x00c1, ..., 0x200c + }; + int N = sizeof(name_table) / sizeof(name_table[0]); + + const QLatin1String *name = qBinaryFind(name_table, name_table + N, + entity); + int index = name - name_table; + if (index == N) + return QChar(); + + return QChar(value_table[index]); +} +//! [2] + + +//! [3] +QChar resolveEntity(const QString &entity) +{ + static QMap<QString, int> entityMap; + + if (!entityMap) { + entityMap.insert("AElig", 0x0061); + entityMap.insert("Aacute", 0x00c1); + ... + entityMap.insert("zwnj", 0x200c); + } + return QChar(entityMap.value(entity)); +} +//! [3] + + +//! [4] +QStringList list; +list << "one" << "two" << "three"; + +QVector<QString> vect1(3); +qCopy(list.begin(), list.end(), vect1.begin()); +// vect: [ "one", "two", "three" ] + +QVector<QString> vect2(8); +qCopy(list.begin(), list.end(), vect2.begin() + 2); +// vect: [ "", "", "one", "two", "three", "", "", "" ] +//! [4] + + +//! [5] +QStringList list; +list << "one" << "two" << "three"; + +QVector<QString> vect(5); +qCopyBackward(list.begin(), list.end(), vect.end()); +// vect: [ "", "", "one", "two", "three" ] +//! [5] + + +//! [6] +QStringList list; +list << "one" << "two" << "three"; + +QVector<QString> vect(3); +vect[0] = "one"; +vect[1] = "two"; +vect[2] = "three"; + +bool ret1 = qEqual(list.begin(), list.end(), vect.begin()); +// ret1 == true + +vect[2] = "seven"; +bool ret2 = qEqual(list.begin(), list.end(), vect.begin()); +// ret2 == false +//! [6] + + +//! [7] +QStringList list; +list << "one" << "two" << "three"; + +qFill(list.begin(), list.end(), "eleven"); +// list: [ "eleven", "eleven", "eleven" ] + +qFill(list.begin() + 1, list.end(), "six"); +// list: [ "eleven", "six", "six" ] +//! [7] + + +//! [8] +QStringList list; +list << "one" << "two" << "three"; + +QStringList::iterator i1 = qFind(list.begin(), list.end(), "two"); +// i1 == list.begin() + 1 + +QStringList::iterator i2 = qFind(list.begin(), list.end(), "seventy"); +// i2 == list.end() +//! [8] + + +//! [9] +QList<int> list; +list << 3 << 3 << 6 << 6 << 6 << 8; + +int countOf6 = 0; +qCount(list.begin(), list.end(), 6, countOf6); +// countOf6 == 3 + +int countOf7 = 0; +qCount(list.begin(), list.end(), 7, countOf7); +// countOf7 == 0 +//! [9] + + +//! [10] +double pi = 3.14; +double e = 2.71; + +qSwap(pi, e); +// pi == 2.71, e == 3.14 +//! [10] + + +//! [11] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qSort(list.begin(), list.end()); +// list: [ 6, 12, 12, 33, 68 ] +//! [11] + + +//! [12] +bool caseInsensitiveLessThan(const QString &s1, const QString &s2) +{ + return s1.toLower() < s2.toLower(); +} + +int doSomething() +{ + QStringList list; + list << "AlPha" << "beTA" << "gamma" << "DELTA"; + qSort(list.begin(), list.end(), caseInsensitiveLessThan); + // list: [ "AlPha", "beTA", "DELTA", "gamma" ] +} +//! [12] + + +//! [13] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qSort(list.begin(), list.end(), qGreater<int>()); +// list: [ 68, 33, 12, 12, 6 ] +//! [13] + + +//! [14] +QStringList list; +list << "AlPha" << "beTA" << "gamma" << "DELTA"; + +QMap<QString, QString> map; +foreach (QString str, list) + map.insert(str.toLower(), str); + +list = map.values(); +//! [14] + + +//! [15] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qStableSort(list.begin(), list.end()); +// list: [ 6, 12, 12, 33, 68 ] +//! [15] + + +//! [16] +bool caseInsensitiveLessThan(const QString &s1, const QString &s2) +{ + return s1.toLower() < s2.toLower(); +} + +int doSomething() +{ + QStringList list; + list << "AlPha" << "beTA" << "gamma" << "DELTA"; + qStableSort(list.begin(), list.end(), caseInsensitiveLessThan); + // list: [ "AlPha", "beTA", "DELTA", "gamma" ] +} +//! [16] + + +//! [17] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qStableSort(list.begin(), list.end(), qGreater<int>()); +// list: [ 68, 33, 12, 12, 6 ] +//! [17] + + +//! [18] +QList<int> list; +list << 3 << 3 << 6 << 6 << 6 << 8; + +QList<int>::iterator i = qLowerBound(list.begin(), list.end(), 5); +list.insert(i, 5); +// list: [ 3, 3, 5, 6, 6, 6, 8 ] + +i = qLowerBound(list.begin(), list.end(), 12); +list.insert(i, 12); +// list: [ 3, 3, 5, 6, 6, 6, 8, 12 ] +//! [18] + + +//! [19] +QVector<int> vect; +vect << 3 << 3 << 6 << 6 << 6 << 8; +QVector<int>::iterator begin6 = + qLowerBound(vect.begin(), vect.end(), 6); +QVector<int>::iterator end6 = + qUpperBound(begin6, vect.end(), 6); + +QVector<int>::iterator i = begin6; +while (i != end6) { + *i = 7; + ++i; +} +// vect: [ 3, 3, 7, 7, 7, 8 ] +//! [19] + + +//! [20] +QList<int> list; +list << 3 << 3 << 6 << 6 << 6 << 8; + +QList<int>::iterator i = qUpperBound(list.begin(), list.end(), 5); +list.insert(i, 5); +// list: [ 3, 3, 5, 6, 6, 6, 8 ] + +i = qUpperBound(list.begin(), list.end(), 12); +list.insert(i, 12); +// list: [ 3, 3, 5, 6, 6, 6, 8, 12 ] +//! [20] + + +//! [21] +QVector<int> vect; +vect << 3 << 3 << 6 << 6 << 6 << 8; +QVector<int>::iterator begin6 = + qLowerBound(vect.begin(), vect.end(), 6); +QVector<int>::iterator end6 = + qUpperBound(vect.begin(), vect.end(), 6); + +QVector<int>::iterator i = begin6; +while (i != end6) { + *i = 7; + ++i; +} +// vect: [ 3, 3, 7, 7, 7, 8 ] +//! [21] + + +//! [22] +QVector<int> vect; +vect << 3 << 3 << 6 << 6 << 6 << 8; + +QVector<int>::iterator i = + qBinaryFind(vect.begin(), vect.end(), 6); +// i == vect.begin() + 2 (or 3 or 4) +//! [22] + + +//! [23] +QList<Employee *> list; +list.append(new Employee("Blackpool", "Stephen")); +list.append(new Employee("Twist", "Oliver")); + +qDeleteAll(list.begin(), list.end()); +list.clear(); +//! [23] + + +//! [24] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qSort(list.begin(), list.end(), qLess<int>()); +// list: [ 68, 33, 12, 12, 6 ] +//! [24] + + +//! [25] +QList<int> list; +list << 33 << 12 << 68 << 6 << 12; +qSort(list.begin(), list.end(), qGreater<int>()); +// list: [ 68, 33, 12, 12, 6 ] +//! [25] diff --git a/doc/src/snippets/code/doc_src_qaxcontainer.qdoc b/doc/src/snippets/code/doc_src_qaxcontainer.qdoc new file mode 100644 index 0000000..9edd87f --- /dev/null +++ b/doc/src/snippets/code/doc_src_qaxcontainer.qdoc @@ -0,0 +1,8 @@ +//! [0] +CONFIG += qaxcontainer +//! [0] + + +//! [1] +TYPELIBS = file.tlb +//! [1] diff --git a/doc/src/snippets/code/doc_src_qaxserver.qdoc b/doc/src/snippets/code/doc_src_qaxserver.qdoc new file mode 100644 index 0000000..9b51e66 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qaxserver.qdoc @@ -0,0 +1,223 @@ +//! [0] +TEMPLATE = app +CONFIG += qaxserver + +RC_FILE = qaxserver.rc +... +//! [0] + + +//! [1] +TEMPLATE = lib +CONFIG += qaxserver dll + +DEF_FILE = qaxserver.def +RC_FILE = qaxserver.rc +... +//! [1] + + +//! [2] +TEMPLATE = lib +VERSION = 2.5 +... +//! [2] + + +//! [3] +#include <QWidget> + +class MyActiveX : public QWidget +{ + Q_OBJECT +//! [3] + + +//! [4] +Q_CLASSINFO("ClassID", "{1D9928BD-4453-4bdd-903D-E525ED17FDE5}") +Q_CLASSINFO("InterfaceID", "{99F6860E-2C5A-42ec-87F2-43396F4BE389}") +Q_CLASSINFO("EventsID", "{0A3E9F27-E4F1-45bb-9E47-63099BCCD0E3}") +//! [4] + + +//! [5] +Q_PROPERTY(int value READ value WRITE setValue) +//! [5] + + +//! [6] +public: + MyActiveX(QWidget *parent = 0) + ... + + int value() const; + +public slots: + void setValue(int v); + ... + +signals: + void valueChange(int v); + ... + +}; +//! [6] + + +//! [7] +#include <QAxBindable> +#include <QWidget> + +class MyActiveX : public QWidget, public QAxBindable +{ + Q_OBJECT +//! [7] + + +//! [8] +QAXFACTORY_BEGIN("{ad90301a-849e-4e8b-9a91-0a6dc5f6461f}", + "{a8f21901-7ff7-4f6a-b939-789620c03d83}") + QAXCLASS(MyWidget) + QAXCLASS(MyWidget2) + QAXTYPE(MySubType) +QAXFACTORY_END() +//! [8] + + +//! [9] +#include <QApplication> +#include <QAxFactory> + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + if (!QAxFactory::isServer()) { + // create and show main window + } + return app.exec(); +} +//! [9] + + +//! [10] +MyFactory(const QUuid &, const QUuid &); +//! [10] + + +//! [11] +HMODULE dll = LoadLibrary("myserver.dll"); +typedef HRESULT(__stdcall *DllRegisterServerProc)(); +DllRegisterServerProc DllRegisterServer = + (DllRegisterServerProc)GetProcAddress(dll, "DllRegisterServer"); + +HRESULT res = E_FAIL; +if (DllRegisterServer) + res = DllRegisterServer(); +if (res != S_OK) + // error handling +//! [11] + + +//! [12] +cabarc N simpleax.cab simpleax.exe simple.inf +//! [12] + + +//! [13] +<object ID="MyActiveX1" CLASSID="CLSID:ad90301a-849e-4e8b-9a91-0a6dc5f6461f"> + ... +<\object> +//! [13] + + +//! [14] +<object ID=...> + <param name="name" value="value"> +<\object> +//! [14] + + +//! [15] +class MyActiveX : public QWidget +{ + Q_OBJECT + Q_CLASSINFO("Version", "2.0") + Q_CLASSINFO("ClassID", "{7a4cffd8-cbcd-4ae9-ae7e-343e1e5710df}") + Q_CLASSINFO("InterfaceID", "{6fb035bf-8019-48d8-be51-ef05427d8994}") + Q_CLASSINFO("EventsID", "{c42fffdf-6557-47c9-817a-2da2228bc29c}") + Q_CLASSINFO("Insertable", "yes") + Q_CLASSINFO("ToSuperClass", "MyActiveX") + Q_PROPERTY(...) + +public: + MyActiveX(QWidget *parent = 0); + + ... +}; +//! [15] + + +//! [16] +class MyLicensedControl : public QWidget +{ + Q_OBJECT + Q_CLASSINFO("LicenseKey", "<key string>") + ... +}; +//! [16] + + +//! [17] +class AxImpl : public QAxAggregated, public ISomeCOMInterface +{ +public: + AxImpl() {} + + long queryInterface(const QUuid &iid, void **iface); + + // IUnknown + QAXAGG_IUNKNOWN + + // ISomeCOMInterface + ... +} +//! [17] + + +//! [18] +long AxImpl::queryInterface(const QUuid &iid, void **iface) +{ + *iface = 0; + if (iid == IID_ISomeCOMInterface) + *iface = (ISomeCOMInterface *)this; + else + return E_NOINTERFACE; + + AddRef(); + return S_OK; +} +//! [18] + + +//! [19] +HRESULT AxImpl::QueryInterface(REFIID iid, void **iface) +{ + return controllingUnknown()->QueryInterface(iid, iface); +} +//! [19] + + +//! [20] +class MyActiveX : public QWidget, public QAxBindable +{ + Q_OBJECT + +public: + MyActiveX(QWidget *parent); + + QAxAggregated *createAggregate() + { + return new AxImpl(); + } +}; +//! [20] diff --git a/doc/src/snippets/code/doc_src_qcache.qdoc b/doc/src/snippets/code/doc_src_qcache.qdoc new file mode 100644 index 0000000..66bda6a --- /dev/null +++ b/doc/src/snippets/code/doc_src_qcache.qdoc @@ -0,0 +1,17 @@ +//! [0] +QCache<int, Employee> cache; +//! [0] + + +//! [1] +Employee *employee = new Employee; +employee->setId(37); +employee->setName("Richard Schmit"); +... +cache.insert(employee->id(), employee); +//! [1] + + +//! [2] +QCache<int, MyDataStructure> cache(5000); +//! [2] diff --git a/doc/src/snippets/code/doc_src_qdbusadaptors.qdoc b/doc/src/snippets/code/doc_src_qdbusadaptors.qdoc new file mode 100644 index 0000000..7f69a90 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qdbusadaptors.qdoc @@ -0,0 +1,253 @@ +//! [0] + class MainApplicationAdaptor: public QDBusAbstractAdaptor + { + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.kde.DBus.MainApplication") + Q_PROPERTY(QString caption READ caption WRITE setCaption) + Q_PROPERTY(QString organizationName READ organizationName) + Q_PROPERTY(QString organizationDomain READ organizationDomain) + + private: + QApplication *app; + + public: + MainApplicationAdaptor(QApplication *application) + : QDBusAbstractAdaptor(application), app(application) + { + connect(application, SIGNAL(aboutToQuit()), SIGNAL(aboutToQuit())); + connect(application, SIGNAL(focusChanged(QWidget*, QWidget*)), + SLOT(focusChangedSlot(QWidget*, QWidget*))); + } + + QString caption() + { + if (app->hasMainWindow()) + return app->mainWindow()->caption(); + return QString(""); // must not return a null QString + } + + void setCaption(const QString &newCaption) + { + if (app->hasMainWindow()) + app->mainWindow()->setCaption(newCaption); + } + + QString organizationName() + { + return app->organizationName(); + } + + QString organizationDomain() + { + return app->organizationDomain(); + } + + public slots: + Q_NOREPLY void quit() + { app->quit(); } + + void reparseConfiguration() + { app->reparseConfiguration(); } + + QString mainWindowObject() + { + if (app->hasMainWindow()) + return QString("/%1/mainwindow").arg(app->applicationName()); + return QString(); + } + + void setSessionManagement(bool enable) + { + if (enable) + app->enableSessionManagement(); + else + app->disableSessionManagement(); + } + + private slots: + void focusChangedSlot(QWidget *, QWidget *now) + { + if (now == app->mainWindow()) + emit mainWindowHasFocus(); + } + + signals: + void aboutToQuit(); + void mainWindowHasFocus(); + }; +//! [0] + + +//! [1] +interface org.kde.DBus.MainApplication +{ + property readwrite STRING caption + property read STRING organizationName + property read STRING organizationDomain + + method quit() annotation("org.freedesktop.DBus.Method.NoReply", "true") + method reparseConfiguration() + method mainWindowObject(out STRING) + method disableSessionManagement(in BOOLEAN enable) + + signal aboutToQuit() + signal mainWindowHasFocus() +} +//! [1] + + +//! [2] +int main(int argc, char **argv) +{ + // create the QApplication object + QApplication app(argc, argv); + + // create the MainApplication adaptor: + new MainApplicationAdaptor(app); + + // connect to D-Bus and register as an object: + QDBusConnection::sessionBus().registerObject("/MainApplication", app); + + // add main window, etc. + [...] + + app.exec(); +} +//! [2] + + +//! [3] +class MainApplicationAdaptor: public QDBusAbstractAdaptor +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.kde.DBus.MainApplication") +//! [3] + + +//! [4] + Q_PROPERTY(QString caption READ caption WRITE setCaption) + Q_PROPERTY(QString organizationName READ organizationName) + Q_PROPERTY(QString organizationDomain READ organizationDomain) +//! [4] + + +//! [5] +QString caption() +{ + if (app->hasMainWindow()) + return app->mainWindow()->caption(); + return QString(); +} + +void setCaption(const QString &newCaption) +{ + if (app->hasMainWindow()) + app->mainWindow()->setCaption(newCaption); +} + +QString organizationName() +{ + return app->organizationName(); +} + +QString organizationDomain() +{ + return app->organizationDomain(); +} +//! [5] + + +//! [6] +MyInterfaceAdaptor(QApplication *application) + : QDBusAbstractAdaptor(application), app(application) +{ + connect(application, SIGNAL(aboutToQuit()), SIGNAL(aboutToQuit()); + connect(application, SIGNAL(focusChanged(QWidget*, QWidget*)), + SLOT(focusChangedSlot(QWidget*, QWidget*))); +} +//! [6] + + +//! [7] +public slots: + Q_NOREPLY void quit() + { app->quit(); } + + void reparseConfiguration() + { app->reparseConfiguration(); } + + QString mainWindowObject() + { + if (app->hasMainWindow()) + return QString("/%1/mainwindow").arg(app->applicationName()); + return QString(); + } + + void setSessionManagement(bool enable) + { + if (enable) + app->enableSessionManagement(); + else + app->disableSessionManagement(); + } +//! [7] + + +//! [8] +signals: + void aboutToQuit(); + void mainWindowHasFocus(); +//! [8] + + +//! [9] +private slots: + void focusChangedSlot(QWidget *, QWidget *now) + { + if (now == app->mainWindow()) + emit mainWindowHasFocus(); + } +//! [9] + + +//! [10] +struct RequestData +{ + QString request; + QString processedData; + QDBusMessage reply; +}; + +QString processRequest(const QString &request, const QDBusMessage &message) +{ + RequestData *data = new RequestData; + data->request = request; + message.setDelayedReply(true); + data->reply = message.createReply(); + QDBusConnection::sessionBus().send(data->reply); + + appendRequest(data); + return QString(); +} +//! [10] + + +//! [11] +void sendReply(RequestData *data) +{ + // data->processedData has been initialized with the request's reply + QDBusMessage &reply = &data->reply; + + // send the reply over D-Bus: + reply << data->processedData; + QDBusConnection::sessionBus().send(reply); + + // dispose of the transaction data + delete data; +} +//! [11] + + +//! [12] +Q_NOREPLY void myMethod(); +//! [12] diff --git a/doc/src/snippets/code/doc_src_qiterator.qdoc b/doc/src/snippets/code/doc_src_qiterator.qdoc new file mode 100644 index 0000000..3dfa68a --- /dev/null +++ b/doc/src/snippets/code/doc_src_qiterator.qdoc @@ -0,0 +1,380 @@ +//! [0] +QList<float> list; +... +QListIterator<float> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [0] + + +//! [1] +QListIterator<float> i(list); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [1] + + +//! [2] +QLinkedList<float> list; +... +QLinkedListIterator<float> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [2] + + +//! [3] +QLinkedListIterator<float> i(list); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [3] + + +//! [4] +QVector<float> vector; +... +QVectorIterator<float> i(vector); +while (i.hasNext()) + qDebug() << i.next(); +//! [4] + + +//! [5] +QVectorIterator<float> i(vector); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [5] + + +//! [6] +QSet<QString> set; +... +QSetIterator<QString> i(set); +while (i.hasNext()) + qDebug() << i.next(); +//! [6] + + +//! [7] +QSetIterator<QString> i(set); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [7] + + +//! [8] +QList<float> list; +... +QMutableListIterator<float> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [8] + + +//! [9] +QMutableListIterator<float> i(list); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [9] + + +//! [10] +QMutableListIterator<int> i(list); +while (i.hasNext()) { + int val = i.next(); + if (val < 0) { + i.setValue(-val); + } else if (val == 0) { + i.remove(); + } +} +//! [10] + + +//! [11] +QLinkedList<float> list; +... +QMutableLinkedListIterator<float> i(list); +while (i.hasNext()) + qDebug() << i.next(); +//! [11] + + +//! [12] +QMutableLinkedListIterator<float> i(list); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [12] + + +//! [13] +QMutableLinkedListIterator<int> i(list); +while (i.hasNext()) { + int val = i.next(); + if (val < 0) { + i.setValue(-val); + } else if (val == 0) { + i.remove(); + } +} +//! [13] + + +//! [14] +QVector<float> vector; +... +QMutableVectorIterator<float> i(vector); +while (i.hasNext()) + qDebug() << i.next(); +//! [14] + + +//! [15] +QMutableVectorIterator<float> i(vector); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [15] + + +//! [16] +QMutableVectorIterator<int> i(vector); +while (i.hasNext()) { + int val = i.next(); + if (val < 0) { + i.setValue(-val); + } else if (val == 0) { + i.remove(); + } +} +//! [16] + + +//! [17] +QSet<float> set; +... +QMutableSetIterator<float> i(set); +while (i.hasNext()) + qDebug() << i.next(); +//! [17] + + +//! [18] +QMutableSetIterator<float> i(set); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [18] + + +//! [19] +QMutableListIterator<int> i(list); +while (i.hasNext()) { + int val = i.next(); + if (val < -32768 || val > 32767) + i.remove(); +} +//! [19] + + +//! [20] +QMutableLinkedListIterator<int> i(list); +while (i.hasNext()) { + int val = i.next(); + if (val < -32768 || val > 32767) + i.remove(); +} +//! [20] + + +//! [21] +QMutableVectorIterator<int> i(vector); +while (i.hasNext()) { + int val = i.next(); + if (val < -32768 || val > 32767) + i.remove(); +} +//! [21] + + +//! [22] +QMutableSetIterator<int> i(set); +while (i.hasNext()) { + int val = i.next(); + if (val < -32768 || val > 32767) + i.remove(); +} +//! [22] + + +//! [23] +QMutableListIterator<double> i(list); +while (i.hasNext()) { + double val = i.next(); + i.setValue(sqrt(val)); +} +//! [23] + + +//! [24] +QMutableLinkedListIterator<double> i(list); +while (i.hasNext()) { + double val = i.next(); + i.setValue(sqrt(val)); +} +//! [24] + + +//! [25] +QMutableVectorIterator<double> i(list); +while (i.hasNext()) { + double val = i.next(); + i.setValue(sqrt(val)); +} +//! [25] + + +//! [26] +QMap<int, QWidget *> map; +... +QMapIterator<int, QWidget *> i(map); +while (i.hasNext()) { + i.next(); + qDebug() << i.key() << ": " << i.value(); +} +//! [26] + + +//! [27] +QMapIterator<int, QWidget *> i(map); +i.toBack(); +while (i.hasPrevious()) { + i.previous(); + qDebug() << i.key() << ": " << i.value(); +} +//! [27] + + +//! [28] +QMapIterator<int, QWidget *> i(map); +while (i.findNext(widget)) { + qDebug() << "Found widget " << widget << " under key " + << i.key(); +} +//! [28] + + +//! [29] +QHash<int, QWidget *> hash; +... +QHashIterator<int, QWidget *> i(hash); +while (i.hasNext()) { + i.next(); + qDebug() << i.key() << ": " << i.value(); +} +//! [29] + + +//! [30] +QHashIterator<int, QWidget *> i(hash); +i.toBack(); +while (i.hasPrevious()) { + i.previous(); + qDebug() << i.key() << ": " << i.value(); +} +//! [30] + + +//! [31] +QHashIterator<int, QWidget *> i(hash); +while (i.findNext(widget)) { + qDebug() << "Found widget " << widget << " under key " + << i.key(); +} +//! [31] + + +//! [32] +QMap<int, QWidget *> map; +... +QMutableMapIterator<int, QWidget *> i(map); +while (i.hasNext()) { + i.next(); + qDebug() << i.key() << ": " << i.value(); +} +//! [32] + + +//! [33] +QMutableMapIterator<int, QWidget *> i(map); +i.toBack(); +while (i.hasPrevious()) { + i.previous(); + qDebug() << i.key() << ": " << i.value(); +} +//! [33] + + +//! [34] +QMutableMapIterator<int, QWidget *> i(map); +while (i.findNext(widget)) { + qDebug() << "Found widget " << widget << " under key " + << i.key(); +} +//! [34] + + +//! [35] +QMutableMapIterator<QString, QString> i(map); +while (i.hasNext()) { + i.next(); + if (i.key() == i.value()) + i.remove(); +} +//! [35] + + +//! [36] +QHash<int, QWidget *> hash; +... +QMutableHashIterator<QString, QWidget *> i(hash); +while (i.hasNext()) { + i.next(); + qDebug() << i.key() << ": " << i.value(); +} +//! [36] + + +//! [37] +QMutableHashIterator<int, QWidget *> i(hash); +i.toBack(); +while (i.hasPrevious()) { + i.previous(); + qDebug() << i.key() << ": " << i.value(); +} +//! [37] + + +//! [38] +QMutableHashIterator<int, QWidget *> i(hash); +while (i.findNext(widget)) { + qDebug() << "Found widget " << widget << " under key " + << i.key(); +} +//! [38] + + +//! [39] +QMutableHashIterator<QString, QString> i(hash); +while (i.hasNext()) { + i.next(); + if (i.key() == i.value()) + i.remove(); +} +//! [39] diff --git a/doc/src/snippets/code/doc_src_qmake-manual.qdoc b/doc/src/snippets/code/doc_src_qmake-manual.qdoc new file mode 100644 index 0000000..edb66bc --- /dev/null +++ b/doc/src/snippets/code/doc_src_qmake-manual.qdoc @@ -0,0 +1,813 @@ +//! [0] +make all +//! [0] + + +//! [1] +CONFIG += qt thread debug +//! [1] + + +//! [2] +CONFIG += qt +QT += network xml +//! [2] + + +//! [3] +QT = network xml # This will omit the core and gui modules. +//! [3] + + +//! [4] +QT -= gui # Only the core module is used. +//! [4] + + +//! [5] +CONFIG += link_pkgconfig +PKGCONFIG += ogg dbus-1 +//! [5] + + +//! [6] +LIBS += -L/usr/local/lib -lmath +//! [6] + + +//! [7] +INCLUDEPATH = c:/msdev/include d:/stl/include +//! [7] + + +//! [8] +qmake [mode] [options] files +//! [8] + + +//! [9] +qmake -makefile [options] files +//! [9] + + +//! [10] +qmake -makefile -unix -o Makefile "CONFIG+=test" test.pro +//! [10] + + +//! [11] +qmake "CONFIG+=test" test.pro +//! [11] + + +//! [12] +qmake -project [options] files +//! [12] + + +//! [13] +qmake -spec macx-g++ +//! [13] + + +//! [14] +QMAKE_LFLAGS += -F/path/to/framework/directory/ +//! [14] + + +//! [15] +LIBS += -framework TheFramework +//! [15] + + +//! [16] +TEMPLATE = lib +CONFIG += lib_bundle +//! [16] + + +//! [17] +FRAMEWORK_HEADERS.version = Versions +FRAMEWORK_HEADERS.files = path/to/header_one.h path/to/header_two.h +FRAMEWORK_HEADERS.path = Headers +QMAKE_BUNDLE_DATA += FRAMEWORK_HEADERS +//! [17] + + +//! [18] +CONFIG += x86 ppc +//! [18] + + +//! [19] +qmake -spec macx-xcode project.pro +//! [19] + + +//! [20] +qmake -tp vc +//! [20] + + +//! [21] +qmake -tp vc -r +//! [21] + + +//! [22] +CONFIG -= embed_manifest_exe +//! [22] + + +//! [23] +CONFIG -= embed_manifest_dll +//! [23] + + +//! [24] +make all +//! [24] + + +//! [25] +build_pass:CONFIG(debug, debug|release) { + unix: TARGET = $$join(TARGET,,,_debug) + else: TARGET = $$join(TARGET,,,d) +} +//! [25] + + +//! [26] +CONFIG += qt console newstuff +... +newstuff { + SOURCES += new.cpp + HEADERS += new.h +} +//! [26] + + +//! [27] +DEFINES += USE_MY_STUFF QT_DLL +//! [27] + + +//! [28] +myFiles.sources = path\*.png +DEPLOYMENT += myFiles +//! [28] + + +//! [29] +myFiles.sources = path\file1.ext1 path2\file2.ext1 path3\* +myFiles.path = \some\path\on\device +someother.sources = C:\additional\files\* +someother.path = \myFiles\path2 +DEPLOYMENT += myFiles someother +//! [29] + + +//! [30] +DESTDIR = ../../lib +//! [30] + + +//! [31] +DISTFILES += ../program.txt +//! [31] + + +//! [32] +FORMS = mydialog.ui \ + mywidget.ui \ + myconfig.ui +//! [32] + + +//! [33] +FORMS3 = my_uic3_dialog.ui \ + my_uic3_widget.ui \ + my_uic3_config.ui +//! [33] + + +//! [34] +HEADERS = myclass.h \ + login.h \ + mainwindow.h +//! [34] + + +//! [35] +INCLUDEPATH = c:/msdev/include d:/stl/include +//! [35] + + +//! [36] +target.path += $$[QT_INSTALL_PLUGINS]/imageformats +INSTALLS += target +//! [36] + + +//! [37] +LEXSOURCES = lexer.l +//! [37] + + +//! [38] +unix:LIBS += -L/usr/local/lib -lmath +win32:LIBS += c:/mylibs/math.lib +//! [38] + + +//! [39] +CONFIG += no_lflags_merge +//! [39] + + +//! [40] +unix:MOC_DIR = ../myproject/tmp +win32:MOC_DIR = c:/myproject/tmp +//! [40] + + +//! [41] +unix:OBJECTS_DIR = ../myproject/tmp +win32:OBJECTS_DIR = c:/myproject/tmp +//! [41] + + +//! [42] +app { + # Conditional code for 'app' template here +} +//! [42] + + +//! [43] +FRAMEWORK_HEADERS.version = Versions +FRAMEWORK_HEADERS.files = path/to/header_one.h path/to/header_two.h +FRAMEWORK_HEADERS.path = Headers +QMAKE_BUNDLE_DATA += FRAMEWORK_HEADERS +//! [43] + + +//! [44] +QMAKE_BUNDLE_EXTENSION = .myframework +//! [44] + + +//! [45] +QMAKE_RESOURCE_FLAGS += -threshold 0 -compress 9 +//! [45] + + +//! [46] +QMAKE_UIC = uic -L /path/to/plugin +//! [46] + + +//! [47] +QT -= gui # Only the core module is used. +//! [47] + + +//! [48] +unix:RCC_DIR = ../myproject/resources +win32:RCC_DIR = c:/myproject/resources +//! [48] + + +//! [49] +SOURCES = myclass.cpp \ + login.cpp \ + mainwindow.cpp +//! [49] + + +//! [50] +SUBDIRS = kernel \ + tools +//! [50] + + +//! [51] +CONFIG += ordered +//! [51] + + +//! [52] +TEMPLATE = app +TARGET = myapp +SOURCES = main.cpp +//! [52] + + +//! [53] +TEMPLATE = lib +SOURCES = main.cpp +TARGET = mylib +//! [53] + + +//! [54] +unix:UI_DIR = ../myproject/ui +win32:UI_DIR = c:/myproject/ui +//! [54] + + +//! [55] +unix:UI_HEADERS_DIR = ../myproject/ui/include +win32:UI_HEADERS_DIR = c:/myproject/ui/include +//! [55] + + +//! [56] +unix:UI_SOURCES_DIR = ../myproject/ui/src +win32:UI_SOURCES_DIR = c:/myproject/ui/src +//! [56] + + +//! [57] +VERSION = 1.2.3 +//! [57] + + +//! [58] +YACCSOURCES = moc.y +//! [58] + + +//! [59] +FILE = /etc/passwd +FILENAME = $$basename(FILE) #passwd +//! [59] + + +//! [60] +CONFIG = debug +CONFIG += release +CONFIG(release, debug|release):message(Release build!) #will print +CONFIG(debug, debug|release):message(Debug build!) #no print +//! [60] + + +//! [61] +contains( drivers, network ) { + # drivers contains 'network' + message( "Configuring for network build..." ) + HEADERS += network.h + SOURCES += network.cpp +} +//! [61] + + +//! [62] +error(An error has occurred in the configuration process.) +//! [62] + + +//! [63] +exists( $(QTDIR)/lib/libqt-mt* ) { + message( "Configuring for multi-threaded Qt..." ) + CONFIG += thread +} +//! [63] + + +//! [64] +MY_VAR = one two three four +MY_VAR2 = $$join(MY_VAR, " -L", -L) -Lfive +MY_VAR3 = $$member(MY_VAR, 2) $$find(MY_VAR, t.*) +//! [64] + + +//! [65] +LIST = 1 2 3 +for(a, LIST):exists(file.$${a}):message(I see a file.$${a}!) +//! [65] + + +//! [66] +include( shared.pri ) +OPTIONS = standard custom +!include( options.pri ) { + message( "No custom build options specified" ) +OPTIONS -= custom +} +//! [66] + + +//! [67] +isEmpty( CONFIG ) { +CONFIG += qt warn_on debug +} +//! [67] + + +//! [68] +message( "This is a message" ) +//! [68] + + +//! [69] +!build_pass:message( "This is a message" ) +//! [69] + + +//! [70] +This is a test. +//! [70] + + +//! [71] +system(ls /bin):HAS_BIN=FALSE +//! [71] + + +//! [72] +UNAME = $$system(uname -s) +contains( UNAME, [lL]inux ):message( This looks like Linux ($$UNAME) to me ) +//! [72] + + +//! [73] +ARGS = 1 2 3 2 5 1 +ARGS = $$unique(ARGS) #1 2 3 5 +//! [73] + + +//! [74] +qmake -set VARIABLE VALUE +//! [74] + + +//! [75] +qmake -query VARIABLE +qmake -query #queries all current VARIABLE/VALUE pairs.. +//! [75] + + +//! [76] +qmake -query "1.06a/VARIABLE" +//! [76] + + +//! [77] +qmake -query "QT_INSTALL_PREFIX" +//! [77] + + +//! [78] +QMAKE_VERS = $$[QMAKE_VERSION] +//! [78] + + +//! [79] +documentation.path = /usr/local/program/doc +documentation.files = docs/* +//! [79] + + +//! [80] +INSTALLS += documentation +//! [80] + + +//! [81] +unix:documentation.extra = create_docs; mv master.doc toc.doc +//! [81] + + +//! [82] +target.path = /usr/local/myprogram +INSTALLS += target +//! [82] + + +//! [83] +CONFIG += create_prl +//! [83] + + +//! [84] +CONFIG += link_prl +//! [84] + + +//! [85] +QMAKE_EXT_MOC = .mymoc +//! [85] + + +//! [86] +mytarget.target = .buildfile +mytarget.commands = touch $$mytarget.target +mytarget.depends = mytarget2 + +mytarget2.commands = @echo Building $$mytarget.target +//! [86] + + +//! [87] +QMAKE_EXTRA_TARGETS += mytarget mytarget2 +//! [87] + + +//! [88] +new_moc.output = moc_${QMAKE_FILE_BASE}.cpp +new_moc.commands = moc ${QMAKE_FILE_NAME} -o ${QMAKE_FILE_OUT} +new_moc.depend_command = g++ -E -M ${QMAKE_FILE_NAME} | sed "s,^.*: ,," +new_moc.input = NEW_HEADERS +QMAKE_EXTRA_COMPILERS += new_moc +//! [88] + + +//! [89] +TARGET = myapp +//! [89] + + +//! [90] +DEFINES += QT_DLL +//! [90] + + +//! [91] +DEFINES -= QT_DLL +//! [91] + + +//! [92] +DEFINES *= QT_DLL +//! [92] + + +//! [93] +DEFINES ~= s/QT_[DT].+/QT +//! [93] + + +//! [94] +EVERYTHING = $$SOURCES $$HEADERS +message("The project contains the following files:") +message($$EVERYTHING) +//! [94] + + +//! [95] +win32:DEFINES += QT_DLL +//! [95] + + +//! [96] +win32:xml { + message(Building for Windows) + SOURCES += xmlhandler_win.cpp +} else:xml { + SOURCES += xmlhandler.cpp +} else { + message("Unknown configuration") +} +//! [96] + + +//! [97] +MY_VARIABLE = value +//! [97] + + +//! [98] +MY_DEFINES = $$DEFINES +//! [98] + + +//! [99] +MY_DEFINES = $${DEFINES} +//! [99] + + +//! [100] +TARGET = myproject_$${TEMPLATE} +//! [100] + + +//! [101] +target.path = $$[QT_INSTALL_PLUGINS]/designer +INSTALLS += target +//! [101] + + +//! [102] +defineReplace(functionName){ + #function code +} +//! [102] + + +//! [103] +CONFIG += myfeatures +//! [103] + + +//! [104] +// Add C includes here + +#if defined __cplusplus +// Add C++ includes here +#include <stdlib> +#include <iostream> +#include <vector> +#include <QApplication> // Qt includes +#include <QPushButton> +#include <QLabel> +#include "thirdparty/include/libmain.h" +#include "my_stable_class.h" +... +#endif +//! [104] + + +//! [105] +PRECOMPILED_HEADER = stable.h +//! [105] + + +//! [106] +precompile_header:!isEmpty(PRECOMPILED_HEADER) { +DEFINES += USING_PCH +} +//! [106] + + +//! [107] +PRECOMPILED_HEADER = window.h +SOURCES = window.cpp +//! [107] + + +//! [108] +SOURCES += hello.cpp +//! [108] + + +//! [109] +SOURCES += hello.cpp +SOURCES += main.cpp +//! [109] + + +//! [110] +SOURCES = hello.cpp \ + main.cpp +//! [110] + + +//! [111] +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +//! [111] + + +//! [112] +TARGET = helloworld +//! [112] + + +//! [113] +CONFIG += qt +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +//! [113] + + +//! [114] +qmake -o Makefile hello.pro +//! [114] + + +//! [115] +qmake -tp vc -o hello.dsp hello.pro +//! [115] + + +//! [116] +CONFIG += qt debug +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +//! [116] + + +//! [117] +win32 { + SOURCES += hellowin.cpp +} +//! [117] + + +//! [118] +CONFIG += qt debug +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +win32 { + SOURCES += hellowin.cpp +} +unix { + SOURCES += hellounix.cpp +} +//! [118] + + +//! [119] +!exists( main.cpp ) { + error( "No main.cpp file found" ) +} +//! [119] + + +//! [120] +CONFIG += qt debug +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +win32 { + SOURCES += hellowin.cpp +} +unix { + SOURCES += hellounix.cpp +} +!exists( main.cpp ) { + error( "No main.cpp file found" ) +} +//! [120] + + +//! [121] +win32 { + debug { + CONFIG += console + } +} +//! [121] + + +//! [122] +CONFIG += qt debug +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +win32 { + SOURCES += hellowin.cpp +} +unix { + SOURCES += hellounix.cpp +} +!exists( main.cpp ) { + error( "No main.cpp file found" ) +} +win32:debug { + CONFIG += console +} +//! [122] + + +//! [123] +TEMPLATE = app +DESTDIR = c:/helloapp +HEADERS += hello.h +SOURCES += hello.cpp +SOURCES += main.cpp +DEFINES += QT_DLL +CONFIG += qt warn_on release +//! [123] + + +//! [124] +make all +//! [124] + + +//! [125] +make +//! [125] + + +//! [126] +make install +//! [126] + + +//! [127] +CONFIG(debug, debug|release) { + mac: TARGET = $$join(TARGET,,,_debug) + win32: TARGET = $$join(TARGET,,d) +} +//! [127] + +//! [128] +DEPLOYMENT_PLUGIN += qjpeg +//! [128] diff --git a/doc/src/snippets/code/doc_src_qnamespace.qdoc b/doc/src/snippets/code/doc_src_qnamespace.qdoc new file mode 100644 index 0000000..250d62d --- /dev/null +++ b/doc/src/snippets/code/doc_src_qnamespace.qdoc @@ -0,0 +1,24 @@ +//! [0] +QObject::connect: Cannot queue arguments of type 'MyType' +//! [0] + + +//! [1] +enum CustomEventPriority +{ + // An important event + ImportantEventPriority = Qt::HighEventPriority, + + // A more important event + MoreImportantEventPriority = ImportantEventPriority + 1, + + // A critical event + CriticalEventPriority = 100 * MoreImportantEventPriority, + + // Not that important + StatusEventPriority = Qt::LowEventPriority, + + // These are less important than Status events + IdleProcessingDoneEventPriority = StatusEventPriority - 1 +}; +//! [1] diff --git a/doc/src/snippets/code/doc_src_qpair.qdoc b/doc/src/snippets/code/doc_src_qpair.qdoc new file mode 100644 index 0000000..74c7c83 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qpair.qdoc @@ -0,0 +1,15 @@ +//! [0] +QPair<QString, double> pair; +//! [0] + + +//! [1] +pair.first = "pi"; +pair.second = 3.14159265358979323846; +//! [1] + + +//! [2] +QList<QPair<int, double> > list; +list.append(qMakePair(66, 3.14159)); +//! [2] diff --git a/doc/src/snippets/code/doc_src_qplugin.qdoc b/doc/src/snippets/code/doc_src_qplugin.qdoc new file mode 100644 index 0000000..d9b627e --- /dev/null +++ b/doc/src/snippets/code/doc_src_qplugin.qdoc @@ -0,0 +1,24 @@ +//! [0] +namespace Foo +{ + struct MyInterface { ... }; +} + +Q_DECLARE_INTERFACE(Foo::MyInterface, "org.examples.MyInterface") +//! [0] + + +//! [1] +Q_EXPORT_PLUGIN2(pnp_extrafilters, ExtraFiltersPlugin) +//! [1] + + +//! [2] +Q_IMPORT_PLUGIN(qjpeg) +//! [2] + + +//! [3] +TEMPLATE = app +QTPLUGIN += qjpeg qgif qmng # image formats +//! [3] diff --git a/doc/src/snippets/code/doc_src_qset.qdoc b/doc/src/snippets/code/doc_src_qset.qdoc new file mode 100644 index 0000000..7469d2a --- /dev/null +++ b/doc/src/snippets/code/doc_src_qset.qdoc @@ -0,0 +1,126 @@ +//! [0] +QSet<QString> set; +//! [0] + + +//! [1] +set.insert("one"); +set.insert("three"); +set.insert("seven"); +//! [1] + + +//! [2] +set << "twelve" << "fifteen" << "nineteen"; +//! [2] + + +//! [3] +if (!set.contains("ninety-nine")) + ... +//! [3] + + +//! [4] +QSetIterator<QWidget *> i(set); +while (i.hasNext()) + qDebug() << i.next(); +//! [4] + + +//! [5] +QSet<QWidget *>::const_iterator i = set.constBegin(); +while (i != set.constEnd()) { + qDebug() << *i; + ++i; +} +//! [5] + + +//! [6] +QSet<QString> set; +... +foreach (QString value, set) + qDebug() << value; +//! [6] + + +//! [7] +QSet<QString> set; +set.reserve(20000); +for (int i = 0; i < 20000; ++i) + set.insert(values[i]); +//! [7] + + +//! [8] +QSet<QString> set; +set << "January" << "February" << ... << "December"; + +QSet<QString>::iterator i; +for (i = set.begin(); i != set.end(); ++i) + qDebug() << *i; +//! [8] + + +//! [9] +QSet<QString> set; +set << "January" << "February" << ... << "December"; + +QSet<QString>::iterator i = set.begin(); +while (i != set.end()) { + if ((*i).startsWith('J')) { + i = set.erase(i); + } else { + ++i; + } +} +//! [9] + + +//! [10] +QSet<QString> set; +... +QSet<QString>::iterator it = qFind(set.begin(), set.end(), "Jeanette"); +if (it != set.end()) + cout << "Found Jeanette" << endl; +//! [10] + + +//! [11] +QSet<QString> set; +set << "January" << "February" << ... << "December"; + +QSet<QString>::const_iterator i; +for (i = set.begin(); i != set.end(); ++i) + qDebug() << *i; +//! [11] + + +//! [12] +QSet<QString> set; +... +QSet<QString>::iterator it = qFind(set.begin(), set.end(), "Jeanette"); +if (it != set.constEnd()) + cout << "Found Jeanette" << endl; +//! [12] + + +//! [13] +QSet<QString> set; +set << "red" << "green" << "blue" << ... << "black"; + +QList<QString> list = set.toList(); +qSort(list); +//! [13] + + +//! [14] +QStringList list; +list << "Julia" << "Mike" << "Mike" << "Julia" << "Julia"; + +QSet<QString> set = QSet<QString>::fromList(list); +set.contains("Julia"); // returns true +set.contains("Mike"); // returns true +set.size(); // returns 2 +//! [14] diff --git a/doc/src/snippets/code/doc_src_qsignalspy.qdoc b/doc/src/snippets/code/doc_src_qsignalspy.qdoc new file mode 100644 index 0000000..d6b65dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_qsignalspy.qdoc @@ -0,0 +1,41 @@ +//! [0] +QCheckBox *box = ...; +QSignalSpy spy(box, SIGNAL(clicked(bool))); + +// do something that triggers the signal +box->animateClick(); + +QCOMPARE(spy.count(), 1); // make sure the signal was emitted exactly one time +QList<QVariant> arguments = spy.takeFirst(); // take the first signal + +QVERIFY(arguments.at(0).toBool() == true); // verify the first argument +//! [0] + + +//! [1] +QSignalSpy spy(myCustomObject, SIGNAL(mySignal(int, QString, double))); + +myCustomObject->doSomething(); // trigger emission of the signal + +QList<QVariant> arguments = spy.takeFirst(); +QVERIFY(arguments.at(0).type() == QVariant::Int); +QVERIFY(arguments.at(1).type() == QVariant::QString); +QVERIFY(arguments.at(2).type() == QVariant::double); +//! [1] + + +//! [2] +qRegisterMetaType<QModelIndex>("QModelIndex"); +QSignalSpy spy(&model, SIGNAL(whatever(QModelIndex))); +//! [2] + + +//! [3] +// get the first argument from the first received signal: +QModelIndex result = qvariant_cast<QModelIndex>(spy.at(0).at(0)); +//! [3] + + +//! [4] +QSignalSpy spy(myPushButton, SIGNAL(clicked(bool))); +//! [4] diff --git a/doc/src/snippets/code/doc_src_qt-conf.qdoc b/doc/src/snippets/code/doc_src_qt-conf.qdoc new file mode 100644 index 0000000..d675795 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt-conf.qdoc @@ -0,0 +1,14 @@ +//! [0] +[Paths] +Prefix = /some/path +Translations = i18n +//! [0] + + +//! [1] +Paths +Paths/4 +Paths/4.1 +Paths/4.2.5 +Paths/6 +//! [1] diff --git a/doc/src/snippets/code/doc_src_qt-embedded-displaymanagement.qdoc b/doc/src/snippets/code/doc_src_qt-embedded-displaymanagement.qdoc new file mode 100644 index 0000000..a3ab4dd --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt-embedded-displaymanagement.qdoc @@ -0,0 +1,51 @@ +//! [0] +$QPEDIR/qtopiacore/qt/configure -help +//! [0] + + +//! [1] +./configure -help +//! [1] + + +//! [2] +./configure -extra-qt-embedded-config "-qt-gfx-transformed" +//! [2] + + +//! [3] +./configure -qt-gfx-transformed +//! [3] + + +//! [4] +export QWS_DISPLAY="<driver>[:<driver specific options>]... + [:<display num>]" +//! [4] + + +//! [5] +myApplication -display "<driver>[:<driver specific options>]... + [:<display num>]" +//! [5] + + +//! [6] +export QWS_DISPLAY="<driver>[:<subdriver>][:<subdriver options>]... + [ :<display num>]" +//! [6] + + +//! [7] +export QWS_DISPLAY="Multi: QVFb:0 QVFb:offset=640,0:1 :2" +//! [7] + + +//! [8] +export QWS_DISPLAY="VNC:size=720x480:depth=32" +//! [8] + + +//! [9] +export QWS_DISPLAY="VNC:LinuxFb" +//! [9] diff --git a/doc/src/snippets/code/doc_src_qt3support.qdoc b/doc/src/snippets/code/doc_src_qt3support.qdoc new file mode 100644 index 0000000..e6f0272 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt3support.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <Qt3Support> +//! [0] + + +//! [1] +QT += qt3support +//! [1] diff --git a/doc/src/snippets/code/doc_src_qt3to4.qdoc b/doc/src/snippets/code/doc_src_qt3to4.qdoc new file mode 100644 index 0000000..da0832d --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt3to4.qdoc @@ -0,0 +1,26 @@ +//! [0] +qt3to4 myfile.cpp +qt3to4 myapp.pro +//! [0] + + +//! [1] +<Rules> + <Include>/path/to/q3porting.xml</Include> + + <item Type="RenamedHeader" Disable="True" > + <Qt4>q3sqlselectcursor.h</Qt4> + <Qt3>qsqlselectcursor.h</Qt3> + </item> + + <item Type="RenamedHeader" > + <Qt4>newclass.h</Qt4> + <Qt3>oldclass.h</Qt3> + </item> +</Rules> +//! [1] + + +//! [2] +using namespace Qt; +//! [2] diff --git a/doc/src/snippets/code/doc_src_qt4-accessibility.qdoc b/doc/src/snippets/code/doc_src_qt4-accessibility.qdoc new file mode 100644 index 0000000..8bed0a9 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-accessibility.qdoc @@ -0,0 +1,59 @@ +//! [environment] +export QT_ACCESSIBILITY=1 +//! [environment] + +//! [0] +class MyWidgetInterface : public QAccessibleWidget +{ +public: + MyWidgetInterface(QWidget *widget, Role role); + + QString text(Text text, int child) const; + State state(int child) const; + QString actionText(int action, Text text, int child) const; + bool doAction(int action, int child, const QVariantList ¶ms); + ... +}; +//! [0] + + +//! [1] +bool MyWidgetInterface::doAction(int action, int child, + const QVariantList ¶ms) +{ + if (child || !widget()->isEnabled()) + return false; + + switch (action) { + case DefaultAction: + case Press: + { + MyWidget *widget = qobject_cast<MyWidget *>(object()); + if (widget) + widget->click(); + } + return true; + } + return QAccessibleWidget::doAction(action, child, params); +} +//! [1] + + +//! [2] +QStringList MyFactory::keys() const +{ + return QStringList() << "MyWidget" << "MyOtherWidget"; +} + +QAccessibleInterface *MyFactory::create(const QString &className, + QObject *object) +{ + if (classname == "MyWidget") + return new MyWidgetInterface(object); + if (classname == "MyOtherWidget") + return new MyOtherWidgetInterface(object); + return 0; +} + +Q_EXPORT_PLUGIN2(myfactory, MyFactory) +//! [2] diff --git a/doc/src/snippets/code/doc_src_qt4-arthur.qdoc b/doc/src/snippets/code/doc_src_qt4-arthur.qdoc new file mode 100644 index 0000000..6ac30ae --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-arthur.qdoc @@ -0,0 +1,104 @@ +//! [0] +QLinearGradient gradient(0, 0, 100, 100); +gradient.setColorAt(0, Qt::red); +gradient.setColorAt(0.5, Qt::green); +gradient.setColorAt(1, Qt::blue); +painter.setBrush(gradient); +painter.drawRect(0, 0, 100, 100); +//! [0] + + +//! [1] +QRadialGradient gradient(50, 50, 50, 30, 30); +gradient.setColorAt(0.2, Qt::white); +gradient.setColorAt(0.8, Qt::green); +gradient.setColorAt(1, Qt::black); +painter.setBrush(gradient); +painter.drawEllipse(0, 0, 100, 100); +//! [1] + + +//! [2] +QConicalGradient gradient(60, 40, 0); +gradient.setColorAt(0, Qt::black); +gradient.setColorAt(0.4, Qt::green); +gradient.setColorAt(0.6, Qt::white); +gradient.setColorAt(1, Qt::black); +painter.setBrush(gradient); +painter.drawEllipse(0, 0, 100, 100); +//! [2] + + +//! [3] +// Specfiy semi-transparent red +painter.setBrush(QColor(255, 0, 0, 127)); +painter.drawRect(0, 0, width()/2, height()); + +// Specify semi-transparend blue +painter.setBrush(QColor(0, 0, 255, 127)); +painter.drawRect(0, 0, width(), height()/2); +//! [3] + + +//! [4] +// One line without anti-aliasing +painter.drawLine(0, 0, width()/2, height()); + +// One line with anti-aliasing +painter.setRenderHint(QPainter::Antialiasing); +painter.drawLine(width()/2, 0, width()/2, height()); +//! [4] + + +//! [5] +QPainterPath path; +path.addRect(20, 20, 60, 60); +path.addBezier(0, 0, 99, 0, 50, 50, 99, 99); +path.addBezier(99, 99, 0, 99, 50, 50, 0, 0); +painter.drawPath(path); +//! [5] + + +//! [6] +QPixmap buffer(size()); +QPainter painter(&buffer); + +// Paint code here + +painter.end(); +bitBlt(this, 0, 0, &buffer); +//! [6] + + +//! [7] +QPainter painter(this); + +// Paint code here + +painter.end(); +//! [7] + + +//! [8] +unbufferedWidget->setAttribute(Qt::WA_PaintOnScreen); +//! [8] + + +//! [9] +QLinearGradient gradient(0, 0, 100, 100); +gradient.setColorAt(0, Qt::blue); +gradient.setColorAt(1, Qt::red); +painter.setPen(QPen(gradient, 0)); +for (int y=fontSize; y<100; y+=fontSize) + drawText(0, y, text); +//! [9] + + +//! [10] +QImage image(100, 100, 32); +QPainter painter(&image); + +// painter commands. + +painter.end(); +//! [10] diff --git a/doc/src/snippets/code/doc_src_qt4-intro.qdoc b/doc/src/snippets/code/doc_src_qt4-intro.qdoc new file mode 100644 index 0000000..ced563e --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-intro.qdoc @@ -0,0 +1,101 @@ +//! [0] +QT -= gui +//! [0] + + +//! [1] +QT += network opengl sql qt3support +//! [1] + + +//! [2] +CONFIG += uic3 +//! [2] + + +//! [3] +#include <QClassName> +//! [3] + + +//! [4] +#include <QString> +#include <QApplication> +#include <QSqlTableModel> +//! [4] + + +//! [5] +#include <qclassname.h> +//! [5] + + +//! [6] +#include <QtCore> +//! [6] + + +//! [7] +using namespace Qt; +//! [7] + + +//! [8] +QLabel *label1 = new QLabel("Hello", this); +QLabel *label2 = new QLabel(this, "Hello"); +//! [8] + + +//! [9] +MyWidget::MyWidget(QWidget *parent, const char *name) + : QWidget(parent, name) +{ + ... +} +//! [9] + + +//! [10] +// DEPRECATED +if (obj->inherits("QPushButton")) { + QPushButton *pushButton = (QPushButton *)obj; + ... +} +//! [10] + + +//! [11] +QPushButton *pushButton = qobject_cast<QPushButton *>(obj); +if (pushButton) { + ... +} +//! [11] + + +//! [12] +QLabel *label = new QLabel; +QPointer<QLabel> safeLabel = label; +safeLabel->setText("Hello world!"); +delete label; +// safeLabel is now 0, whereas label is a dangling pointer +//! [12] + + +//! [13] +QT += qt3support +//! [13] + + +//! [14] +DEFINES += QT3_SUPPORT +//! [14] + + +//! [15] +DEFINES += QT3_SUPPORT_WARNINGS +//! [15] + + +//! [16] +DEFINES += QT3_SUPPORT +//! [16] diff --git a/doc/src/snippets/code/doc_src_qt4-mainwindow.qdoc b/doc/src/snippets/code/doc_src_qt4-mainwindow.qdoc new file mode 100644 index 0000000..9e81fd1 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-mainwindow.qdoc @@ -0,0 +1,70 @@ +//! [0] +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) +{ +//! [0] + + +//! [1] +fileToolbar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); +addToolBar(Qt::TopToolBarArea, fileToolbar); +//! [1] + + +//! [2] +setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); +setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); +setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); +setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); +//! [2] + + +//! [3] +QWidget *centralWidget = new QWidget(this); +setCentralWidget(centralWidget); +//! [3] + + +//! [4] +QPopupMenu *fileMenu = new QPopupMenu(this); +openAction->addTo(fileMenu); +saveAction->addTo(fileMenu); +... +menuBar()->insertItem(tr("&File"), fileMenu); +//! [4] + + +//! [5] +QMenu *fileMenu = menuBar()->addMenu(tr("&File")); +fileMenu->addAction(openAction); +fileMenu->addAction(saveAction); +... +//! [5] + + +//! [6] +QToolBar *fileTools = new QToolBar(this, "file toolbar"); +openAction->addTo(fileTools); +saveAction->addTo(fileTools); +... +//! [6] + + +//! [7] +QToolBar *fileTools = addToolBar(tr("File Tool Bar")); +fileTools->addAction(openAction); +fileTools->addAction(saveAction); +... +//! [7] + + +//! [8] +QDockWidget *dockWidget = new QDockWidget(this); +mainWin->moveDockWidget(dockWidget, Qt::DockLeft); +//! [8] + + +//! [9] +QDockWidget *dockWidget = new QDockWidget(mainWindow); +mainWindow->addDockWidget(Qt::LeftDockWidgetArea, dockWidget); +//! [9] diff --git a/doc/src/snippets/code/doc_src_qt4-sql.qdoc b/doc/src/snippets/code/doc_src_qt4-sql.qdoc new file mode 100644 index 0000000..74b04eb --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-sql.qdoc @@ -0,0 +1,19 @@ +//! [0] +QSqlQueryModel model; +model.setQuery("select * from person"); + +QTableView view; +view.setModel(&model); +view.show(); +//! [0] + + +//! [1] +QSqlTableModel model; +model.setTable("person"); +model.select(); + +QTableView view; +view.setModel(&model); +view.show(); +//! [1] diff --git a/doc/src/snippets/code/doc_src_qt4-styles.qdoc b/doc/src/snippets/code/doc_src_qt4-styles.qdoc new file mode 100644 index 0000000..b75c135 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-styles.qdoc @@ -0,0 +1,42 @@ +//! [0] +const QStyleOptionFocusRect *focusRectOption = + qstyleoption_cast<const QStyleOptionFocusRect *>(option); +if (focusRectOption) { + ... +} +//! [0] + + +//! [1] +void MyWidget::paintEvent(QPaintEvent *event) +{ + QPainter painter(this); + ... + + QStyleOptionFocusRect option(1); + option.init(this); + option.backgroundColor = palette().color(QPalette::Window); + + style().drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter, + this); +} +//! [1] + + +//! [2] +void drawControl(ControlElement element, + QPainter *painter, + const QWidget *widget, + const QRect &rect, + const QColorGroup &colorGroup, + SFlags how = Style_Default, + const QStyleOption &option = QStyleOption::Default) const; +//! [2] + + +//! [3] +void drawControl(ControlElement element, + const QStyleOption *option, + QPainter *painter, + const QWidget *widget = 0) const; +//! [3] diff --git a/doc/src/snippets/code/doc_src_qt4-tulip.qdoc b/doc/src/snippets/code/doc_src_qt4-tulip.qdoc new file mode 100644 index 0000000..2bc5af1 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qt4-tulip.qdoc @@ -0,0 +1,100 @@ +//! [0] +foreach (variable, container) + statement; +//! [0] + + +//! [1] +QList<QString> list; +... +foreach (QString str, list) + cout << str.ascii() << endl; +//! [1] + + +//! [2] +QString str; +foreach (str, list) + cout << str.ascii() << endl; +//! [2] + + +//! [3] +// forward // backward +QList<QString> list; QList<QString> list; +... ... +QListIterator<QString> i(list); QListIterator<QString> i(list); +while (i.hasNext()) i.toBack(); + cout << i.next().ascii() << endl; while (i.hasPrev()) + cout << i.prev().ascii() << endl; +//! [3] + + +//! [4] +// forward // backward +QMutableListIterator<int> i(list); QMutableListIterator<int> i(list); +while (i.hasNext()) i.toBack(); + if (i.next() > 128) while (i.hasPrev()) + i.setValue(128); if (i.prev() > 128) + i.setValue(128); +//! [4] + + +//! [5] +// forward // backward +QMutableListIterator<int> i(list); QMutableListIterator<int> i(list); +while (i.hasNext()) i.toBack(); + if (i.next() % 2 != 0) while (i.hasPrev()) + i.remove(); if (i.prev() % 2 != 0) + i.remove(); +//! [5] + + +//! [6] +// STL-style // Java-style +QMap<int, QWidget *>::const_iterator i; QMapIterator<int, QWidget *> i(map); +for (i = map.begin(); i != map.end(); ++i) while (i.findNext(widget)) + if (i.value() == widget) cout << "Found widget " << widget + cout << "Found widget " << widget << " under key " + << " under key " << i.key() << endl; + << i.key() << endl; +//! [6] + + +//! [7] +// STL-style // Java-style +QList<int>::iterator i = list.begin(); QMutableListIterator<int> i(list); +while (i != list.end()) { while (i.hasNext()) { + if (*i == 0) { int val = i.next(); + i = list.erase(i); if (val < 0) + } else { i.setValue(-val); + if (*i < 0) else if (val == 0) + *i = -*i; i.remove(); + ++i; } + } +} +//! [7] + + +//! [8] +QList<double> list; +... +for (int i = 0; i < list.size(); ++i) { + if (list[i] < 0.0) + list[i] = 0.0; +} +//! [8] + + +//! [9] +QMap<QString, int> map; +... +map.value("TIMEOUT", 30); // returns 30 if "TIMEOUT" isn't in the map +//! [9] + + +//! [10] +QMultiMap<QString, int> map; +... +QList<int> values = map.values("TIMEOUT"); +//! [10] diff --git a/doc/src/snippets/code/doc_src_qtcore.qdoc b/doc/src/snippets/code/doc_src_qtcore.qdoc new file mode 100644 index 0000000..efa155f --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtcore.qdoc @@ -0,0 +1,3 @@ +//! [0] +#include <QtCore> +//! [0] diff --git a/doc/src/snippets/code/doc_src_qtdbus.qdoc b/doc/src/snippets/code/doc_src_qtdbus.qdoc new file mode 100644 index 0000000..4c8c4b0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtdbus.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <QtDBus> +//! [0] + + +//! [1] +QT += dbus +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtdesigner.qdoc b/doc/src/snippets/code/doc_src_qtdesigner.qdoc new file mode 100644 index 0000000..b19a747 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtdesigner.qdoc @@ -0,0 +1,293 @@ +//! [0] +#include <QtDesigner> +//! [0] + + +//! [1] +CONFIG += designer +//! [1] + + +//! [2] +QDesignerMemberSheetExtension *memberSheet = 0; +QExtensionManager manager = formEditor->extensionManager(); + +memberSheet = qt_extension<QDesignerMemberSheetExtension*>(manager, widget); +int index = memberSheet->indexOf(setEchoMode); +memberSheet->setVisible(index, false); + +delete memberSheet; +//! [2] + + +//! [3] +class MyMemberSheetExtension : public QObject, + public QDesignerMemberSheetExtension +{ + Q_OBJECT + Q_INTERFACES(QDesignerMemberSheetExtension) + +public: + ... +} +//! [3] + + +//! [4] +QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + if (iid != Q_TYPEID(QDesignerMemberSheetExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*> + (object)) + return new MyMemberSheetExtension(widget, parent); + + return 0; +} +//! [4] + + +//! [5] +QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerMemberSheetExtension))) { + return new MyMemberSheetExtension(widget, parent); + + } else { + return 0; + } +} +//! [5] + + +//! [6] +class MyContainerExtension : public QObject, + public QDesignerContainerExtension +{ + Q_OBJECT + Q_INTERFACES(QDesignerContainerExtension) + +public: + MyContainerExtension(MyCustomWidget *widget, + QObject *parent = 0); + int count() const; + QWidget *widget(int index) const; + int currentIndex() const; + void setCurrentIndex(int index); + void addWidget(QWidget *widget); + void insertWidget(int index, QWidget *widget); + void remove(int index); + +private: + MyCustomWidget *myWidget; +}; +//! [6] + + +//! [7] +QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + if (iid != Q_TYPEID(QDesignerContainerExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*> + (object)) + return new MyContainerExtension(widget, parent); + + return 0; +} +//! [7] + + +//! [8] +QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) { + return new MyContainerExtension(widget, parent); + + } else { + return 0; + } +} +//! [8] + + +//! [9] +class MyTaskMenuExtension : public QObject, + public QDesignerTaskMenuExtension +{ + Q_OBJECT + Q_INTERFACES(QDesignerTaskMenuExtension) + +public: + MyTaskMenuExtension(MyCustomWidget *widget, QObject *parent); + + QAction *preferredEditAction() const; + QList<QAction *> taskActions() const; + +private slots: + void mySlot(); + +private: + MyCustomWidget *widget; + QAction *myAction; +}; +//! [9] + + +//! [10] +QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + if (iid != Q_TYPEID(QDesignerTaskMenuExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object)) + return new MyTaskMenuExtension(widget, parent); + + return 0; +} +//! [10] + + +//! [11] +QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) { + return new MyContainerExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else { + return 0; + } +} +//! [11] + + +//! [12] +#include customwidgetoneinterface.h +#include customwidgettwointerface.h +#include customwidgetthreeinterface.h + +#include <QtDesigner/QtDesigner> +#include <QtCore/qplugin.h> + +class MyCustomWidgets: public QObject, public QDesignerCustomWidgetCollectionInterface +{ + Q_OBJECT + Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) + +public: + MyCustomWidgets(QObject *parent = 0); + + virtual QList<QDesignerCustomWidgetInterface*> customWidgets() const; + +private: + QList<QDesignerCustomWidgetInterface*> widgets; +}; +//! [12] + + +//! [13] +MyCustomWidgets::MyCustomWidgets(QObject *parent) + : QObject(parent) +{ + widgets.append(new CustomWidgetOneInterface(this)); + widgets.append(new CustomWidgetTwoInterface(this)); + widgets.append(new CustomWidgetThreeInterface(this)); +} + +QList<QDesignerCustomWidgetInterface*> MyCustomWidgets::customWidgets() const +{ + return widgets; +} + +Q_EXPORT_PLUGIN2(customwidgetsplugin, MyCustomWidgets) +//! [13] + + +//! [14] +Q_EXPORT_PLUGIN2(customwidgetplugin, MyCustomWidget) +//! [14] + + +//! [15] +QDesignerPropertySheetExtension *propertySheet = 0; +QExtensionManager manager = formEditor->extensionManager(); + +propertySheet = qt_extension<QDesignerPropertySheetExtension*>(manager, widget); +int index = propertySheet->indexOf(QLatin1String("margin")); + +propertySheet->setProperty(index, 10); +propertySheet->setChanged(index, true); + +delete propertySheet; +//! [15] + + +//! [16] +class MyPropertySheetExtension : public QObject, + public QDesignerPropertySheetExtension +{ + Q_OBJECT + Q_INTERFACES(QDesignerPropertySheetExtension) + +public: + ... +} +//! [16] + + +//! [17] +QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + if (iid != Q_TYPEID(QDesignerPropertySheetExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*> + (object)) + return new MyPropertySheetExtension(widget, parent); + + return 0; +} +//! [17] + + +//! [18] +QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const +{ + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerPropertySheetExtension))) { + return new MyPropertySheetExtension(widget, parent); + + } else { + return 0; + } +} +//! [18] diff --git a/doc/src/snippets/code/doc_src_qtestevent.qdoc b/doc/src/snippets/code/doc_src_qtestevent.qdoc new file mode 100644 index 0000000..87591e0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtestevent.qdoc @@ -0,0 +1,11 @@ +//! [0] +QTestEventList events; +events.addKeyClick('a'); +events.addKeyClick(Qt::Key_Backspace); +events.addDelay(200); + +QLineEdit *lineEdit = new QLineEdit(myParent); +... +events.simulate(lineEdit); +events.simulate(lineEdit); +//! [0] diff --git a/doc/src/snippets/code/doc_src_qtestlib.qdoc b/doc/src/snippets/code/doc_src_qtestlib.qdoc new file mode 100644 index 0000000..a4ef52e --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtestlib.qdoc @@ -0,0 +1,102 @@ +//! [0] +class MyFirstTest: public QObject +{ + Q_OBJECT +private slots: + void initTestCase() + { qDebug("called before everything else"); } + void myFirstTest() + { QVERIFY(1 == 1); } + void mySecondTest() + { QVERIFY(1 != 2); } + void cleanupTestCase() + { qDebug("called after myFirstTest and mySecondTest"); } +}; +//! [0] + + +//! [1] +QT += testlib +//! [1] + + +//! [2] +testname [options] [testfunctions[:testdata]]... +//! [2] + + +//! [3] +/myTestDirectory$ testQString toUpper +//! [3] + + +//! [4] +/myTestDirectory$ testQString toUpper toInt:zero +//! [4] + + +//! [5] +/myTestDirectory$ testMyWidget -vs -eventdelay 500 +//! [5] + + +//! [6] +cetest [options] ... +//! [6] + + +//! [7] +set INCLUDE=C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Inc;%INCLUDE% +set LIB=C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Activesync\Lib;%LIB% +//! [7] + + +//! [8] +void TestQString::toUpper() +{ + QString str = "Hello"; + QVERIFY(str.toUpper() == "HELLO"); +} +//! [8] + + +//! [9] +/myTestDirectory$ qmake -project "QT += testlib" +/myTestDirectory$ qmake +/myTestDirectory$ make +//! [9] + + +//! [10] +********* Start testing of TestQString ********* +Config: Using QTest library 4.1.0, Qt 4.1.0 +PASS : TestQString::initTestCase() +PASS : TestQString::toUpper() +PASS : TestQString::cleanupTestCase() +Totals: 3 passed, 0 failed, 0 skipped +********* Finished testing of TestQString ********* +//! [10] + + +//! [11] +QCOMPARE(QString("hello").toUpper(), QString("HELLO")); +QCOMPARE(QString("Hello").toUpper(), QString("HELLO")); +QCOMPARE(QString("HellO").toUpper(), QString("HELLO")); +QCOMPARE(QString("HELLO").toUpper(), QString("HELLO")); +//! [11] + +//! [12] +class MyFirstBenchmark: public QObject +{ + Q_OBJECT +private slots: + void myFirstBenchmark() + { + QString string1; + QString string2; + QBENCHMARK { + string1.localeAwareCompare(string2); + } + } +}; +//! [12]
\ No newline at end of file diff --git a/doc/src/snippets/code/doc_src_qtgui.qdoc b/doc/src/snippets/code/doc_src_qtgui.qdoc new file mode 100644 index 0000000..ff3afcf --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtgui.qdoc @@ -0,0 +1,3 @@ +//! [0] +#include <QtGui> +//! [0] diff --git a/doc/src/snippets/code/doc_src_qthelp.qdoc b/doc/src/snippets/code/doc_src_qthelp.qdoc new file mode 100644 index 0000000..11d231f --- /dev/null +++ b/doc/src/snippets/code/doc_src_qthelp.qdoc @@ -0,0 +1,161 @@ +//! [0] +#include <QtHelp> +//! [0] + + +//! [1] +CONFIG += help +//! [1] + + +//! [2] +qhelpgenerator doc.qhp -o doc.qch +//! [2] + + +//! [3] +<?xml version="1.0" encoding="utf-8" ?> +<QHelpCollectionProject version="1.0"> + <docFiles> + <register> + <file>doc.qch</file> + </register> + </docFiles> +</QHelpCollectionProject> +//! [3] + + +//! [4] +qcollectiongenerator mycollection.qhcp -o mycollection.qhc +//! [4] + + +//! [5] +... +<docFiles> + <generate> + <file> + <input>doc.qhp</input> + <output>doc.qch</output> + </file> + </generate> + <register> + <file>doc.qch</file> + </register> +</docFiles> +... +//! [5] + + +//! [6] +QHelpEngineCore helpEngine("mycollection.qhc"); +... + +// get all file references for the identifier +QMap<QString, QUrl> links = + helpEngine.linksForIdentifier(QLatin1String("MyDialog::ChangeButton")); + +// If help is available for this keyword, get the help data +// of the first file reference. +if (links.count()) { + QByteArray helpData = helpEngine->fileData(links.constBegin().value()); + // show the documentation to the user + if (!helpData.isEmpty()) + displayHelp(helpData); +} +//! [6] + + +//! [7] +<?xml version="1.0" encoding="UTF-8"?> +<QtHelpProject version="1.0"> + <namespace>mycompany.com.myapplication.1_0</namespace> + <virtualFolder>doc</virtualFolder> + <customFilter name="My Application 1.0"> + <filterAttribute>myapp</filterAttribute> + <filterAttribute>1.0</filterAttribute> + </customFilter> + <filterSection> + <filterAttribute>myapp</filterAttribute> + <filterAttribute>1.0</filterAttribute> + <toc> + <section title="My Application Manual" ref="index.html"> + <section title="Chapter 1" ref="doc.html#chapter1"/> + <section title="Chapter 2" ref="doc.html#chapter2"/> + <section title="Chapter 3" ref="doc.html#chapter3"/> + </section> + </toc> + <keywords> + <keyword name="foo" id="MyApplication::foo" ref="doc.html#foo"/> + <keyword name="bar" ref="doc.html#bar"/> + <keyword id="MyApplication::foobar" ref="doc.html#foobar"/> + </keywords> + <files> + <file>classic.css</file> + <file>index.html</file> + <file>doc.html</file> + </files> + </filterSection> +</QtHelpProject> +//! [7] + + +//! [8] +... +<virtualFolder>doc</virtualFolder> +... +//! [8] + + +//! [9] +... +<customFilter name="My Application 1.0"> + <filterAttribute>myapp</filterAttribute> + <filterAttribute>1.0</filterAttribute> +</customFilter> +... +//! [9] + + +//! [10] +... +<filterSection> + <filterAttribute>myapp</filterAttribute> + <filterAttribute>1.0</filterAttribute> +... +//! [10] + + +//! [11] +... +<toc> + <section title="My Application Manual" ref="index.html"> + <section title="Chapter 1" ref="doc.html#chapter1"/> + <section title="Chapter 2" ref="doc.html#chapter2"/> + <section title="Chapter 3" ref="doc.html#chapter3"/> + </section> +</toc> +... +//! [11] + + +//! [12] +... +<keywords> + <keyword name="foo" id="MyApplication::foo" ref="doc.html#foo"/> + <keyword name="bar" ref="doc.html#bar"/> + <keyword id="MyApplication::foobar" ref="doc.html#foobar"/> +</keywords> +... +//! [12] + + +//! [13] +... +<files> + <file>classic.css</file> + <file>index.html</file> + <file>doc.html</file> +</files> +... +//! [13] diff --git a/doc/src/snippets/code/doc_src_qtmac-as-native.qdoc b/doc/src/snippets/code/doc_src_qtmac-as-native.qdoc new file mode 100644 index 0000000..6ad42b9 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtmac-as-native.qdoc @@ -0,0 +1,3 @@ +//! [0] +qmake -spec macx-xcode project.pro +//! [0] diff --git a/doc/src/snippets/code/doc_src_qtnetwork.qdoc b/doc/src/snippets/code/doc_src_qtnetwork.qdoc new file mode 100644 index 0000000..4856686 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtnetwork.qdoc @@ -0,0 +1,8 @@ +//! [0] +QT += network +//! [0] + + +//! [1] +#include <QtNetwork> +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtopengl.qdoc b/doc/src/snippets/code/doc_src_qtopengl.qdoc new file mode 100644 index 0000000..e13cdf0 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtopengl.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <QtOpenGL> +//! [0] + + +//! [1] +QT += opengl +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtscript.qdoc b/doc/src/snippets/code/doc_src_qtscript.qdoc new file mode 100644 index 0000000..4031fef --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtscript.qdoc @@ -0,0 +1,948 @@ +//! [0] +#include <QtScript> +//! [0] + + +//! [1] +QT += script +//! [1] + + +//! [2] +function myInterestingScriptFunction() { ... } +... +myQObject.somethingChanged.connect(myInterestingScriptFunction); +//! [2] + + +//! [3] +myQObject.somethingChanged.connect(myOtherQObject.doSomething); +//! [3] + + +//! [4] +myQObject.somethingChanged.disconnect(myInterestingFunction); +myQObject.somethingChanged.disconnect(myOtherQObject.doSomething); +//! [4] + + +//! [5] +var obj = { x: 123 }; +var fun = function() { print(this.x); }; +myQObject.somethingChanged.connect(obj, fun); +//! [5] + + +//! [6] +myQObject.somethingChanged.disconnect(obj, fun); +//! [6] + + +//! [7] +var obj = { x: 123, fun: function() { print(this.x); } }; +myQObject.somethingChanged.connect(obj, "fun"); +//! [7] + + +//! [8] +myQObject.somethingChanged.disconnect(obj, "fun"); +//! [8] + + +//! [9] +try { + myQObject.somethingChanged.connect(myQObject, "slotThatDoesntExist"); +} catch (e) { + print(e); +} +//! [9] + + +//! [10] +myQObject.somethingChanged("hello"); +//! [10] + + +//! [11] +myQObject.myOverloadedSlot(10); // will call the int overload +myQObject.myOverloadedSlot("10"); // will call the QString overload +//! [11] + + +//! [12] +myQObject['myOverloadedSlot(int)']("10"); // call int overload; the argument is converted to an int +myQObject['myOverloadedSlot(QString)'](10); // call QString overload; the argument is converted to a string +//! [12] + + +//! [13] +Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) +//! [13] + + +//! [14] +myQObject.enabled = true; + +... + +myQObject.enabled = !myQObject.enabled; +//! [14] + + +//! [15] +myDialog.okButton +//! [15] + + +//! [16] +myDialog.okButton.objectName = "cancelButton"; +// from now on, myDialog.cancelButton references the button +//! [16] + + +//! [17] +var okButton = myDialog.findChild("okButton"); +if (okButton != null) { + // do something with the OK button +} + +var buttons = myDialog.findChildren(RegExp("button[0-9]+")); +for (var i = 0; i < buttons.length; ++i) { + // do something with buttons[i] +} +//! [17] + + +//! [18] +QScriptValue myQObjectConstructor(QScriptContext *context, QScriptEngine *engine) +{ + // let the engine manage the new object's lifetime. + return engine->newQObject(new MyQObject(), QScriptEngine::ScriptOwnership); +} +//! [18] + + +//! [19] +class MyObject : public QObject +{ + Q_OBJECT + +public: + MyObject( ... ); + + void aNonScriptableFunction(); + +public slots: // these functions (slots) will be available in QtScript + void calculate( ... ); + void setEnabled( bool enabled ); + bool isEnabled() const; + +private: + .... + +}; +//! [19] + + +//! [20] +class MyObject : public QObject +{ + Q_OBJECT + + public: + Q_INVOKABLE void thisMethodIsInvokableInQtScript(); + void thisMethodIsNotInvokableInQtScript(); + + ... +}; +//! [20] + + +//! [21] +var obj = new MyObject; +obj.setEnabled( true ); +print( "obj is enabled: " + obj.isEnabled() ); +//! [21] + + +//! [22] +var obj = new MyObject; +obj.enabled = true; +print( "obj is enabled: " + obj.enabled ); +//! [22] + + +//! [23] +class MyObject : public QObject +{ + Q_OBJECT + // define the enabled property + Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled ) + +public: + MyObject( ... ); + + void aNonScriptableFunction(); + +public slots: // these functions (slots) will be available in QtScript + void calculate( ... ); + void setEnabled( bool enabled ); + bool isEnabled() const; + +private: + .... + +}; +//! [23] + + +//! [24] +Q_PROPERTY(int nonScriptableProperty READ foo WRITE bar SCRIPTABLE false) +//! [24] + + +//! [25] +class MyObject : public QObject +{ + Q_OBJECT + // define the enabled property + Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled ) + +public: + MyObject( ... ); + + void aNonScriptableFunction(); + +public slots: // these functions (slots) will be available in QtScript + void calculate( ... ); + void setEnabled( bool enabled ); + bool isEnabled() const; + +signals: // the signals + void enabledChanged( bool newState ); + +private: + .... + +}; +//! [25] + + +//! [26] +function enabledChangedHandler( b ) +{ + print( "state changed to: " + b ); +} + +function init() +{ + var obj = new MyObject(); + // connect a script function to the signal + obj["enabledChanged(bool)"].connect(enabledChangedHandler); + obj.enabled = true; + print( "obj is enabled: " + obj.enabled ); +} +//! [26] + + +//! [27] +var o = new Object(); +o.foo = 123; +print(o.hasOwnProperty('foo')); // true +print(o.hasOwnProperty('bar')); // false +print(o); // calls o.toString(), which returns "[object Object]" +//! [27] + + +//! [28] +function Person(name) +{ + this.name = name; +} +//! [28] + + +//! [29] +Person.prototype.toString = function() { return "Person(name: " + this.name + ")"; } +//! [29] + + +//! [30] +var p1 = new Person("John Doe"); +var p2 = new Person("G.I. Jane"); +print(p1); // "Person(name: John Doe)" +print(p2); // "Person(name: G.I. Jane)" +//! [30] + + +//! [31] +print(p1.hasOwnProperty('name')); // 'name' is an instance variable, so this returns true +print(p1.hasOwnProperty('toString')); // returns false; inherited from prototype +print(p1 instanceof Person); // true +print(p1 instanceof Object); // true +//! [31] + + +//! [32] +function Employee(name, salary) +{ + Person.call(this, name); // call base constructor + + this.salary = salary; +} + +// set the prototype to be an instance of the base class +Employee.prototype = new Person(); + +// initialize prototype +Employee.prototype.toString = function() { ... } +//! [32] + + +//! [33] +var e = new Employee("Johnny Bravo", 5000000); +print(e instanceof Employee); // true +print(e instanceof Person); // true +print(e instanceof Object); // true +print(e instanceof Array); // false +//! [33] + + +//! [34] +QScriptValue Person_ctor(QScriptContext *context, QScriptEngine *engine) +{ + QString name = context->argument(0).toString(); + context->thisObject().setProperty("name", name); + return engine->undefinedValue(); +} +//! [34] + + +//! [35] +QScriptValue Person_prototype_toString(QScriptContext *context, QScriptEngine *engine) +{ + QString name = context->thisObject().property("name").toString(); + QString result = QString::fromLatin1("Person(name: %0)").arg(name); + return result; +} +//! [35] + + +//! [36] +QScriptEngine engine; +QScriptValue ctor = engine.newFunction(Person_ctor); +ctor.property("prototype").setProperty("toString", engine.newFunction(Person_prototype_toString)); +QScriptValue global = engine.globalObject(); +global.setProperty("Person", ctor); +//! [36] + + +//! [37] +QScriptValue Employee_ctor(QScriptContext *context, QScriptEngine *engine) +{ + QScriptValue super = context->callee().property("prototype").property("constructor"); + super.call(context->thisObject(), QScriptValueList() << context->argument(0)); + context->thisObject().setProperty("salary", context->argument(1)); + return engine->undefinedValue(); +} +//! [37] + + +//! [38] +QScriptValue empCtor = engine.newFunction(Employee_ctor); +empCtor.setProperty("prototype", global.property("Person").construct()); +global.setProperty("Employee", empCtor); +//! [38] + + +//! [39] +Q_DECLARE_METATYPE(QPointF) +Q_DECLARE_METATYPE(QPointF*) + +QScriptValue QPointF_prototype_x(QScriptContext *context, QScriptEngine *engine) +{ + // Since the point is not to be modified, it's OK to cast to a value here + QPointF point = qscriptvalue_cast<QPointF>(context->thisObject()); + return point.x(); +} + +QScriptValue QPointF_prototype_setX(QScriptContext *context, QScriptEngine *engine) +{ + // Cast to a pointer to be able to modify the underlying C++ value + QPointF *point = qscriptvalue_cast<QPointF*>(context->thisObject()); + if (!point) + return context->throwError(QScriptContext::TypeError, "QPointF.prototype.setX: this object is not a QPointF"); + point->setX(context->argument(0).toNumber()); + return engine->undefinedValue(); +} +//! [39] + + +//! [40] +var o = new Object(); +(o.__proto__ === Object.prototype); // this evaluates to true +//! [40] + + +//! [41] +var o = new Object(); +o.__defineGetter__("x", function() { return 123; }); +var y = o.x; // 123 +//! [41] + + +//! [42] +var o = new Object(); +o.__defineSetter__("x", function(v) { print("and the value is:", v); }); +o.x = 123; // will print "and the value is: 123" +//! [42] + + +//! [43] +class MyObject : public QObject +{ + Q_OBJECT + ... +}; + +Q_DECLARE_METATYPE(MyObject*) + +QScriptValue myObjectToScriptValue(QScriptEngine *engine, MyObject* const &in) +{ return engine->newQObject(in); } + +void myObjectFromScriptValue(const QScriptValue &object, MyObject* &out) +{ out = qobject_cast<MyObject*>(object.toQObject()); } + +... + +qScriptRegisterMetaType(&engine, myObjectToScriptValue, myObjectFromScriptValue); +//! [43] + +//! [44] +QScriptValue QPoint_ctor(QScriptContext *context, QScriptEngine *engine) +{ + int x = context->argument(0).toInt32(); + int y = context->argument(1).toInt32(); + return engine->toScriptValue(QPoint(x, y)); +} + +... + +engine.globalObject().setProperty("QPoint", engine.newFunction(QPoint_ctor)); +//! [44] + +//! [45] +QScriptValue myPrintFunction(QScriptContext *context, QScriptEngine *engine) +{ + QString result; + for (int i = 0; i < context->argumentCount(); ++i) { + if (i > 0) + result.append(" "); + result.append(context->argument(i).toString()); + } + + QScriptValue calleeData = context->callee().data(); + QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(calleeData.toQObject()); + edit->appendPlainText(result); + + return engine->undefinedValue(); +} +//! [45] + +//! [46] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QScriptEngine eng; + QPlainTextEdit edit; + + QScriptValue fun = eng.newFunction(myPrintFunction); + fun.setData(eng.newQObject(&edit)); + eng.globalObject().setProperty("print", fun); + + eng.evaluate("print('hello', 'world')"); + + edit.show(); + return app.exec(); +} +//! [46] + + +//! [47] +QScriptEngine eng; +QLineEdit *edit = new QLineEdit(...); +QScriptValue handler = eng.evaluate("function(text) { print('text was changed to', text); }"); +qScriptConnect(edit, SIGNAL(textChanged(const QString &)), QScriptValue(), handler); +//! [47] + +//! [48] +QLineEdit *edit1 = new QLineEdit(...); +QLineEdit *edit2 = new QLineEdit(...); + +QScriptValue handler = eng.evaluate("function() { print('I am', this.name); }"); +QScriptValue obj1 = eng.newObject(); +obj1.setProperty("name", "the walrus"); +QScriptValue obj2 = eng.newObject(); +obj2.setProperty("name", "Sam"); + +qScriptConnect(edit1, SIGNAL(returnPressed()), obj1, handler); +qScriptConnect(edit2, SIGNAL(returnPressed()), obj2, handler); +//! [48] + +//! [49] +var getProperty = function(name) { return this[name]; }; + +name = "Global Object"; // creates a global variable +print(getProperty("name")); // "Global Object" + +var myObject = { name: 'My Object' }; +print(getProperty.call(myObject, "name")); // "My Object" + +myObject.getProperty = getProperty; +print(myObject.getProperty("name")); // "My Object" + +getProperty.name = "The getProperty() function"; +getProperty.getProperty = getProperty; +getProperty.getProperty("name"); // "The getProperty() function" +//! [49] + +//! [50] +var o = { a: 1, b: 2, sum: function() { return a + b; } }; +print(o.sum()); // reference error, or sum of global variables a and b!! +//! [50] + +//! [51] +var o = { a: 1, b: 2, sum: function() { return this.a + this.b; } }; +print(o.sum()); // 3 +//! [51] + +//! [52] +QScriptValue getProperty(QScriptContext *ctx, QScriptEngine *eng) +{ + QString name = ctx->argument(0).toString(); + return ctx->thisObject().property(name); +} +//! [52] + +//! [53] +QScriptValue myCompare(QScriptContext *ctx, QScriptEngine *eng) +{ + double first = ctx->argument(0).toNumber(); + double second = ctx->argument(1).toNumber(); + int result; + if (first == second) + result = 0; + else if (first < second) + result = -1; + else + result = 1; + return result; +} +//! [53] + +//! [54] +QScriptEngine eng; +QScriptValue comparefn = eng.newFunction(myCompare); +QScriptValue array = eng.evaluate("new Array(10, 5, 20, 15, 30)"); +array.property("sort").call(array, QScriptValueList() << comparefn); + +// prints "5,10,15,20,30" +qDebug() << array.toString(); +//! [54] + +//! [55] +QScriptValue rectifier(QScriptContext *ctx, QScriptEngine *eng) +{ + QRectF magicRect = qscriptvalue_cast<QRectF>(ctx->callee().data()); + QRectF sourceRect = qscriptvalue_cast<QRectF>(ctx->argument(0)); + return eng->toScriptValue(sourceRect.intersected(magicRect)); +} + +... + +QScriptValue fun = eng.newFunction(rectifier); +QRectF magicRect = QRectF(10, 20, 30, 40); +fun.setData(eng.toScriptValue(magicRect)); +eng.globalObject().setProperty("rectifier", fun); +//! [55] + +//! [56] +function add(a, b) { + return a + b; +} +//! [56] + +//! [57] +function add() { + return arguments[0] + arguments[1]; +} +//! [57] + +//! [58] +QScriptValue add(QScriptContext *ctx, QScriptEngine *eng) +{ + double a = ctx->argument(0).toNumber(); + double b = ctx->argument(1).toNumber(); + return a + b; +} +//! [58] + +//! [59] +function add() { + if (arguments.length != 2) + throw Error("add() takes exactly two arguments"); + return arguments[0] + arguments[1]; +} +//! [59] + +//! [60] +function add() { + if (arguments.length != 2) + throw Error("add() takes exactly two arguments"); + if (typeof arguments[0] != "number") + throw TypeError("add(): first argument is not a number"); + if (typeof arguments[1] != "number") + throw TypeError("add(): second argument is not a number"); + return arguments[0] + arguments[1]; +} +//! [60] + +//! [61] +function add() { + if (arguments.length != 2) + throw Error("add() takes exactly two arguments"); + return Number(arguments[0]) + Number(arguments[1]); +} +//! [61] + +//! [62] +QScriptValue add(QScriptContext *ctx, QScriptEngine *eng) +{ + if (ctx->argumentCount() != 2) + return ctx->throwError("add() takes exactly two arguments"); + double a = ctx->argument(0).toNumber(); + double b = ctx->argument(1).toNumber(); + return a + b; +} +//! [62] + +//! [63] +QScriptValue add(QScriptContext *ctx, QScriptEngine *eng) +{ + if (ctx->argumentCount() != 2) + return ctx->throwError("add() takes exactly two arguments"); + if (!ctx->argument(0).isNumber()) + return ctx->throwError(QScriptContext::TypeError, "add(): first argument is not a number"); + if (!ctx->argument(1).isNumber()) + return ctx->throwError(QScriptContext::TypeError, "add(): second argument is not a number"); + double a = ctx->argument(0).toNumber(); + double b = ctx->argument(1).toNumber(); + return a + b; +} +//! [63] + +//! [64] +function concat() { + var result = ""; + for (var i = 0; i < arguments.length; ++i) + result += String(arguments[i]); + return result; +} +//! [64] + +//! [65] +QScriptValue concat(QScriptContext *ctx, QScriptEngine *eng) +{ + QString result = ""; + for (int i = 0; i < ctx->argumentCount(); ++i) + result += ctx->argument(i).toString(); + return result; +} +//! [65] + +//! [66] +function sort(comparefn) { + if (comparefn == undefined) + comparefn = /* the built-in comparison function */; + else if (typeof comparefn != "function") + throw TypeError("sort(): argument must be a function"); + ... +} +//! [66] + +//! [67] +QScriptValue sort(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue comparefn = ctx->argument(0); + if (comparefn.isUndefined()) + comparefn = /* the built-in comparison function */; + else if (!comparefn.isFunction()) + return ctx->throwError(QScriptContext::TypeError, "sort(): argument is not a function"); + ... +} +//! [67] + +//! [68] +function foo() { + // Let bar() take care of this. + print("calling bar() with " + arguments.length + "arguments"); + var result = return bar.apply(this, arguments); + print("bar() returned" + result); + return result; +} +//! [68] + +//! [69] +QScriptValue foo(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue bar = eng->globalObject().property("bar"); + QScriptValue arguments = ctx->argumentsObject(); + qDebug() << "calling bar() with" << arguments.property("length").toInt32() << "arguments"; + QScriptValue result = bar.apply(ctx->thisObject(), arguments); + qDebug() << "bar() returned" << result.toString(); + return result; +} +//! [69] + +//! [70] +function counter() { + var count = 0; + return function() { + return count++; + } +} +//! [70] + +//! [71] +var c1 = counter(); // create a new counter function +var c2 = counter(); // create a new counter function +print(c1()); // 0 +print(c1()); // 1 +print(c2()); // 0 +print(c2()); // 1 +//! [71] + +//! [72] +QScriptValue counter(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue act = ctx->activationObject(); + act.setProperty("count", 0); + QScriptValue result = eng->newFunction(counter_inner); + result.setScope(act); + return result; +} +//! [72] + +//! [73] +QScriptValue counter_inner(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue outerAct = ctx->callee().scope(); + double count = outerAct.property("count").toNumber(); + outerAct.setProperty("count", count+1); + return count; +} +//! [73] + +//! [74] +QScriptValue counter_hybrid(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue act = ctx->activationObject(); + act.setProperty("count", 0); + return eng->evaluate("function() { return count++; }"); +} +//! [74] + +//! [75] +function Book(isbn) { + this.isbn = isbn; +} + +var coolBook1 = new Book("978-0131872493"); +var coolBook2 = new Book("978-1593271473"); +//! [75] + +//! [76] +QScriptValue Person_ctor(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue object; + if (ctx->isCalledAsConstructor()) { + object = ctx->thisObject(); + } else { + object = eng->newObject(); + object.setPrototype(ctx->callee().property("prototype")); + } + object.setProperty("name", ctx->argument(0)); + return object; +} +//! [76] + +//! [77] +QScriptContext *ctx = eng.pushContext(); +QScriptValue act = ctx->activationObject(); +act.setProperty("digit", 7); + +qDebug() << eng.evaluate("digit + 1").toNumber(); // 8 + +eng.popContext(); +//! [77] + +//! [78] +QScriptValue getSet(QScriptContext *ctx, QScriptEngine *eng) +{ + QScriptValue obj = ctx->thisObject(); + QScriptValue data = obj.data(); + if (!data.isValid()) { + data = eng->newObject(); + obj.setData(data); + } + QScriptValue result; + if (ctx->argumentCount() == 1) { + QString str = ctx->argument(0).toString(); + str.replace("Roberta", "Ken"); + result = str; + data.setProperty("x", result); + } else { + result = data.property("x"); + } + return result; +} +//! [78] + +//! [79] +QScriptEngine eng; +QScriptValue obj = eng.newObject(); +obj.setProperty("x", eng.newFunction(getSet), + QScriptValue::PropertyGetter|QScriptValue::PropertySetter); +//! [79] + +//! [80] +obj.x = "Roberta sent me"; +print(obj.x); // "Ken sent me" +obj.x = "I sent the bill to Roberta"; +print(obj.x); // "I sent the bill to Ken" +//! [80] + +//! [81] +obj = {}; +obj.__defineGetter__("x", function() { return this._x; }); +obj.__defineSetter__("x", function(v) { print("setting x to", v); this._x = v; }); +obj.x = 123; +//! [81] + +//! [82] +myButton.text = qsTr("Hello world!"); +//! [82] + +//! [83] +myButton.text = qsTranslate("MyAwesomeScript", "Hello world!"); +//! [83] + +//! [84] +FriendlyConversation.prototype.greeting = function(type) +{ + if (FriendlyConversation['greeting_strings'] == undefined) { + FriendlyConversation['greeting_strings'] = [ + QT_TR_NOOP("Hello"), + QT_TR_NOOP("Goodbye") + ]; + } + return qsTr(FriendlyConversation.greeting_strings[type]); +} +//! [84] + +//! [85] +FriendlyConversation.prototype.greeting = function(type) +{ + if (FriendlyConversation['greeting_strings'] == undefined) { + FriendlyConversation['greeting_strings'] = [ + QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), + QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") + ]; + } + return qsTranslate("FriendlyConversation", FriendlyConversation.greeting_strings[type]); +} +//! [85] + +//! [86] +FileCopier.prototype.showProgress = function(done, total, currentFileName) +{ + this.label.text = qsTr("%1 of %2 files copied.\nCopying: %3") + .arg(done) + .arg(total) + .arg(currentFileName)); +} +//! [86] + +//! [87] +lupdate myscript.qs -ts myscript_la.ts +//! [87] + +//! [88] +lupdate -extensions qs scripts/ -ts scripts_la.ts +//! [88] + +//! [89] +lrelease myscript_la.ts +//! [89] + +//! [90] +({ unitName: "Celsius", + toKelvin: function(x) { return x + 273; } + }) +//! [90] + +//! [91] +QScriptValue object = engine.evaluate("({ unitName: 'Celsius', toKelvin: function(x) { return x + 273; } })"); +QScriptValue toKelvin = object.property("toKelvin"); +QScriptValue result = toKelvin.call(object, QScriptValueList() << 100); +qDebug() << result.toNumber(); // 373 +//! [91] + +//! [92] +QScriptValue add = engine.globalObject().property("add"); +qDebug() << add.call(QScriptValue(), QScriptValueList() << 1 << 2).toNumber(); // 3 +//! [92] + +//! [93] +typedef QSharedPointer<QXmlStreamReader> XmlStreamReaderPointer; + +Q_DECLARE_METATYPE(XmlStreamReaderPointer) + +QScriptValue constructXmlStreamReader(QScriptContext *context, QScriptEngine *engine) +{ + if (!context->isCalledAsConstructor()) + return context->throwError(QScriptContext::SyntaxError, "please use the 'new' operator"); + + QIODevice *device = qobject_cast<QIODevice*>(context->argument(0).toQObject()); + if (!device) + return context->throwError(QScriptContext::TypeError, "please supply a QIODevice as first argument"); + + // Create the C++ object + QXmlStreamReader *reader = new QXmlStreamReader(device); + + XmlStreamReaderPointer pointer(reader); + + // store the shared pointer in the script object that we are constructing + return engine->newVariant(context->thisObject(), qVariantFromValue(pointer)); +} +//! [93] + +//! [94] +QScriptValue xmlStreamReader_atEnd(QScriptContext *context, QScriptEngine *) +{ + XmlStreamReaderPointer reader = qscriptvalue_cast<XmlStreamReaderPointer>(context->thisObject()); + if (!reader) + return context->throwError(QScriptContext::TypeError, "this object is not an XmlStreamReader"); + return reader->atEnd(); +} +//! [94] + +//! [95] + QScriptEngine engine; + QScriptValue xmlStreamReaderProto = engine.newObject(); + xmlStreamReaderProto.setProperty("atEnd", engine.newFunction(xmlStreamReader_atEnd)); + + QScriptValue xmlStreamReaderCtor = engine.newFunction(constructXmlStreamReader, xmlStreamReaderProto); + engine.globalObject().setProperty("XmlStreamReader", xmlStreamReaderCtor); +//! [95] diff --git a/doc/src/snippets/code/doc_src_qtscriptextensions.qdoc b/doc/src/snippets/code/doc_src_qtscriptextensions.qdoc new file mode 100644 index 0000000..24fb254 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtscriptextensions.qdoc @@ -0,0 +1,7 @@ +//! [0] +print("importing " + __extension__); +__setupPackage__("cool.stuff"); + +cool.stuff.add = function(a, b) { return a + b; } +cool.stuff.subtract = function(a, b) { return a - b; } +//! [0] diff --git a/doc/src/snippets/code/doc_src_qtsql.qdoc b/doc/src/snippets/code/doc_src_qtsql.qdoc new file mode 100644 index 0000000..1a687db --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtsql.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <QtSql> +//! [0] + + +//! [1] +QT += sql +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtsvg.qdoc b/doc/src/snippets/code/doc_src_qtsvg.qdoc new file mode 100644 index 0000000..c99ea41 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtsvg.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <QtSvg> +//! [0] + + +//! [1] +QT += svg +//! [1] diff --git a/doc/src/snippets/code/doc_src_qttest.qdoc b/doc/src/snippets/code/doc_src_qttest.qdoc new file mode 100644 index 0000000..c2aa27b --- /dev/null +++ b/doc/src/snippets/code/doc_src_qttest.qdoc @@ -0,0 +1,8 @@ +//! [0] +#include <QtTest> +//! [0] + + +//! [1] +CONFIG += qtestlib +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtuiloader.qdoc b/doc/src/snippets/code/doc_src_qtuiloader.qdoc new file mode 100644 index 0000000..64f3eac --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtuiloader.qdoc @@ -0,0 +1,8 @@ +//! [0] +CONFIG += uitools +//! [0] + + +//! [1] +#include <QtUiTools> +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtwebkit.qdoc b/doc/src/snippets/code/doc_src_qtwebkit.qdoc new file mode 100644 index 0000000..d4fc2bd --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtwebkit.qdoc @@ -0,0 +1,8 @@ +//! [0] +QT += webkit +//! [0] + + +//! [1] +#include <QtWebKit> +//! [1] diff --git a/doc/src/snippets/code/doc_src_qtxml.qdoc b/doc/src/snippets/code/doc_src_qtxml.qdoc new file mode 100644 index 0000000..f5dc5a5 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtxml.qdoc @@ -0,0 +1,77 @@ +//! [0] +#include <QtXml> +//! [0] + + +//! [1] +QT += xml +//! [1] + + +//! [2] +QT += xml +//! [2] + + +//! [3] +<quote>A quotation.</quote> +//! [3] + + +//! [4] +<document xmlns:book = 'http://qtsoftware.com/fnord/book/' + xmlns = 'http://qtsoftware.com/fnord/' > +//! [4] + + +//! [5] +<author xmlns:fnord = 'http://qtsoftware.com/fnord/' + title="Ms" + fnord:title="Goddess" + name="Eris Kallisti"/> +//! [5] + + +//! [6] +<document> +<book> + <title>Practical XML</title> + <author title="Ms" name="Eris Kallisti"/> + <chapter> + <title>A Namespace Called fnord</title> + </chapter> +</book> +</document> +//! [6] + + +//! [7] +<book:title>Practical XML</book:title> +//! [7] + + +//! [8] +xmlns="http://qtsoftware.com/fnord/" +//! [8] + + +//! [9] +xmlns:book="http://qtsoftware.com/fnord/book/" +//! [9] + + +//! [10] +<document xmlns:book = 'http://qtsoftware.com/fnord/book/' + xmlns = 'http://qtsoftware.com/fnord/' > +<book> + <book:title>Practical XML</book:title> + <book:author xmlns:fnord = 'http://qtsoftware.com/fnord/' + title="Ms" + fnord:title="Goddess" + name="Eris Kallisti"/> + <chapter> + <title>A Namespace Called fnord</title> + </chapter> +</book> +</document> +//! [10] diff --git a/doc/src/snippets/code/doc_src_qtxmlpatterns.qdoc b/doc/src/snippets/code/doc_src_qtxmlpatterns.qdoc new file mode 100644 index 0000000..638bf93 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qtxmlpatterns.qdoc @@ -0,0 +1,349 @@ + +void wrapInFunction() +{ + +//! [0] +#include <QtXmlPatterns> +//! [0] + + +//! [1] +QT += xmlpatterns +//! [1] + +//! [2] +xmlpatterns myQuery.xq +//! [2] + +//! [3] +declare namespace c = "http://cookbook/namespace"; +doc('cookbook.xml')//c:recipe/c:title +//! [3] + +//! [4] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')//recipe/title +//! [4] + +//! [5] +<title xmlns="http://cookbook/namespace">Quick and Easy Mushroom Soup</title> +<title xmlns="http://cookbook/namespace">Cheese on Toast</title> +<title xmlns="http://cookbook/namespace">Hard-Boiled Eggs</title> +//! [5] + +//! [6] +xmlpatterns file.xq +//! [6] + +//! [7] +doc('cookbook.xml')//@xml:* +//! [7] + +//! [8] +doc('cookbook.xml')//@*:name +//! [8] + +//! [9] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/@* +//! [9] + +//! [10] +declare default element namespace "http://cookbook/namespace"; +doc("cookbook.xml")/cookbook/recipe[title = "Hard-Boiled Eggs"] +//! [10] + +//! [11] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')//method[string-length(.) = 0] +//! [11] + +//! [12] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')//method[string-length() = 0] +//! [12] + +//! [13] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[2] +//! [13] + +//! [14] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[position() = 2] +//! [14] + +//! [15] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[position() > 1] +//! [15] + +//! [16] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[last()] +//! [16] + +//! [17] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[last() - 1] +//! [17] + +//! [18] +doc('cookbook.xml')//recipe +//! [18] + +//! [19] +doc('cookbook.xml')//recipe/title +//! [19] + +//! [20] +<recipe/> +//! [20] + +//! [21] + <html xmlns="http://www.w3.org/1999/xhtml/" + xml:id="{doc("other.html")/html/@xml:id}"/> +//! [21] + +//! [22] +doc('cookbook.xml')/descendant-or-self::element(recipe)/child::element(title) +//! [22] + +//! [23] +<cookbook> +//! [23] + +//! [24] +<cookbook xmlns="http://cookbook/namespace"> +//! [24] + +//! [25] +for $i in doc("cookbook.xml")//@xml:* +return <p>{$i}</p> +//! [25] + +//! [26] +for $i in doc("cookbook.xml")//@*:name +return <p>{$i}</p> +//! [26] + +//! [27] +declare default element namespace "http://cookbook/namespace"; +for $i in doc("cookbook.xml")/cookbook/@* +return <p>{$i}</p> +//! [27] + +//! [28] +<p xml:id="MushroomSoup"/> +<p xml:id="CheeseOnToast"/> +<p xml:id="HardBoiledEggs"/> +//! [28] + +//! [29] +<p name="Fresh mushrooms"/> +<p name="Garlic"/> +<p name="Olive oil"/> +<p name="Milk"/> +<p name="Water"/> +<p name="Cream"/> +<p name="Vegetable soup cube"/> +<p name="Ground black pepper"/> +<p name="Dried parsley"/> +<p name="Bread"/> +<p name="Cheese"/> +<p name="Eggs"/> +//! [29] + +//! [30] +<p xmlns="http://cookbook/namespace" count="3"/> +//! [30] + +//! [31] +<method xmlns="http://cookbook/namespace"/> +//! [31] + +//! [32] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')//recipe[string-length(method) = 0] +//! [32] + +//! [33] +<recipe xmlns="http://cookbook/namespace" xml:id="HardBoiledEggs"> + <title>Hard-Boiled Eggs</title> + <ingredient name="Eggs" quantity="3" unit="eggs"/> + <time quantity="3" unit="minutes"/> + <method/> +</recipe> +//! [33] + +//! [34] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[method[empty(step)]] +//! [34] + +//! [35] +declare default element namespace "http://cookbook/namespace"; +doc('cookbook.xml')/cookbook/recipe[not(normalize-space(method))] +//! [35] + +//! [36] +<e>{sum((1, 2, 3))}</e> +//! [36] + +//! [37] +<e>6</e> +//! [37] + +//![38] +declare variable $insertion := "example"; +<p class="important {$insertion} obsolete"/> +//![38] + +//! [39] +<p class="important example obsolete"/> +//! [39] + +//! [40] +declare default element namespace "http://cookbook/namespace"; +let $docURI := 'cookbook.xml' +return if(doc-available($docURI)) + then doc($docURI)//recipe/<resept>{./node()}</resept> + else <resept>Failed to load {$docURI}</resept> +//! [40] + +//! [41] +<span>1</span> +<span>3</span> +<span>5</span> +<span>7</span> +<span>9</span> +<span>b</span> +<span>d</span> +<span>f</span> +//! [41] + +//! [42] +<span>1</span> +//! [42] + +//! [43] +let $doc := doc('doc.txt') +return $doc/doc/p[1]/span[1] +//! [43] + +//! [44] +for $a in doc('doc.txt')/doc/p/span[1] +return $a +//! [44] + +//! [45] +doc('doc.txt')/doc/p/span[1] +//! [45] + +//! [46] +doc('doc.txt')//p/<p>{span/node()}</p> +//! [46] + +//! [47] +<p>78</p> +<p>9a</p> +<p>12</p> +<p>bc</p> +<p>de</p> +<p>34</p> +<p>56</p> +<p>f0</p> +//! [47] + +//! [48] +for $a in doc('doc.txt')//p + return <p>{$a/span/node()}</p> +//! [48] + +//! [49] +<p>12</p> +<p>34</p> +<p>56</p> +<p>78</p> +<p>9a</p> +<p>bc</p> +<p>de</p> +<p>f0</p> +//! [49] + +//! [100] +<?xml version="1.0" encoding="UTF-8"?> +<cookbook> + <recipe xml:id="MushroomSoup"> + <title>Quick and Easy Mushroom Soup</title> + <ingredient name="Fresh mushrooms" + quantity="7" + unit="pieces"/> + <ingredient name="Garlic" + quantity="1" + unit="cloves"/> + <ingredient name="Olive oil" + quantity="2" + unit="tablespoons"/> + <ingredient name="Milk" + quantity="200" + unit="milliliters"/> + <ingredient name="Water" + quantity="200" + unit="milliliters"/> + <ingredient name="Cream" + quantity="100" + unit="milliliters"/> + <ingredient name="Vegetable soup cube" + quantity="1/2" + unit="cubes"/> + <ingredient name="Ground black pepper" + quantity="1/2" + unit="teaspoons"/> + <ingredient name="Dried parsley" + quantity="1" + unit="teaspoons"/> + <time quantity="20" + unit="minutes"/> + <method> + <step>1. Slice mushrooms and garlic.</step> + <step>2. Fry mushroom slices and garlic with olive oil.</step> + <step>3. Once mushrooms are cooked, add milk, cream water. Stir.</step> + <step>4. Add vegetable soup cube.</step> + <step>5. Reduce heat, add pepper and parsley.</step> + <step>6. Turn off the stove before the mixture boils.</step> + <step>7. Blend the mixture.</step> + </method> + </recipe> + <recipe xml:id="CheeseOnToast"> + <title>Cheese on Toast</title> + <ingredient name="Bread" + quantity="2" + unit="slices"/> + <ingredient name="Cheese" + quantity="2" + unit="slices"/> + <time quantity="3" + unit="minutes"/> + <method> + <step>1. Slice the bread and cheese.</step> + <step>2. Grill one side of each slice of bread.</step> + <step>3. Turn over the bread and place a slice of cheese on each piece.</step> + <step>4. Grill until the cheese has started to melt.</step> + <step>5. Serve and enjoy!</step> + </method> + </recipe> + <recipe xml:id="HardBoiledEggs"> + <title>Hard-Boiled Eggs</title> + <ingredient name="Eggs" + quantity="3" + unit="eggs"/> + <time quantity="3" + unit="minutes"/> + <method/> + </recipe> +</cookbook> +//! [100] + +} + diff --git a/doc/src/snippets/code/doc_src_qvarlengtharray.qdoc b/doc/src/snippets/code/doc_src_qvarlengtharray.qdoc new file mode 100644 index 0000000..95db9d3 --- /dev/null +++ b/doc/src/snippets/code/doc_src_qvarlengtharray.qdoc @@ -0,0 +1,38 @@ +//! [0] +int myfunc(int n) +{ + int table[n + 1]; // WRONG + ... + return table[n]; +} +//! [0] + + +//! [1] +int myfunc(int n) +{ + int *table = new int[n + 1]; + ... + int ret = table[n]; + delete[] table; + return ret; +} +//! [1] + + +//! [2] +int myfunc(int n) +{ + QVarLengthArray<int, 1024> array(n + 1); + ... + return array[n]; +} +//! [2] + + +//! [3] +QVarLengthArray<int> array(10); +int *data = array.data(); +for (int i = 0; i < 10; ++i) + data[i] = 2 * i; +//! [3] diff --git a/doc/src/snippets/code/doc_src_rcc.qdoc b/doc/src/snippets/code/doc_src_rcc.qdoc new file mode 100644 index 0000000..423f8e6 --- /dev/null +++ b/doc/src/snippets/code/doc_src_rcc.qdoc @@ -0,0 +1,3 @@ +//! [0] +rcc [options] <inputs> +//! [0] diff --git a/doc/src/snippets/code/doc_src_resources.qdoc b/doc/src/snippets/code/doc_src_resources.qdoc new file mode 100644 index 0000000..bc85341 --- /dev/null +++ b/doc/src/snippets/code/doc_src_resources.qdoc @@ -0,0 +1,41 @@ +//! [0] +<file alias="cut-img.png">images/cut.png</file> +//! [0] + + +//! [1] +<qresource prefix="/myresources"> + <file alias="cut-img.png">images/cut.png</file> +</qresource> +//! [1] + + +//! [2] +<qresource> + <file>cut.jpg</file> +</qresource> +<qresource lang="fr"> + <file alias="cut.jpg">cut_fr.jpg</file> +</qresource> +//! [2] + + +//! [3] +rcc -binary myresource.qrc -o myresource.rcc +//! [3] + + +//! [4] +QResource::registerResource("/path/to/myresource.rcc"); +//! [4] + + +//! [5] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Q_INIT_RESOURCE(graphlib); + ... + return app.exec(); +} +//! [5] diff --git a/doc/src/snippets/code/doc_src_richtext.qdoc b/doc/src/snippets/code/doc_src_richtext.qdoc new file mode 100644 index 0000000..d6f54c2 --- /dev/null +++ b/doc/src/snippets/code/doc_src_richtext.qdoc @@ -0,0 +1,50 @@ +//! [0] +QTextDocument *newDocument = new QTextDocument; +//! [0] + + +//! [1] +QTextEdit *editor = new QTextEdit; +QTextDocument *editorDocument = editor->document(); +//! [1] + + +//! [2] +QTextEdit *editor = new QTextEdit(parent); +editor->setHtml(aStringContainingHTMLtext); +editor->show(); +//! [2] + + +//! [3] +QTextDocument *document = editor->document(); +//! [3] + + +//! [4] +QTextCursor cursor = editor->textCursor(); +//! [4] + + +//! [5] +editor->setTextCursor(cursor); +//! [5] + + +//! [6] +textEdit.show(); + +textCursor.beginEditBlock(); + +for (int i = 0; i < 1000; ++i) { + textCursor.insertBlock(); + textCursor.insertText(paragraphText.at(i)); +} + +textCursor.endEditBlock(); +//! [6] + + +//! [7] +<meta http-equiv="Content-Type" content="text/html; charset=EUC-JP" /> +//! [7] diff --git a/doc/src/snippets/code/doc_src_session.qdoc b/doc/src/snippets/code/doc_src_session.qdoc new file mode 100644 index 0000000..6a32863 --- /dev/null +++ b/doc/src/snippets/code/doc_src_session.qdoc @@ -0,0 +1,3 @@ +//! [0] +xterm +//! [0] diff --git a/doc/src/snippets/code/doc_src_sql-driver.qdoc b/doc/src/snippets/code/doc_src_sql-driver.qdoc new file mode 100644 index 0000000..74cd8dc --- /dev/null +++ b/doc/src/snippets/code/doc_src_sql-driver.qdoc @@ -0,0 +1,239 @@ +//! [0] +-no-sql-<driver> ... Disable SQL <driver> entirely. +-qt-sql-<driver> ... Enable a SQL <driver> in the Qt Library, by default + none are turned on. +-plugin-sql-<driver> Enable SQL <driver> as a plugin to be linked to + at run time. + + Possible values for <driver>: + [ db2 ibase mysql oci odbc psql sqlite sqlite2 tds ] +//! [0] + + +//! [1] +create procedure qtestproc (OUT param1 INT, OUT param2 INT) +BEGIN + set param1 = 42; + set param2 = 43; +END +//! [1] + + +//! [2] +QSqlQuery q; +q.exec("call qtestproc (@outval1, @outval2)"); +q.exec("select @outval1, @outval2"); +q.next(); +qDebug() << q.value(0) << q.value(1); // outputs "42" and "43" +//! [2] + + +//! [3] +cd $QTDIR/src/plugins/sqldrivers/mysql +qmake "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro +make +//! [3] + + +//! [4] +cd $QTDIR/src/plugins/sqldrivers/mysql +make install +//! [4] + + +//! [5] +cd %QTDIR%\src\plugins\sqldrivers\mysql +qmake "INCLUDEPATH+=C:\MySQL\include" "LIBS+=C:\MYSQL\MySQL Server <version>\lib\opt\libmysql.lib" mysql.pro +nmake +//! [5] + + +//! [6] +cd $QTDIR/src/plugins/sqldrivers/oci +qmake "INCLUDEPATH+=$ORACLE_HOME/rdbms/public $ORACLE_HOME/rdbms/demo" "LIBS+=-L$ORACLE_HOME/lib -lclntsh -lwtc9" oci.pro +make +//! [6] + + +//! [7] +cd $QTDIR/src/plugins/sqldrivers/oci +qmake "INCLUDEPATH+=/usr/include/oracle/10.1.0.3/client/" "LIBS+=-L/usr/lib/oracle/10.1.0.3/client/lib" oci.pro +make +//! [7] + + +//! [8] +set INCLUDE=%INCLUDE%;c:\oracle\oci\include +set LIB=%LIB%;c:\oracle\oci\lib\msvc +cd %QTDIR%\src\plugins\sqldrivers\oci +qmake oci.pro +nmake +//! [8] + + +//! [9] +set PATH=%PATH%;c:\oracle\bin +//! [9] + + +//! [10] +\\ STORED_PROC uses the return statement or returns multiple result sets +QSqlQuery query; +query.setForwardOnly(true); +query.exec("{call STORED_PROC}"); +//! [10] + + +//! [11] +cd $QTDIR/src/plugins/sqldrivers/odbc +qmake "INCLUDEPATH+=/usr/local/unixODBC/include" "LIBS+=-L/usr/local/unixODBC/lib -lodbc" +make +//! [11] + + +//! [12] +cd %QTDIR%\src\plugins\sqldrivers\odbc +qmake odbc.pro +nmake +//! [12] + + +//! [13] +cd $QTDIR/src/plugins/sqldrivers/psql +qmake "INCLUDEPATH+=/usr/include/pgsql" "LIBS+=-L/usr/lib -lpq" psql.pro +make +//! [13] + + +//! [14] +cd $QTDIR/src/plugins/sqldrivers/psql +make install +//! [14] + + +//! [15] +cd %QTDIR%\src\plugins\sqldrivers\psql +qmake "INCLUDEPATH+=C:\psql\include" "LIBS+=C:\psql\lib\ms\libpq.lib" psql.pro +nmake +//! [15] + + +//! [16] +cd $QTDIR/src/plugins/sqldrivers/tds +qmake "INCLUDEPATH=$SYBASE/include" "LIBS=-L$SYBASE/lib -lsybdb" +make +//! [16] + + +//! [17] +cd %QTDIR%\src\plugins\sqldrivers\tds +qmake "LIBS+=NTWDBLIB.LIB" tds.pro +nmake +//! [17] + + +//! [18] +cd $QTDIR/src/plugins/sqldrivers/db2 +qmake "INCLUDEPATH+=$DB2DIR/include" "LIBS+=-L$DB2DIR/lib -ldb2" +make +//! [18] + + +//! [19] +cd $QTDIR/src/plugins/sqldrivers/db2 +make install +//! [19] + + +//! [20] +cd %QTDIR%\src\plugins\sqldrivers\db2 +qmake "INCLUDEPATH+=<DB2 home>/sqllib/include" "LIBS+=<DB2 home>/sqllib/lib/db2cli.lib" +nmake +//! [20] + + +//! [21] +cd $QTDIR/src/plugins/sqldrivers/sqlite +qmake "INCLUDEPATH+=$SQLITE/include" "LIBS+=-L$SQLITE/lib -lsqlite" +make +//! [21] + + +//! [22] +cd $QTDIR/src/plugins/sqldrivers/sqlite +make install +//! [22] + + +//! [23] +cd %QTDIR%\src\plugins\sqldrivers\sqlite +qmake "INCLUDEPATH+=C:\SQLITE\INCLUDE" "LIBS+=C:\SQLITE\LIB\SQLITE3.LIB" sqlite.pro +nmake +//! [23] + + +//! [24] +db.setHostName("MyServer"); +db.setDatabaseName("C:\\test.gdb"); +//! [24] + + +//! [25] +// connect to database using the Latin-1 character set +db.setConnectOptions("ISC_DPB_LC_CTYPE=Latin1"); +db.open(); +//! [25] + + +//! [26] +QSqlQuery q; +q.exec("execute procedure my_procedure"); +q.next(); +qDebug() << q.value(0); // outputs the first RETURN/OUT value +//! [26] + + +//! [27] +cd $QTDIR/src/plugins/sqldrivers/ibase +qmake "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib" ibase.pro +make +//! [27] + + +//! [28] +cd $QTDIR/src/plugins/sqldrivers/ibase +qmake "INCLUDEPATH+=/opt/interbase/include" "LIBS+=-L/opt/interbase/lib -lfbclient" ibase.pro +make +//! [28] + + +//! [29] +cd %QTDIR%\src\plugins\sqldrivers\ibase +qmake "INCLUDEPATH+=C:\interbase\include" ibase.pro +nmake +//! [29] + + +//! [30] +cd %QTDIR%\src\plugins\sqldrivers\ibase +qmake "INCLUDEPATH+=C:\interbase\include" "LIBS+=-lfbclient" ibase.pro +nmake +//! [30] + + +//! [31] +QSqlDatabase: QMYSQL driver not loaded +QSqlDatabase: available drivers: QMYSQL +//! [31] + +//! [32] +configure -I /usr/include/oracle/10.1.0.3/client -L /usr/lib/oracle/10.1.0.3/client/lib -R /usr/lib/oracle/10.1.0.3/client/lib -lclntsh -lnnz10 +make +//! [32] + +//! [33] +cd $QTDIR/src/plugins/sqldrivers/oci +qmake "INCLUDEPATH+=/usr/include/oracle/10.1.0.3/client" "LIBS+=-L/usr/lib/oracle/10.1.0.3/client/lib -Wl,-rpath,/usr/lib/oracle/10.1.0.3/client/lib -lclntsh -lnnz10" oci.pro +make +//! [33] + diff --git a/doc/src/snippets/code/doc_src_styles.qdoc b/doc/src/snippets/code/doc_src_styles.qdoc new file mode 100644 index 0000000..e11dc05 --- /dev/null +++ b/doc/src/snippets/code/doc_src_styles.qdoc @@ -0,0 +1,94 @@ +//! [0] + opt.init(q); + if (down) + opt.state |= QStyle::State_Sunken; + if (tristate && noChange) + opt.state |= QStyle::State_NoChange; + else + opt.state |= checked ? QStyle::State_On : + QStyle::State_Off; + if (q->testAttribute(Qt::WA_Hover) && q->underMouse()) { + if (hovering) + opt.state |= QStyle::State_MouseOver; + else + opt.state &= ~QStyle::State_MouseOver; + } + opt.text = text; + opt.icon = icon; + opt.iconSize = q->iconSize(); +//! [0] + + +//! [1] + state = QStyle::State_None; + if (widget->isEnabled()) + state |= QStyle::State_Enabled; + if (widget->hasFocus()) + state |= QStyle::State_HasFocus; + if (widget->window()->testAttribute(Qt::WA_KeyboardFocusChange)) + state |= QStyle::State_KeyboardFocusChange; + if (widget->underMouse()) + state |= QStyle::State_MouseOver; + if (widget->window()->isActiveWindow()) + state |= QStyle::State_Active; +#ifdef Q_WS_MAC + extern bool qt_mac_can_clickThrough(const QWidget *w); //qwidget_mac.cpp + if (!(state & QStyle::State_Active) && !qt_mac_can_clickThrough(widget)) + state &= ~QStyle::State_Enabled; +#endif +#ifdef QT_KEYPAD_NAVIGATION + if (widget->hasEditFocus()) + state |= QStyle::State_HasEditFocus; +#endif + + direction = widget->layoutDirection(); + rect = widget->rect(); + palette = widget->palette(); + fontMetrics = widget->fontMetrics(); +//! [1] + + +//! [2] + QStylePainter p(this); + QStyleOptionButton opt = d->getStyleOption(); + p.drawControl(QStyle::CE_CheckBox, opt); +//! [2] + + +//! [3] + QStyleOptionButton subopt = *btn; + subopt.rect = subElementRect(SE_CheckBoxIndicator, btn, widget); + drawPrimitive(PE_IndicatorCheckBox, &subopt, p, widget); + subopt.rect = subElementRect(SE_CheckBoxContents, btn, widget); + drawControl(CE_CheckBoxLabel, &subopt, p, widget); + + if (btn->state & State_HasFocus) { + QStyleOptionFocusRect fropt; + fropt.QStyleOption::operator=(*btn); + fropt.rect = subElementRect(SE_CheckBoxFocusRect, btn, widget); + drawPrimitive(PE_FrameFocusRect, &fropt, p, widget); + } +//! [3] + + +//! [4] + const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt); + uint alignment = visualAlignment(btn->direction, Qt::AlignLeft | Qt::AlignVCenter); + + if (!styleHint(SH_UnderlineShortcut, btn, widget)) + alignment |= Qt::TextHideMnemonic; + QPixmap pix; + QRect textRect = btn->rect; + if (!btn->icon.isNull()) { + pix = btn->icon.pixmap(btn->iconSize, btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled); + drawItemPixmap(p, btn->rect, alignment, pix); + if (btn->direction == Qt::RightToLeft) + textRect.setRight(textRect.right() - btn->iconSize.width() - 4); + else + textRect.setLeft(textRect.left() + btn->iconSize.width() + 4); + } + if (!btn->text.isEmpty()){ + drawItemText(p, textRect, alignment | Qt::TextShowMnemonic, + btn->palette, btn->state & State_Enabled, btn->text, QPalette::WindowText); + } +//! [4] diff --git a/doc/src/snippets/code/doc_src_stylesheet.qdoc b/doc/src/snippets/code/doc_src_stylesheet.qdoc new file mode 100644 index 0000000..60622d3 --- /dev/null +++ b/doc/src/snippets/code/doc_src_stylesheet.qdoc @@ -0,0 +1,1911 @@ +//! [0] +QLineEdit { background: yellow } +QCheckBox { color: red } +//! [0] + + +//! [1] +QPushButton { color: red } +//! [1] + + +//! [2] +QPushButton, QLineEdit, QComboBox { color: red } +//! [2] + + +//! [3] +QPushButton { color: red } +QLineEdit { color: red } +QComboBox { color: red } +//! [3] + + +//! [4] +QPushButton { color: red; background-color: white } +//! [4] + + +//! [5] +QComboBox::drop-down { image: url(dropdown.png) } +//! [5] + + +//! [6] +QComboBox { + margin-right: 20px; +} +QComboBox::drop-down { + subcontrol-origin: margin; +} +//! [6] + + +//! [7] +QComboBox::down-arrow { + image: url(down_arrow.png); +} +QComboBox::down-arrow:pressed { + position: relative; + top: 1px; left: 1px; +} +//! [7] + + +//! [8] +QPushButton:hover { color: white } +//! [8] + + +//! [9] +QRadioButton:!hover { color: red } +//! [9] + + +//! [10] +QCheckBox:hover:checked { color: white } +//! [10] + + +//! [11] +QPushButton:hover:!pressed { color: blue; } +//! [11] + + +//! [12] +QCheckBox:hover, QCheckBox:checked { color: white } +//! [12] + + +//! [13] +QComboBox::drop-down:hover { image: url(dropdown_bright.png) } +//! [13] + + +//! [14] +QPushButton#okButton { color: gray } +QPushButton { color: red } +//! [14] + + +//! [15] +QPushButton:hover { color: white } +QPushButton { color: red } +//! [15] + + +//! [16] +QPushButton:hover { color: white } +QPushButton:enabled { color: red } +//! [16] + + +//! [17] +QPushButton:enabled { color: red } +QPushButton:hover { color: white } +//! [17] + + +//! [18] +QPushButton:hover:enabled { color: white } +QPushButton:enabled { color: red } +//! [18] + + +//! [19] +QPushButton { color: red } +QAbstractButton { color: gray } +//! [19] + + +//! [20] +* {} /* a=0 b=0 c=0 -> specificity = 0 */ +LI {} /* a=0 b=0 c=1 -> specificity = 1 */ +UL LI {} /* a=0 b=0 c=2 -> specificity = 2 */ +UL OL+LI {} /* a=0 b=0 c=3 -> specificity = 3 */ +H1 + *[REL=up]{} /* a=0 b=1 c=1 -> specificity = 11 */ +UL OL LI.red {} /* a=0 b=1 c=3 -> specificity = 13 */ +LI.red.level {} /* a=0 b=2 c=1 -> specificity = 21 */ +#x34y {} /* a=1 b=0 c=0 -> specificity = 100 */ +//! [20] + + +//! [21] +qApp->setStyleSheet("QPushButton { color: white }"); +//! [21] + + +//! [22] +myPushButton->setStyleSheet("* { color: blue }"); +//! [22] + + +//! [23] +myPushButton->setStyleSheet("color: blue"); +//! [23] + + +//! [24] +qApp->setStyleSheet("QGroupBox { color: red; } "); +//! [24] + + +//! [25] +qApp->setStyleSheet("QGroupBox, QGroupBox * { color: red; }"); +//! [25] + + +//! [26] +class MyPushButton : public QPushButton { + // ... +} + +// ... +qApp->setStyleSheet("MyPushButton { background: yellow; }"); +//! [26] + + +//! [27] +namespace ns { + class MyPushButton : public QPushButton { + // ... + } +} + +// ... +qApp->setSytleSheet("ns--MyPushButton { background: yellow; }"); +//! [27] + + +//! [28] +MyLabel { qproperty-pixmap: url(pixmap.png); } +MyGroupBox { qproperty-titleColor: rgb(100, 200, 100); } +QPushButton { qproperty-iconSize: 20px 20px; } +//! [28] + + +//! [30] +QPushButton { background-color: red; border: none; } +//! [30] + + +//! [31] +QToolButton { background-color: red; border: none; } +//! [31] + + +//! [32] +void CustomWidget::paintEvent(QPaintEvent *) +{ + QStyleOption opt; + opt.init(this); + QPainter p(this); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); +} +//! [32] + + +//! [33] +QTreeView { + alternate-background-color: blue; + background: yellow; +} +//! [33] + + +//! [34] +QTextEdit { background: yellow } +//! [34] + + +//! [35] +QLabel { + background-image: url(dense6pattern.png); + background-repeat: repeat-xy; +} +//! [35] + + +//! [36] +QLabel { background-color: yellow } +QLineEdit { background-color: rgb(255, 0, 0) } +//! [36] + + +//! [37] +QFrame { background-image: url(:/images/hydro.png) } +//! [37] + + +//! [38] +QFrame { + background: white url(:/images/ring.png); + background-repeat: repeat-y; + background-position: left; +} +//! [38] + + +//! [39] +QFrame { + background: url(:/images/footer.png); + background-position: bottom left; +} +//! [39] + + +//! [40] +QTextEdit { + background-image: url("leaves.png"); + background-attachment: fixed; +} +//! [40] + + +//! [41] +QFrame { + background-image: url(:/images/header.png); + background-position: top left; + background-origin: content; + background-clip: padding; +} +//! [41] + + +//! [42] +QFrame { + background-image: url(:/images/header.png); + background-position: top left; + background-origin: content; +} +//! [42] + + +//! [43] +QLineEdit { border: 1px solid white } +//! [43] + + +//! [44] +QLineEdit { + border-width: 1px; + border-style: solid; + border-color: white; +} +//! [44] + + +//! [45] +QLineEdit { + border-width: 1px; + border-style: solid; + border-radius: 4px; +} +//! [45] + + +//! [46] +QLineEdit { + border-width: 1px; + border-style: solid; + border-color: blue; +} +//! [46] + + +//! [47] +QLineEdit { + border-width: 2px; + border-style: solid; + border-color: darkblue; +} +//! [47] + + +//! [48] +QSpinBox::down-button { bottom: 2px } +//! [48] + + +//! [49] +* { button-layout: 2 } +//! [49] + + +//! [50] +QPushButton { color: red } +//! [50] + + +//! [51] +QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; } +//! [51] + + +//! [52] +* { etch-disabled-text: 1 } +//! [52] + + +//! [53] +QCheckBox { font: bold italic large "Times New Roman" } +//! [53] + + +//! [54] +QCheckBox { font-family: "New Century Schoolbook" } +//! [54] + + +//! [55] +QTextEdit { font-size: 12px } +//! [55] + + +//! [56] +QTextEdit { font-style: italic } +//! [56] + + +//! [57] +* { gridline-color: gray } +//! [57] + + +//! [58] +QSpinBox::down-button { height: 10px } +//! [58] + + +//! [59] +/* implicitly sets the size of down-button to the size of spindown.png */ +QSpinBox::down-button { image: url(:/images/spindown.png) } + +QTextEdit { image: url(x1.png) url(x2.png) } +QTextEdit { image: url(pic1.svg) } +//! [59] + + +//! [60] +QSpinBox::down-button { left: 2px } +//! [60] + + +//! [61] +* { lineedit-password-character: 9679 } +//! [61] + + +//! [62] +QLineEdit { margin: 2px } +//! [62] + + +//! [63] +QSpinBox { max-height: 24px } +//! [63] + + +//! [64] +QComboBox { max-width: 72px } +//! [64] + + +//! [65] +QMessageBox { messagebox-text-interaction-flags: 5 } +//! [65] + + +//! [66] +QComboBox { min-height: 24px } +//! [66] + + +//! [67] +QComboBox { min-width: 72px } +//! [67] + + +//! [68] +QToolTip { opacity: 223 } +//! [68] + + +//! [69] +QLineEdit { padding: 3px } +//! [69] + + +//! [70] +QSpinBox::down-button { right: 2px } +//! [70] + + +//! [71] +QTextEdit { selection-background-color: darkblue } +//! [71] + + +//! [72] +QTextEdit { selection-color: white } +//! [72] + + +//! [73] +* { show-decoration-selected: 1 } +//! [73] + + +//! [74] +QMenuBar { spacing: 10 } +//! [74] + + +//! [75] +QSpinBox::up-button { + image: url(:/images/spinup.png); + subcontrol-origin: content; + subcontrol-position: right top; +} +//! [75] + + +//! [76] +QSpinBox::down-button { + image: url(:/images/spindown.png); + subcontrol-origin: padding; + subcontrol-position: right bottom; +} +//! [76] + + +//! [77] +QPushButton { + text-align: left; +} +//! [77] + + +//! [78] +QSpinBox::up-button { top: 2px } +//! [78] + + +//! [79] +QSpinBox::up-button { width: 12px } +//! [79] + + +//! [80] +QTextEdit { background-position: bottom center } +//! [80] + + +//! [81] +QDialog { etch-disabled-text: 1 } +//! [81] + + +//! [82] +QLabel { border-color: red } /* red red red red */ +QLabel { border-color: red blue } /* red blue red blue */ +QLabel { border-color: red blue green } /* red blue green blue */ +QLabel { border-color: red blue green yellow } /* red blue green yellow */ +//! [82] + + +//! [83] +QLabel { border-width: 1px } /* 1px 1px 1px 1px */ +QLabel { border-width: 1px 2px } /* 1px 2px 1px 2px */ +QLabel { border-width: 1px 2px 3px } /* 1px 2px 3px 2px */ +QLabel { border-width: 1px 2px 3px 4px } /* 1px 2px 3px 4px */ +//! [83] + + +//! [84] +QLabel { border-color: red } /* opaque red */ +QLabel { border-color: #FF0000 } /* opaque red */ +QLabel { border-color: rgba(255, 0, 0, 75%) } /* 75% opaque red */ +QLabel { border-color: rgb(255, 0, 0) } /* opaque red */ +QLabel { border-color: rgb(100%, 0%, 0%) } /* opaque red */ +QLabel { border-color: hsv(60, 255, 255) } /* opaque yellow */ +QLabel { border-color: hsva(240, 255, 255, 75%) } /* 75% blue */ +//! [84] + + +//! [85] +/* linear gradient from white to green */ +QTextEdit { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, + stop:0 white, stop: 0.4 gray, stop:1 green) +} + +/* linear gradient from white to green */ +QTextEdit { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, + stop:0 white, stop: 0.4 rgba(10, 20, 30, 40), stop:1 rgb(0, 200, 230, 200)) +} + + +/* conical gradient from white to green */ +QTextEdit { + background: qconicalgradient(cx:0.5, cy:0.5, angle:30, + stop:0 white, stop:1 #00FF00) +} + +/* radial gradient from white to green */ +QTextEdit { + background: qradialgradient(cx:0, cy:0, radius: 1, + fx:0.5, fy:0.5, stop:0 white, stop:1 green) +} +//! [85] + + +//! [86] +* { + file-icon: url(file.png), + url(file_selected.png) selected; + } + +QMessageBox { + dialogbuttonbox-buttons-have-icons: true; + dialog-ok-icon: url(ok.svg); + dialog-cancel-icon: url(cancel.png), url(grayed_cancel.png) disabled; +} +//! [86] + + +//! [87] +QPushButton { color: palette(dark); } +//! [87] + + +//! [88] +qApp->setStyleSheet("QLineEdit { background-color: yellow }"); +//! [88] + + +//! [89] +myDialog->setStyleSheet("QLineEdit { background-color: yellow }"); +//! [89] + + +//! [90] +myDialog->setStyleSheet("QLineEdit#nameEdit { background-color: yellow }"); +//! [90] + + +//! [91] +nameEdit->setStyleSheet("background-color: yellow"); +//! [91] + + +//! [92] +nameEdit->setStyleSheet("color: blue; background-color: yellow"); +//! [92] + + +//! [93] +nameEdit->setStyleSheet("color: blue;" + "background-color: yellow;" + "selection-color: yellow;" + "selection-background-color: blue;"); +//! [93] + + +//! [94] +*[mandatoryField="true"] { background-color: yellow } +//! [94] + + +//! [95] +QLineEdit *nameEdit = new QLineEdit(this); +nameEdit->setProperty("mandatoryField", true); + +QLineEdit *emailEdit = new QLineEdit(this); +emailEdit->setProperty("mandatoryField", true); + +QSpinBox *ageSpinBox = new QSpinBox(this); +ageSpinBox->setProperty("mandatoryField", true); +//! [95] + + +//! [96] +QPushButton#evilButton { background-color: red } +//! [96] + + +//! [97] +QPushButton#evilButton { + background-color: red; + border-style: outset; + border-width: 2px; + border-color: beige; +} +//! [97] + + +//! [98] +QPushButton#evilButton { + background-color: red; + border-style: outset; + border-width: 2px; + border-radius: 10px; + border-color: beige; + font: bold 14px; + min-width: 10em; + padding: 6px; +} +//! [98] + + +//! [99] +QPushButton#evilButton { + background-color: red; + border-style: outset; + border-width: 2px; + border-radius: 10px; + border-color: beige; + font: bold 14px; + min-width: 10em; + padding: 6px; +} +QPushButton#evilButton:pressed { + background-color: rgb(224, 0, 0); + border-style: inset; +} +//! [99] + + +//! [100] +QPushButton#evilButton::menu-indicator { + image: url(myindicator.png); +} +//! [100] + + +//! [101] +QPushButton::menu-indicator { + image: url(myindicator.png); + subcontrol-position: right center; + subcontrol-origin: padding; + left: -2px; +} +//! [101] + + +//! [102] +QLineEdit { color: red } +//! [102] + + +//! [103] +QLineEdit { color: red } +QLineEdit[readOnly="true"] { color: gray } +//! [103] + + +//! [104] +QLineEdit { color: red } +QLineEdit[readOnly="true"] { color: gray } +#registrationDialog QLineEdit { color: brown } +//! [104] + + +//! [105] +QLineEdit { color: red } +QLineEdit[readOnly="true"] { color: gray } +QDialog QLineEdit { color: brown } +//! [105] + + +//! [106] +QTextEdit, QListView { + background-color: white; + background-image: url(draft.png); + background-attachment: scroll; +} +//! [106] + + +//! [107] +QTextEdit, QListView { + background-color: white; + background-image: url(draft.png); + background-attachment: fixed; +} +//! [107] + + +//! [108] +QCheckBox { + spacing: 5px; +} + +QCheckBox::indicator { + width: 13px; + height: 13px; +} + +QCheckBox::indicator:unchecked { + image: url(:/images/checkbox_unchecked.png); +} + +QCheckBox::indicator:unchecked:hover { + image: url(:/images/checkbox_unchecked_hover.png); +} + +QCheckBox::indicator:unchecked:pressed { + image: url(:/images/checkbox_unchecked_pressed.png); +} + +QCheckBox::indicator:checked { + image: url(:/images/checkbox_checked.png); +} + +QCheckBox::indicator:checked:hover { + image: url(:/images/checkbox_checked_hover.png); +} + +QCheckBox::indicator:checked:pressed { + image: url(:/images/checkbox_checked_pressed.png); +} + +QCheckBox::indicator:indeterminate:hover { + image: url(:/images/checkbox_indeterminate_hover.png); +} + +QCheckBox::indicator:indeterminate:pressed { + image: url(:/images/checkbox_indeterminate_pressed.png); +} +//! [108] + + +//! [109] +QComboBox { + border: 1px solid gray; + border-radius: 3px; + padding: 1px 18px 1px 3px; + min-width: 6em; +} + +QComboBox:editable { + background: white; +} + +QComboBox:!editable, QComboBox::drop-down:editable { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, + stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); +} + +/* QComboBox gets the "on" state when the popup is open */ +QComboBox:!editable:on, QComboBox::drop-down:editable:on { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #D3D3D3, stop: 0.4 #D8D8D8, + stop: 0.5 #DDDDDD, stop: 1.0 #E1E1E1); +} + +QComboBox:on { /* shift the text when the popup opens */ + padding-top: 3px; + padding-left: 4px; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 15px; + + border-left-width: 1px; + border-left-color: darkgray; + border-left-style: solid; /* just a single line */ + border-top-right-radius: 3px; /* same radius as the QComboBox */ + border-bottom-right-radius: 3px; +} + +QComboBox::down-arrow { + image: url(/usr/share/icons/crystalsvg/16x16/actions/1downarrow.png); +} + +QComboBox::down-arrow:on { /* shift the arrow when popup is open */ + top: 1px; + left: 1px; +} +//! [109] + + +//! [110] +QComboBox QAbstractItemView { + border: 2px solid darkgray; + selection-background-color: lightgray; +} +//! [110] + + +//! [111] +QDockWidget { + border: 1px solid lightgray; + titlebar-close-icon: url(close.png); + titlebar-normal-icon: url(undock.png); +} + +QDockWidget::title { + text-align: left; /* align the text to the left */ + background: lightgray; + padding-left: 5px; +} + +QDockWidget::close-button, QDockWidget::float-button { + border: 1px solid transparent; + background: darkgray; + padding: 0px; +} + +QDockWidget::close-button:hover, QDockWidget::float-button:hover { + background: gray; +} + +QDockWidget::close-button:pressed, QDockWidget::float-button:pressed { + padding: 1px -1px -1px 1px; +} +//! [111] + + +//! [112] +QDockWidget { + border: 1px solid lightgray; + titlebar-close-icon: url(close.png); + titlebar-normal-icon: url(float.png); +} + +QDockWidget::title { + text-align: left; + background: lightgray; + padding-left: 35px; +} + +QDockWidget::close-button, QDockWidget::float-button { + background: darkgray; + padding: 0px; + icon-size: 14px; /* maximum icon size */ +} + +QDockWidget::close-button:hover, QDockWidget::float-button:hover { + background: gray; +} + +QDockWidget::close-button:pressed, QDockWidget::float-button:pressed { + padding: 1px -1px -1px 1px; +} + +QDockWidget::close-button { + subcontrol-position: top left; + subcontrol-origin: margin; + position: absolute; + top: 0px; left: 0px; bottom: 0px; + width: 14px; +} + +QDockWidget::float-button { + subcontrol-position: top left; + subcontrol-origin: margin; + position: absolute; + top: 0px; left: 16px; bottom: 0px; + width: 14px; +} +//! [112] + + +//! [113] +QFrame, QLabel, QToolTip { + border: 2px solid green; + border-radius: 4px; + padding: 2px; + background-image: url(images/welcome.png); +} +//! [113] + + +//! [114] +QGroupBox { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E0E0E0, stop: 1 #FFFFFF); + border: 2px solid gray; + border-radius: 5px; + margin-top: 1ex; /* leave space at the top for the title */ +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top center; /* position at the top center */ + padding: 0 3px; + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #FFOECE, stop: 1 #FFFFFF); +} +//! [114] + + +//! [115] +QGroupBox::indicator { + width: 13px; + height: 13px; +} + +QGroupBox::indicator:unchecked { + image: url(:/images/checkbox_unchecked.png); +} + +/* proceed with styling just like QCheckBox */ +//! [115] + + +//! [116] +QHeaderView::section { + background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, + stop:0 #616161, stop: 0.5 #505050, + stop: 0.6 #434343, stop:1 #656565); + color: white; + padding-left: 4px; + border: 1px solid #6c6c6c; +} + +/* style the sort indicator */ +QHeaderView::down-arrow { + image: url(down_arrow.png); +} + +QHeaderView::up-arrow { + image: url(up_arrow.png); +} +//! [116] + + +//! [117] +QLineEdit { + border: 2px solid gray; + border-radius: 10px; + padding: 0 8px; + background: yellow; + selection-background-color: darkgray; +} +//! [117] + + +//! [118] +QLineEdit[echoMode="2"] { + lineedit-password-character: 9679; +} +//! [118] + + +//! [119] +QLineEdit:read-only { + background: lightblue; +//! [119] + + +//! [120] +QListView { + alternate-background-color: yellow; +} +//! [120] + + +//! [121] +QListView { + show-decoration-selected: 1; /* make the selection span the entire width of the view */ +} + +QListView::item:alternate { + background: #EEEEEE; +} + +QListView::item:selected { + border: 1px solid #6a6ea9; +} + +QListView::item:selected:!active { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #ABAFE5, stop: 1 #8588B2); +} + +QListView::item:selected:active { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #6a6ea9, stop: 1 #888dd9); +} + +QListView::item:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #FAFBFE, stop: 1 #DCDEF1); +} +//! [121] + + +//! [122] +QMainWindow::separator { + background: yellow; + width: 10px; /* when vertical */ + height: 10px; /* when horizontal */ +} + +QMainWindow::separator:hover { + background: red; +} +//! [122] + + +//! [123] +QMenu { + background-color: #ABABAB; /* sets background of the menu */ + border: 1px solid black; +} + +QMenu::item { + /* sets background of menu item. set this to something non-transparent + if you want menu color and menu item color to be different */ + background-color: transparent; +} + +QMenu::item:selected { /* when user selects item using mouse or keyboard */ + background-color: #654321; +} +//! [123] + + +//! [124] +QMenu { + background-color: white; + margin: 2px; /* some spacing around the menu */ +} + +QMenu::item { + padding: 2px 25px 2px 20px; + border: 1px solid transparent; /* reserve space for selection border */ +} + +QMenu::item:selected { + border-color: darkblue; + background: rgba(100, 100, 100, 150); +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: gray; + border: 1px inset gray; + position: absolute; + top: 1px; + right: 1px; + bottom: 1px; + left: 1px; +} + +QMenu::separator { + height: 2px; + background: lightblue; + margin-left: 10px; + margin-right: 5px; +} + +QMenu::indicator { + width: 13px; + height: 13px; +} + +/* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ +QMenu::indicator:non-exclusive:unchecked { + image: url(:/images/checkbox_unchecked.png); +} + +QMenu::indicator:non-exclusive:unchecked:selected { + image: url(:/images/checkbox_unchecked_hover.png); +} + +QMenu::indicator:non-exclusive:checked { + image: url(:/images/checkbox_checked.png); +} + +QMenu::indicator:non-exclusive:checked:selected { + image: url(:/images/checkbox_checked_hover.png); +} + +/* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ +QMenu::indicator:exclusive:unchecked { + image: url(:/images/radiobutton_unchecked.png); +} + +QMenu::indicator:exclusive:unchecked:selected { + image: url(:/images/radiobutton_unchecked_hover.png); +} + +QMenu::indicator:exclusive:checked { + image: url(:/images/radiobutton_checked.png); +} + +QMenu::indicator:exclusive:checked:selected { + image: url(:/images/radiobutton_checked_hover.png); +} + +//! [124] + + +//! [125] +QMenuBar { + background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, + stop:0 lightgray, stop:1 darkgray); +} + +QMenuBar::item { + spacing: 3px; /* spacing between menu bar items */ + padding: 1px 4px; + background: transparent; + border-radius: 4px; +} + +QMenuBar::item:selected { /* when selected using mouse or keyboard */ + background: #a8a8a8; +} + +QMenuBar::item:pressed { + background: #888888; +} +//! [125] + + +//! [126] +QProgressBar { + border: 2px solid grey; + border-radius: 5px; +} + +QProgressBar::chunk { + background-color: #05B8CC; + width: 20px; +} +//! [126] + + +//! [127] +QProgressBar { + border: 2px solid grey; + border-radius: 5px; + text-align: center; +} +//! [127] + + +//! [128] +QProgressBar::chunk { + background-color: #CD96CD; + width: 10px; + margin: 0.5px; +} +//! [128] + + +//! [129] +QPushButton { + border: 2px solid #8f8f91; + border-radius: 6px; + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #f6f7fa, stop: 1 #dadbde); + min-width: 80px; +} + +QPushButton:pressed { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #dadbde, stop: 1 #f6f7fa); +} + +QPushButton:flat { + border: none; /* no border for a flat push button */ +} + +QPushButton:default { + border-color: navy; /* make the default button prominent */ +} +//! [129] + + +//! [130] +QPushButton:open { /* when the button has its menu open */ + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #dadbde, stop: 1 #f6f7fa); +} + +QPushButton::menu-indicator { + image: url(menu_indicator.png); + subcontrol-origin: padding; + subcontrol-position: bottom right; +} + +QPushButton::menu-indicator:pressed, QPushButton::menu-indicator:open { + position: relative; + top: 2px; left: 2px; /* shift the arrow by 2 px */ +} +//! [130] + + +//! [131] +QRadioButton::indicator { + width: 13px; + height: 13px; +} + +QRadioButton::indicator::unchecked { + image: url(:/images/radiobutton_unchecked.png); +} + +QRadioButton::indicator:unchecked:hover { + image: url(:/images/radiobutton_unchecked_hover.png); +} + +QRadioButton::indicator:unchecked:pressed { + image: url(:/images/radiobutton_unchecked_pressed.png); +} + +QRadioButton::indicator::checked { + image: url(:/images/radiobutton_checked.png); +} + +QRadioButton::indicator:checked:hover { + image: url(:/images/radiobutton_checked_hover.png); +} + +QRadioButton::indicator:checked:pressed { + image: url(:/images/radiobutton_checked_pressed.png); +} +//! [131] + + +//! [132] +QScrollBar:horizontal { + border: 2px solid grey; + background: #32CC99; + height: 15px; + margin: 0px 20px 0 20px; +} +//! [132] + + +//! [133] +QScrollBar::handle:horizontal { + background: white; + min-width: 20px; +} +//! [133] + + +//! [134] +QScrollBar::add-line:horizontal { + border: 2px solid grey; + background: #32CC99; + width: 20px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal { + border: 2px solid grey; + background: #32CC99; + width: 20px; + subcontrol-position: left; + subcontrol-origin: margin; +} +//! [134] + + +//! [135] +QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal { + border: 2px solid grey; + width: 3px; + height: 3px; + background: white; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} +//! [135] + + +//! [136] +QScrollBar:horizontal { + border: 2px solid green; + background: cyan; + height: 15px; + margin: 0px 40px 0 0px; +} + +QScrollBar::handle:horizontal { + background: gray; + min-width: 20px; +} + +QScrollBar::add-line:horizontal { + background: blue; + width: 16px; + subcontrol-position: right; + subcontrol-origin: margin; + border: 2px solid black; +} + +QScrollBar::sub-line:horizontal { + background: magenta; + width: 16px; + subcontrol-position: top right; + subcontrol-origin: margin; + border: 2px solid black; + position: absolute; + right: 20px; +} + +QScrollBar:left-arrow:horizontal, QScrollBar::right-arrow:horizontal { + width: 3px; + height: 3px; + background: pink; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} + +//! [136] + + +//! [137] + QScrollBar:vertical { + border: 2px solid grey; + background: #32CC99; + width: 15px; + margin: 22px 0 22px 0; + } + QScrollBar::handle:vertical { + background: white; + min-height: 20px; + } + QScrollBar::add-line:vertical { + border: 2px solid grey; + background: #32CC99; + height: 20px; + subcontrol-position: bottom; + subcontrol-origin: margin; + } + + QScrollBar::sub-line:vertical { + border: 2px solid grey; + background: #32CC99; + height: 20px; + subcontrol-position: top; + subcontrol-origin: margin; + } + QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + border: 2px solid grey; + width: 3px; + height: 3px; + background: white; + } + + QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; + } +//! [137] + + +//! [138] +QSizeGrip { + image: url(:/images/sizegrip.png); + width: 16px; + height: 16px; +} +//! [138] + + +//! [139] +QSlider::groove:horizontal { + border: 1px solid #999999; + height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */ + background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4); + margin: 2px 0; +} + +QSlider::handle:horizontal { + background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f); + border: 1px solid #5c5c5c; + width: 18px; + margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */ + border-radius: 3px; +} +//! [139] + + +//! [140] +QSlider::groove:vertical { + background: red; + position: absolute; /* absolutely position 4px from the left and right of the widget. setting margins on the widget should work too... */ + left: 4px; right: 4px; +} + +QSlider::handle:vertical { + height: 10px; + background: green; + margin: 0 -4px; /* expand outside the groove */ +} + +QSlider::add-page:vertical { + background: white; +} + +QSlider::sub-page:vertical { + background: pink; +} +//! [140] + + +//! [141] +QSpinBox { + padding-right: 15px; /* make room for the arrows */ + border-image: url(:/images/frame.png) 4; + border-width: 3; +} + +QSpinBox::up-button { + subcontrol-origin: border; + subcontrol-position: top right; /* position at the top right corner */ + + width: 16px; /* 16 + 2*1px border-width = 15px padding + 3px parent border */ + border-image: url(:/images/spinup.png) 1; + border-width: 1px; +} + +QSpinBox::up-button:hover { + border-image: url(:/images/spinup_hover.png) 1; +} + +QSpinBox::up-button:pressed { + border-image: url(:/images/spinup_pressed.png) 1; +} + +QSpinBox::up-arrow { + image: url(:/images/up_arrow.png); + width: 7px; + height: 7px; +} + +QSpinBox::up-arrow:disabled, QSpinBox::up-arrow:off { /* off state when value is max */ + image: url(:/images/up_arrow_disabled.png); +} + +QSpinBox::down-button { + subcontrol-origin: border; + subcontrol-position: bottom right; /* position at bottom right corner */ + + width: 16px; + border-image: url(:/images/spindown.png) 1; + border-width: 1px; + border-top-width: 0; +} + +QSpinBox::down-button:hover { + border-image: url(:/images/spindown_hover.png) 1; +} + +QSpinBox::down-button:pressed { + border-image: url(:/images/spindown_pressed.png) 1; +} + +QSpinBox::down-arrow { + image: url(:/images/down_arrow.png); + width: 7px; + height: 7px; +} + +QSpinBox::down-arrow:disabled, +QSpinBox::down-arrow:off { /* off state when value in min */ + image: url(:/images/down_arrow_disabled.png); +} + +//! [141] + + +//! [142] +QSplitter::handle { + image: url(images/splitter.png); +} + +QSplitter::handle:horizontal { + width: 2px; +} + +QSplitter::handle:vertical { + height: 2px; +} +//! [142] + + +//! [143] +QStatusBar { + background: brown; +} + +QStatusBar::item { + border: 1px solid red; + border-radius: 3px; +} +//! [143] + + +//! [144] +QStatusBar QLabel { + border: 3px solid white; +} +//! [144] + + +//! [145] +QTabWidget::pane { /* The tab widget frame */ + border-top: 2px solid #C2C7CB; +} + +QTabWidget::tab-bar { + left: 5px; /* move to the right by 5px */ +} + +/* Style the tab using the tab sub-control. Note that + it reads QTabBar _not_ QTabWidget */ +QTabBar::tab { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, + stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); + border: 2px solid #C4C4C3; + border-bottom-color: #C2C7CB; /* same as the pane color */ + border-top-left-radius: 4px; + border-top-right-radius: 4px; + min-width: 8ex; + padding: 2px; +} + +QTabBar::tab:selected, QTabBar::tab:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #fafafa, stop: 0.4 #f4f4f4, + stop: 0.5 #e7e7e7, stop: 1.0 #fafafa); +} + +QTabBar::tab:selected { + border-color: #9B9B9B; + border-bottom-color: #C2C7CB; /* same as pane color */ +} + +QTabBar::tab:!selected { + margin-top: 2px; /* make non-selected tabs look smaller */ +} +//! [145] + + +//! [146] +QTabWidget::pane { /* The tab widget frame */ + border-top: 2px solid #C2C7CB; +} + +QTabWidget::tab-bar { + left: 5px; /* move to the right by 5px */ +} + +/* Style the tab using the tab sub-control. Note that + it reads QTabBar _not_ QTabWidget */ +QTabBar::tab { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, + stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); + border: 2px solid #C4C4C3; + border-bottom-color: #C2C7CB; /* same as the pane color */ + border-top-left-radius: 4px; + border-top-right-radius: 4px; + min-width: 8ex; + padding: 2px; +} + +QTabBar::tab:selected, QTabBar::tab:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #fafafa, stop: 0.4 #f4f4f4, + stop: 0.5 #e7e7e7, stop: 1.0 #fafafa); +} + +QTabBar::tab:selected { + border-color: #9B9B9B; + border-bottom-color: #C2C7CB; /* same as pane color */ +} + +QTabBar::tab:!selected { + margin-top: 2px; /* make non-selected tabs look smaller */ +} + +/* make use of negative margins for overlapping tabs */ +QTabBar::tab:selected { + /* expand/overlap to the left and right by 4px */ + margin-left: -4px; + margin-right: -4px; +} + +QTabBar::tab:first:selected { + margin-left: 0; /* the first selected tab has nothing to overlap with on the left */ +} + +QTabBar::tab:last:selected { + margin-right: 0; /* the last selected tab has nothing to overlap with on the right */ +} + +QTabBar::tab:only-one { + margin: 0; /* if there is only one tab, we don't want overlapping margins */ +} +//! [146] + + +//! [147] +QTabWidget::pane { /* The tab widget frame */ + border-top: 2px solid #C2C7CB; + position: absolute; + top: -0.5em; +} + +QTabWidget::tab-bar { + alignment: center; +} + +/* Style the tab using the tab sub-control. Note that + it reads QTabBar _not_ QTabWidget */ +QTabBar::tab { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, + stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); + border: 2px solid #C4C4C3; + border-bottom-color: #C2C7CB; /* same as the pane color */ + border-top-left-radius: 4px; + border-top-right-radius: 4px; + min-width: 8ex; + padding: 2px; +} + +QTabBar::tab:selected, QTabBar::tab:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #fafafa, stop: 0.4 #f4f4f4, + stop: 0.5 #e7e7e7, stop: 1.0 #fafafa); +} + +QTabBar::tab:selected { + border-color: #9B9B9B; + border-bottom-color: #C2C7CB; /* same as pane color */ +} +//! [147] + + +//! [148] +QTabBar::tear { + image: url(tear_indicator.png); +} + +QTabBar::scroller { /* the width of the scroll buttons */ + width: 20px; +} + +QTabBar QToolButton { /* the scroll buttons are tool buttons */ + border-image: url(scrollbutton.png) 2; + border-width: 2px; +} + +QTabBar QToolButton::right-arrow { /* the arrow mark in the tool buttons */ + image: url(rightarrow.png); +} + +QTabBar QToolButton::left-arrow { + image: url(leftarrow.png); +} +//! [148] + + +//! [149] +QTableView { + selection-background-color: qlineargradient(x1: 0, y1: 0, x2: 0.5, y2: 0.5, + stop: 0 #FF92BB, stop: 1 white); +} +//! [149] + + +//! [150] +QTableView QTableCornerButton::section { + background: red; + border: 2px outset red; +} +//! [150] + + +//! [151] +QToolBar { + background: red; + spacing: 3px; /* spacing between items in the tool bar */ +} + +QToolBar::handle { + image: url(handle.png); +} +//! [151] + + +//! [152] +QToolBox::tab { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #E1E1E1, stop: 0.4 #DDDDDD, + stop: 0.5 #D8D8D8, stop: 1.0 #D3D3D3); + border-radius: 5px; + color: darkgray; +} + +QToolBox::tab:selected { /* italicize selected tabs */ + font: italic; + color: white; +} +//! [152] + + +//! [153] +QToolButton { /* all types of tool button */ + border: 2px solid #8f8f91; + border-radius: 6px; + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #f6f7fa, stop: 1 #dadbde); +} + +QToolButton[popupMode="1"] { /* only for MenuButtonPopup */ + padding-right: 20px; /* make way for the popup button */ +} + +QToolButton:pressed { + background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, + stop: 0 #dadbde, stop: 1 #f6f7fa); +} + +/* the subcontrols below are used only in the MenuButtonPopup mode */ +QToolButton::menu-button { + border: 2px solid gray; + border-top-right-radius: 6px; + border-bottom-right-radius: 6px; + /* 16px width + 4px for border = 20px allocated above */ + width: 16px; +} + +QToolButton::menu-arrow { + image: url(downarrow.png); +} + +QToolButton::menu-arrow:open { + top: 1px; left: 1px; /* shift it a bit */ +} +//! [153] + + +//! [154] +QToolTip { + border: 2px solid darkkhaki; + padding: 5px; + border-radius: 3px; + opacity: 200; +} +//! [154] + + +//! [155] +QTreeView { + alternate-background-color: yellow; +} +//! [155] + + +//! [156] +QTreeView { + show-decoration-selected: 1; +} + +QTreeView::item { + border: 1px solid #d9d9d9; + border-top-color: transparent; + border-bottom-color: transparent; +} + +QTreeView::item:hover { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1); + border: 1px solid #bfcde4; +} + +QTreeView::item:selected { + border: 1px solid #567dbc; +} + +QTreeView::item:selected:active{ + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6ea1f1, stop: 1 #567dbc); +} + +QTreeView::item:selected:!active { + background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #6b9be8, stop: 1 #577fbf); +} +//! [156] + + +//! [157] +QTreeView::branch { + background: palette(base); +} + +QTreeView::branch:has-siblings:!adjoins-item { + background: cyan; +} + +QTreeView::branch:has-siblings:adjoins-item { + background: red; +} + +QTreeView::branch:!has-children:!has-siblings:adjoins-item { + background: blue; +} + +QTreeView::branch:closed:has-children:has-siblings { + background: pink; +} + +QTreeView::branch:has-children:!has-siblings:closed { + background: gray; +} + +QTreeView::branch:open:has-children:has-siblings { + background: magenta; +} + +QTreeView::branch:open:has-children:!has-siblings { + background: green; +} + +//! [157] + + +//! [158] +QTreeView::branch:has-siblings:!adjoins-item { + border-image: url(vline.png) 0; +} + +QTreeView::branch:has-siblings:adjoins-item { + border-image: url(branch-more.png) 0; +} + +QTreeView::branch:!has-children:!has-siblings:adjoins-item { + border-image: url(branch-end.png) 0; +} + +QTreeView::branch:has-children:!has-siblings:closed, +QTreeView::branch:closed:has-children:has-siblings { + border-image: none; + image: url(branch-closed.png); +} + +QTreeView::branch:open:has-children:!has-siblings, +QTreeView::branch:open:has-children:has-siblings { + border-image: none; + image: url(branch-open.png); +} +//! [158] diff --git a/doc/src/snippets/code/doc_src_uic.qdoc b/doc/src/snippets/code/doc_src_uic.qdoc new file mode 100644 index 0000000..310e839 --- /dev/null +++ b/doc/src/snippets/code/doc_src_uic.qdoc @@ -0,0 +1,15 @@ +//! [0] +uic [options] <uifile> +//! [0] + + +//! [1] +ui_%.h: %.ui + uic $< -o $@ +//! [1] + + +//! [2] +ui_foo.h: foo.ui + uic $< -o $@ +//! [2] diff --git a/doc/src/snippets/code/doc_src_unicode.qdoc b/doc/src/snippets/code/doc_src_unicode.qdoc new file mode 100644 index 0000000..30a3710 --- /dev/null +++ b/doc/src/snippets/code/doc_src_unicode.qdoc @@ -0,0 +1,18 @@ +//! [0] +label->setText("Password:"); +//! [0] + + +//! [1] +label->setText(tr("Password:")); +//! [1] + + +//! [2] +QFile file(QString::fromLatin1("appicon.png")); +//! [2] + + +//! [3] +QFile file(QLatin1String("appicon.png")); +//! [3] diff --git a/doc/src/snippets/code/doc_src_unix-signal-handlers.qdoc b/doc/src/snippets/code/doc_src_unix-signal-handlers.qdoc new file mode 100644 index 0000000..8abcba6 --- /dev/null +++ b/doc/src/snippets/code/doc_src_unix-signal-handlers.qdoc @@ -0,0 +1,110 @@ +//! [0] +class MyDaemon : public QObject +{ + Q_OBJECT + + public: + MyDaemon(QObject *parent = 0, const char *name = 0); + ~MyDaemon(); + + // Unix signal handlers. + static void hupSignalHandler(int unused); + static void termSignalHandler(int unused); + + public slots: + // Qt signal handlers. + void handleSigHup(); + void handleSigTerm(); + + private: + static int sighupFd[2]; + static int sigtermFd[2]; + + QSocketNotifier *snHup; + QSocketNotifier *snTerm; +}; +//! [0] + + +//! [1] +MyDaemon::MyDaemon(QObject *parent, const char *name) + : QObject(parent,name) +{ + if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd)) + qFatal("Couldn't create HUP socketpair"); + + if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd)) + qFatal("Couldn't create TERM socketpair"); + snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this); + connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup())); + snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this); + connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm())); + + ... +} +//! [1] + + +//! [2] +static int setup_unix_signal_handlers() +{ + struct sigaction hup, term; + + hup.sa_handler = MyDaemon::hupSignalHandler; + sigemptyset(&hup.sa_mask); + hup.sa_flags = 0; + hup.sa_flags |= SA_RESTART; + + if (sigaction(SIGHUP, &hup, 0) > 0) + return 1; + + term.sa_handler = MyDaemon::termSignalHandler; + sigemptyset(&term.sa_mask); + term.sa_flags |= SA_RESTART; + + if (sigaction(SIGTERM, &term, 0) > 0) + return 2; + + return 0; +} +//! [2] + + +//! [3] +void MyDaemon::hupSignalHandler(int) +{ + char a = 1; + ::write(sighupFd[0], &a, sizeof(a)); +} + +void MyDaemon::termSignalHandler(int) +{ + char a = 1; + ::write(sigtermFd[0], &a, sizeof(a)); +} +//! [3] + + +//! [4] +void MyDaemon::handleSigTerm() +{ + snTerm->setEnabled(false); + char tmp; + ::read(sigtermFd[1], &tmp, sizeof(tmp)); + + // do Qt stuff + + snTerm->setEnabled(true); +} + +void MyDaemon::handleSigHup() +{ + snHup->setEnabled(false); + char tmp; + ::read(sighupFd[1], &tmp, sizeof(tmp)); + + // do Qt stuff + + snHup->setEnabled(true); +} +//! [4] diff --git a/doc/src/snippets/code/doc_src_wince-customization.qdoc b/doc/src/snippets/code/doc_src_wince-customization.qdoc new file mode 100644 index 0000000..0399231 --- /dev/null +++ b/doc/src/snippets/code/doc_src_wince-customization.qdoc @@ -0,0 +1,70 @@ +//! [0] +wince<version><SDK-shortcut>-[architecture]-msvc2005 +//! [0] + + +//! [1] +CE_SDK = Windows Mobile 5.0 Pocket PC SDK +CE_ARCH = ARMV4I +//! [1] + + +//! [2] +DEFINES += UNDER_CE WINCE _WINDOWS _UNICODE UNICODE _WIN32_WCE=0x501 $$CE_ARCH _ARMV4I_ armv4i _ARM_ ARM _M_ARM ARM _WIN32 __arm__ Q_OS_WINCE_WM QT_NO_PRINTER QT_NO_PRINTDIALOG +//! [2] + + +//! [3] +set PATH=C:\Qt\mobile5-shadow\bin;%PATH% +//! [3] + + +//! [4] +cd c:\Qt\mobile5-shadow +C:\Qt\%VERSION%\configure.exe -platform win32-msvc2005 -xplatform wincewm50pocket-msvc2005 -release +//! [4] + + +//! [5] +set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ce\include; + C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Include\Armv4i +set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ce\lib\armv4i; + C:\Program Files\Windows CE Tools\wce500\Windows Mobile 5.0 Pocket PC SDK\Lib\ARMV4I +set PATH=C:\Program Files\Microsoft Visual Studio 8\VC\ce\bin\x86_arm; + %PATH% +//! [5] + + +//! [6] +setcepaths wincewm50pocket-msvc2005 +//! [6] + + +//! [7] +nmake +//! [7] + +//! [8] +if(equals(TEMPLATE_PREFIX, "vc") | equals(TEMPLATE, "vc*")) { + DEFINES -= _M_ARM +} +//! [8] + +//! [9] +wchar_t* libraries[] = { + L"QtCore4.dll", + L"QtGui4.dll", + 0 +}; + +for (int i = 0; libraries[i] != 0; ++i) { + HINSTANCE instance = LoadLibraryW(libraries[i]); + OutputDebugStringW(libraries[i]); + if (instance != NULL) { + OutputDebugStringW(L" : Successfully instantiated\n"); + FreeLibrary(instance); + } else { + OutputDebugStringW(L" : Could not be loaded\n"); + } +} +//! [9] diff --git a/doc/src/snippets/code/doc_src_wince-introduction.qdoc b/doc/src/snippets/code/doc_src_wince-introduction.qdoc new file mode 100644 index 0000000..ffb4cfb --- /dev/null +++ b/doc/src/snippets/code/doc_src_wince-introduction.qdoc @@ -0,0 +1,9 @@ +//! [0] +qmake +nmake +//! [0] + + +//! [1] +qmake -tp vc +//! [1] diff --git a/doc/src/snippets/code/doc_src_wince-opengl.qdoc b/doc/src/snippets/code/doc_src_wince-opengl.qdoc new file mode 100644 index 0000000..db2bfaa --- /dev/null +++ b/doc/src/snippets/code/doc_src_wince-opengl.qdoc @@ -0,0 +1,3 @@ +//! [0] +configure -platform win32-msvc2005 -xplatform wincewm50pocket-msvc2005 -opengl-es-cl +//! [0] diff --git a/doc/src/snippets/code/src.gui.text.qtextdocumentwriter.cpp b/doc/src/snippets/code/src.gui.text.qtextdocumentwriter.cpp new file mode 100644 index 0000000..3f206ea --- /dev/null +++ b/doc/src/snippets/code/src.gui.text.qtextdocumentwriter.cpp @@ -0,0 +1,5 @@ +//! [0] + QTextDocumentWriter writer; + writer.setFormat("odf"); // same as writer.setFormat("ODF"); +//! [0] + diff --git a/doc/src/snippets/code/src.qdbus.qdbuspendingcall.cpp b/doc/src/snippets/code/src.qdbus.qdbuspendingcall.cpp new file mode 100644 index 0000000..c9b3b7c --- /dev/null +++ b/doc/src/snippets/code/src.qdbus.qdbuspendingcall.cpp @@ -0,0 +1,24 @@ +{ +//! [0] + QDBusPendingCall async = iface->asyncCall("RemoteMethod", value1, value2); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this); + + QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), + this, SLOT(callFinishedSlot(QDBusPendingCallWatcher*))); +//! [0] + +} + +//! [1] +void MyClass::callFinishedSlot(QDBusPendingCallWatcher *call) +{ + QDBusPendingReply<QString, QByteArray> reply = *call; + if (reply.isError()) { + showError(); + } else { + QString text = reply.argumentAt<0>(); + QByteArray data = reply.argumentAt<1>(); + showReply(text, data); + } +} +//! [1] diff --git a/doc/src/snippets/code/src.qdbus.qdbuspendingreply.cpp b/doc/src/snippets/code/src.qdbus.qdbuspendingreply.cpp new file mode 100644 index 0000000..49363a8 --- /dev/null +++ b/doc/src/snippets/code/src.qdbus.qdbuspendingreply.cpp @@ -0,0 +1,23 @@ +{ +//! [0] + QDBusPendingReply<QString> reply = interface->asyncCall("RemoteMethod"); + reply.waitForFinished(); + if (reply.isError()) + // call failed. Show an error condition. + showError(reply.error()); + else + // use the returned value + useValue(reply.value()); +//! [0] + +//! [2] + QDBusPendingReply<bool, QString> reply = interface->asyncCall("RemoteMethod"); + reply.waitForFinished(); + if (!reply.isError()) { + if (reply.argumentAt<0>()) + showSuccess(reply.argumentAt<1>()); + else + showFailure(reply.argumentAt<1>()); + } +//! [2] +} diff --git a/doc/src/snippets/code/src.scripttools.qscriptenginedebugger.cpp b/doc/src/snippets/code/src.scripttools.qscriptenginedebugger.cpp new file mode 100644 index 0000000..f81611c --- /dev/null +++ b/doc/src/snippets/code/src.scripttools.qscriptenginedebugger.cpp @@ -0,0 +1,9 @@ +//! [0] + QScriptEngine engine; + QScriptEngineDebugger debugger; + debugger.attachTo(&engine); +//! [0] + +//! [1] + engine.evaluate("debugger"); +//! [1] diff --git a/doc/src/snippets/code/src_3rdparty_webkit_WebKit_qt_Api_qwebview.cpp b/doc/src/snippets/code/src_3rdparty_webkit_WebKit_qt_Api_qwebview.cpp new file mode 100644 index 0000000..f04cd29 --- /dev/null +++ b/doc/src/snippets/code/src_3rdparty_webkit_WebKit_qt_Api_qwebview.cpp @@ -0,0 +1,35 @@ + +void wrapInFunction() +{ + +//! [0] + view->page()->history(); +//! [0] + + +//! [1] + view->page()->settings(); +//! [1] + + +//! [2] + view->triggerAction(QWebPage::Copy); +//! [2] + + +//! [3] + view->page()->triggerPageAction(QWebPage::Stop); +//! [3] + + +//! [4] + view->page()->triggerPageAction(QWebPage::GoBack); +//! [4] + + +//! [5] + view->page()->triggerPageAction(QWebPage::GoForward); +//! [5] + +} + diff --git a/doc/src/snippets/code/src_activeqt_container_qaxbase.cpp b/doc/src/snippets/code/src_activeqt_container_qaxbase.cpp new file mode 100644 index 0000000..94b0da8 --- /dev/null +++ b/doc/src/snippets/code/src_activeqt_container_qaxbase.cpp @@ -0,0 +1,159 @@ +//! [0] +connect(buttonBack, SIGNAL(clicked()), webBrowser, SLOT(GoBack())); +//! [0] + + +//! [1] +activeX->setProperty("text", "some text"); +int value = activeX->property("value"); +//! [1] + + +//! [2] +webBrowser->dynamicCall("GoHome()"); +//! [2] + + +//! [3] +connect(webBrowser, SIGNAL(TitleChanged(QString)), + this, SLOT(setCaption(QString))); +//! [3] + + +//! [4] +dispinterface IControl +{ +properties: + [id(1)] BSTR text; + [id(2)] IFontDisp *font; + +methods: + [id(6)] void showColumn([in] int i); + [id(3)] bool addColumn([in] BSTR t); + [id(4)] int fillList([in, out] SAFEARRAY(VARIANT) *list); + [id(5)] IDispatch *item([in] int i); +}; +//! [4] + + +//! [5] +QAxObject object("<CLSID>"); + +QString text = object.property("text").toString(); +object.setProperty("font", QFont("Times New Roman", 12)); + +connect(this, SIGNAL(clicked(int)), &object, SLOT(showColumn(int))); +bool ok = object.dynamicCall("addColumn(const QString&)", "Column 1").toBool(); + +QList<QVariant> varlist; +QList<QVariant> parameters; +parameters << QVariant(varlist); +int n = object.dynamicCall("fillList(QList<QVariant>&)", parameters).toInt(); + +QAxObject *item = object.querySubItem("item(int)", 5); +//! [5] + + +//! [6] +IUnknown *iface = 0; +activeX->queryInterface(IID_IUnknown, (void**)&iface); +if (iface) { + // use the interface + iface->Release(); +} +//! [6] + + +//! [7] +ctrl->setControl("{8E27C92B-1264-101C-8A2F-040224009C02}"); +//! [7] + + +//! [8] +ctrl->setControl("MSCal.Calendar"); +//! [8] + + +//! [9] +ctrl->setControl("Calendar Control 9.0"); +//! [9] + + +//! [10] +ctrl->setControl("c:/files/file.doc"); +//! [10] + + +//! [11] +<domain/username>:<password>@server/{8E27C92B-1264-101C-8A2F-040224009C02} +//! [11] + + +//! [12] +{8E27C92B-1264-101C-8A2F-040224009C02}:<LicenseKey> +//! [12] + + +//! [13] +{8E27C92B-1264-101C-8A2F-040224009C02}& +//! [13] + + +//! [14] +ctrl->setControl("DOMAIN/user:password@server/{8E27C92B-1264-101C-8A2F-040224009C02}:LicenseKey"); +//! [14] + + +//! [15] +activeX->dynamicCall("Navigate(const QString&)", "qtsoftware.com"); +//! [15] + + +//! [16] +activeX->dynamicCall("Navigate(\"qtsoftware.com\")"); +//! [16] + + +//! [17] +activeX->dynamicCall("Value", 5); +QString text = activeX->dynamicCall("Text").toString(); +//! [17] + + +//! [18] +IWebBrowser2 *webBrowser = 0; +activeX->queryInterface(IID_IWebBrowser2, (void **)&webBrowser); +if (webBrowser) { + webBrowser->Navigate2(pvarURL); + webBrowser->Release(); +} +//! [18] + + +//! [19] +QAxWidget outlook("Outlook.Application"); +QAxObject *session = outlook.querySubObject("Session"); +if (session) { + QAxObject *defFolder = session->querySubObject( + "GetDefaultFolder(OlDefaultFolders)", + "olFolderContacts"); + //... +} +//! [19] + + +//! [20] +void Receiver::slot(const QString &name, int argc, void *argv) +{ + VARIANTARG *params = (VARIANTARG*)argv; + if (name.startsWith("BeforeNavigate2(")) { + IDispatch *pDisp = params[argc-1].pdispVal; + VARIANTARG URL = *params[argc-2].pvarVal; + VARIANTARG Flags = *params[argc-3].pvarVal; + VARIANTARG TargetFrameName = *params[argc-4].pvarVal; + VARIANTARG PostData = *params[argc-5].pvarVal; + VARIANTARG Headers = *params[argc-6].pvarVal; + bool *Cancel = params[argc-7].pboolVal; + } +} +//! [20] diff --git a/doc/src/snippets/code/src_activeqt_container_qaxscript.cpp b/doc/src/snippets/code/src_activeqt_container_qaxscript.cpp new file mode 100644 index 0000000..07fca1e --- /dev/null +++ b/doc/src/snippets/code/src_activeqt_container_qaxscript.cpp @@ -0,0 +1,18 @@ +//! [0] +function setNumber(number) +{ + n = number; +} +//! [0] + + +//! [1] +QValueList args; +args << 5; +script->call("setNumber(const QVariant&)", args); +//! [1] + + +//! [2] +script->call("setNumber(5)"); +//! [2] diff --git a/doc/src/snippets/code/src_activeqt_control_qaxbindable.cpp b/doc/src/snippets/code/src_activeqt_control_qaxbindable.cpp new file mode 100644 index 0000000..c296789 --- /dev/null +++ b/doc/src/snippets/code/src_activeqt_control_qaxbindable.cpp @@ -0,0 +1,60 @@ +//! [0] +class MyActiveX : public QWidget, public QAxBindable +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) + +public: + MyActiveX(QWidget *parent = 0); + ... + + int value() const; + void setValue(int); +}; +//! [0] + + +//! [1] +void MyActiveQt::setText(const QString &text) +{ + if (!requestPropertyChange("text")) + return; + + // update property + + propertyChanged("text"); +} +//! [1] + + +//! [2] +long AxImpl::queryInterface(const QUuid &iid, void **iface) +{ + *iface = 0; + if (iid == IID_ISomeCOMInterface) + *iface = (ISomeCOMInterface*)this; + else + return E_NOINTERFACE; + + AddRef(); + return S_OK; +} +//! [2] + + +//! [3] +HRESULT AxImpl::QueryInterface(REFIID iid, void **iface) +{ + return controllingUnknown()->QueryInterface(iid, iface); +} + +ulong AxImpl::AddRef() +{ + return controllingUnknown()->AddRef(); +} + +ulong AxImpl::Release() +{ + return controllingUnknown()->Release(); +} +//! [3] diff --git a/doc/src/snippets/code/src_activeqt_control_qaxfactory.cpp b/doc/src/snippets/code/src_activeqt_control_qaxfactory.cpp new file mode 100644 index 0000000..6eca434 --- /dev/null +++ b/doc/src/snippets/code/src_activeqt_control_qaxfactory.cpp @@ -0,0 +1,155 @@ +//! [0] +QStringList ActiveQtFactory::featureList() const +{ + QStringList list; + list << "ActiveX1"; + list << "ActiveX2"; + return list; +} + +QObject *ActiveQtFactory::createObject(const QString &key) +{ + if (key == "ActiveX1") + return new ActiveX1(parent); + if (key == "ActiveX2") + return new ActiveX2(parent); + return 0; +} + +const QMetaObject *ActiveQtFactory::metaObject(const QString &key) const +{ + if (key == "ActiveX1") + return &ActiveX1::staticMetaObject; + if (key == "ActiveX2") + return &ActiveX2::staticMetaObject; +} + +QUuid ActiveQtFactory::classID(const QString &key) const +{ + if (key == "ActiveX1") + return "{01234567-89AB-CDEF-0123-456789ABCDEF}"; + ... + return QUuid(); +} + +QUuid ActiveQtFactory::interfaceID(const QString &key) const +{ + if (key == "ActiveX1") + return "{01234567-89AB-CDEF-0123-456789ABCDEF}"; + ... + return QUuid(); +} + +QUuid ActiveQtFactory::eventsID(const QString &key) const +{ + if (key == "ActiveX1") + return "{01234567-89AB-CDEF-0123-456789ABCDEF}"; + ... + return QUuid(); +} + +QAXFACTORY_EXPORT( + ActiveQtFactory, // factory class + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) +//! [0] + + +//! [1] +QAXFACTORY_BEGIN( + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) + QAXCLASS(Class1) + QAXCLASS(Class2) +QAXFACTORY_END() +//! [1] + + +//! [2] +#include <qapplication.h> +#include <qaxfactory.h> + +#include "theactivex.h" + +QAXFACTORY_DEFAULT( + TheActiveX, // widget class + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // class ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // interface ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // event interface ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) +//! [2] + + +//! [3] +settings->setValue("/CLSID/" + classID(key) + + "/Implemented Categories/" + + "/{00000000-0000-0000-000000000000}/.", + QString()); +//! [3] + + +//! [4] +settings->remove("/CLSID/" + classID(key) + + "/Implemented Categories" + + "/{00000000-0000-0000-000000000000}/."); +//! [4] + + +//! [5] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + if (!QAxFactory::isServer()) { + // initialize for stand-alone execution + } + return app.exec(); +} +//! [5] + + +//! [6] +if (QAxFactory::isServer()) { + QAxFactory::stopServer(); + QAxFactory::startServer(QAxFactory::SingleInstance); +} +//! [6] + + +//! [7] +#include <qaxfactory.h> + +#include "theactivex.h" + +QAXFACTORY_DEFAULT( + TheActiveX, // widget class + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // class ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // interface ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // event interface ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) +//! [7] + + +//! [8] +QAXFACTORY_EXPORT( + MyFactory, // factory class + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) +//! [8] + + +//! [9] +QAXFACTORY_BEGIN( + "{01234567-89AB-CDEF-0123-456789ABCDEF}", // type library ID + "{01234567-89AB-CDEF-0123-456789ABCDEF}" // application ID +) + QAXCLASS(Class1) + QAXCLASS(Class2) +QAXFACTORY_END() +//! [9] diff --git a/doc/src/snippets/code/src_corelib_codecs_qtextcodec.cpp b/doc/src/snippets/code/src_corelib_codecs_qtextcodec.cpp new file mode 100644 index 0000000..1dfd325 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_codecs_qtextcodec.cpp @@ -0,0 +1,34 @@ +//! [0] +QByteArray encodedString = "..."; +QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); +QString string = codec->toUnicode(encodedString); +//! [0] + + +//! [1] +QString string = "..."; +QTextCodec *codec = QTextCodec::codecForName("KOI8-R"); +QByteArray encodedString = codec->fromUnicode(string); +//! [1] + + +//! [2] +QTextCodec *codec = QTextCodec::codecForName("Shift-JIS"); +QTextDecoder *decoder = codec->makeDecoder(); + +QString string; +while (new_data_available()) { + QByteArray chunk = get_new_data(); + string += decoder->toUnicode(chunk); +} +//! [2] + + +//! [3] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QTextCodec::setCodecForTr(QTextCodec::codecForName("eucKR")); + ... +} +//! [3] diff --git a/doc/src/snippets/code/src_corelib_codecs_qtextcodecplugin.cpp b/doc/src/snippets/code/src_corelib_codecs_qtextcodecplugin.cpp new file mode 100644 index 0000000..a6870b8 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_codecs_qtextcodecplugin.cpp @@ -0,0 +1,16 @@ +//! [0] +QList<QByteArray> MyCodecPlugin::names() const +{ + return QList<QByteArray> << "IBM01140" << "hp15-tw"; +} + +QTextCodec *MyCodecPlugin::createForName(const QByteArray &name) +{ + if (name == "IBM01140") { + return new Ibm01140Codec; + } else if (name == "hp15-tw") { + return new Hp15TwCodec; + } + return 0; +} +//! [0] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp b/doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp new file mode 100644 index 0000000..24fc791 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp @@ -0,0 +1,24 @@ +//! [0] +QFuture<QString> future = ...; + +QFuture<QString>::const_iterator i; +for (i = future.constBegin(); i != future.constEnd(); ++i) + cout << *i << endl; +//! [0] + + +//! [1] +QFuture<QString> future; +... +QFutureIterator<QString> i(future); +while (i.hasNext()) + qDebug() << i.next(); +//! [1] + + +//! [2] +QFutureIterator<QString> i(future); +i.toBack(); +while (i.hasPrevious()) + qDebug() << i.previous(); +//! [2] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qfuturesynchronizer.cpp b/doc/src/snippets/code/src_corelib_concurrent_qfuturesynchronizer.cpp new file mode 100644 index 0000000..a50a99e --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qfuturesynchronizer.cpp @@ -0,0 +1,13 @@ +//! [0] +void someFunction() +{ + QFutureSynchronizer<void> synchronizer; + + ... + + synchronizer.addFuture(QtConcurrent::run(anotherFunction)); + synchronizer.addFuture(QtConcurrent::map(list, mapFunction)); + + return; // QFutureSynchronizer waits for all futures to finish +} +//! [0] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qfuturewatcher.cpp b/doc/src/snippets/code/src_corelib_concurrent_qfuturewatcher.cpp new file mode 100644 index 0000000..e1f06cc --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qfuturewatcher.cpp @@ -0,0 +1,10 @@ +//! [0] +// Instantiate the objects and connect to the finished signal. +MyClass myObject; +QFutureWatcher<int> watcher; +connect(&watcher, SIGNAL(finished()), &myObject, SLOT(handleFinished())); + +// Start the computation. +QFuture<int> future = QtConcurrent::run(...); +watcher.setFuture(future); +//! [0] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp new file mode 100644 index 0000000..8b4d10a --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp @@ -0,0 +1,35 @@ +//! [0] + +class MyException : public QtConcurrent::Exception +{ +public: + void raise() const { throw *this; } + Exception *clone() const { return new MyException(*this); } +}; + +//! [0] + + +//! [1] + +try { + QtConcurrent::blockingMap(list, throwFunction); // throwFunction throws MyException +} catch (MyException &e) { + // handle exception +} + +//! [1] + + +//! [2] + +void MyException::raise() const { throw *this; } + +//! [2] + + +//! [3] + +MyException *MyException::clone() const { return new MyException(*this); } + +//! [3] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp new file mode 100644 index 0000000..d284d02 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp @@ -0,0 +1,131 @@ +//! [0] +bool function(const T &t); +//! [0] + + +//! [1] +bool allLowerCase(const QString &string) +{ + return string.lowered() == string; +} + +QStringList strings = ...; +QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings, allLowerCase); +//! [1] + + +//! [2] +QStringList strings = ...; +QFuture<void> future = QtConcurrent::filter(strings, allLowerCase); +//! [2] + + +//! [3] +V function(T &result, const U &intermediate) +//! [3] + + +//! [4] +void addToDictionary(QSet<QString> &dictionary, const QString &string) +{ + dictionary.insert(string); +} + +QStringList strings = ...; +QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings, allLowerCase, addToDictionary); +//! [4] + + +//! [5] +QStringList strings = ...; +QFuture<QString> lowerCaseStrings = QtConcurrent::filtered(strings.constBegin(), strings.constEnd(), allLowerCase); + +// filter in-place only works on non-const iterators +QFuture<void> future = QtConcurrent::filter(strings.begin(), strings.end(), allLowerCase); + +QFuture<QSet<QString> > dictionary = QtConcurrent::filteredReduced(strings.constBegin(), strings.constEnd(), allLowerCase, addToDictionary); +//! [5] + + +//! [6] +QStringList strings = ...; + +// each call blocks until the entire operation is finished +QStringList lowerCaseStrings = QtConcurrent::blockingFiltered(strings, allLowerCase); + + +QtConcurrent::blockingFilter(strings, allLowerCase); + +QSet<QString> dictionary = QtConcurrent::blockingFilteredReduced(strings, allLowerCase, addToDictionary); +//! [6] + + +//! [7] +// keep only images with an alpha channel +QList<QImage> images = ...; +QFuture<void> alphaImages = QtConcurrent::filter(strings, &QImage::hasAlphaChannel); + +// keep only gray scale images +QList<QImage> images = ...; +QFuture<QImage> grayscaleImages = QtConcurrent::filtered(images, &QImage::isGrayscale); + +// create a set of all printable characters +QList<QChar> characters = ...; +QFuture<QSet<QChar> > set = QtConcurrent::filteredReduced(characters, &QChar::isPrint, &QSet<QChar>::insert); +//! [7] + + +//! [8] +// can mix normal functions and member functions with QtConcurrent::filteredReduced() + +// create a dictionary of all lower cased strings +extern bool allLowerCase(const QString &string); +QStringList strings = ...; +QFuture<QSet<int> > averageWordLength = QtConcurrent::filteredReduced(strings, allLowerCase, QSet<QString>::insert); + +// create a collage of all gray scale images +extern void addToCollage(QImage &collage, const QImage &grayscaleImage); +QList<QImage> images = ...; +QFuture<QImage> collage = QtConcurrent::filteredReduced(images, &QImage::isGrayscale, addToCollage); +//! [8] + + +//! [9] +bool QString::contains(const QRegExp ®exp) const; +//! [9] + + +//! [10] +boost::bind(&QString::contains, QRegExp("^\\S+$")); // matches strings without whitespace +//! [10] + + +//! [11] +bool contains(const QString &string) +//! [11] + + +//! [12] +QStringList strings = ...; +boost::bind(static_cast<bool(QString::*)(const QRegExp&)>( &QString::contains ), QRegExp("..." )); +//! [12] + +//! [13] +struct StartsWith +{ + StartsWith(const QString &string) + : m_string(string) { } + + typedef bool result_type; + + bool operator()(const QString &testString) + { + return testString.startsWith(m_string); + } + + QString m_string; +}; + +QList<QString> strings = ...; +QFuture<QString> fooString = QtConcurrent::filtered(images, StartsWith(QLatin1String("Foo"))); +//! [13] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentmap.cpp b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentmap.cpp new file mode 100644 index 0000000..cbff318 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentmap.cpp @@ -0,0 +1,144 @@ +//! [0] +U function(const T &t); +//! [0] + + +//! [1] +QImage scaled(const QImage &image) +{ + return image.scaled(100, 100); +} + +QList<QImage> images = ...; +QFuture<QImage> thumbnails = QtConcurrent::mapped(images, scaled); +//! [1] + + +//! [2] +U function(T &t); +//! [2] + + +//! [3] +void scale(QImage &image) +{ + image = image.scaled(100, 100); +} + +QList<QImage> images = ...; +QFuture<void> future = QtConcurrent::map(images, scale); +//! [3] + + +//! [4] +V function(T &result, const U &intermediate) +//! [4] + + +//! [5] +void addToCollage(QImage &collage, const QImage &thumbnail) +{ + QPainter p(&collage); + static QPoint offset = QPoint(0, 0); + p.drawImage(offset, thumbnail); + offset += ...; +} + +QList<QImage> images = ...; +QFuture<QImage> collage = QtConcurrent::mappedReduced(images, scaled, addToCollage); +//! [5] + + +//! [6] +QList<QImage> images = ...; + +QFuture<QImage> thumbnails = QtConcurrent::mapped(images.constBegin(), images.constEnd(), scaled); + +// map in-place only works on non-const iterators +QFuture<void> future = QtConcurrent::map(images.begin(), images.end(), scale); + +QFuture<QImage> collage = QtConcurrent::mappedReduced(images.constBegin(), images.constEnd(), scaled, addToCollage); +//! [6] + + +//! [7] +QList<QImage> images = ...; + +// each call blocks until the entire operation is finished +QList<QImage> future = QtConcurrent::blockingMapped(images, scaled); + +QtConcurrent::blockingMap(images, scale); + +QImage collage = QtConcurrent::blockingMappedReduced(images, scaled, addToCollage); +//! [7] + + +//! [8] +// squeeze all strings in a QStringList +QStringList strings = ...; +QFuture<void> squeezedStrings = QtConcurrent::map(strings, &QString::squeeze); + +// swap the rgb values of all pixels on a list of images +QList<QImage> images = ...; +QFuture<QImage> bgrImages = QtConcurrent::mapped(images, &QImage::rgbSwapped); + +// create a set of the lengths of all strings in a list +QStringList strings = ...; +QFuture<QSet<int> > wordLengths = QtConcurrent::mappedReduced(string, &QString::length, &QSet<int>::insert); +//! [8] + + +//! [9] +// can mix normal functions and member functions with QtConcurrent::mappedReduced() + +// compute the average length of a list of strings +extern void computeAverage(int &average, int length); +QStringList strings = ...; +QFuture<int> averageWordLength = QtConcurrent::mappedReduced(strings, &QString::length, computeAverage); + +// create a set of the color distribution of all images in a list +extern int colorDistribution(const QImage &string); +QList<QImage> images = ...; +QFuture<QSet<int> > totalColorDistribution = QtConcurrent::mappedReduced(images, colorDistribution, QSet<int>::insert); +//! [9] + + +//! [10] +QImage QImage::scaledToWidth(int width, Qt::TransformationMode) const; +//! [10] + + +//! [11] +boost::bind(&QImage::scaledToWidth, 100, Qt::SmoothTransformation) +//! [11] + + +//! [12] +QImage scaledToWith(const QImage &image) +//! [12] + + +//! [13] +QList<QImage> images = ...; +QFuture<QImage> thumbnails = QtConcurrent::mapped(images, boost::bind(&QImage::scaledToWidth, 100 Qt::SmoothTransformation)); +//! [13] + +//! [14] +struct Scaled +{ + Scaled(int size) + : m_size(size) { } + + typedef QImage result_type; + + QImage operator()(const QImage &image) + { + return image.scaled(m_size, m_size); + } + + int m_size; +}; + +QList<QImage> images = ...; +QFuture<QImage> thumbnails = QtConcurrent::mapped(images, Scaled(100)); +//! [14] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentrun.cpp b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentrun.cpp new file mode 100644 index 0000000..99583ba --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qtconcurrentrun.cpp @@ -0,0 +1,60 @@ +//! [0] +extern void aFunction(); +QFuture<void> future = QtConcurrent::run(aFunction); +//! [0] + + +//! [1] +extern void aFunctionWithArguments(int arg1, double arg2, const QString &string); + +int integer = ...; +double floatingPoint = ...; +QString string = ...; + +QFuture<void> future = QtConcurrent::run(aFunctionWithArguments, integer, floatingPoint, string); +//! [1] + + +//! [2] +extern QString functionReturningAString(); +QFuture<QString> future = QtConcurrent::run(functionReturningAString); +... +QString result = future.result(); +//! [2] + + +//! [3] +extern QString someFunction(const QByteArray &input); + +QByteArray bytearray = ...; + +QFuture<QString> future = QtConcurrent::run(someFunction, bytearray); +... +QString result = future.result(); +//! [3] + + +//! [4] +// call 'QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const' in a separate thread +QString string = ...; +QFuture<QStringList> future = QtConcurrent::run(string, &QString::split, QString(", "), QString::KeepEmptyParts, Qt::CaseSensitive); +... +QStringList result = future.result(); +//! [4] + + +//! [5] +// call 'void QImage::invertPixels(InvertMode mode)' in a separate thread +QImage image = ...; +QFuture<void> future = QtConcurrent::run(image, &QImage::invertPixels, QImage::InvertRgba); +... +future.waitForFinished(); +// At this point, the pixels in 'image' have been inverted +//! [5] + + +//! [6] +void someFunction(int arg1, double arg2); +QFuture<void> future = QtConcurrent::run(boost::bind(someFunction, 1, 2.0)); +... +//! [6] diff --git a/doc/src/snippets/code/src_corelib_concurrent_qthreadpool.cpp b/doc/src/snippets/code/src_corelib_concurrent_qthreadpool.cpp new file mode 100644 index 0000000..327a00f --- /dev/null +++ b/doc/src/snippets/code/src_corelib_concurrent_qthreadpool.cpp @@ -0,0 +1,13 @@ +//! [0] +class HelloWorldTask : public QRunnable +{ + void run() + { + qDebug() << "Hello world from thread" << QThread::currentThread(); + } +} + +HelloWorldTask *hello = new HelloWorldTask(); +// QThreadPool takes ownership and deletes 'hello' automatically +QThreadPool::globalInstance()->start(hello); +//! [0] diff --git a/doc/src/snippets/code/src_corelib_global_qglobal.cpp b/doc/src/snippets/code/src_corelib_global_qglobal.cpp new file mode 100644 index 0000000..72663e9 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_global_qglobal.cpp @@ -0,0 +1,458 @@ +//! [0] +label->setAlignment(Qt::AlignLeft | Qt::AlignTop); +//! [0] + + +//! [1] +class MyClass +{ +public: + enum Option { + NoOptions = 0x0, + ShowTabs = 0x1, + ShowAll = 0x2, + SqueezeBlank = 0x4 + }; + Q_DECLARE_FLAGS(Options, Option) + ... +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(MyClass::Options) +//! [1] + +//! [meta-object flags] +Q_FLAGS(Options) +//! [meta-object flags] + +//! [2] +typedef QFlags<Enum> Flags; +//! [2] + + +//! [3] +int myValue = 10; +int minValue = 2; +int maxValue = 6; + +int boundedValue = qBound(minValue, myValue, maxValue); +// boundedValue == 6 +//! [3] + + +//! [4] +if (!driver()->isOpen() || driver()->isOpenError()) { + qWarning("QSqlQuery::exec: database not open"); + return false; +} +//! [4] + + +//! [5] +qint64 value = Q_INT64_C(932838457459459); +//! [5] + + +//! [6] +quint64 value = Q_UINT64_C(932838457459459); +//! [6] + + +//! [7] +void myMsgHandler(QtMsgType, const char *); +//! [7] + + +//! [8] +qint64 value = Q_INT64_C(932838457459459); +//! [8] + + +//! [9] +quint64 value = Q_UINT64_C(932838457459459); +//! [9] + + +//! [10] +int absoluteValue; +int myValue = -4; + +absoluteValue = qAbs(myValue); +// absoluteValue == 4 +//! [10] + + +//! [11] +qreal valueA = 2.3; +qreal valueB = 2.7; + +int roundedValueA = qRound(valueA); +// roundedValueA = 2 +int roundedValueB = qRound(valueB); +// roundedValueB = 3 +//! [11] + + +//! [12] +qreal valueA = 42949672960.3; +qreal valueB = 42949672960.7; + +int roundedValueA = qRound(valueA); +// roundedValueA = 42949672960 +int roundedValueB = qRound(valueB); +// roundedValueB = 42949672961 +//! [12] + + +//! [13] +int myValue = 6; +int yourValue = 4; + +int minValue = qMin(myValue, yourValue); +// minValue == yourValue +//! [13] + + +//! [14] +int myValue = 6; +int yourValue = 4; + +int maxValue = qMax(myValue, yourValue); +// maxValue == myValue +//! [14] + + +//! [15] +int myValue = 10; +int minValue = 2; +int maxValue = 6; + +int boundedValue = qBound(minValue, myValue, maxValue); +// boundedValue == 6 +//! [15] + + +//! [16] +#if QT_VERSION >= 0x040100 + QIcon icon = style()->standardIcon(QStyle::SP_TrashIcon); +#else + QPixmap pixmap = style()->standardPixmap(QStyle::SP_TrashIcon); + QIcon icon(pixmap); +#endif +//! [16] + + +//! [17] +// File: div.cpp + +#include <QtGlobal> + +int divide(int a, int b) +{ + Q_ASSERT(b != 0); + return a / b; +} +//! [17] + + +//! [18] +ASSERT: "b == 0" in file div.cpp, line 7 +//! [18] + + +//! [19] +// File: div.cpp + +#include <QtGlobal> + +int divide(int a, int b) +{ + Q_ASSERT_X(b != 0, "divide", "division by zero"); + return a / b; +} +//! [19] + + +//! [20] +ASSERT failure in divide: "division by zero", file div.cpp, line 7 +//! [20] + + +//! [21] +int *a; + +Q_CHECK_PTR(a = new int[80]); // WRONG! + +a = new (nothrow) int[80]; // Right +Q_CHECK_PTR(a); +//! [21] + + +//! [22] +template<typename TInputType> +const TInputType &myMin(const TInputType &value1, const TInputType &value2) +{ + qDebug() << Q_FUNC_INFO << "was called with value1:" << value1 << "value2:" << value2; + + if(value1 < value2) + return value1; + else + return value2; +} +//! [22] + + +//! [23] +#include <qapplication.h> +#include <stdio.h> +#include <stdlib.h> + +void myMessageOutput(QtMsgType type, const char *msg) +{ + switch (type) { + case QtDebugMsg: + fprintf(stderr, "Debug: %s\n", msg); + break; + case QtWarningMsg: + fprintf(stderr, "Warning: %s\n", msg); + break; + case QtCriticalMsg: + fprintf(stderr, "Critical: %s\n", msg); + break; + case QtFatalMsg: + fprintf(stderr, "Fatal: %s\n", msg); + abort(); + } +} + +int main(int argc, char **argv) +{ + qInstallMsgHandler(myMessageOutput); + QApplication app(argc, argv); + ... + return app.exec(); +} +//! [23] + + +//! [24] +qDebug("Items in list: %d", myList.size()); +//! [24] + + +//! [25] +qDebug() << "Brush:" << myQBrush << "Other value:" << i; +//! [25] + + +//! [26] +void f(int c) +{ + if (c > 200) + qWarning("f: bad argument, c == %d", c); +} +//! [26] + + +//! [27] +qWarning() << "Brush:" << myQBrush << "Other value:" +<< i; +//! [27] + + +//! [28] +void load(const QString &fileName) +{ + QFile file(fileName); + if (!file.exists()) + qCritical("File '%s' does not exist!", qPrintable(fileName)); +} +//! [28] + + +//! [29] +qCritical() << "Brush:" << myQBrush << "Other +value:" << i; +//! [29] + + +//! [30] +int divide(int a, int b) +{ + if (b == 0) // program error + qFatal("divide: cannot divide by zero"); + return a / b; +} +//! [30] + + +//! [31] +forever { + ... +} +//! [31] + + +//! [32] +CONFIG += no_keywords +//! [32] + + +//! [33] +CONFIG += no_keywords +//! [33] + + +//! [34] +QString FriendlyConversation::greeting(int type) +{ +static const char *greeting_strings[] = { + QT_TR_NOOP("Hello"), + QT_TR_NOOP("Goodbye") +}; +return tr(greeting_strings[type]); +} +//! [34] + + +//! [35] +static const char *greeting_strings[] = { + QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), + QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") +}; + +QString FriendlyConversation::greeting(int type) +{ + return tr(greeting_strings[type]); +} + +QString global_greeting(int type) +{ + return qApp->translate("FriendlyConversation", + greeting_strings[type]); +} +//! [35] + + +//! [36] + +static { const char *source; const char *comment; } greeting_strings[] = +{ + QT_TRANSLATE_NOOP3("FriendlyConversation", "Hello", + "A really friendly hello"), + QT_TRANSLATE_NOOP3("FriendlyConversation", "Goodbye", + "A really friendly goodbye") +}; + +QString FriendlyConversation::greeting(int type) +{ + return tr(greeting_strings[type].source, + greeting_strings[type].comment); +} + +QString global_greeting(int type) +{ + return qApp->translate("FriendlyConversation", + greeting_strings[type].source, + greeting_strings[type].comment); +} +//! [36] + + +//! [37] +qWarning("%s: %s", qPrintable(key), qPrintable(value)); +//! [37] + + +//! [38] +struct Point2D +{ + int x; + int y; +}; + +Q_DECLARE_TYPEINFO(Point2D, Q_PRIMITIVE_TYPE); +//! [38] + + +//! [39] +class Point2D +{ +public: + Point2D() { data = new int[2]; } + Point2D(const Point2D &other) { ... } + ~Point2D() { delete[] data; } + + Point2D &operator=(const Point2D &other) { ... } + + int x() const { return data[0]; } + int y() const { return data[1]; } + +private: + int *data; +}; + +Q_DECLARE_TYPEINFO(Point2D, Q_MOVABLE_TYPE); +//! [39] + + +//! [40] +#if Q_BYTE_ORDER == Q_BIG_ENDIAN +... +#endif + +or + +#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN +... +#endif + +//! [40] + + +//! [41] + +#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN +... +#endif + +//! [41] + + +//! [42] +#if Q_BYTE_ORDER == Q_BIG_ENDIAN +... +#endif + +//! [42] + +//! [begin namespace macro] +namespace QT_NAMESPACE { +//! [begin namespace macro] + +//! [end namespace macro] +} +//! [end namespace macro] + +//! [43] +class MyClass : public QObject +{ + + private: + Q_DISABLE_COPY(MyClass) +}; + +//! [43] + +//! [44] +class MyClass : public QObject +{ + + private: + MyClass(const MyClass &); + MyClass &operator=(const MyClass &); +}; +//! [44] + +//! [45] + QWidget w = QWidget(); +//! [45] diff --git a/doc/src/snippets/code/src_corelib_io_qabstractfileengine.cpp b/doc/src/snippets/code/src_corelib_io_qabstractfileengine.cpp new file mode 100644 index 0000000..a7d7c75 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qabstractfileengine.cpp @@ -0,0 +1,80 @@ +//! [0] +class ZipEngineHandler : public QAbstractFileEngineHandler +{ +public: + QAbstractFileEngine *create(const QString &fileName) const; +}; + +QAbstractFileEngine *ZipEngineHandler::create(const QString &fileName) const +{ + // ZipEngineHandler returns a ZipEngine for all .zip files + return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + ZipEngineHandler engine; + + MainWindow window; + window.show(); + + return app.exec(); +} +//! [0] + + +//! [1] +QAbstractSocketEngine *ZipEngineHandler::create(const QString &fileName) const +{ + // ZipEngineHandler returns a ZipEngine for all .zip files + return fileName.toLower().endsWith(".zip") ? new ZipEngine(fileName) : 0; +} +//! [1] + + +//! [2] +QAbstractFileEngineIterator * +CustomFileEngine::beginEntryList(QDir::Filters filters, const QStringList &filterNames) +{ + return new CustomFileEngineIterator(filters, filterNames); +} +//! [2] + + +//! [3] +class CustomIterator : public QAbstractFileEngineIterator +{ +public: + CustomIterator(const QStringList &nameFilters, QDir::Filters filters) + : QAbstractFileEngineIterator(nameFilters, filters), index(0) + { + // In a real iterator, these entries are fetched from the + // file system based on the value of path(). + entries << "entry1" << "entry2" << "entry3"; + } + + bool hasNext() const + { + return index < entries.size() - 1; + } + + QString next() + { + if (!hasNext()) + return QString(); + ++index; + return currentFilePath(); + } + + QString currentFileName() + { + return entries.at(index); + } + +private: + QStringList entries; + int index; +}; +//! [3] diff --git a/doc/src/snippets/code/src_corelib_io_qdatastream.cpp b/doc/src/snippets/code/src_corelib_io_qdatastream.cpp new file mode 100644 index 0000000..fd6d564 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qdatastream.cpp @@ -0,0 +1,81 @@ +void wrapInFunction() +{ + +//! [0] +QFile file("file.dat"); +file.open(QIODevice::WriteOnly); +QDataStream out(&file); // we will serialize the data into the file +out << "the answer is"; // serialize a string +out << (qint32)42; // serialize an integer +//! [0] + + +//! [1] +QFile file("file.dat"); +file.open(QIODevice::ReadOnly); +QDataStream in(&file); // read the data serialized from the file +QString str; +qint32 a; +in >> str >> a; // extract "the answer is" and 42 +//! [1] + + +//! [2] +stream.setVersion(QDataStream::Qt_4_0); +//! [2] + + +//! [3] +QFile file("file.xxx"); +file.open(QIODevice::WriteOnly); +QDataStream out(&file); + +// Write a header with a "magic number" and a version +out << (quint32)0xA0B0C0D0; +out << (qint32)123; + +out.setVersion(QDataStream::Qt_4_0); + +// Write the data +out << lots_of_interesting_data; +//! [3] + + +//! [4] +QFile file("file.xxx"); +file.open(QIODevice::ReadOnly); +QDataStream in(&file); + +// Read and check the header +quint32 magic; +in >> magic; +if (magic != 0xA0B0C0D0) + return XXX_BAD_FILE_FORMAT; + +// Read the version +qint32 version; +in >> version; +if (version < 100) + return XXX_BAD_FILE_TOO_OLD; +if (version > 123) + return XXX_BAD_FILE_TOO_NEW; + +if (version <= 110) + in.setVersion(QDataStream::Qt_3_2); +else + in.setVersion(QDataStream::Qt_4_0); + +// Read the data +in >> lots_of_interesting_data; +if (version >= 120) + in >> data_new_in_XXX_version_1_2; +in >> other_interesting_data; +//! [4] + + +//! [5] +QDataStream out(file); +out.setVersion(QDataStream::Qt_4_0); +//! [5] + +} diff --git a/doc/src/snippets/code/src_corelib_io_qdir.cpp b/doc/src/snippets/code/src_corelib_io_qdir.cpp new file mode 100644 index 0000000..4af4d4b --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qdir.cpp @@ -0,0 +1,135 @@ + +void wrapInFunction() +{ + +//! [0] +QDir("/home/user/Documents") +QDir("C:/Documents and Settings") +//! [0] + + +//! [1] +QDir("images/landscape.png") +//! [1] + + +//! [2] +QDir("Documents/Letters/Applications").dirName() // "Applications" +QDir().dirName() // "." +//! [2] + + +//! [3] +QDir directory("Documents/Letters"); +QString path = directory.filePath("contents.txt"); +QString absolutePath = directory.absoluteFilePath("contents.txt"); +//! [3] + + +//! [4] +QDir dir("example"); +if (!dir.exists()) + qWarning("Cannot find the example directory"); +//! [4] + + +//! [5] +QDir dir = QDir::root(); // "/" +if (!dir.cd("tmp")) { // "/tmp" + qWarning("Cannot find the \"/tmp\" directory"); +} else { + QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt" + if (!file.open(QIODevice::ReadWrite)) + qWarning("Cannot create the file %s", file.name()); +} +//! [5] + + +//! [6] +QString bin = "/local/bin"; // where /local/bin is a symlink to /usr/bin +QDir binDir(bin); +QString canonicalBin = binDir.canonicalPath(); +// canonicalBin now equals "/usr/bin" + +QString ls = "/local/bin/ls"; // where ls is the executable "ls" +QDir lsDir(ls); +QString canonicalLs = lsDir.canonicalPath(); +// canonicalLS now equals "/usr/bin/ls". +//! [6] + + +//! [7] +QDir dir("/home/bob"); +QString s; + +s = dir.relativeFilePath("images/file.jpg"); // s is "images/file.jpg" +s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt" +//! [7] + + +//! [8] +QDir::setSearchPaths("icons", QStringList(QDir::homePath() + "/images")); +QDir::setSearchPaths("docs", QStringList(":/embeddedDocuments")); +... +QPixmap pixmap("icons:undo.png"); // will look for undo.png in QDir::homePath() + "/images" +QFile file("docs:design.odf"); // will look in the :/embeddedDocuments resource path +//! [8] + + +//! [9] +QDir dir("/tmp/root_link"); +dir = dir.canonicalPath(); +if (dir.isRoot()) + qWarning("It is a root link"); +//! [9] + + +//! [10] +// The current directory is "/usr/local" +QDir d1("/usr/local/bin"); +QDir d2("bin"); +if (d1 == d2) + qDebug("They're the same"); +//! [10] + + +//! [11] +// The current directory is "/usr/local" +QDir d1("/usr/local/bin"); +d1.setFilter(QDir::Executable); +QDir d2("bin"); +if (d1 != d2) + qDebug("They differ"); +//! [11] + + +//! [12] +C:/Documents and Settings/Username +//! [12] + + +//! [13] +Q_INIT_RESOURCE(myapp); +//! [13] + + +//! [14] +inline void initMyResource() { Q_INIT_RESOURCE(myapp); } + +namespace MyNamespace +{ + ... + + void myFunction() + { + initMyResource(); + } +} +//! [14] + + +//! [15] +Q_CLEANUP_RESOURCE(myapp); +//! [15] + +} diff --git a/doc/src/snippets/code/src_corelib_io_qdiriterator.cpp b/doc/src/snippets/code/src_corelib_io_qdiriterator.cpp new file mode 100644 index 0000000..2983a25 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qdiriterator.cpp @@ -0,0 +1,12 @@ +//! [0] +QDirIterator it("/etc", QDirIterator::Subdirectories); +while (it.hasNext()) { + qDebug() << it.next(); + + // /etc/. + // /etc/.. + // /etc/X11 + // /etc/X11/fs + // ... +} +//! [0] diff --git a/doc/src/snippets/code/src_corelib_io_qfile.cpp b/doc/src/snippets/code/src_corelib_io_qfile.cpp new file mode 100644 index 0000000..84b8b4a --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qfile.cpp @@ -0,0 +1,35 @@ +//! [0] +QFile file; +QDir::setCurrent("/tmp"); +file.setFileName("readme.txt"); +QDir::setCurrent("/home"); +file.open(QIODevice::ReadOnly); // opens "/home/readme.txt" under Unix +//! [0] + + +//! [1] +QByteArray myEncoderFunc(const QString &fileName); +//! [1] + + +//! [2] +QString myDecoderFunc(const QByteArray &localFileName); +//! [2] + + +//! [3] +#include <stdio.h> + +void printError(const char* msg) +{ + QFile file; + file.open(stderr, QIODevice::WriteOnly); + file.write(msg, qstrlen(msg)); // write to stderr + file.close(); +} +//! [3] + + +//! [4] +CONFIG += console +//! [4] diff --git a/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp b/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp new file mode 100644 index 0000000..2ab15ee --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qfileinfo.cpp @@ -0,0 +1,106 @@ + +//![newstuff] + QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath() => "C:/temp/foo" +//![newstuff] + +//! [0] +#ifdef Q_OS_UNIX + +QFileInfo info1("/home/bob/bin/untabify"); +info1.isSymLink(); // returns true +info1.absoluteFilePath(); // returns "/home/bob/bin/untabify" +info1.size(); // returns 56201 +info1.symLinkTarget(); // returns "/opt/pretty++/bin/untabify" + +QFileInfo info2(info1.symLinkTarget()); +info1.isSymLink(); // returns false +info1.absoluteFilePath(); // returns "/opt/pretty++/bin/untabify" +info1.size(); // returns 56201 + +#endif +//! [0] + + +//! [1] +#ifdef Q_OS_WIN + +QFileInfo info1("C:\\Documents and Settings\\Bob\\untabify.lnk"); +info1.isSymLink(); // returns true +info1.absoluteFilePath(); // returns "C:/Documents and Settings/Bob/untabify.lnk" +info1.size(); // returns 743 +info1.symLinkTarget(); // returns "C:/Pretty++/untabify" + +QFileInfo info2(info1.symLinkTarget()); +info1.isSymLink(); // returns false +info1.absoluteFilePath(); // returns "C:/Pretty++/untabify" +info1.size(); // returns 63942 + +#endif +//! [1] + + +//! [2] +QString absolute = "/local/bin"; +QString relative = "local/bin"; +QFileInfo absFile(absolute); +QFileInfo relFile(relative); + +QDir::setCurrent(QDir::rootPath()); +// 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" +//! [2] + + +//! [3] +QFileInfo fi("/tmp/archive.tar.gz"); +QString name = fi.fileName(); // name = "archive.tar.gz" +//! [3] + + +//! [4] +QFileInfo fi("/Applications/Safari.app"); +QString bundle = fi.bundleName(); // name = "Safari" +//! [4] + + +//! [5] +QFileInfo fi("/tmp/archive.tar.gz"); +QString base = fi.baseName(); // base = "archive" +//! [5] + + +//! [6] +QFileInfo fi("/tmp/archive.tar.gz"); +QString base = fi.completeBaseName(); // base = "archive.tar" +//! [6] + + +//! [7] +QFileInfo fi("/tmp/archive.tar.gz"); +QString ext = fi.completeSuffix(); // ext = "tar.gz" +//! [7] + + +//! [8] +QFileInfo fi("/tmp/archive.tar.gz"); +QString ext = fi.suffix(); // ext = "gz" +//! [8] + + +//! [9] +QFileInfo info(fileName); +if (info.isSymLink()) + fileName = info.symLinkTarget(); +//! [9] + + +//! [10] +QFileInfo fi("/tmp/archive.tar.gz"); +if (fi.permission(QFile::WriteUser | QFile::ReadGroup)) + qWarning("I can change the file; my group can read the file"); +if (fi.permission(QFile::WriteGroup | QFile::WriteOther)) + qWarning("The group or others can change the file"); +//! [10] diff --git a/doc/src/snippets/code/src_corelib_io_qiodevice.cpp b/doc/src/snippets/code/src_corelib_io_qiodevice.cpp new file mode 100644 index 0000000..422ca11 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qiodevice.cpp @@ -0,0 +1,59 @@ +//! [0] +QProcess gzip; +gzip.start("gzip", QStringList() << "-c"); +if (!gzip.waitForStarted()) + return false; + +gzip.write("uncompressed data"); + +QByteArray compressed; +while (gzip.waitForReadyRead()) + compressed += gzip.readAll(); +//! [0] + + +//! [1] +qint64 CustomDevice::bytesAvailable() const +{ + return buffer.size() + QIODevice::bytesAvailable(); +} +//! [1] + + +//! [2] +QFile file("box.txt"); +if (file.open(QFile::ReadOnly)) { + char buf[1024]; + qint64 lineLength = file.readLine(buf, sizeof(buf)); + if (lineLength != -1) { + // the line is available in buf + } +} +//! [2] + + +//! [3] +bool CustomDevice::canReadLine() const +{ + return buffer.contains('\n') || QIODevice::canReadLine(); +} +//! [3] + + +//! [4] +bool isExeFile(QFile *file) +{ + char buf[2]; + if (file->peek(buf, sizeof(buf)) == sizeof(buf)) + return (buf[0] == 'M' && buf[1] == 'Z'); + return false; +} +//! [4] + + +//! [5] +bool isExeFile(QFile *file) +{ + return file->peek(2) == "MZ"; +} +//! [5] diff --git a/doc/src/snippets/code/src_corelib_io_qprocess.cpp b/doc/src/snippets/code/src_corelib_io_qprocess.cpp new file mode 100644 index 0000000..6eb8ccb --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qprocess.cpp @@ -0,0 +1,94 @@ + +void wrapInFunction() +{ + +//! [0] +QProcess builder; +builder.setProcessChannelMode(QProcess::MergedChannels); +builder.start("make", QStringList() << "-j2"); + +if (!builder.waitForFinished()) + qDebug() << "Make failed:" << builder.errorString(); +else + qDebug() << "Make output:" << builder.readAll(); +//! [0] + + +//! [1] +QProcess more; +more.start("more"); +more.write("Text to display"); +more.closeWriteChannel(); +// QProcess will emit readyRead() once "more" starts printing +//! [1] + + +//! [2] +command1 | command2 +//! [2] + + +//! [3] +QProcess process1; +QProcess process2; + +process1.setStandardOutputProcess(process2); + +process1.start("command1"); +process2.start("command2"); +//! [3] + + +//! [4] +class SandboxProcess : public QProcess +{ + ... + protected: + void setupChildProcess(); + ... +}; + +void SandboxProcess::setupChildProcess() +{ + // Drop all privileges in the child process, and enter + // a chroot jail. +#if defined Q_OS_UNIX + ::setgroups(0, 0); + ::chroot("/etc/safe"); + ::chdir("/"); + ::setgid(safeGid); + ::setuid(safeUid); + ::umask(0); +#endif +} + +//! [4] + + +//! [5] +QProcess process; +process.start("del /s *.txt"); +// same as process.start("del", QStringList() << "/s" << "*.txt"); +... +//! [5] + + +//! [6] +QProcess process; +process.start("dir \"My Documents\""); +//! [6] + + +//! [7] +QProcess process; +process.start("dir \"\"\"My Documents\"\"\""); +//! [7] + + +//! [8] +QStringList environment = QProcess::systemEnvironment(); +// environment = {"PATH=/usr/bin:/usr/local/bin", +// "USER=greg", "HOME=/home/greg"} +//! [8] + +} diff --git a/doc/src/snippets/code/src_corelib_io_qsettings.cpp b/doc/src/snippets/code/src_corelib_io_qsettings.cpp new file mode 100644 index 0000000..dfe666f --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qsettings.cpp @@ -0,0 +1,276 @@ +//! [0] +QSettings settings("MySoft", "Star Runner"); +QColor color = settings.value("DataPump/bgcolor").value<QColor>(); +//! [0] + + +//! [1] +QSettings settings("MySoft", "Star Runner"); +QColor color = palette().background().color(); +settings.setValue("DataPump/bgcolor", color); +//! [1] + + +//! [2] +QSettings settings("/home/petra/misc/myapp.ini", + QSettings::IniFormat); +//! [2] + + +//! [3] +QSettings settings("/Users/petra/misc/myapp.plist", + QSettings::NativeFormat); +//! [3] + + +//! [4] +QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office", + QSettings::NativeFormat); +//! [4] + + +//! [5] +settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0); +//! [5] + + +//! [6] +settings.setValue("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy", "Milkyway"); +settings.setValue("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy\\Sun", "OurStar"); +settings.value("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy\\Default"); // returns "Milkyway" +//! [6] + + +//! [7] +#ifdef Q_WS_MAC + QSettings settings("grenoullelogique.fr", "Squash"); +#else + QSettings settings("Grenoulle Logique", "Squash"); +#endif +//! [7] + + +//! [8] +pos = @Point(100 100) +//! [8] + + +//! [9] +windir = C:\Windows +//! [9] + + +//! [10] +QSettings settings("Moose Tech", "Facturo-Pro"); +//! [10] + + +//! [11] +QSettings settings("Moose Soft", "Facturo-Pro"); +//! [11] + + +//! [12] +QCoreApplication::setOrganizationName("Moose Soft"); +QCoreApplication::setApplicationName("Facturo-Pro"); +QSettings settings; +//! [12] + + +//! [13] +settings.beginGroup("mainwindow"); +settings.setValue("size", win->size()); +settings.setValue("fullScreen", win->isFullScreen()); +settings.endGroup(); + +settings.beginGroup("outputpanel"); +settings.setValue("visible", panel->isVisible()); +settings.endGroup(); +//! [13] + + +//! [14] +settings.beginGroup("alpha"); +// settings.group() == "alpha" + +settings.beginGroup("beta"); +// settings.group() == "alpha/beta" + +settings.endGroup(); +// settings.group() == "alpha" + +settings.endGroup(); +// settings.group() == "" +//! [14] + + +//! [15] +struct Login { + QString userName; + QString password; +}; +QList<Login> logins; +... + +QSettings settings; +int size = settings.beginReadArray("logins"); +for (int i = 0; i < size; ++i) { + settings.setArrayIndex(i); + Login login; + login.userName = settings.value("userName").toString(); + login.password = settings.value("password").toString(); + logins.append(login); +} +settings.endArray(); +//! [15] + + +//! [16] +struct Login { + QString userName; + QString password; +}; +QList<Login> logins; +... + +QSettings settings; +settings.beginWriteArray("logins"); +for (int i = 0; i < logins.size(); ++i) { + settings.setArrayIndex(i); + settings.setValue("userName", list.at(i).userName); + settings.setValue("password", list.at(i).password); +} +settings.endArray(); +//! [16] + + +//! [17] +QSettings settings; +settings.setValue("fridge/color", Qt::white); +settings.setValue("fridge/size", QSize(32, 96)); +settings.setValue("sofa", true); +settings.setValue("tv", false); + +QStringList keys = settings.allKeys(); +// keys: ["fridge/color", "fridge/size", "sofa", "tv"] +//! [17] + + +//! [18] +settings.beginGroup("fridge"); +keys = settings.allKeys(); +// keys: ["color", "size"] +//! [18] + + +//! [19] +QSettings settings; +settings.setValue("fridge/color", Qt::white); +settings.setValue("fridge/size", QSize(32, 96)); +settings.setValue("sofa", true); +settings.setValue("tv", false); + +QStringList keys = settings.childKeys(); +// keys: ["sofa", "tv"] +//! [19] + + +//! [20] +settings.beginGroup("fridge"); +keys = settings.childKeys(); +// keys: ["color", "size"] +//! [20] + + +//! [21] +QSettings settings; +settings.setValue("fridge/color", Qt::white); +settings.setValue("fridge/size", QSize(32, 96)); +settings.setValue("sofa", true); +settings.setValue("tv", false); + +QStringList groups = settings.childGroups(); +// group: ["fridge"] +//! [21] + + +//! [22] +settings.beginGroup("fridge"); +groups = settings.childGroups(); +// groups: [] +//! [22] + + +//! [23] +QSettings settings; +settings.setValue("interval", 30); +settings.value("interval").toInt(); // returns 30 + +settings.setValue("interval", 6.55); +settings.value("interval").toDouble(); // returns 6.55 +//! [23] + + +//! [24] +QSettings settings; +settings.setValue("ape"); +settings.setValue("monkey", 1); +settings.setValue("monkey/sea", 2); +settings.setValue("monkey/doe", 4); + +settings.remove("monkey"); +QStringList keys = settings.allKeys(); +// keys: ["ape"] +//! [24] + + +//! [25] +QSettings settings; +settings.setValue("ape"); +settings.setValue("monkey", 1); +settings.setValue("monkey/sea", 2); +settings.setValue("monkey/doe", 4); + +settings.beginGroup("monkey"); +settings.remove(""); +settings.endGroup(); + +QStringList keys = settings.allKeys(); +// keys: ["ape"] +//! [25] + + +//! [26] +QSettings settings; +settings.setValue("animal/snake", 58); +settings.value("animal/snake", 1024).toInt(); // returns 58 +settings.value("animal/zebra", 1024).toInt(); // returns 1024 +settings.value("animal/zebra").toInt(); // returns 0 +//! [26] + + +//! [27] +bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map); +//! [27] + + +//! [28] +bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map); +//! [28] + + +//! [29] +bool readXmlFile(QIODevice &device, QSettings::SettingsMap &map); +bool writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map); + +int main(int argc, char *argv[]) +{ + const QSettings::Format XmlFormat = + QSettings::registerFormat("xml", readXmlFile, writeXmlFile); + + QSettings settings(XmlFormat, QSettings::UserSettings, "MySoft", + "Star Runner"); + + ... +} +//! [29] diff --git a/doc/src/snippets/code/src_corelib_io_qtemporaryfile.cpp b/doc/src/snippets/code/src_corelib_io_qtemporaryfile.cpp new file mode 100644 index 0000000..adb8a71 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qtemporaryfile.cpp @@ -0,0 +1,13 @@ +{ +//! [0] + // Within a function/method... + + QTemporaryFile file; + if (file.open()) { + // file.fileName() returns the unique file name + } + + // The QTemporaryFile destructor removes the temporary file + // as it goes out of scope. +//! [0] +} diff --git a/doc/src/snippets/code/src_corelib_io_qtextstream.cpp b/doc/src/snippets/code/src_corelib_io_qtextstream.cpp new file mode 100644 index 0000000..e85fcc1 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qtextstream.cpp @@ -0,0 +1,89 @@ +//! [0] +QFile data("output.txt"); +if (data.open(QFile::WriteOnly | QFile::Truncate)) { + QTextStream out(&data); + out << "Result: " << qSetFieldWidth(10) << left << 3.14 << 2.7; + // writes "Result: 3.14 2.7 " +} +//! [0] + + +//! [1] +QTextStream stream(stdin); +QString line; +do { + line = stream.readLine(); +} while (!line.isNull()); +//! [1] + + +//! [2] +QTextStream in("0x50 0x20"); +int firstNumber, secondNumber; + +in >> firstNumber; // firstNumber == 80 +in >> dec >> secondNumber; // secondNumber == 0 + +char ch; +in >> ch; // ch == 'x' +//! [2] + + +//! [3] +int main(int argc, char *argv[]) +{ + // read numeric arguments (123, 0x20, 4.5...) + for (int i = 1; i < argc; ++i) { + int number; + QTextStream in(argv[i]); + in >> number; + ... + } +} +//! [3] + + +//! [4] +QString str; +QTextStream in(stdin); +in >> str; +//! [4] + + +//! [5] +QString s; +QTextStream out(&s); +out.setFieldWidth(10); +out.setFieldAlignment(QTextStream::AlignCenter); +out.setPadChar('-'); +out << "Qt" << "rocks!"; +//! [5] + + +//! [6] +----Qt------rocks!-- +//! [6] + + +//! [7] +QTextStream in(file); +QChar ch1, ch2, ch3; +in >> ch1 >> ch2 >> ch3; +//! [7] + + +//! [8] +QTextStream out(stdout); +out << "Qt rocks!" << endl; +//! [8] + + +//! [9] +stream << '\n' << flush; +//! [9] + + +//! [10] +QTextStream out(&file); +out.setCodec("UTF-8"); +//! [10] diff --git a/doc/src/snippets/code/src_corelib_io_qurl.cpp b/doc/src/snippets/code/src_corelib_io_qurl.cpp new file mode 100644 index 0000000..95de86c --- /dev/null +++ b/doc/src/snippets/code/src_corelib_io_qurl.cpp @@ -0,0 +1,47 @@ +//! [0] +QUrl url("http://www.example.com/List of holidays.xml"); +// url.toEncoded() == "http://www.example.com/List%20of%20holidays.xml" +//! [0] + + +//! [1] +QUrl url = QUrl::fromEncoded("http://qtsoftware.com/List%20of%20holidays.xml"); +//! [1] + + +//! [2] +bool checkUrl(const QUrl &url) { + if (!url.isValid()) { + qDebug(QString("Invalid URL: %1").arg(url.toString())); + return false; + } + + return true; +} +//! [2] + + +//! [3] +QFtp ftp; +ftp.connectToHost(url.host(), url.port(21)); +//! [3] + + +//! [4] +http://www.example.com/cgi-bin/drawgraph.cgi?type-pie/color-green +//! [4] + + +//! [5] +QUrl baseUrl("http://qtsoftware.com/support"); +QUrl relativeUrl("../products/solutions"); +qDebug(baseUrl.resolved(relativeUrl).toString()); +// prints "http://qtsoftware.com/products/solutions" +//! [5] + + +//! [6] +QByteArray ba = QUrl::toPercentEncoding("{a fishy string?}", "{}", "s"); +qDebug(ba.constData()); +// prints "{a fi%73hy %73tring%3F}" +//! [6] diff --git a/doc/src/snippets/code/src_corelib_kernel_qabstracteventdispatcher.cpp b/doc/src/snippets/code/src_corelib_kernel_qabstracteventdispatcher.cpp new file mode 100644 index 0000000..a531f22 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qabstracteventdispatcher.cpp @@ -0,0 +1,3 @@ +//! [0] +bool myEventFilter(void *message); +//! [0] diff --git a/doc/src/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp b/doc/src/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp new file mode 100644 index 0000000..31576d5 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qabstractitemmodel.cpp @@ -0,0 +1,28 @@ +//! [0] +beginInsertRows(parent, 2, 4); +//! [0] + + +//! [1] +beginInsertRows(parent, 4, 5); +//! [1] + + +//! [2] +beginRemoveRows(parent, 2, 3); +//! [2] + + +//! [3] +beginInsertColumns(parent, 4, 6); +//! [3] + + +//! [4] +beginInsertColumns(parent, 6, 8); +//! [4] + + +//! [5] +beginRemoveColumns(parent, 4, 6); +//! [5] diff --git a/doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp b/doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp new file mode 100644 index 0000000..748d894 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qcoreapplication.cpp @@ -0,0 +1,86 @@ +//! [0] +QMouseEvent event(QEvent::MouseButtonPress, pos, 0, 0, 0); +QApplication::sendEvent(mainWindow, &event); +//! [0] + + +//! [1] +QPushButton *quitButton = new QPushButton("Quit"); +connect(quitButton, SIGNAL(clicked()), &app, SLOT(quit())); +//! [1] + + +//! [2] +foreach (QString path, app.libraryPaths()) + do_something(path); +//! [2] + + +//! [3] +bool myEventFilter(void *message, long *result); +//! [3] + + +//! [4] +static int *global_ptr = 0; + +static void cleanup_ptr() +{ + delete [] global_ptr; + global_ptr = 0; +} + +void init_ptr() +{ + global_ptr = new int[100]; // allocate data + qAddPostRoutine(cleanup_ptr); // delete later +} +//! [4] + + +//! [5] +class MyPrivateInitStuff : public QObject +{ +public: + static MyPrivateInitStuff *initStuff(QObject *parent) + { + if (!p) + p = new MyPrivateInitStuff(parent); + return p; + } + + ~MyPrivateInitStuff() + { + // cleanup goes here + } + +private: + MyPrivateInitStuff(QObject *parent) + : QObject(parent) + { + // initialization goes here + } + + MyPrivateInitStuff *p; +}; +//! [5] + + +//! [6] +static inline QString tr(const char *sourceText, + const char *comment = 0); +static inline QString trUtf8(const char *sourceText, + const char *comment = 0); +//! [6] + + +//! [7] +class MyMfcView : public CView +{ + Q_DECLARE_TR_FUNCTIONS(MyMfcView) + +public: + MyMfcView(); + ... +}; +//! [7] diff --git a/doc/src/snippets/code/src_corelib_kernel_qmetaobject.cpp b/doc/src/snippets/code/src_corelib_kernel_qmetaobject.cpp new file mode 100644 index 0000000..ca18465 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qmetaobject.cpp @@ -0,0 +1,95 @@ + +void wrapInFunction() +{ + +//! [0] +class MyClass +{ + Q_OBJECT + Q_CLASSINFO("author", "Sabrina Schweinsteiger") + Q_CLASSINFO("url", "http://doc.moosesoft.co.uk/1.0/") + +public: + ... +}; +//! [0] + + +//! [1] +QByteArray normType = QMetaObject::normalizedType(" int const *"); +// normType is now "const int*" +//! [1] + + +//! [2] +QMetaObject::invokeMethod(pushButton, "animateClick", + Qt::QueuedConnection); +//! [2] + + +//! [3] +QMetaObject::invokeMethod: Unable to handle unregistered datatype 'MyType' +//! [3] + + +//! [4] +QString retVal; +QMetaObject::invokeMethod(obj, "compute", Qt::DirectConnection, + Q_RETURN_ARG(QString, retVal), + Q_ARG(QString, "sqrt"), + Q_ARG(int, 42), + Q_ARG(double, 9.7)); +//! [4] + + +//! [5] +class MyClass +{ + Q_OBJECT + Q_CLASSINFO("author", "Sabrina Schweinsteiger") + Q_CLASSINFO("url", "http://doc.moosesoft.co.uk/1.0/") + +public: + ... +}; +//! [5] + + +//! [propertyCount] +const QMetaObject* metaObject = obj->metaObject(); +QStringList properties; +for(int i = metaObject->propertyOffset(); i < metaObject->propertyCount(); ++i) + properties << QString::fromLatin1(metaObject->property(i).name()); +//! [propertyCount] + + +//! [methodCount] +const QMetaObject* metaObject = obj->metaObject(); +QStringList methods; +for(int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) + methods << QString::fromLatin1(metaObject->method(i).signature()); +//! [methodCount] + +//! [6] +int methodIndex = pushButton->metaObject()->indexForMethod("animateClick"); +QMetaMethod method = metaObject->method(methodIndex); +method.invoke(pushButton, Qt::QueuedConnection); +//! [6] + +//! [7] +QMetaMethod::invoke: Unable to handle unregistered datatype 'MyType' +//! [7] + +//! [8] +QString retVal; +int methodIndex = obj->metaObject()->indexForMethod("compute"); +QMetaMethod method = metaObject->method(methodIndex); +method.invoke(obj, + Qt::DirectConnection, + Q_RETURN_ARG(QString, retVal), + Q_ARG(QString, "sqrt"), + Q_ARG(int, 42), + Q_ARG(double, 9.7)); +//! [8] + +} diff --git a/doc/src/snippets/code/src_corelib_kernel_qmetatype.cpp b/doc/src/snippets/code/src_corelib_kernel_qmetatype.cpp new file mode 100644 index 0000000..355a237 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qmetatype.cpp @@ -0,0 +1,69 @@ +//! [0] +struct MyStruct +{ + int i; + ... +}; + +Q_DECLARE_METATYPE(MyStruct) +//! [0] + + +//! [1] +namespace MyNamespace +{ + ... +} + +Q_DECLARE_METATYPE(MyNamespace::MyStruct) +//! [1] + + +//! [2] +MyStruct s; +QVariant var; +var.setValue(s); // copy s into the variant + +... + +// retrieve the value +MyStruct s2 = var.value<MyStruct>(); +//! [2] + + +//! [3] +int id = QMetaType::type("MyClass"); +if (id != -1) { + void *myClassPtr = QMetaType::construct(id); + ... + QMetaType::destroy(id, myClassPtr); + myClassPtr = 0; +} +//! [3] + + +//! [4] +qRegisterMetaType<MyClass>("MyClass"); +//! [4] + + +//! [5] +qRegisterMetaTypeStreamOperators<MyClass>("MyClass"); +//! [5] + + +//! [6] +QDataStream &operator<<(QDataStream &out, const MyClass &myObj); +QDataStream &operator>>(QDataStream &in, MyClass &myObj); +//! [6] + + +//! [7] +int id = qRegisterMetaType<MyStruct>(); +//! [7] + + +//! [8] +int id = qMetaTypeId<QString>(); // id is now QMetaType::QString +id = qMetaTypeId<MyStruct>(); // compile error if MyStruct not declared +//! [8] diff --git a/doc/src/snippets/code/src_corelib_kernel_qmimedata.cpp b/doc/src/snippets/code/src_corelib_kernel_qmimedata.cpp new file mode 100644 index 0000000..94f1dc9 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qmimedata.cpp @@ -0,0 +1,68 @@ +//! [0] +void MyWidget::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->mimeData()->hasUrls()) + event->acceptProposedAction(); +} + +void MyWidget::dropEvent(QDropEvent *event) +{ + if (event->mimeData()->hasUrls()) { + foreach (QUrl url, event->mimeData()->urls()) { + ... + } + } +} +//! [0] + + +//! [1] +QByteArray csvData = ...; + +QMimeData *mimeData = new QMimeData; +mimeData->setData("text/csv", csvData); +//! [1] + + +//! [2] +void MyWidget::dropEvent(QDropEvent *event) +{ + const MyMimeData *myData = + qobject_cast<const MyMimeData *>(event->mimeData()); + if (myData) { + // access myData's data directly (not through QMimeData's API) + } +} +//! [2] + + +//! [3] +application/x-qt-windows-mime;value="<custom type>" +//! [3] + + +//! [4] +application/x-qt-windows-mime;value="FileGroupDescriptor" +application/x-qt-windows-mime;value="FileContents" +//! [4] + + +//! [5] +if (event->mimeData()->hasImage()) { + QImage image = qvariant_cast<QImage>(event->mimeData()->imageData()); + ... +} +//! [5] + + +//! [6] +mimeData->setImageData(QImage("beautifulfjord.png")); +//! [6] + + +//! [7] +if (event->mimeData()->hasColor()) { + QColor color = qvariant_cast<QColor>(event->mimeData()->colorData()); + ... +} +//! [7] diff --git a/doc/src/snippets/code/src_corelib_kernel_qobject.cpp b/doc/src/snippets/code/src_corelib_kernel_qobject.cpp new file mode 100644 index 0000000..5a7c5a7 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qobject.cpp @@ -0,0 +1,381 @@ +//! [0] +QLineEdit *lineEdit = static_cast<QLineEdit *>( + qt_find_obj_child(myWidget, "QLineEdit", "my line edit")); +if (lineEdit) + lineEdit->setText("Default"); +//! [0] + + +//! [1] +QObject *obj = new QPushButton; +obj->metaObject()->className(); // returns "QPushButton" + +QPushButton::staticMetaObject.className(); // returns "QPushButton" +//! [1] + + +//! [2] +QPushButton::staticMetaObject.className(); // returns "QPushButton" + +QObject *obj = new QPushButton; +obj->metaObject()->className(); // returns "QPushButton" +//! [2] + + +//! [3] +QObject *obj = new QTimer; // QTimer inherits QObject + +QTimer *timer = qobject_cast<QTimer *>(obj); +// timer == (QObject *)obj + +QAbstractButton *button = qobject_cast<QAbstractButton *>(obj); +// button == 0 +//! [3] + + +//! [4] +QTimer *timer = new QTimer; // QTimer inherits QObject +timer->inherits("QTimer"); // returns true +timer->inherits("QObject"); // returns true +timer->inherits("QAbstractButton"); // returns false + +// QLayout inherits QObject and QLayoutItem +QLayout *layout = new QLayout; +layout->inherits("QObject"); // returns true +layout->inherits("QLayoutItem"); // returns false +//! [4] + + +//! [5] +qDebug("MyClass::setPrecision(): (%s) invalid precision %f", + qPrintable(objectName()), newPrecision); +//! [5] + + +//! [6] +class MainWindow : public QMainWindow +{ +public: + MainWindow(); + +protected: + bool eventFilter(QObject *obj, QEvent *ev); + +private: + QTextEdit *textEdit; +}; + +MainWindow::MainWindow() +{ + textEdit = new QTextEdit; + setCentralWidget(textEdit); + + textEdit->installEventFilter(this); +} + +bool MainWindow::eventFilter(QObject *obj, QEvent *event) +{ + if (obj == textEdit) { + if (event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); + qDebug() << "Ate key press" << keyEvent->key(); + return true; + } else { + return false; + } + } else { + // pass the event on to the parent class + return QMainWindow::eventFilter(obj, event); + } +} +//! [6] + + +//! [7] +myObject->moveToThread(QApplication::instance()->thread()); +//! [7] + + +//! [8] +class MyObject : public QObject +{ + Q_OBJECT + +public: + MyObject(QObject *parent = 0); + +protected: + void timerEvent(QTimerEvent *event); +}; + +MyObject::MyObject(QObject *parent) + : QObject(parent) +{ + startTimer(50); // 50-millisecond timer + startTimer(1000); // 1-second timer + startTimer(60000); // 1-minute timer +} + +void MyObject::timerEvent(QTimerEvent *event) +{ + qDebug() << "Timer ID:" << event->timerId(); +} +//! [8] + + +//! [9] +QList<QObject *> list = window()->queryList("QAbstractButton")); +foreach (QObject *obj, list) + static_cast<QAbstractButton *>(obj)->setEnabled(false); +//! [9] + + +//! [10] +QPushButton *button = parentWidget->findChild<QPushButton *>("button1"); +//! [10] + + +//! [11] +QListWidget *list = parentWidget->findChild<QListWidget *>(); +//! [11] + + +//! [12] +QList<QWidget *> widgets = parentWidget.findChildren<QWidget *>("widgetname"); +//! [12] + + +//! [13] +QList<QPushButton *> allPButtons = parentWidget.findChildren<QPushButton *>(); +//! [13] + + +//! [14] +monitoredObj->installEventFilter(filterObj); +//! [14] + + +//! [15] +class KeyPressEater : public QObject +{ + Q_OBJECT + ... + +protected: + bool eventFilter(QObject *obj, QEvent *event); +}; + +bool KeyPressEater::eventFilter(QObject *obj, QEvent *event) +{ + if (event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); + qDebug("Ate key press %d", keyEvent->key()); + return true; + } else { + // standard event processing + return QObject::eventFilter(obj, event); + } +} +//! [15] + + +//! [16] +KeyPressEater *keyPressEater = new KeyPressEater(this); +QPushButton *pushButton = new QPushButton(this); +QListView *listView = new QListView(this); + +pushButton->installEventFilter(keyPressEater); +listView->installEventFilter(keyPressEater); +//! [16] + + +//! [17] +MyWindow::MyWindow() +{ + QLabel *senderLabel = new QLabel(tr("Name:")); + QLabel *recipientLabel = new QLabel(tr("Name:", "recipient")); + ... +} +//! [17] + + +//! [18] +int n = messages.count(); +showMessage(tr("%n message(s) saved", "", n)); +//! [18] + + +//! [19] +n == 1 ? tr("%n message saved") : tr("%n messages saved") +//! [19] + + +//! [20] +label->setText(tr("F\374r \310lise")); +//! [20] + + +//! [21] +if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) { + QByteArray data; + get_the_value(&data); // expensive operation + emit valueChanged(data); +} +//! [21] + + +//! [22] +QLabel *label = new QLabel; +QScrollBar *scrollBar = new QScrollBar; +QObject::connect(scrollBar, SIGNAL(valueChanged(int)), + label, SLOT(setNum(int))); +//! [22] + + +//! [23] +// WRONG +QObject::connect(scrollBar, SIGNAL(valueChanged(int value)), + label, SLOT(setNum(int value))); +//! [23] + + +//! [24] +class MyWidget : public QWidget +{ + Q_OBJECT + +public: + MyWidget(); + +signals: + void buttonClicked(); + +private: + QPushButton *myButton; +}; + +MyWidget::MyWidget() +{ + myButton = new QPushButton(this); + connect(myButton, SIGNAL(clicked()), + this, SIGNAL(buttonClicked())); +} +//! [24] + + +//! [25] +QObject::connect: Cannot queue arguments of type 'MyType' +(Make sure 'MyType' is registered using qRegisterMetaType().) +//! [25] + + +//! [26] +disconnect(myObject, 0, 0, 0); +//! [26] + + +//! [27] +myObject->disconnect(); +//! [27] + + +//! [28] +disconnect(myObject, SIGNAL(mySignal()), 0, 0); +//! [28] + + +//! [29] +myObject->disconnect(SIGNAL(mySignal())); +//! [29] + + +//! [30] +disconnect(myObject, 0, myReceiver, 0); +//! [30] + + +//! [31] +myObject->disconnect(myReceiver); +//! [31] + + +//! [32] +if (QLatin1String(signal) == SIGNAL(valueChanged(int))) { + // signal is valueChanged(int) +} +//! [32] + + +//! [33] +void on_<object name>_<signal name>(<signal parameters>); +//! [33] + + +//! [34] +void on_button1_clicked(); +//! [34] + + +//! [35] +class MyClass : public QObject +{ + Q_OBJECT + Q_CLASSINFO("Author", "Pierre Gendron") + Q_CLASSINFO("URL", "http://www.my-organization.qc.ca") + +public: + ... +}; +//! [35] + + +//! [36] +Q_PROPERTY(type name + READ getFunction + [WRITE setFunction] + [RESET resetFunction] + [DESIGNABLE bool] + [SCRIPTABLE bool] + [STORED bool] + [USER bool]) +//! [36] + + +//! [37] +Q_PROPERTY(QString title READ title WRITE setTitle USER true) +//! [37] + + +//! [38] +class MyClass : public QObject +{ + Q_OBJECT + Q_ENUMS(Priority) + +public: + MyClass(QObject *parent = 0); + ~MyClass(); + + enum Priority { High, Low, VeryHigh, VeryLow }; + void setPriority(Priority priority); + Priority priority() const; +}; +//! [38] + + +//! [39] +Q_FLAGS(Options Alignment) +//! [39] + + +//! [40] +//: This name refers to a host name. +hostNameLabel->setText(tr("Name:")); + +/*: This text refers to a C++ code example. */ +QString example = tr("Example"); +//! [40] + +//! [explicit tr context] +QString text = QScrollBar::tr("Page up"); +//! [explicit tr context] diff --git a/doc/src/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp b/doc/src/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp new file mode 100644 index 0000000..cd5665f --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qsystemsemaphore.cpp @@ -0,0 +1,21 @@ +//! [0] +QSystemSemaphore sem("market", 3, QSystemSemaphore::Create); + // resources available == 3 +sem.acquire(); // resources available == 2 +sem.acquire(); // resources available == 1 +sem.acquire(); // resources available == 0 +sem.release(); // resources available == 1 +sem.release(2); // resources available == 3 +//! [0] + + +//! [1] +QSystemSemaphore sem("market", 5, QSystemSemaphore::Create); +sem.acquire(5); // acquire all 5 resources +sem.release(5); // release the 5 resources +//! [1] + + +//! [2] +sem.release(10); // "create" 10 new resources +//! [2] diff --git a/doc/src/snippets/code/src_corelib_kernel_qtimer.cpp b/doc/src/snippets/code/src_corelib_kernel_qtimer.cpp new file mode 100644 index 0000000..02cdc0a --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qtimer.cpp @@ -0,0 +1,12 @@ +//! [0] +#include <QApplication> +#include <QTimer> + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QTimer::singleShot(600000, &app, SLOT(quit())); + ... + return app.exec(); +} +//! [0] diff --git a/doc/src/snippets/code/src_corelib_kernel_qvariant.cpp b/doc/src/snippets/code/src_corelib_kernel_qvariant.cpp new file mode 100644 index 0000000..ef19dbb --- /dev/null +++ b/doc/src/snippets/code/src_corelib_kernel_qvariant.cpp @@ -0,0 +1,97 @@ +//! [0] +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 QByteArray +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 = v.toInt() + 100; // The variant now hold the value 223 +v = QVariant(QStringList()); +//! [0] + + +//! [1] +QVariant x, y(QString()), z(QString("")); +x.convert(QVariant::Int); +// x.isNull() == true +// y.isNull() == true, z.isNull() == false +// y.isEmpty() == true, z.isEmpty() == true +//! [1] + + +//! [2] +QVariant variant; +... +QColor color = variant.value<QColor>(); +//! [2] + + +//! [3] +QColor color = palette().background().color(); +QVariant variant = color; +//! [3] + + +//! [4] +QVariant v; + +v.setValue(5); +int i = v.toInt(); // i is now 5 +QString s = v.toString() // s is now "5" + +MyCustomStruct c; +v.setValue(c); + +... + +MyCustomStruct c2 = v.value<MyCustomStruct>(); +//! [4] + + +//! [5] +QVariant v; + +MyCustomStruct c; +if (v.canConvert<MyCustomStruct>()) + c = v.value<MyCustomStruct>(v); + +v = 7; +int i = v.value<int>(); // same as v.toInt() +QString s = v.value<QString>(); // same as v.toString(), s is now "7" +MyCustomStruct c2 = v.value<MyCustomStruct>(); // conversion failed, c2 is empty +//! [5] + + +//! [6] +QVariant v = 42; + +v.canConvert<int>(); // returns true +v.canConvert<QString>(); // returns true + +MyCustomStruct s; +v.setValue(s); + +v.canConvert<int>(); // returns false +v.canConvert<MyCustomStruct>(); // returns true +//! [6] + + +//! [7] +MyCustomStruct s; +return QVariant::fromValue(s); +//! [7] + + +//! [8] +QObject *object = getObjectFromSomewhere(); +QVariant data = qVariantFromValue(object); +//! [8] diff --git a/doc/src/snippets/code/src_corelib_plugin_qlibrary.cpp b/doc/src/snippets/code/src_corelib_plugin_qlibrary.cpp new file mode 100644 index 0000000..0659061 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_plugin_qlibrary.cpp @@ -0,0 +1,44 @@ +//! [0] +QLibrary myLib("mylib"); +typedef void (*MyPrototype)(); +MyPrototype myFunction = (MyPrototype) myLib.resolve("mysymbol"); +if (myFunction) + myFunction(); +//! [0] + + +//! [1] +typedef void (*MyPrototype)(); +MyPrototype myFunction = + (MyPrototype) QLibrary::resolve("mylib", "mysymbol"); +if (myFunction) + myFunction(); +//! [1] + + +//! [2] +typedef int (*AvgFunction)(int, int); + +AvgFunction avg = (AvgFunction) library->resolve("avg"); +if (avg) + return avg(5, 8); +else + return -1; +//! [2] + + +//! [3] +extern "C" MY_EXPORT int avg(int a, int b) +{ + return (a + b) / 2; +} +//! [3] + + +//! [4] +#ifdef Q_WS_WIN +#define MY_EXPORT __declspec(dllexport) +#else +#define MY_EXPORT +#endif +//! [4] diff --git a/doc/src/snippets/code/src_corelib_plugin_quuid.cpp b/doc/src/snippets/code/src_corelib_plugin_quuid.cpp new file mode 100644 index 0000000..5c91afc --- /dev/null +++ b/doc/src/snippets/code/src_corelib_plugin_quuid.cpp @@ -0,0 +1,4 @@ +//! [0] +// {67C8770B-44F1-410A-AB9A-F9B5446F13EE} +QUuid IID_MyInterface(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee) +//! [0] diff --git a/doc/src/snippets/code/src_corelib_thread_qatomic.cpp b/doc/src/snippets/code/src_corelib_thread_qatomic.cpp new file mode 100644 index 0000000..3f67ddf --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qatomic.cpp @@ -0,0 +1,58 @@ +//! [0] +MySharedType &MySharedType::operator=(const MySharedType &other) +{ + (void) other.data->atomicInt.ref(); + if (!data->atomicInt.deref()) { + // The last reference has been released + delete d; + } + d = other.d; + return *this; +} +//! [0] + + +//! [1] +if (currentValue == expectedValue) { + currentValue = newValue; + return true; +} +return false; +//! [1] + + +//! [2] +int originalValue = currentValue; +currentValue = newValue; +return originalValue; +//! [2] + + +//! [3] +int originalValue = currentValue; +currentValue += valueToAdd; +return originalValue; +//! [3] + + +//! [4] +if (currentValue == expectedValue) { + currentValue = newValue; + return true; +} +return false; +//! [4] + + +//! [5] +T *originalValue = currentValue; +currentValue = newValue; +return originalValue; +//! [5] + + +//! [6] +T *originalValue = currentValue; +currentValue += valueToAdd; +return originalValue; +//! [6] diff --git a/doc/src/snippets/code/src_corelib_thread_qmutex.cpp b/doc/src/snippets/code/src_corelib_thread_qmutex.cpp new file mode 100644 index 0000000..e79bb35 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qmutex.cpp @@ -0,0 +1,153 @@ +//! [0] +int number = 6; + +void method1() +{ + number *= 5; + number /= 4; +} + +void method2() +{ + number *= 3; + number /= 2; +} +//! [0] + + +//! [1] +// method1() +number *= 5; // number is now 30 +number /= 4; // number is now 7 + +// method2() +number *= 3; // number is now 21 +number /= 2; // number is now 10 +//! [1] + + +//! [2] +// Thread 1 calls method1() +number *= 5; // number is now 30 + +// Thread 2 calls method2(). +// +// Most likely Thread 1 has been put to sleep by the operating +// system to allow Thread 2 to run. +number *= 3; // number is now 90 +number /= 2; // number is now 45 + +// Thread 1 finishes executing. +number /= 4; // number is now 11, instead of 10 +//! [2] + + +//! [3] +QMutex mutex; +int number = 6; + +void method1() +{ + mutex.lock(); + number *= 5; + number /= 4; + mutex.unlock(); +} + +void method2() +{ + mutex.lock(); + number *= 3; + number /= 2; + mutex.unlock(); +} +//! [3] + + +//! [4] +int complexFunction(int flag) +{ + mutex.lock(); + + int retVal = 0; + + switch (flag) { + case 0: + case 1: + mutex.unlock(); + return moreComplexFunction(flag); + case 2: + { + int status = anotherFunction(); + if (status < 0) { + mutex.unlock(); + return -2; + } + retVal = status + flag; + } + break; + default: + if (flag > 10) { + mutex.unlock(); + return -1; + } + break; + } + + mutex.unlock(); + return retVal; +} +//! [4] + + +//! [5] +int complexFunction(int flag) +{ + QMutexLocker locker(&mutex); + + int retVal = 0; + + switch (flag) { + case 0: + case 1: + return moreComplexFunction(flag); + case 2: + { + int status = anotherFunction(); + if (status < 0) + return -2; + retVal = status + flag; + } + break; + default: + if (flag > 10) + return -1; + break; + } + + return retVal; +} +//! [5] + + +//! [6] +class SignalWaiter +{ +private: + QMutexLocker locker; + +public: + SignalWaiter(QMutex *mutex) + : locker(mutex) + { + } + + void waitForSignal() + { + ... + while (!signalled) + waitCondition.wait(locker.mutex()); + ... + } +}; +//! [6] diff --git a/doc/src/snippets/code/src_corelib_thread_qmutexpool.cpp b/doc/src/snippets/code/src_corelib_thread_qmutexpool.cpp new file mode 100644 index 0000000..8e64a36 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qmutexpool.cpp @@ -0,0 +1,21 @@ +//! [0] +class Number { +public: + Number(double n) : num (n) { } + + void setNumber(double n) { num = n; } + double number() const { return num; } + +private: + double num; +}; +//! [0] + + +//! [1] +void calcSquare(Number *num) +{ + QMutexLocker locker(mutexpool.get(num)); + num.setNumber(num.number() * num.number()); +} +//! [1] diff --git a/doc/src/snippets/code/src_corelib_thread_qreadwritelock.cpp b/doc/src/snippets/code/src_corelib_thread_qreadwritelock.cpp new file mode 100644 index 0000000..f0f4935 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qreadwritelock.cpp @@ -0,0 +1,69 @@ +//! [0] +QReadWriteLock lock; + +void ReaderThread::run() +{ + ... + lock.lockForRead(); + read_file(); + lock.unlock(); + ... +} + +void WriterThread::run() +{ + ... + lock.lockForWrite(); + write_file(); + lock.unlock(); + ... +} +//! [0] + + +//! [1] +QReadWriteLock lock; + +QByteArray readData() +{ + QReadLocker locker(&lock); + ... + return data; +} +//! [1] + + +//! [2] +QReadWriteLock lock; + +QByteArray readData() +{ + locker.lockForRead(); + ... + locker.unlock(); + return data; +} +//! [2] + + +//! [3] +QReadWriteLock lock; + +void writeData(const QByteArray &data) +{ + QWriteLocker locker(&lock); + ... +} +//! [3] + + +//! [4] +QReadWriteLock lock; + +void writeData(const QByteArray &data) +{ + locker.lockForWrite(); + ... + locker.unlock(); +} +//! [4] diff --git a/doc/src/snippets/code/src_corelib_thread_qsemaphore.cpp b/doc/src/snippets/code/src_corelib_thread_qsemaphore.cpp new file mode 100644 index 0000000..e02f05e --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qsemaphore.cpp @@ -0,0 +1,33 @@ +//! [0] +QSemaphore sem(5); // sem.available() == 5 + +sem.acquire(3); // sem.available() == 2 +sem.acquire(2); // sem.available() == 0 +sem.release(5); // sem.available() == 5 +sem.release(5); // sem.available() == 10 + +sem.tryAcquire(1); // sem.available() == 9, returns true +sem.tryAcquire(250); // sem.available() == 9, returns false +//! [0] + + +//! [1] +QSemaphore sem(5); // a semaphore that guards 5 resources +sem.acquire(5); // acquire all 5 resources +sem.release(5); // release the 5 resources +sem.release(10); // "create" 10 new resources +//! [1] + + +//! [2] +QSemaphore sem(5); // sem.available() == 5 +sem.tryAcquire(250); // sem.available() == 5, returns false +sem.tryAcquire(3); // sem.available() == 2, returns true +//! [2] + + +//! [3] +QSemaphore sem(5); // sem.available() == 5 +sem.tryAcquire(250, 1000); // sem.available() == 5, waits 1000 milliseconds and returns false +sem.tryAcquire(3, 30000); // sem.available() == 2, returns true without waiting +//! [3] diff --git a/doc/src/snippets/code/src_corelib_thread_qthread.cpp b/doc/src/snippets/code/src_corelib_thread_qthread.cpp new file mode 100644 index 0000000..58c35e5 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qthread.cpp @@ -0,0 +1,16 @@ +//! [0] +class MyThread : public QThread +{ +public: + void run(); +}; + +void MyThread::run() +{ + QTcpSocket socket; + // connect QTcpSocket's signals somewhere meaningful + ... + socket.connectToHost(hostName, portNumber); + exec(); +} +//! [0] diff --git a/doc/src/snippets/code/src_corelib_thread_qwaitcondition_unix.cpp b/doc/src/snippets/code/src_corelib_thread_qwaitcondition_unix.cpp new file mode 100644 index 0000000..5c83d97 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_thread_qwaitcondition_unix.cpp @@ -0,0 +1,49 @@ +//! [0] +forever { + mutex.lock(); + keyPressed.wait(&mutex); + do_something(); + mutex.unlock(); +} +//! [0] + + +//! [1] +forever { + getchar(); + keyPressed.wakeAll(); +} +//! [1] + + +//! [2] +forever { + mutex.lock(); + keyPressed.wait(&mutex); + ++count; + mutex.unlock(); + + do_something(); + + mutex.lock(); + --count; + mutex.unlock(); +} +//! [2] + + +//! [3] +forever { + getchar(); + + mutex.lock(); + // Sleep until there are no busy worker threads + while (count > 0) { + mutex.unlock(); + sleep(1); + mutex.lock(); + } + keyPressed.wakeAll(); + mutex.unlock(); +} +//! [3] diff --git a/doc/src/snippets/code/src_corelib_tools_qbitarray.cpp b/doc/src/snippets/code/src_corelib_tools_qbitarray.cpp new file mode 100644 index 0000000..e931d40 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qbitarray.cpp @@ -0,0 +1,136 @@ +//! [0] +QBitArray ba(200); +//! [0] + + +//! [1] +QBitArray ba; +ba.resize(3); +ba[0] = true; +ba[1] = false; +ba[2] = true; +//! [1] + + +//! [2] +QBitArray ba(3); +ba.setBit(0, true); +ba.setBit(1, false); +ba.setBit(2, true); +//! [2] + + +//! [3] +QBitArray x(5); +x.setBit(3, true); +// x: [ 0, 0, 0, 1, 0 ] + +QBitArray y(5); +y.setBit(4, true); +// y: [ 0, 0, 0, 0, 1 ] + +x |= y; +// x: [ 0, 0, 0, 1, 1 ] +//! [3] + + +//! [4] +QBitArray().isNull(); // returns true +QBitArray().isEmpty(); // returns true + +QBitArray(0).isNull(); // returns false +QBitArray(0).isEmpty(); // returns true + +QBitArray(3).isNull(); // returns false +QBitArray(3).isEmpty(); // returns false +//! [4] + + +//! [5] +QBitArray().isNull(); // returns true +QBitArray(0).isNull(); // returns false +QBitArray(3).isNull(); // returns false +//! [5] + + +//! [6] +QBitArray ba(8); +ba.fill(true); +// ba: [ 1, 1, 1, 1, 1, 1, 1, 1 ] + +ba.fill(false, 2); +// ba: [ 0, 0 ] +//! [6] + + +//! [7] +QBitArray a(3); +a[0] = false; +a[1] = true; +a[2] = a[0] ^ a[1]; +//! [7] + + +//! [8] +QBitArray a(3); +QBitArray b(2); +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +a &= b; // a: [ 1, 0, 0 ] +//! [8] + + +//! [9] +QBitArray a(3); +QBitArray b(2); +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +a |= b; // a: [ 1, 1, 1 ] +//! [9] + + +//! [10] +QBitArray a(3); +QBitArray b(2); +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +a ^= b; // a: [ 0, 1, 1 ] +//! [10] + + +//! [11] +QBitArray a(3); +QBitArray b; +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b = ~a; // b: [ 0, 1, 0 ] +//! [11] + + +//! [12] +QBitArray a(3); +QBitArray b(2); +QBitArray c; +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +c = a & b; // c: [ 1, 0, 0 ] +//! [12] + + +//! [13] +QBitArray a(3); +QBitArray b(2); +QBitArray c; +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +c = a | b; // c: [ 1, 1, 1 ] +//! [13] + + +//! [14] +QBitArray a(3); +QBitArray b(2); +QBitArray c; +a[0] = 1; a[1] = 0; a[2] = 1; // a: [ 1, 0, 1 ] +b[0] = 1; b[1] = 0; // b: [ 1, 1 ] +c = a ^ b; // c: [ 0, 1, 1 ] +//! [14] diff --git a/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp b/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp new file mode 100644 index 0000000..3c5b413 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qbytearray.cpp @@ -0,0 +1,364 @@ + +void wrapInFunction() +{ + +//! [0] +QByteArray ba("Hello"); +//! [0] + + +//! [1] +QByteArray ba; +ba.resize(5); +ba[0] = 0x3c; +ba[1] = 0xb8; +ba[2] = 0x64; +ba[3] = 0x18; +ba[4] = 0xca; +//! [1] + + +//! [2] +for (int i = 0; i < ba.size(); ++i) { + if (ba.at(i) >= 'a' && ba.at(i) <= 'f') + cout << "Found character in range [a-f]" << endl; +} +//! [2] + + +//! [3] +QByteArray x("and"); +x.prepend("rock "); // x == "rock and" +x.append(" roll"); // x == "rock and roll" +x.replace(5, 3, "&"); // x == "rock & roll" +//! [3] + + +//! [4] +QByteArray ba("We must be <b>bold</b>, very <b>bold</b>"); +int j = 0; +while ((j = ba.indexOf("<b>", j)) != -1) { + cout << "Found <b> tag at index position " << j << endl; + ++j; +} +//! [4] + + +//! [5] +QByteArray().isNull(); // returns true +QByteArray().isEmpty(); // returns true + +QByteArray("").isNull(); // returns false +QByteArray("").isEmpty(); // returns true + +QByteArray("abc").isNull(); // returns false +QByteArray("abc").isEmpty(); // returns false +//! [5] + + +//! [6] +QByteArray ba("Hello"); +int n = ba.size(); // n == 5 +ba.data()[0]; // returns 'H' +ba.data()[4]; // returns 'o' +ba.data()[5]; // returns '\0' +//! [6] + + +//! [7] +QByteArray().isEmpty(); // returns true +QByteArray("").isEmpty(); // returns true +QByteArray("abc").isEmpty(); // returns false +//! [7] + + +//! [8] +QByteArray ba("Hello world"); +char *data = ba.data(); +while (*data) { + cout << "[" << *data << "]" << endl; + ++data; +} +//! [8] + + +//! [9] +QByteArray ba; +for (int i = 0; i < 10; ++i) + ba[i] = 'A' + i; +// ba == "ABCDEFGHIJ" +//! [9] + + +//! [10] +QByteArray ba("Stockholm"); +ba.truncate(5); // ba == "Stock" +//! [10] + + +//! [11] +QByteArray ba("STARTTLS\r\n"); +ba.chop(2); // ba == "STARTTLS" +//! [11] + + +//! [12] +QByteArray x("free"); +QByteArray y("dom"); +x += y; +// x == "freedom" +//! [12] + + +//! [13] +QByteArray().isNull(); // returns true +QByteArray("").isNull(); // returns false +QByteArray("abc").isNull(); // returns false +//! [13] + + +//! [14] +QByteArray ba("Istambul"); +ba.fill('o'); +// ba == "oooooooo" + +ba.fill('X', 2); +// ba == "XX" +//! [14] + + +//! [15] +QByteArray x("ship"); +QByteArray y("air"); +x.prepend(y); +// x == "airship" +//! [15] + + +//! [16] +QByteArray x("free"); +QByteArray y("dom"); +x.append(y); +// x == "freedom" +//! [16] + + +//! [17] +QByteArray ba("Meal"); +ba.insert(1, QByteArray("ontr")); +// ba == "Montreal" +//! [17] + + +//! [18] +QByteArray ba("Montreal"); +ba.remove(1, 4); +// ba == "Meal" +//! [18] + + +//! [19] +QByteArray x("Say yes!"); +QByteArray y("no"); +x.replace(4, 3, y); +// x == "Say no!" +//! [19] + + +//! [20] +QByteArray ba("colour behaviour flavour neighbour"); +ba.replace(QByteArray("ou"), QByteArray("o")); +// ba == "color behavior flavor neighbor" +//! [20] + + +//! [21] +QByteArray x("sticky question"); +QByteArray y("sti"); +x.indexOf(y); // returns 0 +x.indexOf(y, 1); // returns 10 +x.indexOf(y, 10); // returns 10 +x.indexOf(y, 11); // returns -1 +//! [21] + + +//! [22] +QByteArray ba("ABCBA"); +ba.indexOf("B"); // returns 1 +ba.indexOf("B", 1); // returns 1 +ba.indexOf("B", 2); // returns 3 +ba.indexOf("X"); // returns -1 +//! [22] + + +//! [23] +QByteArray x("crazy azimuths"); +QByteArray y("azy"); +x.lastIndexOf(y); // returns 6 +x.lastIndexOf(y, 6); // returns 6 +x.lastIndexOf(y, 5); // returns 2 +x.lastIndexOf(y, 1); // returns -1 +//! [23] + + +//! [24] +QByteArray ba("ABCBA"); +ba.lastIndexOf("B"); // returns 3 +ba.lastIndexOf("B", 3); // returns 3 +ba.lastIndexOf("B", 2); // returns 1 +ba.lastIndexOf("X"); // returns -1 +//! [24] + + +//! [25] +QByteArray url("ftp://ftp.trolltech.com/"); +if (url.startsWith("ftp:")) + ... +//! [25] + + +//! [26] +QByteArray url("http://qtsoftware.com/index.html"); +if (url.endsWith(".html")) + ... +//! [26] + + +//! [27] +QByteArray x("Pineapple"); +QByteArray y = x.left(4); +// y == "Pine" +//! [27] + + +//! [28] +QByteArray x("Pineapple"); +QByteArray y = x.right(5); +// y == "apple" +//! [28] + + +//! [29] +QByteArray x("Five pineapples"); +QByteArray y = x.mid(5, 4); // y == "pine" +QByteArray z = x.mid(5); // z == "pineapples" +//! [29] + + +//! [30] +QByteArray x("TROlltECH"); +QByteArray y = x.toLower(); +// y == "trolltech" +//! [30] + + +//! [31] +QByteArray x("TROlltECH"); +QByteArray y = x.toUpper(); +// y == "TROLLTECH" +//! [31] + + +//! [32] +QByteArray ba(" lots\t of\nwhitespace\r\n "); +ba = ba.simplified(); +// ba == "lots of whitespace"; +//! [32] + + +//! [33] +QByteArray ba(" lots\t of\nwhitespace\r\n "); +ba = ba.trimmed(); +// ba == "lots\t of\nwhitespace"; +//! [33] + + +//! [34] +QByteArray x("apple"); +QByteArray y = x.leftJustified(8, '.'); // y == "apple..." +//! [34] + + +//! [35] +QByteArray x("apple"); +QByteArray y = x.rightJustified(8, '.'); // y == "...apple" +//! [35] + + +//! [36] +QByteArray str("FF"); +bool ok; +int hex = str.toInt(&ok, 16); // hex == 255, ok == true +int dec = str.toInt(&ok, 10); // dec == 0, ok == false +//! [36] + + +//! [37] +QByteArray str("FF"); +bool ok; +long hex = str.toLong(&ok, 16); // hex == 255, ok == true +long dec = str.toLong(&ok, 10); // dec == 0, ok == false +//! [37] + + +//! [38] +QByteArray string("1234.56"); +double a = string.toDouble(); // a == 1234.56 +//! [38] + + +//! [39] +QByteArray text("Qt is great!"); +text.toBase64(); // returns "UXQgaXMgZ3JlYXQh" +//! [39] + + +//! [40] +QByteArray ba; +int n = 63; +ba.setNum(n); // ba == "63" +ba.setNum(n, 16); // ba == "3f" +//! [40] + + +//! [41] +int n = 63; +QByteArray::number(n); // returns "63" +QByteArray::number(n, 16); // returns "3f" +QByteArray::number(n, 16).toUpper(); // returns "3F" +//! [41] + + +//! [42] +QByteArray ba = QByteArray::number(12.3456, 'E', 3); +// ba == 1.235E+01 +//! [42] + + +//! [43] + static const char mydata[] = { + 0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76, + 0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99, + ... + 0x6d, 0x5b +}; + +QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata)); +QDataStream in(&data, QIODevice::ReadOnly); +... +//! [43] + + +//! [44] +QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh"); +text.data(); // returns "Qt is great!" +//! [44] + + +//! [45] +QByteArray text = QByteArray::fromHex("517420697320677265617421"); +text.data(); // returns "Qt is great!" +//! [45] + +} + diff --git a/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp b/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp new file mode 100644 index 0000000..a1424f4 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qdatetime.cpp @@ -0,0 +1,106 @@ +//! [0] +QDate d1(1995, 5, 17); // May 17, 1995 +QDate d2(1995, 5, 20); // May 20, 1995 +d1.daysTo(d2); // returns 3 +d2.daysTo(d1); // returns -3 +//! [0] + + +//! [1] +QDate date = QDate::fromString("1MM12car2003", "d'MM'MMcaryyyy"); +// date is 1 December 2003 +//! [1] + + +//! [2] +QDate date = QDate::fromString("130", "Md"); // invalid +//! [2] + + +//! [3] +QDate::fromString("1.30", "M.d"); // January 30 1900 +QDate::fromString("20000110", "yyyyMMdd"); // January 10, 2000 +QDate::fromString("20000110", "yyyyMd"); // January 10, 2000 +//! [3] + + +//! [4] +QDate::isValid(2002, 5, 17); // true +QDate::isValid(2002, 2, 30); // false (Feb 30 does not exist) +QDate::isValid(2004, 2, 29); // true (2004 is a leap year) +QDate::isValid(2000, 2, 29); // true (2000 is a leap year) +QDate::isValid(2006, 2, 29); // false (2006 is not a leap year) +QDate::isValid(2100, 2, 29); // false (2100 is not a leap year) +QDate::isValid(1202, 6, 6); // true (even though 1202 is pre-Gregorian) +//! [4] + + +//! [5] +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 +//! [5] + + +//! [6] +QTime time = QTime::fromString("1mm12car00", "m'mm'hcarss"); +// time is 12:01.00 +//! [6] + + +//! [7] +QTime time = QTime::fromString("00:710", "hh:ms"); // invalid +//! [7] + + +//! [8] +QTime time = QTime::fromString("1.30", "m.s"); +// time is 00:01:30.000 +//! [8] + + +//! [9] +QTime::isValid(21, 10, 30); // returns true +QTime::isValid(22, 5, 62); // returns false +//! [9] + + +//! [10] +QTime t; +t.start(); +some_lengthy_task(); +qDebug("Time elapsed: %d ms", t.elapsed()); +//! [10] + + +//! [11] +QDateTime now = QDateTime::currentDateTime(); +QDateTime xmas(QDate(now.date().year(), 12, 25), QTime(0, 0)); +qDebug("There are %d seconds to Christmas", now.secsTo(xmas)); +//! [11] + + +//! [12] +QTime time1 = QTime::fromString("131", "HHh"); +// time1 is 13:00:00 +QTime time1 = QTime::fromString("1apA", "1amAM"); +// time1 is 01:00:00 + +QDateTime dateTime2 = QDateTime::fromString("M1d1y9800:01:02", + "'M'M'd'd'y'yyhh:mm:ss"); +// dateTime is 1 January 1998 00:01:02 +//! [12] + + +//! [13] +QDateTime dateTime = QDateTime::fromString("130", "Mm"); // invalid +//! [13] + + +//! [14] +QDateTime dateTime = QDateTime::fromString("1.30.1", "M.d.s"); +// dateTime is January 30 in 1900 at 00:00:01. +//! [14] diff --git a/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp b/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp new file mode 100644 index 0000000..65358ea --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp @@ -0,0 +1,4 @@ +//! [0] +qreal myEasingFunction(qreal progress); +//! [0] + diff --git a/doc/src/snippets/code/src_corelib_tools_qhash.cpp b/doc/src/snippets/code/src_corelib_tools_qhash.cpp new file mode 100644 index 0000000..05f6eb3 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qhash.cpp @@ -0,0 +1,259 @@ +//! [0] +QHash<QString, int> hash; +//! [0] + + +//! [1] +hash["one"] = 1; +hash["three"] = 3; +hash["seven"] = 7; +//! [1] + + +//! [2] +hash.insert("twelve", 12); +//! [2] + + +//! [3] +int num1 = hash["thirteen"]; +int num2 = hash.value("thirteen"); +//! [3] + + +//! [4] +int timeout = 30; +if (hash.contains("TIMEOUT")) + timeout = hash.value("TIMEOUT"); +//! [4] + + +//! [5] +int timeout = hash.value("TIMEOUT", 30); +//! [5] + + +//! [6] +// WRONG +QHash<int, QWidget *> hash; +... +for (int i = 0; i < 1000; ++i) { + if (hash[i] == okButton) + cout << "Found button at index " << i << endl; +} +//! [6] + + +//! [7] +QHashIterator<QString, int> i(hash); +while (i.hasNext()) { + i.next(); + cout << i.key() << ": " << i.value() << endl; +} +//! [7] + + +//! [8] +QHash<QString, int>::const_iterator i = hash.constBegin(); +while (i != hash.constEnd()) { + cout << i.key() << ": " << i.value() << endl; + ++i; +} +//! [8] + + +//! [9] +hash.insert("plenty", 100); +hash.insert("plenty", 2000); +// hash.value("plenty") == 2000 +//! [9] + + +//! [10] +QList<int> values = hash.values("plenty"); +for (int i = 0; i < values.size(); ++i) + cout << values.at(i) << endl; +//! [10] + + +//! [11] +QHash<QString, int>::iterator i = hash.find("plenty"); +while (i != hash.end() && i.key() == "plenty") { + cout << i.value() << endl; + ++i; +} +//! [11] + + +//! [12] +QHash<QString, int> hash; +... +foreach (int value, hash) + cout << value << endl; +//! [12] + + +//! [13] +#ifndef EMPLOYEE_H +#define EMPLOYEE_H + +class Employee +{ +public: + Employee() {} + Employee(const QString &name, const QDate &dateOfBirth); + ... + +private: + QString myName; + QDate myDateOfBirth; +}; + +inline bool operator==(const Employee &e1, const Employee &e2) +{ + return e1.name() == e2.name() + && e1.dateOfBirth() == e2.dateOfBirth(); +} + +inline uint qHash(const Employee &key) +{ + return qHash(key.name()) ^ key.dateOfBirth().day(); +} + +#endif // EMPLOYEE_H +//! [13] + + +//! [14] +QHash<QString, int> hash; +hash.reserve(20000); +for (int i = 0; i < 20000; ++i) + hash.insert(keys[i], values[i]); +//! [14] + + +//! [15] +QHash<QObject *, int> objectHash; +... +QHash<QObject *, int>::iterator i = objectHash.find(obj); +while (i != objectHash.end() && i.key() == obj) { + if (i.value() == 0) { + i = objectHash.erase(i); + } else { + ++i; + } +} +//! [15] + + +//! [16] +QHash<QString, int> hash; +... +QHash<QString, int>::const_iterator i = hash.find("HDR"); +while (i != hash.end() && i.key() == "HDR") { + cout << i.value() << endl; + ++i; +} +//! [16] + + +//! [17] +QHash<QString, int> hash; +hash.insert("January", 1); +hash.insert("February", 2); +... +hash.insert("December", 12); + +QHash<QString, int>::iterator i; +for (i = hash.begin(); i != hash.end(); ++i) + cout << i.key() << ": " << i.value() << endl; +//! [17] + + +//! [18] +QHash<QString, int>::iterator i; +for (i = hash.begin(); i != hash.end(); ++i) + i.value() += 2; +//! [18] + + +//! [19] +QHash<QString, int>::iterator i = hash.begin(); +while (i != hash.end()) { + if (i.key().startsWith("_")) + i = hash.erase(i); + else + ++i; +} +//! [19] + + +//! [20] +QHash<QString, int>::iterator i = hash.begin(); +while (i != hash.end()) { + QHash<QString, int>::iterator prev = i; + ++i; + if (prev.key().startsWith("_")) + hash.erase(prev); +} +//! [20] + + +//! [21] +// WRONG +while (i != hash.end()) { + if (i.key().startsWith("_")) + hash.erase(i); + ++i; +} +//! [21] + + +//! [22] +if (i.key() == "Hello") + i.value() = "Bonjour"; +//! [22] + + +//! [23] +QHash<QString, int> hash; +hash.insert("January", 1); +hash.insert("February", 2); +... +hash.insert("December", 12); + +QHash<QString, int>::const_iterator i; +for (i = hash.constBegin(); i != hash.constEnd(); ++i) + cout << i.key() << ": " << i.value() << endl; +//! [23] + + +//! [24] +QMultiHash<QString, int> hash1, hash2, hash3; + +hash1.insert("plenty", 100); +hash1.insert("plenty", 2000); +// hash1.size() == 2 + +hash2.insert("plenty", 5000); +// hash2.size() == 1 + +hash3 = hash1 + hash2; +// hash3.size() == 3 +//! [24] + + +//! [25] +QList<int> values = hash.values("plenty"); +for (int i = 0; i < values.size(); ++i) + cout << values.at(i) << endl; +//! [25] + + +//! [26] +QMultiHash<QString, int>::iterator i = hash.find("plenty"); +while (i != hash.end() && i.key() == "plenty") { + cout << i.value() << endl; + ++i; +} +//! [26] diff --git a/doc/src/snippets/code/src_corelib_tools_qlinkedlist.cpp b/doc/src/snippets/code/src_corelib_tools_qlinkedlist.cpp new file mode 100644 index 0000000..3d63b2c --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qlinkedlist.cpp @@ -0,0 +1,164 @@ +//! [0] +QLinkedList<int> integerList; +QLinkedList<QTime> timeList; +//! [0] + + +//! [1] +QLinkedList<QString> list; +list << "one" << "two" << "three"; +// list: ["one", "two", "three"] +//! [1] + + +//! [2] +QLinkedList<QWidget *> list; +... +while (!list.isEmpty()) + delete list.takeFirst(); +//! [2] + + +//! [3] +QLinkedList<QString> list; +list.append("one"); +list.append("two"); +list.append("three"); +// list: ["one", "two", "three"] +//! [3] + + +//! [4] +QLinkedList<QString> list; +list.prepend("one"); +list.prepend("two"); +list.prepend("three"); +// list: ["three", "two", "one"] +//! [4] + + +//! [5] +QList<QString> list; +list << "sun" << "cloud" << "sun" << "rain"; +list.removeAll("sun"); +// list: ["cloud", "rain"] +//! [5] + + +//! [6] +QList<QString> list; +list << "sun" << "cloud" << "sun" << "rain"; +list.removeOne("sun"); +// list: ["cloud", "sun", "rain"] +//! [6] + + +//! [7] +QLinkedList<QString> list; +list.append("January"); +list.append("February"); +... +list.append("December"); + +QLinkedList<QString>::iterator i; +for (i = list.begin(); i != list.end(); ++i) + cout << *i << endl; +//! [7] + + +//! [8] +QLinkedList<QString> list; +... +QLinkedList<QString>::iterator it = qFind(list.begin(), + list.end(), "Joel"); +if (it != list.end()) + cout << "Found Joel" << endl; +//! [8] + + +//! [9] +QLinkedList<int>::iterator i; +for (i = list.begin(); i != list.end(); ++i) + *i += 2; +//! [9] + + +//! [10] +QLinkedList<QString> list; +... +QLinkedList<QString>::iterator i = list.begin(); +while (i != list.end()) { + if ((*i).startsWith("_")) + i = list.erase(i); + else + ++i; +} +//! [10] + + +//! [11] +QLinkedList<QString>::iterator i = list.begin(); +while (i != list.end()) { + QLinkedList<QString>::iterator previous = i; + ++i; + if ((*previous).startsWith("_")) + list.erase(previous); +} +//! [11] + + +//! [12] +// WRONG +while (i != list.end()) { + if ((*i).startsWith("_")) + list.erase(i); + ++i; +} +//! [12] + + +//! [13] +if (*it == "Hello") + *it = "Bonjour"; +//! [13] + + +//! [14] +QLinkedList<QString> list; +list.append("January"); +list.append("February"); +... +list.append("December"); + +QLinkedList<QString>::const_iterator i; +for (i = list.constBegin(); i != list.constEnd(); ++i) + cout << *i << endl; +//! [14] + + +//! [15] +QLinkedList<QString> list; +... +QLinkedList<QString>::iterator it = qFind(list.constBegin(), + list.constEnd(), "Joel"); +if (it != list.constEnd()) + cout << "Found Joel" << endl; +//! [15] + + +//! [16] +std::list<double> stdlist; +list.push_back(1.2); +list.push_back(0.5); +list.push_back(3.14); + +QLinkedList<double> list = QLinkedList<double>::fromStdList(stdlist); +//! [16] + + +//! [17] +QLinkedList<double> list; +list << 1.2 << 0.5 << 3.14; + +std::list<double> stdlist = list.toStdList(); +//! [17] diff --git a/doc/src/snippets/code/src_corelib_tools_qlistdata.cpp b/doc/src/snippets/code/src_corelib_tools_qlistdata.cpp new file mode 100644 index 0000000..7d75e1b --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qlistdata.cpp @@ -0,0 +1,227 @@ +//! [0] +QList<int> integerList; +QList<QDate> dateList; +//! [0] + + +//! [1] +QList<QString> list; +list << "one" << "two" << "three"; +// list: ["one", "two", "three"] +//! [1] + + +//! [2] +if (list[0] == "Bob") + list[0] = "Robert"; +//! [2] + + +//! [3] +for (int i = 0; i < list.size(); ++i) { + if (list.at(i) == "Jane") + cout << "Found Jane at position " << i << endl; +} +//! [3] + + +//! [4] +QList<QWidget *> list; +... +while (!list.isEmpty()) + delete list.takeFirst(); +//! [4] + + +//! [5] +int i = list.indexOf("Jane"); +if (i != -1) + cout << "First occurrence of Jane is at position " << i << endl; +//! [5] + + +//! [6] +QList<QString> list; +list.append("one"); +list.append("two"); +list.append("three"); +// list: ["one", "two", "three"] +//! [6] + + +//! [7] +QList<QString> list; +list.prepend("one"); +list.prepend("two"); +list.prepend("three"); +// list: ["three", "two", "one"] +//! [7] + + +//! [8] +QList<QString> list; +list << "alpha" << "beta" << "delta"; +list.insert(2, "gamma"); +// list: ["alpha", "beta", "gamma", "delta"] +//! [8] + + +//! [9] +QList<QString> list; +list << "sun" << "cloud" << "sun" << "rain"; +list.removeAll("sun"); +// list: ["cloud", "rain"] +//! [9] + + +//! [10] +QList<QString> list; +list << "sun" << "cloud" << "sun" << "rain"; +list.removeOne("sun"); +// list: ["cloud", ,"sun", "rain"] +//! [10] + + +//! [11] +QList<QString> list; +list << "A" << "B" << "C" << "D" << "E" << "F"; +list.move(1, 4); +// list: ["A", "C", "D", "E", "B", "F"] +//! [11] + + +//! [12] +QList<QString> list; +list << "A" << "B" << "C" << "D" << "E" << "F"; +list.swap(1, 4); +// list: ["A", "E", "C", "D", "B", "F"] +//! [12] + + +//! [13] +QList<QString> list; +list << "A" << "B" << "C" << "B" << "A"; +list.indexOf("B"); // returns 1 +list.indexOf("B", 1); // returns 1 +list.indexOf("B", 2); // returns 3 +list.indexOf("X"); // returns -1 +//! [13] + + +//! [14] +QList<QString> list; +list << "A" << "B" << "C" << "B" << "A"; +list.lastIndexOf("B"); // returns 3 +list.lastIndexOf("B", 3); // returns 3 +list.lastIndexOf("B", 2); // returns 1 +list.lastIndexOf("X"); // returns -1 +//! [14] + + +//! [15] +QList<QString> list; +list.append("January"); +list.append("February"); +... +list.append("December"); + +QList<QString>::iterator i; +for (i = list.begin(); i != list.end(); ++i) + cout << *i << endl; +//! [15] + + +//! [16] +QList<int>::iterator i; +for (i = list.begin(); i != list.end(); ++i) + *i += 2; +//! [16] + + +//! [17] +QList<QWidget *> list; +... +qDeleteAll(list.begin(), list.end()); +//! [17] + + +//! [18] +if (*it == "Hello") + *it = "Bonjour"; +//! [18] + + +//! [19] +QList<QString> list; +list.append("January"); +list.append("February"); +... +list.append("December"); + +QList<QString>::const_iterator i; +for (i = list.constBegin(); i != list.constEnd(); ++i) + cout << *i << endl; +//! [19] + + +//! [20] +QList<QWidget *> list; +... +qDeleteAll(list.constBegin(), list.constEnd()); +//! [20] + + +//! [21] +QVector<double> vect; +vect << 20.0 << 30.0 << 40.0 << 50.0; + +QList<double> list = QVector<T>::fromVector(vect); +// list: [20.0, 30.0, 40.0, 50.0] +//! [21] + + +//! [22] +QStringList list; +list << "Sven" << "Kim" << "Ola"; + +QVector<QString> vect = list.toVector(); +// vect: ["Sven", "Kim", "Ola"] +//! [22] + + +//! [23] +QSet<double> set; +set << 20.0 << 30.0 << 40.0 << ... << 70.0; + +QList<double> list = QList<double>::fromSet(set); +qSort(list); +//! [23] + + +//! [24] +QStringList list; +list << "Julia" << "Mike" << "Mike" << "Julia" << "Julia"; + +QSet<QString> set = list.toSet(); +set.contains("Julia"); // returns true +set.contains("Mike"); // returns true +set.size(); // returns 2 +//! [24] + + +//! [25] +std::list<double> stdlist; +list.push_back(1.2); +list.push_back(0.5); +list.push_back(3.14); + +QList<double> list = QList<double>::fromStdList(stdlist); +//! [25] + + +//! [26] +QList<double> list; +list << 1.2 << 0.5 << 3.14; + +std::list<double> stdlist = list.toStdList(); +//! [26] diff --git a/doc/src/snippets/code/src_corelib_tools_qlocale.cpp b/doc/src/snippets/code/src_corelib_tools_qlocale.cpp new file mode 100644 index 0000000..37ddb4e --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qlocale.cpp @@ -0,0 +1,55 @@ +//! [0] +QLocale egyptian(QLocale::Arabic, QLocale::Egypt); +QString s1 = egyptian.toString(1.571429E+07, 'e'); +QString s2 = egyptian.toString(10); + +double d = egyptian.toDouble(s1); +int i = egyptian.toInt(s2); +//! [0] + + +//! [1] +QLocale::setDefault(QLocale(QLocale::Hebrew, QLocale::Israel)); +QLocale hebrew; // Constructs a default QLocale +QString s1 = hebrew.toString(15714.3, 'e'); + +bool ok; +double d; + +QLocale::setDefault(QLocale::C); +d = QString("1234,56").toDouble(&ok); // ok == false +d = QString("1234.56").toDouble(&ok); // ok == true, d == 1234.56 + +QLocale::setDefault(QLocale::German); +d = QString("1234,56").toDouble(&ok); // ok == true, d == 1234.56 +d = QString("1234.56").toDouble(&ok); // ok == true, d == 1234.56 + +QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); +str = QString("%1 %L2 %L3") + .arg(12345).arg(12345).arg(12345, 0, 16); +// str == "12345 12,345 3039" +//! [1] + + +//! [2] +QLocale korean("ko"); +QLocale swiss("de_CH"); +//! [2] + + +//! [3] +bool ok; +double d; + +QLocale c(QLocale::C); +d = c.toDouble( "1234.56", &ok ); // ok == true, d == 1234.56 +d = c.toDouble( "1,234.56", &ok ); // ok == true, d == 1234.56 +d = c.toDouble( "1234,56", &ok ); // ok == false + +QLocale german(QLocale::German); +d = german.toDouble( "1234,56", &ok ); // ok == true, d == 1234.56 +d = german.toDouble( "1.234,56", &ok ); // ok == true, d == 1234.56 +d = german.toDouble( "1234.56", &ok ); // ok == false + +d = german.toDouble( "1.234", &ok ); // ok == true, d == 1234.0 +//! [3] diff --git a/doc/src/snippets/code/src_corelib_tools_qmap.cpp b/doc/src/snippets/code/src_corelib_tools_qmap.cpp new file mode 100644 index 0000000..924ed22 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qmap.cpp @@ -0,0 +1,273 @@ +//! [0] +QMap<QString, int> map; +//! [0] + + +//! [1] +map["one"] = 1; +map["three"] = 3; +map["seven"] = 7; +//! [1] + + +//! [2] +map.insert("twelve", 12); +//! [2] + + +//! [3] +int num1 = map["thirteen"]; +int num2 = map.value("thirteen"); +//! [3] + + +//! [4] +int timeout = 30; +if (map.contains("TIMEOUT")) + timeout = map.value("TIMEOUT"); +//! [4] + + +//! [5] +int timeout = map.value("TIMEOUT", 30); +//! [5] + + +//! [6] +// WRONG +QMap<int, QWidget *> map; +... +for (int i = 0; i < 1000; ++i) { + if (map[i] == okButton) + cout << "Found button at index " << i << endl; +} +//! [6] + + +//! [7] +QMapIterator<QString, int> i(map); +while (i.hasNext()) { + i.next(); + cout << i.key() << ": " << i.value() << endl; +} +//! [7] + + +//! [8] +QMap<QString, int>::const_iterator i = map.constBegin(); +while (i != map.constEnd()) { + cout << i.key() << ": " << i.value() << endl; + ++i; +} +//! [8] + + +//! [9] +map.insert("plenty", 100); +map.insert("plenty", 2000); +// map.value("plenty") == 2000 +//! [9] + + +//! [10] +QList<int> values = map.values("plenty"); +for (int i = 0; i < values.size(); ++i) + cout << values.at(i) << endl; +//! [10] + + +//! [11] +QMap<QString, int>::iterator i = map.find("plenty"); +while (i != map.end() && i.key() == "plenty") { + cout << i.value() << endl; + ++i; +} +//! [11] + + +//! [12] +QMap<QString, int> map; +... +foreach (int value, map) + cout << value << endl; +//! [12] + + +//! [13] +#ifndef EMPLOYEE_H +#define EMPLOYEE_H + +class Employee +{ +public: + Employee() {} + Employee(const QString &name, const QDate &dateOfBirth); + ... + +private: + QString myName; + QDate myDateOfBirth; +}; + +inline bool operator<(const Employee &e1, const Employee &e2) +{ + if (e1.name() != e2.name()) + return e1.name() < e2.name(); + return e1.dateOfBirth() < e2.dateOfBirth(); +} + +#endif // EMPLOYEE_H +//! [13] + + +//! [14] +QMap<QString, int> map; +... +QMap<QString, int>::const_iterator i = map.find("HDR"); +while (i != map.end() && i.key() == "HDR") { + cout << i.value() << endl; + ++i; +} +//! [14] + + +//! [15] +QMap<int, QString> map; +map.insert(1, "one"); +map.insert(5, "five"); +map.insert(10, "ten"); + +map.lowerBound(0); // returns iterator to (1, "one") +map.lowerBound(1); // returns iterator to (1, "one") +map.lowerBound(2); // returns iterator to (5, "five") +map.lowerBound(10); // returns iterator to (10, "ten") +map.lowerBound(999); // returns end() +//! [15] + + +//! [16] +QMap<QString, int> map; +... +QMap<QString, int>::const_iterator i = map.lowerBound("HDR"); +QMap<QString, int>::const_iterator upperBound = map.upperBound("HDR"); +while (i != upperBound) { + cout << i.value() << endl; + ++i; +} +//! [16] + + +//! [17] +QMap<int, QString> map; +map.insert(1, "one"); +map.insert(5, "five"); +map.insert(10, "ten"); + +map.upperBound(0); // returns iterator to (1, "one") +map.upperBound(1); // returns iterator to (5, "five") +map.upperBound(2); // returns iterator to (5, "five") +map.upperBound(10); // returns end() +map.upperBound(999); // returns end() +//! [17] + + +//! [18] +QMap<QString, int> map; +map.insert("January", 1); +map.insert("February", 2); +... +map.insert("December", 12); + +QMap<QString, int>::iterator i; +for (i = map.begin(); i != map.end(); ++i) + cout << i.key() << ": " << i.value() << endl; +//! [18] + + +//! [19] +QMap<QString, int>::iterator i; +for (i = map.begin(); i != map.end(); ++i) + i.value() += 2; +//! [19] + + +//! [20] +QMap<QString, int>::iterator i = map.begin(); +while (i != map.end()) { + if (i.key().startsWith("_")) + i = map.erase(i); + else + ++i; +} +//! [20] + + +//! [21] +QMap<QString, int>::iterator i = map.begin(); +while (i != map.end()) { + QMap<QString, int>::iterator prev = i; + ++i; + if (prev.key().startsWith("_")) + map.erase(prev); +} +//! [21] + + +//! [22] +// WRONG +while (i != map.end()) { + if (i.key().startsWith("_")) + map.erase(i); + ++i; +} +//! [22] + + +//! [23] +if (i.key() == "Hello") + i.value() = "Bonjour"; +//! [23] + + +//! [24] +QMap<QString, int> map; +map.insert("January", 1); +map.insert("February", 2); +... +map.insert("December", 12); + +QMap<QString, int>::const_iterator i; +for (i = map.constBegin(); i != map.constEnd(); ++i) + cout << i.key() << ": " << i.value() << endl; +//! [24] + + +//! [25] +QMultiMap<QString, int> map1, map2, map3; + +map1.insert("plenty", 100); +map1.insert("plenty", 2000); +// map1.size() == 2 + +map2.insert("plenty", 5000); +// map2.size() == 1 + +map3 = map1 + map2; +// map3.size() == 3 +//! [25] + + +//! [26] +QList<int> values = map.values("plenty"); +for (int i = 0; i < values.size(); ++i) + cout << values.at(i) << endl; +//! [26] + + +//! [27] +QMultiMap<QString, int>::iterator i = map.find("plenty"); +while (i != map.end() && i.key() == "plenty") { + cout << i.value() << endl; + ++i; +} +//! [27] diff --git a/doc/src/snippets/code/src_corelib_tools_qpoint.cpp b/doc/src/snippets/code/src_corelib_tools_qpoint.cpp new file mode 100644 index 0000000..f16d856 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qpoint.cpp @@ -0,0 +1,109 @@ +//! [0] +QPoint p; + +p.setX(p.x() + 1); +p += QPoint(1, 0); +p.rx()++; +//! [0] + + +//! [1] +QPoint p(1, 2); +p.rx()--; // p becomes (0, 2) +//! [1] + + +//! [2] +QPoint p(1, 2); +p.ry()++; // p becomes (1, 3) +//! [2] + + +//! [3] +QPoint p( 3, 7); +QPoint q(-1, 4); +p += q; // p becomes (2, 11) +//! [3] + + +//! [4] +QPoint p( 3, 7); +QPoint q(-1, 4); +p -= q; // p becomes (4, 3) +//! [4] + + +//! [5] +QPoint p(-1, 4); +p *= 2.5; // p becomes (-3, 10) +//! [5] + + +//! [6] +QPoint p(-3, 10); +p /= 2.5; // p becomes (-1, 4) +//! [6] + + +//! [7] +QPoint oldPosition; + +MyWidget::mouseMoveEvent(QMouseEvent *event) +{ + QPoint point = event->pos() - oldPosition; + if (point.manhattanLength() > 3) + // the mouse has moved more than 3 pixels since the oldPosition +} +//! [7] + + +//! [8] +double trueLength = sqrt(pow(x(), 2) + pow(y(), 2)); +//! [8] + + +//! [9] +QPointF p; + +p.setX(p.x() + 1.0); +p += QPointF(1.0, 0.0); +p.rx()++; +//! [9] + + +//! [10] + QPointF p(1.1, 2.5); + p.rx()--; // p becomes (0.1, 2.5) +//! [10] + + +//! [11] +QPointF p(1.1, 2.5); +p.ry()++; // p becomes (1.1, 3.5) +//! [11] + + +//! [12] +QPointF p( 3.1, 7.1); +QPointF q(-1.0, 4.1); +p += q; // p becomes (2.1, 11.2) +//! [12] + + +//! [13] +QPointF p( 3.1, 7.1); +QPointF q(-1.0, 4.1); +p -= q; // p becomes (4.1, 3.0) +//! [13] + + +//! [14] +QPointF p(-1.1, 4.1); +p *= 2.5; // p becomes (-2.75, 10.25) +//! [14] + + +//! [15] +QPointF p(-2.75, 10.25); +p /= 2.5; // p becomes (-1.1, 4.1) +//! [15] diff --git a/doc/src/snippets/code/src_corelib_tools_qqueue.cpp b/doc/src/snippets/code/src_corelib_tools_qqueue.cpp new file mode 100644 index 0000000..da4c4a6 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qqueue.cpp @@ -0,0 +1,8 @@ +//! [0] +QQueue<int> queue; +queue.enqueue(1); +queue.enqueue(2); +queue.enqueue(3); +while (!queue.isEmpty()) + cout << queue.dequeue() << endl; +//! [0] diff --git a/doc/src/snippets/code/src_corelib_tools_qrect.cpp b/doc/src/snippets/code/src_corelib_tools_qrect.cpp new file mode 100644 index 0000000..fdab506 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qrect.cpp @@ -0,0 +1,10 @@ +//! [0] +QRect r1(100, 200, 11, 16); +QRect r2(QPoint(100, 200), QSize(11, 16)); +//! [0] + + +//! [1] +QRectF r1(100, 200, 11, 16); +QRectF r2(QPoint(100, 200), QSize(11, 16)); +//! [1] diff --git a/doc/src/snippets/code/src_corelib_tools_qregexp.cpp b/doc/src/snippets/code/src_corelib_tools_qregexp.cpp new file mode 100644 index 0000000..ae25885 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qregexp.cpp @@ -0,0 +1,184 @@ +//! [0] +QRegExp rx("(\\d+)"); +QString str = "Offsets: 12 14 99 231 7"; +QStringList list; +int pos = 0; + +while ((pos = rx.indexIn(str, pos)) != -1) { + list << rx.cap(1); + pos += rx.matchedLength(); +} +// list: ["12", "14", "99", "231", "7"] +//! [0] + + +//! [1] +QRegExp rx("*.txt"); +rx.setPatternSyntax(QRegExp::Wildcard); +rx.exactMatch("README.txt"); // returns true +rx.exactMatch("welcome.txt.bak"); // returns false +//! [1] + + +//! [2] +QRegExp rx("ro+m"); +rx.setMinimal(true); +//! [2] + + +//! [3] +QRegExp mark("\\b" // word boundary + "[Mm]ark" // the word we want to match + ); +//! [3] + + +//! [4] +QRegExp rx("^\\d\\d?$"); // match integers 0 to 99 +rx.indexIn("123"); // returns -1 (no match) +rx.indexIn("-6"); // returns -1 (no match) +rx.indexIn("6"); // returns 0 (matched as position 0) +//! [4] + + +//! [5] +QRegExp rx("^\\S+$"); // match strings without whitespace +rx.indexIn("Hello world"); // returns -1 (no match) +rx.indexIn("This_is-OK"); // returns 0 (matched at position 0) +//! [5] + + +//! [6] +QRegExp rx("\\b(mail|letter|correspondence)\\b"); +rx.indexIn("I sent you an email"); // returns -1 (no match) +rx.indexIn("Please write the letter"); // returns 17 +//! [6] + + +//! [7] +QString captured = rx.cap(1); // captured == "letter" +//! [7] + + +//! [8] +QRegExp rx("&(?!amp;)"); // match ampersands but not & +QString line1 = "This & that"; +line1.replace(rx, "&"); +// line1 == "This & that" +QString line2 = "His & hers & theirs"; +line2.replace(rx, "&"); +// line2 == "His & hers & theirs" +//! [8] + + +//! [9] +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.indexIn(str, pos); + if (pos >= 0) { + ++pos; // move along in str + ++count; // count our Eric or Eirik + } +} +//! [9] + + +//! [10] +str = "Nokia Corporation and/or its subsidiary(-ies)\tqtsoftware.com\tNorway"; +QString company, web, country; +rx.setPattern("^([^\t]+)\t([^\t]+)\t([^\t]+)$"); +if (rx.indexIn(str) != -1) { + company = rx.cap(1); + web = rx.cap(2); + country = rx.cap(3); +} +//! [10] + + +//! [11] +QStringList field = str.split("\t"); +//! [11] + + +//! [12] +QRegExp rx("*.html"); +rx.setPatternSyntax(QRegExp::Wildcard); +rx.exactMatch("index.html"); // returns true +rx.exactMatch("default.htm"); // returns false +rx.exactMatch("readme.txt"); // returns false +//! [12] + + +//! [13] +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 = rx.indexIn(str, pos)) != -1) { + ++count; + pos += rx.matchedLength(); +} +// pos will be 9, 14, 18 and finally 24; count will end up as 4 +//! [13] + + +//! [14] +QRegExp rx("(\\d+)(\\s*)(cm|inch(es)?)"); +int pos = rx.indexIn("Length: 36 inches"); +QStringList list = rx.capturedTexts(); +// list is now ("36 inches", "36", " ", "inches", "es") +//! [14] + + +//! [15] +QRegExp rx("(\\d+)(?:\\s*)(cm|inch(?:es)?)"); +int pos = rx.indexIn("Length: 36 inches"); +QStringList list = rx.capturedTexts(); +// list is now ("36 inches", "36", "inches") +//! [15] + + +//! [16] +QStringList list = rx.capturedTexts(); +QStringList::iterator it = list.begin(); +while (it != list.end()) { + myProcessing(*it); + ++it; +} +//! [16] + + +//! [17] +QRegExp rxlen("(\\d+)(?:\\s*)(cm|inch)"); +int pos = rxlen.indexIn("Length: 189cm"); +if (pos > -1) { + QString value = rxlen.cap(1); // "189" + QString unit = rxlen.cap(2); // "cm" + // ... +} +//! [17] + + +//! [18] +QRegExp rx("/([a-z]+)/([a-z]+)"); +rx.indexIn("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) +//! [18] + + +//! [19] +s1 = QRegExp::escape("bingo"); // s1 == "bingo" +s2 = QRegExp::escape("f(x)"); // s2 == "f\\(x\\)" +//! [19] + + +//! [20] +QRegExp rx("(" + QRegExp::escape(name) + + "|" + QRegExp::escape(alias) + ")"); +//! [20] diff --git a/doc/src/snippets/code/src_corelib_tools_qsize.cpp b/doc/src/snippets/code/src_corelib_tools_qsize.cpp new file mode 100644 index 0000000..4804dd0 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qsize.cpp @@ -0,0 +1,96 @@ +//! [0] +QSize t1(10, 12); +t1.scale(60, 60, Qt::IgnoreAspectRatio); +// t1 is (60, 60) + +QSize t2(10, 12); +t2.scale(60, 60, Qt::KeepAspectRatio); +// t2 is (50, 60) + +QSize t3(10, 12); +t3.scale(60, 60, Qt::KeepAspectRatioByExpanding); +// t3 is (60, 72) +//! [0] + + +//! [1] +QSize size(100, 10); +size.rwidth() += 20; + +// size becomes (120,10) +//! [1] + + +//! [2] +QSize size(100, 10); +size.rheight() += 5; + +// size becomes (100,15) +//! [2] + + +//! [3] +QSize s( 3, 7); +QSize r(-1, 4); +s += r; + +// s becomes (2,11) +//! [3] + + +//! [4] +QSize s( 3, 7); +QSize r(-1, 4); +s -= r; + +// s becomes (4,3) +//! [4] + + +//! [5] +QSizeF t1(10, 12); +t1.scale(60, 60, Qt::IgnoreAspectRatio); +// t1 is (60, 60) + +QSizeF t2(10, 12); +t2.scale(60, 60, Qt::KeepAspectRatio); +// t2 is (50, 60) + +QSizeF t3(10, 12); +t3.scale(60, 60, Qt::KeepAspectRatioByExpanding); +// t3 is (60, 72) +//! [5] + + +//! [6] +QSizeF size(100.3, 10); +size.rwidth() += 20.5; + + // size becomes (120.8,10) +//! [6] + + +//! [7] +QSizeF size(100, 10.2); +size.rheight() += 5.5; + +// size becomes (100,15.7) +//! [7] + + +//! [8] +QSizeF s( 3, 7); +QSizeF r(-1, 4); +s += r; + +// s becomes (2,11) +//! [8] + + +//! [9] +QSizeF s( 3, 7); +QSizeF r(-1, 4); +s -= r; + +// s becomes (4,3) +//! [9] diff --git a/doc/src/snippets/code/src_corelib_tools_qstring.cpp b/doc/src/snippets/code/src_corelib_tools_qstring.cpp new file mode 100644 index 0000000..13cdbd5 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qstring.cpp @@ -0,0 +1,47 @@ +//! [0] +DEFINES += QT_NO_CAST_FROM_ASCII \ + QT_NO_CAST_TO_ASCII +//! [0] + + +//! [1] +QString url = QLatin1String("http://www.unicode.org/"); +//! [1] + + +//! [2] +double d = 12.34; +QString str = QString("delta: %1").arg(d, 0, 'E', 3); +// str == "delta: 1.234E+01" +//! [2] + + +//! [3] +if (str == "auto" || str == "extern" + || str == "static" || str == "register") { + ... +} +//! [3] + + +//! [4] +if (str == QString("auto") || str == QString("extern") + || str == QString("static") || str == QString("register")) { + ... +} +//! [4] + + +//! [5] +if (str == QLatin1String("auto") + || str == QLatin1String("extern") + || str == QLatin1String("static") + || str == QLatin1String("register") { + ... +} +//! [5] + + +//! [6] +QLabel *label = new QLabel(QLatin1String("MOD"), this); +//! [6] diff --git a/doc/src/snippets/code/src_corelib_tools_qtimeline.cpp b/doc/src/snippets/code/src_corelib_tools_qtimeline.cpp new file mode 100644 index 0000000..a16205f --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qtimeline.cpp @@ -0,0 +1,15 @@ +//! [0] +... +progressBar = new QProgressBar(this); +progressBar->setRange(0, 100); + +// Construct a 1-second timeline with a frame range of 0 - 100 +QTimeLine *timeLine = new QTimeLine(1000, this); +timeLine->setFrameRange(0, 100); +connect(timeLine, SIGNAL(frameChanged(int)), progressBar, SLOT(setValue(int))); + +// Clicking the push button will start the progress bar animation +pushButton = new QPushButton(tr("Start animation"), this); +connect(pushButton, SIGNAL(clicked()), timeLine, SLOT(start())); +... +//! [0] diff --git a/doc/src/snippets/code/src_corelib_tools_qvector.cpp b/doc/src/snippets/code/src_corelib_tools_qvector.cpp new file mode 100644 index 0000000..bbe7ca2 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qvector.cpp @@ -0,0 +1,143 @@ +//! [0] +QVector<int> integerVector; +QVector<QString> stringVector; +//! [0] + + +//! [1] +QVector<QString> vector(200); +//! [1] + + +//! [2] +QVector<QString> vector(200, "Pass"); +//! [2] + + +//! [3] +if (vector[0] == "Liz") + vector[0] = "Elizabeth"; +//! [3] + + +//! [4] +for (int i = 0; i < vector.size(); ++i) { + if (vector.at(i) == "Alfonso") + cout << "Found Alfonso at position " << i << endl; +} +//! [4] + + +//! [5] +int i = vector.indexOf("Harumi"); +if (i != -1) + cout << "First occurrence of Harumi is at position " << i << endl; +//! [5] + + +//! [6] +QVector<int> vector(10); +int *data = vector.data(); +for (int i = 0; i < 10; ++i) + data[i] = 2 * i; +//! [6] + + +//! [7] +QVector<QString> vector(0); +vector.append("one"); +vector.append("two"); +vector.append("three"); +// vector: ["one", "two", "three"] +//! [7] + + +//! [8] +QVector<QString> vector; +vector.prepend("one"); +vector.prepend("two"); +vector.prepend("three"); +// vector: ["three", "two", "one"] +//! [8] + + +//! [9] +QVector<QString> vector; +vector << "alpha" << "beta" << "delta"; +vector.insert(2, "gamma"); +// vector: ["alpha", "beta", "gamma", "delta"] +//! [9] + + +//! [10] +QVector<double> vector; +vector << 2.718 << 1.442 << 0.4342; +vector.insert(1, 3, 9.9); +// vector: [2.718, 9.9, 9.9, 9.9, 1.442, 0.4342] +//! [10] + + +//! [11] +QVector<QString> vector(3); +vector.fill("Yes"); +// vector: ["Yes", "Yes", "Yes"] + +vector.fill("oh", 5); +// vector: ["oh", "oh", "oh", "oh", "oh"] +//! [11] + + +//! [12] +QVector<QString> vector; +vector << "A" << "B" << "C" << "B" << "A"; +vector.indexOf("B"); // returns 1 +vector.indexOf("B", 1); // returns 1 +vector.indexOf("B", 2); // returns 3 +vector.indexOf("X"); // returns -1 +//! [12] + + +//! [13] +QList<QString> vector; +vector << "A" << "B" << "C" << "B" << "A"; +vector.lastIndexOf("B"); // returns 3 +vector.lastIndexOf("B", 3); // returns 3 +vector.lastIndexOf("B", 2); // returns 1 +vector.lastIndexOf("X"); // returns -1 +//! [13] + + +//! [14] +QVector<double> vect; +vect << "red" << "green" << "blue" << "black"; + +QList<double> list = vect.toList(); +// list: ["red", "green", "blue", "black"] +//! [14] + + +//! [15] +QStringList list; +list << "Sven" << "Kim" << "Ola"; + +QVector<QString> vect = QVector<QString>::fromList(list); +// vect: ["Sven", "Kim", "Ola"] +//! [15] + + +//! [16] +std::vector<double> stdvector; +vector.push_back(1.2); +vector.push_back(0.5); +vector.push_back(3.14); + +QVector<double> vector = QVector<double>::fromStdVector(stdvector); +//! [16] + + +//! [17] +QVector<double> vector; +vector << 1.2 << 0.5 << 3.14; + +std::vector<double> stdvector = vector.toStdVector(); +//! [17] diff --git a/doc/src/snippets/code/src_corelib_xml_qxmlstream.cpp b/doc/src/snippets/code/src_corelib_xml_qxmlstream.cpp new file mode 100644 index 0000000..b445a61 --- /dev/null +++ b/doc/src/snippets/code/src_corelib_xml_qxmlstream.cpp @@ -0,0 +1,27 @@ +//! [0] + QXmlStreamReader xml; + ... + while (!xml.atEnd()) { + xml.readNext(); + ... // do processing + } + if (xml.hasError()) { + ... // do error handling + } +//! [0] + + +//! [1] + writeStartElement(qualifiedName); + writeCharacters(text); + writeEndElement(); +//! [1] + + +//! [2] + writeStartElement(namespaceUri, name); + writeCharacters(text); + writeEndElement(); +//! [2] + + diff --git a/doc/src/snippets/code/src_gui_accessible_qaccessible.cpp b/doc/src/snippets/code/src_gui_accessible_qaccessible.cpp new file mode 100644 index 0000000..69ebeb2 --- /dev/null +++ b/doc/src/snippets/code/src_gui_accessible_qaccessible.cpp @@ -0,0 +1,8 @@ +//! [0] +QAccessibleInterface *child = 0; +int targetChild = object->navigate(Accessible::Child, 1, &child); +if (child) { + // ... + delete child; +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_dialogs_qabstractprintdialog.cpp b/doc/src/snippets/code/src_gui_dialogs_qabstractprintdialog.cpp new file mode 100644 index 0000000..e947bd7 --- /dev/null +++ b/doc/src/snippets/code/src_gui_dialogs_qabstractprintdialog.cpp @@ -0,0 +1,6 @@ +//! [0] +QPrintDialog printDialog(printer, parent); +if (printDialog.exec() == QDialog::Accepted) { + // print ... +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp b/doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp new file mode 100644 index 0000000..6962f4d --- /dev/null +++ b/doc/src/snippets/code/src_gui_dialogs_qfiledialog.cpp @@ -0,0 +1,91 @@ +//! [0] +fileName = QFileDialog::getOpenFileName(this, + tr("Open Image"), "/home/jana", tr("Image Files (*.png *.jpg *.bmp)")); +//! [0] + + +//! [1] +"Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)" +//! [1] + + +//! [2] +QFileDialog dialog(this); +dialog.setFileMode(QFileDialog::AnyFile); +//! [2] + + +//! [3] +dialog.setNameFilter(tr("Images (*.png *.xpm *.jpg)")); +//! [3] + + +//! [4] +dialog.setViewMode(QFileDialog::Detail); +//! [4] + + +//! [5] +QStringList fileNames; +if (dialog.exec()) + fileNames = dialog.selectedFiles(); +//! [5] + + +//! [6] +dialog.setNameFilter("All C++ files (*.cpp *.cc *.C *.cxx *.c++)"); +dialog.setNameFilter("*.cpp *.cc *.C *.cxx *.c++"); +//! [6] + + +//! [7] +QStringList filters; +filters << "Image files (*.png *.xpm *.jpg)" + << "Text files (*.txt)" + << "Any files (*)"; + +QFileDialog dialog(this); +dialog.setNameFilters(filters); +dialog.exec(); +//! [7] + + +//! [8] +QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), + "/home", + tr("Images (*.png *.xpm *.jpg)")); +//! [8] + + +//! [9] +QStringList files = QFileDialog::getOpenFileNames( + this, + "Select one or more files to open", + "/home", + "Images (*.png *.xpm *.jpg)"); +//! [9] + + +//! [10] +QStringList list = files; +QStringList::Iterator it = list.begin(); +while(it != list.end()) { + myProcessing(*it); + ++it; +} +//! [10] + + +//! [11] +QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), + "/home/jana/untitled.png", + tr("Images (*.png *.xpm *.jpg)")); +//! [11] + + +//! [12] +QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), + "/home", + QFileDialog::ShowDirsOnly + | QFileDialog::DontResolveSymlinks); +//! [12] diff --git a/doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp b/doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp new file mode 100644 index 0000000..f1b06ec --- /dev/null +++ b/doc/src/snippets/code/src_gui_dialogs_qfontdialog.cpp @@ -0,0 +1,45 @@ +//! [0] +bool ok; +QFont font = QFontDialog::getFont( + &ok, QFont("Helvetica [Cronyx]", 10), this); +if (ok) { + // the user clicked OK and font is set to the font the user selected +} else { + // the user canceled the dialog; font is set to the initial + // value, in this case Helvetica [Cronyx], 10 +} +//! [0] + + +//! [1] +myWidget.setFont(QFontDialog::getFont(0, myWidget.font())); +//! [1] + + +//! [2] +bool ok; +QFont font = QFontDialog::getFont(&ok, QFont("Times", 12), this); +if (ok) { + // font is set to the font the user selected +} else { + // the user canceled the dialog; font is set to the initial + // value, in this case Times, 12. +} +//! [2] + + +//! [3] +myWidget.setFont(QFontDialog::getFont(0, myWidget.font())); +//! [3] + + +//! [4] +bool ok; +QFont font = QFontDialog::getFont(&ok, this); +if (ok) { + // font is set to the font the user selected +} else { + // the user canceled the dialog; font is set to the default + // application font, QApplication::font() +} +//! [4] diff --git a/doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp b/doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp new file mode 100644 index 0000000..ff0d128 --- /dev/null +++ b/doc/src/snippets/code/src_gui_dialogs_qmessagebox.cpp @@ -0,0 +1,108 @@ +//! [0] +int ret = QMessageBox::warning(this, tr("My Application"), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox::Save | QMessageBox::Discard + | QMessageBox::Cancel, + QMessageBox::Save); +//! [0] + + +//! [1] +QMessageBox msgBox; +msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); +switch (msgBox.exec()) { +case QMessageBox::Yes: + // yes was clicked + break; +case QMessageBox::No: + // no was clicked + break; +default: + // should never be reached + break; +} +//! [1] + + +//! [2] +QMessageBox msgBox; +QPushButton *connectButton = msgBox.addButton(tr("Connect"), QMessageBox::ActionRole); +QPushButton *abortButton = msgBox.addButton(QMessageBox::Abort); + +msgBox.exec(); + +if (msgBox.clickedButton() == connectButton) { + // connect +} else if (msgBox.clickedButton() == abortButton) { + // abort +} +//! [2] + + +//! [3] +QMessageBox messageBox(this); +QAbstractButton *disconnectButton = + messageBox.addButton(tr("Disconnect"), QMessageBox::ActionRole); +... +messageBox.exec(); +if (messageBox.clickedButton() == disconnectButton) { + ... +} +//! [3] + + +//! [4] +#include <QApplication> +#include <QMessageBox> + +int main(int argc, char *argv[]) +{ + QT_REQUIRE_VERSION(argc, argv, "4.0.2") + + QApplication app(argc, argv); + ... + return app.exec(); +} +//! [4] + +//! [5] +QMessageBox msgBox; +msgBox.setText("The document has been modified."); +msgBox.exec(); +//! [5] + +//! [6] +QMessageBox msgBox; +msgBox.setText("The document has been modified."); +msgBox.setInformativeText("Do you want to save your changes?"); +msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); +msgBox.setDefaultButton(QMessageBox::Save); +int ret = msgBox.exec(); +//! [6] + +//! [7] +switch (ret) { + case QMessageBox::Save: + // Save was clicked + break; + case QMessageBox::Discard: + // Don't Save was clicked + break; + case QMessageBox::Cancel: + // Cancel was clicked + break; + default: + // should never be reached + break; +} +//! [7] + +//! [9] +QMessageBox msgBox(this); +msgBox.setText(tr("The document has been modified.\n" + "Do you want to save your changes?")); +msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard + | QMessageBox::Cancel); +msgBox.setDefaultButton(QMessageBox::Save); +//! [9] diff --git a/doc/src/snippets/code/src_gui_dialogs_qwizard.cpp b/doc/src/snippets/code/src_gui_dialogs_qwizard.cpp new file mode 100644 index 0000000..7890e13 --- /dev/null +++ b/doc/src/snippets/code/src_gui_dialogs_qwizard.cpp @@ -0,0 +1,40 @@ +//! [0] +int LicenseWizard::nextId() const +{ + switch (currentId()) { + case Page_Intro: + if (field("intro.evaluate").toBool()) { + return Page_Evaluate; + } else { + return Page_Register; + } + case Page_Evaluate: + return Page_Conclusion; + case Page_Register: + if (field("register.upgradeKey").toString().isEmpty()) { + return Page_Details; + } else { + return Page_Conclusion; + } + case Page_Details: + return Page_Conclusion; + case Page_Conclusion: + default: + return -1; + } +} +//! [0] + + +//! [1] +MyWizard::MyWizard(QWidget *parent) + : QWizard(parent) +{ + ... + QList<QWizard::WizardButton> layout; + layout << QWizard::Stretch << QWizard::BackButton << QWizard::CancelButton + << QWizard::NextButton << QWizard::FinishButton; + setButtonLayout(layout); + ... +} +//! [1] diff --git a/doc/src/snippets/code/src_gui_embedded_qcopchannel_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qcopchannel_qws.cpp new file mode 100644 index 0000000..98fa4a9 --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qcopchannel_qws.cpp @@ -0,0 +1,26 @@ +//! [0] +void MyClass::receive(const QString &message, const QByteArray &data) +{ + QDataStream in(data); + if (message == "execute(QString,QString)") { + QString cmd; + QString arg; + in >> cmd >> arg; + ... + } else if (message == "delete(QString)") { + QString fileName; + in >> fileName; + ... + } else { + ... + } +} +//! [0] + + +//! [1] +QByteArray data; +QDataStream out(&data, QIODevice::WriteOnly); +out << QString("cat") << QString("file.txt"); +QCopChannel::send("System/Shell", "execute(QString,QString)", data); +//! [1] diff --git a/doc/src/snippets/code/src_gui_embedded_qmouse_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qmouse_qws.cpp new file mode 100644 index 0000000..0ad3997 --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qmouse_qws.cpp @@ -0,0 +1,4 @@ +//! [0] +s*Xs = a*Xd + b*Yd + c +s*Ys = d*Xd + e*Yd + f +//! [0] diff --git a/doc/src/snippets/code/src_gui_embedded_qmousetslib_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qmousetslib_qws.cpp new file mode 100644 index 0000000..26cd76c --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qmousetslib_qws.cpp @@ -0,0 +1,9 @@ +//! [0] +configure -L <path to tslib library> -I <path to tslib headers> +//! [0] + + +//! [1] +module_raw input +module linear +//! [1] diff --git a/doc/src/snippets/code/src_gui_embedded_qscreen_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qscreen_qws.cpp new file mode 100644 index 0000000..52ce3b7 --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qscreen_qws.cpp @@ -0,0 +1,8 @@ +//! [0] +[screen driver][:driver specific options][:display number] +//! [0] + + +//! [1] +Mach64:/dev/fb1:2 +//! [1] diff --git a/doc/src/snippets/code/src_gui_embedded_qtransportauth_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qtransportauth_qws.cpp new file mode 100644 index 0000000..5ccebe2 --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qtransportauth_qws.cpp @@ -0,0 +1,47 @@ + +void wrapInFunction() +{ + +//! [0] +QTransportAuth::Data *conData; +QTransportAuth *a = QTransportAuth::getInstance(); + +conData = a->connectTransport( + QTransportAuth::Trusted | QTransportAuth::UnixStreamSock, + socketDescriptor ); +//! [0] + + +//! [1] +// mySocket can be any QIODevice subclass +AuthDevice *ad = a->recvBuf( d, mySocket ); + +// proxy in the auth device where the socket would have gone +connect( ad, SIGNAL(readyRead()), this, SLOT(mySocketReadyRead())); +//! [1] + + +//! [2] +AuthDevice *ad = a->authBuf( d, mySocket ); + +ad->write( someData ); +//! [2] + + +//! [3] +policyCheck( QTransportAuth::Data &, const QString & ) +//! [3] + + +//! [4] +QTransportAuth::Result r = d.status & QTransportAuth::ErrMask; +qWarning( "error: %s", QTransportAuth::errorStrings[r] ); +//! [4] + + +//! [5] +MD5(K XOR opad, MD5(K XOR ipad, text)) +//! [5] + +} + diff --git a/doc/src/snippets/code/src_gui_embedded_qwindowsystem_qws.cpp b/doc/src/snippets/code/src_gui_embedded_qwindowsystem_qws.cpp new file mode 100644 index 0000000..1364f23 --- /dev/null +++ b/doc/src/snippets/code/src_gui_embedded_qwindowsystem_qws.cpp @@ -0,0 +1,45 @@ +//! [0] +bool MyScreenSaver::save( int level ) +{ + switch ( level ) { + case 0: + if ( dim_enabled ) { + // dim the screen + } + return true; + case 1: + if ( screenoff_enabled ) { + // turn off the screen + } + return true; + case 2: + if ( suspend_enabled ) { + // suspend + } + return true; + default: + return false; + } +} + +... + +int timings[4]; +timings[0] = 5000; // dim after 5 seconds +timings[1] = 10000; // light off after 15 seconds +timings[2] = 45000; // suspend after 60 seconds +timings[3] = 0; +QWSServer::setScreenSaverIntervals( timings ); + +// ignore the key/mouse event that turns on the screen +int blocklevel = 1; +if ( !screenoff_enabled ) { + // screenoff is disabled, ignore the key/mouse event that wakes from suspend + blocklevel = 2; + if ( !suspend_enabled ) { + // suspend is disabled, never ignore events + blocklevel = -1; + } +} +QWSServer::setScreenSaverBlockLevel( blocklevel ); +//! [0] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp new file mode 100644 index 0000000..ed09b97 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsgridlayout.cpp @@ -0,0 +1,13 @@ +//! [0] +QGraphicsScene scene; +QGraphicsWidget *textEdit = scene.addWidget(new QTextEdit); +QGraphicsWidget *pushButton = scene.addWidget(new QPushButton); + +QGraphicsGridLayout *layout = new QGraphicsGridLayout; +layout->addItem(textEdit, 0, 0); +layout->addItem(pushButton, 0, 1); + +QGraphicsWidget *form = new QGraphicsWidget; +form->setLayout(layout); +scene.addItem(form); +//! [0] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp new file mode 100644 index 0000000..a57de9d --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp @@ -0,0 +1,221 @@ +//! [0] +class SimpleItem : public QGraphicsItem +{ +public: + QRectF boundingRect() const + { + qreal penWidth = 1; + return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, + 20 + penWidth / 2, 20 + penWidth / 2); + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) + { + painter->drawRoundedRect(-10, -10, 20, 20, 5, 5); + } +}; +//! [0] + + +//! [1] +class CustomItem : public QGraphicsItem +{ + ... + enum { Type = UserType + 1 }; + + int type() const + { + // Enable the use of qgraphicsitem_cast with this item. + return Type; + } + ... +}; +//! [1] + + +//! [2] +item->setCursor(Qt::IBeamCursor); +//! [2] + + +//! [3] +item->setCursor(Qt::IBeamCursor); +//! [3] + + +//! [4] +QGraphicsRectItem rect; +rect.setPos(100, 100); + +rect.sceneTransform().map(QPointF(0, 0)); +// returns QPointF(100, 100); + +rect.sceneTransform().inverted().map(QPointF(100, 100)); +// returns QPointF(0, 0); +//! [4] + + +//! [5] +QGraphicsRectItem rect; +rect.setPos(100, 100); + +rect.deviceTransform(view->viewportTransform()).map(QPointF(0, 0)); +// returns the item's (0, 0) point in view's viewport coordinates + +rect.deviceTransform(view->viewportTransform()).inverted().map(QPointF(100, 100)); +// returns view's viewport's (100, 100) coordinate in item coordinates +//! [5] + + +//! [6] +// Rotate an item 45 degrees around (0, 0). +item->rotate(45); + +// Rotate an item 45 degrees around (x, y). +item->setTransform(QTransform().translate(x, y).rotate(45).translate(-x, -y)); +//! [6] + + +//! [7] +// Scale an item by 3x2 from its origin +item->scale(3, 2); + +// Scale an item by 3x2 from (x, y) +item->setTransform(QTransform().translate(x, y).scale(3, 2).translate(-x, -y)); +//! [7] + + +//! [8] +QRectF CircleItem::boundingRect() const +{ + qreal penWidth = 1; + return QRectF(-radius - penWidth / 2, -radius - penWidth / 2, + diameter + penWidth, diameter + penWidth); +} +//! [8] + + +//! [9] +QPainterPath RoundItem::shape() const +{ + QPainterPath path; + path.addEllipse(boundingRect()); + return path; +} +//! [9] + + +//! [10] +void RoundRectItem::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + painter->drawRoundedRect(-10, -10, 20, 20, 5, 5); +} +//! [10] + + +//! [11] +static const int ObjectName = 0; + +QGraphicsItem *item = scene.itemAt(100, 50); +if (item->data(ObjectName).toString().isEmpty()) { + if (qgraphicsitem_cast<ButtonItem *>(item)) + item->setData(ObjectName, "Button"); +} +//! [11] + + +//! [12] +QGraphicsScene scene; +QGraphicsEllipseItem *ellipse = scene.addEllipse(QRectF(-10, -10, 20, 20)); +QGraphicsLineItem *line = scene.addLine(QLineF(-10, -10, 20, 20)); + +line->installSceneEventFilter(ellipse); +// line's events are filtered by ellipse's sceneEventFilter() function. + +ellipse->installSceneEventFilter(line); +// ellipse's events are filtered by line's sceneEventFilter() function. +//! [12] + + +//! [13] +void CustomItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +{ + QMenu menu; + QAction *removeAction = menu.addAction("Remove"); + QAction *markAction = menu.addAction("Mark"); + QAction *selectedAction = menu.exec(event->screenPos()); + // ... +} +//! [13] + + +//! [14] +CustomItem::CustomItem() +{ + setAcceptDrops(true); + ... +} + +void CustomItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) +{ + event->setAccepted(event->mimeData()->hasFormat("text/plain")); +} +//! [14] + + +//! [15] +QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemPositionChange && scene()) { + // value is the new position. + QPointF newPos = value.toPointF(); + QRectF rect = scene()->sceneRect(); + if (!rect.contains(newPos)) { + // Keep the item inside the scene rect. + newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left()))); + newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top()))); + return newPos; + } + } + return QGraphicsItem::itemChange(change, value); +} +//! [15] + + +//! [16] +void CircleItem::setRadius(qreal newRadius) +{ + if (radius != newRadius) { + prepareGeometryChange(); + radius = newRadius; + } +} +//! [16] + + +//! [17] +// Group all selected items together +QGraphicsItemGroup *group = scene->createItemGroup(scene->selecteditems()); + +// Destroy the group, and delete the group item +scene->destroyItemGroup(group); +//! [17] + + +//! [QGraphicsItem type] +class CustomItem : public QGraphicsItem +{ + ... + enum { Type = UserType + 1 }; + + int type() const + { + // Enable the use of qgraphicsitem_cast with this item. + return Type; + } + ... +}; +//! [QGraphicsItem type] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp new file mode 100644 index 0000000..77f7491 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicslinearlayout.cpp @@ -0,0 +1,13 @@ +//! [0] +QGraphicsScene scene; +QGraphicsWidget *textEdit = scene.addWidget(new QTextEdit); +QGraphicsWidget *pushButton = scene.addWidget(new QPushButton); + +QGraphicsLinearLayout *layout = new QGraphicsLinearLayout; +layout->addItem(textEdit); +layout->addItem(pushButton); + +QGraphicsWidget *form = new QGraphicsWidget; +form->setLayout(layout); +scene.addItem(form); +//! [0] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp new file mode 100644 index 0000000..6c62f26 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsproxywidget.cpp @@ -0,0 +1,47 @@ +//! [0] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QTabWidget *tabWidget = new QTabWidget; + + QGraphicsScene scene; + QGraphicsProxyWidget *proxy = scene.addWidget(tabWidget); + + QGraphicsView view(&scene); + view.show(); + + return app.exec(); +} +//! [0] + +//! [1] +QGroupBox *groupBox = new QGroupBox("Contact Details"); +QLabel *numberLabel = new QLabel("Telephone number"); +QLineEdit *numberEdit = new QLineEdit; + +QFormLayout *layout = new QFormLayout; +layout->addRow(numberLabel, numberEdit); +groupBox->setLayout(layout); + +QGraphicsScene scene; +QGraphicsProxyWidget *proxy = scene.addWidget(groupBox); + +QGraphicsView view(&scene); +view.show(); +//! [1] + +//! [2] +QGraphicsScene scene; + +QLineEdit *edit = new QLineEdit; +QGraphicsProxyWidget *proxy = scene.addWidget(edit); + +edit->isVisible(); // returns true +proxy->isVisible(); // also returns true + +edit->hide(); + +edit->isVisible(); // returns false +proxy->isVisible(); // also returns false +//! [2] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp new file mode 100644 index 0000000..20b0979 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsscene.cpp @@ -0,0 +1,82 @@ +//! [0] +QGraphicsScene scene; +scene.addText("Hello, world!"); + +QGraphicsView view(&scene); +view.show(); +//! [0] + + +//! [1] +QGraphicsScene scene; +scene.addItem(... +... +QPrinter printer(QPrinter::HighResolution); +printer.setPaperSize(QPrinter::A4); + +QPainter painter(&printer); +scene.render(&painter); +//! [1] + + +//! [2] +QSizeF segmentSize = sceneRect().size() / pow(2, depth - 1); +//! [2] + + +//! [3] +QGraphicsScene scene; +QGraphicsView view(&scene); +view.show(); + +// a blue background +scene.setBackgroundBrush(Qt::blue); + +// a gradient background +QRadialGradient gradient(0, 0, 10); +gradient.setSpread(QGradient::RepeatSpread); +scene.setBackgroundBrush(gradient); +//! [3] + + +//! [4] +QGraphicsScene scene; +QGraphicsView view(&scene); +view.show(); + +// a white semi-transparent foreground +scene.setForegroundBrush(QColor(255, 255, 255, 127)); + +// a grid foreground +scene.setForegroundBrush(QBrush(Qt::lightGray, Qt::CrossPattern)); +//! [4] + + +//! [5] +QRectF TileScene::rectForTile(int x, int y) const +{ + // Return the rectangle for the tile at position (x, y). + return QRectF(x * tileWidth, y * tileHeight, tileWidth, tileHeight); +} + +void TileScene::setTile(int x, int y, const QPixmap &pixmap) +{ + // Sets or replaces the tile at position (x, y) with pixmap. + if (x >= 0 && x < numTilesH && y >= 0 && y < numTilesV) { + tiles[y][x] = pixmap; + invalidate(rectForTile(x, y), BackgroundLayer); + } +} + +void TileScene::drawBackground(QPainter *painter, const QRectF &exposed) +{ + // Draws all tiles that intersect the exposed area. + for (int y = 0; y < numTilesV; ++y) { + for (int x = 0; x < numTilesH; ++x) { + QRectF rect = rectForTile(x, y); + if (exposed.intersects(rect)) + painter->drawPixmap(rect.topLeft(), tiles[y][x]); + } + } +} +//! [5] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp new file mode 100644 index 0000000..9b6c22e --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicssceneevent.cpp @@ -0,0 +1,5 @@ +//! [0] + +setDropAction(proposedAction()); + +//! [0] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp new file mode 100644 index 0000000..d22b872 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsview.cpp @@ -0,0 +1,92 @@ +//! [0] +QGraphicsScene scene; +scene.addText("Hello, world!"); + +QGraphicsView view(&scene); +view.show(); +//! [0] + + +//! [1] +QGraphicsScene scene; +scene.addRect(QRectF(-10, -10, 20, 20)); + +QGraphicsView view(&scene); +view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); +view.show(); +//! [1] + + +//! [2] +QGraphicsView view; +view.setBackgroundBrush(QImage(":/images/backgroundtile.png")); +view.setCacheMode(QGraphicsView::CacheBackground); +//! [2] + + +//! [3] +QGraphicsScene scene; +scene.addText("GraphicsView rotated clockwise"); + +QGraphicsView view(&scene); +view.rotate(90); // the text is rendered with a 90 degree clockwise rotation +view.show(); +//! [3] + + +//! [4] +QGraphicsScene scene; +scene.addItem(... +... + +QGraphicsView view(&scene); +view.show(); +... + +QPrinter printer(QPrinter::HighResolution); +printer.setPageSize(QPrinter::A4); +QPainter painter(&printer); + +// print, fitting the viewport contents into a full page +view.render(&painter); + +// print the upper half of the viewport into the lower. +// half of the page. +QRect viewport = view.viewport()->rect(); +view.render(&painter, + QRectF(0, printer.height() / 2, + printer.width(), printer.height() / 2), + viewport.adjusted(0, 0, 0, -viewport.height() / 2)); + +//! [4] + + +//! [5] +void CustomView::mousePressEvent(QMouseEvent *event) +{ + qDebug() << "There are" << items(event->pos()).size() + << "items at position" << mapToScene(event->pos()); +} +//! [5] + + +//! [6] +void CustomView::mousePressEvent(QMouseEvent *event) +{ + if (QGraphicsItem *item = itemAt(event->pos())) { + qDebug() << "You clicked on item" << item; + } else { + qDebug() << "You didn't click on an item."; + } +} +//! [6] + + +//! [7] +QGraphicsScene scene; +scene.addText("GraphicsView rotated clockwise"); + +QGraphicsView view(&scene); +view.rotate(90); // the text is rendered with a 90 degree clockwise rotation +view.show(); +//! [7] diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp new file mode 100644 index 0000000..06fa642 --- /dev/null +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicswidget.cpp @@ -0,0 +1,26 @@ +//! [0] +void MyGroupBoxWidget::initStyleOption(QStyleOption *option) const +{ + QGraphicsWidget::initStyleOption(option); + if (QStyleOptionGroupBox *box = qstyleoption_cast<QStyleOptionGroupBox *>(option)) { + // Add group box specific state. + box->flat = isFlat(); + ... + } +} +//! [0] + + +//! [1] +setTabOrder(a, b); // a to b +setTabOrder(b, c); // a to b to c +setTabOrder(c, d); // a to b to c to d +//! [1] + + +//! [2] +// WRONG +setTabOrder(c, d); // c to d +setTabOrder(a, b); // a to b AND c to d +setTabOrder(b, c); // a to b to c, but not c to d +//! [2] diff --git a/doc/src/snippets/code/src_gui_image_qbitmap.cpp b/doc/src/snippets/code/src_gui_image_qbitmap.cpp new file mode 100644 index 0000000..fa8317a --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qbitmap.cpp @@ -0,0 +1,4 @@ +//! [0] +uchar arrow_bits[] = { 0x3f, 0x1f, 0x0f, 0x1f, 0x3b, 0x71, 0xe0, 0xc0 }; +QBitmap bm(8, 8, arrow_bits, true); +//! [0] diff --git a/doc/src/snippets/code/src_gui_image_qicon.cpp b/doc/src/snippets/code/src_gui_image_qicon.cpp new file mode 100644 index 0000000..2b7c893 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qicon.cpp @@ -0,0 +1,22 @@ +//! [0] +QToolButton *button = new QToolButton; +button->setIcon(QIcon("open.xpm")); +//! [0] + + +//! [1] +button->setIcon(QIcon()); +//! [1] + + +//! [2] +void MyWidget::drawIcon(QPainter *painter, QPoint pos) +{ + QPixmap pixmap = icon.pixmap(QSize(22, 22), + isEnabled() ? QIcon::Normal + : QIcon::Disabled, + isOn() ? QIcon::On + : QIcon::Off); + painter->drawPixmap(pos, pixmap); +} +//! [2] diff --git a/doc/src/snippets/code/src_gui_image_qimage.cpp b/doc/src/snippets/code/src_gui_image_qimage.cpp new file mode 100644 index 0000000..3b7d8de --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qimage.cpp @@ -0,0 +1,42 @@ +//! [0] +QImage image(3, 3, QImage::Format_RGB32); +QRgb value; + +value = qRgb(189, 149, 39); // 0xffbd9527 +image.setPixel(1, 1, value); + +value = qRgb(122, 163, 39); // 0xff7aa327 +image.setPixel(0, 1, value); +image.setPixel(1, 0, value); + +value = qRgb(237, 187, 51); // 0xffedba31 +image.setPixel(2, 1, value); +//! [0] + + +//! [1] +QImage image(3, 3, QImage::Format_Indexed8); +QRgb value; + +value = qRgb(122, 163, 39); // 0xff7aa327 +image.setColor(0, value); + +value = qRgb(237, 187, 51); // 0xffedba31 +image.setColor(1, value); + +value = qRgb(189, 149, 39); // 0xffbd9527 +image.setColor(2, value); + +image.setPixel(0, 1, 0); +image.setPixel(1, 0, 0); +image.setPixel(1, 1, 2); +image.setPixel(2, 1, 1); +//! [1] + + +//! [2] +static const char * const start_xpm[] = { + "16 15 8 1", + "a c #cec6bd", +.... +//! [2] diff --git a/doc/src/snippets/code/src_gui_image_qimagereader.cpp b/doc/src/snippets/code/src_gui_image_qimagereader.cpp new file mode 100644 index 0000000..c645144 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qimagereader.cpp @@ -0,0 +1,26 @@ +//! [0] +QImageReader reader; +reader.setFormat("png"); // same as reader.setFormat("PNG"); +//! [0] + + +//! [1] +QImageReader reader("image.png"); +// reader.format() == "png" +//! [1] + + +//! [2] +QImage icon(64, 64, QImage::Format_RGB32); +QImageReader reader("icon_64x64.bmp"); +if (reader.read(&icon)) { + // Display icon +} +//! [2] + + +//! [3] +QImageReader reader(":/image.png"); +if (reader.supportsOption(QImageIOHandler::Size)) + qDebug() << "Size:" << reader.size(); +//! [3] diff --git a/doc/src/snippets/code/src_gui_image_qimagewriter.cpp b/doc/src/snippets/code/src_gui_image_qimagewriter.cpp new file mode 100644 index 0000000..d4a4118 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qimagewriter.cpp @@ -0,0 +1,19 @@ +//! [0] +QImageWriter writer; +writer.setFormat("png"); // same as writer.setFormat("PNG"); +//! [0] + + +//! [1] +QImage image("some/image.jpeg"); +QImageWriter writer("images/outimage.png", "png"); +writer.setText("Author", "John Smith"); +writer.write(image); +//! [1] + + +//! [2] +QImageWriter writer(fileName); +if (writer.supportsOption(QImageIOHandler::Description)) + writer.setText("Author", "John Smith"); +//! [2] diff --git a/doc/src/snippets/code/src_gui_image_qmovie.cpp b/doc/src/snippets/code/src_gui_image_qmovie.cpp new file mode 100644 index 0000000..77130e8 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qmovie.cpp @@ -0,0 +1,13 @@ +//! [0] +QLabel label; +QMovie *movie = new QMovie("animations/fire.gif"); + +label.setMovie(movie); +movie->start(); +//! [0] + + +//! [1] +QMovie movie("racecar.gif"); +movie.setSpeed(200); // 2x speed +//! [1] diff --git a/doc/src/snippets/code/src_gui_image_qpixmap.cpp b/doc/src/snippets/code/src_gui_image_qpixmap.cpp new file mode 100644 index 0000000..f86eeae --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qpixmap.cpp @@ -0,0 +1,12 @@ +//! [0] +static const char * const start_xpm[]={ + "16 15 8 1", + "a c #cec6bd", +.... +//! [0] + + +//! [1] +QPixmap myPixmap; +myPixmap->setMask(myPixmap->createHeuristicMask()); +//! [1] diff --git a/doc/src/snippets/code/src_gui_image_qpixmapcache.cpp b/doc/src/snippets/code/src_gui_image_qpixmapcache.cpp new file mode 100644 index 0000000..c4b6353 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qpixmapcache.cpp @@ -0,0 +1,21 @@ +//! [0] +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); +//! [0] + + +//! [1] +QPixmap pm; +if (!QPixmapCache::find("my_big_image", pm)) { + pm.load("bigimage.png"); + QPixmapCache::insert("my_big_image", pm); +} +painter->drawPixmap(0, 0, pm); +//! [1] diff --git a/doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp b/doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp new file mode 100644 index 0000000..e305109 --- /dev/null +++ b/doc/src/snippets/code/src_gui_image_qpixmapfilter.cpp @@ -0,0 +1,22 @@ +//! [0] +QPixmapColorizeFilter *myFilter = new QPixmapColorFilter; +myFilter->setColor(QColor(128, 0, 0)); +myFilter->draw(painter, QPoint(0, 0), originalPixmap); +//! [0] + +//! [1] +QPixmapConvolutionFilter *myFilter = new QPixmapConvolutionFilter; +qreal kernel[] = { + 0.0,-1.0, 0.0, + -1.0, 5.0,-1.0, + 0.0,-1.0, 0.0 + }; +myFilter->setConvolutionKernel(kernel, 3, 3); +myFilter->draw(painter, QPoint(0, 0), originalPixmap); +//! [1] + +//! [2] +QPixmapDropShadowFilter *myFilter = new QPixmapDropShadowFilter; +myFilter->draw(painter, QPoint(0, 0), originalPixmap); +//! [2] + diff --git a/doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp b/doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp new file mode 100644 index 0000000..9814c74 --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qabstractitemview.cpp @@ -0,0 +1,18 @@ +//! [0] +void MyView::resizeEvent(QResizeEvent *event) { + horizontalScrollBar()->setRange(0, realWidth - width()); + ... +} +//! [0] + +//! [1] +setIndexWidget(index, new QLineEdit); +... +setIndexWidget(index, new QTextEdit); +//! [1] + +//! [2] +QItemSelectionModel *m = view->selectionModel(); +view->setModel(new model); +delete m; +//! [2] diff --git a/doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp b/doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp new file mode 100644 index 0000000..ea5363c --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qdatawidgetmapper.cpp @@ -0,0 +1,23 @@ +//! [0] +QDataWidgetMapper *mapper = new QDataWidgetMapper; +mapper->setModel(model); +mapper->addMapping(mySpinBox, 0); +mapper->addMapping(myLineEdit, 1); +mapper->addMapping(myCountryChooser, 2); +mapper->toFirst(); +//! [0] + + +//! [1] +QDataWidgetMapper *mapper = new QDataWidgetMapper(); +mapper->setModel(myModel); +mapper->addMapping(nameLineEdit, 0); +mapper->addMapping(ageSpinBox, 1); +//! [1] + + +//! [2] +QDataWidgetMapper *mapper = new QDataWidgetMapper(); +connect(myTableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + mapper, SLOT(setCurrentModelIndex(QModelIndex))); +//! [2] diff --git a/doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp b/doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp new file mode 100644 index 0000000..29601bf --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qitemeditorfactory.cpp @@ -0,0 +1,23 @@ +//! [0] +Q_PROPERTY(QColor color READ color WRITE setColor USER true) +//! [0] + + +//! [1] +QItemEditorCreator<MyEditor> *itemCreator = + new QItemEditorCreator<MyEditor>("myProperty"); + +QItemEditorFactory *factory = new QItemEditorFactory; +//! [1] + + +//! [2] +QItemEditorFactory *editorFactory = new QItemEditorFactory; +QItemEditorCreatorBase *creator = new QStandardItemEditorCreator<MyFancyDateTimeEdit>(); +editorFactory->registerEditor(QVariant::DateType, creator); +//! [2] + + +//! [3] +Q_PROPERTY(QColor color READ color WRITE setColor USER true) +//! [3] diff --git a/doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp b/doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp new file mode 100644 index 0000000..9302fa6 --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qitemselectionmodel.cpp @@ -0,0 +1,10 @@ +//! [0] +QItemSelection *selection = new QItemSelection(topLeft, bottomRight); +//! [0] + + +//! [1] +QItemSelection *selection = new QItemSelection(); +... +selection->select(topLeft, bottomRight); +//! [1] diff --git a/doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp b/doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp new file mode 100644 index 0000000..7480ccd --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qstandarditemmodel.cpp @@ -0,0 +1,42 @@ +//! [0] +QStandardItemModel model(4, 4); +for (int row = 0; row < 4; ++row) { + for (int column = 0; column < 4; ++column) { + QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column)); + model.setItem(row, column, item); + } +} +//! [0] + + +//! [1] +QStandardItemModel model; +QStandardItem *parentItem = model.invisibleRootItem(); +for (int i = 0; i < 4; ++i) { + QStandardItem *item = new QStandardItem(QString("item %0").arg(i)); + parentItem->appendRow(item); + parentItem = item; +} +//! [1] + + +//! [2] +QTreeView *treeView = new QTreeView(this); +treeView->setModel(myStandardItemModel); +connect(treeView, SIGNAL(clicked(QModelIndex)), + this, SLOT(clicked(QModelIndex))); +//! [2] + + +//! [3] +void MyWidget::clicked(const QModelIndex &index) +{ + QStandardItem *item = myStandardItemModel->itemFromIndex(index); + // Do stuff with the item ... +} +//! [3] + + +//! [4] +treeView->scrollTo(item->index()); +//! [4] diff --git a/doc/src/snippets/code/src_gui_itemviews_qtablewidget.cpp b/doc/src/snippets/code/src_gui_itemviews_qtablewidget.cpp new file mode 100644 index 0000000..80adc0b --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qtablewidget.cpp @@ -0,0 +1,5 @@ +//! [0] +setCellWidget(index, new QLineEdit); +... +setCellWidget(index, new QTextEdit); +//! [0] diff --git a/doc/src/snippets/code/src_gui_itemviews_qtreewidget.cpp b/doc/src/snippets/code/src_gui_itemviews_qtreewidget.cpp new file mode 100644 index 0000000..ea0478e --- /dev/null +++ b/doc/src/snippets/code/src_gui_itemviews_qtreewidget.cpp @@ -0,0 +1,8 @@ +//! [0] +QTreeWidget *treeWidget = new QTreeWidget(); +treeWidget->setColumnCount(1); +QList<QTreeWidgetItem *> items; +for (int i = 0; i < 10; ++i) + items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("item: %1").arg(i)))); +treeWidget->insertTopLevelItems(0, items); +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qaction.cpp b/doc/src/snippets/code/src_gui_kernel_qaction.cpp new file mode 100644 index 0000000..b052feb --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qaction.cpp @@ -0,0 +1,9 @@ +//! [0] +QApplication app(argc, argv); +app.setAttribute(Qt::AA_DontShowIconsInMenus); // Icons are *no longer shown* in menus +// ... +QAction *myAction = new QAction(); +// ... +myAction->setIcon(SomeIcon); +myAction->setIconVisibleInMenu(true); // Icon *will* be shown in menus for *this* action. +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qapplication.cpp b/doc/src/snippets/code/src_gui_kernel_qapplication.cpp new file mode 100644 index 0000000..bfb09e3 --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qapplication.cpp @@ -0,0 +1,143 @@ +//! [0] +int main(int argc, char **argv) +{ +#ifdef Q_WS_X11 + bool useGUI = getenv("DISPLAY") != 0; +#else + bool useGUI = true; +#endif + QApplication app(argc, argv, useGUI); + + if (useGUI) { + // start GUI version + ... + } else { + // start non-GUI version + ... + } + return app.exec(); +} +//! [0] + + +//! [1] +QApplication::setStyle(new QWindowsStyle); +//! [1] + + +//! [2] +int main(int argc, char *argv[]) +{ + QApplication::setColorSpec(QApplication::ManyColor); + QApplication app(argc, argv); + ... + return app.exec(); +} +//! [2] + + +//! [3] +QSize MyWidget::sizeHint() const +{ + return QSize(80, 25).expandedTo(QApplication::globalStrut()); +} +//! [3] + + +//! [4] +void showAllHiddenTopLevelWidgets() +{ + foreach (QWidget *widget, QApplication::topLevelWidgets()) { + if (widget->isHidden()) + widget->show(); + } +} +//! [4] + + +//! [5] +void updateAllWidgets() +{ + foreach (QWidget *widget, QApplication::allWidgets()) + widget->update(); +} +//! [5] + + +//! [6] +int main(int argc, char *argv[]) +{ + QApplication::setDesktopSettingsAware(false); + QApplication app(argc, argv); + ... + return app.exec(); +} +//! [6] + + +//! [7] +if ((startPos - currentPos).manhattanLength() >= + QApplication::startDragDistance()) + startTheDrag(); +//! [7] + + +//! [8] +void MyApplication::commitData(QSessionManager& manager) +{ + if (manager.allowsInteraction()) { + int ret = QMessageBox::warning( + mainWindow, + tr("My Application"), + tr("Save changes to document?"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + + switch (ret) { + case QMessageBox::Save: + manager.release(); + if (!saveDocument()) + manager.cancel(); + break; + case QMessageBox::Discard: + break; + case QMessageBox::Cancel: + default: + manager.cancel(); + } + } else { + // we did not get permission to interact, then + // do something reasonable instead + } +} +//! [8] + + +//! [9] +appname -session id +//! [9] + + +//! [10] +foreach (QString command, mySession.restartCommand()) + do_something(command); +//! [10] + + +//! [11] +foreach (QString command, mySession.discardCommand()) + do_something(command); +//! [11] + + +//! [12] +QWidget *widget = qApp->widgetAt(x, y); +if (widget) + widget = widget->window(); +//! [12] + + +//! [13] +QWidget *widget = qApp->widgetAt(point); +if (widget) + widget = widget->window(); +//! [13] diff --git a/doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp b/doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp new file mode 100644 index 0000000..2782200 --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp @@ -0,0 +1,5 @@ +//! [0] +QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); +calculateHugeMandelbrot(); // lunch time... +QApplication::restoreOverrideCursor(); +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qclipboard.cpp b/doc/src/snippets/code/src_gui_kernel_qclipboard.cpp new file mode 100644 index 0000000..5d1cf2b --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qclipboard.cpp @@ -0,0 +1,13 @@ +//! [0] +QClipboard *clipboard = QApplication::clipboard(); +QString originalText = clipboard->text(); +... +clipboard->setText(newText); +//! [0] + + +//! [1] +QMimeData *data = new QMimeData; +data->setImageData(image); +clipboard->setMimeData(data, mode); +//! [1] diff --git a/doc/src/snippets/code/src_gui_kernel_qevent.cpp b/doc/src/snippets/code/src_gui_kernel_qevent.cpp new file mode 100644 index 0000000..cd3d019 --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qevent.cpp @@ -0,0 +1,14 @@ +//! [0] +void MyWidget::wheelEvent(QWheelEvent *event) +{ + int numDegrees = event->delta() / 8; + int numSteps = numDegrees / 15; + + if (event->orientation() == Qt::Horizontal) { + scrollHorizontally(numSteps); + } else { + scrollVertically(numSteps); + } + event->accept(); +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qformlayout.cpp b/doc/src/snippets/code/src_gui_kernel_qformlayout.cpp new file mode 100644 index 0000000..aed6956 --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qformlayout.cpp @@ -0,0 +1,36 @@ +//! [0] +QFormLayout *formLayout = new QFormLayout; +formLayout->addRow(tr("&Name:"), nameLineEdit); +formLayout->addRow(tr("&Email:"), emailLineEdit); +formLayout->addRow(tr("&Age:"), ageSpinBox); +setLayout(formLayout); +//! [0] + + +//! [1] +nameLabel = new QLabel(tr("&Name:")); +nameLabel->setBuddy(nameLineEdit); + +emailLabel = new QLabel(tr("&Name:")); +emailLabel->setBuddy(emailLineEdit); + +ageLabel = new QLabel(tr("&Name:")); +ageLabel->setBuddy(ageSpinBox); + +QGridLayout *gridLayout = new QGridLayout; +gridLayout->addWidget(nameLabel, 0, 0); +gridLayout->addWidget(nameLineEdit, 0, 1); +gridLayout->addWidget(emailLabel, 1, 0); +gridLayout->addWidget(emailLineEdit, 1, 1); +gridLayout->addWidget(ageLabel, 2, 0); +gridLayout->addWidget(ageSpinBox, 2, 1); +setLayout(gridLayout); +//! [1] + + +//! [2] +formLayout->setRowWrapPolicy(QFormLayout::DontWrapRows); +formLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint); +formLayout->setFormAlignment(Qt::AlignHCenter | Qt::AlignTop); +formLayout->setLabelAlignment(Qt::AlignLeft); +//! [2] diff --git a/doc/src/snippets/code/src_gui_kernel_qkeysequence.cpp b/doc/src/snippets/code/src_gui_kernel_qkeysequence.cpp new file mode 100644 index 0000000..a5c734d --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qkeysequence.cpp @@ -0,0 +1,19 @@ +//! [0] +QKeySequence(QKeySequence::Print); +QKeySequence(tr("Ctrl+P")); +QKeySequence(tr("Ctrl+p")); +QKeySequence(Qt::CTRL + Qt::Key_P); +//! [0] + + +//! [1] +QKeySequence(tr("Ctrl+X, Ctrl+C")); +QKeySequence(Qt::CTRL + Qt::Key_X, Qt::CTRL + Qt::Key_C); +//! [1] + + +//! [2] +QMenu *file = new QMenu(this); +file->addAction(tr("&Open..."), this, SLOT(open()), + QKeySequence(tr("Ctrl+O", "File|Open"))); +//! [2] diff --git a/doc/src/snippets/code/src_gui_kernel_qlayout.cpp b/doc/src/snippets/code/src_gui_kernel_qlayout.cpp new file mode 100644 index 0000000..26d178f --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qlayout.cpp @@ -0,0 +1,27 @@ +//! [0] +static void paintLayout(QPainter *painter, QLayoutItem *item) +{ + QLayout *layout = item->layout(); + if (layout) { + for (int i = 0; i < layout->count(); ++i) + paintLayout(painter, layout->itemAt(i)); + } + painter->drawRect(item->geometry()); +} + +void MyWidget::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + if (layout()) + paintLayout(&painter, layout()); +} +//! [0] + + +//! [1] +QLayoutItem *child; +while ((child = layout->takeAt(0)) != 0) { + ... + delete child; +} +//! [1] diff --git a/doc/src/snippets/code/src_gui_kernel_qlayoutitem.cpp b/doc/src/snippets/code/src_gui_kernel_qlayoutitem.cpp new file mode 100644 index 0000000..db6438e --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qlayoutitem.cpp @@ -0,0 +1,13 @@ +//! [0] +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; +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qshortcut.cpp b/doc/src/snippets/code/src_gui_kernel_qshortcut.cpp new file mode 100644 index 0000000..b5fdf95 --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qshortcut.cpp @@ -0,0 +1,15 @@ +//! [0] +shortcut = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")), + parent); +//! [0] + + +//! [1] +setKey(0); // no signal emitted +setKey(QKeySequence()); // no signal emitted +setKey(0x3b1); // Greek letter alpha +setKey(Qt::Key_D); // 'd', e.g. to delete +setKey('q'); // 'q', e.g. to quit +setKey(Qt::CTRL + Qt::Key_P); // Ctrl+P, e.g. to print document +setKey("Ctrl+P"); // Ctrl+P, e.g. to print document +//! [1] diff --git a/doc/src/snippets/code/src_gui_kernel_qshortcutmap.cpp b/doc/src/snippets/code/src_gui_kernel_qshortcutmap.cpp new file mode 100644 index 0000000..6a85c3e --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qshortcutmap.cpp @@ -0,0 +1,3 @@ +//! [0] +key = QKeySequence(); +//! [0] diff --git a/doc/src/snippets/code/src_gui_kernel_qsound.cpp b/doc/src/snippets/code/src_gui_kernel_qsound.cpp new file mode 100644 index 0000000..bdbd1ce --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qsound.cpp @@ -0,0 +1,9 @@ +//! [0] +QSound::play("mysounds/bells.wav"); +//! [0] + + +//! [1] +QSound bells("mysounds/bells.wav"); +bells.play(); +//! [1] diff --git a/doc/src/snippets/code/src_gui_kernel_qwidget.cpp b/doc/src/snippets/code/src_gui_kernel_qwidget.cpp new file mode 100644 index 0000000..4285edd --- /dev/null +++ b/doc/src/snippets/code/src_gui_kernel_qwidget.cpp @@ -0,0 +1,97 @@ +//! [0] +w->setWindowState(w->windowState() ^ Qt::WindowFullScreen); +//! [0] + + +//! [1] +w->setWindowState(w->windowState() & ~Qt::WindowMinimized | Qt::WindowActive); +//! [1] + + +//! [2] +width = baseSize().width() + i * sizeIncrement().width(); +height = baseSize().height() + j * sizeIncrement().height(); +//! [2] + + +//! [3] +aWidget->window()->setWindowTitle("New Window Title"); +//! [3] + + +//! [4] +QFont font("Helvetica", 12, QFont::Bold); +setFont(font); +//! [4] + + +//! [5] +QFont font; +font.setBold(false); +setFont(font); +//! [5] + + +//! [6] +setCursor(Qt::IBeamCursor); +//! [6] + + +//! [7] +QPixmap pixmap(widget->size()); +widget->render(&pixmap); +//! [7] + + +//! [8] +QPainter painter(this); +... +painter.end(); +myWidget->render(this); +//! [8] + + +//! [9] +setTabOrder(a, b); // a to b +setTabOrder(b, c); // a to b to c +setTabOrder(c, d); // a to b to c to d +//! [9] + + +//! [10] +// WRONG +setTabOrder(c, d); // c to d +setTabOrder(a, b); // a to b AND c to d +setTabOrder(b, c); // a to b to c, but not c to d +//! [10] + + +//! [11] +void MyWidget::closeEvent(QCloseEvent *event) +{ + QSettings settings("MyCompany", "MyApp"); + settings.setValue("geometry", saveGeometry()); + QWidget::closeEvent(event); +} +//! [11] + + +//! [12] +QSettings settings("MyCompany", "MyApp"); +myWidget->restoreGeometry(settings.value("myWidget/geometry").toByteArray()); +//! [12] + + +//! [13] +setUpdatesEnabled(false); +bigVisualChanges(); +setUpdatesEnabled(true); +//! [13] + + +//! [14] +... +extern void qt_x11_set_global_double_buffer(bool); +qt_x11_set_global_double_buffer(false); +... +//! [14] diff --git a/doc/src/snippets/code/src_gui_painting_qbrush.cpp b/doc/src/snippets/code/src_gui_painting_qbrush.cpp new file mode 100644 index 0000000..8cb5310 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qbrush.cpp @@ -0,0 +1,11 @@ +//! [0] +QPainter painter(this); + +painter.setBrush(Qt::cyan); +painter.setPen(Qt::darkCyan); +painter.drawRect(0, 0, 100,100); + +painter.setBrush(Qt::NoBrush); +painter.setPen(Qt::darkGreen); +painter.drawRect(40, 40, 100, 100); +//! [0] diff --git a/doc/src/snippets/code/src_gui_painting_qcolor.cpp b/doc/src/snippets/code/src_gui_painting_qcolor.cpp new file mode 100644 index 0000000..c21e589 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qcolor.cpp @@ -0,0 +1,9 @@ +//! [0] +// Specify semi-transparent red +painter.setBrush(QColor(255, 0, 0, 127)); +painter.drawRect(0, 0, width()/2, height()); + +// Specify semi-transparent blue +painter.setBrush(QColor(0, 0, 255, 127)); +painter.drawRect(0, 0, width(), height()/2); +//! [0] diff --git a/doc/src/snippets/code/src_gui_painting_qdrawutil.cpp b/doc/src/snippets/code/src_gui_painting_qdrawutil.cpp new file mode 100644 index 0000000..7e94d59 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qdrawutil.cpp @@ -0,0 +1,58 @@ +//! [0] +QFrame frame: +frame.setFrameStyle(QFrame::HLine | QFrame::Sunken); +//! [0] + + +//! [1] +QFrame frame: +frame.setFrameStyle(QFrame::Box | QFrame::Raised); +//! [1] + + +//! [2] +QFrame frame: +frame.setFrameStyle( QFrame::Panel | QFrame::Sunken); +//! [2] + + +//! [3] +QFrame frame: +frame.setFrameStyle(QFrame::WinPanel | QFrame::Raised); +//! [3] + + +//! [4] +QFrame frame: +frame.setFrameStyle(QFrame::Box | QFrame::Plain); +//! [4] + + +//! [5] +QFrame frame: +frame.setFrameStyle(QFrame::HLine | QFrame::Sunken); +//! [5] + + +//! [6] +QFrame frame: +frame.setFrameStyle(QFrame::Box | QFrame::Raised); +//! [6] + + +//! [7] +QFrame frame: +frame.setFrameStyle( QFrame::Panel | QFrame::Sunken); +//! [7] + + +//! [8] +QFrame frame: +frame.setFrameStyle(QFrame::WinPanel | QFrame::Raised); +//! [8] + + +//! [9] +QFrame frame: +frame.setFrameStyle(QFrame::Box | QFrame::Plain); +//! [9] diff --git a/doc/src/snippets/code/src_gui_painting_qmatrix.cpp b/doc/src/snippets/code/src_gui_painting_qmatrix.cpp new file mode 100644 index 0000000..4a8a427 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qmatrix.cpp @@ -0,0 +1,22 @@ +//! [0] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +//! [0] + + +//! [1] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +//! [1] + + +//! [2] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +//! [2] + + +//! [3] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +//! [3] diff --git a/doc/src/snippets/code/src_gui_painting_qpainter.cpp b/doc/src/snippets/code/src_gui_painting_qpainter.cpp new file mode 100644 index 0000000..611daae --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qpainter.cpp @@ -0,0 +1,202 @@ +//! [0] +void SimpleExampleWidget::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + painter.setPen(Qt::blue); + painter.setFont(QFont("Arial", 30)); + painter.drawText(rect(), Qt::AlignCenter, "Qt"); +} +//! [0] + + +//! [1] +void MyWidget::paintEvent(QPaintEvent *) +{ + QPainter p; + p.begin(this); + p.drawLine(...); // drawing code + p.end(); +} +//! [1] + + +//! [2] +void MyWidget::paintEvent(QPaintEvent *) +{ + QPainter p(this); + p.drawLine(...); // drawing code +} +//! [2] + + +//! [3] +painter->begin(0); // impossible - paint device cannot be 0 + +QPixmap image(0, 0); +painter->begin(&image); // impossible - image.isNull() == true; + +painter->begin(myWidget); +painter2->begin(myWidget); // impossible - only one painter at a time +//! [3] + + +//! [4] +void QPainter::rotate(qreal angle) +{ + QMatrix matrix; + matrix.rotate(angle); + setWorldMatrix(matrix, true); +} +//! [4] + + +//! [5] +QPainterPath path; +path.moveTo(20, 80); +path.lineTo(20, 30); +path.cubicTo(80, 0, 50, 50, 80, 80); + +QPainter painter(this); +painter.drawPath(path); +//! [5] + + +//! [6] +QLineF line(10.0, 80.0, 90.0, 20.0); + +QPainter(this); +painter.drawLine(line); +//! [6] + + +//! [7] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); + +QPainter painter(this); +painter.drawRect(rectangle); +//! [7] + + +//! [8] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); + +QPainter painter(this); +painter.drawRoundedRect(rectangle, 20.0, 15.0); +//! [8] + + +//! [9] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); + +QPainter painter(this); +painter.drawEllipse(rectangle); +//! [9] + + +//! [10] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); +int startAngle = 30 * 16; +int spanAngle = 120 * 16; + +QPainter painter(this); +painter.drawArc(rectangle, startAngle, spanAngle); +//! [10] + + +//! [11] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); +int startAngle = 30 * 16; +int spanAngle = 120 * 16; + +QPainter painter(this); +painter.drawPie(rectangle, startAngle, spanAngle); +//! [11] + + +//! [12] +QRectF rectangle(10.0, 20.0, 80.0, 60.0); +int startAngle = 30 * 16; +int spanAngle = 120 * 16; + +QPainter painter(this); +painter.drawChord(rect, startAngle, spanAngle); +//! [12] + + +//! [13] +static const QPointF points[3] = { + QPointF(10.0, 80.0), + QPointF(20.0, 10.0), + QPointF(80.0, 30.0), +}; + +QPainter painter(this); +painter.drawPolyline(points, 3); +//! [13] + + +//! [14] +static const QPointF points[4] = { + QPointF(10.0, 80.0), + QPointF(20.0, 10.0), + QPointF(80.0, 30.0), + QPointF(90.0, 70.0) +}; + +QPainter painter(this); +painter.drawPolygon(points, 4); +//! [14] + + +//! [15] +static const QPointF points[4] = { + QPointF(10.0, 80.0), + QPointF(20.0, 10.0), + QPointF(80.0, 30.0), + QPointF(90.0, 70.0) +}; + +QPainter painter(this); +painter.drawConvexPolygon(points, 4); +//! [15] + + +//! [16] +QRectF target(10.0, 20.0, 80.0, 60.0); +QRectF source(0.0, 0.0, 70.0, 40.0); +QPixmap pixmap(":myPixmap.png"); + +QPainter(this); +painter.drawPixmap(target, image, source); +//! [16] + + +//! [17] +QPainter painter(this); +painter.drawText(rect, Qt::AlignCenter, tr("Qt by\nTrolltech")); +//! [17] + + +//! [18] +QPicture picture; +QPointF point(10.0, 20.0) +picture.load("drawing.pic"); + +QPainter painter(this); +painter.drawPicture(0, 0, picture); +//! [18] + + +//! [19] +fillRect(rectangle, background()). +//! [19] + + +//! [20] +QRectF target(10.0, 20.0, 80.0, 60.0); +QRectF source(0.0, 0.0, 70.0, 40.0); +QImage image(":/images/myImage.png"); + +QPainter painter(this); +painter.drawImage(target, image, source); +//! [20] diff --git a/doc/src/snippets/code/src_gui_painting_qpainterpath.cpp b/doc/src/snippets/code/src_gui_painting_qpainterpath.cpp new file mode 100644 index 0000000..f5d1e8b --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qpainterpath.cpp @@ -0,0 +1,109 @@ +//! [0] +QPainterPath path; +path.addRect(20, 20, 60, 60); + +path.moveTo(0, 0); +path.cubicTo(99, 0, 50, 50, 99, 99); +path.cubicTo(0, 99, 50, 50, 0, 0); + +QPainter painter(this); +painter.fillRect(0, 0, 100, 100, Qt::white); +painter.setPen(QPen(QColor(79, 106, 25), 1, Qt::SolidLine, + Qt::FlatCap, Qt::MiterJoin)); +painter.setBrush(QColor(122, 163, 39)); + +painter.drawPath(path); +//! [0] + + +//! [1] +QLinearGradient myGradient; +QPen myPen; + +QPainterPath myPath; +myPath.cubicTo(c1, c2, endPoint); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [1] + + +//! [2] +QLinearGradient myGradient; +QPen myPen; + +QPointF center, startPoint; + +QPainterPath myPath; +myPath.moveTo(center); +myPath.arcTo(boundingRect, startAngle, + sweepLength); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [2] + + +//! [3] +QLinearGradient myGradient; +QPen myPen; +QRectF myRectangle; + +QPainterPath myPath; +myPath.addRect(myRectangle); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [3] + + +//! [4] +QLinearGradient myGradient; +QPen myPen; +QPolygonF myPolygon; + +QPainterPath myPath; +myPath.addPolygon(myPolygon); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [4] + + +//! [5] +QLinearGradient myGradient; +QPen myPen; +QRectF boundingRectangle; + +QPainterPath myPath; +myPath.addEllipse(boundingRectangle); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [5] + + +//! [6] +QLinearGradient myGradient; +QPen myPen; +QFont myFont; +QPointF baseline(x, y); + +QPainterPath myPath; +myPath.addText(baseline, myFont, tr("Qt")); + +QPainter painter(this); +painter.setBrush(myGradient); +painter.setPen(myPen); +painter.drawPath(myPath); +//! [6] diff --git a/doc/src/snippets/code/src_gui_painting_qpen.cpp b/doc/src/snippets/code/src_gui_painting_qpen.cpp new file mode 100644 index 0000000..538fa09 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qpen.cpp @@ -0,0 +1,41 @@ +//! [0] +QPainter painter(this); +QPen pen(Qt::green, 3, Qt::DashDotLine, Qt::RoundCap, Qt::RoundJoin); +painter.setPen(pen); +//! [0] + + +//! [1] +QPainter painter(this); +QPen pen(); // creates a default pen + +pen.setStyle(Qt::DashDotLine); +pen.setWidth(3); +pen.setBrush(Qt::green); +pen.setCapStyle(Qt::RoundCap); +pen.setJoinStyle(Qt::RoundJoin); + +painter.setPen(pen); +//! [1] + + +//! [2] +QPen pen; +QVector<qreal> dashes; +qreal space = 4; + +dashes << 1 << space << 3 << space << 9 << space + << 27 << space << 9; + +pen.setDashPattern(dashes); +//! [2] + + +//! [3] +QPen pen; +QVector<qreal> dashes; +qreal space = 4; +dashes << 1 << space << 3 << space << 9 << space + << 27 << space << 9; +pen.setDashPattern(dashes); +//! [3] diff --git a/doc/src/snippets/code/src_gui_painting_qregion.cpp b/doc/src/snippets/code/src_gui_painting_qregion.cpp new file mode 100644 index 0000000..6c5dfa5 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qregion.cpp @@ -0,0 +1,13 @@ +//! [0] +void MyWidget::paintEvent(QPaintEvent *) +{ + 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.intersected(r2); // r3: intersection + + QPainter painter(this); + painter.setClipRegion(r3); + ... // paint clipped graphics +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_painting_qregion_unix.cpp b/doc/src/snippets/code/src_gui_painting_qregion_unix.cpp new file mode 100644 index 0000000..50771ef --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qregion_unix.cpp @@ -0,0 +1,18 @@ +//! [0] +QRegion r1(10, 10, 20, 20); +r1.isNull(); // false +r1.isEmpty(); // false + +QRegion r2(40, 40, 20, 20); +QRegion r3; +r3.isNull(); // true +r3.isEmpty(); // true + +r3 = r1.intersected(r2); // r3: intersection of r1 and r2 +r3.isNull(); // false +r3.isEmpty(); // true + +r3 = r1.united(r2); // r3: union of r1 and r2 +r3.isNull(); // false +r3.isEmpty(); // false +//! [0] diff --git a/doc/src/snippets/code/src_gui_painting_qtransform.cpp b/doc/src/snippets/code/src_gui_painting_qtransform.cpp new file mode 100644 index 0000000..91b1e94 --- /dev/null +++ b/doc/src/snippets/code/src_gui_painting_qtransform.cpp @@ -0,0 +1,42 @@ +//! [0] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +if (is not affine) { + w' = m13*x + m23*y + m33 + x' /= w' + y' /= w' +} +//! [0] + + +//! [1] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +if (is not affine) { + w' = m13*x + m23*y + m33 + x' /= w' + y' /= w' +} +//! [1] + + +//! [2] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +if (is not affine) { + w' = m13*x + m23*y + m33 + x' /= w' + y' /= w' +} +//! [2] + + +//! [3] +x' = m11*x + m21*y + dx +y' = m22*y + m12*x + dy +if (is not affine) { + w' = m13*x + m23*y + m33 + x' /= w' + y' /= w' +} +//! [3] diff --git a/doc/src/snippets/code/src_gui_styles_qstyle.cpp b/doc/src/snippets/code/src_gui_styles_qstyle.cpp new file mode 100644 index 0000000..a78a6c8 --- /dev/null +++ b/doc/src/snippets/code/src_gui_styles_qstyle.cpp @@ -0,0 +1,8 @@ +//! [0] +./myapplication -style motif +//! [0] + + +//! [1] +./myapplication -style custom +//! [1] diff --git a/doc/src/snippets/code/src_gui_styles_qstyleoption.cpp b/doc/src/snippets/code/src_gui_styles_qstyleoption.cpp new file mode 100644 index 0000000..bf0c670 --- /dev/null +++ b/doc/src/snippets/code/src_gui_styles_qstyleoption.cpp @@ -0,0 +1,14 @@ +//! [0] +int MyStyle::styleHint(StyleHint stylehint, const QStyleOption *opt, + const QWidget *widget, QStyleHintReturn* returnData) const; +{ + if (stylehint == SH_RubberBand_Mask) { + const QStyleHintReturnMask *maskReturn = + qstyleoption_cast<const QStyleHintReturnMask *>(hint); + if (maskReturn) { + ... + } + } + ... +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_text_qfont.cpp b/doc/src/snippets/code/src_gui_text_qfont.cpp new file mode 100644 index 0000000..c74772c --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qfont.cpp @@ -0,0 +1,27 @@ +//! [0] +QFont serifFont("Times", 10, QFont::Bold); +QFont sansFont("Helvetica [Cronyx]", 12); +//! [0] + + +//! [1] +QFont f("Helvetica"); +//! [1] + + +//! [2] +QFont f("Helvetica [Cronyx]"); +//! [2] + + +//! [3] +QFontInfo info(f1); +QString family = info.family(); +//! [3] + + +//! [4] +QFontMetrics fm(f1); +int textWidthInPixels = fm.width("How many pixels wide is this text?"); +int textHeightInPixels = fm.height(); +//! [4] diff --git a/doc/src/snippets/code/src_gui_text_qfontmetrics.cpp b/doc/src/snippets/code/src_gui_text_qfontmetrics.cpp new file mode 100644 index 0000000..d7b17ab --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qfontmetrics.cpp @@ -0,0 +1,14 @@ +//! [0] +QFont font("times", 24); +QFontMetrics fm(font); +int pixelsWide = fm.width("What's the width of this text?"); +int pixelsHigh = fm.height(); +//! [0] + + +//! [1] +QFont font("times", 24); +QFontMetricsF fm(font); +qreal pixelsWide = fm.width("What's the width of this text?"); +qreal pixelsHigh = fm.height(); +//! [1] diff --git a/doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp b/doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp new file mode 100644 index 0000000..5dd2e0d --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp @@ -0,0 +1,86 @@ +//! [0] +QTextEdit *editor = new QTextEdit; +MyHighlighter *highlighter = new MyHighlighter(editor->document()); +//! [0] + + +//! [1] +void MyHighlighter::highlightBlock(const QString &text) +{ + QTextCharFormat myClassFormat; + myClassFormat.setFontWeight(QFont::Bold); + myClassFormat.setForeground(Qt::darkMagenta); + QString pattern = "\\bMy[A-Za-z]+\\b"; + + QRegExp expression(pattern); + int index = text.indexOf(expression); + while (index >= 0) { + int length = expression.matchedLength(); + setFormat(index, length, myClassFormat); + index = text.indexOf(expression, index + length); + } +} +//! [1] + + +//! [2] +QTextCharFormat multiLineCommentFormat; +multiLineCommentFormat.setForeground(Qt::red); + +QRegExp startExpression("/\\*"); +QRegExp endExpression("\\*/"); + +setCurrentBlockState(0); + +int startIndex = 0; +if (previousBlockState() != 1) + startIndex = text.indexOf(startExpression); + +while (startIndex >= 0) { + int endIndex = text.indexOf(endExpression, startIndex); + int commentLength; + if (endIndex == -1) { + setCurrentBlockState(1); + commentLength = text.length() - startIndex; + } else { + commentLength = endIndex - startIndex + + endExpression.matchedLength(); + } + setFormat(startIndex, commentLength, multiLineCommentFormat); + startIndex = text.indexOf(startExpression, + startIndex + commentLength); +} +//! [2] + + +//! [3] +void MyHighlighter::highlightBlock(const QString &text) +{ + QTextCharFormat myClassFormat; + myClassFormat.setFontWeight(QFont::Bold); + myClassFormat.setForeground(Qt::darkMagenta); + QString pattern = "\\bMy[A-Za-z]+\\b"; + + QRegExp expression(pattern); + int index = text.indexOf(expression); + while (index >= 0) { + int length = expression.matchedLength(); + setFormat(index, length, myClassFormat); + index = text.indexOf(expression, index + length); + } + } +//! [3] + + +//! [4] +struct ParenthesisInfo +{ + QChar char; + int position; +}; + +struct BlockData : public QTextBlockUserData +{ + QVector<ParenthesisInfo> parentheses; +}; +//! [4] diff --git a/doc/src/snippets/code/src_gui_text_qtextcursor.cpp b/doc/src/snippets/code/src_gui_text_qtextcursor.cpp new file mode 100644 index 0000000..19c60b9 --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qtextcursor.cpp @@ -0,0 +1,40 @@ +//! [0] +cursor.clearSelection(); +cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor); +cursor.insertText("Hello World"); +//! [0] + + +//! [1] +QImage img = ... +textDocument->addResource(QTextDocument::ImageResource, QUrl("myimage"), img); +cursor.insertImage("myimage"); +//! [1] + + +//! [2] +QTextCursor cursor(textDocument); +cursor.beginEditBlock(); +cursor.insertText("Hello"); +cursor.insertText("World"); +cursor.endEditBlock(); + +textDocument->undo(); +//! [2] + + +//! [3] +QTextCursor cursor(textDocument); +cursor.beginEditBlock(); +cursor.insertText("Hello"); +cursor.insertText("World"); +cursor.endEditBlock(); + +... + +cursor.joinPreviousEditBlock(); +cursor.insertText("Hey"); +cursor.endEditBlock(); + +textDocument->undo(); +//! [3] diff --git a/doc/src/snippets/code/src_gui_text_qtextdocument.cpp b/doc/src/snippets/code/src_gui_text_qtextdocument.cpp new file mode 100644 index 0000000..60840f7 --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qtextdocument.cpp @@ -0,0 +1,10 @@ +//! [0] +QString plain = "#include <QtCore>" +QString html = Qt::escape(plain); +// html == "#include <QtCore>" +//! [0] + + +//! [1] +<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>... +//! [1] diff --git a/doc/src/snippets/code/src_gui_text_qtextlayout.cpp b/doc/src/snippets/code/src_gui_text_qtextlayout.cpp new file mode 100644 index 0000000..548bb78 --- /dev/null +++ b/doc/src/snippets/code/src_gui_text_qtextlayout.cpp @@ -0,0 +1,24 @@ +//! [0] +int leading = fontMetrics.leading(); +qreal height = 0; +qreal widthUsed = 0; +textLayout.beginLayout(); +while (1) { + QTextLine line = textLayout.createLine(); + if (!line.isValid()) + break; + + line.setLineWidth(lineWidth); + height += leading; + line.setPosition(QPointF(0, height)); + height += line.height(); + widthUsed = qMax(widthUsed, line.naturalTextWidth()); +} +textLayout.endLayout(); +//! [0] + + +//! [1] +QPainter painter(this); +textLayout.draw(&painter, QPoint(0, 0)); +//! [1] diff --git a/doc/src/snippets/code/src_gui_util_qcompleter.cpp b/doc/src/snippets/code/src_gui_util_qcompleter.cpp new file mode 100644 index 0000000..3017d8c --- /dev/null +++ b/doc/src/snippets/code/src_gui_util_qcompleter.cpp @@ -0,0 +1,23 @@ +//! [0] +QStringList wordList; +wordList << "alpha" << "omega" << "omicron" << "zeta"; + +QLineEdit *lineEdit = new QLineEdit(this); + +QCompleter *completer = new QCompleter(wordList, this); +completer->setCaseSensitivity(Qt::CaseInsensitive); +lineEdit->setCompleter(completer); +//! [0] + + +//! [1] +QCompleter *completer = new QCompleter(this); +completer->setModel(new QDirModel(completer)); +lineEdit->setCompleter(completer); +//! [1] + + +//! [2] +for (int i = 0; completer->setCurrentRow(i); i++) + qDebug() << completer->currentCompletion() << " is match number " << i; +//! [2] diff --git a/doc/src/snippets/code/src_gui_util_qdesktopservices.cpp b/doc/src/snippets/code/src_gui_util_qdesktopservices.cpp new file mode 100644 index 0000000..a9c630b --- /dev/null +++ b/doc/src/snippets/code/src_gui_util_qdesktopservices.cpp @@ -0,0 +1,17 @@ +//! [0] +class MyHelpHandler : public QObject +{ + Q_OBJECT +public: + ... +public slots: + void showHelp(const QUrl &url); +}; + +QDesktopServices::setUrlHandler("help", helpInstance, "showHelp"); +//! [0] + + +//! [1] +mailto:user@foo.com?subject=Test&body=Just a test +//! [1] diff --git a/doc/src/snippets/code/src_gui_util_qundostack.cpp b/doc/src/snippets/code/src_gui_util_qundostack.cpp new file mode 100644 index 0000000..3949e1e --- /dev/null +++ b/doc/src/snippets/code/src_gui_util_qundostack.cpp @@ -0,0 +1,69 @@ +//! [0] +class AppendText : public QUndoCommand +{ +public: + AppendText(QString *doc, const QString &text) + : m_document(doc), m_text(text) { setText("append text"); } + virtual void undo() + { m_document->chop(m_text.length()); } + virtual void redo() + { m_document->append(m_text); } +private: + QString *m_document; + QString m_text; +}; +//! [0] + + +//! [1] +MyCommand *command1 = new MyCommand(); +stack->push(command1); +MyCommand *command2 = new MyCommand(); +stack->push(command2); + +stack->undo(); + +MyCommand *command3 = new MyCommand(); +stack->push(command3); // command2 gets deleted +//! [1] + + +//! [2] +QUndoCommand *insertRed = new QUndoCommand(); // an empty command +insertRed->setText("insert red text"); + +new InsertText(document, idx, text, insertRed); // becomes child of insertRed +new SetColor(document, idx, text.length(), Qt::red, insertRed); + +stack.push(insertRed); +//! [2] + + +//! [3] +bool AppendText::mergeWith(const QUndoCommand *other) +{ + if (other->id() != id()) // make sure other is also an AppendText command + return false; + m_text += static_cast<const AppendText*>(other)->m_text; + return true; +} +//! [3] + + +//! [4] +stack.beginMacro("insert red text"); +stack.push(new InsertText(document, idx, text)); +stack.push(new SetColor(document, idx, text.length(), Qt::red)); +stack.endMacro(); // indexChanged() is emitted +//! [4] + + +//! [5] +QUndoCommand *insertRed = new QUndoCommand(); // an empty command +insertRed->setText("insert red text"); + +new InsertText(document, idx, text, insertRed); // becomes child of insertRed +new SetColor(document, idx, text.length(), Qt::red, insertRed); + +stack.push(insertRed); +//! [5] diff --git a/doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp b/doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp new file mode 100644 index 0000000..3c2b192 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qabstractbutton.cpp @@ -0,0 +1,20 @@ +//! [0] +QPushButton *button = new QPushButton(tr("Ro&ck && Roll"), this); +//! [0] + + +//! [1] +button->setIcon(QIcon(":/images/print.png")); +button->setShortcut(tr("Alt+F7")); +//! [1] + + +//! [2] +void MyWidget::reactToToggle(bool checked) +{ + if (checked) { + // Examine the new button states. + ... + } +} +//! [2] diff --git a/doc/src/snippets/code/src_gui_widgets_qabstractspinbox.cpp b/doc/src/snippets/code/src_gui_widgets_qabstractspinbox.cpp new file mode 100644 index 0000000..67cfeb7 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qabstractspinbox.cpp @@ -0,0 +1,8 @@ +//! [0] +QSpinBox *spinBox = new QSpinBox(this); +spinBox->setRange(0, 100); +spinBox->setWrapping(true); +spinBox->setValue(100); +spinBox->stepBy(1); +// value is 0 +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp b/doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp new file mode 100644 index 0000000..10ceecc --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qcalendarwidget.cpp @@ -0,0 +1,39 @@ +//! [0] +QCalendarWidget *calendar; +calendar->setGridVisible(true); +//! [0] + + +//! [1] +QCalendarWidget *calendar; +calendar->setGridVisible(true); +calendar->setMinimumDate(QDate(2006, 6, 19)); +//! [1] + + +//! [2] +QCalendarWidget *calendar; +calendar->setGridVisible(true); +calendar->setMaximumDate(QDate(2006, 7, 3)); +//! [2] + + +//! [3] +QCalendarWidget *calendar; + +calendar->setDateRange(min, max); +//! [3] + + +//! [4] +QCalendarWidget *calendar; + +calendar->setMinimumDate(min); +calendar->setMaximumDate(max); +//! [4] + + +//! [5] +QCalendarWidget *calendar; +calendar->setGridVisible(true); +//! [5] diff --git a/doc/src/snippets/code/src_gui_widgets_qcheckbox.cpp b/doc/src/snippets/code/src_gui_widgets_qcheckbox.cpp new file mode 100644 index 0000000..7300838 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qcheckbox.cpp @@ -0,0 +1,3 @@ +//! [0] +QCheckBox *checkbox = new QCheckBox("C&ase sensitive", this); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp b/doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp new file mode 100644 index 0000000..796358d --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qdatetimeedit.cpp @@ -0,0 +1,39 @@ +//! [0] +QDateTimeEdit *dateEdit = new QDateTimeEdit(QDate::currentDate()); +dateEdit->setMinimumDate(QDate::currentDate().addDays(-365)); +dateEdit->setMaximumDate(QDate::currentDate().addDays(365)); +dateEdit->setDisplayFormat("yyyy.MM.dd"); +//! [0] + + +//! [1] +setDateTimeRange(min, max); +//! [1] + + +//! [2] +setMinimumDateTime(min); +setMaximumDateTime(max); +//! [2] + + +//! [3] +setDateRange(min, max); +//! [3] + + +//! [4] +setMinimumDate(min); +setMaximumDate(max); +//! [4] + + +//! [5] +setTimeRange(min, max); +//! [5] + + +//! [6] +setMinimumTime(min); +setMaximumTime(max); +//! [6] diff --git a/doc/src/snippets/code/src_gui_widgets_qdockwidget.cpp b/doc/src/snippets/code/src_gui_widgets_qdockwidget.cpp new file mode 100644 index 0000000..2204e11 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qdockwidget.cpp @@ -0,0 +1,8 @@ +//! [0] +QDockWidget *dockWidget = qobject_cast<QDockWidget*>(parentWidget()); +if (dockWidget->features() & QDockWidget::DockWidgetVerticalTitleBar) { + // I need to be vertical +} else { + // I need to be horizontal +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qframe.cpp b/doc/src/snippets/code/src_gui_widgets_qframe.cpp new file mode 100644 index 0000000..99fe79d --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qframe.cpp @@ -0,0 +1,8 @@ +//! [0] +QLabel label(...); +label.setFrameStyle(QFrame::Panel | QFrame::Raised); +label.setLineWidth(2); + +QProgressBar pbar(...); +label.setFrameStyle(QFrame::NoFrame); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qgroupbox.cpp b/doc/src/snippets/code/src_gui_widgets_qgroupbox.cpp new file mode 100644 index 0000000..efd2246 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qgroupbox.cpp @@ -0,0 +1,3 @@ +//! [0] +g->setTitle("&User information"); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qlabel.cpp b/doc/src/snippets/code/src_gui_widgets_qlabel.cpp new file mode 100644 index 0000000..d3b9254 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qlabel.cpp @@ -0,0 +1,24 @@ +//! [0] +QLabel *label = new QLabel(this); +label->setFrameStyle(QFrame::Panel | QFrame::Sunken); +label->setText("first line\nsecond line"); +label->setAlignment(Qt::AlignBottom | Qt::AlignRight); +//! [0] + + +//! [1] +QLineEdit* phoneEdit = new QLineEdit(this); +QLabel* phoneLabel = new QLabel("&Phone:", this); +phoneLabel->setBuddy(phoneEdit); +//! [1] + + +//! [2] +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) +//! [2] diff --git a/doc/src/snippets/code/src_gui_widgets_qlineedit.cpp b/doc/src/snippets/code/src_gui_widgets_qlineedit.cpp new file mode 100644 index 0000000..8191a4f --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qlineedit.cpp @@ -0,0 +1,10 @@ +//! [0] +void LineEdit::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = createStandardContextMenu(); + menu->addAction(tr("My Menu Item")); + //... + menu->exec(event->globalPos()); + delete menu; +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qmenu.cpp b/doc/src/snippets/code/src_gui_widgets_qmenu.cpp new file mode 100644 index 0000000..f30ac35 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qmenu.cpp @@ -0,0 +1,37 @@ +//! [0] +exec(QCursor::pos()); +//! [0] + + +//! [1] +exec(somewidget.mapToGlobal(QPoint(0,0))); +//! [1] + + +//! [2] +exec(e->globalPos()); +//! [2] + + +//! [3] +exec(QCursor::pos()); +//! [3] + + +//! [4] +exec(somewidget.mapToGlobal(QPoint(0, 0))); +//! [4] + + +//! [5] +exec(e->globalPos()); +//! [5] + + +//! [6] +QMenu menu; +QAction *at = actions[0]; // Assumes actions is not empty +foreach (QAction *a, actions) + menu.addAction(a); +menu.exec(pos, at); +//! [6] diff --git a/doc/src/snippets/code/src_gui_widgets_qmenubar.cpp b/doc/src/snippets/code/src_gui_widgets_qmenubar.cpp new file mode 100644 index 0000000..3ff24d3 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qmenubar.cpp @@ -0,0 +1,8 @@ +//! [0] +menubar->addMenu(fileMenu); +//! [0] + + +//! [1] +QMenuBar *menuBar = new QMenuBar(0); +//! [1] diff --git a/doc/src/snippets/code/src_gui_widgets_qplaintextedit.cpp b/doc/src/snippets/code/src_gui_widgets_qplaintextedit.cpp new file mode 100644 index 0000000..7f18995 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qplaintextedit.cpp @@ -0,0 +1,15 @@ +//! [0] +void MyQPlainTextEdit::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = createStandardContextMenu(); + menu->addAction(tr("My Menu Item")); + //... + menu->exec(event->globalPos()); + delete menu; +} +//! [0] + + +//! [1] +edit->textCursor().insertText(text); +//! [1] diff --git a/doc/src/snippets/code/src_gui_widgets_qpushbutton.cpp b/doc/src/snippets/code/src_gui_widgets_qpushbutton.cpp new file mode 100644 index 0000000..e4fc4ce --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qpushbutton.cpp @@ -0,0 +1,3 @@ +//! [0] +QPushButton *button = new QPushButton("&Download", this); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp b/doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp new file mode 100644 index 0000000..05344fc --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qradiobutton.cpp @@ -0,0 +1,3 @@ +//! [0] +QRadioButton *button = new QRadioButton("Search from the &cursor", this); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qrubberband.cpp b/doc/src/snippets/code/src_gui_widgets_qrubberband.cpp new file mode 100644 index 0000000..38a0dad --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qrubberband.cpp @@ -0,0 +1,22 @@ +//! [0] +void Widget::mousePressEvent(QMouseEvent *event) +{ + origin = event->pos(); + if (!rubberBand) + rubberBand = new QRubberBand(QRubberBand::Rectangle, this); + rubberBand->setGeometry(QRect(origin, QSize())); + rubberBand->show(); +} + +void Widget::mouseMoveEvent(QMouseEvent *event) +{ + rubberBand->setGeometry(QRect(origin, event->pos()).normalized()); +} + +void Widget::mouseReleaseEvent(QMouseEvent *event) +{ + rubberBand->hide(); + // determine selection, for example using QRect::intersects() + // and QRect::contains(). +} +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qscrollarea.cpp b/doc/src/snippets/code/src_gui_widgets_qscrollarea.cpp new file mode 100644 index 0000000..a77dc20 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qscrollarea.cpp @@ -0,0 +1,9 @@ +//! [0] +QLabel *imageLabel = new QLabel; +QImage image("happyguy.png"); +imageLabel->setPixmap(QPixmap::fromImage(image)); + +scrollArea = new QScrollArea; +scrollArea->setBackgroundRole(QPalette::Dark); +scrollArea->setWidget(imageLabel); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qspinbox.cpp b/doc/src/snippets/code/src_gui_widgets_qspinbox.cpp new file mode 100644 index 0000000..7dbd6d6 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qspinbox.cpp @@ -0,0 +1,40 @@ +//! [0] +sb->setPrefix("$"); +//! [0] + + +//! [1] +sb->setSuffix(" km"); +//! [1] + + +//! [2] +setRange(minimum, maximum); +//! [2] + + +//! [3] +setMinimum(minimum); +setMaximum(maximum); +//! [3] + + +//! [4] +spinbox->setPrefix("$"); +//! [4] + + +//! [5] +spinbox->setSuffix(" km"); +//! [5] + + +//! [6] +setRange(minimum, maximum); +//! [6] + + +//! [7] +setMinimum(minimum); +setMaximum(maximum); +//! [7] diff --git a/doc/src/snippets/code/src_gui_widgets_qsplashscreen.cpp b/doc/src/snippets/code/src_gui_widgets_qsplashscreen.cpp new file mode 100644 index 0000000..d20f1f2 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qsplashscreen.cpp @@ -0,0 +1,15 @@ +//! [0] +QPixmap pixmap(":/splash.png"); +QSplashScreen *splash = new QSplashScreen(pixmap); +splash->show(); + +... // Loading some items +splash->showMessage("Loaded modules"); + +qApp->processEvents(); + +... // Establishing connections +splash->showMessage("Established connections"); + +qApp->processEvents(); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qsplitter.cpp b/doc/src/snippets/code/src_gui_widgets_qsplitter.cpp new file mode 100644 index 0000000..62f5db1 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qsplitter.cpp @@ -0,0 +1,7 @@ +//! [0] +QWidget *widget = splitter->widget(index); +QSizePolicy policy = widget->sizePolicy(); +policy.setHorizontalStretch(stretch); +policy.setVerticalStretch(stretch); +widget->setSizePolicy(policy); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qstatusbar.cpp b/doc/src/snippets/code/src_gui_widgets_qstatusbar.cpp new file mode 100644 index 0000000..d03f5af --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qstatusbar.cpp @@ -0,0 +1,3 @@ +//! [0] +statusBar()->addWidget(new MyReadWriteIndication); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qtextbrowser.cpp b/doc/src/snippets/code/src_gui_widgets_qtextbrowser.cpp new file mode 100644 index 0000000..0beb133 --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qtextbrowser.cpp @@ -0,0 +1,4 @@ +//! [0] +backaction.setToolTip(browser.historyTitle(-1)); +forwardaction.setToolTip(browser.historyTitle(+1)); +//! [0] diff --git a/doc/src/snippets/code/src_gui_widgets_qtextedit.cpp b/doc/src/snippets/code/src_gui_widgets_qtextedit.cpp new file mode 100644 index 0000000..5f0b73f --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qtextedit.cpp @@ -0,0 +1,20 @@ +//! [0] +void MyTextEdit::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu *menu = createStandardContextMenu(); + menu->addAction(tr("My Menu Item")); + //... + menu->exec(event->globalPos()); + delete menu; +} +//! [0] + + +//! [1] +edit->textCursor().insertText(text); +//! [1] + + +//! [2] +edit->textCursor().insertHtml(fragment); +//! [2] diff --git a/doc/src/snippets/code/src_gui_widgets_qvalidator.cpp b/doc/src/snippets/code/src_gui_widgets_qvalidator.cpp new file mode 100644 index 0000000..0240eea --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qvalidator.cpp @@ -0,0 +1,95 @@ +//! [0] +QValidator *validator = new QIntValidator(100, 999, this); +QLineEdit *edit = new QLineEdit(this); + +// the edit lineedit will only accept integers between 100 and 999 +edit->setValidator(validator); +//! [0] + + +//! [1] +QString str; +int pos = 0; +QIntValidator v(100, 900, this); + +str = "1"; +v.validate(str, pos); // returns Intermediate +str = "012"; +v.validate(str, pos); // returns Intermediate + +str = "123"; +v.validate(str, pos); // returns Acceptable +str = "678"; +v.validate(str, pos); // returns Acceptable + +str = "999"; +v.validate(str, pos); // returns Intermediate + +str = "1234"; +v.validate(str, pos); // returns Invalid +str = "-123"; +v.validate(str, pos); // returns Invalid +str = "abc"; +v.validate(str, pos); // returns Invalid +str = "12cm"; +v.validate(str, pos); // returns Invalid +//! [1] + + +//! [2] +int pos = 0; + +s = "abc"; +v.validate(s, pos); // returns Invalid + +s = "5"; +v.validate(s, pos); // returns Intermediate + +s = "50"; +v.validate(s, pos); // returns Acceptable +//! [2] + + +//! [3] +// regexp: optional '-' followed by between 1 and 3 digits +QRegExp rx("-?\\d{1,3}"); +QValidator *validator = new QRegExpValidator(rx, this); + +QLineEdit *edit = new QLineEdit(this); +edit->setValidator(validator); +//! [3] + + +//! [4] +// 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; +int pos = 0; + +s = "0"; v.validate(s, pos); // returns Invalid +s = "12345"; v.validate(s, pos); // returns Invalid +s = "1"; v.validate(s, pos); // returns Acceptable + +rx.setPattern("\\S+"); // one or more non-whitespace characters +v.setRegExp(rx); +s = "myfile.txt"; v.validate(s, pos); // Returns Acceptable +s = "my file.txt"; v.validate(s, pos); // 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, pos); // Returns Invalid +s = "A12345Z"; v.validate(s, pos); // Returns Acceptable +s = "B12"; v.validate(s, pos); // 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, pos); // Returns Acceptable +s = "README.1ST"; v.validate(s, pos); // Returns Acceptable +s = "read me.txt"; v.validate(s, pos); // Returns Invalid +s = "readm"; v.validate(s, pos); // Returns Intermediate +//! [4] diff --git a/doc/src/snippets/code/src_gui_widgets_qworkspace.cpp b/doc/src/snippets/code/src_gui_widgets_qworkspace.cpp new file mode 100644 index 0000000..0c55e5f --- /dev/null +++ b/doc/src/snippets/code/src_gui_widgets_qworkspace.cpp @@ -0,0 +1,8 @@ +//! [0] +MainWindow::MainWindow() +{ + workspace = new QWorkspace; + setCentralWidget(workspace); + ... +} +//! [0] diff --git a/doc/src/snippets/code/src_network_access_qftp.cpp b/doc/src/snippets/code/src_network_access_qftp.cpp new file mode 100644 index 0000000..25e3da3 --- /dev/null +++ b/doc/src/snippets/code/src_network_access_qftp.cpp @@ -0,0 +1,59 @@ +//! [0] +QFtp *ftp = new QFtp(parent); +ftp->connectToHost("ftp.trolltech.com"); +ftp->login(); +//! [0] + + +//! [1] +ftp->connectToHost("ftp.trolltech.com"); // id == 1 +ftp->login(); // id == 2 +ftp->cd("qt"); // id == 3 +ftp->get("INSTALL"); // id == 4 +ftp->close(); // id == 5 +//! [1] + + +//! [2] +start(1) +stateChanged(HostLookup) +stateChanged(Connecting) +stateChanged(Connected) +finished(1, false) + +start(2) +stateChanged(LoggedIn) +finished(2, false) + +start(3) +finished(3, false) + +start(4) +dataTransferProgress(0, 3798) +dataTransferProgress(2896, 3798) +readyRead() +dataTransferProgress(3798, 3798) +readyRead() +finished(4, false) + +start(5) +stateChanged(Closing) +stateChanged(Unconnected) +finished(5, false) + +done(false) +//! [2] + + +//! [3] +start(1) +stateChanged(HostLookup) +stateChanged(Connecting) +stateChanged(Connected) +finished(1, false) + +start(2) +finished(2, true) + +done(true) +//! [3] diff --git a/doc/src/snippets/code/src_network_access_qhttp.cpp b/doc/src/snippets/code/src_network_access_qhttp.cpp new file mode 100644 index 0000000..57698a0 --- /dev/null +++ b/doc/src/snippets/code/src_network_access_qhttp.cpp @@ -0,0 +1,85 @@ +//! [0] +content-type: text/html +//! [0] + + +//! [1] +header.setValue("content-type", "text/html"); +QString contentType = header.value("content-type"); +//! [1] + + +//! [2] +QHttpRequestHeader header("GET", QUrl::toPercentEncoding("/index.html")); +header.setValue("Host", "qtsoftware.com"); +http->setHost("qtsoftware.com"); +http->request(header); +//! [2] + + +//! [3] +http->setHost("qtsoftware.com"); // id == 1 +http->get(QUrl::toPercentEncoding("/index.html")); // id == 2 +//! [3] + + +//! [4] +requestStarted(1) +requestFinished(1, false) + +requestStarted(2) +stateChanged(Connecting) +stateChanged(Sending) +dataSendProgress(77, 77) +stateChanged(Reading) +responseHeaderReceived(responseheader) +dataReadProgress(5388, 0) +readyRead(responseheader) +dataReadProgress(18300, 0) +readyRead(responseheader) +stateChanged(Connected) +requestFinished(2, false) + +done(false) + +stateChanged(Closing) +stateChanged(Unconnected) +//! [4] + + +//! [5] +http->setHost("www.foo.bar"); // id == 1 +http->get("/index.html"); // id == 2 +http->post("register.html", data); // id == 3 +//! [5] + + +//! [6] +requestStarted(1) +requestFinished(1, false) + +requestStarted(2) +stateChanged(HostLookup) +requestFinished(2, true) + +done(true) + +stateChanged(Unconnected) +//! [6] + + +//! [7] +void Ticker::getTicks() +{ + http = new QHttp(this); + connect(http, SIGNAL(done(bool)), this, SLOT(showPage())); + http->setProxy("proxy.example.com", 3128); + http->setHost("ticker.example.com"); + http->get("/ticks.asp"); +} + +void Ticker::showPage() +{ + display(http->readAll()); +} +//! [7] diff --git a/doc/src/snippets/code/src_network_access_qnetworkaccessmanager.cpp b/doc/src/snippets/code/src_network_access_qnetworkaccessmanager.cpp new file mode 100644 index 0000000..0ef0a3b --- /dev/null +++ b/doc/src/snippets/code/src_network_access_qnetworkaccessmanager.cpp @@ -0,0 +1,21 @@ +//! [0] +QNetworkAccessManager *manager = new QNetworkAccessManager(this); +connect(manager, SIGNAL(finished(QNetworkReply*)), + this, SLOT(replyFinished(QNetworkReply*))); + +manager->get(QNetworkRequest(QUrl("http://qtsoftware.com"))); +//! [0] + + +//! [1] +QNetworkRequest request; +request.setUrl(QUrl("http://qtsoftware.com")); +request.setRawHeader("User-Agent", "MyOwnBrowser 1.0"); + +QNetworkReply *reply = manager->get(request); +connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); +connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), + this, SLOT(slotError(QNetworkReply::NetworkError))); +connect(reply, SIGNAL(sslErrors(QList<QSslError>)), + this, SLOT(slotSslErrors(QList<QSslError>))); +//! [1] diff --git a/doc/src/snippets/code/src_network_access_qnetworkrequest.cpp b/doc/src/snippets/code/src_network_access_qnetworkrequest.cpp new file mode 100644 index 0000000..d1f6962 --- /dev/null +++ b/doc/src/snippets/code/src_network_access_qnetworkrequest.cpp @@ -0,0 +1,3 @@ +//! [0] +request.setRawHeader("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT"); +//! [0] diff --git a/doc/src/snippets/code/src_network_kernel_qhostaddress.cpp b/doc/src/snippets/code/src_network_kernel_qhostaddress.cpp new file mode 100644 index 0000000..0b90404 --- /dev/null +++ b/doc/src/snippets/code/src_network_kernel_qhostaddress.cpp @@ -0,0 +1,8 @@ +//! [0] +Q_IPV6ADDR addr = hostAddr.toIPv6Address(); +// addr contains 16 unsigned characters + +for (int i = 0; i < 16; ++i) { + // process addr[i] +} +//! [0] diff --git a/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp b/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp new file mode 100644 index 0000000..e748f90 --- /dev/null +++ b/doc/src/snippets/code/src_network_kernel_qhostinfo.cpp @@ -0,0 +1,50 @@ +//! [0] +// To find the IP address of qtsoftware.com +QHostInfo::lookupHost("qtsoftware.com", + this, SLOT(printResults(QHostInfo))); + +// To find the host name for 4.2.2.1 +QHostInfo::lookupHost("4.2.2.1", + this, SLOT(printResults(QHostInfo))); +//! [0] + + +//! [1] +QHostInfo info = QHostInfo::fromName("qtsoftware.com"); +//! [1] + + +//! [2] +QHostInfo::lookupHost("www.kde.org", + this, SLOT(lookedUp(QHostInfo))); +//! [2] + + +//! [3] +void MyWidget::lookedUp(const QHostInfo &host) +{ + if (host.error() != QHostInfo::NoError) { + qDebug() << "Lookup failed:" << host.errorString(); + return; + } + + foreach (QHostAddress address, host.addresses()) + qDebug() << "Found address:" << address.toString(); +} +//! [3] + + +//! [4] +QHostInfo::lookupHost("4.2.2.1", + this, SLOT(lookedUp(QHostInfo))); +//! [4] + + +//! [5] +QHostInfo info; +... +if (!info.addresses().isEmpty()) { + QHostAddress address = info.addresses().first(); + // use the first IP address +} +//! [5] diff --git a/doc/src/snippets/code/src_network_kernel_qnetworkproxy.cpp b/doc/src/snippets/code/src_network_kernel_qnetworkproxy.cpp new file mode 100644 index 0000000..34e9466 --- /dev/null +++ b/doc/src/snippets/code/src_network_kernel_qnetworkproxy.cpp @@ -0,0 +1,14 @@ +//! [0] +QNetworkProxy proxy; +proxy.setType(QNetworkProxy::Socks5Proxy); +proxy.setHostName("proxy.example.com"); +proxy.setPort(1080); +proxy.setUser("username"); +proxy.setPassword("password"); +QNetworkProxy::setApplicationProxy(proxy); +//! [0] + + +//! [1] +serverSocket->setProxy(QNetworkProxy::NoProxy); +//! [1] diff --git a/doc/src/snippets/code/src_network_socket_qabstractsocket.cpp b/doc/src/snippets/code/src_network_socket_qabstractsocket.cpp new file mode 100644 index 0000000..d64931a --- /dev/null +++ b/doc/src/snippets/code/src_network_socket_qabstractsocket.cpp @@ -0,0 +1,30 @@ +//! [0] +socket->connectToHost("imap", 143); +if (socket->waitForConnected(1000)) + qDebug("Connected!"); +//! [0] + + +//! [1] +socket->disconnectFromHost(); + if (socket->state() == QAbstractSocket::UnconnectedState || + socket->waitForDisconnected(1000)) + qDebug("Disconnected!"); +//! [1] + + +//! [2] + // This slot is connected to QAbstractSocket::readyRead() + void SocketClass::readyReadSlot() + { + while (!socket.atEnd()) { + QByteArray data = socket.read(100); + .... + } + } +//! [2] + + +//! [3] +socket->setProxy(QNetworkProxy::NoProxy); +//! [3] diff --git a/doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp b/doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp new file mode 100644 index 0000000..da96e6f --- /dev/null +++ b/doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp @@ -0,0 +1,12 @@ +//! [0] +socket->connectToServer("market"); +if (socket->waitForConnected(1000)) + qDebug("Connected!"); +//! [0] + + +//! [1] +socket->disconnectFromServer(); +if (socket->waitForDisconnected(1000)) + qDebug("Disconnected!"); +//! [1] diff --git a/doc/src/snippets/code/src_network_socket_qnativesocketengine.cpp b/doc/src/snippets/code/src_network_socket_qnativesocketengine.cpp new file mode 100644 index 0000000..2aca1e1 --- /dev/null +++ b/doc/src/snippets/code/src_network_socket_qnativesocketengine.cpp @@ -0,0 +1,21 @@ +//! [0] +QNativeSocketEngine socketLayer; +socketLayer.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol); +socketLayer.connectToHost(QHostAddress::LocalHost, 22); +// returns false + +socketLayer.waitForWrite(); +socketLayer.connectToHost(QHostAddress::LocalHost, 22); +// returns true +//! [0] + + +//! [1] +QNativeSocketEngine socketLayer; +socketLayer.bind(QHostAddress::Any, 4000); +socketLayer.listen(); +if (socketLayer.waitForRead()) { + int clientSocket = socketLayer.accept(); + // a client is connected +} +//! [1] diff --git a/doc/src/snippets/code/src_network_socket_qtcpserver.cpp b/doc/src/snippets/code/src_network_socket_qtcpserver.cpp new file mode 100644 index 0000000..0021e3b --- /dev/null +++ b/doc/src/snippets/code/src_network_socket_qtcpserver.cpp @@ -0,0 +1,3 @@ +//! [0] +server->setProxy(QNetworkProxy::NoProxy); +//! [0] diff --git a/doc/src/snippets/code/src_network_socket_qudpsocket.cpp b/doc/src/snippets/code/src_network_socket_qudpsocket.cpp new file mode 100644 index 0000000..966fb50 --- /dev/null +++ b/doc/src/snippets/code/src_network_socket_qudpsocket.cpp @@ -0,0 +1,25 @@ +//! [0] +void Server::initSocket() +{ + udpSocket = new QUdpSocket(this); + udpSocket->bind(QHostAddress::LocalHost, 7755); + + connect(udpSocket, SIGNAL(readyRead()), + this, SLOT(readPendingDatagrams())); +} + +void Server::readPendingDatagrams() +{ + while (udpSocket->hasPendingDatagrams()) { + QByteArray datagram; + datagram.resize(udpSocket->pendingDatagramSize()); + QHostAddress sender; + quint16 senderPort; + + udpSocket->readDatagram(datagram.data(), datagram.size(), + &sender, &senderPort); + + processTheDatagram(datagram); + } +} +//! [0] diff --git a/doc/src/snippets/code/src_network_ssl_qsslcertificate.cpp b/doc/src/snippets/code/src_network_ssl_qsslcertificate.cpp new file mode 100644 index 0000000..2ec84ae --- /dev/null +++ b/doc/src/snippets/code/src_network_ssl_qsslcertificate.cpp @@ -0,0 +1,6 @@ +//! [0] +foreach (QSslCertificate cert, QSslCertificate::fromPath("C:/ssl/certificate.*.pem", QSsl::Pem, + QRegExp::Wildcard)) { + qDebug() << cert.issuerInfo(QSslCertificate::Organization); +} +//! [0] diff --git a/doc/src/snippets/code/src_network_ssl_qsslconfiguration.cpp b/doc/src/snippets/code/src_network_ssl_qsslconfiguration.cpp new file mode 100644 index 0000000..fb3e1ab --- /dev/null +++ b/doc/src/snippets/code/src_network_ssl_qsslconfiguration.cpp @@ -0,0 +1,5 @@ +//! [0] +QSslConfiguration config = sslSocket.sslConfiguration(); +config.setProtocol(QSsl::TlsV1); +sslSocket.setSslConfiguration(config); +//! [0] diff --git a/doc/src/snippets/code/src_network_ssl_qsslsocket.cpp b/doc/src/snippets/code/src_network_ssl_qsslsocket.cpp new file mode 100644 index 0000000..afffbab --- /dev/null +++ b/doc/src/snippets/code/src_network_ssl_qsslsocket.cpp @@ -0,0 +1,56 @@ +//! [0] +QSslSocket *socket = new QSslSocket(this); +connect(socket, SIGNAL(encrypted()), this, SLOT(ready())); + +socket->connectToHostEncrypted("imap.example.com", 993); +//! [0] + + +//! [1] +void SslServer::incomingConnection(int socketDescriptor) +{ + QSslSocket *serverSocket = new QSslSocket; + if (serverSocket->setSocketDescriptor(socketDescriptor)) { + connect(serverSocket, SIGNAL(encrypted()), this, SLOT(ready())); + serverSocket->startServerEncryption(); + } else { + delete serverSocket; + } +} +//! [1] + + +//! [2] +QSslSocket socket; +socket.connectToHostEncrypted("http.example.com", 443); +if (!socket.waitForEncrypted()) { + qDebug() << socket.errorString(); + return false; +} + +socket.write("GET / HTTP/1.0\r\n\r\n"); +while (socket.waitForReadyRead()) + qDebug() << socket.readAll().data(); +//! [2] + + +//! [3] +QSslSocket socket; +connect(&socket, SIGNAL(encrypted()), receiver, SLOT(socketEncrypted())); + +socket.connectToHostEncrypted("imap", 993); +socket->write("1 CAPABILITY\r\n"); +//! [3] + + +//! [4] +QSslSocket socket; +socket.setCiphers("DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA"); +//! [4] + + +//! [5] +socket->connectToHostEncrypted("imap", 993); +if (socket->waitForEncrypted(1000)) + qDebug("Encrypted!"); +//! [5] diff --git a/doc/src/snippets/code/src_opengl_qgl.cpp b/doc/src/snippets/code/src_opengl_qgl.cpp new file mode 100644 index 0000000..15b0005 --- /dev/null +++ b/doc/src/snippets/code/src_opengl_qgl.cpp @@ -0,0 +1,132 @@ +//! [0] +QGLFormat fmt; +fmt.setAlpha(true); +fmt.setStereo(true); +QGLFormat::setDefaultFormat(fmt); +//! [0] + + +//! [1] +QGLFormat fmt; +fmt.setDoubleBuffer(false); // single buffer +fmt.setDirectRendering(false); // software rendering +MyGLWidget* myWidget = new MyGLWidget(fmt, ...); +//! [1] + + +//! [2] +QGLFormat fmt; +fmt.setOverlay(true); +fmt.setStereo(true); +MyGLWidget* myWidget = new MyGLWidget(fmt, ...); +if (!myWidget->format().stereo()) { + // ok, goggles off + if (!myWidget->format().hasOverlay()) { + qFatal("Cool hardware required"); + } +} +//! [2] + + +//! [3] +// The rendering in MyGLWidget depends on using +// stencil buffer and alpha channel +MyGLWidget::MyGLWidget(QWidget* parent) + : QGLWidget(QGLFormat(QGL::StencilBuffer | QGL::AlphaChannel), parent) +{ + if (!format().stencil()) + qWarning("Could not get stencil buffer; results will be suboptimal"); + if (!format().alpha()) + qWarning("Could not get alpha channel; results will be suboptimal"); + ... +} +//! [3] + + +//! [4] +QApplication a(argc, argv); +QGLFormat f; +f.setDoubleBuffer(false); +QGLFormat::setDefaultFormat(f); +//! [4] + + +//! [5] +QGLFormat f = QGLFormat::defaultOverlayFormat(); +f.setDoubleBuffer(true); +QGLFormat::setDefaultOverlayFormat(f); +//! [5] + + +//! [6] +// ...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 +} +//! [6] + + +//! [7] +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 +//! [7] + + +//! [8] +class MyGLDrawer : public QGLWidget +{ + Q_OBJECT // must include this if you use Qt signals/slots + +public: + MyGLDrawer(QWidget *parent) + : QGLWidget(parent) {} + +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(); + ... + } + +}; +//! [8] diff --git a/doc/src/snippets/code/src_opengl_qglcolormap.cpp b/doc/src/snippets/code/src_opengl_qglcolormap.cpp new file mode 100644 index 0000000..b47de76 --- /dev/null +++ b/doc/src/snippets/code/src_opengl_qglcolormap.cpp @@ -0,0 +1,21 @@ +//! [0] +#include <QApplication> +#include <QGLColormap> + +int main() +{ + QApplication app(argc, argv); + + MySuperGLWidget widget; // 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 app.exec(); +} +//! [0] diff --git a/doc/src/snippets/code/src_opengl_qglpixelbuffer.cpp b/doc/src/snippets/code/src_opengl_qglpixelbuffer.cpp new file mode 100644 index 0000000..589ffc0 --- /dev/null +++ b/doc/src/snippets/code/src_opengl_qglpixelbuffer.cpp @@ -0,0 +1,19 @@ +//! [0] +QGLPixelBuffer pbuffer(...); +... +pbuffer.makeCurrent(); +GLuint dynamicTexture = pbuffer.generateDynamicTexture(); +pbuffer.bindToDynamicTexture(dynamicTexture); +... +pbuffer.releaseFromDynamicTexture(); +//! [0] + + +//! [1] +QGLPixelBuffer pbuffer(...); +... +pbuffer.makeCurrent(); +GLuint dynamicTexture = pbuffer.generateDynamicTexture(); +... +pbuffer.updateDynamicTexture(dynamicTexture); +//! [1] diff --git a/doc/src/snippets/code/src_qdbus_qdbusabstractinterface.cpp b/doc/src/snippets/code/src_qdbus_qdbusabstractinterface.cpp new file mode 100644 index 0000000..cc5b86d --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbusabstractinterface.cpp @@ -0,0 +1,20 @@ +//! [0] +QString value = retrieveValue(); +QDBusMessage reply; + +QDBusReply<int> api = interface->call(QLatin1String("GetAPIVersion")); +if (api >= 14) + reply = interface->call(QLatin1String("ProcessWorkUnicode"), value); +else + reply = interface->call(QLatin1String("ProcessWork"), QLatin1String("UTF-8"), value.toUtf8()); +//! [0] + +//! [1] +QString value = retrieveValue(); +QDBusPendingCall pcall = interface->asyncCall(QLatin1String("Process"), value); + +QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this); + +QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), + this, SLOT(callFinishedSlot(QDBusPendingCallWatcher*))); +//! [1] diff --git a/doc/src/snippets/code/src_qdbus_qdbusargument.cpp b/doc/src/snippets/code/src_qdbus_qdbusargument.cpp new file mode 100644 index 0000000..b982510 --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbusargument.cpp @@ -0,0 +1,151 @@ +//! [0] +struct MyStructure +{ + int count; + QString name; +}; +QT_DECLARE_METATYPE(MyStructure) + +// Marshall the MyStructure data into a D-Bus argument +QDBusArgument &operator<<(QDBusArgument &argument, const MyStructure &mystruct) +{ + argument.beginStructure(); + argument << mystruct.count << mystruct.name; + argument.endStructure(); + return argument; +} + +// Retrieve the MyStructure data from the D-Bus argument +const QDBusArgument &operator>>(const QDBusArgument &argument, MyStructure &mystruct) +{ + argument.beginStructure(); + argument >> mystruct.count >> mystruct.name; + argument.endStructure(); + return argument; +} +//! [0] + + +//! [1] +qDBusRegisterMetaType<MyStructure>(); +//! [1] + + +//! [2] +MyType item = qdbus_cast<Type>(argument); +//! [2] + + +//! [3] +MyType item; +argument >> item; +//! [3] + + +//! [4] +QDBusArgument &operator<<(QDBusArgument &argument, const MyStructure &mystruct) +{ + argument.beginStructure(); + argument << mystruct.member1 << mystruct.member2 << ... ; + argument.endStructure(); + return argument; +} +//! [4] + + +//! [5] +QDBusArgument &operator<<(QDBusArgument &argument, const MyStructure &mystruct) +{ + argument.beginStructure(); + argument << mystruct.member1 << mystruct.member2; + + argument.beginStructure(); + argument << mystruct.member3.subMember1 << mystruct.member3.subMember2; + argument.endStructure(); + + argument << mystruct.member4; + argument.endStructure(); + return argument; +} +//! [5] + + +//! [6] +// append an array of MyElement types +QDBusArgument &operator<<(QDBusArgument &argument, const MyArray &myarray) +{ + argument.beginArray( qMetaTypeId<MyElement>() ); + for ( int i = 0; i < myarray.length; ++i ) + argument << myarray.elements[i]; + argument.endArray(); + return argument; +} +//! [6] + + +//! [7] +// append a dictionary that associates ints to MyValue types +QDBusArgument &operator<<(QDBusArgument &argument, const MyDictionary &mydict) +{ + argument.beginMap( QVariant::Int, qMetaTypeId<MyValue>() ); + for ( int i = 0; i < mydict.length; ++i ) { + argument.beginMapEntry(); + argument << mydict.data[i].key << mydict.data[i].value; + argument.endMapEntry(); + } + argument.endMap(); + return argument; +} +//! [7] + + +//! [8] +const QDBusArgument &operator>>(const QDBusArgument &argument, MyStructure &mystruct) +{ + argument.beginStructure() + argument >> mystruct.member1 >> mystruct.member2 >> mystruct.member3 >> ...; + argument.endStructure(); + return argument; +} +//! [8] + + +//! [9] +// extract a MyArray array of MyElement elements +const QDBusArgument &operator>>(const QDBusArgument &argument, MyArray &myarray) +{ + argument.beginArray(); + myarray.clear(); + + while ( !argument.atEnd() ) { + MyElement element; + argument >> element; + myarray.append( element ); + } + + argument.endArray(); + return argument; +} +//! [9] + + +//! [10] +// extract a MyDictionary map that associates ints to MyValue elements +const QDBusArgument &operator>>(const QDBusArgument &argument, MyDictionary &mydict) +{ + argument.beginMap(); + mydict.clear(); + + while ( !argMap.atEnd() ) { + int key; + MyValue value; + argument.beginMapEntry(); + argument >> key >> value; + argument.endMapEntry(); + mydict.append( key, value ); + } + + argument.endMap(); + return argument; +} +//! [10] diff --git a/doc/src/snippets/code/src_qdbus_qdbuscontext.cpp b/doc/src/snippets/code/src_qdbus_qdbuscontext.cpp new file mode 100644 index 0000000..2a8c868 --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbuscontext.cpp @@ -0,0 +1,32 @@ +//! [0] +class MyObject: public QObject, + protected QDBusContext +{ + Q_OBJECT + QDBusConnection conn; + QDBusMessage msg; + +... + +protected slots: + void process(); +public slots: + void methodWithError(); + QString methodWithDelayedReply(); +}; + +void MyObject::methodWithError() +{ + sendErrorReply(QDBusError::NotSupported, + "The method call 'methodWithError()' is not supported"); +} + +QString MyObject::methodWithDelayedReply() +{ + conn = connection(); + msg = message(); + setDelayedReply(true); + QMetaObject::invokeMethod(this, "process", Qt::QueuedConnection); + return QString(); +} +//! [0] diff --git a/doc/src/snippets/code/src_qdbus_qdbusinterface.cpp b/doc/src/snippets/code/src_qdbus_qdbusinterface.cpp new file mode 100644 index 0000000..df883e7 --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbusinterface.cpp @@ -0,0 +1,11 @@ +//! [0] +QDBusInterface remoteApp( "com.example.Calculator", "/Calculator/Operations", + "org.mathematics.RPNCalculator" ); +remoteApp.call( "PushOperand", 2 ); +remoteApp.call( "PushOperand", 2 ); +remoteApp.call( "ExecuteOperation", "+" ); +QDBusReply<int> reply = remoteApp.call( "PopOperand" ); + +if ( reply.isValid() ) + printf( "%d", reply.value() ); // prints 4 +//! [0] diff --git a/doc/src/snippets/code/src_qdbus_qdbusmetatype.cpp b/doc/src/snippets/code/src_qdbus_qdbusmetatype.cpp new file mode 100644 index 0000000..99fd6e4 --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbusmetatype.cpp @@ -0,0 +1,3 @@ +//! [0] +qDBusRegisterMetaType<MyClass>(); +//! [0] diff --git a/doc/src/snippets/code/src_qdbus_qdbusreply.cpp b/doc/src/snippets/code/src_qdbus_qdbusreply.cpp new file mode 100644 index 0000000..4dc896f --- /dev/null +++ b/doc/src/snippets/code/src_qdbus_qdbusreply.cpp @@ -0,0 +1,14 @@ +//! [0] +QDBusReply<QString> reply = interface->call("RemoteMethod"); +if (reply.isValid()) + // use the returned value + useValue(reply.value()); +else + // call failed. Show an error condition. + showError(reply.error()); +//! [0] + + +//! [1] +QString reply = interface->call("RemoteMethod"); +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_canvas_q3canvas.cpp b/doc/src/snippets/code/src_qt3support_canvas_q3canvas.cpp new file mode 100644 index 0000000..bca056c --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_canvas_q3canvas.cpp @@ -0,0 +1,51 @@ +//! [0] +QPrinter pr; +if (pr.setup()) { + QPainter p(&pr); + canvas.drawArea(canvas.rect(), &p); +} +//! [0] + + +//! [1] +void MyCanvasView::contentsMousePressEvent(QMouseEvent* e) +{ + Q3CanvasItemList l = canvas()->collisions(e->pos()); + for (Q3CanvasItemList::Iterator it=l.begin(); it!=l.end(); ++it) { + if ((*it)->rtti() == Q3CanvasRectangle::RTTI) + qDebug("A Q3CanvasRectangle lies somewhere at this point"); + } +} +//! [1] + + +//! [2] +QMatrix 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); +//! [2] + + +//! [3] +QRect rc = QRect(myCanvasView->contentsX(), myCanvasView->contentsY(), + myCanvasView->visibleWidth(), myCanvasView->visibleHeight()); +QRect canvasRect = myCanvasView->inverseWorldMatrix().mapRect(rc); +//! [3] + + +//! [4] +Q3CanvasItem* item; +// Find an item, e.g. with Q3CanvasItem::collisions(). +... +if (item->rtti() == MySprite::RTTI) { + MySprite* s = (MySprite*)item; + if (s->isDamagable()) s->loseHitPoints(1000); + if (s->isHot()) myself->loseHitPoints(1000); + ... +} +//! [4] diff --git a/doc/src/snippets/code/src_qt3support_dialogs_q3filedialog.cpp b/doc/src/snippets/code/src_qt3support_dialogs_q3filedialog.cpp new file mode 100644 index 0000000..ea66985 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_dialogs_q3filedialog.cpp @@ -0,0 +1,229 @@ +//! [0] +QString s = Q3FileDialog::getOpenFileName( + "/home", + "Images (*.png *.xpm *.jpg)", + this, + "open file dialog", + "Choose a file"); +//! [0] + + +//! [1] +"Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)" +//! [1] + + +//! [2] +Q3FileDialog* fd = new Q3FileDialog(this, "file dialog", true); +fd->setMode(Q3FileDialog::AnyFile); +//! [2] + + +//! [3] +fd->setFilter("Images (*.png *.xpm *.jpg)"); +//! [3] + + +//! [4] +fd->setViewMode(Q3FileDialog::Detail); +//! [4] + + +//! [5] +QString fileName; +if (fd->exec() == QDialog::Accepted) + fileName = fd->selectedFile(); +//! [5] + + +//! [6] +class Preview : public QLabel, public Q3FilePreview +{ +public: + Preview(QWidget *parent=0) : QLabel(parent) {} + + void previewUrl(const Q3Url &u) + { + QString path = u.path(); + QPixmap pix(path); + if (pix.isNull()) + setText("This is not a pixmap"); + else + setPixmap(pix); + } +}; +//! [6] + + +//! [7] +Preview* p = new Preview; + +Q3FileDialog* fd = new Q3FileDialog(this); +fd->setContentsPreviewEnabled(true); +fd->setContentsPreview(p, p); +fd->setPreviewMode(Q3FileDialog::Contents); +fd->show(); +//! [7] + + +//! [8] +QStringList list = myFileDialog.selectedFiles(); +QStringList::Iterator it = list.begin(); +while(it != list.end()) { + myProcessing(*it); + ++it; +} +//! [8] + + +//! [9] +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++"); +//! [9] + + +//! [10] +QString s = Q3FileDialog::getOpenFileName( + "/home", + "Images (*.png *.xpm *.jpg)", + this, + "open file dialog", + "Choose a file to open"); +//! [10] + + +//! [11] +QString s = Q3FileDialog::getSaveFileName( + "/home", + "Images (*.png *.xpm *.jpg)", + this, + "save file dialog", + "Choose a filename to save under"); +//! [11] + + +//! [12] +QString s = Q3FileDialog::getExistingDirectory( + "/home", + this, + "get existing directory", + "Choose a directory", + true); +//! [12] + + +//! [13] +MyFileDialog::MyFileDialog(QWidget* parent, const char* name) : + Q3FileDialog(parent, name) +{ + QLabel* label = new QLabel("Added widgets", this); + QLineEdit* lineedit = new QLineEdit(this); + QPushButton* pushbutton = new QPushButton(this); + + addWidgets(label, lineedit, pushbutton); +} +//! [13] + + +//! [14] +QString types("Image files (*.png *.xpm *.jpg);;" + "Text files (*.txt);;" + "Any files (*)"); +Q3FileDialog fd = new Q3FileDialog(this); +fd->setFilters(types); +fd->show(); +//! [14] + + +//! [15] +Q3FileDialog* fd = new Q3FileDialog(this); +fd->addFilter("Images (*.png *.jpg *.xpm)"); +fd->show(); +//! [15] + + +//! [16] +QStringList files = Q3FileDialog::getOpenFileNames( + "Images (*.png *.xpm *.jpg)", + "/home", + this, + "open files dialog", + "Select one or more files to open"); +//! [16] + + +//! [17] +QStringList list = files; +QStringList::Iterator it = list.begin(); +while(it != list.end()) { + myProcessing(*it); + ++it; +} +//! [17] + + +//! [18] +class Preview : public QLabel, public Q3FilePreview +{ +public: + Preview(QWidget *parent=0) : QLabel(parent) {} + + void previewUrl(const Q3Url &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; + + Q3FileDialog* fd = new Q3FileDialog(this); + fd->setInfoPreviewEnabled(true); + fd->setInfoPreview(p, p); + fd->setPreviewMode(Q3FileDialog::Info); + fd->show(); +} + +//! [18] + + +//! [19] +class Preview : public QLabel, public Q3FilePreview +{ +public: + Preview(QWidget *parent=0) : QLabel(parent) {} + + void previewUrl(const Q3Url &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; + + Q3FileDialog* fd = new Q3FileDialog(this); + fd->setContentsPreviewEnabled(true); + fd->setContentsPreview(p, p); + fd->setPreviewMode(Q3FileDialog::Contents); + fd->show(); +} +//! [19] diff --git a/doc/src/snippets/code/src_qt3support_dialogs_q3progressdialog.cpp b/doc/src/snippets/code/src_qt3support_dialogs_q3progressdialog.cpp new file mode 100644 index 0000000..8aeafe8 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_dialogs_q3progressdialog.cpp @@ -0,0 +1,41 @@ +//! [0] +Q3ProgressDialog progress("Copying files...", "Abort Copy", numFiles, + this, "progress", true); +for (int i = 0; i < numFiles; i++) { + progress.setProgress(i); + qApp->processEvents(); + + if (progress.wasCanceled()) + break; + //... copy one file +} +progress.setProgress(numFiles); +//! [0] + + +//! [1] +Operation::Operation(QObject *parent = 0) + : QObject(parent), steps(0) +{ + pd = new Q3ProgressDialog("Operation in progress.", "Cancel", 100); + connect(pd, SIGNAL(canceled()), this, SLOT(cancel())); + t = new QTimer(this); + connect(t, SIGNAL(timeout()), this, SLOT(perform())); + t->start(0); +} + +void Operation::perform() +{ + pd->setProgress(steps); + //... perform one percent of the operation + steps++; + if (steps > pd->totalSteps()) + t->stop(); +} + +void Operation::cancel() +{ + t->stop(); + //... cleanup +} +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_itemviews_q3iconview.cpp b/doc/src/snippets/code/src_qt3support_itemviews_q3iconview.cpp new file mode 100644 index 0000000..8c30389 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_itemviews_q3iconview.cpp @@ -0,0 +1,75 @@ +//! [0] +(void) new Q3IconViewItem( + iconView, // A pointer to a Q3IconView + "This is the text of the item", + aPixmap); +//! [0] + + +//! [1] +Q3IconViewItem *item; +for (item = iconView->firstItem(); item; item = item->nextItem()) + do_something_with(item); +//! [1] + + +//! [2] +Q3IconViewItem *item; +for (item = iconView->firstItem(); item; item = item->nextItem()) + do_something_with(item); +//! [2] + + +//! [3] +int MyIconViewItem::compare(Q3IconViewItem *i) const +{ + return key().compare(i->key()); +} +//! [3] + + +//! [4] +Q3IconView *iv = new Q3IconView(this); +QDir dir(path, "*.xpm"); +for (uint i = 0; i < dir.count(); i++) { + (void) new Q3IconViewItem(iv, dir[i], QPixmap(path + dir[i])); +} +iv->resize(600, 400); +iv->show(); +//! [4] + + +//! [5] +for (Q3IconViewItem *item = iv->firstItem(); item; item = item->nextItem()) + do_something(item); +//! [5] + + +//! [6] +Q3DragObject *MyIconView::dragObject() +{ + return new Q3TextDrag(currentItem()->text(), this); +} +//! [6] + + +//! [7] +bool MyIconViewItem::acceptDrop(const QMimeSource *mime) const +{ + if (mime->provides("text/plain")) + return true; + return false; +} + +void MyIconViewItem::dropped(QDropEvent *evt, const Q3ValueList<Q3IconDragItem>&) +{ + QString label; + if (Q3TextDrag::decode(evt, label)) + setText(label); +} +//! [7] + + +//! [8] +(void) new Q3IconViewItem(myIconview, "The text of the item", aPixmap); +//! [8] diff --git a/doc/src/snippets/code/src_qt3support_itemviews_q3listview.cpp b/doc/src/snippets/code/src_qt3support_itemviews_q3listview.cpp new file mode 100644 index 0000000..615f124 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_itemviews_q3listview.cpp @@ -0,0 +1,73 @@ +//! [0] +(void) new Q3ListViewItem(listView, "Column 1", "Column 2"); +(void) new Q3ListViewItem(listView->firstChild(), "A", "B", "C"); +//! [0] + + +//! [1] +Q3ListViewItem * myChild = myItem->firstChild(); +while(myChild) { + doSomething(myChild); + myChild = myChild->nextSibling(); +} +//! [1] + + +//! [2] +Q3ListViewItemIterator it(listview); +while (it.current()) { + Q3ListViewItem *item = it.current(); + doSomething(item); + ++it; +} +//! [2] + + +//! [3] +int MyListViewItem::compare(Q3ListViewItem *i, int col, + bool ascending) const +{ + return key(col, ascending).compare(i->key(col, ascending)); +} +//! [3] + + +//! [4] +Q3ListViewItem *i = itemAt(p); +if (i) { + if (p.x() > header()->sectionPos(header()->mapToIndex(0)) + + treeStepSize() * (i->depth() + (rootIsDecorated() ? 1 : 0)) + itemMargin() || + p.x() < header()->sectionPos(header()->mapToIndex(0))) { + ; // p is not on root decoration + else + ; // p is on the root decoration +} +//! [4] + + +//! [5] +QRect r(listView->itemRect(item)); +r.setHeight(qMin(item->totalHeight(), + listView->viewport->height() - r.y())) +//! [5] + + +//! [6] +QList<Q3ListViewItem *> lst; +Q3ListViewItemIterator it(myListView); +while (it.current()) { + if (it.current()->isSelected()) + lst.append(it.current()); + ++it; +} +//! [6] + + +//! [7] +QList<Q3ListViewItem *> lst; +Q3ListViewItemIterator it(myListView, Selected); +while (it.current()) { + lst.append(it.current()); + ++it; +} +//! [7] diff --git a/doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp b/doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp new file mode 100644 index 0000000..47f9c4e --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp @@ -0,0 +1,57 @@ + +void wrapInFunction() +{ + +//! [0] +for (int row = 0; row < table->numRows(); row++) { + for (int col = 0; col < table->numCols(); col++) { + table->setItem(row, col, + new Q3TableItem(table, Q3TableItem::WhenCurrent, QString::number(row * col))); + } +} +//! [0] + + +//! [1] +QWidget* MyTableItem::createEditor() const +{ + QHBox* hbox = new QHBox(table()->viewport()); + hbox->setFocusProxy(new QLineEdit(hbox)); + new QLineEdit(hbox); + return hbox; +} +//! [1] + + +//! [2] +p->setClipRect(table()->cellRect(row, col), QPainter::ClipPainter); +//... your drawing code +p->setClipping(false); +//! [2] + + +//! [3] +Q3Table *table = new Q3Table(100, 250, this); +table->setPixmap(3, 2, pix); +table->setText(3, 2, "A pixmap"); +//! [3] + + +//! [4] +p->setClipRect(cellRect(row, col), QPainter::CoordPainter); +//... your drawing code +p->setClipping(false); +//! [4] + + +//! [5] +Q3TableItem *i = item(row, col); +if (initFromCell || (i && !i->isReplaceable())) + // If we had a Q3TableItem ask the base class to create the editor + return Q3Table::createEditor(row, col, initFromCell); +else + return ...(create your own editor) +//! [5] + +} + diff --git a/doc/src/snippets/code/src_qt3support_network_q3dns.cpp b/doc/src/snippets/code/src_qt3support_network_q3dns.cpp new file mode 100644 index 0000000..9638ff1 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3dns.cpp @@ -0,0 +1,58 @@ +//! [0] +QStringList list = myDns.qualifiedNames(); +QStringList::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [0] + + +//! [1] +Q3ValueList<QHostAddress> list = myDns.addresses(); +Q3ValueList<QHostAddress>::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [1] + + +//! [2] +Q3ValueList<Q3Dns::MailServer> list = myDns.mailServers(); +Q3ValueList<Q3Dns::MailServer>::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [2] + + +//! [3] +Q3ValueList<Q3Dns::Server> list = myDns.servers(); +Q3ValueList<Q3Dns::Server>::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [3] + + +//! [4] +QStringList list = myDns.hostNames(); +QStringList::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [4] + + +//! [5] +QStringList list = myDns.texts(); +QStringList::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [5] diff --git a/doc/src/snippets/code/src_qt3support_network_q3ftp.cpp b/doc/src/snippets/code/src_qt3support_network_q3ftp.cpp new file mode 100644 index 0000000..37e17d4 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3ftp.cpp @@ -0,0 +1,65 @@ +//! [0] +QUrlOperator op( "ftp://ftp.trolltech.com" ); +op.listChildren(); // Asks the server to provide a directory listing +//! [0] + + +//! [1] +Q3Ftp *ftp = new Q3Ftp( this ); // this is an optional QObject parent +ftp->connectToHost( "ftp.trolltech.com" ); +ftp->login(); +//! [1] + + +//! [2] +ftp->connectToHost( "ftp.trolltech.com" ); // id == 1 +ftp->login(); // id == 2 +ftp->cd( "qt" ); // id == 3 +ftp->get( "INSTALL" ); // id == 4 +ftp->close(); // id == 5 +//! [2] + + +//! [3] +start( 1 ) +stateChanged( HostLookup ) +stateChanged( Connecting ) +stateChanged( Connected ) +finished( 1, false ) + +start( 2 ) +stateChanged( LoggedIn ) +finished( 2, false ) + +start( 3 ) +finished( 3, false ) + +start( 4 ) +dataTransferProgress( 0, 3798 ) +dataTransferProgress( 2896, 3798 ) +readyRead() +dataTransferProgress( 3798, 3798 ) +readyRead() +finished( 4, false ) + +start( 5 ) +stateChanged( Closing ) +stateChanged( Unconnected ) +finished( 5, false ) + +done( false ) +//! [3] + + +//! [4] +start( 1 ) +stateChanged( HostLookup ) +stateChanged( Connecting ) +stateChanged( Connected ) +finished( 1, false ) + +start( 2 ) +finished( 2, true ) + +done( true ) +//! [4] diff --git a/doc/src/snippets/code/src_qt3support_network_q3http.cpp b/doc/src/snippets/code/src_qt3support_network_q3http.cpp new file mode 100644 index 0000000..6729c5f --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3http.cpp @@ -0,0 +1,74 @@ +//! [0] +content-type: text/html +//! [0] + + +//! [1] +header.setValue( "content-type", "text/html" ); +QString contentType = header.value( "content-type" ); +//! [1] + + +//! [2] +QUrlOperator op( "http://qtsoftware.com" ); +op.get( "index.html" ); +//! [2] + + +//! [3] +Q3HttpRequestHeader header( "GET", "/index.html" ); +header.setValue( "Host", "qtsoftware.com" ); +http->setHost( "qtsoftware.com" ); +http->request( header ); +//! [3] + + +//! [4] +http->setHost( "qtsoftware.com" ); // id == 1 +http->get( "/index.html" ); // id == 2 +//! [4] + + +//! [5] +requestStarted( 1 ) +requestFinished( 1, false ) + +requestStarted( 2 ) +stateChanged( Connecting ) +stateChanged( Sending ) +dataSendProgress( 77, 77 ) +stateChanged( Reading ) +responseHeaderReceived( responseheader ) +dataReadProgress( 5388, 0 ) +readyRead( responseheader ) +dataReadProgress( 18300, 0 ) +readyRead( responseheader ) +stateChanged( Connected ) +requestFinished( 2, false ) + +done( false ) + +stateChanged( Closing ) +stateChanged( Unconnected ) +//! [5] + + +//! [6] +http->setHost( "www.foo.bar" ); // id == 1 +http->get( "/index.html" ); // id == 2 +http->post( "register.html", data ); // id == 3 +//! [6] + + +//! [7] +requestStarted( 1 ) +requestFinished( 1, false ) + +requestStarted( 2 ) +stateChanged( HostLookup ) +requestFinished( 2, true ) + +done( true ) + +stateChanged( Unconnected ) +//! [7] diff --git a/doc/src/snippets/code/src_qt3support_network_q3localfs.cpp b/doc/src/snippets/code/src_qt3support_network_q3localfs.cpp new file mode 100644 index 0000000..243be9e --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3localfs.cpp @@ -0,0 +1,4 @@ +//! [0] +Q3UrlOperator op( "file:///tmp" ); +op.listChildren(); // Asks the server to provide a directory listing +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_network_q3networkprotocol.cpp b/doc/src/snippets/code/src_qt3support_network_q3networkprotocol.cpp new file mode 100644 index 0000000..51d1059 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3networkprotocol.cpp @@ -0,0 +1,8 @@ +//! [0] +Q3NetworkProtocol::registerNetworkProtocol( "nntp", new Q3NetworkProtocolFactory<Nntp> ); +//! [0] + + +//! [1] +Q3Ftp *ftp = Q3NetworkProtocol::getNetworkProtocol( "ftp" ); +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_network_q3socket.cpp b/doc/src/snippets/code/src_qt3support_network_q3socket.cpp new file mode 100644 index 0000000..34474fb --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3socket.cpp @@ -0,0 +1,4 @@ +//! [0] +while( !socket->canReadLine() ) // WRONG + ; +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_network_q3socketdevice.cpp b/doc/src/snippets/code/src_qt3support_network_q3socketdevice.cpp new file mode 100644 index 0000000..cd50fd2 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3socketdevice.cpp @@ -0,0 +1,4 @@ +//! [0] +::close( sd->socket() ); +sd->writeBlock( someData, 42 ); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_network_q3url.cpp b/doc/src/snippets/code/src_qt3support_network_q3url.cpp new file mode 100644 index 0000000..3b78a57 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3url.cpp @@ -0,0 +1,43 @@ +//! [0] +Q3Url url( "http://qtsoftware.com" ); +// or +Q3Url url( "file:///home/myself/Mail", "Inbox" ); +//! [0] + + +//! [1] +Q3Url url( "http://qtsoftware.com" ); +QString s = url; +// or +QString s( "http://qtsoftware.com" ); +Q3Url url( s ); +//! [1] + + +//! [2] +Q3Url url( "ftp://ftp.trolltech.com/qt/source", "qt-2.1.0.tar.gz" ); +//! [2] + + +//! [3] +Q3Url url( "ftp://ftp.trolltech.com/qt/source", "/usr/local" ); +//! [3] + + +//! [4] +Q3Url url( "ftp://ftp.trolltech.com/qt/source", "file:///usr/local" ); +//! [4] + + +//! [5] +QString url = http://qtsoftware.com +Q3Url::encode( url ); +// url is now "http%3A//www%20trolltech%20com" +//! [5] + + +//! [6] +QString url = "http%3A//www%20trolltech%20com" +Q3Url::decode( url ); +// url is now "http://qtsoftware.com" +//! [6] diff --git a/doc/src/snippets/code/src_qt3support_network_q3urloperator.cpp b/doc/src/snippets/code/src_qt3support_network_q3urloperator.cpp new file mode 100644 index 0000000..03b8f7b --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_network_q3urloperator.cpp @@ -0,0 +1,37 @@ +//! [0] +Q3UrlOperator *op = new Q3UrlOperator(); +op->copy( QString("ftp://ftp.trolltech.com/qt/source/qt-2.1.0.tar.gz"), + "file:///tmp" ); +//! [0] + + +//! [1] +Q3UrlOperator op( "http://www.whatever.org/cgi-bin/search.pl?cmd=Hello" ); +op.get(); +//! [1] + + +//! [2] +Q3UrlOperator op( "ftp://ftp.whatever.org/pub" ); +// do some other stuff like op.listChildren() or op.mkdir( "new_dir" ) +op.get( "a_file.txt" ); +//! [2] + + +//! [3] +Q3UrlOperator op( "http://www.whatever.org/cgi-bin" ); +op.get( "search.pl?cmd=Hello" ); // WRONG! +//! [3] + + +//! [4] +Q3UrlOperator op( "ftp://ftp.whatever.com/home/me/filename.dat" ); +op.put( data ); +//! [4] + + +//! [5] +Q3UrlOperator op( "ftp://ftp.whatever.com/home/me" ); +// do some other stuff like op.listChildren() or op.mkdir( "new_dir" ) +op.put( data, "filename.dat" ); +//! [5] diff --git a/doc/src/snippets/code/src_qt3support_other_q3accel.cpp b/doc/src/snippets/code/src_qt3support_other_q3accel.cpp new file mode 100644 index 0000000..ba315c0 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_other_q3accel.cpp @@ -0,0 +1,40 @@ +//! [0] +QPushButton p("&Exit", parent); // automatic shortcut Alt+E +Q3PopupMenu *fileMenu = new fileMenu(parent); +fileMenu->insertItem("Undo", parent, SLOT(undo()), + Qt::CTRL + Qt::Key_Z); +//! [0] + + +//! [1] +accelerator->insertItem(QKeySequence("M")); +//! [1] + + +//! [2] +Q3Accel *a = new Q3Accel(myWindow); +a->connectItem(a->insertItem(Qt::CTRL + Qt::Key_P), + myWindow, SLOT(printDoc())); +//! [2] + + +//! [3] +Q3Accel *a = new Q3Accel(myWindow); // create accels for myWindow +a->insertItem(CTRL + Key_P, 200); // Ctrl+P, e.g. to print document +a->insertItem(ALT + Key_X, 201); // Alt+X, e.g. to quit +a->insertItem(UNICODE_ACCEL + 'q', 202); // Unicode 'q', e.g. to quit +a->insertItem(Key_D); // gets a unique negative id < -1 +a->insertItem(CTRL + SHIFT + Key_P); // gets a unique negative id < -1 +//! [3] + + +//! [4] +a->connectItem(201, mainView, SLOT(quit())); +//! [4] + + +//! [5] +Q3PopupMenu *file = new Q3PopupMenu(this); +file->insertItem(p1, tr("&Open..."), this, SLOT(open()), + Q3Accel::stringToKey(tr("Ctrl+O", "File|Open"))); +//! [5] diff --git a/doc/src/snippets/code/src_qt3support_other_q3mimefactory.cpp b/doc/src/snippets/code/src_qt3support_other_q3mimefactory.cpp new file mode 100644 index 0000000..f00ad73 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_other_q3mimefactory.cpp @@ -0,0 +1,32 @@ +//! [0] +static const char* myimage_data[]={ +"...", +... +"..."}; +//! [0] + + +//! [1] +Q3MimeSourceFactory::defaultFactory()->setImage("myimage", QImage(myimage_data)); +//! [1] + + +//! [2] +QLabel* label = new QLabel( + "Rich text with embedded image:<img source=\"myimage\">" + "Isn't that <em>cute</em>?"); +//! [2] + + +//! [3] +delete label; +Q3MimeSourceFactory::defaultFactory()->setData("myimage", 0); +//! [3] + + +//! [4] +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"); +//! [4] diff --git a/doc/src/snippets/code/src_qt3support_other_q3process.cpp b/doc/src/snippets/code/src_qt3support_other_q3process.cpp new file mode 100644 index 0000000..2ce94bb --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_other_q3process.cpp @@ -0,0 +1,8 @@ +//! [0] +QStringList list = myProcess.arguments(); +QStringList::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_other_q3process_unix.cpp b/doc/src/snippets/code/src_qt3support_other_q3process_unix.cpp new file mode 100644 index 0000000..c443c2e --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_other_q3process_unix.cpp @@ -0,0 +1,4 @@ +//! [0] +process->tryTerminate(); +QTimer::singleShot( 5000, process, SLOT(kill()) ); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_painting_q3paintdevicemetrics.cpp b/doc/src/snippets/code/src_qt3support_painting_q3paintdevicemetrics.cpp new file mode 100644 index 0000000..1e807d5 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_painting_q3paintdevicemetrics.cpp @@ -0,0 +1,4 @@ +//! [0] +Q3PaintDeviceMetrics pdm(myWidget); +double aspect = (double)pdm.widthMM() / (double)pdm.heightMM(); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_painting_q3painter.cpp b/doc/src/snippets/code/src_qt3support_painting_q3painter.cpp new file mode 100644 index 0000000..e932250 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_painting_q3painter.cpp @@ -0,0 +1,4 @@ +//! [0] +QPainter p(myWidget); +p.drawArc(QRect(10,10, 70,100), 100*16, 160*16); // draws a "(" arc +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_painting_q3picture.cpp b/doc/src/snippets/code/src_qt3support_painting_q3picture.cpp new file mode 100644 index 0000000..709b386 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_painting_q3picture.cpp @@ -0,0 +1,14 @@ +//! [0] +Q3Picture picture; +picture.load("drawing.svg", SVG); +//! [0] + + +//! [1] +Q3Picture picture; +QPainter painter; +painter.begin(&picture); // paint in picture +... +painter.end(); // painting done +picture.save("drawing.svg", SVG); // save picture +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3databrowser.cpp b/doc/src/snippets/code/src_qt3support_sql_q3databrowser.cpp new file mode 100644 index 0000000..cb86b32 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3databrowser.cpp @@ -0,0 +1,8 @@ +//! [0] +QStringList list = myDataBrowser.sort(); +QStringList::Iterator it = list.begin(); +while(it != list.end()) { + myProcessing(*it); + ++it; +} +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3datatable.cpp b/doc/src/snippets/code/src_qt3support_sql_q3datatable.cpp new file mode 100644 index 0000000..aa72f44 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3datatable.cpp @@ -0,0 +1,8 @@ +//! [0] +QStringList list = myDataTable.sort(); +QStringList::Iterator it = list.begin(); +while( it != list.end() ) { + myProcessing( *it ); + ++it; +} +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3dataview.cpp b/doc/src/snippets/code/src_qt3support_sql_q3dataview.cpp new file mode 100644 index 0000000..b0b9a59 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3dataview.cpp @@ -0,0 +1,4 @@ +//! [0] +myView.setRecord(record); +myView.readFields(); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3sqlcursor.cpp b/doc/src/snippets/code/src_qt3support_sql_q3sqlcursor.cpp new file mode 100644 index 0000000..b3b643d --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3sqlcursor.cpp @@ -0,0 +1,100 @@ +//! [0] +Q3SqlCursor 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() ); +} +//! [0] + + +//! [1] +Q3SqlCursor 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(); +} +//! [1] + + +//! [2] +Q3SqlCursor 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")); +... +//! [2] + + +//! [3] +Q3SqlCursor 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 +... +//! [3] + + +//! [4] +Q3SqlCursor cur("Employee"); +QSqlIndex pk = cur.primaryIndex(); +cur.setValue("id", 10); +cur.select(pk, pk); // generates "SELECT ... FROM Employee WHERE id=10 ORDER BY id" +... +//! [4] + + +//! [5] +Q3SqlCursor cur("Employee"); +cur.setMode(Q3SqlCursor::Writable); // allow insert/update/delete +... +cur.setMode(Q3SqlCursor::Insert | Q3SqlCursor::Update); // allow inserts and updates only +... +cur.setMode(Q3SqlCursor::ReadOnly); // no inserts/updates/deletes allowed + +//! [5] + + +//! [6] +Q3SqlCursor cur("prices"); +QSqlRecord *buffer = cur.primeInsert(); +buffer->setValue("id", 53981); +buffer->setValue("name", "Thingy"); +buffer->setValue("price", 105.75); +cur.insert(); +//! [6] + + +//! [7] +Q3SqlCursor 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(); +} +//! [7] + + +//! [8] +Q3SqlCursor cur("prices"); +cur.select("id=999"); +if (cur.next()) { + cur.primeDelete(); + cur.del(); +} +//! [8] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3sqlform.cpp b/doc/src/snippets/code/src_qt3support_sql_q3sqlform.cpp new file mode 100644 index 0000000..e91b7ed --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3sqlform.cpp @@ -0,0 +1,26 @@ +//! [0] +QLineEdit myEditor(this); +Q3SqlForm myForm(this); +Q3SqlCursor 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 +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3sqlmanager_p.cpp b/doc/src/snippets/code/src_qt3support_sql_q3sqlmanager_p.cpp new file mode 100644 index 0000000..9d5b2c1 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3sqlmanager_p.cpp @@ -0,0 +1,11 @@ +//! [0] +Q3SqlCursor* myCursor = myManager.cursor(); +... +QSqlRecord* buf = myCursor->primeUpdate(); +buf->setValue("name", "Ola"); +buf->setValue("city", "Oslo"); +... +myCursor->update(); // update current record +myCursor->select(); // refresh the cursor +myManager.findBuffer(myCursor->primaryIndex()); // go to the updated record +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3sqlpropertymap.cpp b/doc/src/snippets/code/src_qt3support_sql_q3sqlpropertymap.cpp new file mode 100644 index 0000000..55146de --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3sqlpropertymap.cpp @@ -0,0 +1,35 @@ +//! [0] +Q3SqlPropertyMap *myMap = new Q3SqlPropertyMap(); +Q3SqlForm *myForm = new Q3SqlForm(this); +MyEditor myEditor(this); + +// Set the Q3SqlForm's record buffer to the update buffer of +// a pre-existing Q3SqlCursor 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(); +... +//! [0] + + +//! [1] +Q3SqlPropertyMap *myMap = new Q3SqlPropertyMap; + +myMap->insert("MyEditor", "content"); +Q3SqlPropertyMap::installDefaultMap(myMap); +... +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_sql_q3sqlselectcursor.cpp b/doc/src/snippets/code/src_qt3support_sql_q3sqlselectcursor.cpp new file mode 100644 index 0000000..bfb7b04 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_sql_q3sqlselectcursor.cpp @@ -0,0 +1,11 @@ +//! [0] +... +Q3SqlSelectCursor* cur = new Q3SqlSelectCursor("SELECT id, firstname, lastname FROM author"); +Q3DataTable* table = new Q3DataTable(this); +table->setSqlCursor(cur, true, true); +table->refresh(); +... +cur->exec("SELECT * FROM books"); +table->refresh(); +... +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_text_q3simplerichtext.cpp b/doc/src/snippets/code/src_qt3support_text_q3simplerichtext.cpp new file mode 100644 index 0000000..073d716 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_text_q3simplerichtext.cpp @@ -0,0 +1,3 @@ +//! [0] +Q3SimpleRichText myrichtext(contents, mywidget->font()); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_text_q3textbrowser.cpp b/doc/src/snippets/code/src_qt3support_text_q3textbrowser.cpp new file mode 100644 index 0000000..b042efb --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_text_q3textbrowser.cpp @@ -0,0 +1,3 @@ +//! [0] +mimeSourceFactory()->setExtensionType("qml", "text/utf8"); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_text_q3textedit.cpp b/doc/src/snippets/code/src_qt3support_text_q3textedit.cpp new file mode 100644 index 0000000..e8d5784 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_text_q3textedit.cpp @@ -0,0 +1,31 @@ +//! [0] +QFile file(fileName); // Read the text from a file +if (file.open(IO_ReadOnly)) { + QTextStream stream(&file); + textEdit->setText(stream.read()); +} + +QFile file(fileName); // Write the text to a file +if (file.open(IO_WriteOnly)) { + QTextStream stream(&file); + stream << textEdit->text(); + textEdit->setModified(false); +} +//! [0] + + +//! [1] +This is <font color=red>red</font> while <b>this</b> is <font color=blue>blue</font>. +<font color=green><font color=yellow>Yellow,</font> and <u>green</u>. +//! [1] + + +//! [2] +Q3TextEdit * log = new Q3TextEdit(this); +log->setTextFormat(Qt::LogText); +Q3StyleSheetItem * item = new Q3StyleSheetItem(log->styleSheet(), "mytag"); +item->setColor("red"); +item->setFontWeight(QFont::Bold); +item->setFontUnderline(true); +log->append("This is a <mytag>custom tag</mytag>!"); +//! [2] diff --git a/doc/src/snippets/code/src_qt3support_text_q3textstream.cpp b/doc/src/snippets/code/src_qt3support_text_q3textstream.cpp new file mode 100644 index 0000000..664a690 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_text_q3textstream.cpp @@ -0,0 +1,29 @@ +//! [0] +QString str; +Q3TextStream ts( &str, IO_WriteOnly ); +ts << "pi = " << 3.14; // str == "pi = 3.14" +//! [0] + + +//! [1] +QString str = "pi = 3.14"; +Q3TextStream ts( &str, IO_WriteOnly ); +ts << "2+2 = " << 2+2; // str == "2+2 = 414" +//! [1] + + +//! [2] +QByteArray array; +Q3TextStream ts( array, IO_WriteOnly ); +ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14" +//! [2] + + +//! [3] +QByteArray array; +QBuffer buf( array ); +buf.open( IO_WriteOnly ); +Q3TextStream ts( &buf ); +ts << "pi = " << 3.14 << '\0'; // array == "pi = 3.14" +buf.close(); +//! [3] diff --git a/doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp b/doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp new file mode 100644 index 0000000..9985e9d --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp @@ -0,0 +1,40 @@ +//! [0] +Q3CString str("helloworld", 6); // assigns "hello" to str +//! [0] + + +//! [1] +Q3CString a; // a.data() == 0, a.size() == 0, a.length() == 0 +Q3CString b == ""; // b.data() == "", b.size() == 1, b.length() == 0 +a.isNull(); // true because a.data() == 0 +a.isEmpty(); // true because a.length() == 0 +b.isNull(); // false because b.data() == "" +b.isEmpty(); // true because b.length() == 0 +//! [1] + + +//! [2] +Q3CString s = "truncate this string"; +s.truncate(5); // s == "trunc" +//! [2] + + +//! [3] +Q3CString s; +s.sprintf("%d - %s", 1, "first"); // result < 256 chars + +Q3CString big(25000); // very long string +big.sprintf("%d - %s", 2, longString); // result < 25000 chars +//! [3] + + +//! [4] +Q3CString s("apple"); +Q3CString t = s.leftJustify(8, '.'); // t == "apple..." +//! [4] + + +//! [5] +Q3CString s("pie"); +Q3CString t = s.rightJustify(8, '.'); // t == ".....pie" +//! [5] diff --git a/doc/src/snippets/code/src_qt3support_tools_q3deepcopy.cpp b/doc/src/snippets/code/src_qt3support_tools_q3deepcopy.cpp new file mode 100644 index 0000000..36f7491 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_tools_q3deepcopy.cpp @@ -0,0 +1,58 @@ +//! [0] +// all 5 strings share the same data +QString s1 = "abcd"; +QString s2 = s1; +QString s3 = s2; +QString s4 = s3; +QString s5 = s2; +//! [0] + + +//! [1] +// s1, s2 and s5 share the same data, neither s3 nor s4 are shared +QString s1 = "abcd"; +QString s2 = s1; +Q3DeepCopy<QString> s3 = s2; // s3 is a deep copy of s2 +QString s4 = s3; // s4 is a deep copy of s3 +QString s5 = s2; +//! [1] + + +//! [2] +// s1, s2 and s5 share the same data, s3 and s4 share the same data +QString s1 = "abcd"; +QString s2 = s1; +QString s3 = Q3DeepCopy<QString>( s2 ); // s3 is a deep copy of s2 +QString s4 = s3; // s4 is a shallow copy of s3 +QString s5 = s2; +//! [2] + + +//! [3] +Q3DeepCopy<QString> global_string; // global string data +QMutex global_mutex; // mutex to protext global_string + +... + +void setGlobalString( const QString &str ) +{ + global_mutex.lock(); + global_string = str; // global_string is a deep copy of str + global_mutex.unlock(); +} + +... + +void MyThread::run() +{ + global_mutex.lock(); + QString str = global_string; // str is a deep copy of global_string + global_mutex.unlock(); + + // process the string data + ... + + // update global_string + setGlobalString( str ); +} +//! [3] diff --git a/doc/src/snippets/code/src_qt3support_tools_q3garray.cpp b/doc/src/snippets/code/src_qt3support_tools_q3garray.cpp new file mode 100644 index 0000000..7108262 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_tools_q3garray.cpp @@ -0,0 +1,20 @@ +//! [0] +static uchar bindata[] = { 231, 1, 44, ... }; +QByteArray a; +a.setRawData(bindata, sizeof(bindata)); // a points to bindata +QDataStream s(a, IO_ReadOnly); // open on a's data +s >> <something>; // read raw bindata +s.close(); +a.resetRawData(bindata, sizeof(bindata)); // finished +//! [0] + + +//! [1] +static uchar bindata[] = { 231, 1, 44, ... }; +QByteArray a, b; +a.setRawData(bindata, sizeof(bindata)); // a points to bindata +a.resize(8); // will crash +b = a; // will crash +a[2] = 123; // might crash + // forget to resetRawData - will crash +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_tools_q3signal.cpp b/doc/src/snippets/code/src_qt3support_tools_q3signal.cpp new file mode 100644 index 0000000..7793ba2 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_tools_q3signal.cpp @@ -0,0 +1,38 @@ +//! [0] +#include <q3signal.h> + +class MyClass +{ +public: + MyClass(); + ~MyClass(); + + void doSomething(); + + void connect(QObject *receiver, const char *member); + +private: + Q3Signal *sig; +}; + +MyClass::MyClass() +{ + sig = new Q3Signal; +} + +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); +} +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3combobox.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3combobox.cpp new file mode 100644 index 0000000..90d7b14 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3combobox.cpp @@ -0,0 +1,15 @@ +//! [0] +Q3ComboBox *c = new Q3ComboBox(this, tr("read-only combobox")); +//! [0] + + +//! [1] +Q3ComboBox *c1 = new Q3ComboBox(false, this, tr("read-only combobox")); +Q3ComboBox *c2 = new Q3ComboBox(true, this, tr("editable combobox")); +//! [1] + + +//! [2] +static const char* items[] = { "red", "green", "blue", 0 }; +combo->insertStrList( items ); +//! [2] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3datetimeedit.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3datetimeedit.cpp new file mode 100644 index 0000000..74070ec --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3datetimeedit.cpp @@ -0,0 +1,28 @@ + +void wrapInFunction() +{ + +//! [0] +Q3DateEdit *dateEdit = new Q3DateEdit(QDate::currentDate(), this); +dateEdit->setRange(QDate::currentDate().addDays(-365), + QDate::currentDate().addDays( 365)); +dateEdit->setOrder(Q3DateEdit::MDY); +dateEdit->setAutoAdvance(true); +//! [0] + + +//! [1] +QTime timeNow = QTime::currentTime(); +Q3TimeEdit *timeEdit = new Q3TimeEdit(timeNow, this); +timeEdit->setRange(timeNow, timeNow.addSecs(60 * 60)); +//! [1] + + +//! [2] +Q3DateTimeEdit *dateTimeEdit = new Q3DateTimeEdit(QDateTime::currentDateTime(), this); +dateTimeEdit->dateEdit()->setRange(QDateTime::currentDate(), + QDateTime::currentDate().addDays(7)); +//! [2] + +} + diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3dockarea.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3dockarea.cpp new file mode 100644 index 0000000..bde7d84 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3dockarea.cpp @@ -0,0 +1,8 @@ +//! [0] +ts << *myDockArea; +//! [0] + + +//! [1] +ts >> *myDockArea; +//! [1] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3dockwindow.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3dockwindow.cpp new file mode 100644 index 0000000..1476dcb --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3dockwindow.cpp @@ -0,0 +1,4 @@ +//! [0] +Q3ToolBar *fileTools = new Q3ToolBar(this, "File Actions"); +moveDockWindow(fileTools, Left); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3gridview.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3gridview.cpp new file mode 100644 index 0000000..43dca3e --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3gridview.cpp @@ -0,0 +1,6 @@ +//! [0] +p->setClipRect(cellRect(), QPainter::CoordPainter); +//... your drawing code +p->setClipping(false); + +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3header.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3header.cpp new file mode 100644 index 0000000..684d182 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3header.cpp @@ -0,0 +1,6 @@ +//! [0] +// Allow resizing of all current and future sections +header->setResizeEnabled(true); +// Disable resizing of section 3, (the fourth section added) +header->setResizeEnabled(false, 3); +//! [0] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3mainwindow.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3mainwindow.cpp new file mode 100644 index 0000000..c63b481 --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3mainwindow.cpp @@ -0,0 +1,45 @@ +//! [0] +Q3MainWindow *mw = new Q3MainWindow; +QTextEdit *edit = new QTextEdit(mw, "editor"); +edit->setFocus(); +mw->setWindowTitle("Main Window"); +mw->setCentralWidget(edit); +mw->show(); +//! [0] + + +//! [1] +Q3ToolBar *tb = new Q3ToolBar(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); +//! [1] + + +//! [2] +QFile file(filename); +if (file.open(IO_WriteOnly)) { + QTextStream stream(&file); + stream << *mainWindow; + file.close(); +} +//! [2] + + +//! [3] +QFile file(filename); +if (file.open(IO_ReadOnly)) { + QTextStream stream(&file); + stream >> *mainWindow; + file.close(); +} +//! [3] + + +//! [4] +Q3PopupMenu * help = new Q3PopupMenu(this); +help->insertItem("What's &This", this , SLOT(enterWhatsThis()), Qt::SHIFT+Qt::Key_F1); +//! [4] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3scrollview.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3scrollview.cpp new file mode 100644 index 0000000..58d5acf --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3scrollview.cpp @@ -0,0 +1,61 @@ +//! [0] +Q3ScrollView* sv = new Q3ScrollView(...); +QWidget *widget = new QWidget(sv->viewport()); +QVBoxLayout *layout = new QVBoxLayout(widget); +addChild(widget); +//! [0] + + +//! [1] +QLabel* child1 = new QLabel("CHILD", widget); +QLabel* child2 = new QLabel("CHILD", widget); +QLabel* child3 = new QLabel("CHILD", widget); +layout->addWidget(child1); +layout->addWidget(child2); +layout->addWidget(child3); +... +//! [1] + + +//! [2] +Q3ScrollView* sv = new Q3ScrollView(...); +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); +//! [2] + + +//! [3] +Q3ScrollView* sv = new Q3ScrollView(...); +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); +//! [3] + + +//! [4] +{ + // Fill a 40000 by 50000 rectangle at (100000,150000) + + // Calculate the coordinates... + int x1 = 100000, y1 = 150000; + int x2 = x1+40000-1, y2 = y1+50000-1; + + // Clip the coordinates so X/Windows will not have problems... + 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; + + // Paint using the small coordinates... + if (x2 >= x1 && y2 >= y1) + p->fillRect(x1, y1, x2-x1+1, y2-y1+1, red); +} +//! [4] diff --git a/doc/src/snippets/code/src_qt3support_widgets_q3whatsthis.cpp b/doc/src/snippets/code/src_qt3support_widgets_q3whatsthis.cpp new file mode 100644 index 0000000..f7b48ba --- /dev/null +++ b/doc/src/snippets/code/src_qt3support_widgets_q3whatsthis.cpp @@ -0,0 +1,3 @@ +//! [0] +(void)Q3WhatsThis::whatsThisButton( my_help_tool_bar ); +//! [0] diff --git a/doc/src/snippets/code/src_qtestlib_qtestcase.cpp b/doc/src/snippets/code/src_qtestlib_qtestcase.cpp new file mode 100644 index 0000000..c143e33 --- /dev/null +++ b/doc/src/snippets/code/src_qtestlib_qtestcase.cpp @@ -0,0 +1,188 @@ + +void wrapInFunction() +{ + +//! [0] +QVERIFY(1 + 1 == 2); +//! [0] + + +//! [1] +QVERIFY2(1 + 1 == 2, "A breach in basic arithmetic occured."); +//! [1] + + +//! [2] +QCOMPARE(QString("hello").toUpper(), QString("HELLO")); +//! [2] + + +//! [3] +void TestQString::toInt_data() +{ + QTest::addColumn<QString>("aString"); + QTest::addColumn<int>("expected"); + + QTest::newRow("positive value") << "42" << 42; + QTest::newRow("negative value") << "-42" << -42; + QTest::newRow("zero") << "0" << 0; +} +//! [3] + + +//! [4] +void TestQString::toInt() +{ + QFETCH(QString, aString); + QFETCH(int, expected); + + QCOMPARE(aString.toInt(), expected); +} +//! [4] + + +//! [5] +if (sizeof(int) != 4) + QFAIL("This test has not been ported to this platform yet."); +//! [5] + + +//! [6] +QFETCH(QString, myString); +QCOMPARE(QString("hello").toUpper(), myString); +//! [6] + + +//! [7] +QTEST(QString("hello").toUpper(), "myString"); +//! [7] + + +//! [8] +if (!QSqlDatabase::drivers().contains("SQLITE")) + QSKIP("This test requires the SQLITE database driver", SkipAll); +//! [8] + + +//! [9] +QEXPECT_FAIL("", "Will fix in the next release", Continue); +QCOMPARE(i, 42); +QCOMPARE(j, 43); +//! [9] + + +//! [10] +QEXPECT_FAIL("data27", "Oh my, this is soooo broken", Abort); +QCOMPARE(i, 42); +//! [10] + + +//! [11] +class TestQString: public QObject { ... }; +QTEST_MAIN(TestQString) +//! [11] + + +//! [12] +#ifdef Q_WS_X11 + QTEST_MAIN(MyX11Test) +#else + // do nothing on non-X11 platforms + QTEST_NOOP_MAIN +#endif +//! [12] + + +//! [13] +QTest::keyClick(myWidget, 'a'); +//! [13] + + +//! [14] +QTest::keyClick(myWidget, Qt::Key_Escape); + +QTest::keyClick(myWidget, Qt::Key_Escape, Qt::ShiftModifier, 200); +//! [14] + + +//! [15] +QTest::keyClicks(myWidget, "hello world"); +//! [15] + + +//! [16] +namespace QTest { + template<> + char *toString(const MyPoint &point) + { + QByteArray ba = "MyPoint("; + ba += QByteArray::number(point.x()) + ", " + QByteArray::number(point.y()); + ba += ")"; + return qstrdup(ba.data()); + } +} +//! [16] + + +//! [17] +int i = 0; +while (myNetworkServerNotResponding() && i++ < 50) + QTest::qWait(250); +//! [17] + + +//! [18] +MyFirstTestObject test1; +QTest::qExec(&test1); + +MySecondTestObject test2; +QTest::qExec(&test2); +//! [18] + + +//! [19] +QDir dir; + +QTest::ignoreMessage(QtWarningMsg, "QDir::mkdir: Empty or null file name(s)"); +dir.mkdir(""); +//! [19] + + +//! [20] +void myTestFunction_data() +{ + QTest::addColumn<QString>("aString"); + QTest::newRow("just hello") << QString("hello"); + QTest::newRow("a null string") << QString(); +} +//! [20] + + +//! [21] +void myTestFunction_data() { + QTest::addColumn<int>("intval"); + QTest::addColumn<QString>("str"); + QTest::addColumn<double>("dbl"); + + QTest::newRow("row1") << 1 << "hello" << 1.5; +} +//! [21] + + +//! [22] +void MyTestClass::cleanup() +{ + if (qstrcmp(currentTestFunction(), "myDatabaseTest") == 0) { + // clean up all database connections + closeAllDatabases(); + } +} +//! [22] + + +//! [23] +QTest::qSleep(250); +//! [23] + +} + diff --git a/doc/src/snippets/code/src_script_qscriptable.cpp b/doc/src/snippets/code/src_script_qscriptable.cpp new file mode 100644 index 0000000..3a02d51 --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptable.cpp @@ -0,0 +1,25 @@ +//! [0] +class MyScriptableObject: public QObject, + protected QScriptable +{ + Q_OBJECT +... + +public slots: + void doSomething(); + double doSomethingElse(); +} +//! [0] + + +//! [1] +void MyScriptableObject::doSomething() +{ + context()->throwError("Threw an error from a slot"); +} + +double MyScriptableObject::doSomethingElse() +{ + return qscriptvalue_cast<double>(thisObject()); +} +//! [1] diff --git a/doc/src/snippets/code/src_script_qscriptclass.cpp b/doc/src/snippets/code/src_script_qscriptclass.cpp new file mode 100644 index 0000000..9d55e0f --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptclass.cpp @@ -0,0 +1,10 @@ +//! [0] +if (extension == Callable) { + QScriptContext *context = qvariant_cast<QScriptContext*>(argument); + QScriptEngine *engine = context->engine(); + double sum = 0; + for (int i = 0; i < context->argumentCount(); ++i) + sum += context->argument(i).toNumber(); + return sum; +} +//! [0] diff --git a/doc/src/snippets/code/src_script_qscriptcontext.cpp b/doc/src/snippets/code/src_script_qscriptcontext.cpp new file mode 100644 index 0000000..a2f18158 --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptcontext.cpp @@ -0,0 +1,28 @@ +//! [0] +foo(20.5, "hello", new Object()) +//! [0] + + +//! [1] +QScriptValue Person_prototype_fullName(QScriptContext *context, QScriptEngine *engine) +{ + QScriptValue self = context->thisObject(); + QString result; + result += self.property("firstName").toString(); + result += QLatin1String(" "); + result += self.property("lastName").toString(); + return result; +} +//! [1] + + +//! [2] +QScriptValue myInclude(QScriptContext *ctx, QScriptEngine *eng) +{ + QString fileName = ctx->argument(0).toString(); + QString contents = readTheFile(fileName); + ctx->setActivationObject(ctx->parentContext()->activationObject()); + ctx->setThisObject(ctx->parentContext()->thisObject()); + return eng->evaluate(contents, fileName); +} +//! [2] diff --git a/doc/src/snippets/code/src_script_qscriptengine.cpp b/doc/src/snippets/code/src_script_qscriptengine.cpp new file mode 100644 index 0000000..81d4fbc --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptengine.cpp @@ -0,0 +1,292 @@ +//! [0] +QScriptEngine myEngine; +QScriptValue three = myEngine.evaluate("1 + 2"); +//! [0] + + +//! [1] +QScriptValue fun = myEngine.evaluate("function(a, b) { return a + b; }"); +QScriptValueList args; +args << 1 << 2; +QScriptValue threeAgain = fun.call(QScriptValue(), args); +//! [1] + + +//! [2] +QString fileName = "helloworld.qs"; +QFile scriptFile(fileName); +if (!scriptFile.open(QIODevice::ReadOnly)) + // handle error +QTextStream stream(&scriptFile); +QString contents = stream.readAll(); +scriptFile.close(); +myEngine.evaluate(contents, fileName); +//! [2] + + +//! [3] +myEngine.globalObject().setProperty("myNumber", 123); +... +QScriptValue myNumberPlusOne = myEngine.evaluate("myNumber + 1"); +//! [3] + + +//! [4] +QScriptValue result = myEngine.evaluate(...); +if (myEngine.hasUncaughtException()) { + int line = myEngine.uncaughtExceptionLineNumber(); + qDebug() << "uncaught exception at line" << line << ":" << result.toString(); +} +//! [4] + + +//! [5] +QPushButton button; +QScriptValue scriptButton = myEngine.newQObject(&button); +myEngine.globalObject().setProperty("button", scriptButton); + +myEngine.evaluate("button.checkable = true"); + +qDebug() << scriptButton.property("checkable").toBoolean(); +scriptButton.property("show").call(); // call the show() slot +//! [5] + + +//! [6] +QScriptValue myAdd(QScriptContext *context, QScriptEngine *engine) +{ + QScriptValue a = context->argument(0); + QScriptValue b = context->argument(1); + return a.toNumber() + b.toNumber(); +} +//! [6] + + +//! [7] +QScriptValue fun = myEngine.newFunction(myAdd); +myEngine.globalObject().setProperty("myAdd", fun); +//! [7] + + +//! [8] +QScriptValue result = myEngine.evaluate("myAdd(myNumber, 1)"); +//! [8] + + +//! [9] +QScriptValue Foo(QScriptContext *context, QScriptEngine *engine) +{ + if (context->calledAsConstructor()) { + // initialize the new object + context->thisObject().setProperty("bar", ...); + // ... + // return a non-object value to indicate that the + // thisObject() should be the result of the "new Foo()" expression + return engine->undefinedValue(); + } else { + // not called as "new Foo()", just "Foo()" + // create our own object and return that one + QScriptValue object = engine->newObject(); + object.setPrototype(context->callee().property("prototype")); + object.setProperty("baz", ...); + return object; + } +} + +... + +QScriptValue fooProto = engine->newObject(); +fooProto.setProperty("whatever", ...); +engine->globalObject().setProperty("Foo", engine->newFunction(Foo, fooProto)); +//! [9] + + +//! [10] +class Bar { ... }; + +Q_DECLARE_METATYPE(Bar) + +QScriptValue constructBar(QScriptContext *context, QScriptEngine *engine) +{ + Bar bar; + // initialize from arguments in context, if desired + ... + return engine->toScriptValue(bar); +} + +class BarPrototype : public QObject, public QScriptable +{ +// provide the scriptable interface of this type using slots and properties +... +}; + +... + +// create and register the Bar prototype and constructor in the engine +BarPrototype *barPrototypeObject = new BarPrototype(...); +QScriptValue barProto = engine->newQObject(barPrototypeObject); +engine->setDefaultPrototype(qMetaTypeId<Bar>, barProto); +QScriptValue barCtor = engine->newFunction(constructBar, barProto); +engine->globalObject().setProperty("Bar", barCtor); +//! [10] + + +//! [11] +static QScriptValue getSetFoo(QScriptContext *context, QScriptEngine *engine) +{ + QScriptValue callee = context->callee(); + if (context->argumentCount() == 1) // writing? + callee.setProperty("value", context->argument(0)); + return callee.property("value"); +} + +.... + +QScriptValue object = engine.newObject(); +object.setProperty("foo", engine.newFunction(getSetFoo), + QScriptValue::PropertyGetter | QScriptValue::PropertySetter); +//! [11] + + +//! [12] +QScriptValue object = engine.newObject(); +object.setProperty("foo", engine.newFunction(getFoo), QScriptValue::PropertyGetter); +object.setProperty("foo", engine.newFunction(setFoo), QScriptValue::PropertySetter); +//! [12] + + +//! [13] +Q_SCRIPT_DECLARE_QMETAOBJECT(QLineEdit, QWidget*) + +... + +QScriptValue lineEditClass = engine.scriptValueFromQMetaObject<QLineEdit>(); +engine.globalObject().setProperty("QLineEdit", lineEditClass); +//! [13] + + +//! [14] +if (hello && world) + print("hello world"); +//! [14] + + +//! [15] +if (hello && +//! [15] + + +//! [16] +0 = 0 +//! [16] + + +//! [17] +./test.js +//! [17] + + +//! [18] +foo["bar"] +//! [18] + + +//! [19] +QScriptEngine engine; +QScriptContext *context = engine.pushContext(); +context->activationObject().setProperty("myArg", 123); +engine.evaluate("var tmp = myArg + 42"); +... +engine.popContext(); +//! [19] + + +//! [20] +struct MyStruct { + int x; + int y; +}; +//! [20] + + +//! [21] +Q_DECLARE_METATYPE(MyStruct) +//! [21] + + +//! [22] +QScriptValue toScriptValue(QScriptEngine *engine, const MyStruct &s) +{ + QScriptValue obj = engine->newObject(); + obj.setProperty("x", s.x); + obj.setProperty("y", s.y); + return obj; +} + +void fromScriptValue(const QScriptValue &obj, MyStruct &s) +{ + s.x = obj.property("x").toInt32(); + s.y = obj.property("y").toInt32(); +} +//! [22] + + +//! [23] +qScriptRegisterMetaType(engine, toScriptValue, fromScriptValue); +//! [23] + + +//! [24] +MyStruct s = qscriptvalue_cast<MyStruct>(context->argument(0)); +... +MyStruct s2; +s2.x = s.x + 10; +s2.y = s.y + 20; +QScriptValue v = engine->toScriptValue(s2); +//! [24] + + +//! [25] +QScriptValue createMyStruct(QScriptContext *, QScriptEngine *engine) +{ + MyStruct s; + s.x = 123; + s.y = 456; + return engine->toScriptValue(s); +} +... +QScriptValue ctor = engine.newFunction(createMyStruct); +engine.globalObject().setProperty("MyStruct", ctor); +//! [25] + + +//! [26] +Q_DECLARE_METATYPE(QVector<int>) + +... + +qScriptRegisterSequenceMetaType<QVector<int> >(engine); +... +QVector<int> v = qscriptvalue_cast<QVector<int> >(engine->evaluate("[5, 1, 3, 2]")); +qSort(v.begin(), v.end()); +QScriptValue a = engine->toScriptValue(v); +qDebug() << a.toString(); // outputs "[1, 2, 3, 5]" +//! [26] + +//! [27] +QScriptValue mySpecialQObjectConstructor(QScriptContext *context, + QScriptEngine *engine) +{ + QObject *parent = context->argument(0).toQObject(); + QObject *object = new QObject(parent); + return engine->newQObject(object, QScriptEngine::ScriptOwnership); +} + +... + +QScriptValue ctor = engine.newFunction(mySpecialQObjectConstructor); +QScriptValue metaObject = engine.newQMetaObject(&QObject::staticMetaObject, ctor); +engine.globalObject().setProperty("QObject", metaObject); + +QScriptValue result = engine.evaluate("new QObject()"); +//! [27] diff --git a/doc/src/snippets/code/src_script_qscriptengineagent.cpp b/doc/src/snippets/code/src_script_qscriptengineagent.cpp new file mode 100644 index 0000000..649d782 --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptengineagent.cpp @@ -0,0 +1,12 @@ +//! [0] +var a = Math.random() + 2; +//! [0] + + +//! [1] +function cube(a) { + return a * a * a; +} + +var a = cube(3); +//! [1] diff --git a/doc/src/snippets/code/src_script_qscriptvalue.cpp b/doc/src/snippets/code/src_script_qscriptvalue.cpp new file mode 100644 index 0000000..d050f2e --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptvalue.cpp @@ -0,0 +1,40 @@ +//! [0] +QScriptEngine myEngine; +QScriptValue myObject = myEngine.newObject(); +QScriptValue myOtherObject = myEngine.newObject(); +myObject.setProperty("myChild", myOtherObject); +myObject.setProperty("name", "John Doe"); +//! [0] + + +//! [1] +QScriptValue val(&myEngine, 123); +myObject.setProperty("myReadOnlyProperty", val, QScriptValue::ReadOnly); +//! [1] + + +//! [2] +QScriptEngine engine; +engine.evaluate("function fullName() { return this.firstName + ' ' + this.lastName; }"); +engine.evaluate("somePerson = { firstName: 'John', lastName: 'Doe' }"); + +QScriptValue global = engine.globalObject(); +QScriptValue fullName = global.property("fullName"); +QScriptValue who = global.property("somePerson"); +qDebug() << fullName.call(who).toString(); // "John Doe" + +engine.evaluate("function cube(x) { return x * x * x; }"); +QScriptValue cube = global.property("cube"); +QScriptValueList args; +args << 3; +qDebug() << cube.call(QScriptValue(), args).toNumber(); // 27 +//! [2] + + +//! [3] +QScriptValue myNativeFunction(QScriptContext *ctx, QScriptEngine *) +{ + QScriptValue otherFunction = ...; + return otherFunction.call(ctx->thisObject(), ctx->argumentsObject()); +} +//! [3] diff --git a/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp b/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp new file mode 100644 index 0000000..c9de602 --- /dev/null +++ b/doc/src/snippets/code/src_script_qscriptvalueiterator.cpp @@ -0,0 +1,32 @@ +//! [0] +QScriptValue object; +... +QScriptValueIterator it(object); +while (it.hasNext()) { + it.next(); + qDebug() << it.name() << ": " << it.value().toString(); +} +//! [0] + + +//! [1] +QScriptValue obj = ...; // the object to iterate over +while (obj.isObject()) { + QScriptValueIterator it(obj); + while (it.hasNext()) { + it.next(); + qDebug() << it.name(); + } + obj = obj.prototype(); +} +//! [1] + + +//! [2] +while (it.hasNext()) { + it.next(); + if (it.flags() & QScriptValue::SkipInEnumeration) + continue; + qDebug() << "found enumerated property:" << it.name(); +} +//! [2] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp b/doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp new file mode 100644 index 0000000..8194611 --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqldatabase.cpp @@ -0,0 +1,95 @@ +//! [0] +// WRONG +QSqlDatabase db = QSqlDatabase::database("sales"); +QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); +QSqlDatabase::removeDatabase("sales"); // will output a warning + +// "db" is now a dangling invalid database connection, +// "query" contains an invalid result set +//! [0] + + +//! [1] +{ + QSqlDatabase db = QSqlDatabase::database("sales"); + QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db); +} +// Both "db" and "query" are destroyed because they are out of scope +QSqlDatabase::removeDatabase("sales"); // correct +//! [1] + + +//! [2] +QSqlDatabase::registerSqlDriver("MYDRIVER", + new QSqlDriverCreator<MyDatabaseDriver>); +QSqlDatabase db = QSqlDatabase::addDatabase("MYDRIVER"); +//! [2] + + +//! [3] +... +db = QSqlDatabase::addDatabase("QODBC"); +db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb"); +if (db.open()) { + // success! +} +... +//! [3] + + +//! [4] +... +// MySQL connection +db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server +if (!db.open()) { + db.setConnectOptions(); // clears the connect option string + ... +} +... +// PostgreSQL connection +db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections +if (!db.open()) { + db.setConnectOptions(); // clear options + ... +} +... +// ODBC connection +db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options +if (!db.open()) { + db.setConnectOptions(); // don't try to set this option + ... +} +//! [4] + + +//! [5] +#include "qtdir/src/sql/drivers/psql/qsql_psql.cpp" +//! [5] + + +//! [6] +PGconn *con = PQconnectdb("host=server user=bart password=simpson dbname=springfield"); +QPSQLDriver *drv = new QPSQLDriver(con); +QSqlDatabase db = QSqlDatabase::addDatabase(drv); // becomes the new default connection +QSqlQuery query; +query.exec("SELECT NAME, ID FROM STAFF"); +... +//! [6] + + +//! [7] +unix:LIBS += -lpq +win32:LIBS += libpqdll.lib +//! [7] + + +//! [8] +QSqlDatabase db; +qDebug() << db.isValid(); // Returns false + +db = QSqlDatabase::database("sales"); +qDebug() << db.isValid(); // Returns true if "sales" connection exists + +QSqlDatabase::removeDatabase("sales"); +qDebug() << db.isValid(); // Returns false +//! [8] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqldriver.cpp b/doc/src/snippets/code/src_sql_kernel_qsqldriver.cpp new file mode 100644 index 0000000..d5992c3 --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqldriver.cpp @@ -0,0 +1,24 @@ +//! [0] +QSqlDatabase db = ...; +QVariant v = db.driver()->handle(); +if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0) { + // v.data() returns a pointer to the handle + sqlite3 *handle = *static_cast<sqlite3 **>(v.data()); + if (handle != 0) { // check that it is not NULL + ... + } +} +//! [0] + + +//! [1] +if (v.typeName() == "PGconn*") { + PGconn *handle = *static_cast<PGconn **>(v.data()); + if (handle != 0) ... +} + +if (v.typeName() == "MYSQL*") { + MYSQL *handle = *static_cast<MYSQL **>(v.data()); + if (handle != 0) ... +} +//! [1] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqlerror.cpp b/doc/src/snippets/code/src_sql_kernel_qsqlerror.cpp new file mode 100644 index 0000000..e25948c --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqlerror.cpp @@ -0,0 +1,6 @@ +//! [0] +QSqlQueryModel model; +model.setQuery("select * from myTable"); +if (model.lastError().isValid()) + qDebug() << model.lastError(); +//! [0] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqlindex.cpp b/doc/src/snippets/code/src_sql_kernel_qsqlindex.cpp new file mode 100644 index 0000000..a372c3e --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqlindex.cpp @@ -0,0 +1,8 @@ +//! [0] +QStringList list = myIndex.toStringList(); +QStringList::Iterator it = list.begin(); +while(it != list.end()) { + myProcessing(*it); + ++it; +} +//! [0] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqlquery.cpp b/doc/src/snippets/code/src_sql_kernel_qsqlquery.cpp new file mode 100644 index 0000000..d0544b8 --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqlquery.cpp @@ -0,0 +1,40 @@ +//! [0] +SELECT forename, surname FROM people; +//! [0] + + +//! [1] +QSqlQuery q("select * from employees"); +QSqlRecord rec = q.record(); + +qDebug() << "Number of columns: " << rec.count(); + +int nameCol = rec.indexOf("name"); // index of the field "name" +while (q.next()) + qDebug() << q.value(nameCol).toString(); // output all names +//! [1] + + +//! [2] +QSqlQuery q; +q.prepare("insert into myTable values (?, ?)"); + +QVariantList ints; +ints << 1 << 2 << 3 << 4; +q.addBindValue(ints); + +QVariantList names; +names << "Harald" << "Boris" << "Trond" << QVariant(QVariant::String); +q.addBindValue(names); + +if (!q.execBatch()) + qDebug() << q.lastError(); +//! [2] + + +//! [3] +1 Harald +2 Boris +3 Trond +4 NULL +//! [3] diff --git a/doc/src/snippets/code/src_sql_kernel_qsqlresult.cpp b/doc/src/snippets/code/src_sql_kernel_qsqlresult.cpp new file mode 100644 index 0000000..7e6c913 --- /dev/null +++ b/doc/src/snippets/code/src_sql_kernel_qsqlresult.cpp @@ -0,0 +1,45 @@ +//! [0] +QSqlQuery q; +q.prepare("insert into test (i1, i2, s) values (?, ?, ?)"); + +QVariantList col1; +QVariantList col2; +QVariantList col3; + +col1 << 1 << 3; +col2 << 2 << 4; +col3 << "hello" << "world"; + +q.bindValue(0, col1); +q.bindValue(1, col2); +q.bindValue(2, col3); + +if (!q.execBatch()) + qDebug() << q.lastError(); +//! [0] + + +//! [1] +QSqlQuery query = ... +QVariant v = query.result()->handle(); +if (v.isValid() && qstrcmp(v.typeName(), "sqlite3_stmt*")) { + // v.data() returns a pointer to the handle + sqlite3_stmt *handle = *static_cast<sqlite3_stmt **>(v.data()); + if (handle != 0) { // check that it is not NULL + ... + } +} +//! [1] + + +//! [2] +if (v.typeName() == "PGresult*") { + PGresult *handle = *static_cast<PGresult **>(v.data()); + if (handle != 0) ... +} + +if (v.typeName() == "MYSQL_STMT*") { + MYSQL_STMT *handle = *static_cast<MYSQL_STMT **>(v.data()); + if (handle != 0) ... +} +//! [2] diff --git a/doc/src/snippets/code/src_sql_models_qsqlquerymodel.cpp b/doc/src/snippets/code/src_sql_models_qsqlquerymodel.cpp new file mode 100644 index 0000000..e3bce75 --- /dev/null +++ b/doc/src/snippets/code/src_sql_models_qsqlquerymodel.cpp @@ -0,0 +1,12 @@ +//! [0] +while (myModel->canFetchMore()) + myModel->fetchMore(); +//! [0] + + +//! [1] +QSqlQueryModel model; +model.setQuery("select * from MyTable"); +if (model.lastError().isValid()) + qDebug() << model.lastError(); +//! [1] diff --git a/doc/src/snippets/code/src_svg_qgraphicssvgitem.cpp b/doc/src/snippets/code/src_svg_qgraphicssvgitem.cpp new file mode 100644 index 0000000..f0846e6 --- /dev/null +++ b/doc/src/snippets/code/src_svg_qgraphicssvgitem.cpp @@ -0,0 +1,11 @@ +//! [0] +QSvgRenderer *renderer = new QSvgRenderer(QLatin1String("SvgCardDeck.svg")); +QGraphicsSvgItem *black = new QGraphicsSvgItem(); +QGraphicsSvgItem *red = new QGraphicsSvgItem(); + +black->setSharedRenderer(renderer); +black->setElementId(QLatin1String("black_joker")); + +red->setSharedRenderer(renderer); +red->setElementId(QLatin1String("red_joker")); +//! [0] diff --git a/doc/src/snippets/code/src_xml_dom_qdom.cpp b/doc/src/snippets/code/src_xml_dom_qdom.cpp new file mode 100644 index 0000000..d07d6d2 --- /dev/null +++ b/doc/src/snippets/code/src_xml_dom_qdom.cpp @@ -0,0 +1,178 @@ +//! [0] +QDomDocument doc; +QDomImplementation impl; + +// This will create the element, but the resulting XML document will +// be invalid, because '~' is not a valid character in a tag name. +impl.setInvalidDataPolicy(QDomImplementation::AcceptInvalidData); +QDomElement elt1 = doc.createElement("foo~bar"); + +// This will create an element with the tag name "foobar". +impl.setInvalidDataPolicy(QDomImplementation::DropInvalidData); +QDomElement elt2 = doc.createElement("foo~bar"); + +// This will create a null element. +impl.setInvalidDataPolicy(QDomImplementation::ReturnNullNode); +QDomElement elt3 = doc.createElement("foo~bar"); +//! [0] + + +//! [1] +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; + break; + } + n = n.nextSibling(); +} +//! [1] + + +//! [2] +QDomDocument document; +QDomElement element1 = document.documentElement(); +QDomElement element2 = element1; +//! [2] + + +//! [3] +QDomElement element3 = document.createElement("MyElement"); +QDomElement element4 = document.createElement("MyElement"); +//! [3] + + +//! [4] +<body> +<h1>Heading</h1> +<p>Hello <b>you</b></p> +</body> +//! [4] + + +//! [5] +<h1>Heading</h1> +<p>The text...</p> +<h2>Next heading</h2> +//! [5] + + +//! [6] +<h1>Heading</h1> +<p>The text...</p> +<h2>Next heading</h2> +//! [6] + + +//! [7] +<link href="http://qtsoftware.com" color="red" /> +//! [7] + + +//! [8] +QDomElement e = //... +//... +QDomAttr a = e.attributeNode("href"); +cout << a.value() << endl; // prints "http://qtsoftware.com" +a.setValue("http://doc.trolltech.com"); // change the node's attribute +QDomAttr a2 = e.attributeNode("href"); +cout << a2.value() << endl; // prints "http://doc.trolltech.com" +//! [8] + + +//! [9] +QDomElement e = //... +//... +QString s = e.text() +//! [9] + + +//! [10] +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(); +} +//! [10] + + +//! [11] +QDomDocument doc = // ... +QDomElement root = doc.firstChildElement("database"); +QDomElement elt = root.firstChildElement("entry"); +for (; !elt.isNull(); elt = elt.nextSiblingElement("entry")) { + // ... +} +//! [11] + + +//! [12] +<img src="myimg.png"> +//! [12] + + +//! [13] +<h1>Hello <b>Qt</b> <![CDATA[<xml is cool>]]></h1> +//! [13] + + +//! [14] +Hello Qt <xml is cool> +//! [14] + + +//! [15] +<!-- this is a comment --> +//! [15] + + +//! [16] +QDomDocument doc("mydocument"); +QFile file("mydocument.xml"); +if (!file.open(QIODevice::ReadOnly)) + return; +if (!doc.setContent(&file)) { + file.close(); + return; +} +file.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 << qPrintable(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); +//! [16] + + +//! [17] +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(); +//! [17] diff --git a/doc/src/snippets/code/src_xml_sax_qxml.cpp b/doc/src/snippets/code/src_xml_sax_qxml.cpp new file mode 100644 index 0000000..478cf9d --- /dev/null +++ b/doc/src/snippets/code/src_xml_sax_qxml.cpp @@ -0,0 +1,3 @@ +//! [0] +xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qabstracturiresolver.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qabstracturiresolver.cpp new file mode 100644 index 0000000..990a849 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qabstracturiresolver.cpp @@ -0,0 +1,3 @@ +//! [0] +return baseURI.resolved(relative); +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlforwarditerator.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlforwarditerator.cpp new file mode 100644 index 0000000..f31ea3f --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlforwarditerator.cpp @@ -0,0 +1,3 @@ +//! [0] +OutputType inputToOutputItem(const InputType &inputType) const; +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlnodemodel.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlnodemodel.cpp new file mode 100644 index 0000000..351a30b --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlnodemodel.cpp @@ -0,0 +1,22 @@ +//! [0] +myInstance = QXmlNodeModelIndex(); +//! [0] + +//! [1] +QFile queryFile(argv[1]); +QFile chemistryData(argv[2]); +QString moleculeName = argv[3]; + +QXmlQuery query; +query.setQuery(&queryFile, QUrl::fromLocalFile(queryFile.fileName())); + +ChemistryNodeModel myNodeModel(query.namePool(), chemistryData); +QXmlNodeModelIndex startNode = myNodeModel.nodeFor(moleculeName); +query.bindVariable("queryRoot", startNode); + +QFile out; +out.open(stdout, QIODevice::WriteOnly); + +QXmlSerializer serializer(query, &out); +query.evaluateTo(&serializer); +//! [1] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlreceiver.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlreceiver.cpp new file mode 100644 index 0000000..e286fa9 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qabstractxmlreceiver.cpp @@ -0,0 +1,7 @@ +//! [0] +QXmlQuery query; +query.setQuery("doc('index.html')/html/body/p[1]"); + +QXmlSerializer serializer(query, myOutputDevice); +query.evaluateTo(&serializer); +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qsimplexmlnodemodel.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qsimplexmlnodemodel.cpp new file mode 100644 index 0000000..0906328 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qsimplexmlnodemodel.cpp @@ -0,0 +1,19 @@ +//! [0] +QXmlNodeModelIndex MyTreeModel::nextFromSimpleAxis(SimpleAxis axis, const QXmlNodeModelIndex &ni) const +{ + // Convert the QXmlNodeModelIndex to a value that is specific to what we represent. + const MyValue value = toMyValue(ni); + + switch(axis) + { + case Parent: + return toNodeIndex(value.parent()); + case FirstChild: + case PreviousSibling: + case NextSibling: + // and so on + ; + } + return QXmlNodeModelIndex(); +} +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qxmlformatter.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qxmlformatter.cpp new file mode 100644 index 0000000..d7e6ab1 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qxmlformatter.cpp @@ -0,0 +1,8 @@ +//! [0] +QXmlQuery query; +query.setQuery("doc('index.html')/html/body/p[1]"); + +QXmlFormatter formatter(query, myOutputDevice); +formatter.setIndentationDepth(2); +query.evaluateTo(&formatter); +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qxmlname.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qxmlname.cpp new file mode 100644 index 0000000..2c891b5 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qxmlname.cpp @@ -0,0 +1,8 @@ +// Fills the bits from begin to end with 1s and leaves the rest as 0. + +template<typename IntegralT> +inline IntegralT bitmask(IntegralT begin, IntegralT end) +{ + IntegralT filled_bits = (1 << (end - begin + 1)) - 1; + return filled_bits << begin; +} diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qxmlquery.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qxmlquery.cpp new file mode 100644 index 0000000..76e1b34 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qxmlquery.cpp @@ -0,0 +1,152 @@ +//! [0] + QXmlNamePool namePool(query.namePool()); + query.bindVariable(QXmlName(namePool, localName), value); +//! [0] + + +{ +//! [1] + QByteArray myDocument; + QBuffer buffer(&myDocument); // This is a QIODevice. + buffer.open(QIODevice::ReadOnly); + QXmlQuery query; + query.bindVariable("myDocument", &buffer); + query.setQuery("doc($myDocument)"); +//! [1] +} + + +{ + QIODevice *device = 0; +//! [2] + QXmlNamePool namePool(query.namePool()); + query.bindVariable(QXmlName(namePool, localName), device); +//! [2] + +} + +{ + QIODevice *myOutputDevice = 0; +//! [3] + QFile xq("myquery.xq"); + + QXmlQuery query; + query.setQuery(&xq, QUrl::fromLocalFile(xq.fileName())); + + QXmlSerializer serializer(query, myOutputDevice); + query.evaluateTo(&serializer); +//! [3] +} + +{ + QIODevice *myOutputDevice = 0; +//! [4] + QFile xq("myquery.xq"); + QString fileName("the filename"); + QString publisherName("the publisher"); + qlonglong year = 1234; + + QXmlQuery query; + + query.bindVariable("file", QVariant(fileName)); + query.bindVariable("publisher", QVariant(publisherName)); + query.bindVariable("year", QVariant(year)); + + query.setQuery(&xq, QUrl::fromLocalFile(xq.fileName())); + + QXmlSerializer serializer(query, myOutputDevice); + query.evaluateTo(&serializer); +//! [4] +} + +{ +//! [5] + QFile xq("myquery.xq"); + QString fileName("the filename"); + QString publisherName("the publisher"); + qlonglong year = 1234; + + QXmlQuery query; + + query.bindVariable("file", QVariant(fileName)); + query.bindVariable("publisher", QVariant(publisherName)); + query.bindVariable("year", QVariant(year)); + + query.setQuery(&xq, QUrl::fromLocalFile(xq.fileName())); + + QXmlResultItems result; + query.evaluateTo(&result); + QXmlItem item(result.next()); + while (!item.isNull()) { + if (item.isAtomicValue()) { + QVariant v = item.toAtomicValue(); + switch (v.type()) { + case QVariant::LongLong: + // xs:integer + break; + case QVariant::String: + // xs:string + break; + default: + // error + break; + } + } + else if (item.isNode()) { + QXmlNodeModelIndex i = item.toNodeModelIndex(); + // process node + } + item = result.next(); + } +//! [5] +} + +{ +//! [6] + QFile xq("myquery.xq"); + + QXmlQuery query; + query.setQuery(&xq, QUrl::fromLocalFile(xq.fileName())); + + QXmlResultItems result; + query.evaluateTo(&result); + QXmlItem item(result.next()); + while (!item.isNull()) { + if (item.isAtomicValue()) { + QVariant v = item.toAtomicValue(); + switch (v.type()) { + case QVariant::LongLong: + // xs:integer + break; + case QVariant::String: + // xs:string + break; + default: + if (v.userType() == qMetaTypeId<QXmlName>()) { + QXmlName n = qVariantValue<QXmlName>(v); + // process QXmlName n... + } + else { + // error + } + break; + } + } + else if (item.isNode()) { + QXmlNodeModelIndex i = item.toNodeModelIndex(); + // process node + } + item = result.next(); + } +//! [6] +} + +{ + QIODevice *out = 0; +//! [7] + QXmlQuery query(QXmlQuery::XSLT20); + query.setFocus(QUrl("myInput.xml")); + query.setQuery(QUrl("myStylesheet.xsl")); + query.evaluateTo(out); +//! [7] +} diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qxmlresultitems.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qxmlresultitems.cpp new file mode 100644 index 0000000..190d610 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qxmlresultitems.cpp @@ -0,0 +1,16 @@ +//! [0] +QXmlQuery query; +query.setQuery("<e/>, 1, 'two'"); +QXmlResultItems result; + +if (query.isValid()) { + query.evaluateTo(&result); + QXmlItem item(result.next()); + while (!item.isNull()) { + // use item + item = result.next(); + } + if (result.hasError()) + /* Runtime error! */; +} +//! [0] diff --git a/doc/src/snippets/code/src_xmlpatterns_api_qxmlserializer.cpp b/doc/src/snippets/code/src_xmlpatterns_api_qxmlserializer.cpp new file mode 100644 index 0000000..e286fa9 --- /dev/null +++ b/doc/src/snippets/code/src_xmlpatterns_api_qxmlserializer.cpp @@ -0,0 +1,7 @@ +//! [0] +QXmlQuery query; +query.setQuery("doc('index.html')/html/body/p[1]"); + +QXmlSerializer serializer(query, myOutputDevice); +query.evaluateTo(&serializer); +//! [0] diff --git a/doc/src/snippets/code/tools_assistant_compat_lib_qassistantclient.cpp b/doc/src/snippets/code/tools_assistant_compat_lib_qassistantclient.cpp new file mode 100644 index 0000000..f5097a9 --- /dev/null +++ b/doc/src/snippets/code/tools_assistant_compat_lib_qassistantclient.cpp @@ -0,0 +1,25 @@ +//! [0] + QProcess *process = new QProcess(this); + QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + + QLatin1String("/assistant"); + + process->start(app, QStringList() << QLatin1String("-enableRemoteControl")); + if (!process->waitForStarted()) { + QMessageBox::critical(this, tr("Remote Control"), + tr("Could not start Qt Assistant from %1.").arg(app)); + return; + } + + // show index page + QTextStream str(process); + str << QLatin1String("SetSource qthelp://mycompany.com/doc/index.html") + << QLatin1Char('\0') << endl; + } +//! [0] + + +//! [1] + CONFIG += assistant +//! [1] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_extension_default_extensionfactory.cpp b/doc/src/snippets/code/tools_designer_src_lib_extension_default_extensionfactory.cpp new file mode 100644 index 0000000..cdfd076 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_extension_default_extensionfactory.cpp @@ -0,0 +1,35 @@ +//! [0] + QObject *ANewExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const + { + if (iid != Q_TYPEID(QDesignerContainerExtension)) + return 0; + + if (MyCustomWidget *widget = qobject_cast<MyCustomWidget*> + (object)) + return new MyContainerExtension(widget, parent); + + return 0; + } +//! [0] + + +//! [1] + QObject *AGeneralExtensionFactory::createExtension(QObject *object, + const QString &iid, QObject *parent) const + { + MyCustomWidget *widget = qobject_cast<MyCustomWidget*>(object); + + if (widget && (iid == Q_TYPEID(QDesignerTaskMenuExtension))) { + return new MyTaskMenuExtension(widget, parent); + + } else if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) { + return new MyContainerExtension(widget, parent); + + } else { + return 0; + } + } +//! [1] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_extension_extension.cpp b/doc/src/snippets/code/tools_designer_src_lib_extension_extension.cpp new file mode 100644 index 0000000..60bd0cc --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_extension_extension.cpp @@ -0,0 +1,15 @@ +//! [0] + QDesignerPropertySheetExtension *propertySheet; + QExtensionManager manager = formEditor->extensionManager(); + + propertySheet = qt_extension<QDesignerPropertySheetExtension*>(manager, widget); + + if(propertySheet) {...} +//! [0] + + +//! [1] + Q_DECLARE_EXTENSION_INTERFACE(MyExtension, "com.mycompany.myproduct.myextension") +//! [1] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_extension_qextensionmanager.cpp b/doc/src/snippets/code/tools_designer_src_lib_extension_qextensionmanager.cpp new file mode 100644 index 0000000..47cee58 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_extension_qextensionmanager.cpp @@ -0,0 +1,17 @@ +//! [0] + void MyPlugin::initialize(QDesignerFormEditorInterface *formEditor) + { + if (initialized) + return; + + QExtensionManager *manager = formEditor->extensionManager(); + Q_ASSERT(manager != 0); + + manager->registerExtensions(new MyExtensionFactory(manager), + Q_TYPEID(QDesignerTaskMenuExtension)); + + initialized = true; + } +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformeditor.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformeditor.cpp new file mode 100644 index 0000000..ef13069 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformeditor.cpp @@ -0,0 +1,11 @@ +//! [0] + QDesignerObjectInspectorInterface *objectInspector = 0; + objectInspector = formEditor->objectInspector(); + + QDesignerFormWindowManagerInterface *manager = 0; + manager = formEditor->formWindowManager(); + + objectInspector->setFormWindow(manager->formWindow(0)); +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp new file mode 100644 index 0000000..840697d --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp @@ -0,0 +1,25 @@ +//! [0] + QDesignerFormWindowInterface *formWindow; + formWindow = QDesignerFormWindowInterface::findFormWindow(myWidget); +//! [0] + + +//! [1] + QList<QDesignerFormWindowInterface *> forms; + QDesignerFormWindowInterface *formWindow; + + QDesignerFormWindowManagerInterface *manager = formEditor->formWindowManager(); + + for (int i = 0; i < manager->formWindowCount(); i++) { + formWindow = manager->formWindow(i); + forms.append(formWindow); + } +//! [1] + + +//! [2] + if (formWindow->isManaged(myWidget)) + formWindow->manageWidget(myWidget->childWidget); +//! [2] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowcursor.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowcursor.cpp new file mode 100644 index 0000000..fbe4fb8 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowcursor.cpp @@ -0,0 +1,8 @@ +//! [0] + QDesignerFormWindowInterface *formWindow = 0; + formWindow = QDesignerFormWindowInterface::findFormWindow(myWidget); + + formWindow->cursor()->setProperty(myWidget, myProperty, newValue); +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowmanager.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowmanager.cpp new file mode 100644 index 0000000..b54f0a6 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindowmanager.cpp @@ -0,0 +1,11 @@ +//! [0] + QDesignerFormWindowManagerInterface *manager = 0; + QDesignerFormWindowInterface *formWindow = 0; + + manager = formEditor->formWindowManager(); + formWindow = manager->formWindow(0); + + manager->setActiveFormWindow(formWindow); +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractobjectinspector.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractobjectinspector.cpp new file mode 100644 index 0000000..ef13069 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractobjectinspector.cpp @@ -0,0 +1,11 @@ +//! [0] + QDesignerObjectInspectorInterface *objectInspector = 0; + objectInspector = formEditor->objectInspector(); + + QDesignerFormWindowManagerInterface *manager = 0; + manager = formEditor->formWindowManager(); + + objectInspector->setFormWindow(manager->formWindow(0)); +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp new file mode 100644 index 0000000..bbc396f --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp @@ -0,0 +1,23 @@ +//! [0] + QDesignerPropertyEditorInterface *propertyEditor = 0; + propertyEditor = formEditor->propertyEditor(); + + connect(propertyEditor, SIGNAL(propertyChanged(QString, QVariant)), + this, SLOT(checkProperty(QString, QVariant))); +//! [0] + + +//! [1] + void checkProperty(QString property, QVariant value) { + QDesignerPropertyEditorInterface *propertyEditor = 0; + propertyEditor = formEditor->propertyEditor(); + + QObject *object = propertyeditor->object(); + MyCustomWidget *widget = qobject_cast<MyCustomWidget>(object); + + if (widget && property == aProperty && value != expectedValue) + {...} + } +//! [1] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractwidgetbox.cpp b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractwidgetbox.cpp new file mode 100644 index 0000000..b80c59e --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractwidgetbox.cpp @@ -0,0 +1,30 @@ +//! [0] + QDesignerWidgetBoxInterface *widgetBox = 0: + widgetBox = formEditor->widgetBox(); + + widgetBox->load(); +//! [0] + + +//! [1] + QString originalFile = widgetBox->fileName(); + + widgetBox->setFileName("myWidgetBox.xml"); + widgetBox->save(); +//! [1] + + +//! [2] + widgetBox->setFileName(originalFile); + widgetBox->load(); +//! [2] + + +//! [3] + if (widgetBox->filename() != "myWidgetBox.xml") { + widgetBox->setFileName("myWidgetBox.xml"); + widgetBox->load(); + } +//! [3] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_uilib_abstractformbuilder.cpp b/doc/src/snippets/code/tools_designer_src_lib_uilib_abstractformbuilder.cpp new file mode 100644 index 0000000..b572fba --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_uilib_abstractformbuilder.cpp @@ -0,0 +1,17 @@ +//! [0] + MyForm::MyForm(QWidget *parent) + : QWidget(parent) + { + QFormBuilder builder; + QFile file(":/forms/myWidget.ui"); + file.open(QFile::ReadOnly); + QWidget *myWidget = builder.load(&file, this); + file.close(); + + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(myWidget); + setLayout(layout); + } +//! [0] + + diff --git a/doc/src/snippets/code/tools_designer_src_lib_uilib_formbuilder.cpp b/doc/src/snippets/code/tools_designer_src_lib_uilib_formbuilder.cpp new file mode 100644 index 0000000..a88dab5 --- /dev/null +++ b/doc/src/snippets/code/tools_designer_src_lib_uilib_formbuilder.cpp @@ -0,0 +1,26 @@ +//! [0] + MyForm::MyForm(QWidget *parent) + : QWidget(parent) + { + QFormBuilder builder; + QFile file(":/forms/myWidget.ui"); + file.open(QFile::ReadOnly); + QWidget *myWidget = builder.load(&file, this); + file.close(); + + QVBoxLayout *layout = new QVBoxLayout; + layout->addWidget(myWidget); + setLayout(layout); + } +//! [0] + + +//! [1] + <!DOCTYPE RCC><RCC version="1.0"> + <qresource prefix="/forms"> + <file>mywidget.ui</file> + </qresource> + </RCC> +//! [1] + + diff --git a/doc/src/snippets/code/tools_patternist_qapplicationargumentparser.cpp b/doc/src/snippets/code/tools_patternist_qapplicationargumentparser.cpp new file mode 100644 index 0000000..da28cd5 --- /dev/null +++ b/doc/src/snippets/code/tools_patternist_qapplicationargumentparser.cpp @@ -0,0 +1,5 @@ +//! [0] + \include main.cpp +//! [0] + + diff --git a/doc/src/snippets/code/tools_shared_qtgradienteditor_qtgradientdialog.cpp b/doc/src/snippets/code/tools_shared_qtgradienteditor_qtgradientdialog.cpp new file mode 100644 index 0000000..72e86ba --- /dev/null +++ b/doc/src/snippets/code/tools_shared_qtgradienteditor_qtgradientdialog.cpp @@ -0,0 +1,44 @@ +//! [0] + bool ok; + QGradient gradient = QtGradientDialog::getGradient(&ok, QRadialGradient(), this); + if (ok) { + // the user clicked OK and gradient is set to the gradient the user selected + } else { + // the user canceled the dialog; gradient is set to the initial + // value, in this case radial gradient + } +//! [0] + + +//! [1] + bool detailsVisible; + QColor::Spec spec; + QGradient gradient; + + QtGradientDialog dlg(this); + dlg.setDetailsVisible(detailsVisible); + dlg.setSpec(spec); + dlg.setGradient(gradient); + if (dlg.exec() != QDialog::Accepted) + return; + + gradient = dlg.gradient(); + // detailsVisible and spec properties can be changed interactively by the user too, + // we store the values of these properties for the next time QtGradientDialog is executed. + detailsVisible = dlg.detailsVisible(); + spec = dlg.spec(); +//! [1] + + +//! [2] + QtGradientDialog dlg; + dlg.setBackgroundCheckered(true); +//! [2] + + +//! [3] + QtGradientDialog dlg; + dlg.setBackgroundCheckered(false); +//! [3] + + diff --git a/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtpropertybrowser.cpp b/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtpropertybrowser.cpp new file mode 100644 index 0000000..62f4319 --- /dev/null +++ b/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtpropertybrowser.cpp @@ -0,0 +1,47 @@ +//! [0] + QtSpinBoxFactory *factory; + QSet<QtIntPropertyManager *> managers = factory->propertyManagers(); +//! [0] + + +//! [1] + QtBrowserItem *item; + QList<QtBrowserItem *> childrenItems = item->children(); + + QList<QtProperty *> childrenProperties = item->property()->subProperties(); +//! [1] + + +//! [2] + QtProperty *property1, *property2, *property3; + + property2->addSubProperty(property1); + property3->addSubProperty(property2); + + QtAbstractPropertyBrowser *editor; + + editor->addProperty(property1); + editor->addProperty(property2); + editor->addProperty(property3); +//! [2] + + +//! [3] + QtIntPropertyManager *intManager; + QtDoublePropertyManager *doubleManager; + + QtProperty *myInteger = intManager->addProperty(); + QtProperty *myDouble = doubleManager->addProperty(); + + QtSpinBoxFactory *spinBoxFactory; + QtDoubleSpinBoxFactory *doubleSpinBoxFactory; + + QtAbstractPropertyBrowser *editor; + editor->setFactoryForManager(intManager, spinBoxFactory); + editor->setFactoryForManager(doubleManager, doubleSpinBoxFactory); + + editor->addProperty(myInteger); + editor->addProperty(myDouble); +//! [3] + + diff --git a/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtvariantproperty.cpp b/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtvariantproperty.cpp new file mode 100644 index 0000000..fbc9682 --- /dev/null +++ b/doc/src/snippets/code/tools_shared_qtpropertybrowser_qtvariantproperty.cpp @@ -0,0 +1,16 @@ +//! [0] + QtVariantPropertyManager *variantPropertyManager; + QtProperty *property; + + variantPropertyManager->setValue(property, 10); +//! [0] + + +//! [1] + QtVariantPropertyManager *variantPropertyManager; + QtVariantProperty *property; + + property->setValue(10); +//! [1] + + diff --git a/doc/src/snippets/code/tools_shared_qttoolbardialog_qttoolbardialog.cpp b/doc/src/snippets/code/tools_shared_qttoolbardialog_qttoolbardialog.cpp new file mode 100644 index 0000000..9162b63 --- /dev/null +++ b/doc/src/snippets/code/tools_shared_qttoolbardialog_qttoolbardialog.cpp @@ -0,0 +1,12 @@ +//! [0] + QtToolBarManager *toolBarManager; + + void MyMainWindow::customize() + { + QtToolBarDialog dialog(this); + dialog.setToolBarManager(toolBarManager); + dialog.exec(); + } +//! [0] + + |