From cde603ba2c4fe7db1711aaf033f796112a840e7d Mon Sep 17 00:00:00 2001 From: Christian Tismer Date: Mon, 4 May 2020 17:38:04 +0200 Subject: Implement __qualname__ and correct __module__ for classes PyType_FromSpec breaks the name "A.B.C.D" in module "A.B.C" and name = qualname = "D". We fix that for PySide: module = "A.B" qualname = "C.D" name = "D" and for other prefixes like Shiboken: module = "A" qualname = "B.C.D" name = "D" This had quite some impact on the signature modules. Change-Id: Ie94971ba737107b15adbfc2517e1ed32b65fda39 Fixes: PYSIDE-1286 Task-number: PYSIDE-15 Reviewed-by: Christian Tismer --- sources/pyside2/PySide2/support/deprecated.py | 2 +- sources/pyside2/PySide2/support/generate_pyi.py | 8 +------- sources/pyside2/doc/inheritance_diagram.py | 2 +- sources/pyside2/tests/QtWidgets/qwidget_test.py | 4 +++- sources/pyside2/tests/registry/existence_test.py | 16 ++++++++++++++-- 5 files changed, 20 insertions(+), 12 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/PySide2/support/deprecated.py b/sources/pyside2/PySide2/support/deprecated.py index 8538826e4..57f33d9e2 100644 --- a/sources/pyside2/PySide2/support/deprecated.py +++ b/sources/pyside2/PySide2/support/deprecated.py @@ -64,7 +64,7 @@ class PySideDeprecationWarningRemovedInQt6(Warning): def constData(self): cls = self.__class__ - name = cls.__name__ + name = cls.__qualname__ warnings.warn(dedent(""" {name}.constData is unpythonic and will be removed in Qt For Python 6.0 . Please use {name}.data instead.""" diff --git a/sources/pyside2/PySide2/support/generate_pyi.py b/sources/pyside2/PySide2/support/generate_pyi.py index f92367c82..af9f4d4f5 100644 --- a/sources/pyside2/PySide2/support/generate_pyi.py +++ b/sources/pyside2/PySide2/support/generate_pyi.py @@ -1,7 +1,7 @@ # This Python file uses the following encoding: utf-8 ############################################################################# ## -## Copyright (C) 2019 The Qt Company Ltd. +## Copyright (C) 2020 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of Qt for Python. @@ -169,12 +169,6 @@ class Formatter(Writer): else: self.print("{spaces}class {class_str}: ...".format(**locals())) yield - if "<" in class_name: - # This is happening in QtQuick for some reason: - ## class QSharedPointer: - # We simply skip over this class. - self.outfile.seek(here) - self.outfile.truncate() @contextmanager def function(self, func_name, signature, modifier=None): diff --git a/sources/pyside2/doc/inheritance_diagram.py b/sources/pyside2/doc/inheritance_diagram.py index 054cb7be9..875e17b50 100644 --- a/sources/pyside2/doc/inheritance_diagram.py +++ b/sources/pyside2/doc/inheritance_diagram.py @@ -176,7 +176,7 @@ class InheritanceGraph(object): if module == '__builtin__': fullname = cls.__name__ else: - fullname = '%s.%s' % (module, cls.__name__) + fullname = '%s.%s' % (module, cls.__qualname__) if parts == 0: return fullname name_parts = fullname.split('.') diff --git a/sources/pyside2/tests/QtWidgets/qwidget_test.py b/sources/pyside2/tests/QtWidgets/qwidget_test.py index 74e97d7be..5e94a8248 100644 --- a/sources/pyside2/tests/QtWidgets/qwidget_test.py +++ b/sources/pyside2/tests/QtWidgets/qwidget_test.py @@ -61,7 +61,9 @@ class QWidgetTest(UsesQApplication): if sys.version_info[0] < 3: def testCallType_Issue_816(self): thing = type(QWidget).__new__(type(QWidget), "", (), {}) - self.assertEqual(repr(thing), "") + # PYSIDE-1286: This works now like in Python 3 + #self.assertEqual(repr(thing), "") + self.assertEqual(repr(thing), "") class QWidgetVisible(UsesQApplication): diff --git a/sources/pyside2/tests/registry/existence_test.py b/sources/pyside2/tests/registry/existence_test.py index 4bfd63cc3..b8a42058d 100644 --- a/sources/pyside2/tests/registry/existence_test.py +++ b/sources/pyside2/tests/registry/existence_test.py @@ -1,6 +1,6 @@ ############################################################################# ## -## Copyright (C) 2019 The Qt Company Ltd. +## Copyright (C) 2020 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of Qt for Python. @@ -67,6 +67,7 @@ List entry """ import os +import re import sys from textwrap import dedent import unittest @@ -144,8 +145,19 @@ class TestSignaturesExists(unittest.TestCase): name = key.rsplit(".", 1)[-1] if name in ("next", "__next__"): # ignore problematic cases continue + if "<" in key: + # Skip over remaining crap in "<...>" + continue + if key.startswith("sample.SampleNamespace"): + # We cannot work with sample namespaces after the change to __qualname__. + continue + if (key.startswith("smart.SharedPtr") or + re.match(r"PySide2\..*?\.QSharedPointer_", key)): + # These mangled names are not supported. + # We should fix them. + continue if key not in found_sigs: - warn("missing key: '{}'".format(key), stacklevel=3) + warn("missing key: '{} value={}'".format(key, value), stacklevel=3) else: found_val = found_sigs[key] if type(value) is list and ( -- cgit v1.2.3 From ef10f62e66a3f409d0077c36f3849c87f96950d2 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Mon, 18 May 2020 11:20:33 +0200 Subject: PySide2: Fix conversion of quintptr Ensure it is 64bit for 64bit systems. Change-Id: I0b4d54f2568bd70288e184a5a2d8f31532fed157 Fixes: PYSIDE-1303 Reviewed-by: Christian Tismer --- .../pyside2/PySide2/QtCore/typesystem_core_common.xml | 4 ++-- sources/pyside2/PySide2/glue/qtcore.cpp | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/PySide2/QtCore/typesystem_core_common.xml b/sources/pyside2/PySide2/QtCore/typesystem_core_common.xml index 53ab29382..26193a0aa 100644 --- a/sources/pyside2/PySide2/QtCore/typesystem_core_common.xml +++ b/sources/pyside2/PySide2/QtCore/typesystem_core_common.xml @@ -223,9 +223,9 @@ - + - + diff --git a/sources/pyside2/PySide2/glue/qtcore.cpp b/sources/pyside2/PySide2/glue/qtcore.cpp index 834383679..111e324b9 100644 --- a/sources/pyside2/PySide2/glue/qtcore.cpp +++ b/sources/pyside2/PySide2/glue/qtcore.cpp @@ -1678,6 +1678,14 @@ Py_END_ALLOW_THREADS %out = %OUTTYPE(PyLong_AsUnsignedLong(%in)); // @snippet conversion-pylong-unsigned +// @snippet conversion-pylong-quintptr +#if defined(IS_PY3K) && QT_POINTER_SIZE == 8 +%out = %OUTTYPE(PyLong_AsUnsignedLongLong(%in)); +#else +%out = %OUTTYPE(PyLong_AsUnsignedLong(%in)); +#endif +// @snippet conversion-pylong-quintptr + // @snippet conversion-pyunicode #ifndef Py_LIMITED_API Py_UNICODE *unicode = PyUnicode_AS_UNICODE(%in); @@ -1870,6 +1878,14 @@ return PyLong_FromLong(%in); return PyLong_FromUnsignedLong(%in); // @snippet return-pylong-unsigned +// @snippet return-pylong-quintptr +#if defined(IS_PY3K) && QT_POINTER_SIZE == 8 +return PyLong_FromUnsignedLongLong(%in); +#else +return PyLong_FromUnsignedLong(%in); +#endif +// @snippet return-pylong-quintptr + // @snippet return-pyunicode QByteArray ba = %in.toUtf8(); return PyUnicode_FromStringAndSize(ba.constData(), ba.size()); -- cgit v1.2.3 From c82ec2bcbdf4db8fc83fefaec6377aaf2bb3614b Mon Sep 17 00:00:00 2001 From: Christian Tismer Date: Mon, 4 May 2020 17:38:04 +0200 Subject: Support pickling of Qt Enum objects Pickling for types exists in most cases. Pickling of Qt Enum objects works fine. Pickling of Qt Enum types is supported, but does not work because the builtin type pickling intercepts and then fails.. This problem is now solved because PySide supports now __qualname__. So pickling of nested types works now without any extra code in Python 3. Python 2 is not supported since it would require too strange patches to Python itself. Fixes: PYSIDE-15 Task-number: PYSIDE-1286 Change-Id: I346bde07a63afcf2555a3324fcca04efe25e704a Reviewed-by: Christian Tismer --- sources/pyside2/tests/QtCore/qenum_test.py | 33 +++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/tests/QtCore/qenum_test.py b/sources/pyside2/tests/QtCore/qenum_test.py index dd91d1581..ed58f4f20 100644 --- a/sources/pyside2/tests/QtCore/qenum_test.py +++ b/sources/pyside2/tests/QtCore/qenum_test.py @@ -32,13 +32,15 @@ import os import sys +import pickle import unittest sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from init_paths import init_test_paths init_test_paths(False) -from PySide2.QtCore import * +from PySide2.QtCore import Qt, QIODevice + class TestEnum(unittest.TestCase): @@ -73,6 +75,7 @@ class TestEnum(unittest.TestCase): with self.assertRaises(TypeError): a = k*2.0 + class TestQFlags(unittest.TestCase): def testToItn(self): om = QIODevice.NotOpen @@ -94,5 +97,33 @@ class TestQFlags(unittest.TestCase): except: pass + +# PYSIDE-15: Pickling of enums +class TestEnumPickling(unittest.TestCase): + def testPickleEnum(self): + + # Pickling of enums with different depth works. + ret = pickle.loads(pickle.dumps(QIODevice.Append)) + self.assertEqual(ret, QIODevice.Append) + + ret = pickle.loads(pickle.dumps(Qt.Key.Key_Asterisk)) + self.assertEqual(ret, Qt.Key.Key_Asterisk) + self.assertEqual(ret, Qt.Key(42)) + + # We can also pickle the whole enum class (built in): + ret = pickle.loads(pickle.dumps(QIODevice)) + + # This works also with nested classes for Python 3, after we + # introduced the correct __qualname__ attribute. + + # Note: For Python 2, we would need quite strange patches. + func = lambda: pickle.loads(pickle.dumps(Qt.Key)) + if sys.version_info[0] < 3: + with self.assertRaises(pickle.PicklingError): + func() + else: + func() + + if __name__ == '__main__': unittest.main() -- cgit v1.2.3 From 8e22b0d5b52f615a9b8ed4d278d103df9f2bd71c Mon Sep 17 00:00:00 2001 From: Christian Tismer Date: Sun, 17 May 2020 14:56:49 +0200 Subject: sbkenum: Fix refcounting leak sbkenum had a wrong deallocator and some other errors. Found while developing pickling on enums. At the same time, a wrong Python 3.8 condition was removed. There are currently no additional bugs in Python 2.7, 3.7 and 3.8. Change-Id: I4abccf3b84a3738bba7781ea3dfd00e98ae63ea1 Reviewed-by: Christian Tismer --- sources/pyside2/libpyside/pysideweakref.cpp | 5 ----- sources/pyside2/tests/QtCore/qenum_test.py | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/libpyside/pysideweakref.cpp b/sources/pyside2/libpyside/pysideweakref.cpp index 84b390e96..cd90634bd 100644 --- a/sources/pyside2/libpyside/pysideweakref.cpp +++ b/sources/pyside2/libpyside/pysideweakref.cpp @@ -98,11 +98,6 @@ PyObject *create(PyObject *obj, PySideWeakRefFunction func, void *userData) PySideCallableObject *callable = PyObject_New(PySideCallableObject, type); if (!callable || PyErr_Occurred()) return 0; - if (!PepRuntime_38_flag) { - // PYSIDE-939: Handling references correctly. - // Workaround for Python issue 35810; no longer necessary in Python 3.8 - Py_INCREF(type); - } PyObject *weak = PyWeakref_NewRef(obj, reinterpret_cast(callable)); if (!weak || PyErr_Occurred()) diff --git a/sources/pyside2/tests/QtCore/qenum_test.py b/sources/pyside2/tests/QtCore/qenum_test.py index ed58f4f20..1edb8981a 100644 --- a/sources/pyside2/tests/QtCore/qenum_test.py +++ b/sources/pyside2/tests/QtCore/qenum_test.py @@ -30,6 +30,7 @@ '''Test cases for QEnum and QFlags''' +import gc import os import sys import pickle @@ -75,6 +76,22 @@ class TestEnum(unittest.TestCase): with self.assertRaises(TypeError): a = k*2.0 + @unittest.skipUnless(getattr(sys, "getobjects", None), "requires debug build") + def testEnumNew_NoLeak(self): + gc.collect() + total = sys.gettotalrefcount() + for idx in range(1000): + ret = Qt.Key(42) + gc.collect() + delta = sys.gettotalrefcount() - total + print("delta total refcount =", delta) + if abs(delta) >= 10: + all = sys.getobjects(0) + all.sort(key=lambda x: sys.getrefcount(x), reverse=True) + for ob in all[:10]: + print(sys.getrefcount(ob), ob) + self.assertTrue(abs(delta) < 10) + class TestQFlags(unittest.TestCase): def testToItn(self): -- cgit v1.2.3 From 89f5b036809e8c92d1ce5845417b644064953507 Mon Sep 17 00:00:00 2001 From: Cristian Maureira-Fredes Date: Sat, 16 May 2020 02:42:41 +0200 Subject: doc: add tutorial for using qrc files We currently have only a tutorial for .ui files, and the .qrc case was missing. Task-number: PYSIDE-841 Change-Id: Ic12e8e77cb1ee042bc118fab74c97b3f6ba54ff4 Reviewed-by: Venugopal Shivashankar --- .../pyside2/doc/tutorials/basictutorial/icons.png | Bin 0 -> 3202 bytes .../doc/tutorials/basictutorial/icons/forward.png | Bin 0 -> 1113 bytes .../doc/tutorials/basictutorial/icons/pause.png | Bin 0 -> 1001 bytes .../doc/tutorials/basictutorial/icons/play.png | Bin 0 -> 970 bytes .../doc/tutorials/basictutorial/icons/previous.png | Bin 0 -> 1050 bytes .../doc/tutorials/basictutorial/icons/stop.png | Bin 0 -> 1064 bytes .../doc/tutorials/basictutorial/player-new.png | Bin 0 -> 7818 bytes .../pyside2/doc/tutorials/basictutorial/player.png | Bin 0 -> 5835 bytes .../doc/tutorials/basictutorial/qrcfiles.rst | 169 +++++++++++++++++++++ .../doc/tutorials/basictutorial/uifiles.rst | 4 +- sources/pyside2/doc/tutorials/index.rst | 1 + 11 files changed, 172 insertions(+), 2 deletions(-) create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons/forward.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons/pause.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons/play.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons/previous.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/icons/stop.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/player-new.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/player.png create mode 100644 sources/pyside2/doc/tutorials/basictutorial/qrcfiles.rst (limited to 'sources/pyside2') diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons.png b/sources/pyside2/doc/tutorials/basictutorial/icons.png new file mode 100644 index 000000000..0bcfd7d77 Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons/forward.png b/sources/pyside2/doc/tutorials/basictutorial/icons/forward.png new file mode 100644 index 000000000..c7a532dfe Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons/forward.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons/pause.png b/sources/pyside2/doc/tutorials/basictutorial/icons/pause.png new file mode 100644 index 000000000..d0beadb43 Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons/pause.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons/play.png b/sources/pyside2/doc/tutorials/basictutorial/icons/play.png new file mode 100644 index 000000000..345685337 Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons/play.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons/previous.png b/sources/pyside2/doc/tutorials/basictutorial/icons/previous.png new file mode 100644 index 000000000..979f18565 Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons/previous.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/icons/stop.png b/sources/pyside2/doc/tutorials/basictutorial/icons/stop.png new file mode 100644 index 000000000..1e88ded3a Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/icons/stop.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/player-new.png b/sources/pyside2/doc/tutorials/basictutorial/player-new.png new file mode 100644 index 000000000..e1f660e5f Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/player-new.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/player.png b/sources/pyside2/doc/tutorials/basictutorial/player.png new file mode 100644 index 000000000..3060a990d Binary files /dev/null and b/sources/pyside2/doc/tutorials/basictutorial/player.png differ diff --git a/sources/pyside2/doc/tutorials/basictutorial/qrcfiles.rst b/sources/pyside2/doc/tutorials/basictutorial/qrcfiles.rst new file mode 100644 index 000000000..2f986875c --- /dev/null +++ b/sources/pyside2/doc/tutorials/basictutorial/qrcfiles.rst @@ -0,0 +1,169 @@ +Using `.qrc` Files (`pyside2-rcc`) +********************************** + +The `Qt Resource System`_ is a mechanism for storing binary files +in an application. + +The most common uses are for custom images, icons, fonts, among others. + +In this tutorial you will learn how to load custom images as button icons. + +For inspiration, we will try to adapt the multimedia player example +from Qt. + +As you can see on the following image, the `QPushButton` that are used +for the media actions (play, pause, stop, and so on) are using the +default icons meant for such actions. + +.. image:: player.png + :alt: Multimedia Player Qt Example + +You could make the application more attractive by designing the icons, +but in case you don't want to design them, `download the following set`_ +and use them. + +.. image:: icons.png + :alt: New Multimedia icons + +You can find more information about the `rcc` command, and `.qrc` file +format, and the resource system in general in the `Qt Resource System`_ +site. + +.. _`download the following set`: icons/ + + +The `.qrc` file +================ + +Before running any command, add information about the resources to a `.qrc` +file. +In the following example, notice how the resources are listed in `icons.qrc` + +:: + + + + + icons/play.png + icons/pause.png + icons/stop.png + icons/previous.png + icons/forward.png + + + + +Generating a Python file +========================= + +Now that the `icons.qrc` file is ready, use the `pyside2-rcc` tool to generate +a Python class containing the binary information about the resources + +To do this, we need to run:: + + pyside2-rcc icons.rc -o rc_icons.py + +The `-o` option lets you specify the output filename, +which is `rc_icons.py` in this case. + +To use the generated file, add the following import at the top of your main Python file:: + + import rc_icons + + +Changes in the code +=================== + +As you are modifying an existing example, you need to modify the following +lines: + +.. code-block:: python + + from PySide2.QtGui import QIcon, QKeySequence + playIcon = self.style().standardIcon(QStyle.SP_MediaPlay) + previousIcon = self.style().standardIcon(QStyle.SP_MediaSkipBackward) + pauseIcon = self.style().standardIcon(QStyle.SP_MediaPause) + nextIcon = self.style().standardIcon(QStyle.SP_MediaSkipForward) + stopIcon = self.style().standardIcon(QStyle.SP_MediaStop) + +and replace them with the following: + +.. code-block:: python + + from PySide2.QtGui import QIcon, QKeySequence, QPixmap + playIcon = QIcon(QPixmap(":/icons/play.png")) + previousIcon = QIcon(QPixmap(":/icons/previous.png")) + pauseIcon = QIcon(QPixmap(":/icons/pause.png")) + nextIcon = QIcon(QPixmap(":/icons/forward.png")) + stopIcon = QIcon(QPixmap(":/icons/stop.png")) + +This ensures that the new icons are used instead of the default ones provided +by the application theme. +Notice that the lines are not consecutive, but are in different parts +of the file. + +After all your imports, add the following + +.. code-block:: python + + import rc_icons + +Now, the constructor of your class should look like this: + +.. code-block:: python + + def __init__(self): + super(MainWindow, self).__init__() + + self.playlist = QMediaPlaylist() + self.player = QMediaPlayer() + + toolBar = QToolBar() + self.addToolBar(toolBar) + + fileMenu = self.menuBar().addMenu("&File") + openAction = QAction(QIcon.fromTheme("document-open"), + "&Open...", self, shortcut=QKeySequence.Open, + triggered=self.open) + fileMenu.addAction(openAction) + exitAction = QAction(QIcon.fromTheme("application-exit"), "E&xit", + self, shortcut="Ctrl+Q", triggered=self.close) + fileMenu.addAction(exitAction) + + playMenu = self.menuBar().addMenu("&Play") + playIcon = QIcon(QPixmap(":/icons/play.png")) + self.playAction = toolBar.addAction(playIcon, "Play") + self.playAction.triggered.connect(self.player.play) + playMenu.addAction(self.playAction) + + previousIcon = QIcon(QPixmap(":/icons/previous.png")) + self.previousAction = toolBar.addAction(previousIcon, "Previous") + self.previousAction.triggered.connect(self.previousClicked) + playMenu.addAction(self.previousAction) + + pauseIcon = QIcon(QPixmap(":/icons/pause.png")) + self.pauseAction = toolBar.addAction(pauseIcon, "Pause") + self.pauseAction.triggered.connect(self.player.pause) + playMenu.addAction(self.pauseAction) + + nextIcon = QIcon(QPixmap(":/icons/forward.png")) + self.nextAction = toolBar.addAction(nextIcon, "Next") + self.nextAction.triggered.connect(self.playlist.next) + playMenu.addAction(self.nextAction) + + stopIcon = QIcon(QPixmap(":/icons/stop.png")) + self.stopAction = toolBar.addAction(stopIcon, "Stop") + self.stopAction.triggered.connect(self.player.stop) + playMenu.addAction(self.stopAction) + + # many lines were omitted + +Executing the example +===================== + +Run the application by calling `python main.py` to checkout the new icon-set: + +.. image:: player-new.png + :alt: New Multimedia Player Qt Example + +.. _`Qt Resource System`: https://doc.qt.io/qt-5/resources.html diff --git a/sources/pyside2/doc/tutorials/basictutorial/uifiles.rst b/sources/pyside2/doc/tutorials/basictutorial/uifiles.rst index 2c0178e2e..2a0d65e46 100644 --- a/sources/pyside2/doc/tutorials/basictutorial/uifiles.rst +++ b/sources/pyside2/doc/tutorials/basictutorial/uifiles.rst @@ -1,5 +1,5 @@ -Using UI Files -*************** +Using `.ui` Files (`QUiLoader` and `pyside2-uic`) +************************************************* This page describes the use of Qt Creator to create graphical interfaces for your Qt for Python project. diff --git a/sources/pyside2/doc/tutorials/index.rst b/sources/pyside2/doc/tutorials/index.rst index 73e6b6b26..598b42ca1 100644 --- a/sources/pyside2/doc/tutorials/index.rst +++ b/sources/pyside2/doc/tutorials/index.rst @@ -18,6 +18,7 @@ Basic tutorials basictutorial/clickablebutton.rst basictutorial/dialog.rst basictutorial/uifiles.rst + basictutorial/qrcfiles.rst Real use-cases applications --------------------------- -- cgit v1.2.3 From 6717d3540fac74c91d9381958a08e60f6532d402 Mon Sep 17 00:00:00 2001 From: Cristian Maureira-Fredes Date: Thu, 26 Mar 2020 18:34:38 +0100 Subject: Add QtUiTools.loadUiType This function will allow users to convert and load .ui files at runtime. A test case was added. Change-Id: I64a220a07955e560f61f823d0ee2c3c9ff2209c1 Fixes: PYSIDE-1223 Reviewed-by: Cristian Maureira-Fredes Reviewed-by: Christian Tismer --- .../PySide2/QtUiTools/typesystem_uitools.xml | 36 ++++++ sources/pyside2/PySide2/glue/qtuitools.cpp | 138 +++++++++++++++++++++ sources/pyside2/tests/QtUiTools/loadUiType_test.py | 75 +++++++++++ 3 files changed, 249 insertions(+) create mode 100644 sources/pyside2/tests/QtUiTools/loadUiType_test.py (limited to 'sources/pyside2') diff --git a/sources/pyside2/PySide2/QtUiTools/typesystem_uitools.xml b/sources/pyside2/PySide2/QtUiTools/typesystem_uitools.xml index 7b27e8783..2ca12e788 100644 --- a/sources/pyside2/PySide2/QtUiTools/typesystem_uitools.xml +++ b/sources/pyside2/PySide2/QtUiTools/typesystem_uitools.xml @@ -139,4 +139,40 @@ + + + + This function will allow users to generate and load a `.ui` file at runtime, and it returns + a `tuple` containing the reference to the Python class, and the base class. + + We don't recommend this approach since the workflow should be to generate a Python file + from the `.ui` file, and then import and load it to use it, but we do understand that + there are some corner cases when such functionality is required. + + The internal process relies on `uic` being in the PATH, which is the same requirement for + the new `pyside2-uic` to work (which is just a wrapper around `uic -g python`) + + A Simple use can be: + + .. code-block:: python + + from PySide2.QtUiTools import loadUiType + + generated_class, base_class = loadUiType("themewidget.ui") + # the values will be: + # (<class '__main__.Ui_ThemeWidgetForm'>, <class 'PySide2.QtWidgets.QWidget'>) + + + In that case, `generated_class` will be a reference to the Python class, + and `base_class` will be a reference to the base class. + + + + + diff --git a/sources/pyside2/PySide2/glue/qtuitools.cpp b/sources/pyside2/PySide2/glue/qtuitools.cpp index 00fc8e44a..668b512e4 100644 --- a/sources/pyside2/PySide2/glue/qtuitools.cpp +++ b/sources/pyside2/PySide2/glue/qtuitools.cpp @@ -109,3 +109,141 @@ registerCustomWidget(%PYARG_1); // Avoid calling the original function: %CPPSELF.%FUNCTION_NAME() %PYARG_0 = QUiLoaderLoadUiFromFileName(%CPPSELF, %1, %2); // @snippet quiloader-load-2 + +// @snippet loaduitype +/* +Arguments: + %PYARG_1 (uifile) +*/ +// 1. Generate the Python code from the UI file +#ifdef IS_PY3K +PyObject *strObj = PyUnicode_AsUTF8String(%PYARG_1); +char *arg1 = PyBytes_AsString(strObj); +QByteArray uiFileName(arg1); +Py_DECREF(strObj); +#else +QByteArray uiFileName(PyBytes_AsString(%PYARG_1)); +#endif + +QFile uiFile(uiFileName); + +if (!uiFile.exists()) { + qCritical().noquote() << "File" << uiFileName << "does not exists"; + Py_RETURN_NONE; +} + +if (uiFileName.isEmpty()) { + qCritical() << "Error converting the UI filename to QByteArray"; + Py_RETURN_NONE; +} + +QString uicBin("uic"); +QStringList uicArgs = {"-g", "python", QString::fromUtf8(uiFileName)}; + +QProcess uicProcess; +uicProcess.start(uicBin, uicArgs); +if (!uicProcess.waitForFinished()) { + qCritical() << "Cannot run 'uic': " << uicProcess.errorString() << " - " + << "Exit status " << uicProcess.exitStatus() + << " (" << uicProcess.exitCode() << ")\n" + << "Check if 'uic' is in PATH"; + Py_RETURN_NONE; +} +QByteArray uiFileContent = uicProcess.readAllStandardOutput(); +QByteArray errorOutput = uicProcess.readAllStandardError(); + +if (!errorOutput.isEmpty()) { + qCritical().noquote() << errorOutput; + Py_RETURN_NONE; +} + +// 2. Obtain the 'classname' and the Qt base class. +QByteArray className; +QByteArray baseClassName; + +// Problem +// The generated Python file doesn't have the Qt Base class information. + +// Solution +// Use the XML file +if (!uiFile.open(QIODevice::ReadOnly)) + Py_RETURN_NONE; + +// This will look for the first tag, e.g.: +// +// and then extract the information from "class", and "name", +// to get the baseClassName and className respectively +QXmlStreamReader reader(&uiFile); +while (!reader.atEnd() && baseClassName.isEmpty() && className.isEmpty()) { + auto token = reader.readNext(); + if (token == QXmlStreamReader::StartElement && reader.name() == "widget") { + baseClassName = reader.attributes().value(QLatin1String("class")).toUtf8(); + className = reader.attributes().value(QLatin1String("name")).toUtf8(); + } +} + +uiFile.close(); + +if (className.isEmpty() || baseClassName.isEmpty() || reader.hasError()) { + qCritical() << "An error occurred when parsing the UI file while looking for the class info " + << reader.errorString(); + Py_RETURN_NONE; +} + +QByteArray pyClassName("Ui_"+className); + +PyObject *module = PyImport_ImportModule("__main__"); +PyObject *loc = PyModule_GetDict(module); + +// 3. exec() the code so the class exists in the context: exec(uiFileContent) +// The context of PyRun_SimpleString is __main__. +// 'Py_file_input' is the equivalent to using exec(), since it will execute +// the code, without returning anything. +Shiboken::AutoDecRef codeUi(Py_CompileString(uiFileContent.constData(), "", Py_file_input)); +if (codeUi.isNull()) { + qCritical() << "Error while compiling the generated Python file"; + Py_RETURN_NONE; +} +PyObject *uiObj = nullptr; +#ifdef IS_PY3K +uiObj = PyEval_EvalCode(codeUi, loc, loc); +#else +uiObj = PyEval_EvalCode(reinterpret_cast(codeUi.object()), loc, loc); +#endif + +if (uiObj == nullptr) { + qCritical() << "Error while running exec() on the generated code"; + Py_RETURN_NONE; +} + +// 4. eval() the name of the class on a variable to return +// 'Py_eval_input' is the equivalent to using eval(), since it will just +// evaluate an expression. +Shiboken::AutoDecRef codeClass(Py_CompileString(pyClassName.constData(),"", Py_eval_input)); +if (codeClass.isNull()) { + qCritical() << "Error while compiling the Python class"; + Py_RETURN_NONE; +} + +Shiboken::AutoDecRef codeBaseClass(Py_CompileString(baseClassName.constData(), "", Py_eval_input)); +if (codeBaseClass.isNull()) { + qCritical() << "Error while compiling the base class"; + Py_RETURN_NONE; +} + +#ifdef IS_PY3K +PyObject *classObj = PyEval_EvalCode(codeClass, loc, loc); +PyObject *baseClassObj = PyEval_EvalCode(codeBaseClass, loc, loc); +#else +PyObject *classObj = PyEval_EvalCode(reinterpret_cast(codeClass.object()), loc, loc); +PyObject *baseClassObj = PyEval_EvalCode(reinterpret_cast(codeBaseClass.object()), loc, loc); +#endif + +%PYARG_0 = PyTuple_New(2); +if (%PYARG_0 == nullptr) { + qCritical() << "Error while creating the return Tuple"; + Py_RETURN_NONE; +} +PyTuple_SET_ITEM(%PYARG_0, 0, classObj); +PyTuple_SET_ITEM(%PYARG_0, 1, baseClassObj); +// @snippet loaduitype diff --git a/sources/pyside2/tests/QtUiTools/loadUiType_test.py b/sources/pyside2/tests/QtUiTools/loadUiType_test.py new file mode 100644 index 000000000..9a3756376 --- /dev/null +++ b/sources/pyside2/tests/QtUiTools/loadUiType_test.py @@ -0,0 +1,75 @@ +############################################################################# +## +## Copyright (C) 2020 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the test suite of Qt for Python. +## +## $QT_BEGIN_LICENSE:GPL-EXCEPT$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## GNU General Public License Usage +## Alternatively, this file may be used under the terms of the GNU +## General Public License version 3 as published by the Free Software +## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +## included in the packaging of this file. Please review the following +## information to ensure the GNU General Public License requirements will +## be met: https://www.gnu.org/licenses/gpl-3.0.html. +## +## $QT_END_LICENSE$ +## +############################################################################# + +import os +import sys +import unittest + +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from init_paths import init_test_paths +init_test_paths(False) + +from helper.usesqapplication import UsesQApplication + +from PySide2.QtWidgets import QWidget, QFrame, QPushButton +from PySide2.QtUiTools import loadUiType + +class loadUiTypeTester(UsesQApplication): + def testFunction(self): + filePath = os.path.join(os.path.dirname(__file__), "minimal.ui") + loaded = loadUiType(filePath) + self.assertNotEqual(loaded, None) + + # (, ) + generated, base = loaded + + # Generated class contains retranslateUi method + self.assertTrue("retranslateUi" in dir(generated)) + + # Base class instance will be QFrame for this example + self.assertTrue(isinstance(base(), QFrame)) + + anotherFileName = os.path.join(os.path.dirname(__file__), "test.ui") + another = loadUiType(anotherFileName) + self.assertNotEqual(another, None) + + generated, base = another + # Base class instance will be QWidget for this example + self.assertTrue(isinstance(base(), QWidget)) + + w = base() + ui = generated() + ui.setupUi(w) + + self.assertTrue(isinstance(ui.child_object, QFrame)) + self.assertTrue(isinstance(ui.grandson_object, QPushButton)) + + +if __name__ == '__main__': + unittest.main() + -- cgit v1.2.3 From b8427aa18824e89a3b28b6b821da4efe0827951b Mon Sep 17 00:00:00 2001 From: Cristian Maureira-Fredes Date: Sat, 23 May 2020 14:10:31 +0200 Subject: Rename and update some snippets * Renaming a few .cpp files into .py * Replacing the use of SIGNAL() and SLOT() * Fixing Python syntax * Removing C++-isms from translated Python code * Including the snippets from QStackedLayout Task-number: PYSIDE-691 Fixes: PYSIDE-1309 Change-Id: I431be3d930b2adc36a22118901baa6799581adb2 Reviewed-by: Friedemann Kleint --- .../doc/src/snippets/clipboard/clipwindow.cpp | 106 ----- .../doc/src/snippets/clipboard/clipwindow.py | 105 +++++ .../snippets/code/src_corelib_kernel_qobject.cpp | 369 ---------------- .../snippets/code/src_corelib_kernel_qobject.py | 375 ++++++++++++++++ ...ols_designer_src_lib_sdk_abstractformwindow.cpp | 75 ---- ...ools_designer_src_lib_sdk_abstractformwindow.py | 74 ++++ ...designer_src_lib_sdk_abstractpropertyeditor.cpp | 73 --- ..._designer_src_lib_sdk_abstractpropertyeditor.py | 71 +++ .../doc/src/snippets/dialogs/dialogs.cpp | 129 ------ .../doc/src/snippets/dialogs/dialogs.py | 123 ++++++ .../doc/src/snippets/dropevents/window.h | 81 ---- .../doc/src/snippets/dropevents/window.py | 65 +++ .../doc/src/snippets/qstackedlayout/main.py | 87 ++++ .../doc/src/snippets/qstackedwidget/main.cpp | 78 ---- .../doc/src/snippets/qstackedwidget/main.py | 77 ++++ .../doc/src/snippets/qxmlquery/bindingExample.cpp | 59 --- .../doc/src/snippets/qxmlquery/bindingExample.py | 59 +++ .../doc/src/snippets/sqldatabase/sqldatabase.cpp | 489 --------------------- .../doc/src/snippets/sqldatabase/sqldatabase.py | 489 +++++++++++++++++++++ .../doc/src/snippets/widgets-tutorial/template.py | 66 +++ .../examples/dialogs/classwizard/classwizard.cpp | 259 ----------- .../examples/dialogs/classwizard/classwizard.py | 254 +++++++++++ .../examples/dialogs/extension/finddialog.cpp | 119 ----- .../examples/dialogs/extension/finddialog.py | 119 +++++ .../mainwindows/application/mainwindow.cpp | 359 --------------- .../examples/mainwindows/application/mainwindow.h | 112 +++++ .../examples/mainwindows/application/mainwindow.py | 357 +++++++++++++++ .../mainwindows/dockwidgets/mainwindow.cpp | 255 ----------- .../examples/mainwindows/dockwidgets/mainwindow.py | 253 +++++++++++ .../examples/mainwindows/mainwindow.cpp | 367 ---------------- .../examples/mainwindows/mainwindow.py | 366 +++++++++++++++ .../examples/mainwindows/mdi/mainwindow.cpp | 381 ---------------- .../examples/mainwindows/mdi/mainwindow.py | 360 +++++++++++++++ .../examples/mainwindows/menus/mainwindow.cpp | 367 ---------------- .../examples/mainwindows/menus/mainwindow.py | 366 +++++++++++++++ .../examples/widgets/spinboxes/window.cpp | 249 ----------- .../examples/widgets/spinboxes/window.py | 247 +++++++++++ 37 files changed, 4025 insertions(+), 3815 deletions(-) delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.h create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.py create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedlayout/main.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.py delete mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.cpp create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py create mode 100644 sources/pyside2/doc/codesnippets/doc/src/snippets/widgets-tutorial/template.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.h create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.py delete mode 100644 sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.cpp create mode 100644 sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.py (limited to 'sources/pyside2') diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.cpp deleted file mode 100644 index 726ceb818..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.cpp +++ /dev/null @@ -1,106 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -form PySide2.QtGui import * - - -def __init__(self, parent): - QMainWindow.__init__(self, parent) - clipboard = QApplication.clipboard() - - centralWidget = QWidget(self) - currentItem = QWidget(centralWidget) - mimeTypeLabel = QLabel(tr("MIME types:"), currentItem) - mimeTypeCombo = QComboBox(currentItem) - dataLabel = QLabel(tr("Data:"), currentItem) - dataInfoLabel = QLabel("", currentItem) - - previousItems = QListWidget(centralWidget) - -//! [0] - connect(clipboard, SIGNAL("dataChanged()"), self, SLOT("updateClipboard()")) -//! [0] - connect(mimeTypeCombo, SIGNAL("activated(const QString &)"), - self, SLOT("updateData(const QString &))") - - currentLayout = QVBoxLayout(currentItem) - currentLayout.addWidget(mimeTypeLabel) - currentLayout.addWidget(mimeTypeCombo) - currentLayout.addWidget(dataLabel) - currentLayout.addWidget(dataInfoLabel) - currentLayout.addStretch(1) - - mainLayout = QHBoxLayout(centralWidget) - mainLayout.addWidget(currentItem, 1) - mainLayout.addWidget(previousItems) - - setCentralWidget(centralWidget) - setWindowTitle(tr("Clipboard")) - -//! [1] -def updateClipboard(self): - formats = clipboard.mimeData().formats() - data = clipboard.mimeData().data(format) -//! [1] - - mimeTypeCombo.clear() - mimeTypeCombo.insertStringList(formats) - - size = clipboard.mimeData().data(formats[0]).size() - Item = QListWidgetItem(previousItems) - Item.setText(tr("%1 (%2 bytes)").arg(formats[0]).arg(size)) - - updateData(formats[0]) -//! [2] -//! [2] - -def updateData(self, format) - data = clipboard.mimeData().data(format) - dataInfoLabel.setText(tr("%1 bytes").arg(data.size())) diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.py new file mode 100644 index 000000000..1cbd56241 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/clipboard/clipwindow.py @@ -0,0 +1,105 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +form PySide2.QtGui import * + + +def __init__(self, parent): + QMainWindow.__init__(self, parent) + clipboard = QApplication.clipboard() + + centralWidget = QWidget(self) + currentItem = QWidget(centralWidget) + mimeTypeLabel = QLabel(tr("MIME types:"), currentItem) + mimeTypeCombo = QComboBox(currentItem) + dataLabel = QLabel(tr("Data:"), currentItem) + dataInfoLabel = QLabel("", currentItem) + + previousItems = QListWidget(centralWidget) + +//! [0] + clipboard.dataChanged.connect(self.updateClipboard) +//! [0] + mimeTypeCombo.activated[str].connect(self.updateData) + + currentLayout = QVBoxLayout(currentItem) + currentLayout.addWidget(mimeTypeLabel) + currentLayout.addWidget(mimeTypeCombo) + currentLayout.addWidget(dataLabel) + currentLayout.addWidget(dataInfoLabel) + currentLayout.addStretch(1) + + mainLayout = QHBoxLayout(centralWidget) + mainLayout.addWidget(currentItem, 1) + mainLayout.addWidget(previousItems) + + setCentralWidget(centralWidget) + setWindowTitle(tr("Clipboard")) + +//! [1] +def updateClipboard(self): + formats = clipboard.mimeData().formats() + data = clipboard.mimeData().data(format) +//! [1] + + mimeTypeCombo.clear() + mimeTypeCombo.insertStringList(formats) + + size = clipboard.mimeData().data(formats[0]).size() + Item = QListWidgetItem(previousItems) + Item.setText(tr("%1 (%2 bytes)").arg(formats[0]).arg(size)) + + updateData(formats[0]) +//! [2] +//! [2] + +def updateData(self, format) + data = clipboard.mimeData().data(format) + dataInfoLabel.setText(tr("%1 bytes").arg(data.size())) diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.cpp deleted file mode 100644 index 1de4dbbe8..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of Qt for Python. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [0] -lineEdit = qt_find_obj_child(myWidget, "QLineEdit", "my line edit") -if lineEdit: - lineEdit.setText("Default") -//! [0] - - -//! [1] -obj = QPushButton() -obj.metaObject().className() # returns "QPushButton" - -QPushButton.staticMetaObject.className() # returns "QPushButton" -//! [1] - - -//! [2] -QPushButton.staticMetaObject.className() # returns "QPushButton" - -obj = QPushButton() -obj.metaObject().className() # returns "QPushButton" -//! [2] - - -//! [3] -obj = QTimer() # QTimer inherits QObject - -timer = obj -# timer == (QObject *)obj - -button = obj -# button == 0 -//! [3] - - -//! [4] -timer = QTimer() # QTimer inherits QObject -timer.inherits("QTimer") # returns true -timer.inherits("QObject") # returns true -timer.inherits("QAbstractButton") # returns false - -# QLayout inherits QObject and QLayoutItem -layout = QLayout() -layout.inherits("QObject") # returns true -layout.inherits("QLayoutItem") # returns false -//! [4] - - -//! [5] -print "MyClass::setPrecision(): (%s) invalid precision %f" % \ - (qPrintable(objectName()), newPrecision) -//! [5] - - -//! [6] -class MainWindow(QMainWindow): - def __init__(self): - self.textEdit = QTextEdit() - setCentralWidget(self.textEdit) - textEdit.installEventFilter(self) - - def eventFilter(self, obj, event): - if obj == textEdit: - if event.type() == QEvent.KeyPress: - keyEvent = event - print "Ate key press", keyEvent.key() - return true - else: - return false - else: - # pass the event on to the parent class - return QMainWindow.eventFilter(self, obj, event) -//! [6] - - -//! [7] -myObject.moveToThread(QApplication.instance().thread()) -//! [7] - - -//! [8] -class MyObject(QObject): - def __init__(self, parent): - QObject.__init__(self, parent) - - self.startTimer(50) # 50-millisecond timer - self.startTimer(1000) # 1-second timer - self.startTimer(60000) # 1-minute timer - - - def timerEvent(self, event): - print "Timer ID:", event.timerId() - -//! [8] - - -//! [9] -list = window().queryList("QAbstractButton") -for obj in list: - obj.setEnabled(false) -//! [9] - - -//! [10] -button = parentWidget.findChild(QPushButton, "button1") -//! [10] - - -//! [11] -list = parentWidget.findChild(QListWidget) -//! [11] - - -//! [12] -widgets = parentWidget.findChildren(QWidget, "widgetname") -//! [12] - - -//! [13] -allPButtons = parentWidget.findChildren(QPushButton) -//! [13] - - -//! [14] -monitoredObj.installEventFilter(filterObj) -//! [14] - - -//! [15] -class KeyPressEater(QObject): - def eventFilter(self, obj, event): - if event.type() == QEvent.KeyPress: - print "Ate key press", event.key() - return True - else: - # standard event processing - return QObject.eventFilter(self, obj, event) -//! [15] - - -//! [16] -keyPressEater = KeyPressEater(self) -pushButton = QPushButton(self) -listView = QListView(self) - -pushButton.installEventFilter(keyPressEater) -listView.installEventFilter(keyPressEater) -//! [16] - - -//! [17] -def __init__(self): - senderLabel = QLabel(self.tr("Name:")) - recipientLabel = QLabel(self.tr("Name:", "recipient")) - # ... -//! [17] - - -//! [18] -n = messages.count(); -showMessage(self.tr("%n message(s) saved", "", n)); -//! [18] - - -//! [19] -if n == 1: - self.tr("%n message saved") -else: - self.tr("%n messages saved") -//! [19] - - -//! [20] -label.setText(self.tr("F\374r \310lise")) -//! [20] - - -//! [21] -if receivers(SIGNAL('valueChanged()')) > 0: - data = get_the_value() # expensive operation - self.valueChanged(data) -//! [21] - - -//! [22] -label = QLabel() -scrollBar = QScrollBar() -QObject.connect(scrollBar, SIGNAL('valueChanged()'), - label, SLOT('setNum()')) -//! [22] - - -//! [23] -// WRONG -QObject.connect(scrollBar, SIGNAL('valueChanged()'), - label, SLOT('setNum()')); -//! [23] - - -//! [24] -class MyWidget(QWidget): - def __init__(self): - myButton = QPushButton(self) - connect(myButton, SIGNAL('clicked()'), - self, 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()'): - # signal is valueChanged() -//! [32] - - -//! [33] -def on__() -//! [33] - - -//! [34] -def on_button1_clicked() -//! [34] - - -//! [35] -class MyClass(QObject): - Q_CLASSINFO("Author", "Pierre Gendron") - Q_CLASSINFO("URL", "http://www.my-organization.qc.ca") - -//! [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] -#this not apply for Python -class MyClass(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] -#this not apply for Python -Q_FLAGS(Options Alignment) -//! [39] - - -//! [40] -//: This name refers to a host name. -hostNameLabel.setText(self.tr("Name:")) - -#: This text refers to a C++ code example. -example = self.tr("Example") -//! [40] - -//! [explicit tr context] -text = QScrollBar.tr("Page up") -//! [explicit tr context] diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py new file mode 100644 index 000000000..7e50f6701 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/src_corelib_kernel_qobject.py @@ -0,0 +1,375 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the documentation of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [0] +lineEdit = qt_find_obj_child(myWidget, "QLineEdit", "my line edit") +if lineEdit: + lineEdit.setText("Default") +//! [0] + + +//! [1] +obj = QPushButton() +obj.metaObject().className() # returns "QPushButton" + +QPushButton.staticMetaObject.className() # returns "QPushButton" +//! [1] + + +//! [2] +QPushButton.staticMetaObject.className() # returns "QPushButton" + +obj = QPushButton() +obj.metaObject().className() # returns "QPushButton" +//! [2] + + +//! [3] +obj = QTimer() # QTimer inherits QObject + +timer = obj +# timer == (QObject *)obj + +button = obj +# button == 0 +//! [3] + + +//! [4] +timer = QTimer() # QTimer inherits QObject +timer.inherits("QTimer") # returns true +timer.inherits("QObject") # returns true +timer.inherits("QAbstractButton") # returns false + +# QLayout inherits QObject and QLayoutItem +layout = QLayout() +layout.inherits("QObject") # returns true +layout.inherits("QLayoutItem") # returns false +//! [4] + + +//! [5] +print("MyClass.setPrecision(): ({}) invalid precision {}".format(qPrintable(objectName()), + newPrecision)) +//! [5] + + +//! [6] +class MainWindow(QMainWindow): + def __init__(self): + self.textEdit = QTextEdit() + setCentralWidget(self.textEdit) + textEdit.installEventFilter(self) + + def eventFilter(self, obj, event): + if obj == textEdit: + if event.type() == QEvent.KeyPress: + keyEvent = event + print("Ate key press", keyEvent.key()) + return true + else: + return false + else: + # pass the event on to the parent class + return QMainWindow.eventFilter(self, obj, event) +//! [6] + + +//! [7] +myObject.moveToThread(QApplication.instance().thread()) +//! [7] + + +//! [8] +class MyObject(QObject): + def __init__(self, parent): + QObject.__init__(self, parent) + + self.startTimer(50) # 50-millisecond timer + self.startTimer(1000) # 1-second timer + self.startTimer(60000) # 1-minute timer + + + def timerEvent(self, event): + print("Timer ID:", event.timerId()) + +//! [8] + + +//! [9] +a_list = window().queryList("QAbstractButton") +for obj in a_list: + obj.setEnabled(false) +//! [9] + + +//! [10] +button = parentWidget.findChild(QPushButton, "button1") +//! [10] + + +//! [11] +a_list = parentWidget.findChild(QListWidget) +//! [11] + + +//! [12] +widgets = parentWidget.findChildren(QWidget, "widgetname") +//! [12] + + +//! [13] +allPButtons = parentWidget.findChildren(QPushButton) +//! [13] + + +//! [14] +monitoredObj.installEventFilter(filterObj) +//! [14] + + +//! [15] +class KeyPressEater(QObject): + def eventFilter(self, obj, event): + if event.type() == QEvent.KeyPress: + print("Ate key press", event.key()) + return True + else: + # standard event processing + return QObject.eventFilter(self, obj, event) +//! [15] + + +//! [16] +keyPressEater = KeyPressEater(self) +pushButton = QPushButton(self) +listView = QListView(self) + +pushButton.installEventFilter(keyPressEater) +listView.installEventFilter(keyPressEater) +//! [16] + + +//! [17] +def __init__(self): + senderLabel = QLabel(self.tr("Name:")) + recipientLabel = QLabel(self.tr("Name:", "recipient")) + # ... +//! [17] + + +//! [18] +n = messages.count(); +showMessage(self.tr("%n message(s) saved", "", n)); +//! [18] + + +//! [19] +if n == 1: + self.tr("%n message saved") +else: + self.tr("%n messages saved") +//! [19] + + +//! [20] +label.setText(self.tr("F\374r \310lise")) +//! [20] + + +//! [21] +if receivers(SIGNAL('valueChanged()')) > 0: + data = get_the_value() # expensive operation + self.valueChanged(data) +//! [21] + + +//! [22] +label = QLabel() +scrollBar = QScrollBar() +QObject.connect(scrollBar, SIGNAL('valueChanged(int)'), + label, SLOT('setNum(int)')); +# or scrollBar.valueChanged.connect(label.setNum) +//! [22] + + +//! [23] +// WRONG +QObject.connect(scrollBar, SIGNAL('valueChanged(int value)'), + label, SLOT('setNum(int value)')); +//! [23] + + +//! [24] +class MyWidget(QWidget): + def __init__(self): + myButton = QPushButton(self) + myButton.clicked.connect(self.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()'): + # signal is valueChanged() +//! [32] + + +//! [33] +def on__() +//! [33] + + +//! [34] +def on_button1_clicked() +//! [34] + + +//! [35] +class MyClass(QObject): + Q_CLASSINFO("Author", "Pierre Gendron") + Q_CLASSINFO("URL", "http://www.my-organization.qc.ca") + +//! [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] +#this does not apply to Python +class MyClass(QObject): + + #Q_OBJECT, not needed + #Q_ENUMS(Priority), not supported + + def __init__(self, parent=None): + pass + + class Priority(Enum): + High = 1 + Low = 2 + VeryHigh = 3 + VeryLow 4 + + def setPriority(self, priority): + pass + + priority = Property(...) +}; +//! [38] + + +//! [39] +#this does not apply to Python +Q_FLAGS(Options Alignment) +//! [39] + + +//! [40] +# This name refers to a host name. +hostNameLabel.setText(self.tr("Name:")) + +# This text refers to a C++ code example. +example = self.tr("Example") +//! [40] + +//! [explicit tr context] +text = QScrollBar.tr("Page up") +//! [explicit tr context] diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp deleted file mode 100644 index f9d97e6ce..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of Qt for Python. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [0] - QDesignerFormWindowInterface *formWindow; - formWindow = QDesignerFormWindowInterface::findFormWindow(myWidget); -//! [0] - - -//! [1] - QList 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/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.py new file mode 100644 index 000000000..6cf5dd21c --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractformwindow.py @@ -0,0 +1,74 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the documentation of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [0] + formWindow = QDesignerFormWindowInterface() + formWindow = QDesignerFormWindowInterface.findFormWindow(myWidget) +//! [0] + + +//! [1] + forms = [] # QList + formWindow = QDesignerFormWindowInterface() + + manager = formEditor.formWindowManager() + + for i in range(manager.formWindowCount()): + formWindow = manager.formWindow(i) + forms.append(formWindow) +//! [1] + + +//! [2] + if formWindow.isManaged(myWidget): + formWindow.manageWidget(myWidget.childWidget) +//! [2] + + diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp deleted file mode 100644 index 255231512..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of Qt for Python. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [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(object); - - if (widget && property == aProperty && value != expectedValue) - {...} - } -//! [1] - - diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.py new file mode 100644 index 000000000..1e2ac506f --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/code/tools_designer_src_lib_sdk_abstractpropertyeditor.py @@ -0,0 +1,71 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the documentation of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [0] + propertyEdit = QDesignerPropertyEditorInterface() + propertyEditor = formEditor.propertyEditor() + + propertyEditor.propertyChanged.connect(self.checkProperty) +//! [0] + + +//! [1] + def checkProperty(self, property, value): + propertyEditor = QDesignerPropertyEditorInterface() + propertyEditor = formEditor.propertyEditor() + + object = propertyeditor.object() + widget = MyCustomWidget(object) + + if (widget and property == aProperty and value != expectedValue): + # ... +//! [1] + + diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.cpp deleted file mode 100644 index 047434f6d..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.cpp +++ /dev/null @@ -1,129 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - - -//! [0] -def find(self) - - if !self.findDialog: - self.findDialog = FindDialog(self) - connect(findDialog, SIGNAL("findNext()"), self, SLOT("findNext()")) - - - self.findDialog.show() - self.findDialog.raise() - self.findDialog.activateWindow() - -//! [0] - -//! [1] -def countWords(self): - dialog = WordCountDialog(self) - dialog.setWordCount(document().wordCount()) - dialog.exec_() - -//! [1] - -//! [2] - mb = QMessageBox("Application Name", - "Hardware failure.\n\nDisk error detected\nDo you want to stop?", - QMessageBox.Question, - QMessageBox.Yes | QMessageBox.Default, - QMessageBox.No | QMessageBox.Escape, - QMessageBox.NoButton) - if mb.exec() == QMessageBox.No: - # try again -//! [2] - -//! [3] - progress = QProgressDialog("Copying files...", "Abort Copy", 0, numFiles, self) - progress.setWindowModality(Qt.WindowModal) - - for i in rang(numFiles): - progress.setValue(i) - - if progress.wasCanceled(): - break - #... copy one file - - progress.setValue(numFiles) -//! [3] - -//! [4] -# Operation constructor -def __init__(self, parent): - QObject.__init__(self, parent) - - pd = QProgressDialog("Operation in progress.", "Cancel", 0, 100) - connect(pd, SIGNAL("canceled()"), self, SLOT("cancel()")) - t = QTimer(self) - connect(t, SIGNAL("timeout()"), self, SLOT("perform()")) - t.start(0) - -//! [4] //! [5] - -def perform(self): - - pd.setValue(steps) - #... perform one percent of the operation - steps++ - if steps > pd.maximum(): - t.stop() - -//! [5] //! [6] - -def cancel(self): - - t.stop() - #... cleanup - -//! [6] - - diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.py new file mode 100644 index 000000000..7bdcb0c91 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/dialogs/dialogs.py @@ -0,0 +1,123 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + + +//! [0] +def find(self): + if not self.findDialog: + self.findDialog = FindDialog(self) + self.findDialog.findNext.connect(self.findNext) + + self.findDialog.show() + self.findDialog.raise() + self.findDialog.activateWindow() + +//! [0] + +//! [1] +def countWords(self): + dialog = WordCountDialog(self) + dialog.setWordCount(document().wordCount()) + dialog.exec_() + +//! [1] + +//! [2] + mb = QMessageBox("Application Name", + "Hardware failure.\n\nDisk error detected\nDo you want to stop?", + QMessageBox.Question, + QMessageBox.Yes | QMessageBox.Default, + QMessageBox.No | QMessageBox.Escape, + QMessageBox.NoButton) + if mb.exec() == QMessageBox.No: + # try again +//! [2] + +//! [3] + progress = QProgressDialog("Copying files...", "Abort Copy", 0, numFiles, self) + progress.setWindowModality(Qt.WindowModal) + + for i in range(numFiles): + progress.setValue(i) + + if progress.wasCanceled(): + break + #... copy one file + + progress.setValue(numFiles) +//! [3] + +//! [4] +# Operation constructor +def __init__(self, parent=None): + QObject.__init__(self, parent) + + pd = QProgressDialog("Operation in progress.", "Cancel", 0, 100) + pd.canceled.connect(self.cancel) + t = QTimer(self) + t.timeout.connect(self.perform) + t.start(0) + +//! [4] //! [5] + +def perform(self): + pd.setValue(steps) + #... perform one percent of the operation + steps += 1 + if steps > pd.maximum(): + t.stop() + +//! [5] //! [6] + +def cancel(self): + t.stop() + #... cleanup + +//! [6] diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.h b/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.h deleted file mode 100644 index 8607b6953..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.h +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of Qt for Python. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef WINDOW_H -#define WINDOW_H - -#include -#include -#include - -class QComboBox; -class QFrame; -class QTextBrowser; - -class Window : public QWidget -{ - Q_OBJECT - -public: - Window(QWidget *parent = 0); - -protected: - void dragEnterEvent(QDragEnterEvent *event); - void dropEvent(QDropEvent *event); - -private: - QComboBox *mimeTypeCombo; - QFrame *dropFrame; - QTextBrowser *textBrowser; - QString oldText; - QStringList oldMimeTypes; -}; - -#endif diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.py new file mode 100644 index 000000000..66a6a7ba2 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/dropevents/window.py @@ -0,0 +1,65 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtWidgets import QWidget, QComboBox, QFrame, QTextBrowser + +class Window(QWidget): + + def __init__(self, parent=None): + self.mimeTypeCombo = QComboBox() + self.dropFrame = QFrame() + self.textBrowser = QTextBrowser() + self.oldText = "" + self.oldMimeTypes = [] + + def dragEnterEvent(self, event): + pass + def dropEvent(self, event): + pass diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedlayout/main.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedlayout/main.py new file mode 100644 index 000000000..184128406 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedlayout/main.py @@ -0,0 +1,87 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the documentation of the Qt Toolkit. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtWidgets import QApplication, QWidget, QStackedLayout, QComboBox + +class Widget(QWidget) + def __init__(self, parent=None): + QWidget.__init__(self, parent) +//! [0] + self.firstPageWidget = QWidget() + self.secondPageWidget = QWidget() + self.thirdPageWidget = QWidget() + + self.stackedLayout = QStackedLayout() + self.stackedLayout.addWidget(self.firstPageWidget) + self.stackedLayout.addWidget(self.secondPageWidget) + self.stackedLayout.addWidget(self.thirdPageWidget) + +//! [0] //! [1] + self.pageComboBox = QComboBox() + self.pageComboBox.addItem(tr("Page 1")) + self.pageComboBox.addItem(tr("Page 2")) + self.pageComboBox.addItem(tr("Page 3")) + self.pageComboBox.activated.connect(self.stackedLayout.setCurrentIndex) +//! [1] + +//! [2] + self.mainLayout = QVBoxLayout() +//! [2] + self.mainLayout.addWidget(self.pageComboBox) +//! [3] + self.mainLayout.addLayout(self.stackedLayout) + self.setLayout(self.mainLayout) +//! [3] + +if __name__ == "__main__": + app = QApplication(sys.argv) + widget = Widget() + widget.show() + sys.exit(app.exec_()) diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.cpp deleted file mode 100644 index 98a08be98..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.cpp +++ /dev/null @@ -1,78 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - - -//! [0] - firstPageWidget = QWidget() - secondPageWidget = QWidget() - thirdPageWidget = QWidget() - - stackedWidget = QStackedWidget() - stackedWidget.addWidget(firstPageWidget) - stackedWidget.addWidget(secondPageWidget) - stackedWidget.addWidget(thirdPageWidget) - -//! [0] //! [1] - pageComboBox = QComboBox() - pageComboBox.addItem(tr("Page 1")) - pageComboBox.addItem(tr("Page 2")) - pageComboBox.addItem(tr("Page 3")) - connect(pageComboBox, SIGNAL("activated(int)"), - stackedWidget, SLOT("setCurrentIndex(int)")) - -//! [1] //! [2] - layout = QVBoxLayout() -//! [2] - layout.addWidget(pageComboBox) -//! [3] - layout.addWidget(stackedWidget) - setLayout(layout) -//! [3] - diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.py new file mode 100644 index 000000000..6f2c49d8e --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/qstackedwidget/main.py @@ -0,0 +1,77 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + + +//! [0] + firstPageWidget = QWidget() + secondPageWidget = QWidget() + thirdPageWidget = QWidget() + + stackedWidget = QStackedWidget() + stackedWidget.addWidget(firstPageWidget) + stackedWidget.addWidget(secondPageWidget) + stackedWidget.addWidget(thirdPageWidget) + +//! [0] //! [1] + pageComboBox = QComboBox() + pageComboBox.addItem(tr("Page 1")) + pageComboBox.addItem(tr("Page 2")) + pageComboBox.addItem(tr("Page 3")) + pageComboBox.activated[int].connect(stackedWidget.setCurrentIndex) + +//! [1] //! [2] + layout = QVBoxLayout() +//! [2] + layout.addWidget(pageComboBox) +//! [3] + layout.addWidget(stackedWidget) + setLayout(layout) +//! [3] + diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.cpp deleted file mode 100644 index 734f603a9..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the documentation of Qt for Python. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [0] - QBuffer device; - device.setData(myQString.toUtf8()); - device.open(QIODevice::ReadOnly); - - QXmlQuery query; - query.setQuery("doc($inputDocument)/query[theDocument]"); - query.bindVariable("inputDocument", &device); -//! [0] diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.py new file mode 100644 index 000000000..16c12b7bc --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/qxmlquery/bindingExample.py @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of Qt for Python. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//! [0] + device = QBuffer() + device.setData(myQString.toUtf8()) + device.open(QIODevice.ReadOnly) + + query = QXmlQuery() + query.setQuery("doc($inputDocument)/query[theDocument]") + query.bindVariable("inputDocument", device) +//! [0] diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.cpp b/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.cpp deleted file mode 100644 index 29ac9c87d..000000000 --- a/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.cpp +++ /dev/null @@ -1,489 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -from PySide2.QtGui import * -from PySide2.QtSql import * - - -def tr(text): - return QApplication.translate(text, text) - -def QSqlDatabase_snippets(): -//! [0] - db = QSqlDatabase.addDatabase("QPSQL") - db.setHostName("acidalia") - db.setDatabaseName("customdb") - db.setUserName("mojito") - db.setPassword("J0a1m8") - ok = db.open() -//! [0] - -//! [1] - db = QSqlDatabase.database() -//! [1] - -def QSqlField_snippets(): -//! [2] - field = QSqlField("age", QVariant.Int) - field.setValue(QPixmap()) # WRONG -//! [2] - -//! [3] - field = QSqlField("age", QVariant.Int) - field.setValue(QString("123")) # casts QString to int -//! [3] - -//! [4] - query = QSqlQuery() -//! [4] //! [5] - record = query.record() -//! [5] //! [6] - field = record.field("country") -//! [6] - -def doSomething(str): - pass - -def QSqlQuery_snippets(): - # typical loop -//! [7] - query = QSqlQuery("SELECT country FROM artist") - while query.next(): - country = query.value(0) - doSomething(country) -//! [7] - - - # field index lookup -//! [8] - query = QSqlQuery("SELECT * FROM artist") - fieldNo = query.record().indexOf("country") - while query.next(): - country = query.value(fieldNo) - doSomething(country) -//! [8] - - # named with named -//! [9] - query = QSqlQuery() - query.prepare("INSERT INTO person (id, forename, surname) " - "VALUES (:id, :forename, :surname)") - query.bindValue(":id", 1001) - query.bindValue(":forename", "Bart") - query.bindValue(":surname", "Simpson") - query.exec_() -//! [9] - - # positional with named -//! [10] - query = QSqlQuery() - query.prepare("INSERT INTO person (id, forename, surname) " - "VALUES (:id, :forename, :surname)") - query.bindValue(0, 1001) - query.bindValue(1, "Bart") - query.bindValue(2, "Simpson") - query.exec_() -//! [10] - - # positional 1 -//! [11] - query = QSqlQuery() - query.prepare("INSERT INTO person (id, forename, surname) " - "VALUES (?, ?, ?)") - query.bindValue(0, 1001) - query.bindValue(1, "Bart") - query.bindValue(2, "Simpson") - query.exec_() -//! [11] - - # positional 2 -//! [12] - query = QSqlQuery() - query.prepare("INSERT INTO person (id, forename, surname) " - "VALUES (?, ?, ?)") - query.addBindValue(1001) - query.addBindValue("Bart") - query.addBindValue("Simpson") - query.exec_() -//! [12] - - # stored -//! [13] - query = QSqlQuery() - query.prepare("CALL AsciiToInt(?, ?)") - query.bindValue(0, "A") - query.bindValue(1, 0, QSql.Out) - query.exec_() - i = query.boundValue(1) # i is 65 -//! [13] - - query = QSqlQuery() - - # examine with named binding -//! [14] - i = query.boundValues() - while i.hasNext(): - i.next() - print i.key(), ": ", i.value() -//! [14] - - # examine with positional binding -//! [15] - list_ = query.boundValues().values() - for item in list: - print item -//! [15] - -def QSqlQueryModel_snippets(): - -//! [16] - model = QSqlQueryModel() - model.setQuery("SELECT name, salary FROM employee") - model.setHeaderData(0, Qt.Horizontal, tr("Name")) - model.setHeaderData(1, Qt.Horizontal, tr("Salary")) - -//! [17] - view = QTableView() -//! [17] //! [18] - view.setModel(model) -//! [18] //! [19] - view.show() -//! [16] //! [19] //! [20] - view.setEditTriggers(QAbstractItemView.NoEditTriggers) -//! [20] - -//! [21] - model = QSqlQueryModel() - model.setQuery("SELECT * FROM employee") - salary = model.record(4).value("salary") -//! [21] - -//! [22] - salary = model.data(model.index(4, 2)) -//! [22] - - for row in range(model.rowCount()): - for (col in range(model.columnCount())): - print model.data(model.index(row, col)) - - -class MyModel(QSqlQueryModel) - m_specialColumnNo = 0 - def data(item, role): -//! [23] - if item.column() == self.m_specialColumnNo: - # handle column separately - pass - - return QSqlQueryModel.data(item, role) - -//! [23] - - -def QSqlTableModel_snippets(): - -//! [24] - model = QSqlTableModel() - model.setTable("employee") - model.setEditStrategy(QSqlTableModel.OnManualSubmit) - model.select() - model.removeColumn(0) # don't show the ID - model.setHeaderData(0, Qt.Horizontal, tr("Name")) - model.setHeaderData(1, Qt.Horizontal, tr("Salary")) - - view = QTableView() - view.setModel(model) - view.show() -//! [24] - - -//! [25] - model = QSqlTableModel() - model.setTable("employee") - QString name = model.record(4).value("name") -//! [25] - -def sql_intro_snippets(): - -//! [26] - db = QSqlDatabase.addDatabase("QMYSQL") - db.setHostName("bigblue") - db.setDatabaseName("flightdb") - db.setUserName("acarlson") - db.setPassword("1uTbSbAs") - ok = db.open() -//! [26] - -//! [27] - firstDB = QSqlDatabase.addDatabase("QMYSQL", "first") - secondDB = QSqlDatabase.addDatabase("QMYSQL", "second") -//! [27] - -//! [28] - defaultDB = QSqlDatabase.database() -//! [28] //! [29] - firstDB = QSqlDatabase.database("first") -//! [29] //! [30] - secondDB = QSqlDatabase.database("second") -//! [30] - - # SELECT1 -//! [31] - query = QSqlQuery() - query.exec_("SELECT name, salary FROM employee WHERE salary > 50000") -//! [31] - -//! [32] - while query.next(): - name = query.value(0) - salary = query.value(1) - print name, salary -//! [32] - - # FEATURE -//! [33] - query = QSqlQuery() - query.exec_("SELECT name, salary FROM employee WHERE salary > 50000") - - defaultDB = QSqlDatabase.database() - if defaultDB.driver().hasFeature(QSqlDriver.QuerySize): - numRows = query.size() - else: - # self can be very slow - query.last() - numRows = query.at() + 1 -//! [33] - - # INSERT1 -//! [34] - query = QSqlQuery() - query.exec_("INSERT INTO employee (id, name, salary) " - "VALUES (1001, 'Thad Beaumont', 65000)") -//! [34] - - # NAMED BINDING -//! [35] - query = QSqlQuery() - query.prepare("INSERT INTO employee (id, name, salary) " - "VALUES (:id, :name, :salary)") - query.bindValue(":id", 1001) - query.bindValue(":name", "Thad Beaumont") - query.bindValue(":salary", 65000) - query.exec_() -//! [35] - - # POSITIONAL BINDING -//! [36] - query = QSqlQuery() - query.prepare("INSERT INTO employee (id, name, salary) " - "VALUES (?, ?, ?)") - query.addBindValue(1001) - query.addBindValue("Thad Beaumont") - query.addBindValue(65000) - query.exec_() -//! [36] - - # UPDATE1 -//! [37] - query = QSqlQuery() - query.exec_("UPDATE employee SET salary = 70000 WHERE id = 1003") -//! [37] - - # DELETE1 -//! [38] - query = QSqlQuery() - query.exec_("DELETE FROM employee WHERE id = 1007") -//! [38] - - # TRANSACTION -//! [39] - QSqlDatabase.database().transaction() - query = QSqlQuery() - query.exec_("SELECT id FROM employee WHERE name = 'Torild Halvorsen'") - if query.next(): - employeeId = query.value(0) - query.exec_("INSERT INTO project (id, name, ownerid) " - "VALUES (201, 'Manhattan Project', " - + QString.number(employeeId) + ')') - - QSqlDatabase.database().commit() -//! [39] - - # SQLQUERYMODEL1 -//! [40] - model = QSqlQueryModel() - model.setQuery("SELECT * FROM employee") - - for i in range(model.rowCount()): - _id = model.record(i).value("id") - name = model.record(i).value("name") - print _id, name - -//! [40] - } - - { - # SQLTABLEMODEL1 -//! [41] - model = QSqlTableModel() - model.setTable("employee") - model.setFilter("salary > 50000") - model.setSort(2, Qt.DescendingOrder) - model.select() - - for i in range(model.rowCount()): - name = model.record(i).value("name") - salary = model.record(i).value("salary") - print "%s: %d" % (name, salary) - -//! [41] - - # SQLTABLEMODEL2 - model = QSqlTableModel() - model.setTable("employee") - -//! [42] - for i in range(model.rowCount()): - record = model.record(i) - salary = record.value("salary") - salary *= 1.1 - record.setValue("salary", salary) - model.setRecord(i, record) - - model.submitAll() -//! [42] - - # SQLTABLEMODEL3 - row = 1 - column = 2 -//! [43] - model.setData(model.index(row, column), 75000) - model.submitAll() -//! [43] - - # SQLTABLEMODEL4 -//! [44] - model.insertRows(row, 1) - model.setData(model.index(row, 0), 1013) - model.setData(model.index(row, 1), "Peter Gordon") - model.setData(model.index(row, 2), 68500) - model.submitAll() -//! [44] - -//! [45] - model.removeRows(row, 5) -//! [45] - -//! [46] - model.submitAll() -//! [46] - -//! [47] -class XyzResult(QSqlResult): - def __init__(driver): - QSqlResult.__init__(self, driver) - pass - - def data(self, index): - return QVariant() - - def isNull(self, index): - return False - - def reset(self, query): - return False - - def fetch(self, index): - return False - - def fetchFirst(self): - return False - - def fetchLast(self): - return False - - def size(self): - return 0 - - def numRowsAffected(self): - return 0 - - def record(self): - return QSqlRecord() - -//! [47] - -//! [48] -class XyzDriver(QSqlDriver) - def hasFeature(self, feature): - return False - - def open(self, db, user, password, host, port, options): - return False - - def close(self): - pass - - def createResult(self): - return XyzResult(self) - -//! [48] - -def main(): - app = QApplication([]) - - QSqlDatabase_snippets() - QSqlField_snippets() - QSqlQuery_snippets() - QSqlQueryModel_snippets() - QSqlTableModel_snippets() - - driver = XyzDriver() - result = XyzResult(driver) diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py new file mode 100644 index 000000000..7c28cf5e6 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/sqldatabase/sqldatabase.py @@ -0,0 +1,489 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtGui import * +from PySide2.QtSql import * + + +def tr(text): + return QApplication.translate(text, text) + +def QSqlDatabase_snippets(): +//! [0] + db = QSqlDatabase.addDatabase("QPSQL") + db.setHostName("acidalia") + db.setDatabaseName("customdb") + db.setUserName("mojito") + db.setPassword("J0a1m8") + ok = db.open() +//! [0] + +//! [1] + db = QSqlDatabase.database() +//! [1] + +def QSqlField_snippets(): +//! [2] + field = QSqlField("age", QVariant.Int) + field.setValue(QPixmap()) # WRONG +//! [2] + +//! [3] + field = QSqlField("age", QVariant.Int) + field.setValue(str(123)) # casts str to int +//! [3] + +//! [4] + query = QSqlQuery() +//! [4] //! [5] + record = query.record() +//! [5] //! [6] + field = record.field("country") +//! [6] + +def doSomething(str): + pass + +def QSqlQuery_snippets(): + # typical loop +//! [7] + query = QSqlQuery("SELECT country FROM artist") + while query.next(): + country = query.value(0) + doSomething(country) +//! [7] + + + # field index lookup +//! [8] + query = QSqlQuery("SELECT * FROM artist") + fieldNo = query.record().indexOf("country") + while query.next(): + country = query.value(fieldNo) + doSomething(country) +//! [8] + + # named with named +//! [9] + query = QSqlQuery() + query.prepare("INSERT INTO person (id, forename, surname) " + "VALUES (:id, :forename, :surname)") + query.bindValue(":id", 1001) + query.bindValue(":forename", "Bart") + query.bindValue(":surname", "Simpson") + query.exec_() +//! [9] + + # positional with named +//! [10] + query = QSqlQuery() + query.prepare("INSERT INTO person (id, forename, surname) " + "VALUES (:id, :forename, :surname)") + query.bindValue(0, 1001) + query.bindValue(1, "Bart") + query.bindValue(2, "Simpson") + query.exec_() +//! [10] + + # positional 1 +//! [11] + query = QSqlQuery() + query.prepare("INSERT INTO person (id, forename, surname) " + "VALUES (?, ?, ?)") + query.bindValue(0, 1001) + query.bindValue(1, "Bart") + query.bindValue(2, "Simpson") + query.exec_() +//! [11] + + # positional 2 +//! [12] + query = QSqlQuery() + query.prepare("INSERT INTO person (id, forename, surname) " + "VALUES (?, ?, ?)") + query.addBindValue(1001) + query.addBindValue("Bart") + query.addBindValue("Simpson") + query.exec_() +//! [12] + + # stored +//! [13] + query = QSqlQuery() + query.prepare("CALL AsciiToInt(?, ?)") + query.bindValue(0, "A") + query.bindValue(1, 0, QSql.Out) + query.exec_() + i = query.boundValue(1) # i is 65 +//! [13] + + query = QSqlQuery() + + # examine with named binding +//! [14] + i = query.boundValues() + while i.hasNext(): + i.next() + print i.key(), ": ", i.value() +//! [14] + + # examine with positional binding +//! [15] + list_ = query.boundValues().values() + for item in list: + print item +//! [15] + +def QSqlQueryModel_snippets(): + +//! [16] + model = QSqlQueryModel() + model.setQuery("SELECT name, salary FROM employee") + model.setHeaderData(0, Qt.Horizontal, tr("Name")) + model.setHeaderData(1, Qt.Horizontal, tr("Salary")) + +//! [17] + view = QTableView() +//! [17] //! [18] + view.setModel(model) +//! [18] //! [19] + view.show() +//! [16] //! [19] //! [20] + view.setEditTriggers(QAbstractItemView.NoEditTriggers) +//! [20] + +//! [21] + model = QSqlQueryModel() + model.setQuery("SELECT * FROM employee") + salary = model.record(4).value("salary") +//! [21] + +//! [22] + salary = model.data(model.index(4, 2)) +//! [22] + + for row in range(model.rowCount()): + for (col in range(model.columnCount())): + print model.data(model.index(row, col)) + + +class MyModel(QSqlQueryModel) + m_specialColumnNo = 0 + def data(item, role): +//! [23] + if item.column() == self.m_specialColumnNo: + # handle column separately + pass + + return QSqlQueryModel.data(item, role) + +//! [23] + + +def QSqlTableModel_snippets(): + +//! [24] + model = QSqlTableModel() + model.setTable("employee") + model.setEditStrategy(QSqlTableModel.OnManualSubmit) + model.select() + model.removeColumn(0) # don't show the ID + model.setHeaderData(0, Qt.Horizontal, tr("Name")) + model.setHeaderData(1, Qt.Horizontal, tr("Salary")) + + view = QTableView() + view.setModel(model) + view.show() +//! [24] + + +//! [25] + model = QSqlTableModel() + model.setTable("employee") + name = model.record(4).value("name") +//! [25] + +def sql_intro_snippets(): + +//! [26] + db = QSqlDatabase.addDatabase("QMYSQL") + db.setHostName("bigblue") + db.setDatabaseName("flightdb") + db.setUserName("acarlson") + db.setPassword("1uTbSbAs") + ok = db.open() +//! [26] + +//! [27] + firstDB = QSqlDatabase.addDatabase("QMYSQL", "first") + secondDB = QSqlDatabase.addDatabase("QMYSQL", "second") +//! [27] + +//! [28] + defaultDB = QSqlDatabase.database() +//! [28] //! [29] + firstDB = QSqlDatabase.database("first") +//! [29] //! [30] + secondDB = QSqlDatabase.database("second") +//! [30] + + # SELECT1 +//! [31] + query = QSqlQuery() + query.exec_("SELECT name, salary FROM employee WHERE salary > 50000") +//! [31] + +//! [32] + while query.next(): + name = query.value(0) + salary = query.value(1) + print name, salary +//! [32] + + # FEATURE +//! [33] + query = QSqlQuery() + query.exec_("SELECT name, salary FROM employee WHERE salary > 50000") + + defaultDB = QSqlDatabase.database() + if defaultDB.driver().hasFeature(QSqlDriver.QuerySize): + numRows = query.size() + else: + # self can be very slow + query.last() + numRows = query.at() + 1 +//! [33] + + # INSERT1 +//! [34] + query = QSqlQuery() + query.exec_("INSERT INTO employee (id, name, salary) " + "VALUES (1001, 'Thad Beaumont', 65000)") +//! [34] + + # NAMED BINDING +//! [35] + query = QSqlQuery() + query.prepare("INSERT INTO employee (id, name, salary) " + "VALUES (:id, :name, :salary)") + query.bindValue(":id", 1001) + query.bindValue(":name", "Thad Beaumont") + query.bindValue(":salary", 65000) + query.exec_() +//! [35] + + # POSITIONAL BINDING +//! [36] + query = QSqlQuery() + query.prepare("INSERT INTO employee (id, name, salary) " + "VALUES (?, ?, ?)") + query.addBindValue(1001) + query.addBindValue("Thad Beaumont") + query.addBindValue(65000) + query.exec_() +//! [36] + + # UPDATE1 +//! [37] + query = QSqlQuery() + query.exec_("UPDATE employee SET salary = 70000 WHERE id = 1003") +//! [37] + + # DELETE1 +//! [38] + query = QSqlQuery() + query.exec_("DELETE FROM employee WHERE id = 1007") +//! [38] + + # TRANSACTION +//! [39] + QSqlDatabase.database().transaction() + query = QSqlQuery() + query.exec_("SELECT id FROM employee WHERE name = 'Torild Halvorsen'") + if query.next(): + employeeId = query.value(0) + query.exec_("INSERT INTO project (id, name, ownerid) " + "VALUES (201, 'Manhattan Project', " + + str(employeeId) + ')') + + QSqlDatabase.database().commit() +//! [39] + + # SQLQUERYMODEL1 +//! [40] + model = QSqlQueryModel() + model.setQuery("SELECT * FROM employee") + + for i in range(model.rowCount()): + _id = model.record(i).value("id") + name = model.record(i).value("name") + print _id, name + +//! [40] + } + + { + # SQLTABLEMODEL1 +//! [41] + model = QSqlTableModel() + model.setTable("employee") + model.setFilter("salary > 50000") + model.setSort(2, Qt.DescendingOrder) + model.select() + + for i in range(model.rowCount()): + name = model.record(i).value("name") + salary = model.record(i).value("salary") + print "%s: %d" % (name, salary) + +//! [41] + + # SQLTABLEMODEL2 + model = QSqlTableModel() + model.setTable("employee") + +//! [42] + for i in range(model.rowCount()): + record = model.record(i) + salary = record.value("salary") + salary *= 1.1 + record.setValue("salary", salary) + model.setRecord(i, record) + + model.submitAll() +//! [42] + + # SQLTABLEMODEL3 + row = 1 + column = 2 +//! [43] + model.setData(model.index(row, column), 75000) + model.submitAll() +//! [43] + + # SQLTABLEMODEL4 +//! [44] + model.insertRows(row, 1) + model.setData(model.index(row, 0), 1013) + model.setData(model.index(row, 1), "Peter Gordon") + model.setData(model.index(row, 2), 68500) + model.submitAll() +//! [44] + +//! [45] + model.removeRows(row, 5) +//! [45] + +//! [46] + model.submitAll() +//! [46] + +//! [47] +class XyzResult(QSqlResult): + def __init__(driver): + QSqlResult.__init__(self, driver) + pass + + def data(self, index): + return QVariant() + + def isNull(self, index): + return False + + def reset(self, query): + return False + + def fetch(self, index): + return False + + def fetchFirst(self): + return False + + def fetchLast(self): + return False + + def size(self): + return 0 + + def numRowsAffected(self): + return 0 + + def record(self): + return QSqlRecord() + +//! [47] + +//! [48] +class XyzDriver(QSqlDriver) + def hasFeature(self, feature): + return False + + def open(self, db, user, password, host, port, options): + return False + + def close(self): + pass + + def createResult(self): + return XyzResult(self) + +//! [48] + +def main(): + app = QApplication([]) + + QSqlDatabase_snippets() + QSqlField_snippets() + QSqlQuery_snippets() + QSqlQueryModel_snippets() + QSqlTableModel_snippets() + + driver = XyzDriver() + result = XyzResult(driver) diff --git a/sources/pyside2/doc/codesnippets/doc/src/snippets/widgets-tutorial/template.py b/sources/pyside2/doc/codesnippets/doc/src/snippets/widgets-tutorial/template.py new file mode 100644 index 000000000..d38829fc7 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/doc/src/snippets/widgets-tutorial/template.py @@ -0,0 +1,66 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the documentation of the Qt Toolkit. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [main.cpp body] +import sys +from PySide2.QtWidgets import QApplication + +# Include header files for application components. +# ... + +if __name__ == "__main__": + app = QApplication(sys.argv) + + # Set up and show widgets. + # ... + + sys.exit(app.exec_()) +} +//! [main.cpp body] diff --git a/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.cpp b/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.cpp deleted file mode 100644 index 897410ed7..000000000 --- a/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2016 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//! [0] //! [1] -def __init__(self, parent): - QWizard.__init__(self, parent): - self.addPage(IntroPage()) - self.addPage(ClassInfoPage()) - self.addPage(CodeStylePage()) - self.addPage(OutputFilesPage()) - self.addPage(ConclusionPage()) -//! [0] - - self.setPixmap(QWizard.BannerPixmap, QPixmap(":/images/banner.png")) - self.setPixmap(QWizard.BackgroundPixmap, QPixmap(":/images/background.png")) - - self.setWindowTitle(self.tr("Class Wizard")) -//! [2] - -//! [1] //! [2] - -//! [3] -def accept(self): -//! [3] //! [4] - className = self.field("className") - baseClass = self.field("baseClass") - macroName = self.field("macroName") - baseInclude = self.field("baseInclude") - - outputDir = self.field("outputDir") - header = self.field("header") - implementation = self.field("implementation") -//! [4] - -... - -//! [5] - QDialog.accept(self) -//! [5] //! [6] -} -//! [6] - -//! [7] -class IntroPage (QWizardPage): - - def __init__(self, parent): - QWizardPage.__init__(self, parent) - - self.setTitle(tr("Introduction")) - self.setPixmap(QWizard.WatermarkPixmap, QPixmap(":/images/watermark1.png")) - - label = QLabel(self.tr("This wizard will generate a skeleton C++ class " \ - "definition, including a few functions. You simply " \ - "need to specify the class name and set a few " \ - "options to produce a header file and an " \ - "implementation file for your new C++ class.")) - label.setWordWrap(True) - - layout = QVBoxLayout() - layout.addWidget(label) - self.setLayout(layout) -} -//! [7] - -//! [8] //! [9] -class ClassInfoPage(QWizardPage): - - def __init__(self, parent): - QWizardPage.__init__(self, parent) -//! [8] - self.setTitle(self.tr("Class Information")) - self.setSubTitle(self.tr("Specify basic information about the class for which you " \ - "want to generate skeleton source code files.")) - self.setPixmap(QWizard.LogoPixmap, QPixmap(":/images/logo1.png")) - -//! [10] - classNameLabel = QLabel(self.tr("&Class name:")) - classNameLineEdit = QLineEdit() - classNameLabel.setBuddy(classNameLineEdit) - - baseClassLabel = QLabel(self.tr("B&ase class:")) - baseClassLineEdit = QLineEdit() - baseClassLabel.setBuddy(baseClassLineEdit) - - qobjectMacroCheckBox = QCheckBox(self.tr("Generate Q_OBJECT ¯o")) - -//! [10] - groupBox = QGroupBox(self.tr("C&onstructor")) -//! [9] - - qobjectCtorRadioButton = QRadioButton(self.tr("&QObject-style constructor")) - qwidgetCtorRadioButton = QRadioButton(self.tr("Q&Widget-style constructor")) - defaultCtorRadioButton = QRadioButton(self.tr("&Default constructor")) - copyCtorCheckBox = QCheckBox(self.tr("&Generate copy constructor and operator=")) - - defaultCtorRadioButton.setChecked(True) - - self.connect(defaultCtorRadioButton, SIGNAL("toggled(bool)"), - copyCtorCheckBox, SLOT("setEnabled(bool)")) - -//! [11] //! [12] - registerField("className*", classNameLineEdit) - registerField("baseClass", baseClassLineEdit) - registerField("qobjectMacro", qobjectMacroCheckBox) -//! [11] - registerField("qobjectCtor", qobjectCtorRadioButton) - registerField("qwidgetCtor", qwidgetCtorRadioButton) - registerField("defaultCtor", defaultCtorRadioButton) - registerField("copyCtor", copyCtorCheckBox) - - groupBoxLayout = QVBoxLayout() -//! [12] - groupBoxLayout.addWidget(qobjectCtorRadioButton) - groupBoxLayout.addWidget(qwidgetCtorRadioButton) - groupBoxLayout.addWidget(defaultCtorRadioButton) - groupBoxLayout.addWidget(copyCtorCheckBox) - groupBox.setLayout(groupBoxLayout) - - layout = QGridLayout() - layout.addWidget(classNameLabel, 0, 0) - layout.addWidget(classNameLineEdit, 0, 1) - layout.addWidget(baseClassLabel, 1, 0) - layout.addWidget(baseClassLineEdit, 1, 1) - layout.addWidget(qobjectMacroCheckBox, 2, 0, 1, 2) - layout.addWidget(groupBox, 3, 0, 1, 2) - self.setLayout(layout) -//! [13] - -//! [13] - -//! [14] -class CodeStylePage(QWizardPage): - - def __init__(self, parent): - QWizardPage.__init__(self, parent) - self.setTitle(tr("Code Style Options")) - self.setSubTitle(tr("Choose the formatting of the generated code.")) - self.setPixmap(QWizard.LogoPixmap, QPixmap(":/images/logo2.png")) - - commentCheckBox = QCheckBox(self.tr("&Start generated files with a comment")) -//! [14] - commentCheckBox.setChecked(True) - - protectCheckBox = QCheckBox(self.tr("&Protect header file against multiple " \ - "inclusions")) - protectCheckBox.setChecked(True) - - macroNameLabel = QLabel(self.tr("&Macro name:")) - macroNameLineEdit = QLineEdit() - macroNameLabel.setBuddy(macroNameLineEdit) - - includeBaseCheckBox = QCheckBox(self.tr("&Include base class definition")) - baseIncludeLabel = QLabel(self.tr("Base class include:")) - baseIncludeLineEdit = QLineEdit() - baseIncludeLabel.setBuddy(baseIncludeLineEdit) - - self.connect(protectCheckBox, SIGNAL("toggled(bool)"), - macroNameLabel, SLOT("setEnabled(bool)")) - self.connect(protectCheckBox, SIGNAL("toggled(bool)"), - macroNameLineEdit, SLOT("setEnabled(bool)")) - self.connect(includeBaseCheckBox, SIGNAL("toggled(bool)"), - baseIncludeLabel, SLOT("setEnabled(bool)")) - self.connect(includeBaseCheckBox, SIGNAL(toggled(bool)), - baseIncludeLineEdit, SLOT("setEnabled(bool)")) - - self.registerField("comment", commentCheckBox) - self.registerField("protect", protectCheckBox) - self.registerField("macroName", macroNameLineEdit) - self.registerField("includeBase", includeBaseCheckBox) - self.registerField("baseInclude", baseIncludeLineEdit) - - layout = QGridLayout() - layout.setColumnMinimumWidth(0, 20) - layout.addWidget(commentCheckBox, 0, 0, 1, 3) - layout.addWidget(protectCheckBox, 1, 0, 1, 3) - layout.addWidget(macroNameLabel, 2, 1) - layout.addWidget(macroNameLineEdit, 2, 2) - layout.addWidget(includeBaseCheckBox, 3, 0, 1, 3) - layout.addWidget(baseIncludeLabel, 4, 1) - layout.addWidget(baseIncludeLineEdit, 4, 2) -//! [15] - self.setLayout(layout) -} -//! [15] - -//! [16] - def initializePage(self): - className = self.field("className") - self.macroNameLineEdit.setText(className.upper() + "_H") - - baseClass = self.field("baseClass") - - self.includeBaseCheckBox.setChecked(len(baseClass)) - self.includeBaseCheckBox.setEnabled(len(baseClass)) - self.baseIncludeLabel.setEnabled(len(baseClass)) - self.baseIncludeLineEdit.setEnabled(len(baseClass)) - - if not baseClass: - self.baseIncludeLineEdit.clear() - elsif QRegExp("Q[A-Z].*").exactMatch(baseClass): - baseIncludeLineEdit.setText("<" + baseClass + ">") - else: - baseIncludeLineEdit.setText("\"" + baseClass.lower() + ".h\"") -//! [16] - -//! [17] - def initializePage(self): - className = field("className") - self.headerLineEdit.setText(className.lower() + ".h") - self.implementationLineEdit.setText(className.lower() + ".cpp") - self.outputDirLineEdit.setText(QDir.convertSeparators(QDir.tempPath())) -//! [17] diff --git a/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.py b/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.py new file mode 100644 index 000000000..08032cf2a --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/dialogs/classwizard/classwizard.py @@ -0,0 +1,254 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//! [0] //! [1] +def __init__(self, parent): + QWizard.__init__(self, parent): + self.addPage(IntroPage()) + self.addPage(ClassInfoPage()) + self.addPage(CodeStylePage()) + self.addPage(OutputFilesPage()) + self.addPage(ConclusionPage()) +//! [0] + + self.setPixmap(QWizard.BannerPixmap, QPixmap(":/images/banner.png")) + self.setPixmap(QWizard.BackgroundPixmap, QPixmap(":/images/background.png")) + + self.setWindowTitle(self.tr("Class Wizard")) +//! [2] + +//! [1] //! [2] + +//! [3] +def accept(self): +//! [3] //! [4] + className = self.field("className") + baseClass = self.field("baseClass") + macroName = self.field("macroName") + baseInclude = self.field("baseInclude") + + outputDir = self.field("outputDir") + header = self.field("header") + implementation = self.field("implementation") +//! [4] + +... + +//! [5] + QDialog.accept(self) +//! [5] //! [6] +} +//! [6] + +//! [7] +class IntroPage (QWizardPage): + + def __init__(self, parent): + QWizardPage.__init__(self, parent) + + self.setTitle(tr("Introduction")) + self.setPixmap(QWizard.WatermarkPixmap, QPixmap(":/images/watermark1.png")) + + label = QLabel(self.tr("This wizard will generate a skeleton C++ class " \ + "definition, including a few functions. You simply " \ + "need to specify the class name and set a few " \ + "options to produce a header file and an " \ + "implementation file for your new C++ class.")) + label.setWordWrap(True) + + layout = QVBoxLayout() + layout.addWidget(label) + self.setLayout(layout) +} +//! [7] + +//! [8] //! [9] +class ClassInfoPage(QWizardPage): + + def __init__(self, parent): + QWizardPage.__init__(self, parent) +//! [8] + self.setTitle(self.tr("Class Information")) + self.setSubTitle(self.tr("Specify basic information about the class for which you " \ + "want to generate skeleton source code files.")) + self.setPixmap(QWizard.LogoPixmap, QPixmap(":/images/logo1.png")) + +//! [10] + classNameLabel = QLabel(self.tr("&Class name:")) + classNameLineEdit = QLineEdit() + classNameLabel.setBuddy(classNameLineEdit) + + baseClassLabel = QLabel(self.tr("B&ase class:")) + baseClassLineEdit = QLineEdit() + baseClassLabel.setBuddy(baseClassLineEdit) + + qobjectMacroCheckBox = QCheckBox(self.tr("Generate Q_OBJECT ¯o")) + +//! [10] + groupBox = QGroupBox(self.tr("C&onstructor")) +//! [9] + + qobjectCtorRadioButton = QRadioButton(self.tr("&QObject-style constructor")) + qwidgetCtorRadioButton = QRadioButton(self.tr("Q&Widget-style constructor")) + defaultCtorRadioButton = QRadioButton(self.tr("&Default constructor")) + copyCtorCheckBox = QCheckBox(self.tr("&Generate copy constructor and operator=")) + + defaultCtorRadioButton.setChecked(True) + + defaultCtorRadioButton.toggled[bool].connect(copyCtorCheckBox.setEnabled) + +//! [11] //! [12] + registerField("className*", classNameLineEdit) + registerField("baseClass", baseClassLineEdit) + registerField("qobjectMacro", qobjectMacroCheckBox) +//! [11] + registerField("qobjectCtor", qobjectCtorRadioButton) + registerField("qwidgetCtor", qwidgetCtorRadioButton) + registerField("defaultCtor", defaultCtorRadioButton) + registerField("copyCtor", copyCtorCheckBox) + + groupBoxLayout = QVBoxLayout() +//! [12] + groupBoxLayout.addWidget(qobjectCtorRadioButton) + groupBoxLayout.addWidget(qwidgetCtorRadioButton) + groupBoxLayout.addWidget(defaultCtorRadioButton) + groupBoxLayout.addWidget(copyCtorCheckBox) + groupBox.setLayout(groupBoxLayout) + + layout = QGridLayout() + layout.addWidget(classNameLabel, 0, 0) + layout.addWidget(classNameLineEdit, 0, 1) + layout.addWidget(baseClassLabel, 1, 0) + layout.addWidget(baseClassLineEdit, 1, 1) + layout.addWidget(qobjectMacroCheckBox, 2, 0, 1, 2) + layout.addWidget(groupBox, 3, 0, 1, 2) + self.setLayout(layout) +//! [13] + +//! [13] + +//! [14] +class CodeStylePage(QWizardPage): + + def __init__(self, parent): + QWizardPage.__init__(self, parent) + self.setTitle(tr("Code Style Options")) + self.setSubTitle(tr("Choose the formatting of the generated code.")) + self.setPixmap(QWizard.LogoPixmap, QPixmap(":/images/logo2.png")) + + commentCheckBox = QCheckBox(self.tr("&Start generated files with a comment")) +//! [14] + commentCheckBox.setChecked(True) + + protectCheckBox = QCheckBox(self.tr("&Protect header file against multiple " \ + "inclusions")) + protectCheckBox.setChecked(True) + + macroNameLabel = QLabel(self.tr("&Macro name:")) + macroNameLineEdit = QLineEdit() + macroNameLabel.setBuddy(macroNameLineEdit) + + includeBaseCheckBox = QCheckBox(self.tr("&Include base class definition")) + baseIncludeLabel = QLabel(self.tr("Base class include:")) + baseIncludeLineEdit = QLineEdit() + baseIncludeLabel.setBuddy(baseIncludeLineEdit) + + protectCheckBox.toggled[bool].connect(macroNameLabel.setEnabled) + protectCheckBox.toggled[bool].connect(macroNameLineEdit.setEnabled) + includeBaseCheckBox.toggled[bool].connect(baseIncludeLabel.setEnabled) + includeBaseCheckBox.toggled[bool].connect(baseIncludeLineEdit.setEnabled) + + self.registerField("comment", commentCheckBox) + self.registerField("protect", protectCheckBox) + self.registerField("macroName", macroNameLineEdit) + self.registerField("includeBase", includeBaseCheckBox) + self.registerField("baseInclude", baseIncludeLineEdit) + + layout = QGridLayout() + layout.setColumnMinimumWidth(0, 20) + layout.addWidget(commentCheckBox, 0, 0, 1, 3) + layout.addWidget(protectCheckBox, 1, 0, 1, 3) + layout.addWidget(macroNameLabel, 2, 1) + layout.addWidget(macroNameLineEdit, 2, 2) + layout.addWidget(includeBaseCheckBox, 3, 0, 1, 3) + layout.addWidget(baseIncludeLabel, 4, 1) + layout.addWidget(baseIncludeLineEdit, 4, 2) +//! [15] + self.setLayout(layout) +} +//! [15] + +//! [16] + def initializePage(self): + className = self.field("className") + self.macroNameLineEdit.setText(className.upper() + "_H") + + baseClass = self.field("baseClass") + + self.includeBaseCheckBox.setChecked(len(baseClass)) + self.includeBaseCheckBox.setEnabled(len(baseClass)) + self.baseIncludeLabel.setEnabled(len(baseClass)) + self.baseIncludeLineEdit.setEnabled(len(baseClass)) + + if not baseClass: + self.baseIncludeLineEdit.clear() + elsif QRegExp("Q[A-Z].*").exactMatch(baseClass): + baseIncludeLineEdit.setText("<" + baseClass + ">") + else: + baseIncludeLineEdit.setText("\"" + baseClass.lower() + ".h\"") +//! [16] + +//! [17] + def initializePage(self): + className = field("className") + self.headerLineEdit.setText(className.lower() + ".h") + self.implementationLineEdit.setText(className.lower() + ".cpp") + self.outputDirLineEdit.setText(QDir.convertSeparators(QDir.tempPath())) +//! [17] diff --git a/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.cpp b/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.cpp deleted file mode 100644 index a8496f4c8..000000000 --- a/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.cpp +++ /dev/null @@ -1,119 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - - -from PySide2.QtGui import * - -//! [0] -def __init__(self, parent): - QDialog.__init__(self, parent) - label = QLabel(self.tr("Find &what:")) - lineEdit = QLineEdit() - label.setBuddy(lineEdit) - - caseCheckBox = QCheckBox(self.tr("Match &case")) - fromStartCheckBox = QCheckBox(self.tr("Search from &start")) - fromStartCheckBox.setChecked(True) - -//! [1] - findButton = QPushButton(self.tr("&Find")) - findButton.setDefault(True) - - moreButton = QPushButton(self.tr("&More")) - moreButton.setCheckable(True) -//! [0] - moreButton.setAutoDefault(False) - - buttonBox = QDialogButtonBox(Qt.Vertical) - buttonBox.addButton(findButton, QDialogButtonBox.ActionRole) - buttonBox.addButton(moreButton, QDialogButtonBox.ActionRole) -//! [1] - -//! [2] - extension = QWidget() - - wholeWordsCheckBox = QCheckBox(self.tr("&Whole words")) - backwardCheckBox = QCheckBox(self.tr("Search &backward")) - searchSelectionCheckBox = QCheckBox(self.tr("Search se&lection")) -//! [2] - -//! [3] - connect(moreButton, SIGNAL("toggled(bool)"), extension, SLOT("setVisible(bool)")) - - extensionLayout = QVBoxLayout() - extensionLayout.setMargin(0) - extensionLayout.addWidget(wholeWordsCheckBox) - extensionLayout.addWidget(backwardCheckBox) - extensionLayout.addWidget(searchSelectionCheckBox) - extension.setLayout(extensionLayout) -//! [3] - -//! [4] - topLeftLayout = QHBoxLayout() - topLeftLayout.addWidget(label) - topLeftLayout.addWidget(lineEdit) - - leftLayout = QVBoxLayout() - leftLayout.addLayout(topLeftLayout) - leftLayout.addWidget(caseCheckBox) - leftLayout.addWidget(fromStartCheckBox) - leftLayout.addSself.tretch(1) - - mainLayout = QGridLayout() - mainLayout.setSizeConsself.traint(QLayout.SetFixedSize) - mainLayout.addLayout(leftLayout, 0, 0) - mainLayout.addWidget(buttonBox, 0, 1) - mainLayout.addWidget(extension, 1, 0, 1, 2) - setLayout(mainLayout) - - setWindowTitle(self.tr("Extension")) -//! [4] //! [5] - extension.hide() -//! [5] diff --git a/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.py b/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.py new file mode 100644 index 000000000..1872e631b --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/dialogs/extension/finddialog.py @@ -0,0 +1,119 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + + +from PySide2.QtGui import * + +//! [0] +def __init__(self, parent): + QDialog.__init__(self, parent) + label = QLabel(self.tr("Find &what:")) + lineEdit = QLineEdit() + label.setBuddy(lineEdit) + + caseCheckBox = QCheckBox(self.tr("Match &case")) + fromStartCheckBox = QCheckBox(self.tr("Search from &start")) + fromStartCheckBox.setChecked(True) + +//! [1] + findButton = QPushButton(self.tr("&Find")) + findButton.setDefault(True) + + moreButton = QPushButton(self.tr("&More")) + moreButton.setCheckable(True) +//! [0] + moreButton.setAutoDefault(False) + + buttonBox = QDialogButtonBox(Qt.Vertical) + buttonBox.addButton(findButton, QDialogButtonBox.ActionRole) + buttonBox.addButton(moreButton, QDialogButtonBox.ActionRole) +//! [1] + +//! [2] + extension = QWidget() + + wholeWordsCheckBox = QCheckBox(self.tr("&Whole words")) + backwardCheckBox = QCheckBox(self.tr("Search &backward")) + searchSelectionCheckBox = QCheckBox(self.tr("Search se&lection")) +//! [2] + +//! [3] + moreButton.toggled[bool].connect(extension.setVisible) + + extensionLayout = QVBoxLayout() + extensionLayout.setMargin(0) + extensionLayout.addWidget(wholeWordsCheckBox) + extensionLayout.addWidget(backwardCheckBox) + extensionLayout.addWidget(searchSelectionCheckBox) + extension.setLayout(extensionLayout) +//! [3] + +//! [4] + topLeftLayout = QHBoxLayout() + topLeftLayout.addWidget(label) + topLeftLayout.addWidget(lineEdit) + + leftLayout = QVBoxLayout() + leftLayout.addLayout(topLeftLayout) + leftLayout.addWidget(caseCheckBox) + leftLayout.addWidget(fromStartCheckBox) + leftLayout.addSself.tretch(1) + + mainLayout = QGridLayout() + mainLayout.setSizeConsself.traint(QLayout.SetFixedSize) + mainLayout.addLayout(leftLayout, 0, 0) + mainLayout.addWidget(buttonBox, 0, 1) + mainLayout.addWidget(extension, 1, 0, 1, 2) + setLayout(mainLayout) + + setWindowTitle(self.tr("Extension")) +//! [4] //! [5] + extension.hide() +//! [5] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.cpp b/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.cpp deleted file mode 100644 index b0331aa79..000000000 --- a/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.cpp +++ /dev/null @@ -1,359 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -//! [0] -from PySide2.QtGui import * -//! [0] - -//! [1] -def __init__(self): - QMainWindow.__init__(self) -//! [1] //! [2] - textEdit = QPlainTextEdit() - setCentralWidget(textEdit) - - createActions() - createMenus() - createToolBars() - createStatusBar() - - readSettings() - - connect(textEdit.document(), SIGNAL("contentsChanged()"), - self, SLOT("documentWasModified()")) - - setCurrentFile("") - setUnifiedTitleAndToolBarOnMac(True) - -//! [2] - -//! [3] -def closeEvent(self, event): -//! [3] //! [4] - if maybeSave(): - writeSettings() - event.accept() - else: - event.ignore() -//! [4] - -//! [5] -def File(self): -//! [5] //! [6] - if maybeSave(): - textEdit.clear() - setCurrentFile("") -//! [6] - -//! [7] -def open(self): -//! [7] //! [8] - if maybeSave(): - fileName = QFileDialog.getOpenFileName(self) - if !fileName.isEmpty(): - loadFile(fileName) -//! [8] - -//! [9] -def save(self): -//! [9] //! [10] - if curFile.isEmpty(): - return saveAs() - else: - return saveFile(curFile) -//! [10] - -//! [11] -def saveAs(self): -//! [11] //! [12] - fileName = QFileDialog.getSaveFileName(self) - if fileName.isEmpty(): - return False - - return saveFile(fileName) -//! [12] - -//! [13] -def about(self): -//! [13] //! [14] - QMessageBox.about(self, tr("About Application"), - tr("The Application example demonstrates how to " - "write modern GUI applications using Qt, with a menu bar, " - "toolbars, and a status bar.")) - -//! [14] - -//! [15] -def documentWasModified(self): -//! [15] //! [16] - setWindowModified(textEdit.document().isModified()) -//! [16] - -//! [17] -def MainWindow.createActions(self): -//! [17] //! [18] - Act = QAction(QIcon(":/images/new.png"), tr("&New"), self) - Act.setShortcuts(QKeySequence.New) - Act.setStatusTip(tr("Create a new file")) - connect(Act, SIGNAL("triggered()"), self, SLOT("newFile()")) - -//! [19] - openAct = QAction(QIcon(":/images/open.png"), tr("&Open..."), self) - openAct.setShortcuts(QKeySequence.Open) - openAct.setStatusTip(tr("Open an existing file")) - connect(openAct, SIGNAL("triggered()"), self, SLOT("open()")) -//! [18] //! [19] - - saveAct = QAction(QIcon(":/images/save.png"), tr("&Save"), self) - saveAct.setShortcuts(QKeySequence.Save) - saveAct.setStatusTip(tr("Save the document to disk")) - connect(saveAct, SIGNAL("triggered()"), self, SLOT("save()")) - - saveAsAct = QAction(tr("Save &As..."), self) - saveAsAct.setShortcuts(QKeySequence.SaveAs) - saveAsAct.setStatusTip(tr("Save the document under a name")) - connect(saveAsAct, SIGNAL("triggered()"), self, SLOT("saveAs()")) - -//! [20] - exitAct = QAction(tr("E&xit"), self) - exitAct.setShortcut(tr("Ctrl+Q")) -//! [20] - exitAct.setStatusTip(tr("Exit the application")) - connect(exitAct, SIGNAL("triggered()"), self, SLOT("close()")) - -//! [21] - cutAct = QAction(QIcon(":/images/cut.png"), tr("Cu&t"), self) -//! [21] - cutAct.setShortcuts(QKeySequence.Cut) - cutAct.setStatusTip(tr("Cut the current selection's contents to the " - "clipboard")) - connect(cutAct, SIGNAL("triggered()"), textEdit, SLOT("cut()")) - - copyAct = QAction(QIcon(":/images/copy.png"), tr("&Copy"), self) - copyAct.setShortcuts(QKeySequence.Copy) - copyAct.setStatusTip(tr("Copy the current selection's contents to the " - "clipboard")) - connect(copyAct, SIGNAL("triggered()"), textEdit, SLOT("copy()")) - - pasteAct = QAction(QIcon(":/images/paste.png"), tr("&Paste"), self) - pasteAct.setShortcuts(QKeySequence.Paste) - pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " - "selection")) - connect(pasteAct, SIGNAL("triggered()"), textEdit, SLOT("paste()")) - - aboutAct = QAction(tr("&About"), self) - aboutAct.setStatusTip(tr("Show the application's About box")) - connect(aboutAct, SIGNAL("triggered()"), self, SLOT("about()")) - -//! [22] - aboutQtAct = QAction(tr("About &Qt"), self) - aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) - connect(aboutQtAct, SIGNAL("triggered()"), qApp, SLOT("aboutQt()")) -//! [22] - -//! [23] - cutAct.setEnabled(False) -//! [23] //! [24] - copyAct.setEnabled(False) - connect(textEdit, SIGNAL("copyAvailable(bool)"), - cutAct, SLOT("setEnabled(bool)")) - connect(textEdit, SIGNAL("copyAvailable(bool)"), - copyAct, SLOT("setEnabled(bool)")) -} -//! [24] - -//! [25] //! [26] -def createMenus(self): -//! [25] //! [27] - fileMenu = menuBar().addMenu(tr("&File")) - fileMenu.addAction(Act) -//! [28] - fileMenu.addAction(openAct) -//! [28] - fileMenu.addAction(saveAct) -//! [26] - fileMenu.addAction(saveAsAct) - fileMenu.addSeparator() - fileMenu.addAction(exitAct) - - editMenu = menuBar().addMenu(tr("&Edit")) - editMenu.addAction(cutAct) - editMenu.addAction(copyAct) - editMenu.addAction(pasteAct) - - menuBar().addSeparator() - - helpMenu = menuBar().addMenu(tr("&Help")) - helpMenu.addAction(aboutAct) - helpMenu.addAction(aboutQtAct) - -//! [27] - -//! [29] //! [30] -def createToolBars(self): - fileToolBar = addToolBar(tr("File")) - fileToolBar.addAction(Act) -//! [29] //! [31] - fileToolBar.addAction(openAct) -//! [31] - fileToolBar.addAction(saveAct) - - editToolBar = addToolBar(tr("Edit")) - editToolBar.addAction(cutAct) - editToolBar.addAction(copyAct) - editToolBar.addAction(pasteAct) -//! [30] - -//! [32] -def createStatusBar(self): -//! [32] //! [33] - statusBar().showMessage(tr("Ready")) - -//! [33] - -//! [34] //! [35] -def readSettings(self): -//! [34] //! [36] - settings("Trolltech", "Application Example") - pos = settings.value("pos", QPoint(200, 200)).toPoint() - size = settings.value("size", QSize(400, 400)).toSize() - resize(size) - move(pos) - -//! [35] //! [36] - -//! [37] //! [38] -def writeSettings(self): -//! [37] //! [39] - settings = QSettings("Trolltech", "Application Example") - settings.setValue("pos", pos()) - settings.setValue("size", size()) - -//! [38] //! [39] - -//! [40] -def maybeSave(self): -//! [40] //! [41] - if textEdit.document()->isModified(): - ret = QMessageBox.warning(self, tr("Application"), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) - if ret == QMessageBox.Save: - return save() - elif ret == QMessageBox.Cancel: - return False - return True -//! [41] - -//! [42] -def loadFile(self, fileName): -//! [42] //! [43] - file = QFile(fileName) - if !file.open(QFile.ReadOnly | QFile.Text): - QMessageBox.warning(self, tr("Application"), - tr("Cannot read file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())) - return - - in = QTextStream(file) - QApplication.setOverrideCursor(Qt::WaitCursor) - textEdit.setPlainText(in.readAll()) - QApplication.restoreOverrideCursor() - - setCurrentFile(fileName) - statusBar().showMessage(tr("File loaded"), 2000) - -//! [43] - -//! [44] -def saveFile(self, fileName): -//! [44] //! [45] - file = QFile(fileName) - if !file.open(QFile.WriteOnly | QFile::Text): - QMessageBox.warning(self, tr("Application"), - tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())) - return False - - out = QTextStream(file) - QApplication.setOverrideCursor(Qt.WaitCursor) - out << textEdit.toPlainText() - QApplication.restoreOverrideCursor() - - setCurrentFile(fileName) - statusBar().showMessage(tr("File saved"), 2000) - return True - -//! [45] - -//! [46] -def setCurrentFile(fileName): -//! [46] //! [47] - curFile = fileName - textEdit.document().setModified(False) - setWindowModified(False) - - if curFile.isEmpty(): - shownName = "untitled.txt" - else: - shownName = strippedName(curFile) - - setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Application"))) - -//! [47] - -//! [48] -def strippedName(self, fullFileName): -//! [48] //! [49] - return QFileInfo(fullFileName).fileName() -//! [49] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.h b/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.h new file mode 100644 index 000000000..bdb7bcf22 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.h @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +from PySide2.QtWidgets import (QAction, QApplication, QMainWindow, QMenu, + QPlainTextEdit, QSessionManager) + + +//! [0] +class MainWindow(QMainWindow): + def __init__(self, parent=None): + self.textEdit = QPlainTextEdit() + self.curFile = "" + # ... + + def loadFile(self, fileName): + pass + + def closeEvent(self, event): + pass + + def newFile(self): + pass + + def open(self): + pass + + def save(self): + pass + + def saveAs(self): + pass + + def about(self): + pass + + def documentWasModified(self): + pass + # Enable this only if QT_NO_SESSIONMANAGER is not defined + # def commitData(self): + # pass + + def createActions(self): + pass + + def createStatusBar(self): + pass + + def readSettings(self): + pass + + def writeSettings(self): + pass + + def maybeSave(self): + pass + + def saveFile(self, fileName): + pass + + def setCurrentFile(self, fileName): + pass + + def strippedName(self, fullFileName): + pass +//! [0] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.py b/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.py new file mode 100644 index 000000000..f976bb8e3 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/application/mainwindow.py @@ -0,0 +1,357 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [0] +from PySide2.QtCore import Qt, QFile, QFileInfo, QSettings, QTextStream +from PySide2.QtGui import QIcon +from PySide2.Widgets import (QAction, QApplication, QFileDialog, QMainWindow, + QPlainTextEdit, QFileDialog, QMessageBox, ) +//! [0] + +//! [1] +def __init__(self, parent=None): + QMainWindow.__init__(self) +//! [1] //! [2] + self.textEdit = QPlainTextEdit() + self.setCentralWidget(textEdit) + + self.createActions() + self.createMenus() + self.createToolBars() + self.createStatusBar() + + self.readSettings() + + self.textEdit.document().contentsChanged.connect(self.documentWasModified) + + self.setCurrentFile("") + self.setUnifiedTitleAndToolBarOnMac(True) + +//! [2] + +//! [3] +def closeEvent(self, event): +//! [3] //! [4] + if maybeSave(): + writeSettings() + event.accept() + else: + event.ignore() +//! [4] + +//! [5] +def File(self): +//! [5] //! [6] + if maybeSave(): + textEdit.clear() + setCurrentFile("") +//! [6] + +//! [7] +def open(self): +//! [7] //! [8] + if maybeSave(): + fileName = QFileDialog.getOpenFileName(self) + if not fileName.isEmpty(): + loadFile(fileName) +//! [8] + +//! [9] +def save(self): +//! [9] //! [10] + if curFile.isEmpty(): + return saveAs() + else: + return saveFile(curFile) +//! [10] + +//! [11] +def saveAs(self): +//! [11] //! [12] + fileName = QFileDialog.getSaveFileName(self) + if fileName.isEmpty(): + return False + + return saveFile(fileName) +//! [12] + +//! [13] +def about(self): +//! [13] //! [14] + QMessageBox.about(self, tr("About Application"), + tr("The Application example demonstrates how to " + "write modern GUI applications using Qt, with a menu bar, " + "toolbars, and a status bar.")) + +//! [14] + +//! [15] +def documentWasModified(self): +//! [15] //! [16] + setWindowModified(textEdit.document().isModified()) +//! [16] + +//! [17] +def MainWindow.createActions(self): +//! [17] //! [18] + Act = QAction(QIcon(":/images/new.png"), tr("&New"), self) + Act.setShortcuts(QKeySequence.New) + Act.setStatusTip(tr("Create a new file")) + Act.triggered.connect(newFile) + +//! [19] + openAct = QAction(QIcon(":/images/open.png"), tr("&Open..."), self) + openAct.setShortcuts(QKeySequence.Open) + openAct.setStatusTip(tr("Open an existing file")) + openAct.triggered.connect(open) +//! [18] //! [19] + + saveAct = QAction(QIcon(":/images/save.png"), tr("&Save"), self) + saveAct.setShortcuts(QKeySequence.Save) + saveAct.setStatusTip(tr("Save the document to disk")) + saveAct.triggered.connect(save) + + saveAsAct = QAction(tr("Save &As..."), self) + saveAsAct.setShortcuts(QKeySequence.SaveAs) + saveAsAct.setStatusTip(tr("Save the document under a name")) + saveAsAct.triggered.connect(saveAs) + +//! [20] + exitAct = QAction(tr("E&xit"), self) + exitAct.setShortcut(tr("Ctrl+Q")) +//! [20] + exitAct.setStatusTip(tr("Exit the application")) + exitAct.triggered.connect(close) + +//! [21] + cutAct = QAction(QIcon(":/images/cut.png"), tr("Cu&t"), self) +//! [21] + cutAct.setShortcuts(QKeySequence.Cut) + cutAct.setStatusTip(tr("Cut the current selection's contents to the " + "clipboard")) + cutAct.triggered.connect(cut) + + copyAct = QAction(QIcon(":/images/copy.png"), tr("&Copy"), self) + copyAct.setShortcuts(QKeySequence.Copy) + copyAct.setStatusTip(tr("Copy the current selection's contents to the " + "clipboard")) + copyAct.triggered.connect(copy) + + pasteAct = QAction(QIcon(":/images/paste.png"), tr("&Paste"), self) + pasteAct.setShortcuts(QKeySequence.Paste) + pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " + "selection")) + pasteAct.triggered.connect(textEdit.paste) + + aboutAct = QAction(tr("&About"), self) + aboutAct.setStatusTip(tr("Show the application's About box")) + aboutAct.triggered.connect(about) + +//! [22] + aboutQtAct = QAction(tr("About &Qt"), self) + aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) + aboutQtAct.triggered.connect(qApp.aboutQt) +//! [22] + +//! [23] + cutAct.setEnabled(False) +//! [23] //! [24] + copyAct.setEnabled(False) + textEdit.copyAvailable[bool].connect(cutAct.setEnabled) + textEdit.copyAvailable[bool].connect(copyAct.setEnabled) +} +//! [24] + +//! [25] //! [26] +def createMenus(self): +//! [25] //! [27] + fileMenu = menuBar().addMenu(tr("&File")) + fileMenu.addAction(Act) +//! [28] + fileMenu.addAction(openAct) +//! [28] + fileMenu.addAction(saveAct) +//! [26] + fileMenu.addAction(saveAsAct) + fileMenu.addSeparator() + fileMenu.addAction(exitAct) + + editMenu = menuBar().addMenu(tr("&Edit")) + editMenu.addAction(cutAct) + editMenu.addAction(copyAct) + editMenu.addAction(pasteAct) + + menuBar().addSeparator() + + helpMenu = menuBar().addMenu(tr("&Help")) + helpMenu.addAction(aboutAct) + helpMenu.addAction(aboutQtAct) + +//! [27] + +//! [29] //! [30] +def createToolBars(self): + fileToolBar = addToolBar(tr("File")) + fileToolBar.addAction(Act) +//! [29] //! [31] + fileToolBar.addAction(openAct) +//! [31] + fileToolBar.addAction(saveAct) + + editToolBar = addToolBar(tr("Edit")) + editToolBar.addAction(cutAct) + editToolBar.addAction(copyAct) + editToolBar.addAction(pasteAct) +//! [30] + +//! [32] +def createStatusBar(self): +//! [32] //! [33] + statusBar().showMessage(tr("Ready")) + +//! [33] + +//! [34] //! [35] +def readSettings(self): +//! [34] //! [36] + settings("Trolltech", "Application Example") + pos = settings.value("pos", QPoint(200, 200)).toPoint() + size = settings.value("size", QSize(400, 400)).toSize() + resize(size) + move(pos) + +//! [35] //! [36] + +//! [37] //! [38] +def writeSettings(self): +//! [37] //! [39] + settings = QSettings("Trolltech", "Application Example") + settings.setValue("pos", pos()) + settings.setValue("size", size()) + +//! [38] //! [39] + +//! [40] +def maybeSave(self): +//! [40] //! [41] + if textEdit.document()->isModified(): + ret = QMessageBox.warning(self, tr("Application"), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) + if ret == QMessageBox.Save: + return save() + elif ret == QMessageBox.Cancel: + return False + return True +//! [41] + +//! [42] +def loadFile(self, fileName): +//! [42] //! [43] + file = QFile(fileName) + if !file.open(QFile.ReadOnly | QFile.Text): + QMessageBox.warning(self, tr("Application"), tr("Cannot read file " + "{}:\n{}.".format(fileName, file.errorString()))) + return + + in = QTextStream(file) + QApplication.setOverrideCursor(Qt::WaitCursor) + textEdit.setPlainText(in.readAll()) + QApplication.restoreOverrideCursor() + + self.setCurrentFile(fileName) + self.statusBar().showMessage(tr("File loaded"), 2000) + +//! [43] + +//! [44] +def saveFile(self, fileName): +//! [44] //! [45] + file = QFile(fileName) + if !file.open(QFile.WriteOnly | QFile::Text): + QMessageBox.warning(self, tr("Application"), + tr("Cannot write file %1:\n%2.") + .arg(fileName) + .arg(file.errorString())) + return False + + out = QTextStream(file) + QApplication.setOverrideCursor(Qt.WaitCursor) + out << textEdit.toPlainText() + QApplication.restoreOverrideCursor() + + setCurrentFile(fileName) + statusBar().showMessage(tr("File saved"), 2000) + return True + +//! [45] + +//! [46] +def setCurrentFile(fileName): +//! [46] //! [47] + curFile = fileName + textEdit.document().setModified(False) + setWindowModified(False) + + if curFile.isEmpty(): + shownName = "untitled.txt" + else: + shownName = strippedName(curFile) + + setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Application"))) + +//! [47] + +//! [48] +def strippedName(self, fullFileName): +//! [48] //! [49] + return QFileInfo(fullFileName).fileName() +//! [49] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.cpp b/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.cpp deleted file mode 100644 index e1a9f556e..000000000 --- a/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.cpp +++ /dev/null @@ -1,255 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -//! [0] -from PySide2.QtGui import * -//! [0] - -//! [1] -def __init__(self): - textEdit = QTextEdit() - setCentralWidget(textEdit) - - createActions() - createMenus() - createToolBars() - createStatusBar() - createDockWindows() - - setWindowTitle(tr("Dock Widgets")) - - Letter() - setUnifiedTitleAndToolBarOnMac(True) -//! [1] - -//! [2] -def Letter(self) - textEdit.clear() - - cursor = QTextCursor(textEdit.textCursor()) - cursor.movePosition(QTextCursor.Start) - topFrame = cursor.currentFrame() - topFrameFormat = topFrame.frameFormat() - topFrameFormat.setPadding(16) - topFrame.setFrameFormat(topFrameFormat) - - textFormat = QTextCharFormat() - boldFormat = QTextCharFormat() - boldFormat.setFontWeight(QFont.Bold) - italicFormat = QTextCharFormat() - italicFormat.setFontItalic(True) - - tableFormat = QTextTableFormat() - tableFormat.setBorder(1) - tableFormat.setCellPadding(16) - tableFormat.setAlignment(Qt.AlignRight) - cursor.insertTable(1, 1, tableFormat) - cursor.insertText("The Firm", boldFormat) - cursor.insertBlock() - cursor.insertText("321 City Street", textFormat) - cursor.insertBlock() - cursor.insertText("Industry Park") - cursor.insertBlock() - cursor.insertText("Some Country") - cursor.setPosition(topFrame.lastPosition()) - cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) - cursor.insertBlock() - cursor.insertBlock() - cursor.insertText("Dear ", textFormat) - cursor.insertText("NAME", italicFormat) - cursor.insertText(",", textFormat) - for i in range(3): - cursor.insertBlock() - cursor.insertText(tr("Yours sincerely,"), textFormat) - for i in range(3): - cursor.insertBlock() - cursor.insertText("The Boss", textFormat) - cursor.insertBlock() - cursor.insertText("ADDRESS", italicFormat) -//! [2] - -//! [3] -def print(self) - document = textEdit.document() - printer = QPrinter() - - dlg = QPrintDialog(&printer, self) - if dlg.exec() != QDialog.Accepted: - return - - document.print(printer) - statusBar().showMessage(tr("Ready"), 2000) -//! [3] - -//! [4] -def save(self): - fileName = QFileDialog.getSaveFileName(self, - tr("Choose a file name"), ".", - tr("HTML (*.html *.htm)")) - if fileName.isEmpty(): - return - file = QFile(fileName) - if !file.open(QFile.WriteOnly | QFile::Text): - QMessageBox.warning(self, tr("Dock Widgets"), - tr("Cannot write file %1:\n%2.") - .arg(fileName) - .arg(file.errorString())) - return - - - out = QTextStream(file) - QApplication.setOverrideCursor(Qt::WaitCursor) - out << textEdit.toHtml() - QApplication.restoreOverrideCursor() - - statusBar().showMessage(tr("Saved '%1'").arg(fileName), 2000) - -//! [4] - -//! [5] -def undo(self): - document = textEdit.document() - document.undo() - -//! [5] - -//! [6] -def insertCustomer(self, customer): - if customer.isEmpty(): - return - - customerList = customer.split(", ") - document = textEdit.document() - cursor = document.find("NAME") - if not cursor.isNull(): - cursor.beginEditBlock() - cursor.insertText(customerList.at(0)) - oldcursor = cursor - cursor = document.find("ADDRESS") - if not cursor.isNull(): - for i in range(customerList.size()): - cursor.insertBlock() - cursor.insertText(customerList.at(i)) - - cursor.endEditBlock() - else: - oldcursor.endEditBlock() -//! [6] - -//! [7] -def addParagraph(self, paragraph): - if (paragraph.isEmpty()) - return - - document = textEdit.document() - cursor = document.find(tr("Yours sincerely,")) - if cursor.isNull(): - return - cursor.beginEditBlock() - cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor, 2) - cursor.insertBlock() - cursor.insertText(paragraph) - cursor.insertBlock() - cursor.endEditBlock() - -//! [7] - - -//! [8] -def createStatusBar(self): - statusBar().showMessage(tr("Ready")) - -//! [8] - -//! [9] -def createDockWindows(self): - dock = QDockWidget(tr("Customers"), self) - dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) - customerList = QListWidget(dock) - customerList.addItems(QStringList() - << "John Doe, Harmony Enterprises, 12 Lakeside, Ambleton" - << "Jane Doe, Memorabilia, 23 Watersedge, Beaton" - << "Tammy Shea, Tiblanka, 38 Sea Views, Carlton" - << "Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal" - << "Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston" - << "Sally Hobart, Tiroli Tea, 67 Long River, Fedula") - dock.setWidget(customerList) - addDockWidget(Qt.RightDockWidgetArea, dock) - viewMenu.addAction(dock.toggleViewAction()) - - dock = QDockWidget(tr("Paragraphs"), self) - paragraphsList = QListWidget(dock) - paragraphsList.addItems(QStringList() - << "Thank you for your payment which we have received today." - << "Your order has been dispatched and should be with you " - "within 28 days." - << "We have dispatched those items that were in stock. The " - "rest of your order will be dispatched once all the " - "remaining items have arrived at our warehouse. No " - "additional shipping charges will be made." - << "You made a small overpayment (less than $5) which we " - "will keep on account for you, or return at your request." - << "You made a small underpayment (less than $1), but we have " - "sent your order anyway. We'll add self underpayment to " - "your next bill." - << "Unfortunately you did not send enough money. Please remit " - "an additional $. Your order will be dispatched as soon as " - "the complete amount has been received." - << "You made an overpayment (more than $5). Do you wish to " - "buy more items, or should we return the excess to you?") - dock.setWidget(paragraphsList) - addDockWidget(Qt.RightDockWidgetArea, dock) - viewMenu.addAction(dock.toggleViewAction()) - - connect(customerList, SIGNAL("currentTextChanged(const QString &)"), - self, SLOT("insertCustomer(const QString &)")) - connect(paragraphsList, SIGNAL("currentTextChanged(const QString &)"), - self, SLOT("addParagraph(const QString &)")) -//! [9] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.py b/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.py new file mode 100644 index 000000000..55d551c24 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/dockwidgets/mainwindow.py @@ -0,0 +1,253 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +//! [0] +from PySide2.QtGui import * +//! [0] + +//! [1] +def __init__(self): + textEdit = QTextEdit() + setCentralWidget(textEdit) + + createActions() + createMenus() + createToolBars() + createStatusBar() + createDockWindows() + + setWindowTitle(tr("Dock Widgets")) + + Letter() + setUnifiedTitleAndToolBarOnMac(True) +//! [1] + +//! [2] +def Letter(self) + textEdit.clear() + + cursor = QTextCursor(textEdit.textCursor()) + cursor.movePosition(QTextCursor.Start) + topFrame = cursor.currentFrame() + topFrameFormat = topFrame.frameFormat() + topFrameFormat.setPadding(16) + topFrame.setFrameFormat(topFrameFormat) + + textFormat = QTextCharFormat() + boldFormat = QTextCharFormat() + boldFormat.setFontWeight(QFont.Bold) + italicFormat = QTextCharFormat() + italicFormat.setFontItalic(True) + + tableFormat = QTextTableFormat() + tableFormat.setBorder(1) + tableFormat.setCellPadding(16) + tableFormat.setAlignment(Qt.AlignRight) + cursor.insertTable(1, 1, tableFormat) + cursor.insertText("The Firm", boldFormat) + cursor.insertBlock() + cursor.insertText("321 City Street", textFormat) + cursor.insertBlock() + cursor.insertText("Industry Park") + cursor.insertBlock() + cursor.insertText("Some Country") + cursor.setPosition(topFrame.lastPosition()) + cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"), textFormat) + cursor.insertBlock() + cursor.insertBlock() + cursor.insertText("Dear ", textFormat) + cursor.insertText("NAME", italicFormat) + cursor.insertText(",", textFormat) + for i in range(3): + cursor.insertBlock() + cursor.insertText(tr("Yours sincerely,"), textFormat) + for i in range(3): + cursor.insertBlock() + cursor.insertText("The Boss", textFormat) + cursor.insertBlock() + cursor.insertText("ADDRESS", italicFormat) +//! [2] + +//! [3] +def print(self) + document = textEdit.document() + printer = QPrinter() + + dlg = QPrintDialog(&printer, self) + if dlg.exec() != QDialog.Accepted: + return + + document.print(printer) + statusBar().showMessage(tr("Ready"), 2000) +//! [3] + +//! [4] +def save(self): + fileName = QFileDialog.getSaveFileName(self, + tr("Choose a file name"), ".", + tr("HTML (*.html *.htm)")) + if fileName.isEmpty(): + return + file = QFile(fileName) + if !file.open(QFile.WriteOnly | QFile::Text): + QMessageBox.warning(self, tr("Dock Widgets"), + tr("Cannot write file %1:\n%2.") + .arg(fileName) + .arg(file.errorString())) + return + + + out = QTextStream(file) + QApplication.setOverrideCursor(Qt::WaitCursor) + out << textEdit.toHtml() + QApplication.restoreOverrideCursor() + + statusBar().showMessage(tr("Saved '%1'").arg(fileName), 2000) + +//! [4] + +//! [5] +def undo(self): + document = textEdit.document() + document.undo() + +//! [5] + +//! [6] +def insertCustomer(self, customer): + if customer.isEmpty(): + return + + customerList = customer.split(", ") + document = textEdit.document() + cursor = document.find("NAME") + if not cursor.isNull(): + cursor.beginEditBlock() + cursor.insertText(customerList.at(0)) + oldcursor = cursor + cursor = document.find("ADDRESS") + if not cursor.isNull(): + for i in range(customerList.size()): + cursor.insertBlock() + cursor.insertText(customerList.at(i)) + + cursor.endEditBlock() + else: + oldcursor.endEditBlock() +//! [6] + +//! [7] +def addParagraph(self, paragraph): + if (paragraph.isEmpty()) + return + + document = textEdit.document() + cursor = document.find(tr("Yours sincerely,")) + if cursor.isNull(): + return + cursor.beginEditBlock() + cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor, 2) + cursor.insertBlock() + cursor.insertText(paragraph) + cursor.insertBlock() + cursor.endEditBlock() + +//! [7] + + +//! [8] +def createStatusBar(self): + statusBar().showMessage(tr("Ready")) + +//! [8] + +//! [9] +def createDockWindows(self): + dock = QDockWidget(tr("Customers"), self) + dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) + customerList = QListWidget(dock) + customerList.addItems(QStringList() + << "John Doe, Harmony Enterprises, 12 Lakeside, Ambleton" + << "Jane Doe, Memorabilia, 23 Watersedge, Beaton" + << "Tammy Shea, Tiblanka, 38 Sea Views, Carlton" + << "Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal" + << "Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston" + << "Sally Hobart, Tiroli Tea, 67 Long River, Fedula") + dock.setWidget(customerList) + addDockWidget(Qt.RightDockWidgetArea, dock) + viewMenu.addAction(dock.toggleViewAction()) + + dock = QDockWidget(tr("Paragraphs"), self) + paragraphsList = QListWidget(dock) + paragraphsList.addItems(QStringList() + << "Thank you for your payment which we have received today." + << "Your order has been dispatched and should be with you " + "within 28 days." + << "We have dispatched those items that were in stock. The " + "rest of your order will be dispatched once all the " + "remaining items have arrived at our warehouse. No " + "additional shipping charges will be made." + << "You made a small overpayment (less than $5) which we " + "will keep on account for you, or return at your request." + << "You made a small underpayment (less than $1), but we have " + "sent your order anyway. We'll add self underpayment to " + "your next bill." + << "Unfortunately you did not send enough money. Please remit " + "an additional $. Your order will be dispatched as soon as " + "the complete amount has been received." + << "You made an overpayment (more than $5). Do you wish to " + "buy more items, or should we return the excess to you?") + dock.setWidget(paragraphsList) + addDockWidget(Qt.RightDockWidgetArea, dock) + viewMenu.addAction(dock.toggleViewAction()) + + customerList.currentTextChanged[str].connect(self.insertCostumer) + paragraphsList.currentTextChanged[str].connect(self.addParagraph) +//! [9] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.cpp b/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.cpp deleted file mode 100644 index 6ed5f5466..000000000 --- a/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.cpp +++ /dev/null @@ -1,367 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -from PySide2.QtGui import * - -//! [0] -def __init__(self): - Q__init__(self) - - widget = QWidget() - setCentralWidget(widget) -//! [0] - -//! [1] - topFiller = QWidget() - topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - - infoLabel = QLabel(tr("Choose a menu option, or right-click to " - "invoke a context menu")) - infoLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) - infoLabel.setAlignment(Qt.AlignCenter) - - bottomFiller = QWidget() - bottomFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - - layout = QVBoxLayout() - layout.setMargin(5) - layout.addWidget(topFiller) - layout.addWidget(infoLabel) - layout.addWidget(bottomFiller) - widget.setLayout(layout) -//! [1] - -//! [2] - createActions() - createMenus() - - message = tr("A context menu is available by right-clicking") - statusBar().showMessage(message) - - setWindowTitle(tr("Menus")) - setMinimumSize(160, 160) - resize(480, 320) - -//! [2] - -//! [3] -def contextMenuEvent(self, event): - menu = QMenu(self) - menu.addAction(cutAct) - menu.addAction(copyAct) - menu.addAction(pasteAct) - menu.exec_(event.globalPos()") - -//! [3] - -def File(self): - infoLabel.setText(tr("Invoked File|New")) - - -def open(self): - infoLabel.setText(tr("Invoked File|Open")) - - -def save(self): - infoLabel.setText(tr("Invoked File|Save")) - -def print_(self): - infoLabel.setText(tr("Invoked File|Print")) - -def undo(self): - infoLabel.setText(tr("Invoked Edit|Undo")) - -def redo(self): - infoLabel.setText(tr("Invoked Edit|Redo")) - -def cut(self): - - infoLabel.setText(tr("Invoked Edit|Cut")) - - -def copy(self): - - infoLabel.setText(tr("Invoked Edit|Copy")) - - -def paste(self): - - infoLabel.setText(tr("Invoked Edit|Paste")) - - -def bold(self): - - infoLabel.setText(tr("Invoked Edit|Format|Bold")) - - -def italic(self): - - infoLabel.setText(tr("Invoked Edit|Format|Italic")) - - -def leftAlign(self): - - infoLabel.setText(tr("Invoked Edit|Format|Left Align")) - - -def rightAlign(self): - - infoLabel.setText(tr("Invoked Edit|Format|Right Align")) - - -def justify(self): - - infoLabel.setText(tr("Invoked Edit|Format|Justify")) - - -def center(self): - - infoLabel.setText(tr("Invoked Edit|Format|Center")) - - -def setLineSpacing(self): - - infoLabel.setText(tr("Invoked Edit|Format|Set Line Spacing")) - - -def setParagraphSpacing(self): - - infoLabel.setText(tr("Invoked Edit|Format|Set Paragraph Spacing")) - - -def about(self): - - infoLabel.setText(tr("Invoked Help|About")) - QMessageBox.about(self, tr("About Menu"), - tr("The Menu example shows how to create " - "menu-bar menus and context menus.")) - - -def aboutQt(self): - - infoLabel.setText(tr("Invoked Help|About Qt")) - - -//! [4] -def createActions(self): - -//! [5] - Act = new QAction(tr("&New"), self) - Act.setShortcuts(QKeySequence.New) - Act.setStatusTip(tr("Create a new file")) - connect(Act, SIGNAL("triggered()"), self, SLOT("newFile()")) -//! [4] - - openAct = QAction(tr("&Open..."), self) - openAct.setShortcuts(QKeySequence.Open) - openAct.setStatusTip(tr("Open an existing file")) - connect(openAct, SIGNAL("triggered()"), self, SLOT("open()")) -//! [5] - - saveAct = QAction(tr("&Save"), self) - saveAct.setShortcuts(QKeySequence.Save) - saveAct.setStatusTip(tr("Save the document to disk")) - connect(saveAct, SIGNAL("triggered()"), self, SLOT("save()")) - - printAct = QAction(tr("&Print..."), self) - printAct.setShortcuts(QKeySequence.Print) - printAct.setStatusTip(tr("Print the document")) - connect(printAct, SIGNAL("triggered()"), self, SLOT("print_()")) - - exitAct = QAction(tr("E&xit"), self) - exitAct.setShortcut(tr("Ctrl+Q")) - exitAct.setStatusTip(tr("Exit the application")) - connect(exitAct, SIGNAL("triggered()"), self, SLOT("close()")) - - undoAct = QAction(tr("&Undo"), self) - undoAct.setShortcuts(QKeySequence.Undo) - undoAct.setStatusTip(tr("Undo the last operation")) - connect(undoAct, SIGNAL("triggered()"), self, SLOT("undo()")) - - redoAct = QAction(tr("&Redo"), self) - redoAct.setShortcuts(QKeySequence.Redo) - redoAct.setStatusTip(tr("Redo the last operation")) - connect(redoAct, SIGNAL("triggered()"), self, SLOT("redo()")) - - cutAct = QAction(tr("Cu&t"), self) - cutAct.setShortcuts(QKeySequence.Cut) - cutAct.setStatusTip(tr("Cut the current selection's contents to the " - "clipboard")) - connect(cutAct, SIGNAL("triggered()"), self, SLOT("cut()")) - - copyAct = QAction(tr("&Copy"), self) - copyAct.setShortcut(tr("Ctrl+C")) - copyAct.setStatusTip(tr("Copy the current selection's contents to the " - "clipboard")) - connect(copyAct, SIGNAL("triggered()"), self, SLOT("copy()")) - - pasteAct = QAction(tr("&Paste"), self) - pasteAct.setShortcuts(QKeySequence.Paste) - pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " - "selection")) - connect(pasteAct, SIGNAL("triggered()"), self, SLOT("paste()")) - - boldAct = QAction(tr("&Bold"), self) - boldAct.setCheckable(True) - boldAct.setShortcut(tr("Ctrl+B")) - boldAct.setStatusTip(tr("Make the text bold")) - connect(boldAct, SIGNAL("triggered()"), self, SLOT("bold()")) - - QFont boldFont = boldAct.font() - boldFont.setBold(True) - boldAct.setFont(boldFont) - - italicAct = QAction(tr("&Italic"), self) - italicAct.setCheckable(True) - italicAct.setShortcut(tr("Ctrl+I")) - italicAct.setStatusTip(tr("Make the text italic")) - connect(italicAct, SIGNAL("triggered()"), self, SLOT("italic()")) - - QFont italicFont = italicAct.font() - italicFont.setItalic(True) - italicAct.setFont(italicFont) - - setLineSpacingAct = QAction(tr("Set &Line Spacing..."), self) - setLineSpacingAct.setStatusTip(tr("Change the gap between the lines of a " - "paragraph")) - connect(setLineSpacingAct, SIGNAL("triggered()"), self, SLOT("setLineSpacing()")) - - setParagraphSpacingAct = QAction(tr("Set &Paragraph Spacing..."), self) - setLineSpacingAct.setStatusTip(tr("Change the gap between paragraphs")) - connect(setParagraphSpacingAct, SIGNAL("triggered()"), - self, SLOT("setParagraphSpacing()")) - - aboutAct = QAction(tr("&About"), self) - aboutAct.setStatusTip(tr("Show the application's About box")) - connect(aboutAct, SIGNAL("triggered()"), self, SLOT("about()")) - - aboutQtAct = QAction(tr("About &Qt"), self) - aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) - connect(aboutQtAct, SIGNAL("triggered()"), qApp, SLOT("aboutQt()")) - connect(aboutQtAct, SIGNAL("triggered()"), self, SLOT("aboutQt()")) - - leftAlignAct = QAction(tr("&Left Align"), self) - leftAlignAct.setCheckable(True) - leftAlignAct.setShortcut(tr("Ctrl+L")) - leftAlignAct.setStatusTip(tr("Left align the selected text")) - connect(leftAlignAct, SIGNAL("triggered()"), self, SLOT("leftAlign()")) - - rightAlignAct = QAction(tr("&Right Align"), self) - rightAlignAct.setCheckable(True) - rightAlignAct.setShortcut(tr("Ctrl+R")) - rightAlignAct.setStatusTip(tr("Right align the selected text")) - connect(rightAlignAct, SIGNAL("triggered()"), self, SLOT("rightAlign()")) - - justifyAct = QAction(tr("&Justify"), self) - justifyAct.setCheckable(True) - justifyAct.setShortcut(tr("Ctrl+J")) - justifyAct.setStatusTip(tr("Justify the selected text")) - connect(justifyAct, SIGNAL("triggered()"), self, SLOT("justify()")) - - centerAct = QAction(tr("&Center"), self) - centerAct.setCheckable(True) - centerAct.setShortcut(tr("Ctrl+E")) - centerAct.setStatusTip(tr("Center the selected text")) - connect(centerAct, SIGNAL("triggered()"), self, SLOT("center()")) - -//! [6] //! [7] - alignmentGroup = QActionGroup(self) - alignmentGroup.addAction(leftAlignAct) - alignmentGroup.addAction(rightAlignAct) - alignmentGroup.addAction(justifyAct) - alignmentGroup.addAction(centerAct) - leftAlignAct.setChecked(True) -//! [6] - -//! [7] - -//! [8] -def createMenus(self): - -//! [9] //! [10] - fileMenu = menuBar().addMenu(tr("&File")) - fileMenu.addAction(Act) -//! [9] - fileMenu.addAction(openAct) -//! [10] - fileMenu.addAction(saveAct) - fileMenu.addAction(printAct) -//! [11] - fileMenu.addSeparator() -//! [11] - fileMenu.addAction(exitAct) - - editMenu = menuBar().addMenu(tr("&Edit")) - editMenu.addAction(undoAct) - editMenu.addAction(redoAct) - editMenu.addSeparator() - editMenu.addAction(cutAct) - editMenu.addAction(copyAct) - editMenu.addAction(pasteAct) - editMenu.addSeparator() - - helpMenu = menuBar().addMenu(tr("&Help")) - helpMenu.addAction(aboutAct) - helpMenu.addAction(aboutQtAct) -//! [8] - -//! [12] - formatMenu = editMenu.addMenu(tr("&Format")) - formatMenu.addAction(boldAct) - formatMenu.addAction(italicAct) - formatMenu.addSeparator()->setText(tr("Alignment")) - formatMenu.addAction(leftAlignAct) - formatMenu.addAction(rightAlignAct) - formatMenu.addAction(justifyAct) - formatMenu.addAction(centerAct) - formatMenu.addSeparator() - formatMenu.addAction(setLineSpacingAct) - formatMenu.addAction(setParagraphSpacingAct) -//! [12] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.py b/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.py new file mode 100644 index 000000000..b0bbed810 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/mainwindow.py @@ -0,0 +1,366 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtGui import * + +//! [0] +def __init__(self): + Q__init__(self) + + widget = QWidget() + setCentralWidget(widget) +//! [0] + +//! [1] + topFiller = QWidget() + topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + + infoLabel = QLabel(tr("Choose a menu option, or right-click to " + "invoke a context menu")) + infoLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) + infoLabel.setAlignment(Qt.AlignCenter) + + bottomFiller = QWidget() + bottomFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + + layout = QVBoxLayout() + layout.setMargin(5) + layout.addWidget(topFiller) + layout.addWidget(infoLabel) + layout.addWidget(bottomFiller) + widget.setLayout(layout) +//! [1] + +//! [2] + createActions() + createMenus() + + message = tr("A context menu is available by right-clicking") + statusBar().showMessage(message) + + setWindowTitle(tr("Menus")) + setMinimumSize(160, 160) + resize(480, 320) + +//! [2] + +//! [3] +def contextMenuEvent(self, event): + menu = QMenu(self) + menu.addAction(cutAct) + menu.addAction(copyAct) + menu.addAction(pasteAct) + menu.exec_(event.globalPos()") + +//! [3] + +def File(self): + infoLabel.setText(tr("Invoked File|New")) + + +def open(self): + infoLabel.setText(tr("Invoked File|Open")) + + +def save(self): + infoLabel.setText(tr("Invoked File|Save")) + +def print_(self): + infoLabel.setText(tr("Invoked File|Print")) + +def undo(self): + infoLabel.setText(tr("Invoked Edit|Undo")) + +def redo(self): + infoLabel.setText(tr("Invoked Edit|Redo")) + +def cut(self): + + infoLabel.setText(tr("Invoked Edit|Cut")) + + +def copy(self): + + infoLabel.setText(tr("Invoked Edit|Copy")) + + +def paste(self): + + infoLabel.setText(tr("Invoked Edit|Paste")) + + +def bold(self): + + infoLabel.setText(tr("Invoked Edit|Format|Bold")) + + +def italic(self): + + infoLabel.setText(tr("Invoked Edit|Format|Italic")) + + +def leftAlign(self): + + infoLabel.setText(tr("Invoked Edit|Format|Left Align")) + + +def rightAlign(self): + + infoLabel.setText(tr("Invoked Edit|Format|Right Align")) + + +def justify(self): + + infoLabel.setText(tr("Invoked Edit|Format|Justify")) + + +def center(self): + + infoLabel.setText(tr("Invoked Edit|Format|Center")) + + +def setLineSpacing(self): + + infoLabel.setText(tr("Invoked Edit|Format|Set Line Spacing")) + + +def setParagraphSpacing(self): + + infoLabel.setText(tr("Invoked Edit|Format|Set Paragraph Spacing")) + + +def about(self): + + infoLabel.setText(tr("Invoked Help|About")) + QMessageBox.about(self, tr("About Menu"), + tr("The Menu example shows how to create " + "menu-bar menus and context menus.")) + + +def aboutQt(self): + + infoLabel.setText(tr("Invoked Help|About Qt")) + + +//! [4] +def createActions(self): + +//! [5] + Act = new QAction(tr("&New"), self) + Act.setShortcuts(QKeySequence.New) + Act.setStatusTip(tr("Create a new file")) + Act.triggered.connect(newFile) +//! [4] + + openAct = QAction(tr("&Open..."), self) + openAct.setShortcuts(QKeySequence.Open) + openAct.setStatusTip(tr("Open an existing file")) + openAct.triggered.connect(open) +//! [5] + + saveAct = QAction(tr("&Save"), self) + saveAct.setShortcuts(QKeySequence.Save) + saveAct.setStatusTip(tr("Save the document to disk")) + saveAct.triggered.connect(save) + + printAct = QAction(tr("&Print..."), self) + printAct.setShortcuts(QKeySequence.Print) + printAct.setStatusTip(tr("Print the document")) + printAct.triggered.connect(print_) + + exitAct = QAction(tr("E&xit"), self) + exitAct.setShortcut(tr("Ctrl+Q")) + exitAct.setStatusTip(tr("Exit the application")) + exitAct.triggered.connect(close) + + undoAct = QAction(tr("&Undo"), self) + undoAct.setShortcuts(QKeySequence.Undo) + undoAct.setStatusTip(tr("Undo the last operation")) + undoAct.triggered.connect(undo) + + redoAct = QAction(tr("&Redo"), self) + redoAct.setShortcuts(QKeySequence.Redo) + redoAct.setStatusTip(tr("Redo the last operation")) + redoAct.triggered.connect(redo) + + cutAct = QAction(tr("Cu&t"), self) + cutAct.setShortcuts(QKeySequence.Cut) + cutAct.setStatusTip(tr("Cut the current selection's contents to the " + "clipboard")) + cutAct.triggered.connect(cut) + + copyAct = QAction(tr("&Copy"), self) + copyAct.setShortcut(tr("Ctrl+C")) + copyAct.setStatusTip(tr("Copy the current selection's contents to the " + "clipboard")) + copyAct.triggered.connect(copy) + + pasteAct = QAction(tr("&Paste"), self) + pasteAct.setShortcuts(QKeySequence.Paste) + pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " + "selection")) + pasteAct.triggered.connect(paste) + + boldAct = QAction(tr("&Bold"), self) + boldAct.setCheckable(True) + boldAct.setShortcut(tr("Ctrl+B")) + boldAct.setStatusTip(tr("Make the text bold")) + boldAct.triggered.connect(bold) + + QFont boldFont = boldAct.font() + boldFont.setBold(True) + boldAct.setFont(boldFont) + + italicAct = QAction(tr("&Italic"), self) + italicAct.setCheckable(True) + italicAct.setShortcut(tr("Ctrl+I")) + italicAct.setStatusTip(tr("Make the text italic")) + italicAct.triggered.connect(italic) + + QFont italicFont = italicAct.font() + italicFont.setItalic(True) + italicAct.setFont(italicFont) + + setLineSpacingAct = QAction(tr("Set &Line Spacing..."), self) + setLineSpacingAct.setStatusTip(tr("Change the gap between the lines of a " + "paragraph")) + setLineSpacingAct.triggered.connect(setLineSpacing) + + setParagraphSpacingAct = QAction(tr("Set &Paragraph Spacing..."), self) + setLineSpacingAct.setStatusTip(tr("Change the gap between paragraphs")) + setParagraphSpacingAct.triggered.connect(setParagraphSpacing) + + aboutAct = QAction(tr("&About"), self) + aboutAct.setStatusTip(tr("Show the application's About box")) + aboutAct.triggered.connect(about) + + aboutQtAct = QAction(tr("About &Qt"), self) + aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) + aboutQtAct.triggered.connect(qApp.aboutQt) + aboutQtAct.triggered.connect(aboutQt) + + leftAlignAct = QAction(tr("&Left Align"), self) + leftAlignAct.setCheckable(True) + leftAlignAct.setShortcut(tr("Ctrl+L")) + leftAlignAct.setStatusTip(tr("Left align the selected text")) + leftAlignAct.triggered.connect(leftAlign) + + rightAlignAct = QAction(tr("&Right Align"), self) + rightAlignAct.setCheckable(True) + rightAlignAct.setShortcut(tr("Ctrl+R")) + rightAlignAct.setStatusTip(tr("Right align the selected text")) + rightAlignAct.triggered.connect.(rightAlign) + + justifyAct = QAction(tr("&Justify"), self) + justifyAct.setCheckable(True) + justifyAct.setShortcut(tr("Ctrl+J")) + justifyAct.setStatusTip(tr("Justify the selected text")) + justifyAct.triggered.connect(justify) + + centerAct = QAction(tr("&Center"), self) + centerAct.setCheckable(True) + centerAct.setShortcut(tr("Ctrl+E")) + centerAct.setStatusTip(tr("Center the selected text")) + centerAct.triggered.connect(center) + +//! [6] //! [7] + alignmentGroup = QActionGroup(self) + alignmentGroup.addAction(leftAlignAct) + alignmentGroup.addAction(rightAlignAct) + alignmentGroup.addAction(justifyAct) + alignmentGroup.addAction(centerAct) + leftAlignAct.setChecked(True) +//! [6] + +//! [7] + +//! [8] +def createMenus(self): + +//! [9] //! [10] + fileMenu = menuBar().addMenu(tr("&File")) + fileMenu.addAction(Act) +//! [9] + fileMenu.addAction(openAct) +//! [10] + fileMenu.addAction(saveAct) + fileMenu.addAction(printAct) +//! [11] + fileMenu.addSeparator() +//! [11] + fileMenu.addAction(exitAct) + + editMenu = menuBar().addMenu(tr("&Edit")) + editMenu.addAction(undoAct) + editMenu.addAction(redoAct) + editMenu.addSeparator() + editMenu.addAction(cutAct) + editMenu.addAction(copyAct) + editMenu.addAction(pasteAct) + editMenu.addSeparator() + + helpMenu = menuBar().addMenu(tr("&Help")) + helpMenu.addAction(aboutAct) + helpMenu.addAction(aboutQtAct) +//! [8] + +//! [12] + formatMenu = editMenu.addMenu(tr("&Format")) + formatMenu.addAction(boldAct) + formatMenu.addAction(italicAct) + formatMenu.addSeparator()->setText(tr("Alignment")) + formatMenu.addAction(leftAlignAct) + formatMenu.addAction(rightAlignAct) + formatMenu.addAction(justifyAct) + formatMenu.addAction(centerAct) + formatMenu.addSeparator() + formatMenu.addAction(setLineSpacingAct) + formatMenu.addAction(setParagraphSpacingAct) +//! [12] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.cpp b/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.cpp deleted file mode 100644 index cfee5cdca..000000000 --- a/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.cpp +++ /dev/null @@ -1,381 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -from PySide2.QtGui import * - -def __init__(self): - - mdiArea = QMdiArea() - mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) - mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) - setCentralWidget(mdiArea) - connect(mdiArea, SIGNAL("subWindowActivated(QMdiSubWindow *)"), - self, SLOT("updateMenus()")) - windowMapper = QSignalMapper(self) - connect(windowMapper, SIGNAL("mapped(QWidget *)"), - self, SLOT("setActiveSubWindow(QWidget *)")) - - createActions() - createMenus() - createToolBars() - createStatusBar() - updateMenus() - - readSettings() - - setWindowTitle(tr("MDI")) - setUnifiedTitleAndToolBarOnMac(True) - - -def closeEvent(self, event): - mdiArea.closeAllSubWindows() - if self.activeMdiChild(): - event.ignore() - else: - self.writeSettings() - event.accept() - -def File(self): - child = self.createMdiChild() - child.File() - child.show() - - -def open(self): - fileName = QFileDialog.getOpenFileName(self) - if !fileName.isEmpty()): - existing = self.findMdiChild(fileName) - if existing: - mdiArea.setActiveSubWindow(existing) - return - - child = createMdiChild() - if child.loadFile(fileName)): - statusBar().showMessage(tr("File loaded"), 2000) - child.show() - else: - child.close() - -def save(self): - if self.activeMdiChild() && self.activeMdiChild().save(): - self.statusBar().showMessage(tr("File saved"), 2000) - -def saveAs(self): - if self.activeMdiChild() && self.activeMdiChild().saveAs(): - self.statusBar().showMessage(tr("File saved"), 2000) - -def cut(self): - if self.activeMdiChild(): - self.activeMdiChild().cut() - -def copy(self): - if self.activeMdiChild(): - activeMdiChild().copy() - -def paste(self): - if self.activeMdiChild(): - activeMdiChild().paste() - -def about(self): - QMessageBox.about(self, tr("About MDI"), - tr("The MDI example demonstrates how to write multiple " - "document interface applications using Qt.")") - -def updateMenus(self): - hasMdiChild = (activeMdiChild() != 0) - self.saveAct.setEnabled(hasMdiChild) - self.saveAsAct.setEnabled(hasMdiChild) - self.pasteAct.setEnabled(hasMdiChild) - self.closeAct.setEnabled(hasMdiChild) - self.closeAllAct.setEnabled(hasMdiChild) - self.tileAct.setEnabled(hasMdiChild) - self.cascadeAct.setEnabled(hasMdiChild) - self.nextAct.setEnabled(hasMdiChild) - self.previousAct.setEnabled(hasMdiChild) - self.separatorAct.setVisible(hasMdiChild) - - hasSelection = (self.activeMdiChild() && - self.activeMdiChild().textCursor().hasSelection()") - self.cutAct.setEnabled(hasSelection) - self.copyAct.setEnabled(hasSelection) - -def updateWindowMenu(self): - self.windowMenu.clear() - self.windowMenu.addAction(closeAct) - self.windowMenu.addAction(closeAllAct) - self.windowMenu.addSeparator() - self.windowMenu.addAction(tileAct) - self.windowMenu.addAction(cascadeAct) - self.windowMenu.addSeparator() - self.windowMenu.addAction(nextAct) - self.windowMenu.addAction(previousAct) - self.windowMenu.addAction(separatorAct) - - windows = mdiArea.subWindowList() - separatorAct.setVisible(!windows.isEmpty()") - - for i in range((int i = 0 i < windows.size(); ++i) - MdiChild *child = qobject_cast(windows.at(i).widget()") - - QString text - if (i < 9) - text = tr("&%1 %2").arg(i + 1) - .arg(child.userFriendlyCurrentFile()") - else - text = tr("%1 %2").arg(i + 1) - .arg(child.userFriendlyCurrentFile()") - - QAction *action = windowMenu.addAction(text) - action.setCheckable(True) - action .setChecked(child == activeMdiChild()") - connect(action, SIGNAL("triggered()"), windowMapper, SLOT("map()")) - windowMapper.setMapping(action, windows.at(i)") - - - -MdiChild *createMdiChild() - - MdiChild *child = MdiChild - mdiArea.addSubWindow(child) - - connect(child, SIGNAL("copyAvailable(bool)"), - cutAct, SLOT("setEnabled(bool)")) - connect(child, SIGNAL("copyAvailable(bool)"), - copyAct, SLOT("setEnabled(bool)")) - - return child - - -def createActions() - - Act = new QAction(QIcon(":/images/new.png"), tr("&New"), self) - Act.setShortcuts(QKeySequence.New) - Act.setStatusTip(tr("Create a new file")") - connect(Act, SIGNAL("triggered()"), self, SLOT("newFile()")) - - openAct = QAction(QIcon(":/images/open.png"), tr("&Open..."), self) - openAct.setShortcuts(QKeySequence.Open) - openAct.setStatusTip(tr("Open an existing file")") - connect(openAct, SIGNAL("triggered()"), self, SLOT("open()")) - - saveAct = QAction(QIcon(":/images/save.png"), tr("&Save"), self) - saveAct.setShortcuts(QKeySequence.Save) - saveAct.setStatusTip(tr("Save the document to disk")") - connect(saveAct, SIGNAL("triggered()"), self, SLOT("save()")) - - saveAsAct = QAction(tr("Save &As..."), self) - saveAsAct.setShortcuts(QKeySequence.SaveAs) - saveAsAct.setStatusTip(tr("Save the document under a name")") - connect(saveAsAct, SIGNAL("triggered()"), self, SLOT("saveAs()")) - -//! [0] - exitAct = QAction(tr("E&xit"), self) - exitAct.setShortcut(tr("Ctrl+Q")") - exitAct.setStatusTip(tr("Exit the application")") - connect(exitAct, SIGNAL("triggered()"), qApp, SLOT("closeAllWindows()")) -//! [0] - - cutAct = QAction(QIcon(":/images/cut.png"), tr("Cu&t"), self) - cutAct.setShortcuts(QKeySequence.Cut) - cutAct.setStatusTip(tr("Cut the current selection's contents to the " - "clipboard")") - connect(cutAct, SIGNAL("triggered()"), self, SLOT("cut()")) - - copyAct = QAction(QIcon(":/images/copy.png"), tr("&Copy"), self) - copyAct.setShortcuts(QKeySequence.Copy) - copyAct.setStatusTip(tr("Copy the current selection's contents to the " - "clipboard")") - connect(copyAct, SIGNAL("triggered()"), self, SLOT("copy()")) - - pasteAct = QAction(QIcon(":/images/paste.png"), tr("&Paste"), self) - pasteAct.setShortcuts(QKeySequence.Paste) - pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " - "selection")") - connect(pasteAct, SIGNAL("triggered()"), self, SLOT("paste()")) - - closeAct = QAction(tr("Cl&ose"), self) - closeAct.setShortcut(tr("Ctrl+F4")") - closeAct.setStatusTip(tr("Close the active window")") - connect(closeAct, SIGNAL("triggered()"), - mdiArea, SLOT("closeActiveSubWindow()")) - - closeAllAct = QAction(tr("Close &All"), self) - closeAllAct.setStatusTip(tr("Close all the windows")") - connect(closeAllAct, SIGNAL("triggered()"), - mdiArea, SLOT("closeAllSubWindows()")) - - tileAct = QAction(tr("&Tile"), self) - tileAct.setStatusTip(tr("Tile the windows")") - connect(tileAct, SIGNAL("triggered()"), mdiArea, SLOT("tileSubWindows()")) - - cascadeAct = QAction(tr("&Cascade"), self) - cascadeAct.setStatusTip(tr("Cascade the windows")") - connect(cascadeAct, SIGNAL("triggered()"), mdiArea, SLOT("cascadeSubWindows()")) - - nextAct = QAction(tr("Ne&xt"), self) - nextAct.setShortcuts(QKeySequence.NextChild) - nextAct.setStatusTip(tr("Move the focus to the next window")") - connect(nextAct, SIGNAL("triggered()"), - mdiArea, SLOT("activateNextSubWindow()")) - - previousAct = QAction(tr("Pre&vious"), self) - previousAct.setShortcuts(QKeySequence.PreviousChild) - previousAct.setStatusTip(tr("Move the focus to the previous " - "window")") - connect(previousAct, SIGNAL("triggered()"), - mdiArea, SLOT("activatePreviousSubWindow()")) - - separatorAct = QAction(self) - separatorAct.setSeparator(True) - - aboutAct = QAction(tr("&About"), self) - aboutAct.setStatusTip(tr("Show the application's About box")") - connect(aboutAct, SIGNAL("triggered()"), self, SLOT("about()")) - - aboutQtAct = QAction(tr("About &Qt"), self) - aboutQtAct.setStatusTip(tr("Show the Qt library's About box")") - connect(aboutQtAct, SIGNAL("triggered()"), qApp, SLOT("aboutQt()")) - - -def createMenus() - - fileMenu = menuBar().addMenu(tr("&File")") - fileMenu.addAction(Act) - fileMenu.addAction(openAct) - fileMenu.addAction(saveAct) - fileMenu.addAction(saveAsAct) - fileMenu.addSeparator() - QAction *action = fileMenu.addAction(tr("Switch layout direction")") - connect(action, SIGNAL("triggered()"), self, SLOT("switchLayoutDirection()")) - fileMenu.addAction(exitAct) - - editMenu = menuBar().addMenu(tr("&Edit")") - editMenu.addAction(cutAct) - editMenu.addAction(copyAct) - editMenu.addAction(pasteAct) - - windowMenu = menuBar().addMenu(tr("&Window")") - updateWindowMenu() - connect(windowMenu, SIGNAL("aboutToShow()"), self, SLOT("updateWindowMenu()")) - - menuBar().addSeparator() - - helpMenu = menuBar().addMenu(tr("&Help")") - helpMenu.addAction(aboutAct) - helpMenu.addAction(aboutQtAct) - - -def createToolBars() - - fileToolBar = addToolBar(tr("File")") - fileToolBar.addAction(Act) - fileToolBar.addAction(openAct) - fileToolBar.addAction(saveAct) - - editToolBar = addToolBar(tr("Edit")") - editToolBar.addAction(cutAct) - editToolBar.addAction(copyAct) - editToolBar.addAction(pasteAct) - - -def createStatusBar() - - statusBar().showMessage(tr("Ready")") - - -def readSettings() - - QSettings settings("Trolltech", "MDI Example") - QPoint pos = settings.value("pos", QPoint(200, 200)").toPoint() - QSize size = settings.value("size", QSize(400, 400)").toSize() - move(pos) - resize(size) - - -def writeSettings() - - QSettings settings("Trolltech", "MDI Example") - settings.setValue("pos", pos()") - settings.setValue("size", size()") - - -MdiChild *activeMdiChild() - - if (QMdiSubWindow *activeSubWindow = mdiArea.activeSubWindow()") - return qobject_cast(activeSubWindow.widget()") - return 0 - - -QMdiSubWindow *findMdiChild(const QString &fileName) - - QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath() - - foreach (QMdiSubWindow *window, mdiArea.subWindowList()") - MdiChild *mdiChild = qobject_cast(window.widget()") - if (mdiChild.currentFile() == canonicalFilePath) - return window - - return 0 - - -def switchLayoutDirection() - - if (layoutDirection() == Qt.LeftToRight) - qApp.setLayoutDirection(Qt.RightToLeft) - else - qApp.setLayoutDirection(Qt.LeftToRight) - - -def setActiveSubWindow(QWidget *window) - - if (!window) - return - mdiArea.setActiveSubWindow(qobject_cast(window)") - diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py b/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py new file mode 100644 index 000000000..41f515847 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/mdi/mainwindow.py @@ -0,0 +1,360 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtGui import * + +class QMdiSubWindow(QMainWindow): + def __init__(self, parent=None): + QMainWindow.__init__(self, parent) + + mdiArea = QMdiArea() + mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) + mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) + setCentralWidget(mdiArea) + mdiArea.subWindowActivated[QMdiSubWindow].connect(updateMenus) + windowMapper = QSignalMapper(self) + windowMapper.mapped[QWidget].connect(setActiveSubWindow) + + self.createActions() + self.createMenus() + self.createToolBars() + self.createStatusBar() + self.updateMenus() + self.readSettings() + self.setWindowTitle(tr("MDI")) + self.setUnifiedTitleAndToolBarOnMac(True) + + + def closeEvent(self, event): + mdiArea.closeAllSubWindows() + if self.activeMdiChild(): + event.ignore() + else: + self.writeSettings() + event.accept() + + def File(self): + child = self.createMdiChild() + child.File() + child.show() + + + def open(self): + fileName = QFileDialog.getOpenFileName(self) + if not fileName.isEmpty(): + existing = self.findMdiChild(fileName) + if existing: + mdiArea.setActiveSubWindow(existing) + return + + child = createMdiChild() + if child.loadFile(fileName): + statusBar().showMessage(tr("File loaded"), 2000) + child.show() + else: + child.close() + + def save(self): + if self.activeMdiChild() and self.activeMdiChild().save(): + self.statusBar().showMessage(tr("File saved"), 2000) + + def saveAs(self): + if self.activeMdiChild() and self.activeMdiChild().saveAs(): + self.statusBar().showMessage(tr("File saved"), 2000) + + def cut(self): + if self.activeMdiChild(): + self.activeMdiChild().cut() + + def copy(self): + if self.activeMdiChild(): + activeMdiChild().copy() + + def paste(self): + if self.activeMdiChild(): + activeMdiChild().paste() + + def about(self): + QMessageBox.about(self, tr("About MDI"), + tr("The MDI example demonstrates how to write multiple " + "document interface applications using Qt.")) + + def updateMenus(self): + hasMdiChild = (activeMdiChild() != 0) + self.saveAct.setEnabled(hasMdiChild) + self.saveAsAct.setEnabled(hasMdiChild) + self.pasteAct.setEnabled(hasMdiChild) + self.closeAct.setEnabled(hasMdiChild) + self.closeAllAct.setEnabled(hasMdiChild) + self.tileAct.setEnabled(hasMdiChild) + self.cascadeAct.setEnabled(hasMdiChild) + self.nextAct.setEnabled(hasMdiChild) + self.previousAct.setEnabled(hasMdiChild) + self.separatorAct.setVisible(hasMdiChild) + + hasSelection = (self.activeMdiChild() and + self.activeMdiChild().textCursor().hasSelection()) + self.cutAct.setEnabled(hasSelection) + self.copyAct.setEnabled(hasSelection) + + def updateWindowMenu(self): + self.windowMenu.clear() + self.windowMenu.addAction(closeAct) + self.windowMenu.addAction(closeAllAct) + self.windowMenu.addSeparator() + self.windowMenu.addAction(tileAct) + self.windowMenu.addAction(cascadeAct) + self.windowMenu.addSeparator() + self.windowMenu.addAction(nextAct) + self.windowMenu.addAction(previousAct) + self.windowMenu.addAction(separatorAct) + + windows = mdiArea.subWindowList() + separatorAct.setVisible(not windows.isEmpty()) + + for i in range(0, windows.size()): + child = windows.at(i).widget() + + text = "" + if i < 9: + text = "{} {}".format(i + 1, child.userFriendlyCurrentFile()) + else: + text = "{} {}".format(i + 1, child.userFriendlyCurrentFile()) + + action = windowMenu.addAction(text) + action.setCheckable(True) + action.setChecked(child == activeMdiChild()) + action.triggered.connect(windowMapper.map) + windowMapper.setMapping(action, windows.at(i)) + + createMdiChild = MdiChild() + + child = MdiChild() + mdiArea.addSubWindow(child) + + child.copyAvailable[bool].connect(cutAct.setEnabled) + child.copyAvailable[bool].connect(copyAct.setEnabled) + + return child + + + def createActions(self): + + Act = QAction(QIcon(":/images/new.png"), tr("&New"), self) + Act.setShortcuts(QKeySequence.New) + Act.setStatusTip(tr("Create a new file")) + Act.triggered.connect(self.newFile) + + openAct = QAction(QIcon(":/images/open.png"), tr("&Open..."), self) + openAct.setShortcuts(QKeySequence.Open) + openAct.setStatusTip(tr("Open an existing file")) + openAct.triggered.connect(self.open) + + saveAct = QAction(QIcon(":/images/save.png"), tr("&Save"), self) + saveAct.setShortcuts(QKeySequence.Save) + saveAct.setStatusTip(tr("Save the document to disk")) + saveAct.triggered.connect(self.save) + + saveAsAct = QAction(tr("Save &As..."), self) + saveAsAct.setShortcuts(QKeySequence.SaveAs) + saveAsAct.setStatusTip(tr("Save the document under a name")) + saveAsAct.triggered.connect(self.saveAs) + +//! [0] + exitAct = QAction(tr("E&xit"), self) + exitAct.setShortcut(tr("Ctrl+Q")) + exitAct.setStatusTip(tr("Exit the application")) + exitAct.triggered.connect(qApp.closeAllWindows) +//! [0] + + cutAct = QAction(QIcon(":/images/cut.png"), tr("Cu&t"), self) + cutAct.setShortcuts(QKeySequence.Cut) + cutAct.setStatusTip(tr("Cut the current selection's contents to the " + "clipboard")) + cutAct.triggered.connect(self.cut) + + copyAct = QAction(QIcon(":/images/copy.png"), tr("&Copy"), self) + copyAct.setShortcuts(QKeySequence.Copy) + copyAct.setStatusTip(tr("Copy the current selection's contents to the " + "clipboard")) + copyAct.triggered.connect(self.copy) + + pasteAct = QAction(QIcon(":/images/paste.png"), tr("&Paste"), self) + pasteAct.setShortcuts(QKeySequence.Paste) + pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " + "selection")) + pasteAct.triggered.connect(self.paste) + + closeAct = QAction(tr("Cl&ose"), self) + closeAct.setShortcut(tr("Ctrl+F4")) + closeAct.setStatusTip(tr("Close the active window")) + closeAct.triggered.connect(mdiArea.closeActiveSubWindow) + + closeAllAct = QAction(tr("Close &All"), self) + closeAllAct.setStatusTip(tr("Close all the windows")) + closeAllAct.triggered.connect(mdiArea.closeAllSubWindows) + + tileAct = QAction(tr("&Tile"), self) + tileAct.setStatusTip(tr("Tile the windows")) + tileAct.triggered.connect(mdiArea.tileSubWindows) + + cascadeAct = QAction(tr("&Cascade"), self) + cascadeAct.setStatusTip(tr("Cascade the windows")) + cascadeAct.triggered.connect(mdiArea.cascadeSubWindows) + + nextAct = QAction(tr("Ne&xt"), self) + nextAct.setShortcuts(QKeySequence.NextChild) + nextAct.setStatusTip(tr("Move the focus to the next window")) + nextAct.triggered.connect(mdiArea.activateNextSubWindow) + + previousAct = QAction(tr("Pre&vious"), self) + previousAct.setShortcuts(QKeySequence.PreviousChild) + previousAct.setStatusTip(tr("Move the focus to the previous " + "window")) + previousAct.triggered.connect(mdiArea.activatePreviousSubWindow) + + separatorAct = QAction(self) + separatorAct.setSeparator(True) + + aboutAct = QAction(tr("&About"), self) + aboutAct.setStatusTip(tr("Show the application's About box")) + aboutAct.triggered.connect(self.about) + + aboutQtAct = QAction(tr("About &Qt"), self) + aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) + aboutQtAct.triggered.connect(qApp.aboutQt) + + + def createMenus(self): + + fileMenu = menuBar().addMenu(tr("&File")) + fileMenu.addAction(Act) + fileMenu.addAction(openAct) + fileMenu.addAction(saveAct) + fileMenu.addAction(saveAsAct) + fileMenu.addSeparator() + action = fileMenu.addAction(tr("Switch layout direction")) + action.triggered.connect(self.switchLayoutDirection) + fileMenu.addAction(exitAct) + + editMenu = menuBar().addMenu(tr("&Edit")) + editMenu.addAction(cutAct) + editMenu.addAction(copyAct) + editMenu.addAction(pasteAct) + + windowMenu = menuBar().addMenu(tr("&Window")) + updateWindowMenu() + windowMenu.aboutToShow.connect(self.updateWindowMenu) + + menuBar().addSeparator() + + helpMenu = menuBar().addMenu(tr("&Help")) + helpMenu.addAction(aboutAct) + helpMenu.addAction(aboutQtAct) + + + def createToolBars(self): + fileToolBar = addToolBar(tr("File")) + fileToolBar.addAction(Act) + fileToolBar.addAction(openAct) + fileToolBar.addAction(saveAct) + + editToolBar = addToolBar(tr("Edit")) + editToolBar.addAction(cutAct) + editToolBar.addAction(copyAct) + editToolBar.addAction(pasteAct) + + + def createStatusBar(self): + statusBar().showMessage(tr("Ready")) + + + def readSettings(self): + settings = QSettings("Trolltech", "MDI Example") + QPoint pos = settings.value("pos", QPoint(200, 200)").toPoint() + QSize size = settings.value("size", QSize(400, 400)").toSize() + move(pos) + resize(size) + + def writeSettings(self): + QSettings settings("Trolltech", "MDI Example") + settings.setValue("pos", pos()") + settings.setValue("size", size()") + + + activeMdiChild = MdiChild() + activeSubWindow = mdiArea.activeSubWindow() + if activeSubWindow: + return activeSubWindow.widget() + return 0 + + + def findMdiChild(self, fileName): + + canonicalFilePath = QFileInfo(fileName).canonicalFilePath() + + for window in mdiArea.subWindowList(): + mdiChild = window.widget() + if mdiChild.currentFile() == canonicalFilePath: + return window + return 0 + + + def switchLayoutDirection(self) + if layoutDirection() == Qt.LeftToRight: + qApp.setLayoutDirection(Qt.RightToLeft) + else: + qApp.setLayoutDirection(Qt.LeftToRight) + + + def setActiveSubWindow(self, window): + if not window: + return + mdiArea.setActiveSubWindow(window) diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.cpp b/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.cpp deleted file mode 100644 index 6ed5f5466..000000000 --- a/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.cpp +++ /dev/null @@ -1,367 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -from PySide2.QtGui import * - -//! [0] -def __init__(self): - Q__init__(self) - - widget = QWidget() - setCentralWidget(widget) -//! [0] - -//! [1] - topFiller = QWidget() - topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - - infoLabel = QLabel(tr("Choose a menu option, or right-click to " - "invoke a context menu")) - infoLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) - infoLabel.setAlignment(Qt.AlignCenter) - - bottomFiller = QWidget() - bottomFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - - layout = QVBoxLayout() - layout.setMargin(5) - layout.addWidget(topFiller) - layout.addWidget(infoLabel) - layout.addWidget(bottomFiller) - widget.setLayout(layout) -//! [1] - -//! [2] - createActions() - createMenus() - - message = tr("A context menu is available by right-clicking") - statusBar().showMessage(message) - - setWindowTitle(tr("Menus")) - setMinimumSize(160, 160) - resize(480, 320) - -//! [2] - -//! [3] -def contextMenuEvent(self, event): - menu = QMenu(self) - menu.addAction(cutAct) - menu.addAction(copyAct) - menu.addAction(pasteAct) - menu.exec_(event.globalPos()") - -//! [3] - -def File(self): - infoLabel.setText(tr("Invoked File|New")) - - -def open(self): - infoLabel.setText(tr("Invoked File|Open")) - - -def save(self): - infoLabel.setText(tr("Invoked File|Save")) - -def print_(self): - infoLabel.setText(tr("Invoked File|Print")) - -def undo(self): - infoLabel.setText(tr("Invoked Edit|Undo")) - -def redo(self): - infoLabel.setText(tr("Invoked Edit|Redo")) - -def cut(self): - - infoLabel.setText(tr("Invoked Edit|Cut")) - - -def copy(self): - - infoLabel.setText(tr("Invoked Edit|Copy")) - - -def paste(self): - - infoLabel.setText(tr("Invoked Edit|Paste")) - - -def bold(self): - - infoLabel.setText(tr("Invoked Edit|Format|Bold")) - - -def italic(self): - - infoLabel.setText(tr("Invoked Edit|Format|Italic")) - - -def leftAlign(self): - - infoLabel.setText(tr("Invoked Edit|Format|Left Align")) - - -def rightAlign(self): - - infoLabel.setText(tr("Invoked Edit|Format|Right Align")) - - -def justify(self): - - infoLabel.setText(tr("Invoked Edit|Format|Justify")) - - -def center(self): - - infoLabel.setText(tr("Invoked Edit|Format|Center")) - - -def setLineSpacing(self): - - infoLabel.setText(tr("Invoked Edit|Format|Set Line Spacing")) - - -def setParagraphSpacing(self): - - infoLabel.setText(tr("Invoked Edit|Format|Set Paragraph Spacing")) - - -def about(self): - - infoLabel.setText(tr("Invoked Help|About")) - QMessageBox.about(self, tr("About Menu"), - tr("The Menu example shows how to create " - "menu-bar menus and context menus.")) - - -def aboutQt(self): - - infoLabel.setText(tr("Invoked Help|About Qt")) - - -//! [4] -def createActions(self): - -//! [5] - Act = new QAction(tr("&New"), self) - Act.setShortcuts(QKeySequence.New) - Act.setStatusTip(tr("Create a new file")) - connect(Act, SIGNAL("triggered()"), self, SLOT("newFile()")) -//! [4] - - openAct = QAction(tr("&Open..."), self) - openAct.setShortcuts(QKeySequence.Open) - openAct.setStatusTip(tr("Open an existing file")) - connect(openAct, SIGNAL("triggered()"), self, SLOT("open()")) -//! [5] - - saveAct = QAction(tr("&Save"), self) - saveAct.setShortcuts(QKeySequence.Save) - saveAct.setStatusTip(tr("Save the document to disk")) - connect(saveAct, SIGNAL("triggered()"), self, SLOT("save()")) - - printAct = QAction(tr("&Print..."), self) - printAct.setShortcuts(QKeySequence.Print) - printAct.setStatusTip(tr("Print the document")) - connect(printAct, SIGNAL("triggered()"), self, SLOT("print_()")) - - exitAct = QAction(tr("E&xit"), self) - exitAct.setShortcut(tr("Ctrl+Q")) - exitAct.setStatusTip(tr("Exit the application")) - connect(exitAct, SIGNAL("triggered()"), self, SLOT("close()")) - - undoAct = QAction(tr("&Undo"), self) - undoAct.setShortcuts(QKeySequence.Undo) - undoAct.setStatusTip(tr("Undo the last operation")) - connect(undoAct, SIGNAL("triggered()"), self, SLOT("undo()")) - - redoAct = QAction(tr("&Redo"), self) - redoAct.setShortcuts(QKeySequence.Redo) - redoAct.setStatusTip(tr("Redo the last operation")) - connect(redoAct, SIGNAL("triggered()"), self, SLOT("redo()")) - - cutAct = QAction(tr("Cu&t"), self) - cutAct.setShortcuts(QKeySequence.Cut) - cutAct.setStatusTip(tr("Cut the current selection's contents to the " - "clipboard")) - connect(cutAct, SIGNAL("triggered()"), self, SLOT("cut()")) - - copyAct = QAction(tr("&Copy"), self) - copyAct.setShortcut(tr("Ctrl+C")) - copyAct.setStatusTip(tr("Copy the current selection's contents to the " - "clipboard")) - connect(copyAct, SIGNAL("triggered()"), self, SLOT("copy()")) - - pasteAct = QAction(tr("&Paste"), self) - pasteAct.setShortcuts(QKeySequence.Paste) - pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " - "selection")) - connect(pasteAct, SIGNAL("triggered()"), self, SLOT("paste()")) - - boldAct = QAction(tr("&Bold"), self) - boldAct.setCheckable(True) - boldAct.setShortcut(tr("Ctrl+B")) - boldAct.setStatusTip(tr("Make the text bold")) - connect(boldAct, SIGNAL("triggered()"), self, SLOT("bold()")) - - QFont boldFont = boldAct.font() - boldFont.setBold(True) - boldAct.setFont(boldFont) - - italicAct = QAction(tr("&Italic"), self) - italicAct.setCheckable(True) - italicAct.setShortcut(tr("Ctrl+I")) - italicAct.setStatusTip(tr("Make the text italic")) - connect(italicAct, SIGNAL("triggered()"), self, SLOT("italic()")) - - QFont italicFont = italicAct.font() - italicFont.setItalic(True) - italicAct.setFont(italicFont) - - setLineSpacingAct = QAction(tr("Set &Line Spacing..."), self) - setLineSpacingAct.setStatusTip(tr("Change the gap between the lines of a " - "paragraph")) - connect(setLineSpacingAct, SIGNAL("triggered()"), self, SLOT("setLineSpacing()")) - - setParagraphSpacingAct = QAction(tr("Set &Paragraph Spacing..."), self) - setLineSpacingAct.setStatusTip(tr("Change the gap between paragraphs")) - connect(setParagraphSpacingAct, SIGNAL("triggered()"), - self, SLOT("setParagraphSpacing()")) - - aboutAct = QAction(tr("&About"), self) - aboutAct.setStatusTip(tr("Show the application's About box")) - connect(aboutAct, SIGNAL("triggered()"), self, SLOT("about()")) - - aboutQtAct = QAction(tr("About &Qt"), self) - aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) - connect(aboutQtAct, SIGNAL("triggered()"), qApp, SLOT("aboutQt()")) - connect(aboutQtAct, SIGNAL("triggered()"), self, SLOT("aboutQt()")) - - leftAlignAct = QAction(tr("&Left Align"), self) - leftAlignAct.setCheckable(True) - leftAlignAct.setShortcut(tr("Ctrl+L")) - leftAlignAct.setStatusTip(tr("Left align the selected text")) - connect(leftAlignAct, SIGNAL("triggered()"), self, SLOT("leftAlign()")) - - rightAlignAct = QAction(tr("&Right Align"), self) - rightAlignAct.setCheckable(True) - rightAlignAct.setShortcut(tr("Ctrl+R")) - rightAlignAct.setStatusTip(tr("Right align the selected text")) - connect(rightAlignAct, SIGNAL("triggered()"), self, SLOT("rightAlign()")) - - justifyAct = QAction(tr("&Justify"), self) - justifyAct.setCheckable(True) - justifyAct.setShortcut(tr("Ctrl+J")) - justifyAct.setStatusTip(tr("Justify the selected text")) - connect(justifyAct, SIGNAL("triggered()"), self, SLOT("justify()")) - - centerAct = QAction(tr("&Center"), self) - centerAct.setCheckable(True) - centerAct.setShortcut(tr("Ctrl+E")) - centerAct.setStatusTip(tr("Center the selected text")) - connect(centerAct, SIGNAL("triggered()"), self, SLOT("center()")) - -//! [6] //! [7] - alignmentGroup = QActionGroup(self) - alignmentGroup.addAction(leftAlignAct) - alignmentGroup.addAction(rightAlignAct) - alignmentGroup.addAction(justifyAct) - alignmentGroup.addAction(centerAct) - leftAlignAct.setChecked(True) -//! [6] - -//! [7] - -//! [8] -def createMenus(self): - -//! [9] //! [10] - fileMenu = menuBar().addMenu(tr("&File")) - fileMenu.addAction(Act) -//! [9] - fileMenu.addAction(openAct) -//! [10] - fileMenu.addAction(saveAct) - fileMenu.addAction(printAct) -//! [11] - fileMenu.addSeparator() -//! [11] - fileMenu.addAction(exitAct) - - editMenu = menuBar().addMenu(tr("&Edit")) - editMenu.addAction(undoAct) - editMenu.addAction(redoAct) - editMenu.addSeparator() - editMenu.addAction(cutAct) - editMenu.addAction(copyAct) - editMenu.addAction(pasteAct) - editMenu.addSeparator() - - helpMenu = menuBar().addMenu(tr("&Help")) - helpMenu.addAction(aboutAct) - helpMenu.addAction(aboutQtAct) -//! [8] - -//! [12] - formatMenu = editMenu.addMenu(tr("&Format")) - formatMenu.addAction(boldAct) - formatMenu.addAction(italicAct) - formatMenu.addSeparator()->setText(tr("Alignment")) - formatMenu.addAction(leftAlignAct) - formatMenu.addAction(rightAlignAct) - formatMenu.addAction(justifyAct) - formatMenu.addAction(centerAct) - formatMenu.addSeparator() - formatMenu.addAction(setLineSpacingAct) - formatMenu.addAction(setParagraphSpacingAct) -//! [12] diff --git a/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.py b/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.py new file mode 100644 index 000000000..6505f1f1a --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/mainwindows/menus/mainwindow.py @@ -0,0 +1,366 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtGui import * + +//! [0] +def __init__(self): + Q__init__(self) + + widget = QWidget() + setCentralWidget(widget) +//! [0] + +//! [1] + topFiller = QWidget() + topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + + infoLabel = QLabel(tr("Choose a menu option, or right-click to " + "invoke a context menu")) + infoLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) + infoLabel.setAlignment(Qt.AlignCenter) + + bottomFiller = QWidget() + bottomFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + + layout = QVBoxLayout() + layout.setMargin(5) + layout.addWidget(topFiller) + layout.addWidget(infoLabel) + layout.addWidget(bottomFiller) + widget.setLayout(layout) +//! [1] + +//! [2] + createActions() + createMenus() + + message = tr("A context menu is available by right-clicking") + statusBar().showMessage(message) + + setWindowTitle(tr("Menus")) + setMinimumSize(160, 160) + resize(480, 320) + +//! [2] + +//! [3] +def contextMenuEvent(self, event): + menu = QMenu(self) + menu.addAction(cutAct) + menu.addAction(copyAct) + menu.addAction(pasteAct) + menu.exec_(event.globalPos()") + +//! [3] + +def File(self): + infoLabel.setText(tr("Invoked File|New")) + + +def open(self): + infoLabel.setText(tr("Invoked File|Open")) + + +def save(self): + infoLabel.setText(tr("Invoked File|Save")) + +def print_(self): + infoLabel.setText(tr("Invoked File|Print")) + +def undo(self): + infoLabel.setText(tr("Invoked Edit|Undo")) + +def redo(self): + infoLabel.setText(tr("Invoked Edit|Redo")) + +def cut(self): + + infoLabel.setText(tr("Invoked Edit|Cut")) + + +def copy(self): + + infoLabel.setText(tr("Invoked Edit|Copy")) + + +def paste(self): + + infoLabel.setText(tr("Invoked Edit|Paste")) + + +def bold(self): + + infoLabel.setText(tr("Invoked Edit|Format|Bold")) + + +def italic(self): + + infoLabel.setText(tr("Invoked Edit|Format|Italic")) + + +def leftAlign(self): + + infoLabel.setText(tr("Invoked Edit|Format|Left Align")) + + +def rightAlign(self): + + infoLabel.setText(tr("Invoked Edit|Format|Right Align")) + + +def justify(self): + + infoLabel.setText(tr("Invoked Edit|Format|Justify")) + + +def center(self): + + infoLabel.setText(tr("Invoked Edit|Format|Center")) + + +def setLineSpacing(self): + + infoLabel.setText(tr("Invoked Edit|Format|Set Line Spacing")) + + +def setParagraphSpacing(self): + + infoLabel.setText(tr("Invoked Edit|Format|Set Paragraph Spacing")) + + +def about(self): + + infoLabel.setText(tr("Invoked Help|About")) + QMessageBox.about(self, tr("About Menu"), + tr("The Menu example shows how to create " + "menu-bar menus and context menus.")) + + +def aboutQt(self): + + infoLabel.setText(tr("Invoked Help|About Qt")) + + +//! [4] +def createActions(self): + +//! [5] + Act = new QAction(tr("&New"), self) + Act.setShortcuts(QKeySequence.New) + Act.setStatusTip(tr("Create a new file")) + Act.triggered.connect(newFile) +//! [4] + + openAct = QAction(tr("&Open..."), self) + openAct.setShortcuts(QKeySequence.Open) + openAct.setStatusTip(tr("Open an existing file")) + openAct.triggered.connect(open) +//! [5] + + saveAct = QAction(tr("&Save"), self) + saveAct.setShortcuts(QKeySequence.Save) + saveAct.setStatusTip(tr("Save the document to disk")) + saveAct.triggered.connect(save) + + printAct = QAction(tr("&Print..."), self) + printAct.setShortcuts(QKeySequence.Print) + printAct.setStatusTip(tr("Print the document")) + printAct.triggered.connect(print_) + + exitAct = QAction(tr("E&xit"), self) + exitAct.setShortcut(tr("Ctrl+Q")) + exitAct.setStatusTip(tr("Exit the application")) + exitAct.triggered.connect(close) + + undoAct = QAction(tr("&Undo"), self) + undoAct.setShortcuts(QKeySequence.Undo) + undoAct.setStatusTip(tr("Undo the last operation")) + undoAct.triggered.connect(undo) + + redoAct = QAction(tr("&Redo"), self) + redoAct.setShortcuts(QKeySequence.Redo) + redoAct.setStatusTip(tr("Redo the last operation")) + redoAct.triggered.connect(redo) + + cutAct = QAction(tr("Cu&t"), self) + cutAct.setShortcuts(QKeySequence.Cut) + cutAct.setStatusTip(tr("Cut the current selection's contents to the " + "clipboard")) + cutAct.triggered.connect(cut) + + copyAct = QAction(tr("&Copy"), self) + copyAct.setShortcut(tr("Ctrl+C")) + copyAct.setStatusTip(tr("Copy the current selection's contents to the " + "clipboard")) + copyAct.triggered.connect(copy) + + pasteAct = QAction(tr("&Paste"), self) + pasteAct.setShortcuts(QKeySequence.Paste) + pasteAct.setStatusTip(tr("Paste the clipboard's contents into the current " + "selection")) + pasteAct.triggered.connect(paste) + + boldAct = QAction(tr("&Bold"), self) + boldAct.setCheckable(True) + boldAct.setShortcut(tr("Ctrl+B")) + boldAct.setStatusTip(tr("Make the text bold")) + boldAct.triggered.connect(bold) + + QFont boldFont = boldAct.font() + boldFont.setBold(True) + boldAct.setFont(boldFont) + + italicAct = QAction(tr("&Italic"), self) + italicAct.setCheckable(True) + italicAct.setShortcut(tr("Ctrl+I")) + italicAct.setStatusTip(tr("Make the text italic")) + italicAct.triggered.connect(italic) + + QFont italicFont = italicAct.font() + italicFont.setItalic(True) + italicAct.setFont(italicFont) + + setLineSpacingAct = QAction(tr("Set &Line Spacing..."), self) + setLineSpacingAct.setStatusTip(tr("Change the gap between the lines of a " + "paragraph")) + setLineSpacingAct.triggered.connect(setLineSpacing) + + setParagraphSpacingAct = QAction(tr("Set &Paragraph Spacing..."), self) + setLineSpacingAct.setStatusTip(tr("Change the gap between paragraphs")) + setParagraphSpacingAct.triggered.connect(setParagraphSpacing) + + aboutAct = QAction(tr("&About"), self) + aboutAct.setStatusTip(tr("Show the application's About box")) + aboutAct.triggered.connect(about) + + aboutQtAct = QAction(tr("About &Qt"), self) + aboutQtAct.setStatusTip(tr("Show the Qt library's About box")) + aboutQtAct.triggered.connect(qApp.aboutQt) + aboutQtAct.triggered.connect(aboutQt) + + leftAlignAct = QAction(tr("&Left Align"), self) + leftAlignAct.setCheckable(True) + leftAlignAct.setShortcut(tr("Ctrl+L")) + leftAlignAct.setStatusTip(tr("Left align the selected text")) + leftAlignAct.triggered.connect(leftAlign) + + rightAlignAct = QAction(tr("&Right Align"), self) + rightAlignAct.setCheckable(True) + rightAlignAct.setShortcut(tr("Ctrl+R")) + rightAlignAct.setStatusTip(tr("Right align the selected text")) + rightAlignAct.triggered.connect(rightAlign) + + justifyAct = QAction(tr("&Justify"), self) + justifyAct.setCheckable(True) + justifyAct.setShortcut(tr("Ctrl+J")) + justifyAct.setStatusTip(tr("Justify the selected text")) + justifyAct.triggered.connect(justify) + + centerAct = QAction(tr("&Center"), self) + centerAct.setCheckable(True) + centerAct.setShortcut(tr("Ctrl+E")) + centerAct.setStatusTip(tr("Center the selected text")) + centerAct.triggered.connect(center) + +//! [6] //! [7] + alignmentGroup = QActionGroup(self) + alignmentGroup.addAction(leftAlignAct) + alignmentGroup.addAction(rightAlignAct) + alignmentGroup.addAction(justifyAct) + alignmentGroup.addAction(centerAct) + leftAlignAct.setChecked(True) +//! [6] + +//! [7] + +//! [8] +def createMenus(self): + +//! [9] //! [10] + fileMenu = menuBar().addMenu(tr("&File")) + fileMenu.addAction(Act) +//! [9] + fileMenu.addAction(openAct) +//! [10] + fileMenu.addAction(saveAct) + fileMenu.addAction(printAct) +//! [11] + fileMenu.addSeparator() +//! [11] + fileMenu.addAction(exitAct) + + editMenu = menuBar().addMenu(tr("&Edit")) + editMenu.addAction(undoAct) + editMenu.addAction(redoAct) + editMenu.addSeparator() + editMenu.addAction(cutAct) + editMenu.addAction(copyAct) + editMenu.addAction(pasteAct) + editMenu.addSeparator() + + helpMenu = menuBar().addMenu(tr("&Help")) + helpMenu.addAction(aboutAct) + helpMenu.addAction(aboutQtAct) +//! [8] + +//! [12] + formatMenu = editMenu.addMenu(tr("&Format")) + formatMenu.addAction(boldAct) + formatMenu.addAction(italicAct) + formatMenu.addSeparator()->setText(tr("Alignment")) + formatMenu.addAction(leftAlignAct) + formatMenu.addAction(rightAlignAct) + formatMenu.addAction(justifyAct) + formatMenu.addAction(centerAct) + formatMenu.addSeparator() + formatMenu.addAction(setLineSpacingAct) + formatMenu.addAction(setParagraphSpacingAct) +//! [12] diff --git a/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.cpp b/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.cpp deleted file mode 100644 index 7eace108a..000000000 --- a/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.cpp +++ /dev/null @@ -1,249 +0,0 @@ -############################################################################ -## -## Copyright (C) 2016 The Qt Company Ltd. -## Contact: https://www.qt.io/licensing/ -## -## This file is part of the examples of Qt for Python. -## -## $QT_BEGIN_LICENSE:BSD$ -## Commercial License Usage -## Licensees holding valid commercial Qt licenses may use this file in -## accordance with the commercial license agreement provided with the -## Software or, alternatively, in accordance with the terms contained in -## a written agreement between you and The Qt Company. For licensing terms -## and conditions see https://www.qt.io/terms-conditions. For further -## information use the contact form at https://www.qt.io/contact-us. -## -## BSD License Usage -## Alternatively, you may use this file under the terms of the BSD license -## as follows: -## -## "Redistribution and use in source and binary forms, with or without -## modification, are permitted provided that the following conditions are -## met: -## * Redistributions of source code must retain the above copyright -## notice, this list of conditions and the following disclaimer. -## * Redistributions in binary form must reproduce the above copyright -## notice, this list of conditions and the following disclaimer in -## the documentation and/or other materials provided with the -## distribution. -## * Neither the name of The Qt Company Ltd nor the names of its -## contributors may be used to endorse or promote products derived -## from this software without specific prior written permission. -## -## -## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -## -## $QT_END_LICENSE$ -## -############################################################################ - -from PySide2.QtGui import * - -//! [0] -def __init__(self): - createSpinBoxes() - createDateTimeEdits() - createDoubleSpinBoxes() - - layout = QHBoxLayout() - layout.addWidget(spinBoxesGroup) - layout.addWidget(editsGroup) - layout.addWidget(doubleSpinBoxesGroup) - setLayout(layout) - - setWindowTitle(tr("Spin Boxes")) -//! [0] - -//! [1] -def createSpinBoxes(self): - spinBoxesGroup = QGroupBox(tr("Spinboxes")) - - integerLabel = QLabel(tr("Enter a value between " - "%1 and %2:").arg(-20).arg(20)) - integerSpinBox = QSpinBox() - integerSpinBox.setRange(-20, 20) - integerSpinBox.setSingleStep(1) - integerSpinBox.setValue(0) -//! [1] - -//! [2] - zoomLabel = QLabel(tr("Enter a zoom value between " - "%1 and %2:").arg(0).arg(1000)) -//! [3] - zoomSpinBox = QSpinBox() - zoomSpinBox.setRange(0, 1000) - zoomSpinBox.setSingleStep(10) - zoomSpinBox.setSuffix("%") - zoomSpinBox.setSpecialValueText(tr("Automatic")) - zoomSpinBox.setValue(100) -//! [2] //! [3] - -//! [4] - priceLabel = QLabel(tr("Enter a price between " - "%1 and %2:").arg(0).arg(999)) - priceSpinBox = QSpinBox() - priceSpinBox.setRange(0, 999) - priceSpinBox.setSingleStep(1) - priceSpinBox.setPrefix("$") - priceSpinBox.setValue(99) -//! [4] //! [5] - - spinBoxLayout = QVBoxLayout() - spinBoxLayout.addWidget(integerLabel) - spinBoxLayout.addWidget(integerSpinBox) - spinBoxLayout.addWidget(zoomLabel) - spinBoxLayout.addWidget(zoomSpinBox) - spinBoxLayout.addWidget(priceLabel) - spinBoxLayout.addWidget(priceSpinBox) - spinBoxesGroup.setLayout(spinBoxLayout) - -//! [5] - -//! [6] -def createDateTimeEdits(self): - editsGroup = QGroupBox(tr("Date and time spin boxes")) - - dateLabel = QLabel() - dateEdit = QDateEdit(QDate.currentDate()) - dateEdit.setDateRange(QDate(2005, 1, 1), QDate(2010, 12, 31)) - dateLabel.setText(tr("Appointment date (between %0 and %1):") - .arg(dateEdit.minimumDate().toString(Qt.ISODate)) - .arg(dateEdit.maximumDate().toString(Qt.ISODate))) -//! [6] - -//! [7] - timeLabel = QLabel() - timeEdit = QTimeEdit(QTime.currentTime()) - timeEdit.setTimeRange(QTime(9, 0, 0, 0), QTime(16, 30, 0, 0)) - timeLabel.setText(tr("Appointment time (between %0 and %1):") - .arg(timeEdit.minimumTime().toString(Qt.ISODate)) - .arg(timeEdit.maximumTime().toString(Qt.ISODate))) -//! [7] - -//! [8] - meetingLabel = QLabel() - meetingEdit = QDateTimeEdit(QDateTime.currentDateTime()) -//! [8] - -//! [9] - formatLabel = QLabel(tr("Format string for the meeting date " - "and time:")) - formatComboBox = QComboBox() - formatComboBox.addItem("yyyy-MM-dd hh:mm:ss (zzz 'ms')") - formatComboBox.addItem("hh:mm:ss MM/dd/yyyy") - formatComboBox.addItem("hh:mm:ss dd/MM/yyyy") - formatComboBox.addItem("hh:mm:ss") - formatComboBox.addItem("hh:mm ap") -//! [9] //! [10] - - connect(formatComboBox, SIGNAL("activated(const QString &)"), - self, SLOT("setFormatString(const QString &)")) -//! [10] - - setFormatString(formatComboBox.currentText()) - -//! [11] - editsLayout = QVBoxLayout() - editsLayout.addWidget(dateLabel) - editsLayout.addWidget(dateEdit) - editsLayout.addWidget(timeLabel) - editsLayout.addWidget(timeEdit) - editsLayout.addWidget(meetingLabel) - editsLayout.addWidget(meetingEdit) - editsLayout.addWidget(formatLabel) - editsLayout.addWidget(formatComboBox) - editsGroup.setLayout(editsLayout) -//! [11] - -//! [12] -def setFormatString(self, formatString): - meetingEdit.setDisplayFormat(formatString) -//! [12] //! [13] - if meetingEdit.displayedSections() & QDateTimeEdit.DateSections_Mask: - meetingEdit.setDateRange(QDate(2004, 11, 1), QDate(2005, 11, 30)) - meetingLabel.setText(tr("Meeting date (between %0 and %1):") - .arg(meetingEdit.minimumDate().toString(Qt.ISODate)) - .arg(meetingEdit.maximumDate().toString(Qt.ISODate))) - else: - meetingEdit.setTimeRange(QTime(0, 7, 20, 0), QTime(21, 0, 0, 0)) - meetingLabel.setText(tr("Meeting time (between %0 and %1):") - .arg(meetingEdit.minimumTime().toString(Qt.ISODate)) - .arg(meetingEdit.maximumTime().toString(Qt.ISODate))) -//! [13] - -//! [14] -def createDoubleSpinBoxes(): - doubleSpinBoxesGroup = QGroupBox(tr("Double precision spinboxes")) - - precisionLabel = QLabel(tr("Number of decimal places " - "to show:")) - precisionSpinBox = QSpinBox() - precisionSpinBox.setRange(0, 100) - precisionSpinBox.setValue(2) -//! [14] - -//! [15] - doubleLabel = QLabel(tr("Enter a value between " - "%1 and %2:").arg(-20).arg(20)) - doubleSpinBox = QDoubleSpinBox () - doubleSpinBox.setRange(-20.0, 20.0) - doubleSpinBox.setSingleStep(1.0) - doubleSpinBox.setValue(0.0) -//! [15] - -//! [16] - scaleLabel = QLabel(tr("Enter a scale factor between " - "%1 and %2:").arg(0).arg(1000.0)) - scaleSpinBox = QDoubleSpinBox() - scaleSpinBox.setRange(0.0, 1000.0) - scaleSpinBox.setSingleStep(10.0) - scaleSpinBox.setSuffix("%") - scaleSpinBox.setSpecialValueText(tr("No scaling")) - scaleSpinBox.setValue(100.0) -//! [16] - -//! [17] - priceLabel = QLabel(tr("Enter a price between " - "%1 and %2:").arg(0).arg(1000)) - priceSpinBox = QDoubleSpinBox() - priceSpinBox.setRange(0.0, 1000.0) - priceSpinBox.setSingleStep(1.0) - priceSpinBox.setPrefix("$") - priceSpinBox.setValue(99.99) - - connect(precisionSpinBox, SIGNAL("valueChanged(int)"), -//! [17] - self, SLOT("changePrecision(int))") - -//! [18] - spinBoxLayout = QVBoxLayout() - spinBoxLayout.addWidget(precisionLabel) - spinBoxLayout.addWidget(precisionSpinBox) - spinBoxLayout.addWidget(doubleLabel) - spinBoxLayout.addWidget(doubleSpinBox) - spinBoxLayout.addWidget(scaleLabel) - spinBoxLayout.addWidget(scaleSpinBox) - spinBoxLayout.addWidget(priceLabel) - spinBoxLayout.addWidget(priceSpinBox) - doubleSpinBoxesGroup.setLayout(spinBoxLayout) -} -//! [18] - -//! [19] -def changePrecision(self, int) - doubleSpinBox.setDecimals(decimals) - scaleSpinBox.setDecimals(decimals) - priceSpinBox.setDecimals(decimals) - -//! [19] diff --git a/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.py b/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.py new file mode 100644 index 000000000..40fe28bf1 --- /dev/null +++ b/sources/pyside2/doc/codesnippets/examples/widgets/spinboxes/window.py @@ -0,0 +1,247 @@ +############################################################################ +## +## Copyright (C) 2016 The Qt Company Ltd. +## Contact: https://www.qt.io/licensing/ +## +## This file is part of the examples of Qt for Python. +## +## $QT_BEGIN_LICENSE:BSD$ +## Commercial License Usage +## Licensees holding valid commercial Qt licenses may use this file in +## accordance with the commercial license agreement provided with the +## Software or, alternatively, in accordance with the terms contained in +## a written agreement between you and The Qt Company. For licensing terms +## and conditions see https://www.qt.io/terms-conditions. For further +## information use the contact form at https://www.qt.io/contact-us. +## +## BSD License Usage +## Alternatively, you may use this file under the terms of the BSD license +## as follows: +## +## "Redistribution and use in source and binary forms, with or without +## modification, are permitted provided that the following conditions are +## met: +## * Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## * Redistributions in binary form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. +## * Neither the name of The Qt Company Ltd nor the names of its +## contributors may be used to endorse or promote products derived +## from this software without specific prior written permission. +## +## +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +## +## $QT_END_LICENSE$ +## +############################################################################ + +from PySide2.QtGui import * + +//! [0] +def __init__(self): + createSpinBoxes() + createDateTimeEdits() + createDoubleSpinBoxes() + + layout = QHBoxLayout() + layout.addWidget(spinBoxesGroup) + layout.addWidget(editsGroup) + layout.addWidget(doubleSpinBoxesGroup) + setLayout(layout) + + setWindowTitle(tr("Spin Boxes")) +//! [0] + +//! [1] +def createSpinBoxes(self): + spinBoxesGroup = QGroupBox(tr("Spinboxes")) + + integerLabel = QLabel(tr("Enter a value between " + "%1 and %2:").arg(-20).arg(20)) + integerSpinBox = QSpinBox() + integerSpinBox.setRange(-20, 20) + integerSpinBox.setSingleStep(1) + integerSpinBox.setValue(0) +//! [1] + +//! [2] + zoomLabel = QLabel(tr("Enter a zoom value between " + "%1 and %2:").arg(0).arg(1000)) +//! [3] + zoomSpinBox = QSpinBox() + zoomSpinBox.setRange(0, 1000) + zoomSpinBox.setSingleStep(10) + zoomSpinBox.setSuffix("%") + zoomSpinBox.setSpecialValueText(tr("Automatic")) + zoomSpinBox.setValue(100) +//! [2] //! [3] + +//! [4] + priceLabel = QLabel(tr("Enter a price between " + "%1 and %2:").arg(0).arg(999)) + priceSpinBox = QSpinBox() + priceSpinBox.setRange(0, 999) + priceSpinBox.setSingleStep(1) + priceSpinBox.setPrefix("$") + priceSpinBox.setValue(99) +//! [4] //! [5] + + spinBoxLayout = QVBoxLayout() + spinBoxLayout.addWidget(integerLabel) + spinBoxLayout.addWidget(integerSpinBox) + spinBoxLayout.addWidget(zoomLabel) + spinBoxLayout.addWidget(zoomSpinBox) + spinBoxLayout.addWidget(priceLabel) + spinBoxLayout.addWidget(priceSpinBox) + spinBoxesGroup.setLayout(spinBoxLayout) + +//! [5] + +//! [6] +def createDateTimeEdits(self): + editsGroup = QGroupBox(tr("Date and time spin boxes")) + + dateLabel = QLabel() + dateEdit = QDateEdit(QDate.currentDate()) + dateEdit.setDateRange(QDate(2005, 1, 1), QDate(2010, 12, 31)) + dateLabel.setText(tr("Appointment date (between %0 and %1):") + .arg(dateEdit.minimumDate().toString(Qt.ISODate)) + .arg(dateEdit.maximumDate().toString(Qt.ISODate))) +//! [6] + +//! [7] + timeLabel = QLabel() + timeEdit = QTimeEdit(QTime.currentTime()) + timeEdit.setTimeRange(QTime(9, 0, 0, 0), QTime(16, 30, 0, 0)) + timeLabel.setText(tr("Appointment time (between %0 and %1):") + .arg(timeEdit.minimumTime().toString(Qt.ISODate)) + .arg(timeEdit.maximumTime().toString(Qt.ISODate))) +//! [7] + +//! [8] + meetingLabel = QLabel() + meetingEdit = QDateTimeEdit(QDateTime.currentDateTime()) +//! [8] + +//! [9] + formatLabel = QLabel(tr("Format string for the meeting date " + "and time:")) + formatComboBox = QComboBox() + formatComboBox.addItem("yyyy-MM-dd hh:mm:ss (zzz 'ms')") + formatComboBox.addItem("hh:mm:ss MM/dd/yyyy") + formatComboBox.addItem("hh:mm:ss dd/MM/yyyy") + formatComboBox.addItem("hh:mm:ss") + formatComboBox.addItem("hh:mm ap") +//! [9] //! [10] + + formatComboBox.activated[str].connect(setFormatString) +//! [10] + + setFormatString(formatComboBox.currentText()) + +//! [11] + editsLayout = QVBoxLayout() + editsLayout.addWidget(dateLabel) + editsLayout.addWidget(dateEdit) + editsLayout.addWidget(timeLabel) + editsLayout.addWidget(timeEdit) + editsLayout.addWidget(meetingLabel) + editsLayout.addWidget(meetingEdit) + editsLayout.addWidget(formatLabel) + editsLayout.addWidget(formatComboBox) + editsGroup.setLayout(editsLayout) +//! [11] + +//! [12] +def setFormatString(self, formatString): + meetingEdit.setDisplayFormat(formatString) +//! [12] //! [13] + if meetingEdit.displayedSections() & QDateTimeEdit.DateSections_Mask: + meetingEdit.setDateRange(QDate(2004, 11, 1), QDate(2005, 11, 30)) + meetingLabel.setText(tr("Meeting date (between %0 and %1):") + .arg(meetingEdit.minimumDate().toString(Qt.ISODate)) + .arg(meetingEdit.maximumDate().toString(Qt.ISODate))) + else: + meetingEdit.setTimeRange(QTime(0, 7, 20, 0), QTime(21, 0, 0, 0)) + meetingLabel.setText(tr("Meeting time (between %0 and %1):") + .arg(meetingEdit.minimumTime().toString(Qt.ISODate)) + .arg(meetingEdit.maximumTime().toString(Qt.ISODate))) +//! [13] + +//! [14] +def createDoubleSpinBoxes(): + doubleSpinBoxesGroup = QGroupBox(tr("Double precision spinboxes")) + + precisionLabel = QLabel(tr("Number of decimal places " + "to show:")) + precisionSpinBox = QSpinBox() + precisionSpinBox.setRange(0, 100) + precisionSpinBox.setValue(2) +//! [14] + +//! [15] + doubleLabel = QLabel(tr("Enter a value between " + "%1 and %2:").arg(-20).arg(20)) + doubleSpinBox = QDoubleSpinBox () + doubleSpinBox.setRange(-20.0, 20.0) + doubleSpinBox.setSingleStep(1.0) + doubleSpinBox.setValue(0.0) +//! [15] + +//! [16] + scaleLabel = QLabel(tr("Enter a scale factor between " + "%1 and %2:").arg(0).arg(1000.0)) + scaleSpinBox = QDoubleSpinBox() + scaleSpinBox.setRange(0.0, 1000.0) + scaleSpinBox.setSingleStep(10.0) + scaleSpinBox.setSuffix("%") + scaleSpinBox.setSpecialValueText(tr("No scaling")) + scaleSpinBox.setValue(100.0) +//! [16] + +//! [17] + priceLabel = QLabel(tr("Enter a price between " + "%1 and %2:").arg(0).arg(1000)) + priceSpinBox = QDoubleSpinBox() + priceSpinBox.setRange(0.0, 1000.0) + priceSpinBox.setSingleStep(1.0) + priceSpinBox.setPrefix("$") + priceSpinBox.setValue(99.99) + + precisionSpinBox.valueChanged[int].connect(changePrecision) +//! [17] + +//! [18] + spinBoxLayout = QVBoxLayout() + spinBoxLayout.addWidget(precisionLabel) + spinBoxLayout.addWidget(precisionSpinBox) + spinBoxLayout.addWidget(doubleLabel) + spinBoxLayout.addWidget(doubleSpinBox) + spinBoxLayout.addWidget(scaleLabel) + spinBoxLayout.addWidget(scaleSpinBox) + spinBoxLayout.addWidget(priceLabel) + spinBoxLayout.addWidget(priceSpinBox) + doubleSpinBoxesGroup.setLayout(spinBoxLayout) +} +//! [18] + +//! [19] +def changePrecision(self, int) + doubleSpinBox.setDecimals(decimals) + scaleSpinBox.setDecimals(decimals) + priceSpinBox.setDecimals(decimals) + +//! [19] -- cgit v1.2.3 From 10390cc16084c5f386163664f6e42d9e4d28b129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simo=20F=C3=A4lt?= Date: Mon, 25 May 2020 14:46:29 +0300 Subject: Rename pre_release_version_type to release_version_type Renaming pre_release_version_type to release_version_type to match its future usage to differentiate between wheel/package types. Change-Id: I70a2361f639a36b17f63b7f76d8c231a144bd825 Reviewed-by: Cristian Maureira-Fredes --- sources/pyside2/pyside_version.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/pyside_version.py b/sources/pyside2/pyside_version.py index c022fc803..f5ef03613 100644 --- a/sources/pyside2/pyside_version.py +++ b/sources/pyside2/pyside_version.py @@ -44,7 +44,7 @@ patch_version = "0" # For example: "a", "b", "rc" # (which means "alpha", "beta", "release candidate"). # An empty string means the generated package will be an official release. -pre_release_version_type = "a" +release_version_type = "a" # For example: "1", "2" (which means "beta1", "beta2", if type is "b"). pre_release_version = "1" @@ -52,4 +52,4 @@ pre_release_version = "1" if __name__ == '__main__': # Used by CMake. print('{0};{1};{2};{3};{4}'.format(major_version, minor_version, patch_version, - pre_release_version_type, pre_release_version)) + release_version_type, pre_release_version)) -- cgit v1.2.3 From b9a814cc89283a86cbf4c38ea1d00ac5ba283ade Mon Sep 17 00:00:00 2001 From: Andreas Buhr Date: Sun, 24 May 2020 18:18:58 +0200 Subject: QtSerialPort improved unit tests Support for QtSerialPort was added to PySide2 recently. However, only very few unit tests were added at that time. This change replicates a part of the C++ unit tests of QtSerialPort in PySide/Python. Change-Id: I7e7a1ee7a521b952a6c0860cd8cceacb3b0b7e57 Reviewed-by: Friedemann Kleint Reviewed-by: Cristian Maureira-Fredes Reviewed-by: Christian Tismer --- sources/pyside2/tests/QtSerialPort/serial.py | 49 ++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 6 deletions(-) (limited to 'sources/pyside2') diff --git a/sources/pyside2/tests/QtSerialPort/serial.py b/sources/pyside2/tests/QtSerialPort/serial.py index c30d9eb03..7c0839d8e 100644 --- a/sources/pyside2/tests/QtSerialPort/serial.py +++ b/sources/pyside2/tests/QtSerialPort/serial.py @@ -39,20 +39,57 @@ from init_paths import init_test_paths init_test_paths(False) from PySide2.QtSerialPort import QSerialPort, QSerialPortInfo +from PySide2.QtCore import QIODevice +class QSerialPortTest(unittest.TestCase): + def testDefaultConstructedPort(self): + serialPort = QSerialPort() -def callPortInfoMemberFunctions(portinfo): - portinfo.description() - portinfo.hasProductIdentifier() - portinfo.hasVendorIdentifier() - portinfo.isNull() + self.assertEqual(serialPort.error(), QSerialPort.NoError) + self.assertTrue(not serialPort.errorString() == "") + + # properties + defaultBaudRate = QSerialPort.Baud9600 + self.assertEqual(serialPort.baudRate(), defaultBaudRate) + self.assertEqual(serialPort.baudRate(QSerialPort.Input), defaultBaudRate) + self.assertEqual(serialPort.baudRate(QSerialPort.Output), defaultBaudRate) + self.assertEqual(serialPort.dataBits(), QSerialPort.Data8) + self.assertEqual(serialPort.parity(), QSerialPort.NoParity) + self.assertEqual(serialPort.stopBits(), QSerialPort.OneStop) + self.assertEqual(serialPort.flowControl(), QSerialPort.NoFlowControl) + + self.assertEqual(serialPort.pinoutSignals(), QSerialPort.NoSignal) + self.assertEqual(serialPort.isRequestToSend(), False) + self.assertEqual(serialPort.isDataTerminalReady(), False) + + # QIODevice + self.assertEqual(serialPort.openMode(), QIODevice.NotOpen) + self.assertTrue(not serialPort.isOpen()) + self.assertTrue(not serialPort.isReadable()) + self.assertTrue(not serialPort.isWritable()) + self.assertTrue(serialPort.isSequential()) + self.assertEqual(serialPort.canReadLine(), False) + self.assertEqual(serialPort.pos(), 0) + self.assertEqual(serialPort.size(), 0) + self.assertTrue(serialPort.atEnd()) + self.assertEqual(serialPort.bytesAvailable(), 0) + self.assertEqual(serialPort.bytesToWrite(), 0) + + def testOpenExisting(self): + allportinfos = QSerialPortInfo.availablePorts() + for portinfo in allportinfos: + serialPort = QSerialPort(portinfo) + self.assertEqual(serialPort.portName(), portinfo.portName()) class QSerialPortInfoTest(unittest.TestCase): def test_available_ports(self): allportinfos = QSerialPortInfo.availablePorts() for portinfo in allportinfos: - callPortInfoMemberFunctions(portinfo) + portinfo.description() + portinfo.hasProductIdentifier() + portinfo.hasVendorIdentifier() + portinfo.isNull() if __name__ == '__main__': unittest.main() -- cgit v1.2.3 From f012eedb3d3dc76305b86bc1c79ffe59565dd6f6 Mon Sep 17 00:00:00 2001 From: Cristian Maureira-Fredes Date: Fri, 22 May 2020 16:12:14 +0200 Subject: Add QtQuickControls2 This exposes the C++ class QQuickStyle Task-number: PYSIDE-487 Change-Id: I5776421070362d8b3bf9556eb28a410de3c90948 Reviewed-by: Christian Tismer Reviewed-by: Cristian Maureira-Fredes --- .../PySide2/QtQuickControls2/CMakeLists.txt | 41 +++++++++++++++++++ .../QtQuickControls2/typesystem_quickcontrols2.xml | 47 ++++++++++++++++++++++ .../pyside2/tests/QtQuickControls2/CMakeLists.txt | 1 + 3 files changed, 89 insertions(+) create mode 100644 sources/pyside2/PySide2/QtQuickControls2/CMakeLists.txt create mode 100644 sources/pyside2/PySide2/QtQuickControls2/typesystem_quickcontrols2.xml create mode 100644 sources/pyside2/tests/QtQuickControls2/CMakeLists.txt (limited to 'sources/pyside2') diff --git a/sources/pyside2/PySide2/QtQuickControls2/CMakeLists.txt b/sources/pyside2/PySide2/QtQuickControls2/CMakeLists.txt new file mode 100644 index 000000000..8321d8a3e --- /dev/null +++ b/sources/pyside2/PySide2/QtQuickControls2/CMakeLists.txt @@ -0,0 +1,41 @@ +project(QtQuickControls2) + +set(QtQuickControls2_SRC +${QtQuickControls2_GEN_DIR}/qquickstyle_wrapper.cpp +# module is always needed +${QtQuickControls2_GEN_DIR}/qtquickcontrols2_module_wrapper.cpp +) + + +set(QtQuickControls2_include_dirs ${QtQuickControls2_SOURCE_DIR} + ${QtQml_SOURCE_DIR} + ${Qt${QT_MAJOR_VERSION}Core_INCLUDE_DIRS} + ${Qt${QT_MAJOR_VERSION}Gui_INCLUDE_DIRS} + ${Qt${QT_MAJOR_VERSION}Network_INCLUDE_DIRS} + ${Qt${QT_MAJOR_VERSION}Qml_INCLUDE_DIRS} + ${Qt${QT_MAJOR_VERSION}Quick_INCLUDE_DIRS} + ${Qt${QT_MAJOR_VERSION}QuickControls2_INCLUDE_DIRS} + ${libpyside_SOURCE_DIR} + ${QtGui_GEN_DIR} + ${QtCore_GEN_DIR} + ${QtNetwork_GEN_DIR} + ${QtQml_GEN_DIR} + ${QtQuick_GEN_DIR} + ${QtQuickControls2_GEN_DIR}) + +set(QtQuickControls2_libraries pyside2 + ${Qt${QT_MAJOR_VERSION}Core_LIBRARIES} + ${Qt${QT_MAJOR_VERSION}Gui_LIBRARIES} + ${Qt${QT_MAJOR_VERSION}Network_LIBRARIES} + ${Qt${QT_MAJOR_VERSION}Qml_LIBRARIES} + ${Qt${QT_MAJOR_VERSION}Quick_LIBRARIES} + ${Qt${QT_MAJOR_VERSION}QuickControls2_LIBRARIES}) + +set(QtQuickControls2_deps QtGui QtNetwork QtQml QtQuick) + +create_pyside_module(NAME QtQuickControls2 + INCLUDE_DIRS QtQuickControls2_include_dirs + LIBRARIES QtQuickControls2_libraries + DEPS QtQuickControls2_deps + TYPESYSTEM_PATH QtQuickControls2_SOURCE_DIR + SOURCES QtQuickControls2_SRC) diff --git a/sources/pyside2/PySide2/QtQuickControls2/typesystem_quickcontrols2.xml b/sources/pyside2/PySide2/QtQuickControls2/typesystem_quickcontrols2.xml new file mode 100644 index 000000000..51d42b46b --- /dev/null +++ b/sources/pyside2/PySide2/QtQuickControls2/typesystem_quickcontrols2.xml @@ -0,0 +1,47 @@ + + + + + + + + diff --git a/sources/pyside2/tests/QtQuickControls2/CMakeLists.txt b/sources/pyside2/tests/QtQuickControls2/CMakeLists.txt new file mode 100644 index 000000000..2f7cb08b9 --- /dev/null +++ b/sources/pyside2/tests/QtQuickControls2/CMakeLists.txt @@ -0,0 +1 @@ +# Please add some tests, here -- cgit v1.2.3